blob: 7f404943804e2e76e2466071b983d324d10a05da [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
The Android Open Source Project0c908882009-03-03 19:32:16 -0800897 if (Intent.ACTION_VIEW.equals(action) &&
898 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700899 final String appId =
900 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID);
Patrick Scottcd115892009-07-16 09:42:58 -0400901 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700902 if (appTab != null) {
903 Log.i(LOGTAG, "Reusing tab for " + appId);
904 // Dismiss the subwindow if applicable.
905 dismissSubWindow(appTab);
906 // Since we might kill the WebView, remove it from the
907 // content view first.
908 removeTabFromContentView(appTab);
909 // Recreate the main WebView after destroying the old one.
910 // If the WebView has the same original url and is on that
911 // page, it can be reused.
912 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700913 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100914
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700915 if (current != appTab) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700916 showTab(appTab, needsLoad ? urlData : EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700917 } else {
918 if (mTabOverview != null && mAnimationCount == 0) {
919 sendAnimateFromOverview(appTab, false,
Grace Klobaec7eb372009-06-16 13:45:56 -0700920 needsLoad ? urlData : EMPTY_URL_DATA,
Grace Kloba8ca2c792009-05-26 15:41:51 -0700921 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700922 } else {
923 // If the tab was the current tab, we have to attach
924 // it to the view system again.
925 attachTabToContentView(appTab);
926 if (needsLoad) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700927 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700928 }
929 }
930 }
931 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400932 } else {
933 // No matching application tab, try to find a regular tab
934 // with a matching url.
935 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
936 if (appTab != null) {
937 if (current != appTab) {
938 // Use EMPTY_URL_DATA so we do not reload the page
939 showTab(appTab, EMPTY_URL_DATA);
940 } else {
941 if (mTabOverview != null && mAnimationCount == 0) {
942 sendAnimateFromOverview(appTab, false,
943 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY,
944 null);
945 }
946 // Don't do anything here since we are on the
947 // correct page.
948 }
949 } else {
950 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
951 // will be opened in a new tab unless we have reached
952 // MAX_TABS. Then the url will be opened in the current
953 // tab. If a new tab is created, it will have "true" for
954 // exit on close.
955 openTabAndShow(urlData, null, true, appId);
956 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700957 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700959 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 mSettings.toggleDebugSettings();
961 return;
962 }
963 // If the Window overview is up and we are not in the midst of
964 // an animation, animate away from the Window overview.
965 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700966 sendAnimateFromOverview(current, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 TAB_OVERVIEW_DELAY, null);
968 } else {
969 // Get rid of the subwindow if it exists
970 dismissSubWindow(current);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700971 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800972 }
973 }
974 }
975 }
976
Satish Sampath565505b2009-05-29 15:37:27 +0100977 private int parseUrlShortcut(String url) {
978 if (url == null) return SHORTCUT_INVALID;
979
980 // FIXME: quick search, need to be customized by setting
981 if (url.length() > 2 && url.charAt(1) == ' ') {
982 switch (url.charAt(0)) {
983 case 'g': return SHORTCUT_GOOGLE_SEARCH;
984 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
985 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
986 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
987 }
988 }
989 return SHORTCUT_INVALID;
990 }
991
992 /**
993 * Launches the default web search activity with the query parameters if the given intent's data
994 * are identified as plain search terms and not URLs/shortcuts.
995 * @return true if the intent was handled and web search activity was launched, false if not.
996 */
997 private boolean handleWebSearchIntent(Intent intent) {
998 if (intent == null) return false;
999
1000 String url = null;
1001 final String action = intent.getAction();
1002 if (Intent.ACTION_VIEW.equals(action)) {
1003 url = intent.getData().toString();
1004 } else if (Intent.ACTION_SEARCH.equals(action)
1005 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1006 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1007 url = intent.getStringExtra(SearchManager.QUERY);
1008 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001009 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +01001010 }
1011
1012 /**
1013 * Launches the default web search activity with the query parameters if the given url string
1014 * was identified as plain search terms and not URL/shortcut.
1015 * @return true if the request was handled and web search activity was launched, false if not.
1016 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001017 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +01001018 if (inUrl == null) return false;
1019
1020 // In general, we shouldn't modify URL from Intent.
1021 // But currently, we get the user-typed URL from search box as well.
1022 String url = fixUrl(inUrl).trim();
1023
1024 // URLs and site specific search shortcuts are handled by the regular flow of control, so
1025 // return early.
1026 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +01001027 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +01001028 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
1029 return false;
1030 }
1031
1032 Browser.updateVisitedHistory(mResolver, url, false);
1033 Browser.addSearchUrl(mResolver, url);
1034
1035 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
1036 intent.addCategory(Intent.CATEGORY_DEFAULT);
1037 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001038 if (appData != null) {
1039 intent.putExtra(SearchManager.APP_DATA, appData);
1040 }
Satish Sampath565505b2009-05-29 15:37:27 +01001041 startActivity(intent);
1042
1043 return true;
1044 }
1045
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001046 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 String url = null;
1048 if (intent != null) {
1049 final String action = intent.getAction();
1050 if (Intent.ACTION_VIEW.equals(action)) {
1051 url = smartUrlFilter(intent.getData());
1052 if (url != null && url.startsWith("content:")) {
1053 /* Append mimetype so webview knows how to display */
1054 String mimeType = intent.resolveType(getContentResolver());
1055 if (mimeType != null) {
1056 url += "?" + mimeType;
1057 }
1058 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001059 if ("inline:".equals(url)) {
1060 return new InlinedUrlData(
1061 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
1062 intent.getType(),
1063 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
1064 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
1065 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 } else if (Intent.ACTION_SEARCH.equals(action)
1067 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1068 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1069 url = intent.getStringExtra(SearchManager.QUERY);
1070 if (url != null) {
1071 mLastEnteredUrl = url;
1072 // Don't add Urls, just search terms.
1073 // Urls will get added when the page is loaded.
1074 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
1075 Browser.updateVisitedHistory(mResolver, url, false);
1076 }
1077 // In general, we shouldn't modify URL from Intent.
1078 // But currently, we get the user-typed URL from search box as well.
1079 url = fixUrl(url);
1080 url = smartUrlFilter(url);
1081 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
1082 if (url.contains(searchSource)) {
1083 String source = null;
1084 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
1085 if (appData != null) {
1086 source = appData.getString(SearchManager.SOURCE);
1087 }
1088 if (TextUtils.isEmpty(source)) {
1089 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
1090 }
1091 url = url.replace(searchSource, "&source=android-"+source+"&");
1092 }
1093 }
1094 }
1095 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001096 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 }
1098
1099 /* package */ static String fixUrl(String inUrl) {
1100 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
1101 return inUrl;
1102 if (inUrl.startsWith("http:") ||
1103 inUrl.startsWith("https:")) {
1104 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
1105 inUrl = inUrl.replaceFirst("/", "//");
1106 } else inUrl = inUrl.replaceFirst(":", "://");
1107 }
1108 return inUrl;
1109 }
1110
1111 /**
1112 * Looking for the pattern like this
1113 *
1114 * *
1115 * * *
1116 * *** * *******
1117 * * *
1118 * * *
1119 * *
1120 */
1121 private final SensorListener mSensorListener = new SensorListener() {
1122 private long mLastGestureTime;
1123 private float[] mPrev = new float[3];
1124 private float[] mPrevDiff = new float[3];
1125 private float[] mDiff = new float[3];
1126 private float[] mRevertDiff = new float[3];
1127
1128 public void onSensorChanged(int sensor, float[] values) {
1129 boolean show = false;
1130 float[] diff = new float[3];
1131
1132 for (int i = 0; i < 3; i++) {
1133 diff[i] = values[i] - mPrev[i];
1134 if (Math.abs(diff[i]) > 1) {
1135 show = true;
1136 }
1137 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
1138 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
1139 // start track when there is a big move, or revert
1140 mRevertDiff[i] = mDiff[i];
1141 mDiff[i] = 0;
1142 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1143 // reset when it is flat
1144 mDiff[i] = mRevertDiff[i] = 0;
1145 }
1146 mDiff[i] += diff[i];
1147 mPrevDiff[i] = diff[i];
1148 mPrev[i] = values[i];
1149 }
1150
1151 if (false) {
1152 // only shows if we think the delta is big enough, in an attempt
1153 // to detect "serious" moves left/right or up/down
1154 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
1155 + values[0] + ", " + values[1] + ", " + values[2] + ")"
1156 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
1157 + ")");
1158 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1159 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1160 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1161 + mRevertDiff[2] + ")");
1162 }
1163
1164 long now = android.os.SystemClock.uptimeMillis();
1165 if (now - mLastGestureTime > 1000) {
1166 mLastGestureTime = 0;
1167
1168 float y = mDiff[1];
1169 float z = mDiff[2];
1170 float ay = Math.abs(y);
1171 float az = Math.abs(z);
1172 float ry = mRevertDiff[1];
1173 float rz = mRevertDiff[2];
1174 float ary = Math.abs(ry);
1175 float arz = Math.abs(rz);
1176 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
1177 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
1178
1179 if ((gestY || gestZ) && !(gestY && gestZ)) {
1180 WebView view = mTabControl.getCurrentWebView();
1181
1182 if (view != null) {
1183 if (gestZ) {
1184 if (z < 0) {
1185 view.zoomOut();
1186 } else {
1187 view.zoomIn();
1188 }
1189 } else {
1190 view.flingScroll(0, Math.round(y * 100));
1191 }
1192 }
1193 mLastGestureTime = now;
1194 }
1195 }
1196 }
1197
1198 public void onAccuracyChanged(int sensor, int accuracy) {
1199 // TODO Auto-generated method stub
1200
1201 }
1202 };
1203
1204 @Override protected void onResume() {
1205 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -07001206 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1208 }
1209
1210 if (!mActivityInPause) {
1211 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1212 return;
1213 }
1214
Mike Reed7bfa63b2009-05-28 11:08:32 -04001215 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001216 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001217 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218
1219 if (mWakeLock.isHeld()) {
1220 mHandler.removeMessages(RELEASE_WAKELOCK);
1221 mWakeLock.release();
1222 }
1223
1224 if (mCredsDlg != null) {
1225 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
1226 // In case credential request never comes back
1227 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
1228 }
1229 }
1230
1231 registerReceiver(mNetworkStateIntentReceiver,
1232 mNetworkStateChangedFilter);
1233 WebView.enablePlatformNotifications();
1234
1235 if (mSettings.doFlick()) {
1236 if (mSensorManager == null) {
1237 mSensorManager = (SensorManager) getSystemService(
1238 Context.SENSOR_SERVICE);
1239 }
1240 mSensorManager.registerListener(mSensorListener,
1241 SensorManager.SENSOR_ACCELEROMETER,
1242 SensorManager.SENSOR_DELAY_FASTEST);
1243 } else {
1244 mSensorManager = null;
1245 }
1246 }
1247
1248 /**
1249 * onSaveInstanceState(Bundle map)
1250 * onSaveInstanceState is called right before onStop(). The map contains
1251 * the saved state.
1252 */
1253 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001254 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001255 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1256 }
1257 // the default implementation requires each view to have an id. As the
1258 // browser handles the state itself and it doesn't use id for the views,
1259 // don't call the default implementation. Otherwise it will trigger the
1260 // warning like this, "couldn't save which view has focus because the
1261 // focused view XXX has no id".
1262
1263 // Save all the tabs
1264 mTabControl.saveState(outState);
1265 }
1266
1267 @Override protected void onPause() {
1268 super.onPause();
1269
1270 if (mActivityInPause) {
1271 Log.e(LOGTAG, "BrowserActivity is already paused.");
1272 return;
1273 }
1274
Mike Reed7bfa63b2009-05-28 11:08:32 -04001275 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001276 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001277 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001278 mWakeLock.acquire();
1279 mHandler.sendMessageDelayed(mHandler
1280 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1281 }
1282
1283 // Clear the credentials toast if it is up
1284 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1285 mCredsDlg.dismiss();
1286 }
1287 mCredsDlg = null;
1288
1289 cancelStopToast();
1290
1291 // unregister network state listener
1292 unregisterReceiver(mNetworkStateIntentReceiver);
1293 WebView.disablePlatformNotifications();
1294
1295 if (mSensorManager != null) {
1296 mSensorManager.unregisterListener(mSensorListener);
1297 }
1298 }
1299
1300 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001301 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001302 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1303 }
1304 super.onDestroy();
1305 // Remove the current tab and sub window
1306 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001307 if (t != null) {
1308 dismissSubWindow(t);
1309 removeTabFromContentView(t);
1310 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001311 // Destroy all the tabs
1312 mTabControl.destroy();
1313 WebIconDatabase.getInstance().close();
1314 if (mGlsConnection != null) {
1315 unbindService(mGlsConnection);
1316 mGlsConnection = null;
1317 }
1318
1319 //
1320 // stop MASF proxy service
1321 //
1322 //Intent proxyServiceIntent = new Intent();
1323 //proxyServiceIntent.setComponent
1324 // (new ComponentName(
1325 // "com.android.masfproxyservice",
1326 // "com.android.masfproxyservice.MasfProxyService"));
1327 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001328
1329 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001330 }
1331
1332 @Override
1333 public void onConfigurationChanged(Configuration newConfig) {
1334 super.onConfigurationChanged(newConfig);
1335
1336 if (mPageInfoDialog != null) {
1337 mPageInfoDialog.dismiss();
1338 showPageInfo(
1339 mPageInfoView,
1340 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1341 }
1342 if (mSSLCertificateDialog != null) {
1343 mSSLCertificateDialog.dismiss();
1344 showSSLCertificate(
1345 mSSLCertificateView);
1346 }
1347 if (mSSLCertificateOnErrorDialog != null) {
1348 mSSLCertificateOnErrorDialog.dismiss();
1349 showSSLCertificateOnError(
1350 mSSLCertificateOnErrorView,
1351 mSSLCertificateOnErrorHandler,
1352 mSSLCertificateOnErrorError);
1353 }
1354 if (mHttpAuthenticationDialog != null) {
1355 String title = ((TextView) mHttpAuthenticationDialog
1356 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1357 .toString();
1358 String name = ((TextView) mHttpAuthenticationDialog
1359 .findViewById(R.id.username_edit)).getText().toString();
1360 String password = ((TextView) mHttpAuthenticationDialog
1361 .findViewById(R.id.password_edit)).getText().toString();
1362 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1363 .getId();
1364 mHttpAuthenticationDialog.dismiss();
1365 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1366 name, password, focusId);
1367 }
1368 if (mFindDialog != null && mFindDialog.isShowing()) {
1369 mFindDialog.onConfigurationChanged(newConfig);
1370 }
1371 }
1372
1373 @Override public void onLowMemory() {
1374 super.onLowMemory();
1375 mTabControl.freeMemory();
1376 }
1377
Mike Reed7bfa63b2009-05-28 11:08:32 -04001378 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 if ((!mActivityInPause && !mPageStarted) ||
1380 (mActivityInPause && mPageStarted)) {
1381 CookieSyncManager.getInstance().startSync();
1382 WebView w = mTabControl.getCurrentWebView();
1383 if (w != null) {
1384 w.resumeTimers();
1385 }
1386 return true;
1387 } else {
1388 return false;
1389 }
1390 }
1391
Mike Reed7bfa63b2009-05-28 11:08:32 -04001392 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 if (mActivityInPause && !mPageStarted) {
1394 CookieSyncManager.getInstance().stopSync();
1395 WebView w = mTabControl.getCurrentWebView();
1396 if (w != null) {
1397 w.pauseTimers();
1398 }
1399 return true;
1400 } else {
1401 return false;
1402 }
1403 }
1404
1405 /*
1406 * This function is called when we are launching for the first time. We
1407 * are waiting for the login credentials before loading Google home
1408 * pages. This way the user will be logged in straight away.
1409 */
1410 private void waitForCredentials() {
1411 // Show a toast
1412 mCredsDlg = new ProgressDialog(this);
1413 mCredsDlg.setIndeterminate(true);
1414 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1415 // If the user cancels the operation, then cancel the Google
1416 // Credentials request.
1417 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1418 mCredsDlg.show();
1419
1420 // We set a timeout for the retrieval of credentials in onResume()
1421 // as that is when we have freed up some CPU time to get
1422 // the login credentials.
1423 }
1424
1425 /*
1426 * If we have received the credentials or we have timed out and we are
1427 * showing the credentials dialog, then it is time to move on.
1428 */
1429 private void resumeAfterCredentials() {
1430 if (mCredsDlg == null) {
1431 return;
1432 }
1433
1434 // Clear the toast
1435 if (mCredsDlg.isShowing()) {
1436 mCredsDlg.dismiss();
1437 }
1438 mCredsDlg = null;
1439
1440 // Clear any pending timeout
1441 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1442
1443 // Load the page
1444 WebView w = mTabControl.getCurrentWebView();
1445 if (w != null) {
1446 w.loadUrl(mSettings.getHomePage());
1447 }
1448
1449 // Update the settings, need to do this last as it can take a moment
1450 // to persist the settings. In the mean time we could be loading
1451 // content.
1452 mSettings.setLoginInitialized(this);
1453 }
1454
1455 // Open the icon database and retain all the icons for visited sites.
1456 private void retainIconsOnStartup() {
1457 final WebIconDatabase db = WebIconDatabase.getInstance();
1458 db.open(getDir("icons", 0).getPath());
1459 try {
1460 Cursor c = Browser.getAllBookmarks(mResolver);
1461 if (!c.moveToFirst()) {
1462 c.deactivate();
1463 return;
1464 }
1465 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1466 do {
1467 String url = c.getString(urlIndex);
1468 db.retainIconForPageUrl(url);
1469 } while (c.moveToNext());
1470 c.deactivate();
1471 } catch (IllegalStateException e) {
1472 Log.e(LOGTAG, "retainIconsOnStartup", e);
1473 }
1474 }
1475
1476 // Helper method for getting the top window.
1477 WebView getTopWindow() {
1478 return mTabControl.getCurrentTopWebView();
1479 }
1480
1481 @Override
1482 public boolean onCreateOptionsMenu(Menu menu) {
1483 super.onCreateOptionsMenu(menu);
1484
1485 MenuInflater inflater = getMenuInflater();
1486 inflater.inflate(R.menu.browser, menu);
1487 mMenu = menu;
1488 updateInLoadMenuItems();
1489 return true;
1490 }
1491
1492 /**
1493 * As the menu can be open when loading state changes
1494 * we must manually update the state of the stop/reload menu
1495 * item
1496 */
1497 private void updateInLoadMenuItems() {
1498 if (mMenu == null) {
1499 return;
1500 }
1501 MenuItem src = mInLoad ?
1502 mMenu.findItem(R.id.stop_menu_id):
1503 mMenu.findItem(R.id.reload_menu_id);
1504 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1505 dest.setIcon(src.getIcon());
1506 dest.setTitle(src.getTitle());
1507 }
1508
1509 @Override
1510 public boolean onContextItemSelected(MenuItem item) {
1511 // chording is not an issue with context menus, but we use the same
1512 // options selector, so set mCanChord to true so we can access them.
1513 mCanChord = true;
1514 int id = item.getItemId();
1515 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001516 if (null == webView) {
1517 return false;
1518 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001519 final HashMap hrefMap = new HashMap();
1520 hrefMap.put("webview", webView);
1521 final Message msg = mHandler.obtainMessage(
1522 FOCUS_NODE_HREF, id, 0, hrefMap);
1523 switch (id) {
1524 // -- Browser context menu
1525 case R.id.open_context_menu_id:
1526 case R.id.open_newtab_context_menu_id:
1527 case R.id.bookmark_context_menu_id:
1528 case R.id.save_link_context_menu_id:
1529 case R.id.share_link_context_menu_id:
1530 case R.id.copy_link_context_menu_id:
1531 webView.requestFocusNodeHref(msg);
1532 break;
1533
1534 default:
1535 // For other context menus
1536 return onOptionsItemSelected(item);
1537 }
1538 mCanChord = false;
1539 return true;
1540 }
1541
1542 private Bundle createGoogleSearchSourceBundle(String source) {
1543 Bundle bundle = new Bundle();
1544 bundle.putString(SearchManager.SOURCE, source);
1545 return bundle;
1546 }
1547
1548 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001549 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 */
1551 @Override
1552 public boolean onSearchRequested() {
Grace Klobacf849952009-07-09 18:57:55 -07001553 String url = getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001554 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001555 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 return true;
1557 }
1558
1559 @Override
1560 public void startSearch(String initialQuery, boolean selectInitialQuery,
1561 Bundle appSearchData, boolean globalSearch) {
1562 if (appSearchData == null) {
1563 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1564 }
1565 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1566 }
1567
1568 @Override
1569 public boolean onOptionsItemSelected(MenuItem item) {
1570 if (!mCanChord) {
1571 // The user has already fired a shortcut with this hold down of the
1572 // menu key.
1573 return false;
1574 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001575 if (null == mTabOverview && null == getTopWindow()) {
1576 return false;
1577 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001578 if (mMenuIsDown) {
1579 // The shortcut action consumes the MENU. Even if it is still down,
1580 // it won't trigger the next shortcut action. In the case of the
1581 // shortcut action triggering a new activity, like Bookmarks, we
1582 // won't get onKeyUp for MENU. So it is important to reset it here.
1583 mMenuIsDown = false;
1584 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001585 switch (item.getItemId()) {
1586 // -- Main menu
1587 case R.id.goto_menu_id: {
1588 String url = getTopWindow().getUrl();
1589 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1590 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1591 }
1592 break;
1593
1594 case R.id.bookmarks_menu_id:
1595 bookmarksOrHistoryPicker(false);
1596 break;
1597
1598 case R.id.windows_menu_id:
1599 if (mTabControl.getTabCount() == 1) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001600 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 } else {
1602 tabPicker(true, mTabControl.getCurrentIndex(), false);
1603 }
1604 break;
1605
1606 case R.id.stop_reload_menu_id:
1607 if (mInLoad) {
1608 stopLoading();
1609 } else {
1610 getTopWindow().reload();
1611 }
1612 break;
1613
1614 case R.id.back_menu_id:
1615 getTopWindow().goBack();
1616 break;
1617
1618 case R.id.forward_menu_id:
1619 getTopWindow().goForward();
1620 break;
1621
1622 case R.id.close_menu_id:
1623 // Close the subwindow if it exists.
1624 if (mTabControl.getCurrentSubWindow() != null) {
1625 dismissSubWindow(mTabControl.getCurrentTab());
1626 break;
1627 }
1628 final int currentIndex = mTabControl.getCurrentIndex();
1629 final TabControl.Tab parent =
1630 mTabControl.getCurrentTab().getParentTab();
1631 int indexToShow = -1;
1632 if (parent != null) {
1633 indexToShow = mTabControl.getTabIndex(parent);
1634 } else {
1635 // Get the last tab in the list. If it is the current tab,
1636 // subtract 1 more.
1637 indexToShow = mTabControl.getTabCount() - 1;
1638 if (currentIndex == indexToShow) {
1639 indexToShow--;
1640 }
1641 }
1642 switchTabs(currentIndex, indexToShow, true);
1643 break;
1644
1645 case R.id.homepage_menu_id:
1646 TabControl.Tab current = mTabControl.getCurrentTab();
1647 if (current != null) {
1648 dismissSubWindow(current);
1649 current.getWebView().loadUrl(mSettings.getHomePage());
1650 }
1651 break;
1652
1653 case R.id.preferences_menu_id:
1654 Intent intent = new Intent(this,
1655 BrowserPreferencesPage.class);
1656 startActivityForResult(intent, PREFERENCES_PAGE);
1657 break;
1658
1659 case R.id.find_menu_id:
1660 if (null == mFindDialog) {
1661 mFindDialog = new FindDialog(this);
1662 }
1663 mFindDialog.setWebView(getTopWindow());
1664 mFindDialog.show();
1665 mMenuState = EMPTY_MENU;
1666 break;
1667
1668 case R.id.select_text_id:
1669 getTopWindow().emulateShiftHeld();
1670 break;
1671 case R.id.page_info_menu_id:
1672 showPageInfo(mTabControl.getCurrentTab(), false);
1673 break;
1674
1675 case R.id.classic_history_menu_id:
1676 bookmarksOrHistoryPicker(true);
1677 break;
1678
1679 case R.id.share_page_menu_id:
1680 Browser.sendString(this, getTopWindow().getUrl());
1681 break;
1682
1683 case R.id.dump_nav_menu_id:
1684 getTopWindow().debugDump();
1685 break;
1686
1687 case R.id.zoom_in_menu_id:
1688 getTopWindow().zoomIn();
1689 break;
1690
1691 case R.id.zoom_out_menu_id:
1692 getTopWindow().zoomOut();
1693 break;
1694
1695 case R.id.view_downloads_menu_id:
1696 viewDownloads(null);
1697 break;
1698
1699 // -- Tab menu
1700 case R.id.view_tab_menu_id:
1701 if (mTabListener != null && mTabOverview != null) {
1702 int pos = mTabOverview.getContextMenuPosition(item);
1703 mTabOverview.setCurrentIndex(pos);
1704 mTabListener.onClick(pos);
1705 }
1706 break;
1707
1708 case R.id.remove_tab_menu_id:
1709 if (mTabListener != null && mTabOverview != null) {
1710 int pos = mTabOverview.getContextMenuPosition(item);
1711 mTabListener.remove(pos);
1712 }
1713 break;
1714
1715 case R.id.new_tab_menu_id:
1716 // No need to check for mTabOverview here since we are not
1717 // dependent on it for a position.
1718 if (mTabListener != null) {
1719 // If the overview happens to be non-null, make the "New
1720 // Tab" cell visible.
1721 if (mTabOverview != null) {
1722 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1723 }
1724 mTabListener.onClick(ImageGrid.NEW_TAB);
1725 }
1726 break;
1727
1728 case R.id.bookmark_tab_menu_id:
1729 if (mTabListener != null && mTabOverview != null) {
1730 int pos = mTabOverview.getContextMenuPosition(item);
1731 TabControl.Tab t = mTabControl.getTab(pos);
1732 // Since we called populatePickerData for all of the
1733 // tabs, getTitle and getUrl will return appropriate
1734 // values.
1735 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1736 t.getUrl());
1737 }
1738 break;
1739
1740 case R.id.history_tab_menu_id:
1741 bookmarksOrHistoryPicker(true);
1742 break;
1743
1744 case R.id.bookmarks_tab_menu_id:
1745 bookmarksOrHistoryPicker(false);
1746 break;
1747
1748 case R.id.properties_tab_menu_id:
1749 if (mTabListener != null && mTabOverview != null) {
1750 int pos = mTabOverview.getContextMenuPosition(item);
1751 showPageInfo(mTabControl.getTab(pos), false);
1752 }
1753 break;
1754
1755 case R.id.window_one_menu_id:
1756 case R.id.window_two_menu_id:
1757 case R.id.window_three_menu_id:
1758 case R.id.window_four_menu_id:
1759 case R.id.window_five_menu_id:
1760 case R.id.window_six_menu_id:
1761 case R.id.window_seven_menu_id:
1762 case R.id.window_eight_menu_id:
1763 {
1764 int menuid = item.getItemId();
1765 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1766 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1767 TabControl.Tab desiredTab = mTabControl.getTab(id);
1768 if (desiredTab != null &&
1769 desiredTab != mTabControl.getCurrentTab()) {
1770 switchTabs(mTabControl.getCurrentIndex(), id, false);
1771 }
1772 break;
1773 }
1774 }
1775 }
1776 break;
1777
1778 default:
1779 if (!super.onOptionsItemSelected(item)) {
1780 return false;
1781 }
1782 // Otherwise fall through.
1783 }
1784 mCanChord = false;
1785 return true;
1786 }
1787
1788 public void closeFind() {
1789 mMenuState = R.id.MAIN_MENU;
1790 }
1791
1792 @Override public boolean onPrepareOptionsMenu(Menu menu)
1793 {
1794 // This happens when the user begins to hold down the menu key, so
1795 // allow them to chord to get a shortcut.
1796 mCanChord = true;
1797 // Note: setVisible will decide whether an item is visible; while
1798 // setEnabled() will decide whether an item is enabled, which also means
1799 // whether the matching shortcut key will function.
1800 super.onPrepareOptionsMenu(menu);
1801 switch (mMenuState) {
1802 case R.id.TAB_MENU:
1803 if (mCurrentMenuState != mMenuState) {
1804 menu.setGroupVisible(R.id.MAIN_MENU, false);
1805 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1806 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1807 menu.setGroupVisible(R.id.TAB_MENU, true);
1808 menu.setGroupEnabled(R.id.TAB_MENU, true);
1809 }
1810 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1811 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1812 tab.setVisible(newT);
1813 tab.setEnabled(newT);
1814 break;
1815 case EMPTY_MENU:
1816 if (mCurrentMenuState != mMenuState) {
1817 menu.setGroupVisible(R.id.MAIN_MENU, false);
1818 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1819 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1820 menu.setGroupVisible(R.id.TAB_MENU, false);
1821 menu.setGroupEnabled(R.id.TAB_MENU, false);
1822 }
1823 break;
1824 default:
1825 if (mCurrentMenuState != mMenuState) {
1826 menu.setGroupVisible(R.id.MAIN_MENU, true);
1827 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1828 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1829 menu.setGroupVisible(R.id.TAB_MENU, false);
1830 menu.setGroupEnabled(R.id.TAB_MENU, false);
1831 }
1832 final WebView w = getTopWindow();
1833 boolean canGoBack = false;
1834 boolean canGoForward = false;
1835 boolean isHome = false;
1836 if (w != null) {
1837 canGoBack = w.canGoBack();
1838 canGoForward = w.canGoForward();
1839 isHome = mSettings.getHomePage().equals(w.getUrl());
1840 }
1841 final MenuItem back = menu.findItem(R.id.back_menu_id);
1842 back.setEnabled(canGoBack);
1843
1844 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1845 home.setEnabled(!isHome);
1846
1847 menu.findItem(R.id.forward_menu_id)
1848 .setEnabled(canGoForward);
1849
1850 // decide whether to show the share link option
1851 PackageManager pm = getPackageManager();
1852 Intent send = new Intent(Intent.ACTION_SEND);
1853 send.setType("text/plain");
1854 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1855 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1856
1857 // If there is only 1 window, the text will be "New window"
1858 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1859 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1860 getString(R.string.view_tabs_condensed) :
1861 getString(R.string.tab_picker_new_tab));
1862
1863 boolean isNavDump = mSettings.isNavDump();
1864 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1865 nav.setVisible(isNavDump);
1866 nav.setEnabled(isNavDump);
1867 break;
1868 }
1869 mCurrentMenuState = mMenuState;
1870 return true;
1871 }
1872
1873 @Override
1874 public void onCreateContextMenu(ContextMenu menu, View v,
1875 ContextMenuInfo menuInfo) {
1876 WebView webview = (WebView) v;
1877 WebView.HitTestResult result = webview.getHitTestResult();
1878 if (result == null) {
1879 return;
1880 }
1881
1882 int type = result.getType();
1883 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1884 Log.w(LOGTAG,
1885 "We should not show context menu when nothing is touched");
1886 return;
1887 }
1888 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1889 // let TextView handles context menu
1890 return;
1891 }
1892
1893 // Note, http://b/issue?id=1106666 is requesting that
1894 // an inflated menu can be used again. This is not available
1895 // yet, so inflate each time (yuk!)
1896 MenuInflater inflater = getMenuInflater();
1897 inflater.inflate(R.menu.browsercontext, menu);
1898
1899 // Show the correct menu group
1900 String extra = result.getExtra();
1901 menu.setGroupVisible(R.id.PHONE_MENU,
1902 type == WebView.HitTestResult.PHONE_TYPE);
1903 menu.setGroupVisible(R.id.EMAIL_MENU,
1904 type == WebView.HitTestResult.EMAIL_TYPE);
1905 menu.setGroupVisible(R.id.GEO_MENU,
1906 type == WebView.HitTestResult.GEO_TYPE);
1907 menu.setGroupVisible(R.id.IMAGE_MENU,
1908 type == WebView.HitTestResult.IMAGE_TYPE
1909 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1910 menu.setGroupVisible(R.id.ANCHOR_MENU,
1911 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1912 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1913
1914 // Setup custom handling depending on the type
1915 switch (type) {
1916 case WebView.HitTestResult.PHONE_TYPE:
1917 menu.setHeaderTitle(Uri.decode(extra));
1918 menu.findItem(R.id.dial_context_menu_id).setIntent(
1919 new Intent(Intent.ACTION_VIEW, Uri
1920 .parse(WebView.SCHEME_TEL + extra)));
1921 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1922 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1923 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1924 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1925 addIntent);
1926 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1927 new Copy(extra));
1928 break;
1929
1930 case WebView.HitTestResult.EMAIL_TYPE:
1931 menu.setHeaderTitle(extra);
1932 menu.findItem(R.id.email_context_menu_id).setIntent(
1933 new Intent(Intent.ACTION_VIEW, Uri
1934 .parse(WebView.SCHEME_MAILTO + extra)));
1935 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1936 new Copy(extra));
1937 break;
1938
1939 case WebView.HitTestResult.GEO_TYPE:
1940 menu.setHeaderTitle(extra);
1941 menu.findItem(R.id.map_context_menu_id).setIntent(
1942 new Intent(Intent.ACTION_VIEW, Uri
1943 .parse(WebView.SCHEME_GEO
1944 + URLEncoder.encode(extra))));
1945 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1946 new Copy(extra));
1947 break;
1948
1949 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1950 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1951 TextView titleView = (TextView) LayoutInflater.from(this)
1952 .inflate(android.R.layout.browser_link_context_header,
1953 null);
1954 titleView.setText(extra);
1955 menu.setHeaderView(titleView);
1956 // decide whether to show the open link in new tab option
1957 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1958 mTabControl.getTabCount() < TabControl.MAX_TABS);
1959 PackageManager pm = getPackageManager();
1960 Intent send = new Intent(Intent.ACTION_SEND);
1961 send.setType("text/plain");
1962 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1963 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1964 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1965 break;
1966 }
1967 // otherwise fall through to handle image part
1968 case WebView.HitTestResult.IMAGE_TYPE:
1969 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1970 menu.setHeaderTitle(extra);
1971 }
1972 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1973 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1974 menu.findItem(R.id.download_context_menu_id).
1975 setOnMenuItemClickListener(new Download(extra));
1976 break;
1977
1978 default:
1979 Log.w(LOGTAG, "We should not get here.");
1980 break;
1981 }
1982 }
1983
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 // Attach the given tab to the content view.
1985 private void attachTabToContentView(TabControl.Tab t) {
1986 final WebView main = t.getWebView();
1987 // Attach the main WebView.
1988 mContentView.addView(main, COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001989
1990 if (mShouldShowErrorConsole) {
1991 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1992 if (errorConsole.numberOfErrors() == 0) {
1993 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1994 } else {
1995 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1996 }
1997
1998 mErrorConsoleContainer.addView(errorConsole,
1999 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
2000 ViewGroup.LayoutParams.WRAP_CONTENT));
2001 }
2002
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 // Attach the sub window if necessary
2004 attachSubWindow(t);
2005 // Request focus on the top window.
2006 t.getTopWindow().requestFocus();
2007 }
2008
2009 // Attach a sub window to the main WebView of the given tab.
2010 private void attachSubWindow(TabControl.Tab t) {
2011 // If a sub window exists, attach it to the content view.
2012 final WebView subView = t.getSubWebView();
2013 if (subView != null) {
2014 final View container = t.getSubWebViewContainer();
2015 mContentView.addView(container, COVER_SCREEN_PARAMS);
2016 subView.requestFocus();
2017 }
2018 }
2019
2020 // Remove the given tab from the content view.
2021 private void removeTabFromContentView(TabControl.Tab t) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002022 // Remove the main WebView.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 mContentView.removeView(t.getWebView());
Ben Murdochbff2d602009-07-01 20:19:05 +01002024
2025 if (mTabControl.getCurrentErrorConsole(false) != null) {
2026 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
2027 }
2028
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 // Remove the sub window if it exists.
2030 if (t.getSubWebView() != null) {
2031 mContentView.removeView(t.getSubWebViewContainer());
2032 }
2033 }
2034
2035 // Remove the sub window if it exists. Also called by TabControl when the
2036 // user clicks the 'X' to dismiss a sub window.
2037 /* package */ void dismissSubWindow(TabControl.Tab t) {
2038 final WebView mainView = t.getWebView();
2039 if (t.getSubWebView() != null) {
2040 // Remove the container view and request focus on the main WebView.
2041 mContentView.removeView(t.getSubWebViewContainer());
2042 mainView.requestFocus();
2043 // Tell the TabControl to dismiss the subwindow. This will destroy
2044 // the WebView.
2045 mTabControl.dismissSubWindow(t);
2046 }
2047 }
2048
2049 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
2050 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002051 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 final Message msg) {
2053 // Set the current tab.
2054 mTabControl.setCurrentTab(tab);
2055 // Attach the WebView so it will layout.
2056 attachTabToContentView(tab);
2057 // Set the view to invisibile for now.
2058 tab.getWebView().setVisibility(View.INVISIBLE);
2059 // If there is a sub window, make it invisible too.
2060 if (tab.getSubWebView() != null) {
2061 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
2062 }
2063 // Create our fake animating view.
2064 final AnimatingView view = new AnimatingView(this, tab);
2065 // Attach it to the view system and make in invisible so it will
2066 // layout but not flash white on the screen.
2067 mContentView.addView(view, COVER_SCREEN_PARAMS);
2068 view.setVisibility(View.INVISIBLE);
2069 // Send the animate message.
2070 final HashMap map = new HashMap();
2071 map.put("view", view);
2072 // Load the url after the AnimatingView has captured the picture. This
2073 // prevents any bad layout or bad scale from being used during
2074 // animation.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002075 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 dismissSubWindow(tab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002077 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
2079 map.put("msg", msg);
2080 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2081 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
2082 // Increment the count to indicate that we are in an animation.
2083 mAnimationCount++;
2084 // Remove the listener so we don't get any more tab changes.
2085 mTabOverview.setListener(null);
2086 mTabListener = null;
2087 // Make the menu empty until the animation completes.
2088 mMenuState = EMPTY_MENU;
2089
2090 }
2091
2092 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04002093 private static final int TAB_ANIMATION_DURATION = 200;
2094 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095
2096 // Called by TabControl when a tab is requesting focus
2097 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002098 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002099 }
2100
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002101 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002102 // Disallow focus change during a tab animation.
2103 if (mAnimationCount > 0) {
2104 return;
2105 }
2106 int delay = 0;
2107 if (mTabOverview == null) {
2108 // Add a delay so the tab overview can be shown before the second
2109 // animation begins.
2110 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2111 tabPicker(false, mTabControl.getTabIndex(t), false);
2112 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002113 sendAnimateFromOverview(t, false, urlData, delay, null);
2114 }
2115
2116 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2117 // that accepts url as string.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002118 private TabControl.Tab openTabAndShow(String url, final Message msg,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002119 boolean closeOnExit, String appId) {
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002120 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 }
2122
2123 // This method does a ton of stuff. It will attempt to create a new tab
2124 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2125 // url isn't null, it will load the given url. If the tab overview is not
2126 // showing, it will animate to the tab overview, create a new tab and
2127 // animate away from it. After the animation completes, it will dispatch
2128 // the given Message. If the tab overview is already showing (i.e. this
2129 // method is called from TabListener.onClick(), the method will animate
2130 // away from the tab overview.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002131 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002132 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002133 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2134 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2135 if (newTab) {
2136 int delay = 0;
2137 // If the tab overview is up and there are animations, just load
2138 // the url.
2139 if (mTabOverview != null && mAnimationCount > 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002140 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002141 // We should not have a msg here since onCreateWindow
2142 // checks the animation count and every other caller passes
2143 // null.
2144 assert msg == null;
2145 // just dismiss the subwindow and load the given url.
2146 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002147 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 }
2149 } else {
2150 // show mTabOverview if it is not there.
2151 if (mTabOverview == null) {
2152 // We have to delay the animation from the tab picker by the
2153 // length of the tab animation. Add a delay so the tab
2154 // overview can be shown before the second animation begins.
2155 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2156 tabPicker(false, ImageGrid.NEW_TAB, false);
2157 }
2158 // Animate from the Tab overview after any animations have
2159 // finished.
Grace Klobac9181842009-04-14 08:53:22 -07002160 final TabControl.Tab tab = mTabControl.createNewTab(
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002161 closeOnExit, appId, urlData.mUrl);
Grace Klobaec7eb372009-06-16 13:45:56 -07002162 sendAnimateFromOverview(tab, true, urlData, delay, msg);
Grace Klobac9181842009-04-14 08:53:22 -07002163 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002165 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 // We should not have a msg here.
2167 assert msg == null;
2168 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002169 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 TAB_OVERVIEW_DELAY, null);
2171 } else {
2172 // Get rid of the subwindow if it exists
2173 dismissSubWindow(currentTab);
2174 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002175 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 }
2177 }
Grace Klobac9181842009-04-14 08:53:22 -07002178 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002179 }
2180
2181 private Animation createTabAnimation(final AnimatingView view,
2182 final View cell, boolean scaleDown) {
2183 final AnimationSet set = new AnimationSet(true);
2184 final float scaleX = (float) cell.getWidth() / view.getWidth();
2185 final float scaleY = (float) cell.getHeight() / view.getHeight();
2186 if (scaleDown) {
2187 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2188 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2189 cell.getTop()));
2190 } else {
2191 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2192 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2193 cell.getTop(), 0));
2194 }
2195 set.setDuration(TAB_ANIMATION_DURATION);
2196 set.setInterpolator(new DecelerateInterpolator());
2197 return set;
2198 }
2199
2200 // Animate to the tab overview. currentIndex tells us which position to
2201 // animate to and newIndex is the position that should be selected after
2202 // the animation completes.
2203 // If remove is true, after the animation stops, a confirmation dialog will
2204 // be displayed to the user.
2205 private void animateToTabOverview(final int newIndex, final boolean remove,
2206 final AnimatingView view) {
2207 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2208 int position = mTabControl.getTabIndex(view.mTab);
2209 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2210 position++;
2211 }
2212
2213 // Offset the tab position with the first visible position to get a
2214 // number between 0 and 3.
2215 position -= mTabOverview.getFirstVisiblePosition();
2216
2217 // Grab the view that we are going to animate to.
2218 final View v = mTabOverview.getChildAt(position);
2219
2220 final Animation.AnimationListener l =
2221 new Animation.AnimationListener() {
2222 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002223 if (mTabOverview != null) {
2224 mTabOverview.requestFocus();
2225 // Clear the listener so we don't trigger a tab
2226 // selection.
2227 mTabOverview.setListener(null);
2228 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229 }
2230 public void onAnimationRepeat(Animation a) {}
2231 public void onAnimationEnd(Animation a) {
2232 // We are no longer animating so decrement the count.
2233 mAnimationCount--;
2234 // Make the view GONE so that it will not draw between
2235 // now and when the Runnable is handled.
2236 view.setVisibility(View.GONE);
2237 // Post a runnable since we can't modify the view
2238 // hierarchy during this callback.
2239 mHandler.post(new Runnable() {
2240 public void run() {
2241 // Remove the AnimatingView.
2242 mContentView.removeView(view);
2243 if (mTabOverview != null) {
2244 // Make newIndex visible.
2245 mTabOverview.setCurrentIndex(newIndex);
2246 // Restore the listener.
2247 mTabOverview.setListener(mTabListener);
2248 // Change the menu to TAB_MENU if the
2249 // ImageGrid is interactive.
2250 if (mTabOverview.isLive()) {
2251 mMenuState = R.id.TAB_MENU;
2252 mTabOverview.requestFocus();
2253 }
2254 }
2255 // If a remove was requested, remove the tab.
2256 if (remove) {
2257 // During a remove, the current tab has
2258 // already changed. Remember the current one
2259 // here.
2260 final TabControl.Tab currentTab =
2261 mTabControl.getCurrentTab();
2262 // Remove the tab at newIndex from
2263 // TabControl and the tab overview.
2264 final TabControl.Tab tab =
2265 mTabControl.getTab(newIndex);
2266 mTabControl.removeTab(tab);
2267 // Restore the current tab.
2268 if (currentTab != tab) {
2269 mTabControl.setCurrentTab(currentTab);
2270 }
2271 if (mTabOverview != null) {
2272 mTabOverview.remove(newIndex);
2273 // Make the current tab visible.
2274 mTabOverview.setCurrentIndex(
2275 mTabControl.getCurrentIndex());
2276 }
2277 }
2278 }
2279 });
2280 }
2281 };
2282
2283 // Do an animation if there is a view to animate to.
2284 if (v != null) {
2285 // Create our animation
2286 final Animation anim = createTabAnimation(view, v, true);
2287 anim.setAnimationListener(l);
2288 // Start animating
2289 view.startAnimation(anim);
2290 } else {
2291 // If something goes wrong and we didn't find a view to animate to,
2292 // just do everything here.
2293 l.onAnimationStart(null);
2294 l.onAnimationEnd(null);
2295 }
2296 }
2297
2298 // Animate from the tab picker. The index supplied is the index to animate
2299 // from.
2300 private void animateFromTabOverview(final AnimatingView view,
2301 final boolean newTab, final Message msg) {
2302 // firstVisible is the first visible tab on the screen. This helps
2303 // to know which corner of the screen the selected tab is.
2304 int firstVisible = mTabOverview.getFirstVisiblePosition();
2305 // tabPosition is the 0-based index of of the tab being opened
2306 int tabPosition = mTabControl.getTabIndex(view.mTab);
2307 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2308 // Add one to make room for the "New Tab" cell.
2309 tabPosition++;
2310 }
2311 // If this is a new tab, animate from the "New Tab" cell.
2312 if (newTab) {
2313 tabPosition = 0;
2314 }
2315 // Location corresponds to the four corners of the screen.
2316 // A new tab or 0 is upper left, 0 for an old tab is upper
2317 // right, 1 is lower left, and 2 is lower right
2318 int location = tabPosition - firstVisible;
2319
2320 // Find the view at this location.
2321 final View v = mTabOverview.getChildAt(location);
2322
2323 // Wait until the animation completes to replace the AnimatingView.
2324 final Animation.AnimationListener l =
2325 new Animation.AnimationListener() {
2326 public void onAnimationStart(Animation a) {}
2327 public void onAnimationRepeat(Animation a) {}
2328 public void onAnimationEnd(Animation a) {
2329 mHandler.post(new Runnable() {
2330 public void run() {
2331 mContentView.removeView(view);
2332 // Dismiss the tab overview. If the cell at the
2333 // given location is null, set the fade
2334 // parameter to true.
2335 dismissTabOverview(v == null);
2336 TabControl.Tab t =
2337 mTabControl.getCurrentTab();
2338 mMenuState = R.id.MAIN_MENU;
2339 // Resume regular updates.
2340 t.getWebView().resumeTimers();
2341 // Dispatch the message after the animation
2342 // completes.
2343 if (msg != null) {
2344 msg.sendToTarget();
2345 }
2346 // The animation is done and the tab overview is
2347 // gone so allow key events and other animations
2348 // to begin.
2349 mAnimationCount--;
2350 // Reset all the title bar info.
2351 resetTitle();
2352 }
2353 });
2354 }
2355 };
2356
2357 if (v != null) {
2358 final Animation anim = createTabAnimation(view, v, false);
2359 // Set the listener and start animating
2360 anim.setAnimationListener(l);
2361 view.startAnimation(anim);
2362 // Make the view VISIBLE during the animation.
2363 view.setVisibility(View.VISIBLE);
2364 } else {
2365 // Go ahead and do all the cleanup.
2366 l.onAnimationEnd(null);
2367 }
2368 }
2369
2370 // Dismiss the tab overview applying a fade if needed.
2371 private void dismissTabOverview(final boolean fade) {
2372 if (fade) {
2373 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2374 anim.setDuration(500);
2375 anim.startNow();
2376 mTabOverview.startAnimation(anim);
2377 }
2378 // Just in case there was a problem with animating away from the tab
2379 // overview
2380 WebView current = mTabControl.getCurrentWebView();
2381 if (current != null) {
2382 current.setVisibility(View.VISIBLE);
2383 } else {
2384 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2385 }
2386 // Make the sub window container visible.
2387 if (mTabControl.getCurrentSubWindow() != null) {
2388 mTabControl.getCurrentTab().getSubWebViewContainer()
2389 .setVisibility(View.VISIBLE);
2390 }
2391 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002392 // Clear all the data for tab picker so next time it will be
2393 // recreated.
2394 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002395 mTabOverview.clear();
2396 mTabOverview = null;
2397 mTabListener = null;
2398 }
2399
Grace Klobac9181842009-04-14 08:53:22 -07002400 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002401 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002402 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002403 if (t != null) {
2404 t.getWebView().loadUrl(url);
2405 }
Grace Klobac9181842009-04-14 08:53:22 -07002406 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 } else {
Grace Klobac9181842009-04-14 08:53:22 -07002408 return openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 }
2410 }
2411
2412 private class Copy implements OnMenuItemClickListener {
2413 private CharSequence mText;
2414
2415 public boolean onMenuItemClick(MenuItem item) {
2416 copy(mText);
2417 return true;
2418 }
2419
2420 public Copy(CharSequence toCopy) {
2421 mText = toCopy;
2422 }
2423 }
2424
2425 private class Download implements OnMenuItemClickListener {
2426 private String mText;
2427
2428 public boolean onMenuItemClick(MenuItem item) {
2429 onDownloadStartNoStream(mText, null, null, null, -1);
2430 return true;
2431 }
2432
2433 public Download(String toDownload) {
2434 mText = toDownload;
2435 }
2436 }
2437
2438 private void copy(CharSequence text) {
2439 try {
2440 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2441 if (clip != null) {
2442 clip.setClipboardText(text);
2443 }
2444 } catch (android.os.RemoteException e) {
2445 Log.e(LOGTAG, "Copy failed", e);
2446 }
2447 }
2448
2449 /**
2450 * Resets the browser title-view to whatever it must be (for example, if we
2451 * load a page from history).
2452 */
2453 private void resetTitle() {
2454 resetLockIcon();
2455 resetTitleIconAndProgress();
2456 }
2457
2458 /**
2459 * Resets the browser title-view to whatever it must be
2460 * (for example, if we had a loading error)
2461 * When we have a new page, we call resetTitle, when we
2462 * have to reset the titlebar to whatever it used to be
2463 * (for example, if the user chose to stop loading), we
2464 * call resetTitleAndRevertLockIcon.
2465 */
2466 /* package */ void resetTitleAndRevertLockIcon() {
2467 revertLockIcon();
2468 resetTitleIconAndProgress();
2469 }
2470
2471 /**
2472 * Reset the title, favicon, and progress.
2473 */
2474 private void resetTitleIconAndProgress() {
2475 WebView current = mTabControl.getCurrentWebView();
2476 if (current == null) {
2477 return;
2478 }
2479 resetTitleAndIcon(current);
2480 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002481 mWebChromeClient.onProgressChanged(current, progress);
2482 }
2483
2484 // Reset the title and the icon based on the given item.
2485 private void resetTitleAndIcon(WebView view) {
2486 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2487 if (item != null) {
2488 setUrlTitle(item.getUrl(), item.getTitle());
2489 setFavicon(item.getFavicon());
2490 } else {
2491 setUrlTitle(null, null);
2492 setFavicon(null);
2493 }
2494 }
2495
2496 /**
2497 * Sets a title composed of the URL and the title string.
2498 * @param url The URL of the site being loaded.
2499 * @param title The title of the site being loaded.
2500 */
2501 private void setUrlTitle(String url, String title) {
2502 mUrl = url;
2503 mTitle = title;
2504
2505 // While the tab overview is animating or being shown, block changes
2506 // to the title.
2507 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04002508 if (CUSTOM_BROWSER_BAR) {
2509 mTitleBar.setTitleAndUrl(title, url);
2510 } else {
2511 setTitle(buildUrlTitle(url, title));
2512 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002513 }
2514 }
2515
2516 /**
2517 * Builds and returns the page title, which is some
2518 * combination of the page URL and title.
2519 * @param url The URL of the site being loaded.
2520 * @param title The title of the site being loaded.
2521 * @return The page title.
2522 */
2523 private String buildUrlTitle(String url, String title) {
2524 String urlTitle = "";
2525
2526 if (url != null) {
2527 String titleUrl = buildTitleUrl(url);
2528
2529 if (title != null && 0 < title.length()) {
2530 if (titleUrl != null && 0 < titleUrl.length()) {
2531 urlTitle = titleUrl + ": " + title;
2532 } else {
2533 urlTitle = title;
2534 }
2535 } else {
2536 if (titleUrl != null) {
2537 urlTitle = titleUrl;
2538 }
2539 }
2540 }
2541
2542 return urlTitle;
2543 }
2544
2545 /**
2546 * @param url The URL to build a title version of the URL from.
2547 * @return The title version of the URL or null if fails.
2548 * The title version of the URL can be either the URL hostname,
2549 * or the hostname with an "https://" prefix (for secure URLs),
2550 * or an empty string if, for example, the URL in question is a
2551 * file:// URL with no hostname.
2552 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002553 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 String titleUrl = null;
2555
2556 if (url != null) {
2557 try {
2558 // parse the url string
2559 URL urlObj = new URL(url);
2560 if (urlObj != null) {
2561 titleUrl = "";
2562
2563 String protocol = urlObj.getProtocol();
2564 String host = urlObj.getHost();
2565
2566 if (host != null && 0 < host.length()) {
2567 titleUrl = host;
2568 if (protocol != null) {
2569 // if a secure site, add an "https://" prefix!
2570 if (protocol.equalsIgnoreCase("https")) {
2571 titleUrl = protocol + "://" + host;
2572 }
2573 }
2574 }
2575 }
2576 } catch (MalformedURLException e) {}
2577 }
2578
2579 return titleUrl;
2580 }
2581
2582 // Set the favicon in the title bar.
2583 private void setFavicon(Bitmap icon) {
2584 // While the tab overview is animating or being shown, block changes to
2585 // the favicon.
2586 if (mAnimationCount > 0 || mTabOverview != null) {
2587 return;
2588 }
Leon Scroggins81db3662009-06-04 17:45:11 -04002589 if (CUSTOM_BROWSER_BAR) {
2590 Drawable[] array = new Drawable[3];
2591 array[0] = new PaintDrawable(Color.BLACK);
2592 PaintDrawable p = new PaintDrawable(Color.WHITE);
2593 array[1] = p;
2594 if (icon == null) {
2595 array[2] = mGenericFavicon;
2596 } else {
2597 array[2] = new BitmapDrawable(icon);
2598 }
2599 LayerDrawable d = new LayerDrawable(array);
2600 d.setLayerInset(1, 1, 1, 1, 1);
2601 d.setLayerInset(2, 2, 2, 2, 2);
2602 mTitleBar.setFavicon(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04002604 Drawable[] array = new Drawable[2];
2605 PaintDrawable p = new PaintDrawable(Color.WHITE);
2606 p.setCornerRadius(3f);
2607 array[0] = p;
2608 if (icon == null) {
2609 array[1] = mGenericFavicon;
2610 } else {
2611 array[1] = new BitmapDrawable(icon);
2612 }
2613 LayerDrawable d = new LayerDrawable(array);
2614 d.setLayerInset(1, 2, 2, 2, 2);
2615 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002616 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 }
2618
2619 /**
2620 * Saves the current lock-icon state before resetting
2621 * the lock icon. If we have an error, we may need to
2622 * roll back to the previous state.
2623 */
2624 private void saveLockIcon() {
2625 mPrevLockType = mLockIconType;
2626 }
2627
2628 /**
2629 * Reverts the lock-icon state to the last saved state,
2630 * for example, if we had an error, and need to cancel
2631 * the load.
2632 */
2633 private void revertLockIcon() {
2634 mLockIconType = mPrevLockType;
2635
Dave Bort31a6d1c2009-04-13 15:56:49 -07002636 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002637 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2638 " revert lock icon to " + mLockIconType);
2639 }
2640
2641 updateLockIconImage(mLockIconType);
2642 }
2643
2644 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2645 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2646 // Animate to the tab picker, remove the current tab, then
2647 // animate away from the tab picker to the parent WebView.
2648 tabPicker(false, indexFrom, remove);
2649 // Change to the parent tab
2650 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2651 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002652 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002653 } else {
2654 // Increment this here so that no other animations can happen in
2655 // between the end of the tab picker transition and the beginning
2656 // of openTabAndShow. This has a matching decrement in the handler
2657 // of OPEN_TAB_AND_SHOW.
2658 mAnimationCount++;
2659 // Send a message to open a new tab.
2660 mHandler.sendMessageDelayed(
2661 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2662 mSettings.getHomePage()), delay);
2663 }
2664 }
2665
2666 private void goBackOnePageOrQuit() {
2667 TabControl.Tab current = mTabControl.getCurrentTab();
2668 if (current == null) {
2669 /*
2670 * Instead of finishing the activity, simply push this to the back
2671 * of the stack and let ActivityManager to choose the foreground
2672 * activity. As BrowserActivity is singleTask, it will be always the
2673 * root of the task. So we can use either true or false for
2674 * moveTaskToBack().
2675 */
2676 moveTaskToBack(true);
2677 }
2678 WebView w = current.getWebView();
2679 if (w.canGoBack()) {
2680 w.goBack();
2681 } else {
2682 // Check to see if we are closing a window that was created by
2683 // another window. If so, we switch back to that window.
2684 TabControl.Tab parent = current.getParentTab();
2685 if (parent != null) {
2686 switchTabs(mTabControl.getCurrentIndex(),
2687 mTabControl.getTabIndex(parent), true);
2688 } else {
2689 if (current.closeOnExit()) {
2690 if (mTabControl.getTabCount() == 1) {
2691 finish();
2692 return;
2693 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002694 // call pauseWebViewTimers() now, we won't be able to call
2695 // it in onPause() as the WebView won't be valid.
2696 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697 removeTabFromContentView(current);
2698 mTabControl.removeTab(current);
2699 }
2700 /*
2701 * Instead of finishing the activity, simply push this to the back
2702 * of the stack and let ActivityManager to choose the foreground
2703 * activity. As BrowserActivity is singleTask, it will be always the
2704 * root of the task. So we can use either true or false for
2705 * moveTaskToBack().
2706 */
2707 moveTaskToBack(true);
2708 }
2709 }
2710 }
2711
2712 public KeyTracker.State onKeyTracker(int keyCode,
2713 KeyEvent event,
2714 KeyTracker.Stage stage,
2715 int duration) {
2716 // if onKeyTracker() is called after activity onStop()
2717 // because of accumulated key events,
2718 // we should ignore it as browser is not active any more.
2719 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002720 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 return KeyTracker.State.NOT_TRACKING;
2722
2723 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002724 // Check if a custom view is currently showing and, if it is, hide it.
2725 if (mCustomView != null) {
2726 mWebChromeClient.onHideCustomView();
2727 return KeyTracker.State.DONE_TRACKING;
2728 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002729 // During animations, block the back key so that other animations
2730 // are not triggered and so that we don't end up destroying all the
2731 // WebViews before finishing the animation.
2732 if (mAnimationCount > 0) {
2733 return KeyTracker.State.DONE_TRACKING;
2734 }
2735 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2736 bookmarksOrHistoryPicker(true);
2737 return KeyTracker.State.DONE_TRACKING;
2738 } else if (stage == KeyTracker.Stage.UP) {
2739 // FIXME: Currently, we do not have a notion of the
2740 // history picker for the subwindow, but maybe we
2741 // should?
2742 WebView subwindow = mTabControl.getCurrentSubWindow();
2743 if (subwindow != null) {
2744 if (subwindow.canGoBack()) {
2745 subwindow.goBack();
2746 } else {
2747 dismissSubWindow(mTabControl.getCurrentTab());
2748 }
2749 } else {
2750 goBackOnePageOrQuit();
2751 }
2752 return KeyTracker.State.DONE_TRACKING;
2753 }
2754 return KeyTracker.State.KEEP_TRACKING;
2755 }
2756 return KeyTracker.State.NOT_TRACKING;
2757 }
2758
2759 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2760 if (keyCode == KeyEvent.KEYCODE_MENU) {
2761 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002762 } else if (mMenuIsDown) {
2763 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2764 // still down, we don't want to trigger the search. Pretend to
2765 // consume the key and do nothing.
2766 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 }
2768 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2769 if (!handled) {
2770 switch (keyCode) {
2771 case KeyEvent.KEYCODE_SPACE:
2772 if (event.isShiftPressed()) {
2773 getTopWindow().pageUp(false);
2774 } else {
2775 getTopWindow().pageDown(false);
2776 }
2777 handled = true;
2778 break;
2779
2780 default:
2781 break;
2782 }
2783 }
2784 return handled || super.onKeyDown(keyCode, event);
2785 }
2786
2787 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2788 if (keyCode == KeyEvent.KEYCODE_MENU) {
2789 mMenuIsDown = false;
2790 }
2791 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2792 }
2793
2794 private void stopLoading() {
2795 resetTitleAndRevertLockIcon();
2796 WebView w = getTopWindow();
2797 w.stopLoading();
2798 mWebViewClient.onPageFinished(w, w.getUrl());
2799
2800 cancelStopToast();
2801 mStopToast = Toast
2802 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2803 mStopToast.show();
2804 }
2805
2806 private void cancelStopToast() {
2807 if (mStopToast != null) {
2808 mStopToast.cancel();
2809 mStopToast = null;
2810 }
2811 }
2812
2813 // called by a non-UI thread to post the message
2814 public void postMessage(int what, int arg1, int arg2, Object obj) {
2815 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2816 }
2817
2818 // public message ids
2819 public final static int LOAD_URL = 1001;
2820 public final static int STOP_LOAD = 1002;
2821
2822 // Message Ids
2823 private static final int FOCUS_NODE_HREF = 102;
2824 private static final int CANCEL_CREDS_REQUEST = 103;
2825 private static final int ANIMATE_FROM_OVERVIEW = 104;
2826 private static final int ANIMATE_TO_OVERVIEW = 105;
2827 private static final int OPEN_TAB_AND_SHOW = 106;
2828 private static final int CHECK_MEMORY = 107;
2829 private static final int RELEASE_WAKELOCK = 108;
2830
2831 // Private handler for handling javascript and saving passwords
2832 private Handler mHandler = new Handler() {
2833
2834 public void handleMessage(Message msg) {
2835 switch (msg.what) {
2836 case ANIMATE_FROM_OVERVIEW:
2837 final HashMap map = (HashMap) msg.obj;
2838 animateFromTabOverview((AnimatingView) map.get("view"),
2839 msg.arg1 == 1, (Message) map.get("msg"));
2840 break;
2841
2842 case ANIMATE_TO_OVERVIEW:
2843 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2844 (AnimatingView) msg.obj);
2845 break;
2846
2847 case OPEN_TAB_AND_SHOW:
2848 // Decrement mAnimationCount before openTabAndShow because
2849 // the method relies on the value being 0 to start the next
2850 // animation.
2851 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002852 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853 break;
2854
2855 case FOCUS_NODE_HREF:
2856 String url = (String) msg.getData().get("url");
2857 if (url == null || url.length() == 0) {
2858 break;
2859 }
2860 HashMap focusNodeMap = (HashMap) msg.obj;
2861 WebView view = (WebView) focusNodeMap.get("webview");
2862 // Only apply the action if the top window did not change.
2863 if (getTopWindow() != view) {
2864 break;
2865 }
2866 switch (msg.arg1) {
2867 case R.id.open_context_menu_id:
2868 case R.id.view_image_context_menu_id:
2869 loadURL(getTopWindow(), url);
2870 break;
2871 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002872 final TabControl.Tab parent = mTabControl
2873 .getCurrentTab();
2874 final TabControl.Tab newTab = openTab(url);
2875 if (newTab != parent) {
2876 parent.addChildTab(newTab);
2877 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002878 break;
2879 case R.id.bookmark_context_menu_id:
2880 Intent intent = new Intent(BrowserActivity.this,
2881 AddBookmarkPage.class);
2882 intent.putExtra("url", url);
2883 startActivity(intent);
2884 break;
2885 case R.id.share_link_context_menu_id:
2886 Browser.sendString(BrowserActivity.this, url);
2887 break;
2888 case R.id.copy_link_context_menu_id:
2889 copy(url);
2890 break;
2891 case R.id.save_link_context_menu_id:
2892 case R.id.download_context_menu_id:
2893 onDownloadStartNoStream(url, null, null, null, -1);
2894 break;
2895 }
2896 break;
2897
2898 case LOAD_URL:
2899 loadURL(getTopWindow(), (String) msg.obj);
2900 break;
2901
2902 case STOP_LOAD:
2903 stopLoading();
2904 break;
2905
2906 case CANCEL_CREDS_REQUEST:
2907 resumeAfterCredentials();
2908 break;
2909
2910 case CHECK_MEMORY:
2911 // reschedule to check memory condition
2912 mHandler.removeMessages(CHECK_MEMORY);
2913 mHandler.sendMessageDelayed(mHandler.obtainMessage
2914 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2915 checkMemory();
2916 break;
2917
2918 case RELEASE_WAKELOCK:
2919 if (mWakeLock.isHeld()) {
2920 mWakeLock.release();
2921 }
2922 break;
2923 }
2924 }
2925 };
2926
Leon Scroggins89c6d362009-07-15 16:54:37 -04002927 private void updateScreenshot(WebView view) {
2928 // If this is a bookmarked site, add a screenshot to the database.
2929 // FIXME: When should we update? Every time?
2930 // FIXME: Would like to make sure there is actually something to
2931 // draw, but the API for that (WebViewCore.pictureReady()) is not
2932 // currently accessible here.
2933 String original = view.getOriginalUrl();
2934 if (original != null) {
2935 // copied from BrowserBookmarksAdapter
2936 int query = original.indexOf('?');
2937 String noQuery = original;
2938 if (query != -1) {
2939 noQuery = original.substring(0, query);
2940 }
2941 String URL = noQuery + '?';
2942 String[] selArgs = new String[] { noQuery, URL };
2943 final String where
2944 = "(url == ? OR url GLOB ? || '*') AND bookmark == 1";
2945 final String[] projection
2946 = new String[] { Browser.BookmarkColumns._ID };
2947 ContentResolver cr = getContentResolver();
2948 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection,
2949 where, selArgs, null);
2950 boolean succeed = c.moveToFirst();
2951 ContentValues values = null;
2952 while (succeed) {
2953 if (values == null) {
2954 final ByteArrayOutputStream os
2955 = new ByteArrayOutputStream();
2956 Picture thumbnail = view.capturePicture();
2957 // Keep width and height in sync with BrowserBookmarksPage
2958 // and bookmark_thumb
2959 Bitmap bm = Bitmap.createBitmap(100, 80,
2960 Bitmap.Config.ARGB_4444);
2961 Canvas canvas = new Canvas(bm);
2962 // May need to tweak these values to determine what is the
2963 // best scale factor
2964 canvas.scale(.5f, .5f);
2965 thumbnail.draw(canvas);
2966 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2967 values = new ContentValues();
2968 values.put(Browser.BookmarkColumns.THUMBNAIL,
2969 os.toByteArray());
2970 }
2971 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2972 c.getInt(0)), values, null, null);
2973 succeed = c.moveToNext();
2974 }
2975 c.close();
2976 }
2977 }
2978
The Android Open Source Project0c908882009-03-03 19:32:16 -08002979 // -------------------------------------------------------------------------
2980 // WebViewClient implementation.
2981 //-------------------------------------------------------------------------
2982
2983 // Use in overrideUrlLoading
2984 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2985 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2986 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2987 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2988
2989 /* package */ WebViewClient getWebViewClient() {
2990 return mWebViewClient;
2991 }
2992
2993 private void updateIcon(String url, Bitmap icon) {
2994 if (icon != null) {
2995 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2996 url, icon);
2997 }
2998 setFavicon(icon);
2999 }
3000
3001 private final WebViewClient mWebViewClient = new WebViewClient() {
3002 @Override
3003 public void onPageStarted(WebView view, String url, Bitmap favicon) {
3004 resetLockIcon(url);
3005 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01003006
3007 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
3008 if (errorConsole != null) {
3009 errorConsole.clearErrorMessages();
3010 if (mShouldShowErrorConsole) {
3011 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3012 }
3013 }
3014
The Android Open Source Project0c908882009-03-03 19:32:16 -08003015 // Call updateIcon instead of setFavicon so the bookmark
3016 // database can be updated.
3017 updateIcon(url, favicon);
3018
3019 if (mSettings.isTracing() == true) {
3020 // FIXME: we should save the trace file somewhere other than data.
3021 // I can't use "/tmp" as it competes for system memory.
3022 File file = getDir("browserTrace", 0);
3023 String baseDir = file.getPath();
3024 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
3025 String host;
3026 try {
3027 WebAddress uri = new WebAddress(url);
3028 host = uri.mHost;
3029 } catch (android.net.ParseException ex) {
3030 host = "unknown_host";
3031 }
3032 host = host.replace('.', '_');
3033 baseDir = baseDir + host;
3034 file = new File(baseDir+".data");
3035 if (file.exists() == true) {
3036 file.delete();
3037 }
3038 file = new File(baseDir+".key");
3039 if (file.exists() == true) {
3040 file.delete();
3041 }
3042 mInTrace = true;
3043 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
3044 }
3045
3046 // Performance probe
3047 if (false) {
3048 mStart = SystemClock.uptimeMillis();
3049 mProcessStart = Process.getElapsedCpuTime();
3050 long[] sysCpu = new long[7];
3051 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3052 sysCpu, null)) {
3053 mUserStart = sysCpu[0] + sysCpu[1];
3054 mSystemStart = sysCpu[2];
3055 mIdleStart = sysCpu[3];
3056 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
3057 }
3058 mUiStart = SystemClock.currentThreadTimeMillis();
3059 }
3060
3061 if (!mPageStarted) {
3062 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003063 // if onResume() has been called, resumeWebViewTimers() does
3064 // nothing.
3065 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 }
3067
3068 // reset sync timer to avoid sync starts during loading a page
3069 CookieSyncManager.getInstance().resetSync();
3070
3071 mInLoad = true;
3072 updateInLoadMenuItems();
3073 if (!mIsNetworkUp) {
3074 if ( mAlertDialog == null) {
3075 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
3076 .setTitle(R.string.loadSuspendedTitle)
3077 .setMessage(R.string.loadSuspended)
3078 .setPositiveButton(R.string.ok, null)
3079 .show();
3080 }
3081 if (view != null) {
3082 view.setNetworkAvailable(false);
3083 }
3084 }
3085
3086 // schedule to check memory condition
3087 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
3088 CHECK_MEMORY_INTERVAL);
3089 }
3090
3091 @Override
3092 public void onPageFinished(WebView view, String url) {
3093 // Reset the title and icon in case we stopped a provisional
3094 // load.
3095 resetTitleAndIcon(view);
3096
3097 // Update the lock icon image only once we are done loading
3098 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04003099 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04003100
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003102 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003103 long[] sysCpu = new long[7];
3104 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3105 sysCpu, null)) {
3106 String uiInfo = "UI thread used "
3107 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3108 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003109 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003110 Log.d(LOGTAG, uiInfo);
3111 }
3112 //The string that gets written to the log
3113 String performanceString = "It took total "
3114 + (SystemClock.uptimeMillis() - mStart)
3115 + " ms clock time to load the page."
3116 + "\nbrowser process used "
3117 + (Process.getElapsedCpuTime() - mProcessStart)
3118 + " ms, user processes used "
3119 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3120 + " ms, kernel used "
3121 + (sysCpu[2] - mSystemStart) * 10
3122 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3123 + " ms and irq took "
3124 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3125 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003126 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3128 }
3129 if (url != null) {
3130 // strip the url to maintain consistency
3131 String newUrl = new String(url);
3132 if (newUrl.startsWith("http://www.")) {
3133 newUrl = newUrl.substring(11);
3134 } else if (newUrl.startsWith("http://")) {
3135 newUrl = newUrl.substring(7);
3136 } else if (newUrl.startsWith("https://www.")) {
3137 newUrl = newUrl.substring(12);
3138 } else if (newUrl.startsWith("https://")) {
3139 newUrl = newUrl.substring(8);
3140 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003141 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 Log.d(LOGTAG, newUrl + " loaded");
3143 }
3144 /*
3145 if (sWhiteList.contains(newUrl)) {
3146 // The string that gets pushed to the statistcs
3147 // service
3148 performanceString = performanceString
3149 + "\nWebpage: "
3150 + newUrl
3151 + "\nCarrier: "
3152 + android.os.SystemProperties
3153 .get("gsm.sim.operator.alpha");
3154 if (mWebView != null
3155 && mWebView.getContext() != null
3156 && mWebView.getContext().getSystemService(
3157 Context.CONNECTIVITY_SERVICE) != null) {
3158 ConnectivityManager cManager =
3159 (ConnectivityManager) mWebView
3160 .getContext().getSystemService(
3161 Context.CONNECTIVITY_SERVICE);
3162 NetworkInfo nInfo = cManager
3163 .getActiveNetworkInfo();
3164 if (nInfo != null) {
3165 performanceString = performanceString
3166 + "\nNetwork Type: "
3167 + nInfo.getType().toString();
3168 }
3169 }
3170 Checkin.logEvent(mResolver,
3171 Checkin.Events.Tag.WEBPAGE_LOAD,
3172 performanceString);
3173 Log.w(LOGTAG, "pushed to the statistics service");
3174 }
3175 */
3176 }
3177 }
3178 }
3179
3180 if (mInTrace) {
3181 mInTrace = false;
3182 Debug.stopMethodTracing();
3183 }
3184
3185 if (mPageStarted) {
3186 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003187 // pauseWebViewTimers() will do nothing and return false if
3188 // onPause() is not called yet.
3189 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003190 if (mWakeLock.isHeld()) {
3191 mHandler.removeMessages(RELEASE_WAKELOCK);
3192 mWakeLock.release();
3193 }
3194 }
3195 }
3196
The Android Open Source Project0c908882009-03-03 19:32:16 -08003197 mHandler.removeMessages(CHECK_MEMORY);
3198 checkMemory();
3199 }
3200
3201 // return true if want to hijack the url to let another app to handle it
3202 @Override
3203 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3204 if (url.startsWith(SCHEME_WTAI)) {
3205 // wtai://wp/mc;number
3206 // number=string(phone-number)
3207 if (url.startsWith(SCHEME_WTAI_MC)) {
3208 Intent intent = new Intent(Intent.ACTION_VIEW,
3209 Uri.parse(WebView.SCHEME_TEL +
3210 url.substring(SCHEME_WTAI_MC.length())));
3211 startActivity(intent);
3212 return true;
3213 }
3214 // wtai://wp/sd;dtmf
3215 // dtmf=string(dialstring)
3216 if (url.startsWith(SCHEME_WTAI_SD)) {
3217 // TODO
3218 // only send when there is active voice connection
3219 return false;
3220 }
3221 // wtai://wp/ap;number;name
3222 // number=string(phone-number)
3223 // name=string
3224 if (url.startsWith(SCHEME_WTAI_AP)) {
3225 // TODO
3226 return false;
3227 }
3228 }
3229
Dianne Hackborn99189432009-06-17 18:06:18 -07003230 // The "about:" schemes are internal to the browser; don't
3231 // want these to be dispatched to other apps.
3232 if (url.startsWith("about:")) {
3233 return false;
3234 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003235
Dianne Hackborn99189432009-06-17 18:06:18 -07003236 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01003237
Dianne Hackborn99189432009-06-17 18:06:18 -07003238 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003240 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3241 } catch (URISyntaxException ex) {
3242 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 return false;
3244 }
3245
Grace Kloba5b078b52009-06-24 20:23:41 -07003246 // check whether the intent can be resolved. If not, we will see
3247 // whether we can download it from the Market.
3248 if (getPackageManager().resolveActivity(intent, 0) == null) {
3249 String packagename = intent.getPackage();
3250 if (packagename != null) {
3251 intent = new Intent(Intent.ACTION_VIEW, Uri
3252 .parse("market://search?q=pname:" + packagename));
3253 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3254 startActivity(intent);
3255 return true;
3256 } else {
3257 return false;
3258 }
3259 }
3260
Dianne Hackborn99189432009-06-17 18:06:18 -07003261 // sanitize the Intent, ensuring web pages can not bypass browser
3262 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003264 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 try {
3266 if (startActivityIfNeeded(intent, -1)) {
3267 return true;
3268 }
3269 } catch (ActivityNotFoundException ex) {
3270 // ignore the error. If no application can handle the URL,
3271 // eg about:blank, assume the browser can handle it.
3272 }
3273
3274 if (mMenuIsDown) {
3275 openTab(url);
3276 closeOptionsMenu();
3277 return true;
3278 }
3279
3280 return false;
3281 }
3282
3283 /**
3284 * Updates the lock icon. This method is called when we discover another
3285 * resource to be loaded for this page (for example, javascript). While
3286 * we update the icon type, we do not update the lock icon itself until
3287 * we are done loading, it is slightly more secure this way.
3288 */
3289 @Override
3290 public void onLoadResource(WebView view, String url) {
3291 if (url != null && url.length() > 0) {
3292 // It is only if the page claims to be secure
3293 // that we may have to update the lock:
3294 if (mLockIconType == LOCK_ICON_SECURE) {
3295 // If NOT a 'safe' url, change the lock to mixed content!
3296 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3297 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003298 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3300 " updated lock icon to " + mLockIconType + " due to " + url);
3301 }
3302 }
3303 }
3304 }
3305 }
3306
3307 /**
3308 * Show the dialog, asking the user if they would like to continue after
3309 * an excessive number of HTTP redirects.
3310 */
3311 @Override
3312 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3313 final Message continueMsg) {
3314 new AlertDialog.Builder(BrowserActivity.this)
3315 .setTitle(R.string.browserFrameRedirect)
3316 .setMessage(R.string.browserFrame307Post)
3317 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3318 public void onClick(DialogInterface dialog, int which) {
3319 continueMsg.sendToTarget();
3320 }})
3321 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3322 public void onClick(DialogInterface dialog, int which) {
3323 cancelMsg.sendToTarget();
3324 }})
3325 .setOnCancelListener(new OnCancelListener() {
3326 public void onCancel(DialogInterface dialog) {
3327 cancelMsg.sendToTarget();
3328 }})
3329 .show();
3330 }
3331
Patrick Scott37911c72009-03-24 18:02:58 -07003332 // Container class for the next error dialog that needs to be
3333 // displayed.
3334 class ErrorDialog {
3335 public final int mTitle;
3336 public final String mDescription;
3337 public final int mError;
3338 ErrorDialog(int title, String desc, int error) {
3339 mTitle = title;
3340 mDescription = desc;
3341 mError = error;
3342 }
3343 };
3344
3345 private void processNextError() {
3346 if (mQueuedErrors == null) {
3347 return;
3348 }
3349 // The first one is currently displayed so just remove it.
3350 mQueuedErrors.removeFirst();
3351 if (mQueuedErrors.size() == 0) {
3352 mQueuedErrors = null;
3353 return;
3354 }
3355 showError(mQueuedErrors.getFirst());
3356 }
3357
3358 private DialogInterface.OnDismissListener mDialogListener =
3359 new DialogInterface.OnDismissListener() {
3360 public void onDismiss(DialogInterface d) {
3361 processNextError();
3362 }
3363 };
3364 private LinkedList<ErrorDialog> mQueuedErrors;
3365
3366 private void queueError(int err, String desc) {
3367 if (mQueuedErrors == null) {
3368 mQueuedErrors = new LinkedList<ErrorDialog>();
3369 }
3370 for (ErrorDialog d : mQueuedErrors) {
3371 if (d.mError == err) {
3372 // Already saw a similar error, ignore the new one.
3373 return;
3374 }
3375 }
3376 ErrorDialog errDialog = new ErrorDialog(
3377 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3378 R.string.browserFrameFileErrorLabel :
3379 R.string.browserFrameNetworkErrorLabel,
3380 desc, err);
3381 mQueuedErrors.addLast(errDialog);
3382
3383 // Show the dialog now if the queue was empty.
3384 if (mQueuedErrors.size() == 1) {
3385 showError(errDialog);
3386 }
3387 }
3388
3389 private void showError(ErrorDialog errDialog) {
3390 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3391 .setTitle(errDialog.mTitle)
3392 .setMessage(errDialog.mDescription)
3393 .setPositiveButton(R.string.ok, null)
3394 .create();
3395 d.setOnDismissListener(mDialogListener);
3396 d.show();
3397 }
3398
The Android Open Source Project0c908882009-03-03 19:32:16 -08003399 /**
3400 * Show a dialog informing the user of the network error reported by
3401 * WebCore.
3402 */
3403 @Override
3404 public void onReceivedError(WebView view, int errorCode,
3405 String description, String failingUrl) {
3406 if (errorCode != EventHandler.ERROR_LOOKUP &&
3407 errorCode != EventHandler.ERROR_CONNECT &&
3408 errorCode != EventHandler.ERROR_BAD_URL &&
3409 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3410 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003411 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 }
Patrick Scott37911c72009-03-24 18:02:58 -07003413 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3414 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415
3416 // We need to reset the title after an error.
3417 resetTitleAndRevertLockIcon();
3418 }
3419
3420 /**
3421 * Check with the user if it is ok to resend POST data as the page they
3422 * are trying to navigate to is the result of a POST.
3423 */
3424 @Override
3425 public void onFormResubmission(WebView view, final Message dontResend,
3426 final Message resend) {
3427 new AlertDialog.Builder(BrowserActivity.this)
3428 .setTitle(R.string.browserFrameFormResubmitLabel)
3429 .setMessage(R.string.browserFrameFormResubmitMessage)
3430 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3431 public void onClick(DialogInterface dialog, int which) {
3432 resend.sendToTarget();
3433 }})
3434 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3435 public void onClick(DialogInterface dialog, int which) {
3436 dontResend.sendToTarget();
3437 }})
3438 .setOnCancelListener(new OnCancelListener() {
3439 public void onCancel(DialogInterface dialog) {
3440 dontResend.sendToTarget();
3441 }})
3442 .show();
3443 }
3444
3445 /**
3446 * Insert the url into the visited history database.
3447 * @param url The url to be inserted.
3448 * @param isReload True if this url is being reloaded.
3449 * FIXME: Not sure what to do when reloading the page.
3450 */
3451 @Override
3452 public void doUpdateVisitedHistory(WebView view, String url,
3453 boolean isReload) {
3454 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3455 return;
3456 }
3457 Browser.updateVisitedHistory(mResolver, url, true);
3458 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3459 }
3460
3461 /**
3462 * Displays SSL error(s) dialog to the user.
3463 */
3464 @Override
3465 public void onReceivedSslError(
3466 final WebView view, final SslErrorHandler handler, final SslError error) {
3467
3468 if (mSettings.showSecurityWarnings()) {
3469 final LayoutInflater factory =
3470 LayoutInflater.from(BrowserActivity.this);
3471 final View warningsView =
3472 factory.inflate(R.layout.ssl_warnings, null);
3473 final LinearLayout placeholder =
3474 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3475
3476 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3477 LinearLayout ll = (LinearLayout)factory
3478 .inflate(R.layout.ssl_warning, null);
3479 ((TextView)ll.findViewById(R.id.warning))
3480 .setText(R.string.ssl_untrusted);
3481 placeholder.addView(ll);
3482 }
3483
3484 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3485 LinearLayout ll = (LinearLayout)factory
3486 .inflate(R.layout.ssl_warning, null);
3487 ((TextView)ll.findViewById(R.id.warning))
3488 .setText(R.string.ssl_mismatch);
3489 placeholder.addView(ll);
3490 }
3491
3492 if (error.hasError(SslError.SSL_EXPIRED)) {
3493 LinearLayout ll = (LinearLayout)factory
3494 .inflate(R.layout.ssl_warning, null);
3495 ((TextView)ll.findViewById(R.id.warning))
3496 .setText(R.string.ssl_expired);
3497 placeholder.addView(ll);
3498 }
3499
3500 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3501 LinearLayout ll = (LinearLayout)factory
3502 .inflate(R.layout.ssl_warning, null);
3503 ((TextView)ll.findViewById(R.id.warning))
3504 .setText(R.string.ssl_not_yet_valid);
3505 placeholder.addView(ll);
3506 }
3507
3508 new AlertDialog.Builder(BrowserActivity.this)
3509 .setTitle(R.string.security_warning)
3510 .setIcon(android.R.drawable.ic_dialog_alert)
3511 .setView(warningsView)
3512 .setPositiveButton(R.string.ssl_continue,
3513 new DialogInterface.OnClickListener() {
3514 public void onClick(DialogInterface dialog, int whichButton) {
3515 handler.proceed();
3516 }
3517 })
3518 .setNeutralButton(R.string.view_certificate,
3519 new DialogInterface.OnClickListener() {
3520 public void onClick(DialogInterface dialog, int whichButton) {
3521 showSSLCertificateOnError(view, handler, error);
3522 }
3523 })
3524 .setNegativeButton(R.string.cancel,
3525 new DialogInterface.OnClickListener() {
3526 public void onClick(DialogInterface dialog, int whichButton) {
3527 handler.cancel();
3528 BrowserActivity.this.resetTitleAndRevertLockIcon();
3529 }
3530 })
3531 .setOnCancelListener(
3532 new DialogInterface.OnCancelListener() {
3533 public void onCancel(DialogInterface dialog) {
3534 handler.cancel();
3535 BrowserActivity.this.resetTitleAndRevertLockIcon();
3536 }
3537 })
3538 .show();
3539 } else {
3540 handler.proceed();
3541 }
3542 }
3543
3544 /**
3545 * Handles an HTTP authentication request.
3546 *
3547 * @param handler The authentication handler
3548 * @param host The host
3549 * @param realm The realm
3550 */
3551 @Override
3552 public void onReceivedHttpAuthRequest(WebView view,
3553 final HttpAuthHandler handler, final String host, final String realm) {
3554 String username = null;
3555 String password = null;
3556
3557 boolean reuseHttpAuthUsernamePassword =
3558 handler.useHttpAuthUsernamePassword();
3559
3560 if (reuseHttpAuthUsernamePassword &&
3561 (mTabControl.getCurrentWebView() != null)) {
3562 String[] credentials =
3563 mTabControl.getCurrentWebView()
3564 .getHttpAuthUsernamePassword(host, realm);
3565 if (credentials != null && credentials.length == 2) {
3566 username = credentials[0];
3567 password = credentials[1];
3568 }
3569 }
3570
3571 if (username != null && password != null) {
3572 handler.proceed(username, password);
3573 } else {
3574 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3575 }
3576 }
3577
3578 @Override
3579 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3580 if (mMenuIsDown) {
3581 // only check shortcut key when MENU is held
3582 return getWindow().isShortcutKey(event.getKeyCode(), event);
3583 } else {
3584 return false;
3585 }
3586 }
3587
3588 @Override
3589 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3590 if (view != mTabControl.getCurrentTopWebView()) {
3591 return;
3592 }
3593 if (event.isDown()) {
3594 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3595 } else {
3596 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3597 }
3598 }
3599 };
3600
3601 //--------------------------------------------------------------------------
3602 // WebChromeClient implementation
3603 //--------------------------------------------------------------------------
3604
3605 /* package */ WebChromeClient getWebChromeClient() {
3606 return mWebChromeClient;
3607 }
3608
3609 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3610 // Helper method to create a new tab or sub window.
3611 private void createWindow(final boolean dialog, final Message msg) {
3612 if (dialog) {
3613 mTabControl.createSubWindow();
3614 final TabControl.Tab t = mTabControl.getCurrentTab();
3615 attachSubWindow(t);
3616 WebView.WebViewTransport transport =
3617 (WebView.WebViewTransport) msg.obj;
3618 transport.setWebView(t.getSubWebView());
3619 msg.sendToTarget();
3620 } else {
3621 final TabControl.Tab parent = mTabControl.getCurrentTab();
3622 // openTabAndShow will dispatch the message after creating the
3623 // new WebView. This will prevent another request from coming
3624 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003625 final TabControl.Tab newTab =
3626 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003627 if (newTab != parent) {
3628 parent.addChildTab(newTab);
3629 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 WebView.WebViewTransport transport =
3631 (WebView.WebViewTransport) msg.obj;
3632 transport.setWebView(mTabControl.getCurrentWebView());
3633 }
3634 }
3635
3636 @Override
3637 public boolean onCreateWindow(WebView view, final boolean dialog,
3638 final boolean userGesture, final Message resultMsg) {
3639 // Ignore these requests during tab animations or if the tab
3640 // overview is showing.
3641 if (mAnimationCount > 0 || mTabOverview != null) {
3642 return false;
3643 }
3644 // Short-circuit if we can't create any more tabs or sub windows.
3645 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3646 new AlertDialog.Builder(BrowserActivity.this)
3647 .setTitle(R.string.too_many_subwindows_dialog_title)
3648 .setIcon(android.R.drawable.ic_dialog_alert)
3649 .setMessage(R.string.too_many_subwindows_dialog_message)
3650 .setPositiveButton(R.string.ok, null)
3651 .show();
3652 return false;
3653 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3654 new AlertDialog.Builder(BrowserActivity.this)
3655 .setTitle(R.string.too_many_windows_dialog_title)
3656 .setIcon(android.R.drawable.ic_dialog_alert)
3657 .setMessage(R.string.too_many_windows_dialog_message)
3658 .setPositiveButton(R.string.ok, null)
3659 .show();
3660 return false;
3661 }
3662
3663 // Short-circuit if this was a user gesture.
3664 if (userGesture) {
3665 // createWindow will call openTabAndShow for new Windows and
3666 // that will call tabPicker which will increment
3667 // mAnimationCount.
3668 createWindow(dialog, resultMsg);
3669 return true;
3670 }
3671
3672 // Allow the popup and create the appropriate window.
3673 final AlertDialog.OnClickListener allowListener =
3674 new AlertDialog.OnClickListener() {
3675 public void onClick(DialogInterface d,
3676 int which) {
3677 // Same comment as above for setting
3678 // mAnimationCount.
3679 createWindow(dialog, resultMsg);
3680 // Since we incremented mAnimationCount while the
3681 // dialog was up, we have to decrement it here.
3682 mAnimationCount--;
3683 }
3684 };
3685
3686 // Block the popup by returning a null WebView.
3687 final AlertDialog.OnClickListener blockListener =
3688 new AlertDialog.OnClickListener() {
3689 public void onClick(DialogInterface d, int which) {
3690 resultMsg.sendToTarget();
3691 // We are not going to trigger an animation so
3692 // unblock keys and animation requests.
3693 mAnimationCount--;
3694 }
3695 };
3696
3697 // Build a confirmation dialog to display to the user.
3698 final AlertDialog d =
3699 new AlertDialog.Builder(BrowserActivity.this)
3700 .setTitle(R.string.attention)
3701 .setIcon(android.R.drawable.ic_dialog_alert)
3702 .setMessage(R.string.popup_window_attempt)
3703 .setPositiveButton(R.string.allow, allowListener)
3704 .setNegativeButton(R.string.block, blockListener)
3705 .setCancelable(false)
3706 .create();
3707
3708 // Show the confirmation dialog.
3709 d.show();
3710 // We want to increment mAnimationCount here to prevent a
3711 // potential race condition. If the user allows a pop-up from a
3712 // site and that pop-up then triggers another pop-up, it is
3713 // possible to get the BACK key between here and when the dialog
3714 // appears.
3715 mAnimationCount++;
3716 return true;
3717 }
3718
3719 @Override
3720 public void onCloseWindow(WebView window) {
3721 final int currentIndex = mTabControl.getCurrentIndex();
3722 final TabControl.Tab parent =
3723 mTabControl.getCurrentTab().getParentTab();
3724 if (parent != null) {
3725 // JavaScript can only close popup window.
3726 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3727 }
3728 }
3729
3730 @Override
3731 public void onProgressChanged(WebView view, int newProgress) {
3732 // Block progress updates to the title bar while the tab overview
3733 // is animating or being displayed.
3734 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003735 if (CUSTOM_BROWSER_BAR) {
3736 mTitleBar.setProgress(newProgress);
3737 } else {
3738 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3739 newProgress * 100);
3740
3741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 }
3743
3744 if (newProgress == 100) {
3745 // onProgressChanged() is called for sub-frame too while
3746 // onPageFinished() is only called for the main frame. sync
3747 // cookie and cache promptly here.
3748 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003749 if (mInLoad) {
3750 mInLoad = false;
3751 updateInLoadMenuItems();
3752 }
3753 } else {
3754 // onPageFinished may have already been called but a subframe
3755 // is still loading and updating the progress. Reset mInLoad
3756 // and update the menu items.
3757 if (!mInLoad) {
3758 mInLoad = true;
3759 updateInLoadMenuItems();
3760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003761 }
3762 }
3763
3764 @Override
3765 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003766 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767
3768 // here, if url is null, we want to reset the title
3769 setUrlTitle(url, title);
3770
3771 if (url == null ||
3772 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3773 return;
3774 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003775 // See if we can find the current url in our history database and
3776 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 if (url.startsWith("http://www.")) {
3778 url = url.substring(11);
3779 } else if (url.startsWith("http://")) {
3780 url = url.substring(4);
3781 }
3782 try {
3783 url = "%" + url;
3784 String [] selArgs = new String[] { url };
3785
3786 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3787 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3788 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3789 Browser.HISTORY_PROJECTION, where, selArgs, null);
3790 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 // Current implementation of database only has one entry per
3792 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003793 ContentValues map = new ContentValues();
3794 map.put(Browser.BookmarkColumns.TITLE, title);
3795 mResolver.update(Browser.BOOKMARKS_URI, map,
3796 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 }
3798 c.close();
3799 } catch (IllegalStateException e) {
3800 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3801 } catch (SQLiteException ex) {
3802 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3803 }
3804 }
3805
3806 @Override
3807 public void onReceivedIcon(WebView view, Bitmap icon) {
3808 updateIcon(view.getUrl(), icon);
3809 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003810
Andrei Popescuadc008d2009-06-26 14:11:30 +01003811 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003812 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003813 if (mCustomView != null)
3814 return;
3815
3816 // Add the custom view to its container.
3817 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3818 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003819 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003820 // Save the menu state and set it to empty while the custom
3821 // view is showing.
3822 mOldMenuState = mMenuState;
3823 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003824 // Hide the content view.
3825 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003826 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003827 mCustomViewContainer.setVisibility(View.VISIBLE);
3828 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003829 }
3830
3831 @Override
3832 public void onHideCustomView() {
3833 if (mCustomView == null)
3834 return;
3835
Andrei Popescuc9b55562009-07-07 10:51:15 +01003836 // Hide the custom view.
3837 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003838 // Remove the custom view from its container.
3839 mCustomViewContainer.removeView(mCustomView);
3840 mCustomView = null;
3841 // Reset the old menu state.
3842 mMenuState = mOldMenuState;
3843 mOldMenuState = EMPTY_MENU;
3844 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003845 mCustomViewCallback.onCustomViewHidden();
3846 // Show the content view.
3847 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003848 }
3849
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003850 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003851 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003852 * @param url the URL that exceeded the quota
3853 * @param databaseIdentifier the identifier of the database on
3854 * which the transaction that caused the quota overflow was run
3855 * @param currentQuota the current quota for the origin.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003856 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003857 * @param quotaUpdater The callback to run when a decision to allow or
3858 * deny quota has been made. Don't forget to call this!
3859 */
3860 @Override
3861 public void onExceededDatabaseQuota(String url,
Andrei Popescu79e82b72009-07-27 12:01:59 +01003862 String databaseIdentifier, long currentQuota, long totalUsedQuota,
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003863 WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003864 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3865 url, databaseIdentifier, currentQuota, totalUsedQuota,
3866 quotaUpdater);
3867 }
3868
3869 /**
3870 * The Application Cache has exceeded its max size.
3871 * @param spaceNeeded is the amount of disk space that would be needed
3872 * in order for the last appcache operation to succeed.
3873 * @param totalUsedQuota is the sum of all origins' quota.
3874 * @param quotaUpdater A callback to inform the WebCore thread that a new
3875 * app cache size is available. This callback must always be executed at
3876 * some point to ensure that the sleeping WebCore thread is woken up.
3877 */
3878 @Override
3879 public void onReachedMaxAppCacheSize(long spaceNeeded,
3880 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3881 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3882 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003883 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003884
3885 /* Adds a JavaScript error message to the system log.
3886 * @param message The error message to report.
3887 * @param lineNumber The line number of the error.
3888 * @param sourceID The name of the source file that caused the error.
3889 */
3890 @Override
3891 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003892 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3893 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3894 if (mShouldShowErrorConsole &&
3895 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3896 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3897 }
3898 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003899 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003900 };
3901
3902 /**
3903 * Notify the host application a download should be done, or that
3904 * the data should be streamed if a streaming viewer is available.
3905 * @param url The full url to the content that should be downloaded
3906 * @param contentDisposition Content-disposition http header, if
3907 * present.
3908 * @param mimetype The mimetype of the content reported by the server
3909 * @param contentLength The file size reported by the server
3910 */
3911 public void onDownloadStart(String url, String userAgent,
3912 String contentDisposition, String mimetype, long contentLength) {
3913 // if we're dealing wih A/V content that's not explicitly marked
3914 // for download, check if it's streamable.
3915 if (contentDisposition == null
3916 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3917 // query the package manager to see if there's a registered handler
3918 // that matches.
3919 Intent intent = new Intent(Intent.ACTION_VIEW);
3920 intent.setDataAndType(Uri.parse(url), mimetype);
3921 if (getPackageManager().resolveActivity(intent,
3922 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3923 // someone knows how to handle this mime type with this scheme, don't download.
3924 try {
3925 startActivity(intent);
3926 return;
3927 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003928 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 Log.d(LOGTAG, "activity not found for " + mimetype
3930 + " over " + Uri.parse(url).getScheme(), ex);
3931 }
3932 // Best behavior is to fall back to a download in this case
3933 }
3934 }
3935 }
3936 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3937 }
3938
3939 /**
3940 * Notify the host application a download should be done, even if there
3941 * is a streaming viewer available for thise type.
3942 * @param url The full url to the content that should be downloaded
3943 * @param contentDisposition Content-disposition http header, if
3944 * present.
3945 * @param mimetype The mimetype of the content reported by the server
3946 * @param contentLength The file size reported by the server
3947 */
3948 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3949 String contentDisposition, String mimetype, long contentLength) {
3950
3951 String filename = URLUtil.guessFileName(url,
3952 contentDisposition, mimetype);
3953
3954 // Check to see if we have an SDCard
3955 String status = Environment.getExternalStorageState();
3956 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3957 int title;
3958 String msg;
3959
3960 // Check to see if the SDCard is busy, same as the music app
3961 if (status.equals(Environment.MEDIA_SHARED)) {
3962 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3963 title = R.string.download_sdcard_busy_dlg_title;
3964 } else {
3965 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3966 title = R.string.download_no_sdcard_dlg_title;
3967 }
3968
3969 new AlertDialog.Builder(this)
3970 .setTitle(title)
3971 .setIcon(android.R.drawable.ic_dialog_alert)
3972 .setMessage(msg)
3973 .setPositiveButton(R.string.ok, null)
3974 .show();
3975 return;
3976 }
3977
3978 // java.net.URI is a lot stricter than KURL so we have to undo
3979 // KURL's percent-encoding and redo the encoding using java.net.URI.
3980 URI uri = null;
3981 try {
3982 // Undo the percent-encoding that KURL may have done.
3983 String newUrl = new String(URLUtil.decode(url.getBytes()));
3984 // Parse the url into pieces
3985 WebAddress w = new WebAddress(newUrl);
3986 String frag = null;
3987 String query = null;
3988 String path = w.mPath;
3989 // Break the path into path, query, and fragment
3990 if (path.length() > 0) {
3991 // Strip the fragment
3992 int idx = path.lastIndexOf('#');
3993 if (idx != -1) {
3994 frag = path.substring(idx + 1);
3995 path = path.substring(0, idx);
3996 }
3997 idx = path.lastIndexOf('?');
3998 if (idx != -1) {
3999 query = path.substring(idx + 1);
4000 path = path.substring(0, idx);
4001 }
4002 }
4003 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
4004 query, frag);
4005 } catch (Exception e) {
4006 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
4007 return;
4008 }
4009
4010 // XXX: Have to use the old url since the cookies were stored using the
4011 // old percent-encoded url.
4012 String cookies = CookieManager.getInstance().getCookie(url);
4013
4014 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004015 values.put(Downloads.COLUMN_URI, uri.toString());
4016 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
4017 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
4018 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004020 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004022 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
4023 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
4024 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
4025 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004027 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004028 }
4029 if (mimetype == null) {
4030 // We must have long pressed on a link or image to download it. We
4031 // are not sure of the mimetype in this case, so do a head request
4032 new FetchUrlMimeType(this).execute(values);
4033 } else {
4034 final Uri contentUri =
4035 getContentResolver().insert(Downloads.CONTENT_URI, values);
4036 viewDownloads(contentUri);
4037 }
4038
4039 }
4040
4041 /**
4042 * Resets the lock icon. This method is called when we start a new load and
4043 * know the url to be loaded.
4044 */
4045 private void resetLockIcon(String url) {
4046 // Save the lock-icon state (we revert to it if the load gets cancelled)
4047 saveLockIcon();
4048
4049 mLockIconType = LOCK_ICON_UNSECURE;
4050 if (URLUtil.isHttpsUrl(url)) {
4051 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07004052 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004053 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4054 " reset lock icon to " + mLockIconType);
4055 }
4056 }
4057
4058 updateLockIconImage(LOCK_ICON_UNSECURE);
4059 }
4060
4061 /**
4062 * Resets the lock icon. This method is called when the icon needs to be
4063 * reset but we do not know whether we are loading a secure or not secure
4064 * page.
4065 */
4066 private void resetLockIcon() {
4067 // Save the lock-icon state (we revert to it if the load gets cancelled)
4068 saveLockIcon();
4069
4070 mLockIconType = LOCK_ICON_UNSECURE;
4071
Dave Bort31a6d1c2009-04-13 15:56:49 -07004072 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004073 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4074 " reset lock icon to " + mLockIconType);
4075 }
4076
4077 updateLockIconImage(LOCK_ICON_UNSECURE);
4078 }
4079
4080 /**
4081 * Updates the lock-icon image in the title-bar.
4082 */
4083 private void updateLockIconImage(int lockIconType) {
4084 Drawable d = null;
4085 if (lockIconType == LOCK_ICON_SECURE) {
4086 d = mSecLockIcon;
4087 } else if (lockIconType == LOCK_ICON_MIXED) {
4088 d = mMixLockIcon;
4089 }
4090 // If the tab overview is animating or being shown, do not update the
4091 // lock icon.
4092 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04004093 if (CUSTOM_BROWSER_BAR) {
4094 mTitleBar.setLock(d);
4095 } else {
4096 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4097 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004098 }
4099 }
4100
4101 /**
4102 * Displays a page-info dialog.
4103 * @param tab The tab to show info about
4104 * @param fromShowSSLCertificateOnError The flag that indicates whether
4105 * this dialog was opened from the SSL-certificate-on-error dialog or
4106 * not. This is important, since we need to know whether to return to
4107 * the parent dialog or simply dismiss.
4108 */
4109 private void showPageInfo(final TabControl.Tab tab,
4110 final boolean fromShowSSLCertificateOnError) {
4111 final LayoutInflater factory = LayoutInflater
4112 .from(this);
4113
4114 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4115
4116 final WebView view = tab.getWebView();
4117
4118 String url = null;
4119 String title = null;
4120
4121 if (view == null) {
4122 url = tab.getUrl();
4123 title = tab.getTitle();
4124 } else if (view == mTabControl.getCurrentWebView()) {
4125 // Use the cached title and url if this is the current WebView
4126 url = mUrl;
4127 title = mTitle;
4128 } else {
4129 url = view.getUrl();
4130 title = view.getTitle();
4131 }
4132
4133 if (url == null) {
4134 url = "";
4135 }
4136 if (title == null) {
4137 title = "";
4138 }
4139
4140 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4141 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4142
4143 mPageInfoView = tab;
4144 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4145
4146 AlertDialog.Builder alertDialogBuilder =
4147 new AlertDialog.Builder(this)
4148 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4149 .setView(pageInfoView)
4150 .setPositiveButton(
4151 R.string.ok,
4152 new DialogInterface.OnClickListener() {
4153 public void onClick(DialogInterface dialog,
4154 int whichButton) {
4155 mPageInfoDialog = null;
4156 mPageInfoView = null;
4157 mPageInfoFromShowSSLCertificateOnError = null;
4158
4159 // if we came here from the SSL error dialog
4160 if (fromShowSSLCertificateOnError) {
4161 // go back to the SSL error dialog
4162 showSSLCertificateOnError(
4163 mSSLCertificateOnErrorView,
4164 mSSLCertificateOnErrorHandler,
4165 mSSLCertificateOnErrorError);
4166 }
4167 }
4168 })
4169 .setOnCancelListener(
4170 new DialogInterface.OnCancelListener() {
4171 public void onCancel(DialogInterface dialog) {
4172 mPageInfoDialog = null;
4173 mPageInfoView = null;
4174 mPageInfoFromShowSSLCertificateOnError = null;
4175
4176 // if we came here from the SSL error dialog
4177 if (fromShowSSLCertificateOnError) {
4178 // go back to the SSL error dialog
4179 showSSLCertificateOnError(
4180 mSSLCertificateOnErrorView,
4181 mSSLCertificateOnErrorHandler,
4182 mSSLCertificateOnErrorError);
4183 }
4184 }
4185 });
4186
4187 // if we have a main top-level page SSL certificate set or a certificate
4188 // error
4189 if (fromShowSSLCertificateOnError ||
4190 (view != null && view.getCertificate() != null)) {
4191 // add a 'View Certificate' button
4192 alertDialogBuilder.setNeutralButton(
4193 R.string.view_certificate,
4194 new DialogInterface.OnClickListener() {
4195 public void onClick(DialogInterface dialog,
4196 int whichButton) {
4197 mPageInfoDialog = null;
4198 mPageInfoView = null;
4199 mPageInfoFromShowSSLCertificateOnError = null;
4200
4201 // if we came here from the SSL error dialog
4202 if (fromShowSSLCertificateOnError) {
4203 // go back to the SSL error dialog
4204 showSSLCertificateOnError(
4205 mSSLCertificateOnErrorView,
4206 mSSLCertificateOnErrorHandler,
4207 mSSLCertificateOnErrorError);
4208 } else {
4209 // otherwise, display the top-most certificate from
4210 // the chain
4211 if (view.getCertificate() != null) {
4212 showSSLCertificate(tab);
4213 }
4214 }
4215 }
4216 });
4217 }
4218
4219 mPageInfoDialog = alertDialogBuilder.show();
4220 }
4221
4222 /**
4223 * Displays the main top-level page SSL certificate dialog
4224 * (accessible from the Page-Info dialog).
4225 * @param tab The tab to show certificate for.
4226 */
4227 private void showSSLCertificate(final TabControl.Tab tab) {
4228 final View certificateView =
4229 inflateCertificateView(tab.getWebView().getCertificate());
4230 if (certificateView == null) {
4231 return;
4232 }
4233
4234 LayoutInflater factory = LayoutInflater.from(this);
4235
4236 final LinearLayout placeholder =
4237 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4238
4239 LinearLayout ll = (LinearLayout) factory.inflate(
4240 R.layout.ssl_success, placeholder);
4241 ((TextView)ll.findViewById(R.id.success))
4242 .setText(R.string.ssl_certificate_is_valid);
4243
4244 mSSLCertificateView = tab;
4245 mSSLCertificateDialog =
4246 new AlertDialog.Builder(this)
4247 .setTitle(R.string.ssl_certificate).setIcon(
4248 R.drawable.ic_dialog_browser_certificate_secure)
4249 .setView(certificateView)
4250 .setPositiveButton(R.string.ok,
4251 new DialogInterface.OnClickListener() {
4252 public void onClick(DialogInterface dialog,
4253 int whichButton) {
4254 mSSLCertificateDialog = null;
4255 mSSLCertificateView = null;
4256
4257 showPageInfo(tab, false);
4258 }
4259 })
4260 .setOnCancelListener(
4261 new DialogInterface.OnCancelListener() {
4262 public void onCancel(DialogInterface dialog) {
4263 mSSLCertificateDialog = null;
4264 mSSLCertificateView = null;
4265
4266 showPageInfo(tab, false);
4267 }
4268 })
4269 .show();
4270 }
4271
4272 /**
4273 * Displays the SSL error certificate dialog.
4274 * @param view The target web-view.
4275 * @param handler The SSL error handler responsible for cancelling the
4276 * connection that resulted in an SSL error or proceeding per user request.
4277 * @param error The SSL error object.
4278 */
4279 private void showSSLCertificateOnError(
4280 final WebView view, final SslErrorHandler handler, final SslError error) {
4281
4282 final View certificateView =
4283 inflateCertificateView(error.getCertificate());
4284 if (certificateView == null) {
4285 return;
4286 }
4287
4288 LayoutInflater factory = LayoutInflater.from(this);
4289
4290 final LinearLayout placeholder =
4291 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4292
4293 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4294 LinearLayout ll = (LinearLayout)factory
4295 .inflate(R.layout.ssl_warning, placeholder);
4296 ((TextView)ll.findViewById(R.id.warning))
4297 .setText(R.string.ssl_untrusted);
4298 }
4299
4300 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4301 LinearLayout ll = (LinearLayout)factory
4302 .inflate(R.layout.ssl_warning, placeholder);
4303 ((TextView)ll.findViewById(R.id.warning))
4304 .setText(R.string.ssl_mismatch);
4305 }
4306
4307 if (error.hasError(SslError.SSL_EXPIRED)) {
4308 LinearLayout ll = (LinearLayout)factory
4309 .inflate(R.layout.ssl_warning, placeholder);
4310 ((TextView)ll.findViewById(R.id.warning))
4311 .setText(R.string.ssl_expired);
4312 }
4313
4314 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4315 LinearLayout ll = (LinearLayout)factory
4316 .inflate(R.layout.ssl_warning, placeholder);
4317 ((TextView)ll.findViewById(R.id.warning))
4318 .setText(R.string.ssl_not_yet_valid);
4319 }
4320
4321 mSSLCertificateOnErrorHandler = handler;
4322 mSSLCertificateOnErrorView = view;
4323 mSSLCertificateOnErrorError = error;
4324 mSSLCertificateOnErrorDialog =
4325 new AlertDialog.Builder(this)
4326 .setTitle(R.string.ssl_certificate).setIcon(
4327 R.drawable.ic_dialog_browser_certificate_partially_secure)
4328 .setView(certificateView)
4329 .setPositiveButton(R.string.ok,
4330 new DialogInterface.OnClickListener() {
4331 public void onClick(DialogInterface dialog,
4332 int whichButton) {
4333 mSSLCertificateOnErrorDialog = null;
4334 mSSLCertificateOnErrorView = null;
4335 mSSLCertificateOnErrorHandler = null;
4336 mSSLCertificateOnErrorError = null;
4337
4338 mWebViewClient.onReceivedSslError(
4339 view, handler, error);
4340 }
4341 })
4342 .setNeutralButton(R.string.page_info_view,
4343 new DialogInterface.OnClickListener() {
4344 public void onClick(DialogInterface dialog,
4345 int whichButton) {
4346 mSSLCertificateOnErrorDialog = null;
4347
4348 // do not clear the dialog state: we will
4349 // need to show the dialog again once the
4350 // user is done exploring the page-info details
4351
4352 showPageInfo(mTabControl.getTabFromView(view),
4353 true);
4354 }
4355 })
4356 .setOnCancelListener(
4357 new DialogInterface.OnCancelListener() {
4358 public void onCancel(DialogInterface dialog) {
4359 mSSLCertificateOnErrorDialog = null;
4360 mSSLCertificateOnErrorView = null;
4361 mSSLCertificateOnErrorHandler = null;
4362 mSSLCertificateOnErrorError = null;
4363
4364 mWebViewClient.onReceivedSslError(
4365 view, handler, error);
4366 }
4367 })
4368 .show();
4369 }
4370
4371 /**
4372 * Inflates the SSL certificate view (helper method).
4373 * @param certificate The SSL certificate.
4374 * @return The resultant certificate view with issued-to, issued-by,
4375 * issued-on, expires-on, and possibly other fields set.
4376 * If the input certificate is null, returns null.
4377 */
4378 private View inflateCertificateView(SslCertificate certificate) {
4379 if (certificate == null) {
4380 return null;
4381 }
4382
4383 LayoutInflater factory = LayoutInflater.from(this);
4384
4385 View certificateView = factory.inflate(
4386 R.layout.ssl_certificate, null);
4387
4388 // issued to:
4389 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4390 if (issuedTo != null) {
4391 ((TextView) certificateView.findViewById(R.id.to_common))
4392 .setText(issuedTo.getCName());
4393 ((TextView) certificateView.findViewById(R.id.to_org))
4394 .setText(issuedTo.getOName());
4395 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4396 .setText(issuedTo.getUName());
4397 }
4398
4399 // issued by:
4400 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4401 if (issuedBy != null) {
4402 ((TextView) certificateView.findViewById(R.id.by_common))
4403 .setText(issuedBy.getCName());
4404 ((TextView) certificateView.findViewById(R.id.by_org))
4405 .setText(issuedBy.getOName());
4406 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4407 .setText(issuedBy.getUName());
4408 }
4409
4410 // issued on:
4411 String issuedOn = reformatCertificateDate(
4412 certificate.getValidNotBefore());
4413 ((TextView) certificateView.findViewById(R.id.issued_on))
4414 .setText(issuedOn);
4415
4416 // expires on:
4417 String expiresOn = reformatCertificateDate(
4418 certificate.getValidNotAfter());
4419 ((TextView) certificateView.findViewById(R.id.expires_on))
4420 .setText(expiresOn);
4421
4422 return certificateView;
4423 }
4424
4425 /**
4426 * Re-formats the certificate date (Date.toString()) string to
4427 * a properly localized date string.
4428 * @return Properly localized version of the certificate date string and
4429 * the original certificate date string if fails to localize.
4430 * If the original string is null, returns an empty string "".
4431 */
4432 private String reformatCertificateDate(String certificateDate) {
4433 String reformattedDate = null;
4434
4435 if (certificateDate != null) {
4436 Date date = null;
4437 try {
4438 date = java.text.DateFormat.getInstance().parse(certificateDate);
4439 } catch (ParseException e) {
4440 date = null;
4441 }
4442
4443 if (date != null) {
4444 reformattedDate =
4445 DateFormat.getDateFormat(this).format(date);
4446 }
4447 }
4448
4449 return reformattedDate != null ? reformattedDate :
4450 (certificateDate != null ? certificateDate : "");
4451 }
4452
4453 /**
4454 * Displays an http-authentication dialog.
4455 */
4456 private void showHttpAuthentication(final HttpAuthHandler handler,
4457 final String host, final String realm, final String title,
4458 final String name, final String password, int focusId) {
4459 LayoutInflater factory = LayoutInflater.from(this);
4460 final View v = factory
4461 .inflate(R.layout.http_authentication, null);
4462 if (name != null) {
4463 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4464 }
4465 if (password != null) {
4466 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4467 }
4468
4469 String titleText = title;
4470 if (titleText == null) {
4471 titleText = getText(R.string.sign_in_to).toString().replace(
4472 "%s1", host).replace("%s2", realm);
4473 }
4474
4475 mHttpAuthHandler = handler;
4476 AlertDialog dialog = new AlertDialog.Builder(this)
4477 .setTitle(titleText)
4478 .setIcon(android.R.drawable.ic_dialog_alert)
4479 .setView(v)
4480 .setPositiveButton(R.string.action,
4481 new DialogInterface.OnClickListener() {
4482 public void onClick(DialogInterface dialog,
4483 int whichButton) {
4484 String nm = ((EditText) v
4485 .findViewById(R.id.username_edit))
4486 .getText().toString();
4487 String pw = ((EditText) v
4488 .findViewById(R.id.password_edit))
4489 .getText().toString();
4490 BrowserActivity.this.setHttpAuthUsernamePassword
4491 (host, realm, nm, pw);
4492 handler.proceed(nm, pw);
4493 mHttpAuthenticationDialog = null;
4494 mHttpAuthHandler = null;
4495 }})
4496 .setNegativeButton(R.string.cancel,
4497 new DialogInterface.OnClickListener() {
4498 public void onClick(DialogInterface dialog,
4499 int whichButton) {
4500 handler.cancel();
4501 BrowserActivity.this.resetTitleAndRevertLockIcon();
4502 mHttpAuthenticationDialog = null;
4503 mHttpAuthHandler = null;
4504 }})
4505 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4506 public void onCancel(DialogInterface dialog) {
4507 handler.cancel();
4508 BrowserActivity.this.resetTitleAndRevertLockIcon();
4509 mHttpAuthenticationDialog = null;
4510 mHttpAuthHandler = null;
4511 }})
4512 .create();
4513 // Make the IME appear when the dialog is displayed if applicable.
4514 dialog.getWindow().setSoftInputMode(
4515 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4516 dialog.show();
4517 if (focusId != 0) {
4518 dialog.findViewById(focusId).requestFocus();
4519 } else {
4520 v.findViewById(R.id.username_edit).requestFocus();
4521 }
4522 mHttpAuthenticationDialog = dialog;
4523 }
4524
4525 public int getProgress() {
4526 WebView w = mTabControl.getCurrentWebView();
4527 if (w != null) {
4528 return w.getProgress();
4529 } else {
4530 return 100;
4531 }
4532 }
4533
4534 /**
4535 * Set HTTP authentication password.
4536 *
4537 * @param host The host for the password
4538 * @param realm The realm for the password
4539 * @param username The username for the password. If it is null, it means
4540 * password can't be saved.
4541 * @param password The password
4542 */
4543 public void setHttpAuthUsernamePassword(String host, String realm,
4544 String username,
4545 String password) {
4546 WebView w = mTabControl.getCurrentWebView();
4547 if (w != null) {
4548 w.setHttpAuthUsernamePassword(host, realm, username, password);
4549 }
4550 }
4551
4552 /**
4553 * connectivity manager says net has come or gone... inform the user
4554 * @param up true if net has come up, false if net has gone down
4555 */
4556 public void onNetworkToggle(boolean up) {
4557 if (up == mIsNetworkUp) {
4558 return;
4559 } else if (up) {
4560 mIsNetworkUp = true;
4561 if (mAlertDialog != null) {
4562 mAlertDialog.cancel();
4563 mAlertDialog = null;
4564 }
4565 } else {
4566 mIsNetworkUp = false;
4567 if (mInLoad && mAlertDialog == null) {
4568 mAlertDialog = new AlertDialog.Builder(this)
4569 .setTitle(R.string.loadSuspendedTitle)
4570 .setMessage(R.string.loadSuspended)
4571 .setPositiveButton(R.string.ok, null)
4572 .show();
4573 }
4574 }
4575 WebView w = mTabControl.getCurrentWebView();
4576 if (w != null) {
4577 w.setNetworkAvailable(up);
4578 }
4579 }
4580
4581 @Override
4582 protected void onActivityResult(int requestCode, int resultCode,
4583 Intent intent) {
4584 switch (requestCode) {
4585 case COMBO_PAGE:
4586 if (resultCode == RESULT_OK && intent != null) {
4587 String data = intent.getAction();
4588 Bundle extras = intent.getExtras();
4589 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04004590 final TabControl.Tab newTab = openTab(data);
4591 if (mSettings.openInBackground() &&
4592 newTab != null && mTabOverview != null) {
4593 mTabControl.populatePickerData(newTab);
4594 mTabControl.setCurrentTab(newTab);
4595 mTabOverview.add(newTab);
4596 mTabOverview.setCurrentIndex(
4597 mTabControl.getCurrentIndex());
4598 sendAnimateFromOverview(newTab, false,
4599 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY, null);
4600 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004601 } else {
4602 final TabControl.Tab currentTab =
4603 mTabControl.getCurrentTab();
4604 // If the Window overview is up and we are not in the
4605 // middle of an animation, animate away from it to the
4606 // current tab.
4607 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004608 sendAnimateFromOverview(currentTab, false,
4609 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004610 } else {
4611 dismissSubWindow(currentTab);
4612 if (data != null && data.length() != 0) {
4613 getTopWindow().loadUrl(data);
4614 }
4615 }
4616 }
4617 }
4618 break;
4619 default:
4620 break;
4621 }
4622 getTopWindow().requestFocus();
4623 }
4624
4625 /*
4626 * This method is called as a result of the user selecting the options
4627 * menu to see the download window, or when a download changes state. It
4628 * shows the download window ontop of the current window.
4629 */
4630 /* package */ void viewDownloads(Uri downloadRecord) {
4631 Intent intent = new Intent(this,
4632 BrowserDownloadPage.class);
4633 intent.setData(downloadRecord);
4634 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4635
4636 }
4637
4638 /**
4639 * Handle results from Tab Switcher mTabOverview tool
4640 */
4641 private class TabListener implements ImageGrid.Listener {
4642 public void remove(int position) {
4643 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004644 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004645 throw new AssertionError();
4646 }
4647
4648 // Remember the current tab.
4649 TabControl.Tab current = mTabControl.getCurrentTab();
4650 final TabControl.Tab remove = mTabControl.getTab(position);
4651 mTabControl.removeTab(remove);
4652 // If we removed the current tab, use the tab at position - 1 if
4653 // possible.
4654 if (current == remove) {
4655 // If the user removes the last tab, act like the New Tab item
4656 // was clicked on.
4657 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004658 current = mTabControl.createNewTab();
Grace Klobaec7eb372009-06-16 13:45:56 -07004659 sendAnimateFromOverview(current, true, new UrlData(
4660 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004661 } else {
4662 final int index = position > 0 ? (position - 1) : 0;
4663 current = mTabControl.getTab(index);
4664 }
4665 }
4666
4667 // The tab overview could have been dismissed before this method is
4668 // called.
4669 if (mTabOverview != null) {
4670 // Remove the tab and change the index.
4671 mTabOverview.remove(position);
4672 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4673 }
4674
4675 // Only the current tab ensures its WebView is non-null. This
4676 // implies that we are reloading the freed tab.
4677 mTabControl.setCurrentTab(current);
4678 }
4679 public void onClick(int index) {
4680 // Change the tab if necessary.
4681 // Index equals ImageGrid.CANCEL when pressing back from the tab
4682 // overview.
4683 if (index == ImageGrid.CANCEL) {
4684 index = mTabControl.getCurrentIndex();
4685 // The current index is -1 if the current tab was removed.
4686 if (index == -1) {
4687 // Take the last tab as a fallback.
4688 index = mTabControl.getTabCount() - 1;
4689 }
4690 }
4691
The Android Open Source Project0c908882009-03-03 19:32:16 -08004692 // NEW_TAB means that the "New Tab" cell was clicked on.
4693 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004694 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004695 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004696 sendAnimateFromOverview(mTabControl.getTab(index), false,
4697 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004698 }
4699 }
4700 }
4701
4702 // A fake View that draws the WebView's picture with a fast zoom filter.
4703 // The View is used in case the tab is freed during the animation because
4704 // of low memory.
4705 private static class AnimatingView extends View {
4706 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4707 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4708 private static final DrawFilter sZoomFilter =
4709 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4710 private final Picture mPicture;
4711 private final float mScale;
4712 private final int mScrollX;
4713 private final int mScrollY;
4714 final TabControl.Tab mTab;
4715
4716 AnimatingView(Context ctxt, TabControl.Tab t) {
4717 super(ctxt);
4718 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004719 if (t != null && t.getTopWindow() != null) {
4720 // Use the top window in the animation since the tab overview
4721 // will display the top window in each cell.
4722 final WebView w = t.getTopWindow();
4723 mPicture = w.capturePicture();
4724 mScale = w.getScale() / w.getWidth();
4725 mScrollX = w.getScrollX();
4726 mScrollY = w.getScrollY();
4727 } else {
4728 mPicture = null;
4729 mScale = 1.0f;
4730 mScrollX = mScrollY = 0;
4731 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004732 }
4733
4734 @Override
4735 protected void onDraw(Canvas canvas) {
4736 canvas.save();
4737 canvas.drawColor(Color.WHITE);
4738 if (mPicture != null) {
4739 canvas.setDrawFilter(sZoomFilter);
4740 float scale = getWidth() * mScale;
4741 canvas.scale(scale, scale);
4742 canvas.translate(-mScrollX, -mScrollY);
4743 canvas.drawPicture(mPicture);
4744 }
4745 canvas.restore();
4746 }
4747 }
4748
4749 /**
4750 * Open the tab picker. This function will always use the current tab in
4751 * its animation.
4752 * @param stay boolean stating whether the tab picker is to remain open
4753 * (in which case it needs a listener and its menu) or not.
4754 * @param index The index of the tab to show as the selection in the tab
4755 * overview.
4756 * @param remove If true, the tab at index will be removed after the
4757 * animation completes.
4758 */
4759 private void tabPicker(final boolean stay, final int index,
4760 final boolean remove) {
4761 if (mTabOverview != null) {
4762 return;
4763 }
4764
4765 int size = mTabControl.getTabCount();
4766
4767 TabListener l = null;
4768 if (stay) {
4769 l = mTabListener = new TabListener();
4770 }
4771 mTabOverview = new ImageGrid(this, stay, l);
4772
4773 for (int i = 0; i < size; i++) {
4774 final TabControl.Tab t = mTabControl.getTab(i);
4775 mTabControl.populatePickerData(t);
4776 mTabOverview.add(t);
4777 }
4778
4779 // Tell the tab overview to show the current tab, the tab overview will
4780 // handle the "New Tab" case.
4781 int currentIndex = mTabControl.getCurrentIndex();
4782 mTabOverview.setCurrentIndex(currentIndex);
4783
4784 // Attach the tab overview.
4785 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4786
4787 // Create a fake AnimatingView to animate the WebView's picture.
4788 final TabControl.Tab current = mTabControl.getCurrentTab();
4789 final AnimatingView v = new AnimatingView(this, current);
4790 mContentView.addView(v, COVER_SCREEN_PARAMS);
4791 removeTabFromContentView(current);
4792 // Pause timers to get the animation smoother.
4793 current.getWebView().pauseTimers();
4794
4795 // Send a message so the tab picker has a chance to layout and get
4796 // positions for all the cells.
4797 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4798 index, remove ? 1 : 0, v));
4799 // Setting this will indicate that we are animating to the overview. We
4800 // set it here to prevent another request to animate from coming in
4801 // between now and when ANIMATE_TO_OVERVIEW is handled.
4802 mAnimationCount++;
4803 // Always change the title bar to the window overview title while
4804 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004805 if (CUSTOM_BROWSER_BAR) {
4806 mTitleBar.setToTabPicker();
4807 } else {
4808 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4809 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4810 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4811 Window.PROGRESS_VISIBILITY_OFF);
4812 setTitle(R.string.tab_picker_title);
4813 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004814 // Make the menu empty until the animation completes.
4815 mMenuState = EMPTY_MENU;
4816 }
4817
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004818 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004819 WebView current = mTabControl.getCurrentWebView();
4820 if (current == null) {
4821 return;
4822 }
4823 Intent intent = new Intent(this,
4824 CombinedBookmarkHistoryActivity.class);
4825 String title = current.getTitle();
4826 String url = current.getUrl();
4827 // Just in case the user opens bookmarks before a page finishes loading
4828 // so the current history item, and therefore the page, is null.
4829 if (null == url) {
4830 url = mLastEnteredUrl;
4831 // This can happen.
4832 if (null == url) {
4833 url = mSettings.getHomePage();
4834 }
4835 }
4836 // In case the web page has not yet received its associated title.
4837 if (title == null) {
4838 title = url;
4839 }
4840 intent.putExtra("title", title);
4841 intent.putExtra("url", url);
4842 intent.putExtra("maxTabsOpen",
4843 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4844 if (startWithHistory) {
4845 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4846 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4847 }
4848 startActivityForResult(intent, COMBO_PAGE);
4849 }
4850
4851 // Called when loading from context menu or LOAD_URL message
4852 private void loadURL(WebView view, String url) {
4853 // In case the user enters nothing.
4854 if (url != null && url.length() != 0 && view != null) {
4855 url = smartUrlFilter(url);
4856 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4857 view.loadUrl(url);
4858 }
4859 }
4860 }
4861
4862 private void checkMemory() {
4863 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4864 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4865 .getMemoryInfo(mi);
4866 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4867 // mi.threshold) for now
4868 // if (mi.lowMemory) {
4869 if (mi.availMem < mi.threshold) {
4870 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4871 + (mi.availMem / 1024) + "K threshold="
4872 + (mi.threshold / 1024) + "K");
4873 mTabControl.freeMemory();
4874 }
4875 }
4876
4877 private String smartUrlFilter(Uri inUri) {
4878 if (inUri != null) {
4879 return smartUrlFilter(inUri.toString());
4880 }
4881 return null;
4882 }
4883
4884
4885 // get window count
4886
4887 int getWindowCount(){
4888 if(mTabControl != null){
4889 return mTabControl.getTabCount();
4890 }
4891 return 0;
4892 }
4893
Feng Qianb34f87a2009-03-24 21:27:26 -07004894 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004895 "(?i)" + // switch on case insensitive matching
4896 "(" + // begin group for schema
4897 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004898 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004899 ")" +
4900 "(.*)" );
4901
4902 /**
4903 * Attempts to determine whether user input is a URL or search
4904 * terms. Anything with a space is passed to search.
4905 *
4906 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4907 * "Http://" converts to "http://"
4908 *
4909 * @return Original or modified URL
4910 *
4911 */
4912 String smartUrlFilter(String url) {
4913
4914 String inUrl = url.trim();
4915 boolean hasSpace = inUrl.indexOf(' ') != -1;
4916
4917 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4918 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004919 // force scheme to lowercase
4920 String scheme = matcher.group(1);
4921 String lcScheme = scheme.toLowerCase();
4922 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004923 inUrl = lcScheme + matcher.group(2);
4924 }
4925 if (hasSpace) {
4926 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004927 }
4928 return inUrl;
4929 }
4930 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004931 // FIXME: Is this the correct place to add to searches?
4932 // what if someone else calls this function?
4933 int shortcut = parseUrlShortcut(inUrl);
4934 if (shortcut != SHORTCUT_INVALID) {
4935 Browser.addSearchUrl(mResolver, inUrl);
4936 String query = inUrl.substring(2);
4937 switch (shortcut) {
4938 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004939 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004940 case SHORTCUT_WIKIPEDIA_SEARCH:
4941 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4942 case SHORTCUT_DICTIONARY_SEARCH:
4943 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4944 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004945 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004946 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004947 }
4948 }
4949 } else {
4950 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4951 return URLUtil.guessUrl(inUrl);
4952 }
4953 }
4954
4955 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004956 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004957 }
4958
Ben Murdochbff2d602009-07-01 20:19:05 +01004959 /* package */ void setShouldShowErrorConsole(boolean flag) {
4960 if (flag == mShouldShowErrorConsole) {
4961 // Nothing to do.
4962 return;
4963 }
4964
4965 mShouldShowErrorConsole = flag;
4966
4967 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4968
4969 if (flag) {
4970 // Setting the show state of the console will cause it's the layout to be inflated.
4971 if (errorConsole.numberOfErrors() > 0) {
4972 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4973 } else {
4974 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4975 }
4976
4977 // Now we can add it to the main view.
4978 mErrorConsoleContainer.addView(errorConsole,
4979 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4980 ViewGroup.LayoutParams.WRAP_CONTENT));
4981 } else {
4982 mErrorConsoleContainer.removeView(errorConsole);
4983 }
4984
4985 }
4986
The Android Open Source Project0c908882009-03-03 19:32:16 -08004987 private final static int LOCK_ICON_UNSECURE = 0;
4988 private final static int LOCK_ICON_SECURE = 1;
4989 private final static int LOCK_ICON_MIXED = 2;
4990
4991 private int mLockIconType = LOCK_ICON_UNSECURE;
4992 private int mPrevLockType = LOCK_ICON_UNSECURE;
4993
4994 private BrowserSettings mSettings;
4995 private TabControl mTabControl;
4996 private ContentResolver mResolver;
4997 private FrameLayout mContentView;
4998 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004999 private View mCustomView;
5000 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01005001 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005002
5003 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
5004 // view, we should rewrite this.
5005 private int mCurrentMenuState = 0;
5006 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01005007 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005008 private static final int EMPTY_MENU = -1;
5009 private Menu mMenu;
5010
5011 private FindDialog mFindDialog;
5012 // Used to prevent chording to result in firing two shortcuts immediately
5013 // one after another. Fixes bug 1211714.
5014 boolean mCanChord;
5015
5016 private boolean mInLoad;
5017 private boolean mIsNetworkUp;
5018
5019 private boolean mPageStarted;
5020 private boolean mActivityInPause = true;
5021
5022 private boolean mMenuIsDown;
5023
5024 private final KeyTracker mKeyTracker = new KeyTracker(this);
5025
5026 // As trackball doesn't send repeat down, we have to track it ourselves
5027 private boolean mTrackTrackball;
5028
5029 private static boolean mInTrace;
5030
5031 // Performance probe
5032 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
5033 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
5034 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
5035 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
5036 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
5037 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
5038 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
5039 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
5040 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
5041 };
5042
5043 private long mStart;
5044 private long mProcessStart;
5045 private long mUserStart;
5046 private long mSystemStart;
5047 private long mIdleStart;
5048 private long mIrqStart;
5049
5050 private long mUiStart;
5051
5052 private Drawable mMixLockIcon;
5053 private Drawable mSecLockIcon;
5054 private Drawable mGenericFavicon;
5055
5056 /* hold a ref so we can auto-cancel if necessary */
5057 private AlertDialog mAlertDialog;
5058
5059 // Wait for credentials before loading google.com
5060 private ProgressDialog mCredsDlg;
5061
5062 // The up-to-date URL and title (these can be different from those stored
5063 // in WebView, since it takes some time for the information in WebView to
5064 // get updated)
5065 private String mUrl;
5066 private String mTitle;
5067
5068 // As PageInfo has different style for landscape / portrait, we have
5069 // to re-open it when configuration changed
5070 private AlertDialog mPageInfoDialog;
5071 private TabControl.Tab mPageInfoView;
5072 // If the Page-Info dialog is launched from the SSL-certificate-on-error
5073 // dialog, we should not just dismiss it, but should get back to the
5074 // SSL-certificate-on-error dialog. This flag is used to store this state
5075 private Boolean mPageInfoFromShowSSLCertificateOnError;
5076
5077 // as SSLCertificateOnError has different style for landscape / portrait,
5078 // we have to re-open it when configuration changed
5079 private AlertDialog mSSLCertificateOnErrorDialog;
5080 private WebView mSSLCertificateOnErrorView;
5081 private SslErrorHandler mSSLCertificateOnErrorHandler;
5082 private SslError mSSLCertificateOnErrorError;
5083
5084 // as SSLCertificate has different style for landscape / portrait, we
5085 // have to re-open it when configuration changed
5086 private AlertDialog mSSLCertificateDialog;
5087 private TabControl.Tab mSSLCertificateView;
5088
5089 // as HttpAuthentication has different style for landscape / portrait, we
5090 // have to re-open it when configuration changed
5091 private AlertDialog mHttpAuthenticationDialog;
5092 private HttpAuthHandler mHttpAuthHandler;
5093
5094 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
5095 new FrameLayout.LayoutParams(
5096 ViewGroup.LayoutParams.FILL_PARENT,
5097 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01005098 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
5099 new FrameLayout.LayoutParams(
5100 ViewGroup.LayoutParams.FILL_PARENT,
5101 ViewGroup.LayoutParams.FILL_PARENT,
5102 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07005103 // Google search
5104 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08005105 // Wikipedia search
5106 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
5107 // Dictionary search
5108 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
5109 // Google Mobile Local search
5110 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
5111
5112 final static String QUERY_PLACE_HOLDER = "%s";
5113
5114 // "source" parameter for Google search through search key
5115 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5116 // "source" parameter for Google search through goto menu
5117 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5118 // "source" parameter for Google search through simplily type
5119 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5120 // "source" parameter for Google search suggested by the browser
5121 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5122 // "source" parameter for Google search from unknown source
5123 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5124
5125 private final static String LOGTAG = "browser";
5126
5127 private TabListener mTabListener;
5128
5129 private String mLastEnteredUrl;
5130
5131 private PowerManager.WakeLock mWakeLock;
5132 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5133
5134 private Toast mStopToast;
5135
Leon Scroggins81db3662009-06-04 17:45:11 -04005136 private TitleBar mTitleBar;
5137
Ben Murdochbff2d602009-07-01 20:19:05 +01005138 private LinearLayout mErrorConsoleContainer = null;
5139 private boolean mShouldShowErrorConsole = false;
5140
The Android Open Source Project0c908882009-03-03 19:32:16 -08005141 // Used during animations to prevent other animations from being triggered.
5142 // A count is used since the animation to and from the Window overview can
5143 // overlap. A count of 0 means no animation where a count of > 0 means
5144 // there are animations in progress.
5145 private int mAnimationCount;
5146
5147 // As the ids are dynamically created, we can't guarantee that they will
5148 // be in sequence, so this static array maps ids to a window number.
5149 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5150 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5151 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5152 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5153
5154 // monitor platform changes
5155 private IntentFilter mNetworkStateChangedFilter;
5156 private BroadcastReceiver mNetworkStateIntentReceiver;
5157
Grace Klobab4da0ad2009-05-14 14:45:40 -07005158 private BroadcastReceiver mPackageInstallationReceiver;
5159
The Android Open Source Project0c908882009-03-03 19:32:16 -08005160 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005161 final static int COMBO_PAGE = 1;
5162 final static int DOWNLOAD_PAGE = 2;
5163 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005164
5165 // the frenquency of checking whether system memory is low
5166 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005167
5168 /**
5169 * A UrlData class to abstract how the content will be set to WebView.
5170 * This base class uses loadUrl to show the content.
5171 */
5172 private static class UrlData {
5173 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005174 byte[] mPostData;
5175
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005176 UrlData(String url) {
5177 this.mUrl = url;
5178 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005179
5180 void setPostData(byte[] postData) {
5181 mPostData = postData;
5182 }
5183
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005184 boolean isEmpty() {
5185 return mUrl == null || mUrl.length() == 0;
5186 }
5187
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005188 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005189 if (mPostData != null) {
5190 webView.postUrl(mUrl, mPostData);
5191 } else {
5192 webView.loadUrl(mUrl);
5193 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005194 }
5195 };
5196
5197 /**
5198 * A subclass of UrlData class that can display inlined content using
5199 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5200 */
5201 private static class InlinedUrlData extends UrlData {
5202 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5203 super(failUrl);
5204 mInlined = inlined;
5205 mMimeType = mimeType;
5206 mEncoding = encoding;
5207 }
5208 String mMimeType;
5209 String mInlined;
5210 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005211 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005212 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01005213 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005214 }
5215
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005216 @Override
5217 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005218 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5219 }
5220 }
5221
5222 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005223}