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