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