blob: e65e8e18d9176001c2c90a40ef30326b158b9db9 [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?
Leon Scroggins87ae77b2009-07-07 10:36:35 -04002981 String original = view.getOriginalUrl();
2982 if (original != null) {
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002983 // copied from BrowserBookmarksAdapter
Leon Scroggins87ae77b2009-07-07 10:36:35 -04002984 int query = original.indexOf('?');
2985 String noQuery = original;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002986 if (query != -1) {
Leon Scroggins87ae77b2009-07-07 10:36:35 -04002987 noQuery = original.substring(0, query);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002988 }
2989 String URL = noQuery + '?';
2990 String[] selArgs = new String[] { noQuery, URL };
2991 final String where = "(url == ? OR url GLOB ? || '*') AND bookmark == 1";
2992 final String[] projection = new String[] { Browser.BookmarkColumns._ID };
2993 ContentResolver cr = getContentResolver();
2994 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection, where, selArgs, null);
2995 boolean succeed = c.moveToFirst();
2996 ContentValues values = null;
2997 while (succeed) {
2998 if (values == null) {
2999 final ByteArrayOutputStream os = new ByteArrayOutputStream();
3000 Picture thumbnail = view.capturePicture();
3001 // Height was arbitrarily chosen
3002 Bitmap bm = Bitmap.createBitmap(100, 100,
3003 Bitmap.Config.ARGB_4444);
3004 Canvas canvas = new Canvas(bm);
3005 // Scale chosen to be about one third, since we want
3006 // roughly three rows/columns for bookmark page
3007 canvas.scale(.3f, .3f);
3008 thumbnail.draw(canvas);
3009 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
3010 values = new ContentValues();
3011 values.put(Browser.BookmarkColumns.THUMBNAIL,
3012 os.toByteArray());
3013 }
3014 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
3015 c.getInt(0)), values, null, null);
3016 succeed = c.moveToNext();
3017 }
3018 c.close();
3019 }
3020
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003022 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023 long[] sysCpu = new long[7];
3024 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3025 sysCpu, null)) {
3026 String uiInfo = "UI thread used "
3027 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3028 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003029 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 Log.d(LOGTAG, uiInfo);
3031 }
3032 //The string that gets written to the log
3033 String performanceString = "It took total "
3034 + (SystemClock.uptimeMillis() - mStart)
3035 + " ms clock time to load the page."
3036 + "\nbrowser process used "
3037 + (Process.getElapsedCpuTime() - mProcessStart)
3038 + " ms, user processes used "
3039 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3040 + " ms, kernel used "
3041 + (sysCpu[2] - mSystemStart) * 10
3042 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3043 + " ms and irq took "
3044 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3045 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003046 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003047 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3048 }
3049 if (url != null) {
3050 // strip the url to maintain consistency
3051 String newUrl = new String(url);
3052 if (newUrl.startsWith("http://www.")) {
3053 newUrl = newUrl.substring(11);
3054 } else if (newUrl.startsWith("http://")) {
3055 newUrl = newUrl.substring(7);
3056 } else if (newUrl.startsWith("https://www.")) {
3057 newUrl = newUrl.substring(12);
3058 } else if (newUrl.startsWith("https://")) {
3059 newUrl = newUrl.substring(8);
3060 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003061 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 Log.d(LOGTAG, newUrl + " loaded");
3063 }
3064 /*
3065 if (sWhiteList.contains(newUrl)) {
3066 // The string that gets pushed to the statistcs
3067 // service
3068 performanceString = performanceString
3069 + "\nWebpage: "
3070 + newUrl
3071 + "\nCarrier: "
3072 + android.os.SystemProperties
3073 .get("gsm.sim.operator.alpha");
3074 if (mWebView != null
3075 && mWebView.getContext() != null
3076 && mWebView.getContext().getSystemService(
3077 Context.CONNECTIVITY_SERVICE) != null) {
3078 ConnectivityManager cManager =
3079 (ConnectivityManager) mWebView
3080 .getContext().getSystemService(
3081 Context.CONNECTIVITY_SERVICE);
3082 NetworkInfo nInfo = cManager
3083 .getActiveNetworkInfo();
3084 if (nInfo != null) {
3085 performanceString = performanceString
3086 + "\nNetwork Type: "
3087 + nInfo.getType().toString();
3088 }
3089 }
3090 Checkin.logEvent(mResolver,
3091 Checkin.Events.Tag.WEBPAGE_LOAD,
3092 performanceString);
3093 Log.w(LOGTAG, "pushed to the statistics service");
3094 }
3095 */
3096 }
3097 }
3098 }
3099
3100 if (mInTrace) {
3101 mInTrace = false;
3102 Debug.stopMethodTracing();
3103 }
3104
3105 if (mPageStarted) {
3106 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003107 // pauseWebViewTimers() will do nothing and return false if
3108 // onPause() is not called yet.
3109 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003110 if (mWakeLock.isHeld()) {
3111 mHandler.removeMessages(RELEASE_WAKELOCK);
3112 mWakeLock.release();
3113 }
3114 }
3115 }
3116
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117 mHandler.removeMessages(CHECK_MEMORY);
3118 checkMemory();
3119 }
3120
3121 // return true if want to hijack the url to let another app to handle it
3122 @Override
3123 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3124 if (url.startsWith(SCHEME_WTAI)) {
3125 // wtai://wp/mc;number
3126 // number=string(phone-number)
3127 if (url.startsWith(SCHEME_WTAI_MC)) {
3128 Intent intent = new Intent(Intent.ACTION_VIEW,
3129 Uri.parse(WebView.SCHEME_TEL +
3130 url.substring(SCHEME_WTAI_MC.length())));
3131 startActivity(intent);
3132 return true;
3133 }
3134 // wtai://wp/sd;dtmf
3135 // dtmf=string(dialstring)
3136 if (url.startsWith(SCHEME_WTAI_SD)) {
3137 // TODO
3138 // only send when there is active voice connection
3139 return false;
3140 }
3141 // wtai://wp/ap;number;name
3142 // number=string(phone-number)
3143 // name=string
3144 if (url.startsWith(SCHEME_WTAI_AP)) {
3145 // TODO
3146 return false;
3147 }
3148 }
3149
Dianne Hackborn99189432009-06-17 18:06:18 -07003150 // The "about:" schemes are internal to the browser; don't
3151 // want these to be dispatched to other apps.
3152 if (url.startsWith("about:")) {
3153 return false;
3154 }
3155
3156 Intent intent;
3157
3158 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003159 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003160 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3161 } catch (URISyntaxException ex) {
3162 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163 return false;
3164 }
3165
Grace Kloba5b078b52009-06-24 20:23:41 -07003166 // check whether the intent can be resolved. If not, we will see
3167 // whether we can download it from the Market.
3168 if (getPackageManager().resolveActivity(intent, 0) == null) {
3169 String packagename = intent.getPackage();
3170 if (packagename != null) {
3171 intent = new Intent(Intent.ACTION_VIEW, Uri
3172 .parse("market://search?q=pname:" + packagename));
3173 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3174 startActivity(intent);
3175 return true;
3176 } else {
3177 return false;
3178 }
3179 }
3180
Dianne Hackborn99189432009-06-17 18:06:18 -07003181 // sanitize the Intent, ensuring web pages can not bypass browser
3182 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003183 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003184 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003185 try {
3186 if (startActivityIfNeeded(intent, -1)) {
3187 return true;
3188 }
3189 } catch (ActivityNotFoundException ex) {
3190 // ignore the error. If no application can handle the URL,
3191 // eg about:blank, assume the browser can handle it.
3192 }
3193
3194 if (mMenuIsDown) {
3195 openTab(url);
3196 closeOptionsMenu();
3197 return true;
3198 }
3199
3200 return false;
3201 }
3202
3203 /**
3204 * Updates the lock icon. This method is called when we discover another
3205 * resource to be loaded for this page (for example, javascript). While
3206 * we update the icon type, we do not update the lock icon itself until
3207 * we are done loading, it is slightly more secure this way.
3208 */
3209 @Override
3210 public void onLoadResource(WebView view, String url) {
3211 if (url != null && url.length() > 0) {
3212 // It is only if the page claims to be secure
3213 // that we may have to update the lock:
3214 if (mLockIconType == LOCK_ICON_SECURE) {
3215 // If NOT a 'safe' url, change the lock to mixed content!
3216 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3217 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003218 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3220 " updated lock icon to " + mLockIconType + " due to " + url);
3221 }
3222 }
3223 }
3224 }
3225 }
3226
3227 /**
3228 * Show the dialog, asking the user if they would like to continue after
3229 * an excessive number of HTTP redirects.
3230 */
3231 @Override
3232 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3233 final Message continueMsg) {
3234 new AlertDialog.Builder(BrowserActivity.this)
3235 .setTitle(R.string.browserFrameRedirect)
3236 .setMessage(R.string.browserFrame307Post)
3237 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3238 public void onClick(DialogInterface dialog, int which) {
3239 continueMsg.sendToTarget();
3240 }})
3241 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3242 public void onClick(DialogInterface dialog, int which) {
3243 cancelMsg.sendToTarget();
3244 }})
3245 .setOnCancelListener(new OnCancelListener() {
3246 public void onCancel(DialogInterface dialog) {
3247 cancelMsg.sendToTarget();
3248 }})
3249 .show();
3250 }
3251
Patrick Scott37911c72009-03-24 18:02:58 -07003252 // Container class for the next error dialog that needs to be
3253 // displayed.
3254 class ErrorDialog {
3255 public final int mTitle;
3256 public final String mDescription;
3257 public final int mError;
3258 ErrorDialog(int title, String desc, int error) {
3259 mTitle = title;
3260 mDescription = desc;
3261 mError = error;
3262 }
3263 };
3264
3265 private void processNextError() {
3266 if (mQueuedErrors == null) {
3267 return;
3268 }
3269 // The first one is currently displayed so just remove it.
3270 mQueuedErrors.removeFirst();
3271 if (mQueuedErrors.size() == 0) {
3272 mQueuedErrors = null;
3273 return;
3274 }
3275 showError(mQueuedErrors.getFirst());
3276 }
3277
3278 private DialogInterface.OnDismissListener mDialogListener =
3279 new DialogInterface.OnDismissListener() {
3280 public void onDismiss(DialogInterface d) {
3281 processNextError();
3282 }
3283 };
3284 private LinkedList<ErrorDialog> mQueuedErrors;
3285
3286 private void queueError(int err, String desc) {
3287 if (mQueuedErrors == null) {
3288 mQueuedErrors = new LinkedList<ErrorDialog>();
3289 }
3290 for (ErrorDialog d : mQueuedErrors) {
3291 if (d.mError == err) {
3292 // Already saw a similar error, ignore the new one.
3293 return;
3294 }
3295 }
3296 ErrorDialog errDialog = new ErrorDialog(
3297 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3298 R.string.browserFrameFileErrorLabel :
3299 R.string.browserFrameNetworkErrorLabel,
3300 desc, err);
3301 mQueuedErrors.addLast(errDialog);
3302
3303 // Show the dialog now if the queue was empty.
3304 if (mQueuedErrors.size() == 1) {
3305 showError(errDialog);
3306 }
3307 }
3308
3309 private void showError(ErrorDialog errDialog) {
3310 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3311 .setTitle(errDialog.mTitle)
3312 .setMessage(errDialog.mDescription)
3313 .setPositiveButton(R.string.ok, null)
3314 .create();
3315 d.setOnDismissListener(mDialogListener);
3316 d.show();
3317 }
3318
The Android Open Source Project0c908882009-03-03 19:32:16 -08003319 /**
3320 * Show a dialog informing the user of the network error reported by
3321 * WebCore.
3322 */
3323 @Override
3324 public void onReceivedError(WebView view, int errorCode,
3325 String description, String failingUrl) {
3326 if (errorCode != EventHandler.ERROR_LOOKUP &&
3327 errorCode != EventHandler.ERROR_CONNECT &&
3328 errorCode != EventHandler.ERROR_BAD_URL &&
3329 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3330 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003331 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 }
Patrick Scott37911c72009-03-24 18:02:58 -07003333 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3334 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335
3336 // We need to reset the title after an error.
3337 resetTitleAndRevertLockIcon();
3338 }
3339
3340 /**
3341 * Check with the user if it is ok to resend POST data as the page they
3342 * are trying to navigate to is the result of a POST.
3343 */
3344 @Override
3345 public void onFormResubmission(WebView view, final Message dontResend,
3346 final Message resend) {
3347 new AlertDialog.Builder(BrowserActivity.this)
3348 .setTitle(R.string.browserFrameFormResubmitLabel)
3349 .setMessage(R.string.browserFrameFormResubmitMessage)
3350 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3351 public void onClick(DialogInterface dialog, int which) {
3352 resend.sendToTarget();
3353 }})
3354 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3355 public void onClick(DialogInterface dialog, int which) {
3356 dontResend.sendToTarget();
3357 }})
3358 .setOnCancelListener(new OnCancelListener() {
3359 public void onCancel(DialogInterface dialog) {
3360 dontResend.sendToTarget();
3361 }})
3362 .show();
3363 }
3364
3365 /**
3366 * Insert the url into the visited history database.
3367 * @param url The url to be inserted.
3368 * @param isReload True if this url is being reloaded.
3369 * FIXME: Not sure what to do when reloading the page.
3370 */
3371 @Override
3372 public void doUpdateVisitedHistory(WebView view, String url,
3373 boolean isReload) {
3374 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3375 return;
3376 }
3377 Browser.updateVisitedHistory(mResolver, url, true);
3378 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3379 }
3380
3381 /**
3382 * Displays SSL error(s) dialog to the user.
3383 */
3384 @Override
3385 public void onReceivedSslError(
3386 final WebView view, final SslErrorHandler handler, final SslError error) {
3387
3388 if (mSettings.showSecurityWarnings()) {
3389 final LayoutInflater factory =
3390 LayoutInflater.from(BrowserActivity.this);
3391 final View warningsView =
3392 factory.inflate(R.layout.ssl_warnings, null);
3393 final LinearLayout placeholder =
3394 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3395
3396 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3397 LinearLayout ll = (LinearLayout)factory
3398 .inflate(R.layout.ssl_warning, null);
3399 ((TextView)ll.findViewById(R.id.warning))
3400 .setText(R.string.ssl_untrusted);
3401 placeholder.addView(ll);
3402 }
3403
3404 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3405 LinearLayout ll = (LinearLayout)factory
3406 .inflate(R.layout.ssl_warning, null);
3407 ((TextView)ll.findViewById(R.id.warning))
3408 .setText(R.string.ssl_mismatch);
3409 placeholder.addView(ll);
3410 }
3411
3412 if (error.hasError(SslError.SSL_EXPIRED)) {
3413 LinearLayout ll = (LinearLayout)factory
3414 .inflate(R.layout.ssl_warning, null);
3415 ((TextView)ll.findViewById(R.id.warning))
3416 .setText(R.string.ssl_expired);
3417 placeholder.addView(ll);
3418 }
3419
3420 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3421 LinearLayout ll = (LinearLayout)factory
3422 .inflate(R.layout.ssl_warning, null);
3423 ((TextView)ll.findViewById(R.id.warning))
3424 .setText(R.string.ssl_not_yet_valid);
3425 placeholder.addView(ll);
3426 }
3427
3428 new AlertDialog.Builder(BrowserActivity.this)
3429 .setTitle(R.string.security_warning)
3430 .setIcon(android.R.drawable.ic_dialog_alert)
3431 .setView(warningsView)
3432 .setPositiveButton(R.string.ssl_continue,
3433 new DialogInterface.OnClickListener() {
3434 public void onClick(DialogInterface dialog, int whichButton) {
3435 handler.proceed();
3436 }
3437 })
3438 .setNeutralButton(R.string.view_certificate,
3439 new DialogInterface.OnClickListener() {
3440 public void onClick(DialogInterface dialog, int whichButton) {
3441 showSSLCertificateOnError(view, handler, error);
3442 }
3443 })
3444 .setNegativeButton(R.string.cancel,
3445 new DialogInterface.OnClickListener() {
3446 public void onClick(DialogInterface dialog, int whichButton) {
3447 handler.cancel();
3448 BrowserActivity.this.resetTitleAndRevertLockIcon();
3449 }
3450 })
3451 .setOnCancelListener(
3452 new DialogInterface.OnCancelListener() {
3453 public void onCancel(DialogInterface dialog) {
3454 handler.cancel();
3455 BrowserActivity.this.resetTitleAndRevertLockIcon();
3456 }
3457 })
3458 .show();
3459 } else {
3460 handler.proceed();
3461 }
3462 }
3463
3464 /**
3465 * Handles an HTTP authentication request.
3466 *
3467 * @param handler The authentication handler
3468 * @param host The host
3469 * @param realm The realm
3470 */
3471 @Override
3472 public void onReceivedHttpAuthRequest(WebView view,
3473 final HttpAuthHandler handler, final String host, final String realm) {
3474 String username = null;
3475 String password = null;
3476
3477 boolean reuseHttpAuthUsernamePassword =
3478 handler.useHttpAuthUsernamePassword();
3479
3480 if (reuseHttpAuthUsernamePassword &&
3481 (mTabControl.getCurrentWebView() != null)) {
3482 String[] credentials =
3483 mTabControl.getCurrentWebView()
3484 .getHttpAuthUsernamePassword(host, realm);
3485 if (credentials != null && credentials.length == 2) {
3486 username = credentials[0];
3487 password = credentials[1];
3488 }
3489 }
3490
3491 if (username != null && password != null) {
3492 handler.proceed(username, password);
3493 } else {
3494 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3495 }
3496 }
3497
3498 @Override
3499 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3500 if (mMenuIsDown) {
3501 // only check shortcut key when MENU is held
3502 return getWindow().isShortcutKey(event.getKeyCode(), event);
3503 } else {
3504 return false;
3505 }
3506 }
3507
3508 @Override
3509 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3510 if (view != mTabControl.getCurrentTopWebView()) {
3511 return;
3512 }
3513 if (event.isDown()) {
3514 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3515 } else {
3516 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3517 }
3518 }
3519 };
3520
3521 //--------------------------------------------------------------------------
3522 // WebChromeClient implementation
3523 //--------------------------------------------------------------------------
3524
3525 /* package */ WebChromeClient getWebChromeClient() {
3526 return mWebChromeClient;
3527 }
3528
3529 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3530 // Helper method to create a new tab or sub window.
3531 private void createWindow(final boolean dialog, final Message msg) {
3532 if (dialog) {
3533 mTabControl.createSubWindow();
3534 final TabControl.Tab t = mTabControl.getCurrentTab();
3535 attachSubWindow(t);
3536 WebView.WebViewTransport transport =
3537 (WebView.WebViewTransport) msg.obj;
3538 transport.setWebView(t.getSubWebView());
3539 msg.sendToTarget();
3540 } else {
3541 final TabControl.Tab parent = mTabControl.getCurrentTab();
3542 // openTabAndShow will dispatch the message after creating the
3543 // new WebView. This will prevent another request from coming
3544 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003545 final TabControl.Tab newTab =
3546 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003547 if (newTab != parent) {
3548 parent.addChildTab(newTab);
3549 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003550 WebView.WebViewTransport transport =
3551 (WebView.WebViewTransport) msg.obj;
3552 transport.setWebView(mTabControl.getCurrentWebView());
3553 }
3554 }
3555
3556 @Override
3557 public boolean onCreateWindow(WebView view, final boolean dialog,
3558 final boolean userGesture, final Message resultMsg) {
3559 // Ignore these requests during tab animations or if the tab
3560 // overview is showing.
3561 if (mAnimationCount > 0 || mTabOverview != null) {
3562 return false;
3563 }
3564 // Short-circuit if we can't create any more tabs or sub windows.
3565 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3566 new AlertDialog.Builder(BrowserActivity.this)
3567 .setTitle(R.string.too_many_subwindows_dialog_title)
3568 .setIcon(android.R.drawable.ic_dialog_alert)
3569 .setMessage(R.string.too_many_subwindows_dialog_message)
3570 .setPositiveButton(R.string.ok, null)
3571 .show();
3572 return false;
3573 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3574 new AlertDialog.Builder(BrowserActivity.this)
3575 .setTitle(R.string.too_many_windows_dialog_title)
3576 .setIcon(android.R.drawable.ic_dialog_alert)
3577 .setMessage(R.string.too_many_windows_dialog_message)
3578 .setPositiveButton(R.string.ok, null)
3579 .show();
3580 return false;
3581 }
3582
3583 // Short-circuit if this was a user gesture.
3584 if (userGesture) {
3585 // createWindow will call openTabAndShow for new Windows and
3586 // that will call tabPicker which will increment
3587 // mAnimationCount.
3588 createWindow(dialog, resultMsg);
3589 return true;
3590 }
3591
3592 // Allow the popup and create the appropriate window.
3593 final AlertDialog.OnClickListener allowListener =
3594 new AlertDialog.OnClickListener() {
3595 public void onClick(DialogInterface d,
3596 int which) {
3597 // Same comment as above for setting
3598 // mAnimationCount.
3599 createWindow(dialog, resultMsg);
3600 // Since we incremented mAnimationCount while the
3601 // dialog was up, we have to decrement it here.
3602 mAnimationCount--;
3603 }
3604 };
3605
3606 // Block the popup by returning a null WebView.
3607 final AlertDialog.OnClickListener blockListener =
3608 new AlertDialog.OnClickListener() {
3609 public void onClick(DialogInterface d, int which) {
3610 resultMsg.sendToTarget();
3611 // We are not going to trigger an animation so
3612 // unblock keys and animation requests.
3613 mAnimationCount--;
3614 }
3615 };
3616
3617 // Build a confirmation dialog to display to the user.
3618 final AlertDialog d =
3619 new AlertDialog.Builder(BrowserActivity.this)
3620 .setTitle(R.string.attention)
3621 .setIcon(android.R.drawable.ic_dialog_alert)
3622 .setMessage(R.string.popup_window_attempt)
3623 .setPositiveButton(R.string.allow, allowListener)
3624 .setNegativeButton(R.string.block, blockListener)
3625 .setCancelable(false)
3626 .create();
3627
3628 // Show the confirmation dialog.
3629 d.show();
3630 // We want to increment mAnimationCount here to prevent a
3631 // potential race condition. If the user allows a pop-up from a
3632 // site and that pop-up then triggers another pop-up, it is
3633 // possible to get the BACK key between here and when the dialog
3634 // appears.
3635 mAnimationCount++;
3636 return true;
3637 }
3638
3639 @Override
3640 public void onCloseWindow(WebView window) {
3641 final int currentIndex = mTabControl.getCurrentIndex();
3642 final TabControl.Tab parent =
3643 mTabControl.getCurrentTab().getParentTab();
3644 if (parent != null) {
3645 // JavaScript can only close popup window.
3646 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3647 }
3648 }
3649
3650 @Override
3651 public void onProgressChanged(WebView view, int newProgress) {
3652 // Block progress updates to the title bar while the tab overview
3653 // is animating or being displayed.
3654 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003655 if (CUSTOM_BROWSER_BAR) {
3656 mTitleBar.setProgress(newProgress);
3657 } else {
3658 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3659 newProgress * 100);
3660
3661 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003662 }
3663
3664 if (newProgress == 100) {
3665 // onProgressChanged() is called for sub-frame too while
3666 // onPageFinished() is only called for the main frame. sync
3667 // cookie and cache promptly here.
3668 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003669 if (mInLoad) {
3670 mInLoad = false;
3671 updateInLoadMenuItems();
3672 }
3673 } else {
3674 // onPageFinished may have already been called but a subframe
3675 // is still loading and updating the progress. Reset mInLoad
3676 // and update the menu items.
3677 if (!mInLoad) {
3678 mInLoad = true;
3679 updateInLoadMenuItems();
3680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003681 }
3682 }
3683
3684 @Override
3685 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003686 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003687
3688 // here, if url is null, we want to reset the title
3689 setUrlTitle(url, title);
3690
3691 if (url == null ||
3692 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3693 return;
3694 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003695 // See if we can find the current url in our history database and
3696 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003697 if (url.startsWith("http://www.")) {
3698 url = url.substring(11);
3699 } else if (url.startsWith("http://")) {
3700 url = url.substring(4);
3701 }
3702 try {
3703 url = "%" + url;
3704 String [] selArgs = new String[] { url };
3705
3706 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3707 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3708 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3709 Browser.HISTORY_PROJECTION, where, selArgs, null);
3710 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 // Current implementation of database only has one entry per
3712 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003713 ContentValues map = new ContentValues();
3714 map.put(Browser.BookmarkColumns.TITLE, title);
3715 mResolver.update(Browser.BOOKMARKS_URI, map,
3716 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 }
3718 c.close();
3719 } catch (IllegalStateException e) {
3720 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3721 } catch (SQLiteException ex) {
3722 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3723 }
3724 }
3725
3726 @Override
3727 public void onReceivedIcon(WebView view, Bitmap icon) {
3728 updateIcon(view.getUrl(), icon);
3729 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003730
Andrei Popescuadc008d2009-06-26 14:11:30 +01003731 @Override
3732 public void onShowCustomView(View view) {
3733 if (mCustomView != null)
3734 return;
3735
3736 // Add the custom view to its container.
3737 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3738 mCustomView = view;
3739 // Save the menu state and set it to empty while the custom
3740 // view is showing.
3741 mOldMenuState = mMenuState;
3742 mMenuState = EMPTY_MENU;
3743 // Finally show the custom view container.
3744 mCustomViewContainer.setVisibility(View.VISIBLE);
3745 mCustomViewContainer.bringToFront();
3746 }
3747
3748 @Override
3749 public void onHideCustomView() {
3750 if (mCustomView == null)
3751 return;
3752
3753 // Remove the custom view from its container.
3754 mCustomViewContainer.removeView(mCustomView);
3755 mCustomView = null;
3756 // Reset the old menu state.
3757 mMenuState = mOldMenuState;
3758 mOldMenuState = EMPTY_MENU;
3759 mCustomViewContainer.setVisibility(View.GONE);
3760 }
3761
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003762 /**
3763 * The origin has exceeded it's database quota.
3764 * @param url the URL that exceeded the quota
3765 * @param databaseIdentifier the identifier of the database on
3766 * which the transaction that caused the quota overflow was run
3767 * @param currentQuota the current quota for the origin.
3768 * @param quotaUpdater The callback to run when a decision to allow or
3769 * deny quota has been made. Don't forget to call this!
3770 */
3771 @Override
3772 public void onExceededDatabaseQuota(String url,
3773 String databaseIdentifier, long currentQuota,
3774 WebStorage.QuotaUpdater quotaUpdater) {
3775 if(LOGV_ENABLED) {
3776 Log.v(LOGTAG,
3777 "BrowserActivity received onExceededDatabaseQuota for "
3778 + url +
3779 ":"
3780 + databaseIdentifier +
3781 "(current quota: "
3782 + currentQuota +
3783 ")");
3784 }
Nicolas Roard78a98e42009-05-11 13:34:17 +01003785 mWebStorageQuotaUpdater = quotaUpdater;
3786 String DIALOG_PACKAGE = "com.android.browser";
3787 String DIALOG_CLASS = DIALOG_PACKAGE + ".PermissionDialog";
3788 Intent intent = new Intent();
3789 intent.setClassName(DIALOG_PACKAGE, DIALOG_CLASS);
3790 intent.putExtra(PermissionDialog.PARAM_ORIGIN, url);
3791 intent.putExtra(PermissionDialog.PARAM_QUOTA, currentQuota);
3792 startActivityForResult(intent, WEBSTORAGE_QUOTA_DIALOG);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003793 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003794
3795 /* Adds a JavaScript error message to the system log.
3796 * @param message The error message to report.
3797 * @param lineNumber The line number of the error.
3798 * @param sourceID The name of the source file that caused the error.
3799 */
3800 @Override
3801 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3802 Log.w(LOGTAG, "Console: " + message + " (" + sourceID + ":" + lineNumber + ")");
3803 }
3804
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805 };
3806
3807 /**
3808 * Notify the host application a download should be done, or that
3809 * the data should be streamed if a streaming viewer is available.
3810 * @param url The full url to the content that should be downloaded
3811 * @param contentDisposition Content-disposition http header, if
3812 * present.
3813 * @param mimetype The mimetype of the content reported by the server
3814 * @param contentLength The file size reported by the server
3815 */
3816 public void onDownloadStart(String url, String userAgent,
3817 String contentDisposition, String mimetype, long contentLength) {
3818 // if we're dealing wih A/V content that's not explicitly marked
3819 // for download, check if it's streamable.
3820 if (contentDisposition == null
3821 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3822 // query the package manager to see if there's a registered handler
3823 // that matches.
3824 Intent intent = new Intent(Intent.ACTION_VIEW);
3825 intent.setDataAndType(Uri.parse(url), mimetype);
3826 if (getPackageManager().resolveActivity(intent,
3827 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3828 // someone knows how to handle this mime type with this scheme, don't download.
3829 try {
3830 startActivity(intent);
3831 return;
3832 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003833 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 Log.d(LOGTAG, "activity not found for " + mimetype
3835 + " over " + Uri.parse(url).getScheme(), ex);
3836 }
3837 // Best behavior is to fall back to a download in this case
3838 }
3839 }
3840 }
3841 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3842 }
3843
3844 /**
3845 * Notify the host application a download should be done, even if there
3846 * is a streaming viewer available for thise type.
3847 * @param url The full url to the content that should be downloaded
3848 * @param contentDisposition Content-disposition http header, if
3849 * present.
3850 * @param mimetype The mimetype of the content reported by the server
3851 * @param contentLength The file size reported by the server
3852 */
3853 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3854 String contentDisposition, String mimetype, long contentLength) {
3855
3856 String filename = URLUtil.guessFileName(url,
3857 contentDisposition, mimetype);
3858
3859 // Check to see if we have an SDCard
3860 String status = Environment.getExternalStorageState();
3861 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3862 int title;
3863 String msg;
3864
3865 // Check to see if the SDCard is busy, same as the music app
3866 if (status.equals(Environment.MEDIA_SHARED)) {
3867 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3868 title = R.string.download_sdcard_busy_dlg_title;
3869 } else {
3870 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3871 title = R.string.download_no_sdcard_dlg_title;
3872 }
3873
3874 new AlertDialog.Builder(this)
3875 .setTitle(title)
3876 .setIcon(android.R.drawable.ic_dialog_alert)
3877 .setMessage(msg)
3878 .setPositiveButton(R.string.ok, null)
3879 .show();
3880 return;
3881 }
3882
3883 // java.net.URI is a lot stricter than KURL so we have to undo
3884 // KURL's percent-encoding and redo the encoding using java.net.URI.
3885 URI uri = null;
3886 try {
3887 // Undo the percent-encoding that KURL may have done.
3888 String newUrl = new String(URLUtil.decode(url.getBytes()));
3889 // Parse the url into pieces
3890 WebAddress w = new WebAddress(newUrl);
3891 String frag = null;
3892 String query = null;
3893 String path = w.mPath;
3894 // Break the path into path, query, and fragment
3895 if (path.length() > 0) {
3896 // Strip the fragment
3897 int idx = path.lastIndexOf('#');
3898 if (idx != -1) {
3899 frag = path.substring(idx + 1);
3900 path = path.substring(0, idx);
3901 }
3902 idx = path.lastIndexOf('?');
3903 if (idx != -1) {
3904 query = path.substring(idx + 1);
3905 path = path.substring(0, idx);
3906 }
3907 }
3908 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3909 query, frag);
3910 } catch (Exception e) {
3911 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3912 return;
3913 }
3914
3915 // XXX: Have to use the old url since the cookies were stored using the
3916 // old percent-encoded url.
3917 String cookies = CookieManager.getInstance().getCookie(url);
3918
3919 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003920 values.put(Downloads.COLUMN_URI, uri.toString());
3921 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3922 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3923 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003925 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003927 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3928 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3929 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3930 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003931 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003932 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 }
3934 if (mimetype == null) {
3935 // We must have long pressed on a link or image to download it. We
3936 // are not sure of the mimetype in this case, so do a head request
3937 new FetchUrlMimeType(this).execute(values);
3938 } else {
3939 final Uri contentUri =
3940 getContentResolver().insert(Downloads.CONTENT_URI, values);
3941 viewDownloads(contentUri);
3942 }
3943
3944 }
3945
3946 /**
3947 * Resets the lock icon. This method is called when we start a new load and
3948 * know the url to be loaded.
3949 */
3950 private void resetLockIcon(String url) {
3951 // Save the lock-icon state (we revert to it if the load gets cancelled)
3952 saveLockIcon();
3953
3954 mLockIconType = LOCK_ICON_UNSECURE;
3955 if (URLUtil.isHttpsUrl(url)) {
3956 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003957 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003958 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3959 " reset lock icon to " + mLockIconType);
3960 }
3961 }
3962
3963 updateLockIconImage(LOCK_ICON_UNSECURE);
3964 }
3965
3966 /**
3967 * Resets the lock icon. This method is called when the icon needs to be
3968 * reset but we do not know whether we are loading a secure or not secure
3969 * page.
3970 */
3971 private void resetLockIcon() {
3972 // Save the lock-icon state (we revert to it if the load gets cancelled)
3973 saveLockIcon();
3974
3975 mLockIconType = LOCK_ICON_UNSECURE;
3976
Dave Bort31a6d1c2009-04-13 15:56:49 -07003977 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003978 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3979 " reset lock icon to " + mLockIconType);
3980 }
3981
3982 updateLockIconImage(LOCK_ICON_UNSECURE);
3983 }
3984
3985 /**
3986 * Updates the lock-icon image in the title-bar.
3987 */
3988 private void updateLockIconImage(int lockIconType) {
3989 Drawable d = null;
3990 if (lockIconType == LOCK_ICON_SECURE) {
3991 d = mSecLockIcon;
3992 } else if (lockIconType == LOCK_ICON_MIXED) {
3993 d = mMixLockIcon;
3994 }
3995 // If the tab overview is animating or being shown, do not update the
3996 // lock icon.
3997 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003998 if (CUSTOM_BROWSER_BAR) {
3999 mTitleBar.setLock(d);
4000 } else {
4001 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4002 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004003 }
4004 }
4005
4006 /**
4007 * Displays a page-info dialog.
4008 * @param tab The tab to show info about
4009 * @param fromShowSSLCertificateOnError The flag that indicates whether
4010 * this dialog was opened from the SSL-certificate-on-error dialog or
4011 * not. This is important, since we need to know whether to return to
4012 * the parent dialog or simply dismiss.
4013 */
4014 private void showPageInfo(final TabControl.Tab tab,
4015 final boolean fromShowSSLCertificateOnError) {
4016 final LayoutInflater factory = LayoutInflater
4017 .from(this);
4018
4019 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4020
4021 final WebView view = tab.getWebView();
4022
4023 String url = null;
4024 String title = null;
4025
4026 if (view == null) {
4027 url = tab.getUrl();
4028 title = tab.getTitle();
4029 } else if (view == mTabControl.getCurrentWebView()) {
4030 // Use the cached title and url if this is the current WebView
4031 url = mUrl;
4032 title = mTitle;
4033 } else {
4034 url = view.getUrl();
4035 title = view.getTitle();
4036 }
4037
4038 if (url == null) {
4039 url = "";
4040 }
4041 if (title == null) {
4042 title = "";
4043 }
4044
4045 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4046 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4047
4048 mPageInfoView = tab;
4049 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4050
4051 AlertDialog.Builder alertDialogBuilder =
4052 new AlertDialog.Builder(this)
4053 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4054 .setView(pageInfoView)
4055 .setPositiveButton(
4056 R.string.ok,
4057 new DialogInterface.OnClickListener() {
4058 public void onClick(DialogInterface dialog,
4059 int whichButton) {
4060 mPageInfoDialog = null;
4061 mPageInfoView = null;
4062 mPageInfoFromShowSSLCertificateOnError = null;
4063
4064 // if we came here from the SSL error dialog
4065 if (fromShowSSLCertificateOnError) {
4066 // go back to the SSL error dialog
4067 showSSLCertificateOnError(
4068 mSSLCertificateOnErrorView,
4069 mSSLCertificateOnErrorHandler,
4070 mSSLCertificateOnErrorError);
4071 }
4072 }
4073 })
4074 .setOnCancelListener(
4075 new DialogInterface.OnCancelListener() {
4076 public void onCancel(DialogInterface dialog) {
4077 mPageInfoDialog = null;
4078 mPageInfoView = null;
4079 mPageInfoFromShowSSLCertificateOnError = null;
4080
4081 // if we came here from the SSL error dialog
4082 if (fromShowSSLCertificateOnError) {
4083 // go back to the SSL error dialog
4084 showSSLCertificateOnError(
4085 mSSLCertificateOnErrorView,
4086 mSSLCertificateOnErrorHandler,
4087 mSSLCertificateOnErrorError);
4088 }
4089 }
4090 });
4091
4092 // if we have a main top-level page SSL certificate set or a certificate
4093 // error
4094 if (fromShowSSLCertificateOnError ||
4095 (view != null && view.getCertificate() != null)) {
4096 // add a 'View Certificate' button
4097 alertDialogBuilder.setNeutralButton(
4098 R.string.view_certificate,
4099 new DialogInterface.OnClickListener() {
4100 public void onClick(DialogInterface dialog,
4101 int whichButton) {
4102 mPageInfoDialog = null;
4103 mPageInfoView = null;
4104 mPageInfoFromShowSSLCertificateOnError = null;
4105
4106 // if we came here from the SSL error dialog
4107 if (fromShowSSLCertificateOnError) {
4108 // go back to the SSL error dialog
4109 showSSLCertificateOnError(
4110 mSSLCertificateOnErrorView,
4111 mSSLCertificateOnErrorHandler,
4112 mSSLCertificateOnErrorError);
4113 } else {
4114 // otherwise, display the top-most certificate from
4115 // the chain
4116 if (view.getCertificate() != null) {
4117 showSSLCertificate(tab);
4118 }
4119 }
4120 }
4121 });
4122 }
4123
4124 mPageInfoDialog = alertDialogBuilder.show();
4125 }
4126
4127 /**
4128 * Displays the main top-level page SSL certificate dialog
4129 * (accessible from the Page-Info dialog).
4130 * @param tab The tab to show certificate for.
4131 */
4132 private void showSSLCertificate(final TabControl.Tab tab) {
4133 final View certificateView =
4134 inflateCertificateView(tab.getWebView().getCertificate());
4135 if (certificateView == null) {
4136 return;
4137 }
4138
4139 LayoutInflater factory = LayoutInflater.from(this);
4140
4141 final LinearLayout placeholder =
4142 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4143
4144 LinearLayout ll = (LinearLayout) factory.inflate(
4145 R.layout.ssl_success, placeholder);
4146 ((TextView)ll.findViewById(R.id.success))
4147 .setText(R.string.ssl_certificate_is_valid);
4148
4149 mSSLCertificateView = tab;
4150 mSSLCertificateDialog =
4151 new AlertDialog.Builder(this)
4152 .setTitle(R.string.ssl_certificate).setIcon(
4153 R.drawable.ic_dialog_browser_certificate_secure)
4154 .setView(certificateView)
4155 .setPositiveButton(R.string.ok,
4156 new DialogInterface.OnClickListener() {
4157 public void onClick(DialogInterface dialog,
4158 int whichButton) {
4159 mSSLCertificateDialog = null;
4160 mSSLCertificateView = null;
4161
4162 showPageInfo(tab, false);
4163 }
4164 })
4165 .setOnCancelListener(
4166 new DialogInterface.OnCancelListener() {
4167 public void onCancel(DialogInterface dialog) {
4168 mSSLCertificateDialog = null;
4169 mSSLCertificateView = null;
4170
4171 showPageInfo(tab, false);
4172 }
4173 })
4174 .show();
4175 }
4176
4177 /**
4178 * Displays the SSL error certificate dialog.
4179 * @param view The target web-view.
4180 * @param handler The SSL error handler responsible for cancelling the
4181 * connection that resulted in an SSL error or proceeding per user request.
4182 * @param error The SSL error object.
4183 */
4184 private void showSSLCertificateOnError(
4185 final WebView view, final SslErrorHandler handler, final SslError error) {
4186
4187 final View certificateView =
4188 inflateCertificateView(error.getCertificate());
4189 if (certificateView == null) {
4190 return;
4191 }
4192
4193 LayoutInflater factory = LayoutInflater.from(this);
4194
4195 final LinearLayout placeholder =
4196 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4197
4198 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4199 LinearLayout ll = (LinearLayout)factory
4200 .inflate(R.layout.ssl_warning, placeholder);
4201 ((TextView)ll.findViewById(R.id.warning))
4202 .setText(R.string.ssl_untrusted);
4203 }
4204
4205 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4206 LinearLayout ll = (LinearLayout)factory
4207 .inflate(R.layout.ssl_warning, placeholder);
4208 ((TextView)ll.findViewById(R.id.warning))
4209 .setText(R.string.ssl_mismatch);
4210 }
4211
4212 if (error.hasError(SslError.SSL_EXPIRED)) {
4213 LinearLayout ll = (LinearLayout)factory
4214 .inflate(R.layout.ssl_warning, placeholder);
4215 ((TextView)ll.findViewById(R.id.warning))
4216 .setText(R.string.ssl_expired);
4217 }
4218
4219 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4220 LinearLayout ll = (LinearLayout)factory
4221 .inflate(R.layout.ssl_warning, placeholder);
4222 ((TextView)ll.findViewById(R.id.warning))
4223 .setText(R.string.ssl_not_yet_valid);
4224 }
4225
4226 mSSLCertificateOnErrorHandler = handler;
4227 mSSLCertificateOnErrorView = view;
4228 mSSLCertificateOnErrorError = error;
4229 mSSLCertificateOnErrorDialog =
4230 new AlertDialog.Builder(this)
4231 .setTitle(R.string.ssl_certificate).setIcon(
4232 R.drawable.ic_dialog_browser_certificate_partially_secure)
4233 .setView(certificateView)
4234 .setPositiveButton(R.string.ok,
4235 new DialogInterface.OnClickListener() {
4236 public void onClick(DialogInterface dialog,
4237 int whichButton) {
4238 mSSLCertificateOnErrorDialog = null;
4239 mSSLCertificateOnErrorView = null;
4240 mSSLCertificateOnErrorHandler = null;
4241 mSSLCertificateOnErrorError = null;
4242
4243 mWebViewClient.onReceivedSslError(
4244 view, handler, error);
4245 }
4246 })
4247 .setNeutralButton(R.string.page_info_view,
4248 new DialogInterface.OnClickListener() {
4249 public void onClick(DialogInterface dialog,
4250 int whichButton) {
4251 mSSLCertificateOnErrorDialog = null;
4252
4253 // do not clear the dialog state: we will
4254 // need to show the dialog again once the
4255 // user is done exploring the page-info details
4256
4257 showPageInfo(mTabControl.getTabFromView(view),
4258 true);
4259 }
4260 })
4261 .setOnCancelListener(
4262 new DialogInterface.OnCancelListener() {
4263 public void onCancel(DialogInterface dialog) {
4264 mSSLCertificateOnErrorDialog = null;
4265 mSSLCertificateOnErrorView = null;
4266 mSSLCertificateOnErrorHandler = null;
4267 mSSLCertificateOnErrorError = null;
4268
4269 mWebViewClient.onReceivedSslError(
4270 view, handler, error);
4271 }
4272 })
4273 .show();
4274 }
4275
4276 /**
4277 * Inflates the SSL certificate view (helper method).
4278 * @param certificate The SSL certificate.
4279 * @return The resultant certificate view with issued-to, issued-by,
4280 * issued-on, expires-on, and possibly other fields set.
4281 * If the input certificate is null, returns null.
4282 */
4283 private View inflateCertificateView(SslCertificate certificate) {
4284 if (certificate == null) {
4285 return null;
4286 }
4287
4288 LayoutInflater factory = LayoutInflater.from(this);
4289
4290 View certificateView = factory.inflate(
4291 R.layout.ssl_certificate, null);
4292
4293 // issued to:
4294 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4295 if (issuedTo != null) {
4296 ((TextView) certificateView.findViewById(R.id.to_common))
4297 .setText(issuedTo.getCName());
4298 ((TextView) certificateView.findViewById(R.id.to_org))
4299 .setText(issuedTo.getOName());
4300 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4301 .setText(issuedTo.getUName());
4302 }
4303
4304 // issued by:
4305 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4306 if (issuedBy != null) {
4307 ((TextView) certificateView.findViewById(R.id.by_common))
4308 .setText(issuedBy.getCName());
4309 ((TextView) certificateView.findViewById(R.id.by_org))
4310 .setText(issuedBy.getOName());
4311 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4312 .setText(issuedBy.getUName());
4313 }
4314
4315 // issued on:
4316 String issuedOn = reformatCertificateDate(
4317 certificate.getValidNotBefore());
4318 ((TextView) certificateView.findViewById(R.id.issued_on))
4319 .setText(issuedOn);
4320
4321 // expires on:
4322 String expiresOn = reformatCertificateDate(
4323 certificate.getValidNotAfter());
4324 ((TextView) certificateView.findViewById(R.id.expires_on))
4325 .setText(expiresOn);
4326
4327 return certificateView;
4328 }
4329
4330 /**
4331 * Re-formats the certificate date (Date.toString()) string to
4332 * a properly localized date string.
4333 * @return Properly localized version of the certificate date string and
4334 * the original certificate date string if fails to localize.
4335 * If the original string is null, returns an empty string "".
4336 */
4337 private String reformatCertificateDate(String certificateDate) {
4338 String reformattedDate = null;
4339
4340 if (certificateDate != null) {
4341 Date date = null;
4342 try {
4343 date = java.text.DateFormat.getInstance().parse(certificateDate);
4344 } catch (ParseException e) {
4345 date = null;
4346 }
4347
4348 if (date != null) {
4349 reformattedDate =
4350 DateFormat.getDateFormat(this).format(date);
4351 }
4352 }
4353
4354 return reformattedDate != null ? reformattedDate :
4355 (certificateDate != null ? certificateDate : "");
4356 }
4357
4358 /**
4359 * Displays an http-authentication dialog.
4360 */
4361 private void showHttpAuthentication(final HttpAuthHandler handler,
4362 final String host, final String realm, final String title,
4363 final String name, final String password, int focusId) {
4364 LayoutInflater factory = LayoutInflater.from(this);
4365 final View v = factory
4366 .inflate(R.layout.http_authentication, null);
4367 if (name != null) {
4368 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4369 }
4370 if (password != null) {
4371 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4372 }
4373
4374 String titleText = title;
4375 if (titleText == null) {
4376 titleText = getText(R.string.sign_in_to).toString().replace(
4377 "%s1", host).replace("%s2", realm);
4378 }
4379
4380 mHttpAuthHandler = handler;
4381 AlertDialog dialog = new AlertDialog.Builder(this)
4382 .setTitle(titleText)
4383 .setIcon(android.R.drawable.ic_dialog_alert)
4384 .setView(v)
4385 .setPositiveButton(R.string.action,
4386 new DialogInterface.OnClickListener() {
4387 public void onClick(DialogInterface dialog,
4388 int whichButton) {
4389 String nm = ((EditText) v
4390 .findViewById(R.id.username_edit))
4391 .getText().toString();
4392 String pw = ((EditText) v
4393 .findViewById(R.id.password_edit))
4394 .getText().toString();
4395 BrowserActivity.this.setHttpAuthUsernamePassword
4396 (host, realm, nm, pw);
4397 handler.proceed(nm, pw);
4398 mHttpAuthenticationDialog = null;
4399 mHttpAuthHandler = null;
4400 }})
4401 .setNegativeButton(R.string.cancel,
4402 new DialogInterface.OnClickListener() {
4403 public void onClick(DialogInterface dialog,
4404 int whichButton) {
4405 handler.cancel();
4406 BrowserActivity.this.resetTitleAndRevertLockIcon();
4407 mHttpAuthenticationDialog = null;
4408 mHttpAuthHandler = null;
4409 }})
4410 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4411 public void onCancel(DialogInterface dialog) {
4412 handler.cancel();
4413 BrowserActivity.this.resetTitleAndRevertLockIcon();
4414 mHttpAuthenticationDialog = null;
4415 mHttpAuthHandler = null;
4416 }})
4417 .create();
4418 // Make the IME appear when the dialog is displayed if applicable.
4419 dialog.getWindow().setSoftInputMode(
4420 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4421 dialog.show();
4422 if (focusId != 0) {
4423 dialog.findViewById(focusId).requestFocus();
4424 } else {
4425 v.findViewById(R.id.username_edit).requestFocus();
4426 }
4427 mHttpAuthenticationDialog = dialog;
4428 }
4429
4430 public int getProgress() {
4431 WebView w = mTabControl.getCurrentWebView();
4432 if (w != null) {
4433 return w.getProgress();
4434 } else {
4435 return 100;
4436 }
4437 }
4438
4439 /**
4440 * Set HTTP authentication password.
4441 *
4442 * @param host The host for the password
4443 * @param realm The realm for the password
4444 * @param username The username for the password. If it is null, it means
4445 * password can't be saved.
4446 * @param password The password
4447 */
4448 public void setHttpAuthUsernamePassword(String host, String realm,
4449 String username,
4450 String password) {
4451 WebView w = mTabControl.getCurrentWebView();
4452 if (w != null) {
4453 w.setHttpAuthUsernamePassword(host, realm, username, password);
4454 }
4455 }
4456
4457 /**
4458 * connectivity manager says net has come or gone... inform the user
4459 * @param up true if net has come up, false if net has gone down
4460 */
4461 public void onNetworkToggle(boolean up) {
4462 if (up == mIsNetworkUp) {
4463 return;
4464 } else if (up) {
4465 mIsNetworkUp = true;
4466 if (mAlertDialog != null) {
4467 mAlertDialog.cancel();
4468 mAlertDialog = null;
4469 }
4470 } else {
4471 mIsNetworkUp = false;
4472 if (mInLoad && mAlertDialog == null) {
4473 mAlertDialog = new AlertDialog.Builder(this)
4474 .setTitle(R.string.loadSuspendedTitle)
4475 .setMessage(R.string.loadSuspended)
4476 .setPositiveButton(R.string.ok, null)
4477 .show();
4478 }
4479 }
4480 WebView w = mTabControl.getCurrentWebView();
4481 if (w != null) {
4482 w.setNetworkAvailable(up);
4483 }
4484 }
4485
4486 @Override
4487 protected void onActivityResult(int requestCode, int resultCode,
4488 Intent intent) {
4489 switch (requestCode) {
4490 case COMBO_PAGE:
4491 if (resultCode == RESULT_OK && intent != null) {
4492 String data = intent.getAction();
4493 Bundle extras = intent.getExtras();
4494 if (extras != null && extras.getBoolean("new_window", false)) {
4495 openTab(data);
4496 } else {
4497 final TabControl.Tab currentTab =
4498 mTabControl.getCurrentTab();
4499 // If the Window overview is up and we are not in the
4500 // middle of an animation, animate away from it to the
4501 // current tab.
4502 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004503 sendAnimateFromOverview(currentTab, false,
4504 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004505 } else {
4506 dismissSubWindow(currentTab);
4507 if (data != null && data.length() != 0) {
4508 getTopWindow().loadUrl(data);
4509 }
4510 }
4511 }
4512 }
4513 break;
Nicolas Roard78a98e42009-05-11 13:34:17 +01004514 case WEBSTORAGE_QUOTA_DIALOG:
4515 long currentQuota = 0;
4516 if (resultCode == RESULT_OK && intent != null) {
4517 currentQuota = intent.getLongExtra(
4518 PermissionDialog.PARAM_QUOTA, currentQuota);
4519 }
4520 mWebStorageQuotaUpdater.updateQuota(currentQuota);
4521 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004522 default:
4523 break;
4524 }
4525 getTopWindow().requestFocus();
4526 }
4527
4528 /*
4529 * This method is called as a result of the user selecting the options
4530 * menu to see the download window, or when a download changes state. It
4531 * shows the download window ontop of the current window.
4532 */
4533 /* package */ void viewDownloads(Uri downloadRecord) {
4534 Intent intent = new Intent(this,
4535 BrowserDownloadPage.class);
4536 intent.setData(downloadRecord);
4537 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4538
4539 }
4540
4541 /**
4542 * Handle results from Tab Switcher mTabOverview tool
4543 */
4544 private class TabListener implements ImageGrid.Listener {
4545 public void remove(int position) {
4546 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004547 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004548 throw new AssertionError();
4549 }
4550
4551 // Remember the current tab.
4552 TabControl.Tab current = mTabControl.getCurrentTab();
4553 final TabControl.Tab remove = mTabControl.getTab(position);
4554 mTabControl.removeTab(remove);
4555 // If we removed the current tab, use the tab at position - 1 if
4556 // possible.
4557 if (current == remove) {
4558 // If the user removes the last tab, act like the New Tab item
4559 // was clicked on.
4560 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004561 current = mTabControl.createNewTab();
Grace Klobaec7eb372009-06-16 13:45:56 -07004562 sendAnimateFromOverview(current, true, new UrlData(
4563 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004564 } else {
4565 final int index = position > 0 ? (position - 1) : 0;
4566 current = mTabControl.getTab(index);
4567 }
4568 }
4569
4570 // The tab overview could have been dismissed before this method is
4571 // called.
4572 if (mTabOverview != null) {
4573 // Remove the tab and change the index.
4574 mTabOverview.remove(position);
4575 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4576 }
4577
4578 // Only the current tab ensures its WebView is non-null. This
4579 // implies that we are reloading the freed tab.
4580 mTabControl.setCurrentTab(current);
4581 }
4582 public void onClick(int index) {
4583 // Change the tab if necessary.
4584 // Index equals ImageGrid.CANCEL when pressing back from the tab
4585 // overview.
4586 if (index == ImageGrid.CANCEL) {
4587 index = mTabControl.getCurrentIndex();
4588 // The current index is -1 if the current tab was removed.
4589 if (index == -1) {
4590 // Take the last tab as a fallback.
4591 index = mTabControl.getTabCount() - 1;
4592 }
4593 }
4594
The Android Open Source Project0c908882009-03-03 19:32:16 -08004595 // NEW_TAB means that the "New Tab" cell was clicked on.
4596 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004597 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004598 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004599 sendAnimateFromOverview(mTabControl.getTab(index), false,
4600 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004601 }
4602 }
4603 }
4604
4605 // A fake View that draws the WebView's picture with a fast zoom filter.
4606 // The View is used in case the tab is freed during the animation because
4607 // of low memory.
4608 private static class AnimatingView extends View {
4609 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4610 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4611 private static final DrawFilter sZoomFilter =
4612 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4613 private final Picture mPicture;
4614 private final float mScale;
4615 private final int mScrollX;
4616 private final int mScrollY;
4617 final TabControl.Tab mTab;
4618
4619 AnimatingView(Context ctxt, TabControl.Tab t) {
4620 super(ctxt);
4621 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004622 if (t != null && t.getTopWindow() != null) {
4623 // Use the top window in the animation since the tab overview
4624 // will display the top window in each cell.
4625 final WebView w = t.getTopWindow();
4626 mPicture = w.capturePicture();
4627 mScale = w.getScale() / w.getWidth();
4628 mScrollX = w.getScrollX();
4629 mScrollY = w.getScrollY();
4630 } else {
4631 mPicture = null;
4632 mScale = 1.0f;
4633 mScrollX = mScrollY = 0;
4634 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004635 }
4636
4637 @Override
4638 protected void onDraw(Canvas canvas) {
4639 canvas.save();
4640 canvas.drawColor(Color.WHITE);
4641 if (mPicture != null) {
4642 canvas.setDrawFilter(sZoomFilter);
4643 float scale = getWidth() * mScale;
4644 canvas.scale(scale, scale);
4645 canvas.translate(-mScrollX, -mScrollY);
4646 canvas.drawPicture(mPicture);
4647 }
4648 canvas.restore();
4649 }
4650 }
4651
4652 /**
4653 * Open the tab picker. This function will always use the current tab in
4654 * its animation.
4655 * @param stay boolean stating whether the tab picker is to remain open
4656 * (in which case it needs a listener and its menu) or not.
4657 * @param index The index of the tab to show as the selection in the tab
4658 * overview.
4659 * @param remove If true, the tab at index will be removed after the
4660 * animation completes.
4661 */
4662 private void tabPicker(final boolean stay, final int index,
4663 final boolean remove) {
4664 if (mTabOverview != null) {
4665 return;
4666 }
4667
4668 int size = mTabControl.getTabCount();
4669
4670 TabListener l = null;
4671 if (stay) {
4672 l = mTabListener = new TabListener();
4673 }
4674 mTabOverview = new ImageGrid(this, stay, l);
4675
4676 for (int i = 0; i < size; i++) {
4677 final TabControl.Tab t = mTabControl.getTab(i);
4678 mTabControl.populatePickerData(t);
4679 mTabOverview.add(t);
4680 }
4681
4682 // Tell the tab overview to show the current tab, the tab overview will
4683 // handle the "New Tab" case.
4684 int currentIndex = mTabControl.getCurrentIndex();
4685 mTabOverview.setCurrentIndex(currentIndex);
4686
4687 // Attach the tab overview.
4688 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4689
4690 // Create a fake AnimatingView to animate the WebView's picture.
4691 final TabControl.Tab current = mTabControl.getCurrentTab();
4692 final AnimatingView v = new AnimatingView(this, current);
4693 mContentView.addView(v, COVER_SCREEN_PARAMS);
4694 removeTabFromContentView(current);
4695 // Pause timers to get the animation smoother.
4696 current.getWebView().pauseTimers();
4697
4698 // Send a message so the tab picker has a chance to layout and get
4699 // positions for all the cells.
4700 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4701 index, remove ? 1 : 0, v));
4702 // Setting this will indicate that we are animating to the overview. We
4703 // set it here to prevent another request to animate from coming in
4704 // between now and when ANIMATE_TO_OVERVIEW is handled.
4705 mAnimationCount++;
4706 // Always change the title bar to the window overview title while
4707 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004708 if (CUSTOM_BROWSER_BAR) {
4709 mTitleBar.setToTabPicker();
4710 } else {
4711 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4712 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4713 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4714 Window.PROGRESS_VISIBILITY_OFF);
4715 setTitle(R.string.tab_picker_title);
4716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004717 // Make the menu empty until the animation completes.
4718 mMenuState = EMPTY_MENU;
4719 }
4720
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004721 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004722 WebView current = mTabControl.getCurrentWebView();
4723 if (current == null) {
4724 return;
4725 }
4726 Intent intent = new Intent(this,
4727 CombinedBookmarkHistoryActivity.class);
4728 String title = current.getTitle();
4729 String url = current.getUrl();
4730 // Just in case the user opens bookmarks before a page finishes loading
4731 // so the current history item, and therefore the page, is null.
4732 if (null == url) {
4733 url = mLastEnteredUrl;
4734 // This can happen.
4735 if (null == url) {
4736 url = mSettings.getHomePage();
4737 }
4738 }
4739 // In case the web page has not yet received its associated title.
4740 if (title == null) {
4741 title = url;
4742 }
4743 intent.putExtra("title", title);
4744 intent.putExtra("url", url);
4745 intent.putExtra("maxTabsOpen",
4746 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4747 if (startWithHistory) {
4748 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4749 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4750 }
4751 startActivityForResult(intent, COMBO_PAGE);
4752 }
4753
4754 // Called when loading from context menu or LOAD_URL message
4755 private void loadURL(WebView view, String url) {
4756 // In case the user enters nothing.
4757 if (url != null && url.length() != 0 && view != null) {
4758 url = smartUrlFilter(url);
4759 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4760 view.loadUrl(url);
4761 }
4762 }
4763 }
4764
4765 private void checkMemory() {
4766 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4767 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4768 .getMemoryInfo(mi);
4769 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4770 // mi.threshold) for now
4771 // if (mi.lowMemory) {
4772 if (mi.availMem < mi.threshold) {
4773 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4774 + (mi.availMem / 1024) + "K threshold="
4775 + (mi.threshold / 1024) + "K");
4776 mTabControl.freeMemory();
4777 }
4778 }
4779
4780 private String smartUrlFilter(Uri inUri) {
4781 if (inUri != null) {
4782 return smartUrlFilter(inUri.toString());
4783 }
4784 return null;
4785 }
4786
4787
4788 // get window count
4789
4790 int getWindowCount(){
4791 if(mTabControl != null){
4792 return mTabControl.getTabCount();
4793 }
4794 return 0;
4795 }
4796
Feng Qianb34f87a2009-03-24 21:27:26 -07004797 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004798 "(?i)" + // switch on case insensitive matching
4799 "(" + // begin group for schema
4800 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004801 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004802 ")" +
4803 "(.*)" );
4804
4805 /**
4806 * Attempts to determine whether user input is a URL or search
4807 * terms. Anything with a space is passed to search.
4808 *
4809 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4810 * "Http://" converts to "http://"
4811 *
4812 * @return Original or modified URL
4813 *
4814 */
4815 String smartUrlFilter(String url) {
4816
4817 String inUrl = url.trim();
4818 boolean hasSpace = inUrl.indexOf(' ') != -1;
4819
4820 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4821 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004822 // force scheme to lowercase
4823 String scheme = matcher.group(1);
4824 String lcScheme = scheme.toLowerCase();
4825 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004826 inUrl = lcScheme + matcher.group(2);
4827 }
4828 if (hasSpace) {
4829 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004830 }
4831 return inUrl;
4832 }
4833 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004834 // FIXME: Is this the correct place to add to searches?
4835 // what if someone else calls this function?
4836 int shortcut = parseUrlShortcut(inUrl);
4837 if (shortcut != SHORTCUT_INVALID) {
4838 Browser.addSearchUrl(mResolver, inUrl);
4839 String query = inUrl.substring(2);
4840 switch (shortcut) {
4841 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004842 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004843 case SHORTCUT_WIKIPEDIA_SEARCH:
4844 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4845 case SHORTCUT_DICTIONARY_SEARCH:
4846 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4847 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004848 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004849 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004850 }
4851 }
4852 } else {
4853 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4854 return URLUtil.guessUrl(inUrl);
4855 }
4856 }
4857
4858 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004859 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004860 }
4861
4862 private final static int LOCK_ICON_UNSECURE = 0;
4863 private final static int LOCK_ICON_SECURE = 1;
4864 private final static int LOCK_ICON_MIXED = 2;
4865
4866 private int mLockIconType = LOCK_ICON_UNSECURE;
4867 private int mPrevLockType = LOCK_ICON_UNSECURE;
4868
4869 private BrowserSettings mSettings;
4870 private TabControl mTabControl;
4871 private ContentResolver mResolver;
4872 private FrameLayout mContentView;
4873 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004874 private View mCustomView;
4875 private FrameLayout mCustomViewContainer;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004876
4877 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4878 // view, we should rewrite this.
4879 private int mCurrentMenuState = 0;
4880 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004881 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004882 private static final int EMPTY_MENU = -1;
4883 private Menu mMenu;
4884
4885 private FindDialog mFindDialog;
4886 // Used to prevent chording to result in firing two shortcuts immediately
4887 // one after another. Fixes bug 1211714.
4888 boolean mCanChord;
4889
4890 private boolean mInLoad;
4891 private boolean mIsNetworkUp;
4892
4893 private boolean mPageStarted;
4894 private boolean mActivityInPause = true;
4895
4896 private boolean mMenuIsDown;
4897
4898 private final KeyTracker mKeyTracker = new KeyTracker(this);
4899
4900 // As trackball doesn't send repeat down, we have to track it ourselves
4901 private boolean mTrackTrackball;
4902
4903 private static boolean mInTrace;
4904
4905 // Performance probe
4906 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4907 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4908 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4909 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4910 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4911 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4912 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4913 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4914 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4915 };
4916
4917 private long mStart;
4918 private long mProcessStart;
4919 private long mUserStart;
4920 private long mSystemStart;
4921 private long mIdleStart;
4922 private long mIrqStart;
4923
4924 private long mUiStart;
4925
4926 private Drawable mMixLockIcon;
4927 private Drawable mSecLockIcon;
4928 private Drawable mGenericFavicon;
4929
4930 /* hold a ref so we can auto-cancel if necessary */
4931 private AlertDialog mAlertDialog;
4932
4933 // Wait for credentials before loading google.com
4934 private ProgressDialog mCredsDlg;
4935
4936 // The up-to-date URL and title (these can be different from those stored
4937 // in WebView, since it takes some time for the information in WebView to
4938 // get updated)
4939 private String mUrl;
4940 private String mTitle;
4941
4942 // As PageInfo has different style for landscape / portrait, we have
4943 // to re-open it when configuration changed
4944 private AlertDialog mPageInfoDialog;
4945 private TabControl.Tab mPageInfoView;
4946 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4947 // dialog, we should not just dismiss it, but should get back to the
4948 // SSL-certificate-on-error dialog. This flag is used to store this state
4949 private Boolean mPageInfoFromShowSSLCertificateOnError;
4950
4951 // as SSLCertificateOnError has different style for landscape / portrait,
4952 // we have to re-open it when configuration changed
4953 private AlertDialog mSSLCertificateOnErrorDialog;
4954 private WebView mSSLCertificateOnErrorView;
4955 private SslErrorHandler mSSLCertificateOnErrorHandler;
4956 private SslError mSSLCertificateOnErrorError;
4957
4958 // as SSLCertificate has different style for landscape / portrait, we
4959 // have to re-open it when configuration changed
4960 private AlertDialog mSSLCertificateDialog;
4961 private TabControl.Tab mSSLCertificateView;
4962
4963 // as HttpAuthentication has different style for landscape / portrait, we
4964 // have to re-open it when configuration changed
4965 private AlertDialog mHttpAuthenticationDialog;
4966 private HttpAuthHandler mHttpAuthHandler;
4967
4968 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4969 new FrameLayout.LayoutParams(
4970 ViewGroup.LayoutParams.FILL_PARENT,
4971 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004972 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4973 new FrameLayout.LayoutParams(
4974 ViewGroup.LayoutParams.FILL_PARENT,
4975 ViewGroup.LayoutParams.FILL_PARENT,
4976 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004977 // Google search
4978 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004979 // Wikipedia search
4980 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4981 // Dictionary search
4982 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4983 // Google Mobile Local search
4984 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4985
4986 final static String QUERY_PLACE_HOLDER = "%s";
4987
4988 // "source" parameter for Google search through search key
4989 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4990 // "source" parameter for Google search through goto menu
4991 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4992 // "source" parameter for Google search through simplily type
4993 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4994 // "source" parameter for Google search suggested by the browser
4995 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4996 // "source" parameter for Google search from unknown source
4997 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4998
4999 private final static String LOGTAG = "browser";
5000
5001 private TabListener mTabListener;
5002
5003 private String mLastEnteredUrl;
5004
5005 private PowerManager.WakeLock mWakeLock;
5006 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5007
5008 private Toast mStopToast;
5009
Leon Scroggins81db3662009-06-04 17:45:11 -04005010 private TitleBar mTitleBar;
5011
The Android Open Source Project0c908882009-03-03 19:32:16 -08005012 // Used during animations to prevent other animations from being triggered.
5013 // A count is used since the animation to and from the Window overview can
5014 // overlap. A count of 0 means no animation where a count of > 0 means
5015 // there are animations in progress.
5016 private int mAnimationCount;
5017
5018 // As the ids are dynamically created, we can't guarantee that they will
5019 // be in sequence, so this static array maps ids to a window number.
5020 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5021 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5022 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5023 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5024
5025 // monitor platform changes
5026 private IntentFilter mNetworkStateChangedFilter;
5027 private BroadcastReceiver mNetworkStateIntentReceiver;
5028
Grace Klobab4da0ad2009-05-14 14:45:40 -07005029 private BroadcastReceiver mPackageInstallationReceiver;
5030
The Android Open Source Project0c908882009-03-03 19:32:16 -08005031 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005032 final static int COMBO_PAGE = 1;
5033 final static int DOWNLOAD_PAGE = 2;
5034 final static int PREFERENCES_PAGE = 3;
5035 final static int WEBSTORAGE_QUOTA_DIALOG = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005036
5037 // the frenquency of checking whether system memory is low
5038 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005039
5040 /**
5041 * A UrlData class to abstract how the content will be set to WebView.
5042 * This base class uses loadUrl to show the content.
5043 */
5044 private static class UrlData {
5045 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005046 byte[] mPostData;
5047
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005048 UrlData(String url) {
5049 this.mUrl = url;
5050 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005051
5052 void setPostData(byte[] postData) {
5053 mPostData = postData;
5054 }
5055
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005056 boolean isEmpty() {
5057 return mUrl == null || mUrl.length() == 0;
5058 }
5059
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005060 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005061 if (mPostData != null) {
5062 webView.postUrl(mUrl, mPostData);
5063 } else {
5064 webView.loadUrl(mUrl);
5065 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005066 }
5067 };
5068
5069 /**
5070 * A subclass of UrlData class that can display inlined content using
5071 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5072 */
5073 private static class InlinedUrlData extends UrlData {
5074 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5075 super(failUrl);
5076 mInlined = inlined;
5077 mMimeType = mimeType;
5078 mEncoding = encoding;
5079 }
5080 String mMimeType;
5081 String mInlined;
5082 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005083 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005084 boolean isEmpty() {
5085 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
5086 }
5087
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005088 @Override
5089 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005090 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5091 }
5092 }
5093
5094 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005095}