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