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