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