blob: eddcb28d7c6201c47a081f0da6b17101715501e0 [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
Grace Kloba5b078b52009-06-24 20:23:41 -07003047 // check whether the intent can be resolved. If not, we will see
3048 // whether we can download it from the Market.
3049 if (getPackageManager().resolveActivity(intent, 0) == null) {
3050 String packagename = intent.getPackage();
3051 if (packagename != null) {
3052 intent = new Intent(Intent.ACTION_VIEW, Uri
3053 .parse("market://search?q=pname:" + packagename));
3054 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3055 startActivity(intent);
3056 return true;
3057 } else {
3058 return false;
3059 }
3060 }
3061
Dianne Hackborn99189432009-06-17 18:06:18 -07003062 // sanitize the Intent, ensuring web pages can not bypass browser
3063 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003065 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 try {
3067 if (startActivityIfNeeded(intent, -1)) {
3068 return true;
3069 }
3070 } catch (ActivityNotFoundException ex) {
3071 // ignore the error. If no application can handle the URL,
3072 // eg about:blank, assume the browser can handle it.
3073 }
3074
3075 if (mMenuIsDown) {
3076 openTab(url);
3077 closeOptionsMenu();
3078 return true;
3079 }
3080
3081 return false;
3082 }
3083
3084 /**
3085 * Updates the lock icon. This method is called when we discover another
3086 * resource to be loaded for this page (for example, javascript). While
3087 * we update the icon type, we do not update the lock icon itself until
3088 * we are done loading, it is slightly more secure this way.
3089 */
3090 @Override
3091 public void onLoadResource(WebView view, String url) {
3092 if (url != null && url.length() > 0) {
3093 // It is only if the page claims to be secure
3094 // that we may have to update the lock:
3095 if (mLockIconType == LOCK_ICON_SECURE) {
3096 // If NOT a 'safe' url, change the lock to mixed content!
3097 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3098 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003099 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3101 " updated lock icon to " + mLockIconType + " due to " + url);
3102 }
3103 }
3104 }
3105 }
3106 }
3107
3108 /**
3109 * Show the dialog, asking the user if they would like to continue after
3110 * an excessive number of HTTP redirects.
3111 */
3112 @Override
3113 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3114 final Message continueMsg) {
3115 new AlertDialog.Builder(BrowserActivity.this)
3116 .setTitle(R.string.browserFrameRedirect)
3117 .setMessage(R.string.browserFrame307Post)
3118 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3119 public void onClick(DialogInterface dialog, int which) {
3120 continueMsg.sendToTarget();
3121 }})
3122 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3123 public void onClick(DialogInterface dialog, int which) {
3124 cancelMsg.sendToTarget();
3125 }})
3126 .setOnCancelListener(new OnCancelListener() {
3127 public void onCancel(DialogInterface dialog) {
3128 cancelMsg.sendToTarget();
3129 }})
3130 .show();
3131 }
3132
Patrick Scotta6555242009-03-24 18:01:26 -07003133 // Container class for the next error dialog that needs to be
3134 // displayed.
3135 class ErrorDialog {
3136 public final int mTitle;
3137 public final String mDescription;
3138 public final int mError;
3139 ErrorDialog(int title, String desc, int error) {
3140 mTitle = title;
3141 mDescription = desc;
3142 mError = error;
3143 }
3144 };
3145
3146 private void processNextError() {
3147 if (mQueuedErrors == null) {
3148 return;
3149 }
3150 // The first one is currently displayed so just remove it.
3151 mQueuedErrors.removeFirst();
3152 if (mQueuedErrors.size() == 0) {
3153 mQueuedErrors = null;
3154 return;
3155 }
3156 showError(mQueuedErrors.getFirst());
3157 }
3158
3159 private DialogInterface.OnDismissListener mDialogListener =
3160 new DialogInterface.OnDismissListener() {
3161 public void onDismiss(DialogInterface d) {
3162 processNextError();
3163 }
3164 };
3165 private LinkedList<ErrorDialog> mQueuedErrors;
3166
3167 private void queueError(int err, String desc) {
3168 if (mQueuedErrors == null) {
3169 mQueuedErrors = new LinkedList<ErrorDialog>();
3170 }
3171 for (ErrorDialog d : mQueuedErrors) {
3172 if (d.mError == err) {
3173 // Already saw a similar error, ignore the new one.
3174 return;
3175 }
3176 }
3177 ErrorDialog errDialog = new ErrorDialog(
3178 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3179 R.string.browserFrameFileErrorLabel :
3180 R.string.browserFrameNetworkErrorLabel,
3181 desc, err);
3182 mQueuedErrors.addLast(errDialog);
3183
3184 // Show the dialog now if the queue was empty.
3185 if (mQueuedErrors.size() == 1) {
3186 showError(errDialog);
3187 }
3188 }
3189
3190 private void showError(ErrorDialog errDialog) {
3191 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3192 .setTitle(errDialog.mTitle)
3193 .setMessage(errDialog.mDescription)
3194 .setPositiveButton(R.string.ok, null)
3195 .create();
3196 d.setOnDismissListener(mDialogListener);
3197 d.show();
3198 }
3199
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 /**
3201 * Show a dialog informing the user of the network error reported by
3202 * WebCore.
3203 */
3204 @Override
3205 public void onReceivedError(WebView view, int errorCode,
3206 String description, String failingUrl) {
3207 if (errorCode != EventHandler.ERROR_LOOKUP &&
3208 errorCode != EventHandler.ERROR_CONNECT &&
3209 errorCode != EventHandler.ERROR_BAD_URL &&
3210 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3211 errorCode != EventHandler.FILE_ERROR) {
Patrick Scotta6555242009-03-24 18:01:26 -07003212 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 }
Patrick Scotta6555242009-03-24 18:01:26 -07003214 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3215 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003216
3217 // We need to reset the title after an error.
3218 resetTitleAndRevertLockIcon();
3219 }
3220
3221 /**
3222 * Check with the user if it is ok to resend POST data as the page they
3223 * are trying to navigate to is the result of a POST.
3224 */
3225 @Override
3226 public void onFormResubmission(WebView view, final Message dontResend,
3227 final Message resend) {
3228 new AlertDialog.Builder(BrowserActivity.this)
3229 .setTitle(R.string.browserFrameFormResubmitLabel)
3230 .setMessage(R.string.browserFrameFormResubmitMessage)
3231 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3232 public void onClick(DialogInterface dialog, int which) {
3233 resend.sendToTarget();
3234 }})
3235 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3236 public void onClick(DialogInterface dialog, int which) {
3237 dontResend.sendToTarget();
3238 }})
3239 .setOnCancelListener(new OnCancelListener() {
3240 public void onCancel(DialogInterface dialog) {
3241 dontResend.sendToTarget();
3242 }})
3243 .show();
3244 }
3245
3246 /**
3247 * Insert the url into the visited history database.
3248 * @param url The url to be inserted.
3249 * @param isReload True if this url is being reloaded.
3250 * FIXME: Not sure what to do when reloading the page.
3251 */
3252 @Override
3253 public void doUpdateVisitedHistory(WebView view, String url,
3254 boolean isReload) {
3255 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3256 return;
3257 }
3258 Browser.updateVisitedHistory(mResolver, url, true);
3259 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3260 }
3261
3262 /**
3263 * Displays SSL error(s) dialog to the user.
3264 */
3265 @Override
3266 public void onReceivedSslError(
3267 final WebView view, final SslErrorHandler handler, final SslError error) {
3268
3269 if (mSettings.showSecurityWarnings()) {
3270 final LayoutInflater factory =
3271 LayoutInflater.from(BrowserActivity.this);
3272 final View warningsView =
3273 factory.inflate(R.layout.ssl_warnings, null);
3274 final LinearLayout placeholder =
3275 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3276
3277 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3278 LinearLayout ll = (LinearLayout)factory
3279 .inflate(R.layout.ssl_warning, null);
3280 ((TextView)ll.findViewById(R.id.warning))
3281 .setText(R.string.ssl_untrusted);
3282 placeholder.addView(ll);
3283 }
3284
3285 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3286 LinearLayout ll = (LinearLayout)factory
3287 .inflate(R.layout.ssl_warning, null);
3288 ((TextView)ll.findViewById(R.id.warning))
3289 .setText(R.string.ssl_mismatch);
3290 placeholder.addView(ll);
3291 }
3292
3293 if (error.hasError(SslError.SSL_EXPIRED)) {
3294 LinearLayout ll = (LinearLayout)factory
3295 .inflate(R.layout.ssl_warning, null);
3296 ((TextView)ll.findViewById(R.id.warning))
3297 .setText(R.string.ssl_expired);
3298 placeholder.addView(ll);
3299 }
3300
3301 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3302 LinearLayout ll = (LinearLayout)factory
3303 .inflate(R.layout.ssl_warning, null);
3304 ((TextView)ll.findViewById(R.id.warning))
3305 .setText(R.string.ssl_not_yet_valid);
3306 placeholder.addView(ll);
3307 }
3308
3309 new AlertDialog.Builder(BrowserActivity.this)
3310 .setTitle(R.string.security_warning)
3311 .setIcon(android.R.drawable.ic_dialog_alert)
3312 .setView(warningsView)
3313 .setPositiveButton(R.string.ssl_continue,
3314 new DialogInterface.OnClickListener() {
3315 public void onClick(DialogInterface dialog, int whichButton) {
3316 handler.proceed();
3317 }
3318 })
3319 .setNeutralButton(R.string.view_certificate,
3320 new DialogInterface.OnClickListener() {
3321 public void onClick(DialogInterface dialog, int whichButton) {
3322 showSSLCertificateOnError(view, handler, error);
3323 }
3324 })
3325 .setNegativeButton(R.string.cancel,
3326 new DialogInterface.OnClickListener() {
3327 public void onClick(DialogInterface dialog, int whichButton) {
3328 handler.cancel();
3329 BrowserActivity.this.resetTitleAndRevertLockIcon();
3330 }
3331 })
3332 .setOnCancelListener(
3333 new DialogInterface.OnCancelListener() {
3334 public void onCancel(DialogInterface dialog) {
3335 handler.cancel();
3336 BrowserActivity.this.resetTitleAndRevertLockIcon();
3337 }
3338 })
3339 .show();
3340 } else {
3341 handler.proceed();
3342 }
3343 }
3344
3345 /**
3346 * Handles an HTTP authentication request.
3347 *
3348 * @param handler The authentication handler
3349 * @param host The host
3350 * @param realm The realm
3351 */
3352 @Override
3353 public void onReceivedHttpAuthRequest(WebView view,
3354 final HttpAuthHandler handler, final String host, final String realm) {
3355 String username = null;
3356 String password = null;
3357
3358 boolean reuseHttpAuthUsernamePassword =
3359 handler.useHttpAuthUsernamePassword();
3360
3361 if (reuseHttpAuthUsernamePassword &&
3362 (mTabControl.getCurrentWebView() != null)) {
3363 String[] credentials =
3364 mTabControl.getCurrentWebView()
3365 .getHttpAuthUsernamePassword(host, realm);
3366 if (credentials != null && credentials.length == 2) {
3367 username = credentials[0];
3368 password = credentials[1];
3369 }
3370 }
3371
3372 if (username != null && password != null) {
3373 handler.proceed(username, password);
3374 } else {
3375 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3376 }
3377 }
3378
3379 @Override
3380 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3381 if (mMenuIsDown) {
3382 // only check shortcut key when MENU is held
3383 return getWindow().isShortcutKey(event.getKeyCode(), event);
3384 } else {
3385 return false;
3386 }
3387 }
3388
3389 @Override
3390 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3391 if (view != mTabControl.getCurrentTopWebView()) {
3392 return;
3393 }
3394 if (event.isDown()) {
3395 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3396 } else {
3397 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3398 }
3399 }
3400 };
3401
3402 //--------------------------------------------------------------------------
3403 // WebChromeClient implementation
3404 //--------------------------------------------------------------------------
3405
3406 /* package */ WebChromeClient getWebChromeClient() {
3407 return mWebChromeClient;
3408 }
3409
3410 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3411 // Helper method to create a new tab or sub window.
3412 private void createWindow(final boolean dialog, final Message msg) {
3413 if (dialog) {
3414 mTabControl.createSubWindow();
3415 final TabControl.Tab t = mTabControl.getCurrentTab();
3416 attachSubWindow(t);
3417 WebView.WebViewTransport transport =
3418 (WebView.WebViewTransport) msg.obj;
3419 transport.setWebView(t.getSubWebView());
3420 msg.sendToTarget();
3421 } else {
3422 final TabControl.Tab parent = mTabControl.getCurrentTab();
3423 // openTabAndShow will dispatch the message after creating the
3424 // new WebView. This will prevent another request from coming
3425 // in during the animation.
Patrick Scott95d601f2009-06-11 10:06:46 -04003426 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 parent.addChildTab(mTabControl.getCurrentTab());
3428 WebView.WebViewTransport transport =
3429 (WebView.WebViewTransport) msg.obj;
3430 transport.setWebView(mTabControl.getCurrentWebView());
3431 }
3432 }
3433
3434 @Override
3435 public boolean onCreateWindow(WebView view, final boolean dialog,
3436 final boolean userGesture, final Message resultMsg) {
3437 // Ignore these requests during tab animations or if the tab
3438 // overview is showing.
3439 if (mAnimationCount > 0 || mTabOverview != null) {
3440 return false;
3441 }
3442 // Short-circuit if we can't create any more tabs or sub windows.
3443 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3444 new AlertDialog.Builder(BrowserActivity.this)
3445 .setTitle(R.string.too_many_subwindows_dialog_title)
3446 .setIcon(android.R.drawable.ic_dialog_alert)
3447 .setMessage(R.string.too_many_subwindows_dialog_message)
3448 .setPositiveButton(R.string.ok, null)
3449 .show();
3450 return false;
3451 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3452 new AlertDialog.Builder(BrowserActivity.this)
3453 .setTitle(R.string.too_many_windows_dialog_title)
3454 .setIcon(android.R.drawable.ic_dialog_alert)
3455 .setMessage(R.string.too_many_windows_dialog_message)
3456 .setPositiveButton(R.string.ok, null)
3457 .show();
3458 return false;
3459 }
3460
3461 // Short-circuit if this was a user gesture.
3462 if (userGesture) {
3463 // createWindow will call openTabAndShow for new Windows and
3464 // that will call tabPicker which will increment
3465 // mAnimationCount.
3466 createWindow(dialog, resultMsg);
3467 return true;
3468 }
3469
3470 // Allow the popup and create the appropriate window.
3471 final AlertDialog.OnClickListener allowListener =
3472 new AlertDialog.OnClickListener() {
3473 public void onClick(DialogInterface d,
3474 int which) {
3475 // Same comment as above for setting
3476 // mAnimationCount.
3477 createWindow(dialog, resultMsg);
3478 // Since we incremented mAnimationCount while the
3479 // dialog was up, we have to decrement it here.
3480 mAnimationCount--;
3481 }
3482 };
3483
3484 // Block the popup by returning a null WebView.
3485 final AlertDialog.OnClickListener blockListener =
3486 new AlertDialog.OnClickListener() {
3487 public void onClick(DialogInterface d, int which) {
3488 resultMsg.sendToTarget();
3489 // We are not going to trigger an animation so
3490 // unblock keys and animation requests.
3491 mAnimationCount--;
3492 }
3493 };
3494
3495 // Build a confirmation dialog to display to the user.
3496 final AlertDialog d =
3497 new AlertDialog.Builder(BrowserActivity.this)
3498 .setTitle(R.string.attention)
3499 .setIcon(android.R.drawable.ic_dialog_alert)
3500 .setMessage(R.string.popup_window_attempt)
3501 .setPositiveButton(R.string.allow, allowListener)
3502 .setNegativeButton(R.string.block, blockListener)
3503 .setCancelable(false)
3504 .create();
3505
3506 // Show the confirmation dialog.
3507 d.show();
3508 // We want to increment mAnimationCount here to prevent a
3509 // potential race condition. If the user allows a pop-up from a
3510 // site and that pop-up then triggers another pop-up, it is
3511 // possible to get the BACK key between here and when the dialog
3512 // appears.
3513 mAnimationCount++;
3514 return true;
3515 }
3516
3517 @Override
3518 public void onCloseWindow(WebView window) {
3519 final int currentIndex = mTabControl.getCurrentIndex();
3520 final TabControl.Tab parent =
3521 mTabControl.getCurrentTab().getParentTab();
3522 if (parent != null) {
3523 // JavaScript can only close popup window.
3524 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3525 }
3526 }
3527
3528 @Override
3529 public void onProgressChanged(WebView view, int newProgress) {
3530 // Block progress updates to the title bar while the tab overview
3531 // is animating or being displayed.
3532 if (mAnimationCount == 0 && mTabOverview == null) {
3533 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3534 newProgress * 100);
3535 }
3536
3537 if (newProgress == 100) {
3538 // onProgressChanged() is called for sub-frame too while
3539 // onPageFinished() is only called for the main frame. sync
3540 // cookie and cache promptly here.
3541 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003542 if (mInLoad) {
3543 mInLoad = false;
3544 updateInLoadMenuItems();
3545 }
3546 } else {
3547 // onPageFinished may have already been called but a subframe
3548 // is still loading and updating the progress. Reset mInLoad
3549 // and update the menu items.
3550 if (!mInLoad) {
3551 mInLoad = true;
3552 updateInLoadMenuItems();
3553 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 }
3555 }
3556
3557 @Override
3558 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003559 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560
3561 // here, if url is null, we want to reset the title
3562 setUrlTitle(url, title);
3563
3564 if (url == null ||
3565 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3566 return;
3567 }
3568 if (url.startsWith("http://www.")) {
3569 url = url.substring(11);
3570 } else if (url.startsWith("http://")) {
3571 url = url.substring(4);
3572 }
3573 try {
3574 url = "%" + url;
3575 String [] selArgs = new String[] { url };
3576
3577 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3578 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3579 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3580 Browser.HISTORY_PROJECTION, where, selArgs, null);
3581 if (c.moveToFirst()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003582 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 Log.v(LOGTAG, "updating cursor");
3584 }
3585 // Current implementation of database only has one entry per
3586 // url.
3587 int titleIndex =
3588 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3589 c.updateString(titleIndex, title);
3590 c.commitUpdates();
3591 }
3592 c.close();
3593 } catch (IllegalStateException e) {
3594 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3595 } catch (SQLiteException ex) {
3596 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3597 }
3598 }
3599
3600 @Override
3601 public void onReceivedIcon(WebView view, Bitmap icon) {
3602 updateIcon(view.getUrl(), icon);
3603 }
3604 };
3605
3606 /**
3607 * Notify the host application a download should be done, or that
3608 * the data should be streamed if a streaming viewer is available.
3609 * @param url The full url to the content that should be downloaded
3610 * @param contentDisposition Content-disposition http header, if
3611 * present.
3612 * @param mimetype The mimetype of the content reported by the server
3613 * @param contentLength The file size reported by the server
3614 */
3615 public void onDownloadStart(String url, String userAgent,
3616 String contentDisposition, String mimetype, long contentLength) {
3617 // if we're dealing wih A/V content that's not explicitly marked
3618 // for download, check if it's streamable.
3619 if (contentDisposition == null
3620 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3621 // query the package manager to see if there's a registered handler
3622 // that matches.
3623 Intent intent = new Intent(Intent.ACTION_VIEW);
3624 intent.setDataAndType(Uri.parse(url), mimetype);
3625 if (getPackageManager().resolveActivity(intent,
3626 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3627 // someone knows how to handle this mime type with this scheme, don't download.
3628 try {
3629 startActivity(intent);
3630 return;
3631 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003632 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 Log.d(LOGTAG, "activity not found for " + mimetype
3634 + " over " + Uri.parse(url).getScheme(), ex);
3635 }
3636 // Best behavior is to fall back to a download in this case
3637 }
3638 }
3639 }
3640 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3641 }
3642
3643 /**
3644 * Notify the host application a download should be done, even if there
3645 * is a streaming viewer available for thise type.
3646 * @param url The full url to the content that should be downloaded
3647 * @param contentDisposition Content-disposition http header, if
3648 * present.
3649 * @param mimetype The mimetype of the content reported by the server
3650 * @param contentLength The file size reported by the server
3651 */
3652 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3653 String contentDisposition, String mimetype, long contentLength) {
3654
3655 String filename = URLUtil.guessFileName(url,
3656 contentDisposition, mimetype);
3657
3658 // Check to see if we have an SDCard
3659 String status = Environment.getExternalStorageState();
3660 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3661 int title;
3662 String msg;
3663
3664 // Check to see if the SDCard is busy, same as the music app
3665 if (status.equals(Environment.MEDIA_SHARED)) {
3666 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3667 title = R.string.download_sdcard_busy_dlg_title;
3668 } else {
3669 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3670 title = R.string.download_no_sdcard_dlg_title;
3671 }
3672
3673 new AlertDialog.Builder(this)
3674 .setTitle(title)
3675 .setIcon(android.R.drawable.ic_dialog_alert)
3676 .setMessage(msg)
3677 .setPositiveButton(R.string.ok, null)
3678 .show();
3679 return;
3680 }
3681
3682 // java.net.URI is a lot stricter than KURL so we have to undo
3683 // KURL's percent-encoding and redo the encoding using java.net.URI.
3684 URI uri = null;
3685 try {
3686 // Undo the percent-encoding that KURL may have done.
3687 String newUrl = new String(URLUtil.decode(url.getBytes()));
3688 // Parse the url into pieces
3689 WebAddress w = new WebAddress(newUrl);
3690 String frag = null;
3691 String query = null;
3692 String path = w.mPath;
3693 // Break the path into path, query, and fragment
3694 if (path.length() > 0) {
3695 // Strip the fragment
3696 int idx = path.lastIndexOf('#');
3697 if (idx != -1) {
3698 frag = path.substring(idx + 1);
3699 path = path.substring(0, idx);
3700 }
3701 idx = path.lastIndexOf('?');
3702 if (idx != -1) {
3703 query = path.substring(idx + 1);
3704 path = path.substring(0, idx);
3705 }
3706 }
3707 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3708 query, frag);
3709 } catch (Exception e) {
3710 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3711 return;
3712 }
3713
3714 // XXX: Have to use the old url since the cookies were stored using the
3715 // old percent-encoded url.
3716 String cookies = CookieManager.getInstance().getCookie(url);
3717
3718 ContentValues values = new ContentValues();
3719 values.put(Downloads.URI, uri.toString());
3720 values.put(Downloads.COOKIE_DATA, cookies);
3721 values.put(Downloads.USER_AGENT, userAgent);
3722 values.put(Downloads.NOTIFICATION_PACKAGE,
3723 getPackageName());
3724 values.put(Downloads.NOTIFICATION_CLASS,
3725 BrowserDownloadPage.class.getCanonicalName());
3726 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3727 values.put(Downloads.MIMETYPE, mimetype);
3728 values.put(Downloads.FILENAME_HINT, filename);
3729 values.put(Downloads.DESCRIPTION, uri.getHost());
3730 if (contentLength > 0) {
3731 values.put(Downloads.TOTAL_BYTES, contentLength);
3732 }
3733 if (mimetype == null) {
3734 // We must have long pressed on a link or image to download it. We
3735 // are not sure of the mimetype in this case, so do a head request
3736 new FetchUrlMimeType(this).execute(values);
3737 } else {
3738 final Uri contentUri =
3739 getContentResolver().insert(Downloads.CONTENT_URI, values);
3740 viewDownloads(contentUri);
3741 }
3742
3743 }
3744
3745 /**
3746 * Resets the lock icon. This method is called when we start a new load and
3747 * know the url to be loaded.
3748 */
3749 private void resetLockIcon(String url) {
3750 // Save the lock-icon state (we revert to it if the load gets cancelled)
3751 saveLockIcon();
3752
3753 mLockIconType = LOCK_ICON_UNSECURE;
3754 if (URLUtil.isHttpsUrl(url)) {
3755 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003756 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003757 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3758 " reset lock icon to " + mLockIconType);
3759 }
3760 }
3761
3762 updateLockIconImage(LOCK_ICON_UNSECURE);
3763 }
3764
3765 /**
3766 * Resets the lock icon. This method is called when the icon needs to be
3767 * reset but we do not know whether we are loading a secure or not secure
3768 * page.
3769 */
3770 private void resetLockIcon() {
3771 // Save the lock-icon state (we revert to it if the load gets cancelled)
3772 saveLockIcon();
3773
3774 mLockIconType = LOCK_ICON_UNSECURE;
3775
Dave Bort31a6d1c2009-04-13 15:56:49 -07003776 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3778 " reset lock icon to " + mLockIconType);
3779 }
3780
3781 updateLockIconImage(LOCK_ICON_UNSECURE);
3782 }
3783
3784 /**
3785 * Updates the lock-icon image in the title-bar.
3786 */
3787 private void updateLockIconImage(int lockIconType) {
3788 Drawable d = null;
3789 if (lockIconType == LOCK_ICON_SECURE) {
3790 d = mSecLockIcon;
3791 } else if (lockIconType == LOCK_ICON_MIXED) {
3792 d = mMixLockIcon;
3793 }
3794 // If the tab overview is animating or being shown, do not update the
3795 // lock icon.
3796 if (mAnimationCount == 0 && mTabOverview == null) {
3797 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3798 }
3799 }
3800
3801 /**
3802 * Displays a page-info dialog.
3803 * @param tab The tab to show info about
3804 * @param fromShowSSLCertificateOnError The flag that indicates whether
3805 * this dialog was opened from the SSL-certificate-on-error dialog or
3806 * not. This is important, since we need to know whether to return to
3807 * the parent dialog or simply dismiss.
3808 */
3809 private void showPageInfo(final TabControl.Tab tab,
3810 final boolean fromShowSSLCertificateOnError) {
3811 final LayoutInflater factory = LayoutInflater
3812 .from(this);
3813
3814 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3815
3816 final WebView view = tab.getWebView();
3817
3818 String url = null;
3819 String title = null;
3820
3821 if (view == null) {
3822 url = tab.getUrl();
3823 title = tab.getTitle();
3824 } else if (view == mTabControl.getCurrentWebView()) {
3825 // Use the cached title and url if this is the current WebView
3826 url = mUrl;
3827 title = mTitle;
3828 } else {
3829 url = view.getUrl();
3830 title = view.getTitle();
3831 }
3832
3833 if (url == null) {
3834 url = "";
3835 }
3836 if (title == null) {
3837 title = "";
3838 }
3839
3840 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3841 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3842
3843 mPageInfoView = tab;
3844 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3845
3846 AlertDialog.Builder alertDialogBuilder =
3847 new AlertDialog.Builder(this)
3848 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3849 .setView(pageInfoView)
3850 .setPositiveButton(
3851 R.string.ok,
3852 new DialogInterface.OnClickListener() {
3853 public void onClick(DialogInterface dialog,
3854 int whichButton) {
3855 mPageInfoDialog = null;
3856 mPageInfoView = null;
3857 mPageInfoFromShowSSLCertificateOnError = null;
3858
3859 // if we came here from the SSL error dialog
3860 if (fromShowSSLCertificateOnError) {
3861 // go back to the SSL error dialog
3862 showSSLCertificateOnError(
3863 mSSLCertificateOnErrorView,
3864 mSSLCertificateOnErrorHandler,
3865 mSSLCertificateOnErrorError);
3866 }
3867 }
3868 })
3869 .setOnCancelListener(
3870 new DialogInterface.OnCancelListener() {
3871 public void onCancel(DialogInterface dialog) {
3872 mPageInfoDialog = null;
3873 mPageInfoView = null;
3874 mPageInfoFromShowSSLCertificateOnError = null;
3875
3876 // if we came here from the SSL error dialog
3877 if (fromShowSSLCertificateOnError) {
3878 // go back to the SSL error dialog
3879 showSSLCertificateOnError(
3880 mSSLCertificateOnErrorView,
3881 mSSLCertificateOnErrorHandler,
3882 mSSLCertificateOnErrorError);
3883 }
3884 }
3885 });
3886
3887 // if we have a main top-level page SSL certificate set or a certificate
3888 // error
3889 if (fromShowSSLCertificateOnError ||
3890 (view != null && view.getCertificate() != null)) {
3891 // add a 'View Certificate' button
3892 alertDialogBuilder.setNeutralButton(
3893 R.string.view_certificate,
3894 new DialogInterface.OnClickListener() {
3895 public void onClick(DialogInterface dialog,
3896 int whichButton) {
3897 mPageInfoDialog = null;
3898 mPageInfoView = null;
3899 mPageInfoFromShowSSLCertificateOnError = null;
3900
3901 // if we came here from the SSL error dialog
3902 if (fromShowSSLCertificateOnError) {
3903 // go back to the SSL error dialog
3904 showSSLCertificateOnError(
3905 mSSLCertificateOnErrorView,
3906 mSSLCertificateOnErrorHandler,
3907 mSSLCertificateOnErrorError);
3908 } else {
3909 // otherwise, display the top-most certificate from
3910 // the chain
3911 if (view.getCertificate() != null) {
3912 showSSLCertificate(tab);
3913 }
3914 }
3915 }
3916 });
3917 }
3918
3919 mPageInfoDialog = alertDialogBuilder.show();
3920 }
3921
3922 /**
3923 * Displays the main top-level page SSL certificate dialog
3924 * (accessible from the Page-Info dialog).
3925 * @param tab The tab to show certificate for.
3926 */
3927 private void showSSLCertificate(final TabControl.Tab tab) {
3928 final View certificateView =
3929 inflateCertificateView(tab.getWebView().getCertificate());
3930 if (certificateView == null) {
3931 return;
3932 }
3933
3934 LayoutInflater factory = LayoutInflater.from(this);
3935
3936 final LinearLayout placeholder =
3937 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3938
3939 LinearLayout ll = (LinearLayout) factory.inflate(
3940 R.layout.ssl_success, placeholder);
3941 ((TextView)ll.findViewById(R.id.success))
3942 .setText(R.string.ssl_certificate_is_valid);
3943
3944 mSSLCertificateView = tab;
3945 mSSLCertificateDialog =
3946 new AlertDialog.Builder(this)
3947 .setTitle(R.string.ssl_certificate).setIcon(
3948 R.drawable.ic_dialog_browser_certificate_secure)
3949 .setView(certificateView)
3950 .setPositiveButton(R.string.ok,
3951 new DialogInterface.OnClickListener() {
3952 public void onClick(DialogInterface dialog,
3953 int whichButton) {
3954 mSSLCertificateDialog = null;
3955 mSSLCertificateView = null;
3956
3957 showPageInfo(tab, false);
3958 }
3959 })
3960 .setOnCancelListener(
3961 new DialogInterface.OnCancelListener() {
3962 public void onCancel(DialogInterface dialog) {
3963 mSSLCertificateDialog = null;
3964 mSSLCertificateView = null;
3965
3966 showPageInfo(tab, false);
3967 }
3968 })
3969 .show();
3970 }
3971
3972 /**
3973 * Displays the SSL error certificate dialog.
3974 * @param view The target web-view.
3975 * @param handler The SSL error handler responsible for cancelling the
3976 * connection that resulted in an SSL error or proceeding per user request.
3977 * @param error The SSL error object.
3978 */
3979 private void showSSLCertificateOnError(
3980 final WebView view, final SslErrorHandler handler, final SslError error) {
3981
3982 final View certificateView =
3983 inflateCertificateView(error.getCertificate());
3984 if (certificateView == null) {
3985 return;
3986 }
3987
3988 LayoutInflater factory = LayoutInflater.from(this);
3989
3990 final LinearLayout placeholder =
3991 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3992
3993 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3994 LinearLayout ll = (LinearLayout)factory
3995 .inflate(R.layout.ssl_warning, placeholder);
3996 ((TextView)ll.findViewById(R.id.warning))
3997 .setText(R.string.ssl_untrusted);
3998 }
3999
4000 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4001 LinearLayout ll = (LinearLayout)factory
4002 .inflate(R.layout.ssl_warning, placeholder);
4003 ((TextView)ll.findViewById(R.id.warning))
4004 .setText(R.string.ssl_mismatch);
4005 }
4006
4007 if (error.hasError(SslError.SSL_EXPIRED)) {
4008 LinearLayout ll = (LinearLayout)factory
4009 .inflate(R.layout.ssl_warning, placeholder);
4010 ((TextView)ll.findViewById(R.id.warning))
4011 .setText(R.string.ssl_expired);
4012 }
4013
4014 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4015 LinearLayout ll = (LinearLayout)factory
4016 .inflate(R.layout.ssl_warning, placeholder);
4017 ((TextView)ll.findViewById(R.id.warning))
4018 .setText(R.string.ssl_not_yet_valid);
4019 }
4020
4021 mSSLCertificateOnErrorHandler = handler;
4022 mSSLCertificateOnErrorView = view;
4023 mSSLCertificateOnErrorError = error;
4024 mSSLCertificateOnErrorDialog =
4025 new AlertDialog.Builder(this)
4026 .setTitle(R.string.ssl_certificate).setIcon(
4027 R.drawable.ic_dialog_browser_certificate_partially_secure)
4028 .setView(certificateView)
4029 .setPositiveButton(R.string.ok,
4030 new DialogInterface.OnClickListener() {
4031 public void onClick(DialogInterface dialog,
4032 int whichButton) {
4033 mSSLCertificateOnErrorDialog = null;
4034 mSSLCertificateOnErrorView = null;
4035 mSSLCertificateOnErrorHandler = null;
4036 mSSLCertificateOnErrorError = null;
4037
4038 mWebViewClient.onReceivedSslError(
4039 view, handler, error);
4040 }
4041 })
4042 .setNeutralButton(R.string.page_info_view,
4043 new DialogInterface.OnClickListener() {
4044 public void onClick(DialogInterface dialog,
4045 int whichButton) {
4046 mSSLCertificateOnErrorDialog = null;
4047
4048 // do not clear the dialog state: we will
4049 // need to show the dialog again once the
4050 // user is done exploring the page-info details
4051
4052 showPageInfo(mTabControl.getTabFromView(view),
4053 true);
4054 }
4055 })
4056 .setOnCancelListener(
4057 new DialogInterface.OnCancelListener() {
4058 public void onCancel(DialogInterface dialog) {
4059 mSSLCertificateOnErrorDialog = null;
4060 mSSLCertificateOnErrorView = null;
4061 mSSLCertificateOnErrorHandler = null;
4062 mSSLCertificateOnErrorError = null;
4063
4064 mWebViewClient.onReceivedSslError(
4065 view, handler, error);
4066 }
4067 })
4068 .show();
4069 }
4070
4071 /**
4072 * Inflates the SSL certificate view (helper method).
4073 * @param certificate The SSL certificate.
4074 * @return The resultant certificate view with issued-to, issued-by,
4075 * issued-on, expires-on, and possibly other fields set.
4076 * If the input certificate is null, returns null.
4077 */
4078 private View inflateCertificateView(SslCertificate certificate) {
4079 if (certificate == null) {
4080 return null;
4081 }
4082
4083 LayoutInflater factory = LayoutInflater.from(this);
4084
4085 View certificateView = factory.inflate(
4086 R.layout.ssl_certificate, null);
4087
4088 // issued to:
4089 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4090 if (issuedTo != null) {
4091 ((TextView) certificateView.findViewById(R.id.to_common))
4092 .setText(issuedTo.getCName());
4093 ((TextView) certificateView.findViewById(R.id.to_org))
4094 .setText(issuedTo.getOName());
4095 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4096 .setText(issuedTo.getUName());
4097 }
4098
4099 // issued by:
4100 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4101 if (issuedBy != null) {
4102 ((TextView) certificateView.findViewById(R.id.by_common))
4103 .setText(issuedBy.getCName());
4104 ((TextView) certificateView.findViewById(R.id.by_org))
4105 .setText(issuedBy.getOName());
4106 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4107 .setText(issuedBy.getUName());
4108 }
4109
4110 // issued on:
4111 String issuedOn = reformatCertificateDate(
4112 certificate.getValidNotBefore());
4113 ((TextView) certificateView.findViewById(R.id.issued_on))
4114 .setText(issuedOn);
4115
4116 // expires on:
4117 String expiresOn = reformatCertificateDate(
4118 certificate.getValidNotAfter());
4119 ((TextView) certificateView.findViewById(R.id.expires_on))
4120 .setText(expiresOn);
4121
4122 return certificateView;
4123 }
4124
4125 /**
4126 * Re-formats the certificate date (Date.toString()) string to
4127 * a properly localized date string.
4128 * @return Properly localized version of the certificate date string and
4129 * the original certificate date string if fails to localize.
4130 * If the original string is null, returns an empty string "".
4131 */
4132 private String reformatCertificateDate(String certificateDate) {
4133 String reformattedDate = null;
4134
4135 if (certificateDate != null) {
4136 Date date = null;
4137 try {
4138 date = java.text.DateFormat.getInstance().parse(certificateDate);
4139 } catch (ParseException e) {
4140 date = null;
4141 }
4142
4143 if (date != null) {
4144 reformattedDate =
4145 DateFormat.getDateFormat(this).format(date);
4146 }
4147 }
4148
4149 return reformattedDate != null ? reformattedDate :
4150 (certificateDate != null ? certificateDate : "");
4151 }
4152
4153 /**
4154 * Displays an http-authentication dialog.
4155 */
4156 private void showHttpAuthentication(final HttpAuthHandler handler,
4157 final String host, final String realm, final String title,
4158 final String name, final String password, int focusId) {
4159 LayoutInflater factory = LayoutInflater.from(this);
4160 final View v = factory
4161 .inflate(R.layout.http_authentication, null);
4162 if (name != null) {
4163 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4164 }
4165 if (password != null) {
4166 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4167 }
4168
4169 String titleText = title;
4170 if (titleText == null) {
4171 titleText = getText(R.string.sign_in_to).toString().replace(
4172 "%s1", host).replace("%s2", realm);
4173 }
4174
4175 mHttpAuthHandler = handler;
4176 AlertDialog dialog = new AlertDialog.Builder(this)
4177 .setTitle(titleText)
4178 .setIcon(android.R.drawable.ic_dialog_alert)
4179 .setView(v)
4180 .setPositiveButton(R.string.action,
4181 new DialogInterface.OnClickListener() {
4182 public void onClick(DialogInterface dialog,
4183 int whichButton) {
4184 String nm = ((EditText) v
4185 .findViewById(R.id.username_edit))
4186 .getText().toString();
4187 String pw = ((EditText) v
4188 .findViewById(R.id.password_edit))
4189 .getText().toString();
4190 BrowserActivity.this.setHttpAuthUsernamePassword
4191 (host, realm, nm, pw);
4192 handler.proceed(nm, pw);
4193 mHttpAuthenticationDialog = null;
4194 mHttpAuthHandler = null;
4195 }})
4196 .setNegativeButton(R.string.cancel,
4197 new DialogInterface.OnClickListener() {
4198 public void onClick(DialogInterface dialog,
4199 int whichButton) {
4200 handler.cancel();
4201 BrowserActivity.this.resetTitleAndRevertLockIcon();
4202 mHttpAuthenticationDialog = null;
4203 mHttpAuthHandler = null;
4204 }})
4205 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4206 public void onCancel(DialogInterface dialog) {
4207 handler.cancel();
4208 BrowserActivity.this.resetTitleAndRevertLockIcon();
4209 mHttpAuthenticationDialog = null;
4210 mHttpAuthHandler = null;
4211 }})
4212 .create();
4213 // Make the IME appear when the dialog is displayed if applicable.
4214 dialog.getWindow().setSoftInputMode(
4215 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4216 dialog.show();
4217 if (focusId != 0) {
4218 dialog.findViewById(focusId).requestFocus();
4219 } else {
4220 v.findViewById(R.id.username_edit).requestFocus();
4221 }
4222 mHttpAuthenticationDialog = dialog;
4223 }
4224
4225 public int getProgress() {
4226 WebView w = mTabControl.getCurrentWebView();
4227 if (w != null) {
4228 return w.getProgress();
4229 } else {
4230 return 100;
4231 }
4232 }
4233
4234 /**
4235 * Set HTTP authentication password.
4236 *
4237 * @param host The host for the password
4238 * @param realm The realm for the password
4239 * @param username The username for the password. If it is null, it means
4240 * password can't be saved.
4241 * @param password The password
4242 */
4243 public void setHttpAuthUsernamePassword(String host, String realm,
4244 String username,
4245 String password) {
4246 WebView w = mTabControl.getCurrentWebView();
4247 if (w != null) {
4248 w.setHttpAuthUsernamePassword(host, realm, username, password);
4249 }
4250 }
4251
4252 /**
4253 * connectivity manager says net has come or gone... inform the user
4254 * @param up true if net has come up, false if net has gone down
4255 */
4256 public void onNetworkToggle(boolean up) {
4257 if (up == mIsNetworkUp) {
4258 return;
4259 } else if (up) {
4260 mIsNetworkUp = true;
4261 if (mAlertDialog != null) {
4262 mAlertDialog.cancel();
4263 mAlertDialog = null;
4264 }
4265 } else {
4266 mIsNetworkUp = false;
4267 if (mInLoad && mAlertDialog == null) {
4268 mAlertDialog = new AlertDialog.Builder(this)
4269 .setTitle(R.string.loadSuspendedTitle)
4270 .setMessage(R.string.loadSuspended)
4271 .setPositiveButton(R.string.ok, null)
4272 .show();
4273 }
4274 }
4275 WebView w = mTabControl.getCurrentWebView();
4276 if (w != null) {
4277 w.setNetworkAvailable(up);
4278 }
4279 }
4280
4281 @Override
4282 protected void onActivityResult(int requestCode, int resultCode,
4283 Intent intent) {
4284 switch (requestCode) {
4285 case COMBO_PAGE:
4286 if (resultCode == RESULT_OK && intent != null) {
4287 String data = intent.getAction();
4288 Bundle extras = intent.getExtras();
4289 if (extras != null && extras.getBoolean("new_window", false)) {
4290 openTab(data);
4291 } else {
4292 final TabControl.Tab currentTab =
4293 mTabControl.getCurrentTab();
4294 // If the Window overview is up and we are not in the
4295 // middle of an animation, animate away from it to the
4296 // current tab.
4297 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004298 sendAnimateFromOverview(currentTab, false, new UrlData(data),
The Android Open Source Project0c908882009-03-03 19:32:16 -08004299 TAB_OVERVIEW_DELAY, null);
4300 } else {
4301 dismissSubWindow(currentTab);
4302 if (data != null && data.length() != 0) {
4303 getTopWindow().loadUrl(data);
4304 }
4305 }
4306 }
4307 }
4308 break;
4309 default:
4310 break;
4311 }
4312 getTopWindow().requestFocus();
4313 }
4314
4315 /*
4316 * This method is called as a result of the user selecting the options
4317 * menu to see the download window, or when a download changes state. It
4318 * shows the download window ontop of the current window.
4319 */
4320 /* package */ void viewDownloads(Uri downloadRecord) {
4321 Intent intent = new Intent(this,
4322 BrowserDownloadPage.class);
4323 intent.setData(downloadRecord);
4324 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4325
4326 }
4327
4328 /**
4329 * Handle results from Tab Switcher mTabOverview tool
4330 */
4331 private class TabListener implements ImageGrid.Listener {
4332 public void remove(int position) {
4333 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004334 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004335 throw new AssertionError();
4336 }
4337
4338 // Remember the current tab.
4339 TabControl.Tab current = mTabControl.getCurrentTab();
4340 final TabControl.Tab remove = mTabControl.getTab(position);
4341 mTabControl.removeTab(remove);
4342 // If we removed the current tab, use the tab at position - 1 if
4343 // possible.
4344 if (current == remove) {
4345 // If the user removes the last tab, act like the New Tab item
4346 // was clicked on.
4347 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004348 current = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004349 sendAnimateFromOverview(current, true,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004350 new UrlData(mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004351 } else {
4352 final int index = position > 0 ? (position - 1) : 0;
4353 current = mTabControl.getTab(index);
4354 }
4355 }
4356
4357 // The tab overview could have been dismissed before this method is
4358 // called.
4359 if (mTabOverview != null) {
4360 // Remove the tab and change the index.
4361 mTabOverview.remove(position);
4362 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4363 }
4364
4365 // Only the current tab ensures its WebView is non-null. This
4366 // implies that we are reloading the freed tab.
4367 mTabControl.setCurrentTab(current);
4368 }
4369 public void onClick(int index) {
4370 // Change the tab if necessary.
4371 // Index equals ImageGrid.CANCEL when pressing back from the tab
4372 // overview.
4373 if (index == ImageGrid.CANCEL) {
4374 index = mTabControl.getCurrentIndex();
4375 // The current index is -1 if the current tab was removed.
4376 if (index == -1) {
4377 // Take the last tab as a fallback.
4378 index = mTabControl.getTabCount() - 1;
4379 }
4380 }
4381
The Android Open Source Project0c908882009-03-03 19:32:16 -08004382 // NEW_TAB means that the "New Tab" cell was clicked on.
4383 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004384 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004385 } else {
4386 sendAnimateFromOverview(mTabControl.getTab(index),
Patrick Scott95d601f2009-06-11 10:06:46 -04004387 false, EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004388 }
4389 }
4390 }
4391
4392 // A fake View that draws the WebView's picture with a fast zoom filter.
4393 // The View is used in case the tab is freed during the animation because
4394 // of low memory.
4395 private static class AnimatingView extends View {
4396 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4397 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4398 private static final DrawFilter sZoomFilter =
4399 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4400 private final Picture mPicture;
4401 private final float mScale;
4402 private final int mScrollX;
4403 private final int mScrollY;
4404 final TabControl.Tab mTab;
4405
4406 AnimatingView(Context ctxt, TabControl.Tab t) {
4407 super(ctxt);
4408 mTab = t;
4409 // Use the top window in the animation since the tab overview will
4410 // display the top window in each cell.
4411 final WebView w = t.getTopWindow();
4412 mPicture = w.capturePicture();
4413 mScale = w.getScale() / w.getWidth();
4414 mScrollX = w.getScrollX();
4415 mScrollY = w.getScrollY();
4416 }
4417
4418 @Override
4419 protected void onDraw(Canvas canvas) {
4420 canvas.save();
4421 canvas.drawColor(Color.WHITE);
4422 if (mPicture != null) {
4423 canvas.setDrawFilter(sZoomFilter);
4424 float scale = getWidth() * mScale;
4425 canvas.scale(scale, scale);
4426 canvas.translate(-mScrollX, -mScrollY);
4427 canvas.drawPicture(mPicture);
4428 }
4429 canvas.restore();
4430 }
4431 }
4432
4433 /**
4434 * Open the tab picker. This function will always use the current tab in
4435 * its animation.
4436 * @param stay boolean stating whether the tab picker is to remain open
4437 * (in which case it needs a listener and its menu) or not.
4438 * @param index The index of the tab to show as the selection in the tab
4439 * overview.
4440 * @param remove If true, the tab at index will be removed after the
4441 * animation completes.
4442 */
4443 private void tabPicker(final boolean stay, final int index,
4444 final boolean remove) {
4445 if (mTabOverview != null) {
4446 return;
4447 }
4448
4449 int size = mTabControl.getTabCount();
4450
4451 TabListener l = null;
4452 if (stay) {
4453 l = mTabListener = new TabListener();
4454 }
4455 mTabOverview = new ImageGrid(this, stay, l);
4456
4457 for (int i = 0; i < size; i++) {
4458 final TabControl.Tab t = mTabControl.getTab(i);
4459 mTabControl.populatePickerData(t);
4460 mTabOverview.add(t);
4461 }
4462
4463 // Tell the tab overview to show the current tab, the tab overview will
4464 // handle the "New Tab" case.
4465 int currentIndex = mTabControl.getCurrentIndex();
4466 mTabOverview.setCurrentIndex(currentIndex);
4467
4468 // Attach the tab overview.
4469 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4470
4471 // Create a fake AnimatingView to animate the WebView's picture.
4472 final TabControl.Tab current = mTabControl.getCurrentTab();
4473 final AnimatingView v = new AnimatingView(this, current);
4474 mContentView.addView(v, COVER_SCREEN_PARAMS);
4475 removeTabFromContentView(current);
4476 // Pause timers to get the animation smoother.
4477 current.getWebView().pauseTimers();
4478
4479 // Send a message so the tab picker has a chance to layout and get
4480 // positions for all the cells.
4481 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4482 index, remove ? 1 : 0, v));
4483 // Setting this will indicate that we are animating to the overview. We
4484 // set it here to prevent another request to animate from coming in
4485 // between now and when ANIMATE_TO_OVERVIEW is handled.
4486 mAnimationCount++;
4487 // Always change the title bar to the window overview title while
4488 // animating.
4489 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4490 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4491 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4492 Window.PROGRESS_VISIBILITY_OFF);
4493 setTitle(R.string.tab_picker_title);
4494 // Make the menu empty until the animation completes.
4495 mMenuState = EMPTY_MENU;
4496 }
4497
4498 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4499 WebView current = mTabControl.getCurrentWebView();
4500 if (current == null) {
4501 return;
4502 }
4503 Intent intent = new Intent(this,
4504 CombinedBookmarkHistoryActivity.class);
4505 String title = current.getTitle();
4506 String url = current.getUrl();
4507 // Just in case the user opens bookmarks before a page finishes loading
4508 // so the current history item, and therefore the page, is null.
4509 if (null == url) {
4510 url = mLastEnteredUrl;
4511 // This can happen.
4512 if (null == url) {
4513 url = mSettings.getHomePage();
4514 }
4515 }
4516 // In case the web page has not yet received its associated title.
4517 if (title == null) {
4518 title = url;
4519 }
4520 intent.putExtra("title", title);
4521 intent.putExtra("url", url);
4522 intent.putExtra("maxTabsOpen",
4523 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4524 if (startWithHistory) {
4525 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4526 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4527 }
4528 startActivityForResult(intent, COMBO_PAGE);
4529 }
4530
4531 // Called when loading from context menu or LOAD_URL message
4532 private void loadURL(WebView view, String url) {
4533 // In case the user enters nothing.
4534 if (url != null && url.length() != 0 && view != null) {
4535 url = smartUrlFilter(url);
4536 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4537 view.loadUrl(url);
4538 }
4539 }
4540 }
4541
4542 private void checkMemory() {
4543 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4544 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4545 .getMemoryInfo(mi);
4546 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4547 // mi.threshold) for now
4548 // if (mi.lowMemory) {
4549 if (mi.availMem < mi.threshold) {
4550 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4551 + (mi.availMem / 1024) + "K threshold="
4552 + (mi.threshold / 1024) + "K");
4553 mTabControl.freeMemory();
4554 }
4555 }
4556
4557 private String smartUrlFilter(Uri inUri) {
4558 if (inUri != null) {
4559 return smartUrlFilter(inUri.toString());
4560 }
4561 return null;
4562 }
4563
4564
4565 // get window count
4566
4567 int getWindowCount(){
4568 if(mTabControl != null){
4569 return mTabControl.getTabCount();
4570 }
4571 return 0;
4572 }
4573
4574 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4575 "(?i)" + // switch on case insensitive matching
4576 "(" + // begin group for schema
4577 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004578 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004579 ")" +
4580 "(.*)" );
4581
4582 /**
4583 * Attempts to determine whether user input is a URL or search
4584 * terms. Anything with a space is passed to search.
4585 *
4586 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4587 * "Http://" converts to "http://"
4588 *
4589 * @return Original or modified URL
4590 *
4591 */
4592 String smartUrlFilter(String url) {
4593
4594 String inUrl = url.trim();
4595 boolean hasSpace = inUrl.indexOf(' ') != -1;
4596
4597 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4598 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004599 // force scheme to lowercase
4600 String scheme = matcher.group(1);
4601 String lcScheme = scheme.toLowerCase();
4602 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004603 inUrl = lcScheme + matcher.group(2);
4604 }
4605 if (hasSpace) {
4606 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004607 }
4608 return inUrl;
4609 }
4610 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004611 // FIXME: Is this the correct place to add to searches?
4612 // what if someone else calls this function?
4613 int shortcut = parseUrlShortcut(inUrl);
4614 if (shortcut != SHORTCUT_INVALID) {
4615 Browser.addSearchUrl(mResolver, inUrl);
4616 String query = inUrl.substring(2);
4617 switch (shortcut) {
4618 case SHORTCUT_GOOGLE_SEARCH:
4619 return composeSearchUrl(query);
4620 case SHORTCUT_WIKIPEDIA_SEARCH:
4621 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4622 case SHORTCUT_DICTIONARY_SEARCH:
4623 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4624 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004625 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004626 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004627 }
4628 }
4629 } else {
4630 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4631 return URLUtil.guessUrl(inUrl);
4632 }
4633 }
4634
4635 Browser.addSearchUrl(mResolver, inUrl);
4636 return composeSearchUrl(inUrl);
4637 }
4638
4639 /* package */ String composeSearchUrl(String search) {
4640 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4641 QUERY_PLACE_HOLDER);
4642 }
4643
4644 /* package */void setBaseSearchUrl(String url) {
4645 if (url == null || url.length() == 0) {
4646 /*
4647 * get the google search url based on the SIM. Default is US. NOTE:
4648 * This code uses resources to optionally select the search Uri,
4649 * based on the MCC value from the SIM. The default string will most
4650 * likely be fine. It is parameterized to accept info from the
4651 * Locale, the language code is the first parameter (%1$s) and the
4652 * country code is the second (%2$s). This code must function in the
4653 * same way as a similar lookup in
4654 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4655 * change either of these functions, change them both. (The same is
4656 * true for the underlying resource strings, which are stored in
4657 * mcc-specific xml files.)
4658 */
4659 Locale l = Locale.getDefault();
Bill Napiere9651c32009-05-05 13:16:30 -07004660 String language = l.getLanguage();
4661 String country = l.getCountry().toLowerCase();
4662 // Chinese and Portuguese have two langauge variants.
4663 if ("zh".equals(language)) {
4664 if ("cn".equals(country)) {
4665 language = "zh-CN";
4666 } else if ("tw".equals(country)) {
4667 language = "zh-TW";
4668 }
4669 } else if ("pt".equals(language)) {
4670 if ("br".equals(country)) {
4671 language = "pt-BR";
4672 } else if ("pt".equals(country)) {
4673 language = "pt-PT";
4674 }
4675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004676 QuickSearch_G = getResources().getString(
Bill Napiere9651c32009-05-05 13:16:30 -07004677 R.string.google_search_base,
4678 language,
4679 country)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004680 + "client=ms-"
Ramanan Rajeswaranf447f262009-03-24 20:40:12 -07004681 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004682 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4683 } else {
4684 QuickSearch_G = url;
4685 }
4686 }
4687
4688 private final static int LOCK_ICON_UNSECURE = 0;
4689 private final static int LOCK_ICON_SECURE = 1;
4690 private final static int LOCK_ICON_MIXED = 2;
4691
4692 private int mLockIconType = LOCK_ICON_UNSECURE;
4693 private int mPrevLockType = LOCK_ICON_UNSECURE;
4694
4695 private BrowserSettings mSettings;
4696 private TabControl mTabControl;
4697 private ContentResolver mResolver;
4698 private FrameLayout mContentView;
4699 private ImageGrid mTabOverview;
4700
4701 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4702 // view, we should rewrite this.
4703 private int mCurrentMenuState = 0;
4704 private int mMenuState = R.id.MAIN_MENU;
4705 private static final int EMPTY_MENU = -1;
4706 private Menu mMenu;
4707
4708 private FindDialog mFindDialog;
4709 // Used to prevent chording to result in firing two shortcuts immediately
4710 // one after another. Fixes bug 1211714.
4711 boolean mCanChord;
4712
4713 private boolean mInLoad;
4714 private boolean mIsNetworkUp;
4715
4716 private boolean mPageStarted;
4717 private boolean mActivityInPause = true;
4718
4719 private boolean mMenuIsDown;
4720
4721 private final KeyTracker mKeyTracker = new KeyTracker(this);
4722
4723 // As trackball doesn't send repeat down, we have to track it ourselves
4724 private boolean mTrackTrackball;
4725
4726 private static boolean mInTrace;
4727
4728 // Performance probe
4729 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4730 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4731 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4732 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4733 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4734 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4735 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4736 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4737 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4738 };
4739
4740 private long mStart;
4741 private long mProcessStart;
4742 private long mUserStart;
4743 private long mSystemStart;
4744 private long mIdleStart;
4745 private long mIrqStart;
4746
4747 private long mUiStart;
4748
4749 private Drawable mMixLockIcon;
4750 private Drawable mSecLockIcon;
4751 private Drawable mGenericFavicon;
4752
4753 /* hold a ref so we can auto-cancel if necessary */
4754 private AlertDialog mAlertDialog;
4755
4756 // Wait for credentials before loading google.com
4757 private ProgressDialog mCredsDlg;
4758
4759 // The up-to-date URL and title (these can be different from those stored
4760 // in WebView, since it takes some time for the information in WebView to
4761 // get updated)
4762 private String mUrl;
4763 private String mTitle;
4764
4765 // As PageInfo has different style for landscape / portrait, we have
4766 // to re-open it when configuration changed
4767 private AlertDialog mPageInfoDialog;
4768 private TabControl.Tab mPageInfoView;
4769 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4770 // dialog, we should not just dismiss it, but should get back to the
4771 // SSL-certificate-on-error dialog. This flag is used to store this state
4772 private Boolean mPageInfoFromShowSSLCertificateOnError;
4773
4774 // as SSLCertificateOnError has different style for landscape / portrait,
4775 // we have to re-open it when configuration changed
4776 private AlertDialog mSSLCertificateOnErrorDialog;
4777 private WebView mSSLCertificateOnErrorView;
4778 private SslErrorHandler mSSLCertificateOnErrorHandler;
4779 private SslError mSSLCertificateOnErrorError;
4780
4781 // as SSLCertificate has different style for landscape / portrait, we
4782 // have to re-open it when configuration changed
4783 private AlertDialog mSSLCertificateDialog;
4784 private TabControl.Tab mSSLCertificateView;
4785
4786 // as HttpAuthentication has different style for landscape / portrait, we
4787 // have to re-open it when configuration changed
4788 private AlertDialog mHttpAuthenticationDialog;
4789 private HttpAuthHandler mHttpAuthHandler;
4790
4791 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4792 new FrameLayout.LayoutParams(
4793 ViewGroup.LayoutParams.FILL_PARENT,
4794 ViewGroup.LayoutParams.FILL_PARENT);
4795 // We may provide UI to customize these
4796 // Google search from the browser
4797 static String QuickSearch_G;
4798 // Wikipedia search
4799 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4800 // Dictionary search
4801 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4802 // Google Mobile Local search
4803 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4804
4805 final static String QUERY_PLACE_HOLDER = "%s";
4806
4807 // "source" parameter for Google search through search key
4808 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4809 // "source" parameter for Google search through goto menu
4810 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4811 // "source" parameter for Google search through simplily type
4812 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4813 // "source" parameter for Google search suggested by the browser
4814 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4815 // "source" parameter for Google search from unknown source
4816 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4817
4818 private final static String LOGTAG = "browser";
4819
4820 private TabListener mTabListener;
4821
4822 private String mLastEnteredUrl;
4823
4824 private PowerManager.WakeLock mWakeLock;
4825 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4826
4827 private Toast mStopToast;
4828
4829 // Used during animations to prevent other animations from being triggered.
4830 // A count is used since the animation to and from the Window overview can
4831 // overlap. A count of 0 means no animation where a count of > 0 means
4832 // there are animations in progress.
4833 private int mAnimationCount;
4834
4835 // As the ids are dynamically created, we can't guarantee that they will
4836 // be in sequence, so this static array maps ids to a window number.
4837 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4838 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4839 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4840 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4841
4842 // monitor platform changes
4843 private IntentFilter mNetworkStateChangedFilter;
4844 private BroadcastReceiver mNetworkStateIntentReceiver;
4845
4846 // activity requestCode
4847 final static int COMBO_PAGE = 1;
4848 final static int DOWNLOAD_PAGE = 2;
4849 final static int PREFERENCES_PAGE = 3;
4850
4851 // the frenquency of checking whether system memory is low
4852 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004853
4854 /**
4855 * A UrlData class to abstract how the content will be set to WebView.
4856 * This base class uses loadUrl to show the content.
4857 */
4858 private static class UrlData {
4859 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004860 byte[] mPostData;
4861
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004862 UrlData(String url) {
4863 this.mUrl = url;
4864 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004865
4866 void setPostData(byte[] postData) {
4867 mPostData = postData;
4868 }
4869
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004870 boolean isEmpty() {
4871 return mUrl == null || mUrl.length() == 0;
4872 }
4873
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004874 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004875 if (mPostData != null) {
4876 webView.postUrl(mUrl, mPostData);
4877 } else {
4878 webView.loadUrl(mUrl);
4879 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004880 }
4881 };
4882
4883 /**
4884 * A subclass of UrlData class that can display inlined content using
4885 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4886 */
4887 private static class InlinedUrlData extends UrlData {
4888 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4889 super(failUrl);
4890 mInlined = inlined;
4891 mMimeType = mimeType;
4892 mEncoding = encoding;
4893 }
4894 String mMimeType;
4895 String mInlined;
4896 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004897 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004898 boolean isEmpty() {
4899 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4900 }
4901
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004902 @Override
4903 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004904 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4905 }
4906 }
4907
4908 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004909}