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