blob: 8fb853fd4f30a946cbd2da19e8ec6a7e1c6b512d [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 }
908 return handleWebSearchRequest(url);
909 }
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 */
916 private boolean handleWebSearchRequest(String inUrl) {
917 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);
937 startActivity(intent);
938
939 return true;
940 }
941
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700942 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800943 String url = null;
944 if (intent != null) {
945 final String action = intent.getAction();
946 if (Intent.ACTION_VIEW.equals(action)) {
947 url = smartUrlFilter(intent.getData());
948 if (url != null && url.startsWith("content:")) {
949 /* Append mimetype so webview knows how to display */
950 String mimeType = intent.resolveType(getContentResolver());
951 if (mimeType != null) {
952 url += "?" + mimeType;
953 }
954 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700955 if ("inline:".equals(url)) {
956 return new InlinedUrlData(
957 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
958 intent.getType(),
959 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
960 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
961 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 } else if (Intent.ACTION_SEARCH.equals(action)
963 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
964 || Intent.ACTION_WEB_SEARCH.equals(action)) {
965 url = intent.getStringExtra(SearchManager.QUERY);
966 if (url != null) {
967 mLastEnteredUrl = url;
968 // Don't add Urls, just search terms.
969 // Urls will get added when the page is loaded.
970 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
971 Browser.updateVisitedHistory(mResolver, url, false);
972 }
973 // In general, we shouldn't modify URL from Intent.
974 // But currently, we get the user-typed URL from search box as well.
975 url = fixUrl(url);
976 url = smartUrlFilter(url);
977 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
978 if (url.contains(searchSource)) {
979 String source = null;
980 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
981 if (appData != null) {
982 source = appData.getString(SearchManager.SOURCE);
983 }
984 if (TextUtils.isEmpty(source)) {
985 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
986 }
987 url = url.replace(searchSource, "&source=android-"+source+"&");
988 }
989 }
990 }
991 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700992 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 }
994
Grace Kloba60e095c2009-06-16 11:50:55 -0700995 byte[] getLocationData(Intent intent) {
996 byte[] postData = null;
997 if (intent != null) {
998 final String action = intent.getAction();
999 if (Intent.ACTION_VIEW.equals(action)
1000 && intent.getBooleanExtra(Browser.EXTRA_APPEND_LOCATION,
1001 false)) {
1002 ContentResolver cr = getContentResolver();
1003 int use = Settings.Gservices.getInt(cr,
1004 Settings.Gservices.USE_LOCATION_FOR_SERVICES, -1);
1005 if (use == -1) {
1006 // TODO: bring up the consent dialog
1007 } else if (use == 1
1008 && Settings.Secure.isLocationProviderEnabled(cr,
1009 LocationManager.NETWORK_PROVIDER)) {
1010 Location location = ((LocationManager) getSystemService(
1011 Context.LOCATION_SERVICE)).getLastKnownLocation(
1012 LocationManager.NETWORK_PROVIDER);
1013 if (location != null) {
1014 StringBuilder str = new StringBuilder(
1015 "action=devloc&sll=");
1016 str.append(location.getLatitude()).append(',').append(
1017 location.getLongitude());
1018 postData = str.toString().getBytes();
1019 }
1020 }
1021 }
1022 }
1023 return postData;
1024 }
1025
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 /* package */ static String fixUrl(String inUrl) {
1027 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
1028 return inUrl;
1029 if (inUrl.startsWith("http:") ||
1030 inUrl.startsWith("https:")) {
1031 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
1032 inUrl = inUrl.replaceFirst("/", "//");
1033 } else inUrl = inUrl.replaceFirst(":", "://");
1034 }
1035 return inUrl;
1036 }
1037
1038 /**
1039 * Looking for the pattern like this
1040 *
1041 * *
1042 * * *
1043 * *** * *******
1044 * * *
1045 * * *
1046 * *
1047 */
1048 private final SensorListener mSensorListener = new SensorListener() {
1049 private long mLastGestureTime;
1050 private float[] mPrev = new float[3];
1051 private float[] mPrevDiff = new float[3];
1052 private float[] mDiff = new float[3];
1053 private float[] mRevertDiff = new float[3];
1054
1055 public void onSensorChanged(int sensor, float[] values) {
1056 boolean show = false;
1057 float[] diff = new float[3];
1058
1059 for (int i = 0; i < 3; i++) {
1060 diff[i] = values[i] - mPrev[i];
1061 if (Math.abs(diff[i]) > 1) {
1062 show = true;
1063 }
1064 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
1065 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
1066 // start track when there is a big move, or revert
1067 mRevertDiff[i] = mDiff[i];
1068 mDiff[i] = 0;
1069 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1070 // reset when it is flat
1071 mDiff[i] = mRevertDiff[i] = 0;
1072 }
1073 mDiff[i] += diff[i];
1074 mPrevDiff[i] = diff[i];
1075 mPrev[i] = values[i];
1076 }
1077
1078 if (false) {
1079 // only shows if we think the delta is big enough, in an attempt
1080 // to detect "serious" moves left/right or up/down
1081 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
1082 + values[0] + ", " + values[1] + ", " + values[2] + ")"
1083 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
1084 + ")");
1085 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1086 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1087 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1088 + mRevertDiff[2] + ")");
1089 }
1090
1091 long now = android.os.SystemClock.uptimeMillis();
1092 if (now - mLastGestureTime > 1000) {
1093 mLastGestureTime = 0;
1094
1095 float y = mDiff[1];
1096 float z = mDiff[2];
1097 float ay = Math.abs(y);
1098 float az = Math.abs(z);
1099 float ry = mRevertDiff[1];
1100 float rz = mRevertDiff[2];
1101 float ary = Math.abs(ry);
1102 float arz = Math.abs(rz);
1103 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
1104 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
1105
1106 if ((gestY || gestZ) && !(gestY && gestZ)) {
1107 WebView view = mTabControl.getCurrentWebView();
1108
1109 if (view != null) {
1110 if (gestZ) {
1111 if (z < 0) {
1112 view.zoomOut();
1113 } else {
1114 view.zoomIn();
1115 }
1116 } else {
1117 view.flingScroll(0, Math.round(y * 100));
1118 }
1119 }
1120 mLastGestureTime = now;
1121 }
1122 }
1123 }
1124
1125 public void onAccuracyChanged(int sensor, int accuracy) {
1126 // TODO Auto-generated method stub
1127
1128 }
1129 };
1130
1131 @Override protected void onResume() {
1132 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -07001133 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1135 }
1136
1137 if (!mActivityInPause) {
1138 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1139 return;
1140 }
1141
1142 mActivityInPause = false;
1143 resumeWebView();
1144
1145 if (mWakeLock.isHeld()) {
1146 mHandler.removeMessages(RELEASE_WAKELOCK);
1147 mWakeLock.release();
1148 }
1149
1150 if (mCredsDlg != null) {
1151 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
1152 // In case credential request never comes back
1153 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
1154 }
1155 }
1156
1157 registerReceiver(mNetworkStateIntentReceiver,
1158 mNetworkStateChangedFilter);
1159 WebView.enablePlatformNotifications();
1160
1161 if (mSettings.doFlick()) {
1162 if (mSensorManager == null) {
1163 mSensorManager = (SensorManager) getSystemService(
1164 Context.SENSOR_SERVICE);
1165 }
1166 mSensorManager.registerListener(mSensorListener,
1167 SensorManager.SENSOR_ACCELEROMETER,
1168 SensorManager.SENSOR_DELAY_FASTEST);
1169 } else {
1170 mSensorManager = null;
1171 }
1172 }
1173
1174 /**
1175 * onSaveInstanceState(Bundle map)
1176 * onSaveInstanceState is called right before onStop(). The map contains
1177 * the saved state.
1178 */
1179 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001180 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1182 }
1183 // the default implementation requires each view to have an id. As the
1184 // browser handles the state itself and it doesn't use id for the views,
1185 // don't call the default implementation. Otherwise it will trigger the
1186 // warning like this, "couldn't save which view has focus because the
1187 // focused view XXX has no id".
1188
1189 // Save all the tabs
1190 mTabControl.saveState(outState);
1191 }
1192
1193 @Override protected void onPause() {
1194 super.onPause();
1195
1196 if (mActivityInPause) {
1197 Log.e(LOGTAG, "BrowserActivity is already paused.");
1198 return;
1199 }
1200
1201 mActivityInPause = true;
1202 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebView()) {
1203 mWakeLock.acquire();
1204 mHandler.sendMessageDelayed(mHandler
1205 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1206 }
1207
1208 // Clear the credentials toast if it is up
1209 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1210 mCredsDlg.dismiss();
1211 }
1212 mCredsDlg = null;
1213
1214 cancelStopToast();
1215
1216 // unregister network state listener
1217 unregisterReceiver(mNetworkStateIntentReceiver);
1218 WebView.disablePlatformNotifications();
1219
1220 if (mSensorManager != null) {
1221 mSensorManager.unregisterListener(mSensorListener);
1222 }
1223 }
1224
1225 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001226 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1228 }
1229 super.onDestroy();
1230 // Remove the current tab and sub window
1231 TabControl.Tab t = mTabControl.getCurrentTab();
1232 dismissSubWindow(t);
1233 removeTabFromContentView(t);
1234 // Destroy all the tabs
1235 mTabControl.destroy();
1236 WebIconDatabase.getInstance().close();
1237 if (mGlsConnection != null) {
1238 unbindService(mGlsConnection);
1239 mGlsConnection = null;
1240 }
1241
1242 //
1243 // stop MASF proxy service
1244 //
1245 //Intent proxyServiceIntent = new Intent();
1246 //proxyServiceIntent.setComponent
1247 // (new ComponentName(
1248 // "com.android.masfproxyservice",
1249 // "com.android.masfproxyservice.MasfProxyService"));
1250 //stopService(proxyServiceIntent);
1251 }
1252
1253 @Override
1254 public void onConfigurationChanged(Configuration newConfig) {
1255 super.onConfigurationChanged(newConfig);
1256
1257 if (mPageInfoDialog != null) {
1258 mPageInfoDialog.dismiss();
1259 showPageInfo(
1260 mPageInfoView,
1261 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1262 }
1263 if (mSSLCertificateDialog != null) {
1264 mSSLCertificateDialog.dismiss();
1265 showSSLCertificate(
1266 mSSLCertificateView);
1267 }
1268 if (mSSLCertificateOnErrorDialog != null) {
1269 mSSLCertificateOnErrorDialog.dismiss();
1270 showSSLCertificateOnError(
1271 mSSLCertificateOnErrorView,
1272 mSSLCertificateOnErrorHandler,
1273 mSSLCertificateOnErrorError);
1274 }
1275 if (mHttpAuthenticationDialog != null) {
1276 String title = ((TextView) mHttpAuthenticationDialog
1277 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1278 .toString();
1279 String name = ((TextView) mHttpAuthenticationDialog
1280 .findViewById(R.id.username_edit)).getText().toString();
1281 String password = ((TextView) mHttpAuthenticationDialog
1282 .findViewById(R.id.password_edit)).getText().toString();
1283 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1284 .getId();
1285 mHttpAuthenticationDialog.dismiss();
1286 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1287 name, password, focusId);
1288 }
1289 if (mFindDialog != null && mFindDialog.isShowing()) {
1290 mFindDialog.onConfigurationChanged(newConfig);
1291 }
1292 }
1293
1294 @Override public void onLowMemory() {
1295 super.onLowMemory();
1296 mTabControl.freeMemory();
1297 }
1298
1299 private boolean resumeWebView() {
1300 if ((!mActivityInPause && !mPageStarted) ||
1301 (mActivityInPause && mPageStarted)) {
1302 CookieSyncManager.getInstance().startSync();
1303 WebView w = mTabControl.getCurrentWebView();
1304 if (w != null) {
1305 w.resumeTimers();
1306 }
1307 return true;
1308 } else {
1309 return false;
1310 }
1311 }
1312
1313 private boolean pauseWebView() {
1314 if (mActivityInPause && !mPageStarted) {
1315 CookieSyncManager.getInstance().stopSync();
1316 WebView w = mTabControl.getCurrentWebView();
1317 if (w != null) {
1318 w.pauseTimers();
1319 }
1320 return true;
1321 } else {
1322 return false;
1323 }
1324 }
1325
1326 /*
1327 * This function is called when we are launching for the first time. We
1328 * are waiting for the login credentials before loading Google home
1329 * pages. This way the user will be logged in straight away.
1330 */
1331 private void waitForCredentials() {
1332 // Show a toast
1333 mCredsDlg = new ProgressDialog(this);
1334 mCredsDlg.setIndeterminate(true);
1335 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1336 // If the user cancels the operation, then cancel the Google
1337 // Credentials request.
1338 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1339 mCredsDlg.show();
1340
1341 // We set a timeout for the retrieval of credentials in onResume()
1342 // as that is when we have freed up some CPU time to get
1343 // the login credentials.
1344 }
1345
1346 /*
1347 * If we have received the credentials or we have timed out and we are
1348 * showing the credentials dialog, then it is time to move on.
1349 */
1350 private void resumeAfterCredentials() {
1351 if (mCredsDlg == null) {
1352 return;
1353 }
1354
1355 // Clear the toast
1356 if (mCredsDlg.isShowing()) {
1357 mCredsDlg.dismiss();
1358 }
1359 mCredsDlg = null;
1360
1361 // Clear any pending timeout
1362 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1363
1364 // Load the page
1365 WebView w = mTabControl.getCurrentWebView();
1366 if (w != null) {
1367 w.loadUrl(mSettings.getHomePage());
1368 }
1369
1370 // Update the settings, need to do this last as it can take a moment
1371 // to persist the settings. In the mean time we could be loading
1372 // content.
1373 mSettings.setLoginInitialized(this);
1374 }
1375
1376 // Open the icon database and retain all the icons for visited sites.
1377 private void retainIconsOnStartup() {
1378 final WebIconDatabase db = WebIconDatabase.getInstance();
1379 db.open(getDir("icons", 0).getPath());
1380 try {
1381 Cursor c = Browser.getAllBookmarks(mResolver);
1382 if (!c.moveToFirst()) {
1383 c.deactivate();
1384 return;
1385 }
1386 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1387 do {
1388 String url = c.getString(urlIndex);
1389 db.retainIconForPageUrl(url);
1390 } while (c.moveToNext());
1391 c.deactivate();
1392 } catch (IllegalStateException e) {
1393 Log.e(LOGTAG, "retainIconsOnStartup", e);
1394 }
1395 }
1396
1397 // Helper method for getting the top window.
1398 WebView getTopWindow() {
1399 return mTabControl.getCurrentTopWebView();
1400 }
1401
1402 @Override
1403 public boolean onCreateOptionsMenu(Menu menu) {
1404 super.onCreateOptionsMenu(menu);
1405
1406 MenuInflater inflater = getMenuInflater();
1407 inflater.inflate(R.menu.browser, menu);
1408 mMenu = menu;
1409 updateInLoadMenuItems();
1410 return true;
1411 }
1412
1413 /**
1414 * As the menu can be open when loading state changes
1415 * we must manually update the state of the stop/reload menu
1416 * item
1417 */
1418 private void updateInLoadMenuItems() {
1419 if (mMenu == null) {
1420 return;
1421 }
1422 MenuItem src = mInLoad ?
1423 mMenu.findItem(R.id.stop_menu_id):
1424 mMenu.findItem(R.id.reload_menu_id);
1425 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1426 dest.setIcon(src.getIcon());
1427 dest.setTitle(src.getTitle());
1428 }
1429
1430 @Override
1431 public boolean onContextItemSelected(MenuItem item) {
1432 // chording is not an issue with context menus, but we use the same
1433 // options selector, so set mCanChord to true so we can access them.
1434 mCanChord = true;
1435 int id = item.getItemId();
1436 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001437 if (null == webView) {
1438 return false;
1439 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 final HashMap hrefMap = new HashMap();
1441 hrefMap.put("webview", webView);
1442 final Message msg = mHandler.obtainMessage(
1443 FOCUS_NODE_HREF, id, 0, hrefMap);
1444 switch (id) {
1445 // -- Browser context menu
1446 case R.id.open_context_menu_id:
1447 case R.id.open_newtab_context_menu_id:
1448 case R.id.bookmark_context_menu_id:
1449 case R.id.save_link_context_menu_id:
1450 case R.id.share_link_context_menu_id:
1451 case R.id.copy_link_context_menu_id:
1452 webView.requestFocusNodeHref(msg);
1453 break;
1454
1455 default:
1456 // For other context menus
1457 return onOptionsItemSelected(item);
1458 }
1459 mCanChord = false;
1460 return true;
1461 }
1462
1463 private Bundle createGoogleSearchSourceBundle(String source) {
1464 Bundle bundle = new Bundle();
1465 bundle.putString(SearchManager.SOURCE, source);
1466 return bundle;
1467 }
1468
1469 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001470 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 */
1472 @Override
1473 public boolean onSearchRequested() {
1474 startSearch(null, false,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001475 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 return true;
1477 }
1478
1479 @Override
1480 public void startSearch(String initialQuery, boolean selectInitialQuery,
1481 Bundle appSearchData, boolean globalSearch) {
1482 if (appSearchData == null) {
1483 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1484 }
1485 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1486 }
1487
1488 @Override
1489 public boolean onOptionsItemSelected(MenuItem item) {
1490 if (!mCanChord) {
1491 // The user has already fired a shortcut with this hold down of the
1492 // menu key.
1493 return false;
1494 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001495 if (null == mTabOverview && null == getTopWindow()) {
1496 return false;
1497 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 switch (item.getItemId()) {
1499 // -- Main menu
1500 case R.id.goto_menu_id: {
1501 String url = getTopWindow().getUrl();
1502 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1503 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1504 }
1505 break;
1506
1507 case R.id.bookmarks_menu_id:
1508 bookmarksOrHistoryPicker(false);
1509 break;
1510
1511 case R.id.windows_menu_id:
1512 if (mTabControl.getTabCount() == 1) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001513 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 } else {
1515 tabPicker(true, mTabControl.getCurrentIndex(), false);
1516 }
1517 break;
1518
1519 case R.id.stop_reload_menu_id:
1520 if (mInLoad) {
1521 stopLoading();
1522 } else {
1523 getTopWindow().reload();
1524 }
1525 break;
1526
1527 case R.id.back_menu_id:
1528 getTopWindow().goBack();
1529 break;
1530
1531 case R.id.forward_menu_id:
1532 getTopWindow().goForward();
1533 break;
1534
1535 case R.id.close_menu_id:
1536 // Close the subwindow if it exists.
1537 if (mTabControl.getCurrentSubWindow() != null) {
1538 dismissSubWindow(mTabControl.getCurrentTab());
1539 break;
1540 }
1541 final int currentIndex = mTabControl.getCurrentIndex();
1542 final TabControl.Tab parent =
1543 mTabControl.getCurrentTab().getParentTab();
1544 int indexToShow = -1;
1545 if (parent != null) {
1546 indexToShow = mTabControl.getTabIndex(parent);
1547 } else {
1548 // Get the last tab in the list. If it is the current tab,
1549 // subtract 1 more.
1550 indexToShow = mTabControl.getTabCount() - 1;
1551 if (currentIndex == indexToShow) {
1552 indexToShow--;
1553 }
1554 }
1555 switchTabs(currentIndex, indexToShow, true);
1556 break;
1557
1558 case R.id.homepage_menu_id:
1559 TabControl.Tab current = mTabControl.getCurrentTab();
1560 if (current != null) {
1561 dismissSubWindow(current);
1562 current.getWebView().loadUrl(mSettings.getHomePage());
1563 }
1564 break;
1565
1566 case R.id.preferences_menu_id:
1567 Intent intent = new Intent(this,
1568 BrowserPreferencesPage.class);
1569 startActivityForResult(intent, PREFERENCES_PAGE);
1570 break;
1571
1572 case R.id.find_menu_id:
1573 if (null == mFindDialog) {
1574 mFindDialog = new FindDialog(this);
1575 }
1576 mFindDialog.setWebView(getTopWindow());
1577 mFindDialog.show();
1578 mMenuState = EMPTY_MENU;
1579 break;
1580
1581 case R.id.select_text_id:
1582 getTopWindow().emulateShiftHeld();
1583 break;
1584 case R.id.page_info_menu_id:
1585 showPageInfo(mTabControl.getCurrentTab(), false);
1586 break;
1587
1588 case R.id.classic_history_menu_id:
1589 bookmarksOrHistoryPicker(true);
1590 break;
1591
1592 case R.id.share_page_menu_id:
1593 Browser.sendString(this, getTopWindow().getUrl());
1594 break;
1595
1596 case R.id.dump_nav_menu_id:
1597 getTopWindow().debugDump();
1598 break;
1599
1600 case R.id.zoom_in_menu_id:
1601 getTopWindow().zoomIn();
1602 break;
1603
1604 case R.id.zoom_out_menu_id:
1605 getTopWindow().zoomOut();
1606 break;
1607
1608 case R.id.view_downloads_menu_id:
1609 viewDownloads(null);
1610 break;
1611
1612 // -- Tab menu
1613 case R.id.view_tab_menu_id:
1614 if (mTabListener != null && mTabOverview != null) {
1615 int pos = mTabOverview.getContextMenuPosition(item);
1616 mTabOverview.setCurrentIndex(pos);
1617 mTabListener.onClick(pos);
1618 }
1619 break;
1620
1621 case R.id.remove_tab_menu_id:
1622 if (mTabListener != null && mTabOverview != null) {
1623 int pos = mTabOverview.getContextMenuPosition(item);
1624 mTabListener.remove(pos);
1625 }
1626 break;
1627
1628 case R.id.new_tab_menu_id:
1629 // No need to check for mTabOverview here since we are not
1630 // dependent on it for a position.
1631 if (mTabListener != null) {
1632 // If the overview happens to be non-null, make the "New
1633 // Tab" cell visible.
1634 if (mTabOverview != null) {
1635 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1636 }
1637 mTabListener.onClick(ImageGrid.NEW_TAB);
1638 }
1639 break;
1640
1641 case R.id.bookmark_tab_menu_id:
1642 if (mTabListener != null && mTabOverview != null) {
1643 int pos = mTabOverview.getContextMenuPosition(item);
1644 TabControl.Tab t = mTabControl.getTab(pos);
1645 // Since we called populatePickerData for all of the
1646 // tabs, getTitle and getUrl will return appropriate
1647 // values.
1648 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1649 t.getUrl());
1650 }
1651 break;
1652
1653 case R.id.history_tab_menu_id:
1654 bookmarksOrHistoryPicker(true);
1655 break;
1656
1657 case R.id.bookmarks_tab_menu_id:
1658 bookmarksOrHistoryPicker(false);
1659 break;
1660
1661 case R.id.properties_tab_menu_id:
1662 if (mTabListener != null && mTabOverview != null) {
1663 int pos = mTabOverview.getContextMenuPosition(item);
1664 showPageInfo(mTabControl.getTab(pos), false);
1665 }
1666 break;
1667
1668 case R.id.window_one_menu_id:
1669 case R.id.window_two_menu_id:
1670 case R.id.window_three_menu_id:
1671 case R.id.window_four_menu_id:
1672 case R.id.window_five_menu_id:
1673 case R.id.window_six_menu_id:
1674 case R.id.window_seven_menu_id:
1675 case R.id.window_eight_menu_id:
1676 {
1677 int menuid = item.getItemId();
1678 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1679 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1680 TabControl.Tab desiredTab = mTabControl.getTab(id);
1681 if (desiredTab != null &&
1682 desiredTab != mTabControl.getCurrentTab()) {
1683 switchTabs(mTabControl.getCurrentIndex(), id, false);
1684 }
1685 break;
1686 }
1687 }
1688 }
1689 break;
1690
1691 default:
1692 if (!super.onOptionsItemSelected(item)) {
1693 return false;
1694 }
1695 // Otherwise fall through.
1696 }
1697 mCanChord = false;
1698 return true;
1699 }
1700
1701 public void closeFind() {
1702 mMenuState = R.id.MAIN_MENU;
1703 }
1704
1705 @Override public boolean onPrepareOptionsMenu(Menu menu)
1706 {
1707 // This happens when the user begins to hold down the menu key, so
1708 // allow them to chord to get a shortcut.
1709 mCanChord = true;
1710 // Note: setVisible will decide whether an item is visible; while
1711 // setEnabled() will decide whether an item is enabled, which also means
1712 // whether the matching shortcut key will function.
1713 super.onPrepareOptionsMenu(menu);
1714 switch (mMenuState) {
1715 case R.id.TAB_MENU:
1716 if (mCurrentMenuState != mMenuState) {
1717 menu.setGroupVisible(R.id.MAIN_MENU, false);
1718 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1719 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1720 menu.setGroupVisible(R.id.TAB_MENU, true);
1721 menu.setGroupEnabled(R.id.TAB_MENU, true);
1722 }
1723 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1724 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1725 tab.setVisible(newT);
1726 tab.setEnabled(newT);
1727 break;
1728 case EMPTY_MENU:
1729 if (mCurrentMenuState != mMenuState) {
1730 menu.setGroupVisible(R.id.MAIN_MENU, false);
1731 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1732 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1733 menu.setGroupVisible(R.id.TAB_MENU, false);
1734 menu.setGroupEnabled(R.id.TAB_MENU, false);
1735 }
1736 break;
1737 default:
1738 if (mCurrentMenuState != mMenuState) {
1739 menu.setGroupVisible(R.id.MAIN_MENU, true);
1740 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1741 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1742 menu.setGroupVisible(R.id.TAB_MENU, false);
1743 menu.setGroupEnabled(R.id.TAB_MENU, false);
1744 }
1745 final WebView w = getTopWindow();
1746 boolean canGoBack = false;
1747 boolean canGoForward = false;
1748 boolean isHome = false;
1749 if (w != null) {
1750 canGoBack = w.canGoBack();
1751 canGoForward = w.canGoForward();
1752 isHome = mSettings.getHomePage().equals(w.getUrl());
1753 }
1754 final MenuItem back = menu.findItem(R.id.back_menu_id);
1755 back.setEnabled(canGoBack);
1756
1757 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1758 home.setEnabled(!isHome);
1759
1760 menu.findItem(R.id.forward_menu_id)
1761 .setEnabled(canGoForward);
1762
1763 // decide whether to show the share link option
1764 PackageManager pm = getPackageManager();
1765 Intent send = new Intent(Intent.ACTION_SEND);
1766 send.setType("text/plain");
1767 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1768 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1769
1770 // If there is only 1 window, the text will be "New window"
1771 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1772 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1773 getString(R.string.view_tabs_condensed) :
1774 getString(R.string.tab_picker_new_tab));
1775
1776 boolean isNavDump = mSettings.isNavDump();
1777 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1778 nav.setVisible(isNavDump);
1779 nav.setEnabled(isNavDump);
1780 break;
1781 }
1782 mCurrentMenuState = mMenuState;
1783 return true;
1784 }
1785
1786 @Override
1787 public void onCreateContextMenu(ContextMenu menu, View v,
1788 ContextMenuInfo menuInfo) {
1789 WebView webview = (WebView) v;
1790 WebView.HitTestResult result = webview.getHitTestResult();
1791 if (result == null) {
1792 return;
1793 }
1794
1795 int type = result.getType();
1796 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1797 Log.w(LOGTAG,
1798 "We should not show context menu when nothing is touched");
1799 return;
1800 }
1801 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1802 // let TextView handles context menu
1803 return;
1804 }
1805
1806 // Note, http://b/issue?id=1106666 is requesting that
1807 // an inflated menu can be used again. This is not available
1808 // yet, so inflate each time (yuk!)
1809 MenuInflater inflater = getMenuInflater();
1810 inflater.inflate(R.menu.browsercontext, menu);
1811
1812 // Show the correct menu group
1813 String extra = result.getExtra();
1814 menu.setGroupVisible(R.id.PHONE_MENU,
1815 type == WebView.HitTestResult.PHONE_TYPE);
1816 menu.setGroupVisible(R.id.EMAIL_MENU,
1817 type == WebView.HitTestResult.EMAIL_TYPE);
1818 menu.setGroupVisible(R.id.GEO_MENU,
1819 type == WebView.HitTestResult.GEO_TYPE);
1820 menu.setGroupVisible(R.id.IMAGE_MENU,
1821 type == WebView.HitTestResult.IMAGE_TYPE
1822 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1823 menu.setGroupVisible(R.id.ANCHOR_MENU,
1824 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1825 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1826
1827 // Setup custom handling depending on the type
1828 switch (type) {
1829 case WebView.HitTestResult.PHONE_TYPE:
1830 menu.setHeaderTitle(Uri.decode(extra));
1831 menu.findItem(R.id.dial_context_menu_id).setIntent(
1832 new Intent(Intent.ACTION_VIEW, Uri
1833 .parse(WebView.SCHEME_TEL + extra)));
1834 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1835 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1836 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1837 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1838 addIntent);
1839 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1840 new Copy(extra));
1841 break;
1842
1843 case WebView.HitTestResult.EMAIL_TYPE:
1844 menu.setHeaderTitle(extra);
1845 menu.findItem(R.id.email_context_menu_id).setIntent(
1846 new Intent(Intent.ACTION_VIEW, Uri
1847 .parse(WebView.SCHEME_MAILTO + extra)));
1848 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1849 new Copy(extra));
1850 break;
1851
1852 case WebView.HitTestResult.GEO_TYPE:
1853 menu.setHeaderTitle(extra);
1854 menu.findItem(R.id.map_context_menu_id).setIntent(
1855 new Intent(Intent.ACTION_VIEW, Uri
1856 .parse(WebView.SCHEME_GEO
1857 + URLEncoder.encode(extra))));
1858 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1859 new Copy(extra));
1860 break;
1861
1862 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1863 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1864 TextView titleView = (TextView) LayoutInflater.from(this)
1865 .inflate(android.R.layout.browser_link_context_header,
1866 null);
1867 titleView.setText(extra);
1868 menu.setHeaderView(titleView);
1869 // decide whether to show the open link in new tab option
1870 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1871 mTabControl.getTabCount() < TabControl.MAX_TABS);
1872 PackageManager pm = getPackageManager();
1873 Intent send = new Intent(Intent.ACTION_SEND);
1874 send.setType("text/plain");
1875 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1876 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1877 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1878 break;
1879 }
1880 // otherwise fall through to handle image part
1881 case WebView.HitTestResult.IMAGE_TYPE:
1882 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1883 menu.setHeaderTitle(extra);
1884 }
1885 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1886 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1887 menu.findItem(R.id.download_context_menu_id).
1888 setOnMenuItemClickListener(new Download(extra));
1889 break;
1890
1891 default:
1892 Log.w(LOGTAG, "We should not get here.");
1893 break;
1894 }
1895 }
1896
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 // Attach the given tab to the content view.
1898 private void attachTabToContentView(TabControl.Tab t) {
1899 final WebView main = t.getWebView();
1900 // Attach the main WebView.
1901 mContentView.addView(main, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 // Attach the sub window if necessary
1903 attachSubWindow(t);
1904 // Request focus on the top window.
1905 t.getTopWindow().requestFocus();
1906 }
1907
1908 // Attach a sub window to the main WebView of the given tab.
1909 private void attachSubWindow(TabControl.Tab t) {
1910 // If a sub window exists, attach it to the content view.
1911 final WebView subView = t.getSubWebView();
1912 if (subView != null) {
1913 final View container = t.getSubWebViewContainer();
1914 mContentView.addView(container, COVER_SCREEN_PARAMS);
1915 subView.requestFocus();
1916 }
1917 }
1918
1919 // Remove the given tab from the content view.
1920 private void removeTabFromContentView(TabControl.Tab t) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07001921 // Remove the main WebView.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 mContentView.removeView(t.getWebView());
1923 // Remove the sub window if it exists.
1924 if (t.getSubWebView() != null) {
1925 mContentView.removeView(t.getSubWebViewContainer());
1926 }
1927 }
1928
1929 // Remove the sub window if it exists. Also called by TabControl when the
1930 // user clicks the 'X' to dismiss a sub window.
1931 /* package */ void dismissSubWindow(TabControl.Tab t) {
1932 final WebView mainView = t.getWebView();
1933 if (t.getSubWebView() != null) {
1934 // Remove the container view and request focus on the main WebView.
1935 mContentView.removeView(t.getSubWebViewContainer());
1936 mainView.requestFocus();
1937 // Tell the TabControl to dismiss the subwindow. This will destroy
1938 // the WebView.
1939 mTabControl.dismissSubWindow(t);
1940 }
1941 }
1942
1943 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1944 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001945 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 final Message msg) {
1947 // Set the current tab.
1948 mTabControl.setCurrentTab(tab);
1949 // Attach the WebView so it will layout.
1950 attachTabToContentView(tab);
1951 // Set the view to invisibile for now.
1952 tab.getWebView().setVisibility(View.INVISIBLE);
1953 // If there is a sub window, make it invisible too.
1954 if (tab.getSubWebView() != null) {
1955 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1956 }
1957 // Create our fake animating view.
1958 final AnimatingView view = new AnimatingView(this, tab);
1959 // Attach it to the view system and make in invisible so it will
1960 // layout but not flash white on the screen.
1961 mContentView.addView(view, COVER_SCREEN_PARAMS);
1962 view.setVisibility(View.INVISIBLE);
1963 // Send the animate message.
1964 final HashMap map = new HashMap();
1965 map.put("view", view);
1966 // Load the url after the AnimatingView has captured the picture. This
1967 // prevents any bad layout or bad scale from being used during
1968 // animation.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001969 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 dismissSubWindow(tab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001971 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 }
1973 map.put("msg", msg);
1974 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1975 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1976 // Increment the count to indicate that we are in an animation.
1977 mAnimationCount++;
1978 // Remove the listener so we don't get any more tab changes.
1979 mTabOverview.setListener(null);
1980 mTabListener = null;
1981 // Make the menu empty until the animation completes.
1982 mMenuState = EMPTY_MENU;
1983
1984 }
1985
1986 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04001987 private static final int TAB_ANIMATION_DURATION = 200;
1988 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989
1990 // Called by TabControl when a tab is requesting focus
1991 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04001992 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001993 }
1994
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001995 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 // Disallow focus change during a tab animation.
1997 if (mAnimationCount > 0) {
1998 return;
1999 }
2000 int delay = 0;
2001 if (mTabOverview == null) {
2002 // Add a delay so the tab overview can be shown before the second
2003 // animation begins.
2004 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2005 tabPicker(false, mTabControl.getTabIndex(t), false);
2006 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002007 sendAnimateFromOverview(t, false, urlData, delay, null);
2008 }
2009
2010 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2011 // that accepts url as string.
2012 private void openTabAndShow(String url, final Message msg,
2013 boolean closeOnExit, String appId) {
2014 openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 }
2016
2017 // This method does a ton of stuff. It will attempt to create a new tab
2018 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2019 // url isn't null, it will load the given url. If the tab overview is not
2020 // showing, it will animate to the tab overview, create a new tab and
2021 // animate away from it. After the animation completes, it will dispatch
2022 // the given Message. If the tab overview is already showing (i.e. this
2023 // method is called from TabListener.onClick(), the method will animate
2024 // away from the tab overview.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002025 private void openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002026 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2028 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2029 if (newTab) {
2030 int delay = 0;
2031 // If the tab overview is up and there are animations, just load
2032 // the url.
2033 if (mTabOverview != null && mAnimationCount > 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002034 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 // We should not have a msg here since onCreateWindow
2036 // checks the animation count and every other caller passes
2037 // null.
2038 assert msg == null;
2039 // just dismiss the subwindow and load the given url.
2040 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002041 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 }
2043 } else {
2044 // show mTabOverview if it is not there.
2045 if (mTabOverview == null) {
2046 // We have to delay the animation from the tab picker by the
2047 // length of the tab animation. Add a delay so the tab
2048 // overview can be shown before the second animation begins.
2049 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2050 tabPicker(false, ImageGrid.NEW_TAB, false);
2051 }
2052 // Animate from the Tab overview after any animations have
2053 // finished.
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002054 sendAnimateFromOverview(
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002055 mTabControl.createNewTab(closeOnExit, appId, urlData.mUrl), true,
2056 urlData, delay, msg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002058 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 // We should not have a msg here.
2060 assert msg == null;
2061 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002062 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 TAB_OVERVIEW_DELAY, null);
2064 } else {
2065 // Get rid of the subwindow if it exists
2066 dismissSubWindow(currentTab);
2067 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002068 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 }
2070 }
2071 }
2072
2073 private Animation createTabAnimation(final AnimatingView view,
2074 final View cell, boolean scaleDown) {
2075 final AnimationSet set = new AnimationSet(true);
2076 final float scaleX = (float) cell.getWidth() / view.getWidth();
2077 final float scaleY = (float) cell.getHeight() / view.getHeight();
2078 if (scaleDown) {
2079 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2080 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2081 cell.getTop()));
2082 } else {
2083 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2084 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2085 cell.getTop(), 0));
2086 }
2087 set.setDuration(TAB_ANIMATION_DURATION);
2088 set.setInterpolator(new DecelerateInterpolator());
2089 return set;
2090 }
2091
2092 // Animate to the tab overview. currentIndex tells us which position to
2093 // animate to and newIndex is the position that should be selected after
2094 // the animation completes.
2095 // If remove is true, after the animation stops, a confirmation dialog will
2096 // be displayed to the user.
2097 private void animateToTabOverview(final int newIndex, final boolean remove,
2098 final AnimatingView view) {
2099 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2100 int position = mTabControl.getTabIndex(view.mTab);
2101 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2102 position++;
2103 }
2104
2105 // Offset the tab position with the first visible position to get a
2106 // number between 0 and 3.
2107 position -= mTabOverview.getFirstVisiblePosition();
2108
2109 // Grab the view that we are going to animate to.
2110 final View v = mTabOverview.getChildAt(position);
2111
2112 final Animation.AnimationListener l =
2113 new Animation.AnimationListener() {
2114 public void onAnimationStart(Animation a) {
2115 mTabOverview.requestFocus();
2116 // Clear the listener so we don't trigger a tab
2117 // selection.
2118 mTabOverview.setListener(null);
2119 }
2120 public void onAnimationRepeat(Animation a) {}
2121 public void onAnimationEnd(Animation a) {
2122 // We are no longer animating so decrement the count.
2123 mAnimationCount--;
2124 // Make the view GONE so that it will not draw between
2125 // now and when the Runnable is handled.
2126 view.setVisibility(View.GONE);
2127 // Post a runnable since we can't modify the view
2128 // hierarchy during this callback.
2129 mHandler.post(new Runnable() {
2130 public void run() {
2131 // Remove the AnimatingView.
2132 mContentView.removeView(view);
2133 if (mTabOverview != null) {
2134 // Make newIndex visible.
2135 mTabOverview.setCurrentIndex(newIndex);
2136 // Restore the listener.
2137 mTabOverview.setListener(mTabListener);
2138 // Change the menu to TAB_MENU if the
2139 // ImageGrid is interactive.
2140 if (mTabOverview.isLive()) {
2141 mMenuState = R.id.TAB_MENU;
2142 mTabOverview.requestFocus();
2143 }
2144 }
2145 // If a remove was requested, remove the tab.
2146 if (remove) {
2147 // During a remove, the current tab has
2148 // already changed. Remember the current one
2149 // here.
2150 final TabControl.Tab currentTab =
2151 mTabControl.getCurrentTab();
2152 // Remove the tab at newIndex from
2153 // TabControl and the tab overview.
2154 final TabControl.Tab tab =
2155 mTabControl.getTab(newIndex);
2156 mTabControl.removeTab(tab);
2157 // Restore the current tab.
2158 if (currentTab != tab) {
2159 mTabControl.setCurrentTab(currentTab);
2160 }
2161 if (mTabOverview != null) {
2162 mTabOverview.remove(newIndex);
2163 // Make the current tab visible.
2164 mTabOverview.setCurrentIndex(
2165 mTabControl.getCurrentIndex());
2166 }
2167 }
2168 }
2169 });
2170 }
2171 };
2172
2173 // Do an animation if there is a view to animate to.
2174 if (v != null) {
2175 // Create our animation
2176 final Animation anim = createTabAnimation(view, v, true);
2177 anim.setAnimationListener(l);
2178 // Start animating
2179 view.startAnimation(anim);
2180 } else {
2181 // If something goes wrong and we didn't find a view to animate to,
2182 // just do everything here.
2183 l.onAnimationStart(null);
2184 l.onAnimationEnd(null);
2185 }
2186 }
2187
2188 // Animate from the tab picker. The index supplied is the index to animate
2189 // from.
2190 private void animateFromTabOverview(final AnimatingView view,
2191 final boolean newTab, final Message msg) {
2192 // firstVisible is the first visible tab on the screen. This helps
2193 // to know which corner of the screen the selected tab is.
2194 int firstVisible = mTabOverview.getFirstVisiblePosition();
2195 // tabPosition is the 0-based index of of the tab being opened
2196 int tabPosition = mTabControl.getTabIndex(view.mTab);
2197 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2198 // Add one to make room for the "New Tab" cell.
2199 tabPosition++;
2200 }
2201 // If this is a new tab, animate from the "New Tab" cell.
2202 if (newTab) {
2203 tabPosition = 0;
2204 }
2205 // Location corresponds to the four corners of the screen.
2206 // A new tab or 0 is upper left, 0 for an old tab is upper
2207 // right, 1 is lower left, and 2 is lower right
2208 int location = tabPosition - firstVisible;
2209
2210 // Find the view at this location.
2211 final View v = mTabOverview.getChildAt(location);
2212
2213 // Wait until the animation completes to replace the AnimatingView.
2214 final Animation.AnimationListener l =
2215 new Animation.AnimationListener() {
2216 public void onAnimationStart(Animation a) {}
2217 public void onAnimationRepeat(Animation a) {}
2218 public void onAnimationEnd(Animation a) {
2219 mHandler.post(new Runnable() {
2220 public void run() {
2221 mContentView.removeView(view);
2222 // Dismiss the tab overview. If the cell at the
2223 // given location is null, set the fade
2224 // parameter to true.
2225 dismissTabOverview(v == null);
2226 TabControl.Tab t =
2227 mTabControl.getCurrentTab();
2228 mMenuState = R.id.MAIN_MENU;
2229 // Resume regular updates.
2230 t.getWebView().resumeTimers();
2231 // Dispatch the message after the animation
2232 // completes.
2233 if (msg != null) {
2234 msg.sendToTarget();
2235 }
2236 // The animation is done and the tab overview is
2237 // gone so allow key events and other animations
2238 // to begin.
2239 mAnimationCount--;
2240 // Reset all the title bar info.
2241 resetTitle();
2242 }
2243 });
2244 }
2245 };
2246
2247 if (v != null) {
2248 final Animation anim = createTabAnimation(view, v, false);
2249 // Set the listener and start animating
2250 anim.setAnimationListener(l);
2251 view.startAnimation(anim);
2252 // Make the view VISIBLE during the animation.
2253 view.setVisibility(View.VISIBLE);
2254 } else {
2255 // Go ahead and do all the cleanup.
2256 l.onAnimationEnd(null);
2257 }
2258 }
2259
2260 // Dismiss the tab overview applying a fade if needed.
2261 private void dismissTabOverview(final boolean fade) {
2262 if (fade) {
2263 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2264 anim.setDuration(500);
2265 anim.startNow();
2266 mTabOverview.startAnimation(anim);
2267 }
2268 // Just in case there was a problem with animating away from the tab
2269 // overview
2270 WebView current = mTabControl.getCurrentWebView();
2271 if (current != null) {
2272 current.setVisibility(View.VISIBLE);
2273 } else {
2274 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2275 }
2276 // Make the sub window container visible.
2277 if (mTabControl.getCurrentSubWindow() != null) {
2278 mTabControl.getCurrentTab().getSubWebViewContainer()
2279 .setVisibility(View.VISIBLE);
2280 }
2281 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002282 // Clear all the data for tab picker so next time it will be
2283 // recreated.
2284 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 mTabOverview.clear();
2286 mTabOverview = null;
2287 mTabListener = null;
2288 }
2289
2290 private void openTab(String url) {
2291 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002292 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 if (t != null) {
2294 t.getWebView().loadUrl(url);
2295 }
2296 } else {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002297 openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 }
2299 }
2300
2301 private class Copy implements OnMenuItemClickListener {
2302 private CharSequence mText;
2303
2304 public boolean onMenuItemClick(MenuItem item) {
2305 copy(mText);
2306 return true;
2307 }
2308
2309 public Copy(CharSequence toCopy) {
2310 mText = toCopy;
2311 }
2312 }
2313
2314 private class Download implements OnMenuItemClickListener {
2315 private String mText;
2316
2317 public boolean onMenuItemClick(MenuItem item) {
2318 onDownloadStartNoStream(mText, null, null, null, -1);
2319 return true;
2320 }
2321
2322 public Download(String toDownload) {
2323 mText = toDownload;
2324 }
2325 }
2326
2327 private void copy(CharSequence text) {
2328 try {
2329 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2330 if (clip != null) {
2331 clip.setClipboardText(text);
2332 }
2333 } catch (android.os.RemoteException e) {
2334 Log.e(LOGTAG, "Copy failed", e);
2335 }
2336 }
2337
2338 /**
2339 * Resets the browser title-view to whatever it must be (for example, if we
2340 * load a page from history).
2341 */
2342 private void resetTitle() {
2343 resetLockIcon();
2344 resetTitleIconAndProgress();
2345 }
2346
2347 /**
2348 * Resets the browser title-view to whatever it must be
2349 * (for example, if we had a loading error)
2350 * When we have a new page, we call resetTitle, when we
2351 * have to reset the titlebar to whatever it used to be
2352 * (for example, if the user chose to stop loading), we
2353 * call resetTitleAndRevertLockIcon.
2354 */
2355 /* package */ void resetTitleAndRevertLockIcon() {
2356 revertLockIcon();
2357 resetTitleIconAndProgress();
2358 }
2359
2360 /**
2361 * Reset the title, favicon, and progress.
2362 */
2363 private void resetTitleIconAndProgress() {
2364 WebView current = mTabControl.getCurrentWebView();
2365 if (current == null) {
2366 return;
2367 }
2368 resetTitleAndIcon(current);
2369 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 mWebChromeClient.onProgressChanged(current, progress);
2371 }
2372
2373 // Reset the title and the icon based on the given item.
2374 private void resetTitleAndIcon(WebView view) {
2375 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2376 if (item != null) {
2377 setUrlTitle(item.getUrl(), item.getTitle());
2378 setFavicon(item.getFavicon());
2379 } else {
2380 setUrlTitle(null, null);
2381 setFavicon(null);
2382 }
2383 }
2384
2385 /**
2386 * Sets a title composed of the URL and the title string.
2387 * @param url The URL of the site being loaded.
2388 * @param title The title of the site being loaded.
2389 */
2390 private void setUrlTitle(String url, String title) {
2391 mUrl = url;
2392 mTitle = title;
2393
2394 // While the tab overview is animating or being shown, block changes
2395 // to the title.
2396 if (mAnimationCount == 0 && mTabOverview == null) {
2397 setTitle(buildUrlTitle(url, title));
2398 }
2399 }
2400
2401 /**
2402 * Builds and returns the page title, which is some
2403 * combination of the page URL and title.
2404 * @param url The URL of the site being loaded.
2405 * @param title The title of the site being loaded.
2406 * @return The page title.
2407 */
2408 private String buildUrlTitle(String url, String title) {
2409 String urlTitle = "";
2410
2411 if (url != null) {
2412 String titleUrl = buildTitleUrl(url);
2413
2414 if (title != null && 0 < title.length()) {
2415 if (titleUrl != null && 0 < titleUrl.length()) {
2416 urlTitle = titleUrl + ": " + title;
2417 } else {
2418 urlTitle = title;
2419 }
2420 } else {
2421 if (titleUrl != null) {
2422 urlTitle = titleUrl;
2423 }
2424 }
2425 }
2426
2427 return urlTitle;
2428 }
2429
2430 /**
2431 * @param url The URL to build a title version of the URL from.
2432 * @return The title version of the URL or null if fails.
2433 * The title version of the URL can be either the URL hostname,
2434 * or the hostname with an "https://" prefix (for secure URLs),
2435 * or an empty string if, for example, the URL in question is a
2436 * file:// URL with no hostname.
2437 */
2438 private static String buildTitleUrl(String url) {
2439 String titleUrl = null;
2440
2441 if (url != null) {
2442 try {
2443 // parse the url string
2444 URL urlObj = new URL(url);
2445 if (urlObj != null) {
2446 titleUrl = "";
2447
2448 String protocol = urlObj.getProtocol();
2449 String host = urlObj.getHost();
2450
2451 if (host != null && 0 < host.length()) {
2452 titleUrl = host;
2453 if (protocol != null) {
2454 // if a secure site, add an "https://" prefix!
2455 if (protocol.equalsIgnoreCase("https")) {
2456 titleUrl = protocol + "://" + host;
2457 }
2458 }
2459 }
2460 }
2461 } catch (MalformedURLException e) {}
2462 }
2463
2464 return titleUrl;
2465 }
2466
2467 // Set the favicon in the title bar.
2468 private void setFavicon(Bitmap icon) {
2469 // While the tab overview is animating or being shown, block changes to
2470 // the favicon.
2471 if (mAnimationCount > 0 || mTabOverview != null) {
2472 return;
2473 }
2474 Drawable[] array = new Drawable[2];
2475 PaintDrawable p = new PaintDrawable(Color.WHITE);
2476 p.setCornerRadius(3f);
2477 array[0] = p;
2478 if (icon == null) {
2479 array[1] = mGenericFavicon;
2480 } else {
2481 array[1] = new BitmapDrawable(icon);
2482 }
2483 LayerDrawable d = new LayerDrawable(array);
2484 d.setLayerInset(1, 2, 2, 2, 2);
2485 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2486 }
2487
2488 /**
2489 * Saves the current lock-icon state before resetting
2490 * the lock icon. If we have an error, we may need to
2491 * roll back to the previous state.
2492 */
2493 private void saveLockIcon() {
2494 mPrevLockType = mLockIconType;
2495 }
2496
2497 /**
2498 * Reverts the lock-icon state to the last saved state,
2499 * for example, if we had an error, and need to cancel
2500 * the load.
2501 */
2502 private void revertLockIcon() {
2503 mLockIconType = mPrevLockType;
2504
Dave Bort31a6d1c2009-04-13 15:56:49 -07002505 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002506 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2507 " revert lock icon to " + mLockIconType);
2508 }
2509
2510 updateLockIconImage(mLockIconType);
2511 }
2512
2513 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2514 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2515 // Animate to the tab picker, remove the current tab, then
2516 // animate away from the tab picker to the parent WebView.
2517 tabPicker(false, indexFrom, remove);
2518 // Change to the parent tab
2519 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2520 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002521 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 } else {
2523 // Increment this here so that no other animations can happen in
2524 // between the end of the tab picker transition and the beginning
2525 // of openTabAndShow. This has a matching decrement in the handler
2526 // of OPEN_TAB_AND_SHOW.
2527 mAnimationCount++;
2528 // Send a message to open a new tab.
2529 mHandler.sendMessageDelayed(
2530 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2531 mSettings.getHomePage()), delay);
2532 }
2533 }
2534
2535 private void goBackOnePageOrQuit() {
2536 TabControl.Tab current = mTabControl.getCurrentTab();
2537 if (current == null) {
2538 /*
2539 * Instead of finishing the activity, simply push this to the back
2540 * of the stack and let ActivityManager to choose the foreground
2541 * activity. As BrowserActivity is singleTask, it will be always the
2542 * root of the task. So we can use either true or false for
2543 * moveTaskToBack().
2544 */
2545 moveTaskToBack(true);
2546 }
2547 WebView w = current.getWebView();
2548 if (w.canGoBack()) {
2549 w.goBack();
2550 } else {
2551 // Check to see if we are closing a window that was created by
2552 // another window. If so, we switch back to that window.
2553 TabControl.Tab parent = current.getParentTab();
2554 if (parent != null) {
2555 switchTabs(mTabControl.getCurrentIndex(),
2556 mTabControl.getTabIndex(parent), true);
2557 } else {
2558 if (current.closeOnExit()) {
2559 if (mTabControl.getTabCount() == 1) {
2560 finish();
2561 return;
2562 }
2563 // call pauseWebView() now, we won't be able to call it in
2564 // onPause() as the WebView won't be valid.
2565 pauseWebView();
2566 removeTabFromContentView(current);
2567 mTabControl.removeTab(current);
2568 }
2569 /*
2570 * Instead of finishing the activity, simply push this to the back
2571 * of the stack and let ActivityManager to choose the foreground
2572 * activity. As BrowserActivity is singleTask, it will be always the
2573 * root of the task. So we can use either true or false for
2574 * moveTaskToBack().
2575 */
2576 moveTaskToBack(true);
2577 }
2578 }
2579 }
2580
2581 public KeyTracker.State onKeyTracker(int keyCode,
2582 KeyEvent event,
2583 KeyTracker.Stage stage,
2584 int duration) {
2585 // if onKeyTracker() is called after activity onStop()
2586 // because of accumulated key events,
2587 // we should ignore it as browser is not active any more.
2588 WebView topWindow = getTopWindow();
2589 if (topWindow == null)
2590 return KeyTracker.State.NOT_TRACKING;
2591
2592 if (keyCode == KeyEvent.KEYCODE_BACK) {
2593 // During animations, block the back key so that other animations
2594 // are not triggered and so that we don't end up destroying all the
2595 // WebViews before finishing the animation.
2596 if (mAnimationCount > 0) {
2597 return KeyTracker.State.DONE_TRACKING;
2598 }
2599 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2600 bookmarksOrHistoryPicker(true);
2601 return KeyTracker.State.DONE_TRACKING;
2602 } else if (stage == KeyTracker.Stage.UP) {
2603 // FIXME: Currently, we do not have a notion of the
2604 // history picker for the subwindow, but maybe we
2605 // should?
2606 WebView subwindow = mTabControl.getCurrentSubWindow();
2607 if (subwindow != null) {
2608 if (subwindow.canGoBack()) {
2609 subwindow.goBack();
2610 } else {
2611 dismissSubWindow(mTabControl.getCurrentTab());
2612 }
2613 } else {
2614 goBackOnePageOrQuit();
2615 }
2616 return KeyTracker.State.DONE_TRACKING;
2617 }
2618 return KeyTracker.State.KEEP_TRACKING;
2619 }
2620 return KeyTracker.State.NOT_TRACKING;
2621 }
2622
2623 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2624 if (keyCode == KeyEvent.KEYCODE_MENU) {
2625 mMenuIsDown = true;
2626 }
2627 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2628 if (!handled) {
2629 switch (keyCode) {
2630 case KeyEvent.KEYCODE_SPACE:
2631 if (event.isShiftPressed()) {
2632 getTopWindow().pageUp(false);
2633 } else {
2634 getTopWindow().pageDown(false);
2635 }
2636 handled = true;
2637 break;
2638
2639 default:
2640 break;
2641 }
2642 }
2643 return handled || super.onKeyDown(keyCode, event);
2644 }
2645
2646 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2647 if (keyCode == KeyEvent.KEYCODE_MENU) {
2648 mMenuIsDown = false;
2649 }
2650 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2651 }
2652
2653 private void stopLoading() {
2654 resetTitleAndRevertLockIcon();
2655 WebView w = getTopWindow();
2656 w.stopLoading();
2657 mWebViewClient.onPageFinished(w, w.getUrl());
2658
2659 cancelStopToast();
2660 mStopToast = Toast
2661 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2662 mStopToast.show();
2663 }
2664
2665 private void cancelStopToast() {
2666 if (mStopToast != null) {
2667 mStopToast.cancel();
2668 mStopToast = null;
2669 }
2670 }
2671
2672 // called by a non-UI thread to post the message
2673 public void postMessage(int what, int arg1, int arg2, Object obj) {
2674 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2675 }
2676
2677 // public message ids
2678 public final static int LOAD_URL = 1001;
2679 public final static int STOP_LOAD = 1002;
2680
2681 // Message Ids
2682 private static final int FOCUS_NODE_HREF = 102;
2683 private static final int CANCEL_CREDS_REQUEST = 103;
2684 private static final int ANIMATE_FROM_OVERVIEW = 104;
2685 private static final int ANIMATE_TO_OVERVIEW = 105;
2686 private static final int OPEN_TAB_AND_SHOW = 106;
2687 private static final int CHECK_MEMORY = 107;
2688 private static final int RELEASE_WAKELOCK = 108;
2689
2690 // Private handler for handling javascript and saving passwords
2691 private Handler mHandler = new Handler() {
2692
2693 public void handleMessage(Message msg) {
2694 switch (msg.what) {
2695 case ANIMATE_FROM_OVERVIEW:
2696 final HashMap map = (HashMap) msg.obj;
2697 animateFromTabOverview((AnimatingView) map.get("view"),
2698 msg.arg1 == 1, (Message) map.get("msg"));
2699 break;
2700
2701 case ANIMATE_TO_OVERVIEW:
2702 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2703 (AnimatingView) msg.obj);
2704 break;
2705
2706 case OPEN_TAB_AND_SHOW:
2707 // Decrement mAnimationCount before openTabAndShow because
2708 // the method relies on the value being 0 to start the next
2709 // animation.
2710 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002711 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002712 break;
2713
2714 case FOCUS_NODE_HREF:
2715 String url = (String) msg.getData().get("url");
2716 if (url == null || url.length() == 0) {
2717 break;
2718 }
2719 HashMap focusNodeMap = (HashMap) msg.obj;
2720 WebView view = (WebView) focusNodeMap.get("webview");
2721 // Only apply the action if the top window did not change.
2722 if (getTopWindow() != view) {
2723 break;
2724 }
2725 switch (msg.arg1) {
2726 case R.id.open_context_menu_id:
2727 case R.id.view_image_context_menu_id:
2728 loadURL(getTopWindow(), url);
2729 break;
2730 case R.id.open_newtab_context_menu_id:
2731 openTab(url);
2732 break;
2733 case R.id.bookmark_context_menu_id:
2734 Intent intent = new Intent(BrowserActivity.this,
2735 AddBookmarkPage.class);
2736 intent.putExtra("url", url);
2737 startActivity(intent);
2738 break;
2739 case R.id.share_link_context_menu_id:
2740 Browser.sendString(BrowserActivity.this, url);
2741 break;
2742 case R.id.copy_link_context_menu_id:
2743 copy(url);
2744 break;
2745 case R.id.save_link_context_menu_id:
2746 case R.id.download_context_menu_id:
2747 onDownloadStartNoStream(url, null, null, null, -1);
2748 break;
2749 }
2750 break;
2751
2752 case LOAD_URL:
2753 loadURL(getTopWindow(), (String) msg.obj);
2754 break;
2755
2756 case STOP_LOAD:
2757 stopLoading();
2758 break;
2759
2760 case CANCEL_CREDS_REQUEST:
2761 resumeAfterCredentials();
2762 break;
2763
2764 case CHECK_MEMORY:
2765 // reschedule to check memory condition
2766 mHandler.removeMessages(CHECK_MEMORY);
2767 mHandler.sendMessageDelayed(mHandler.obtainMessage
2768 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2769 checkMemory();
2770 break;
2771
2772 case RELEASE_WAKELOCK:
2773 if (mWakeLock.isHeld()) {
2774 mWakeLock.release();
2775 }
2776 break;
2777 }
2778 }
2779 };
2780
2781 // -------------------------------------------------------------------------
2782 // WebViewClient implementation.
2783 //-------------------------------------------------------------------------
2784
2785 // Use in overrideUrlLoading
2786 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2787 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2788 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2789 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2790
2791 /* package */ WebViewClient getWebViewClient() {
2792 return mWebViewClient;
2793 }
2794
2795 private void updateIcon(String url, Bitmap icon) {
2796 if (icon != null) {
2797 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2798 url, icon);
2799 }
2800 setFavicon(icon);
2801 }
2802
2803 private final WebViewClient mWebViewClient = new WebViewClient() {
2804 @Override
2805 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2806 resetLockIcon(url);
2807 setUrlTitle(url, null);
2808 // Call updateIcon instead of setFavicon so the bookmark
2809 // database can be updated.
2810 updateIcon(url, favicon);
2811
2812 if (mSettings.isTracing() == true) {
2813 // FIXME: we should save the trace file somewhere other than data.
2814 // I can't use "/tmp" as it competes for system memory.
2815 File file = getDir("browserTrace", 0);
2816 String baseDir = file.getPath();
2817 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2818 String host;
2819 try {
2820 WebAddress uri = new WebAddress(url);
2821 host = uri.mHost;
2822 } catch (android.net.ParseException ex) {
2823 host = "unknown_host";
2824 }
2825 host = host.replace('.', '_');
2826 baseDir = baseDir + host;
2827 file = new File(baseDir+".data");
2828 if (file.exists() == true) {
2829 file.delete();
2830 }
2831 file = new File(baseDir+".key");
2832 if (file.exists() == true) {
2833 file.delete();
2834 }
2835 mInTrace = true;
2836 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2837 }
2838
2839 // Performance probe
2840 if (false) {
2841 mStart = SystemClock.uptimeMillis();
2842 mProcessStart = Process.getElapsedCpuTime();
2843 long[] sysCpu = new long[7];
2844 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2845 sysCpu, null)) {
2846 mUserStart = sysCpu[0] + sysCpu[1];
2847 mSystemStart = sysCpu[2];
2848 mIdleStart = sysCpu[3];
2849 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2850 }
2851 mUiStart = SystemClock.currentThreadTimeMillis();
2852 }
2853
2854 if (!mPageStarted) {
2855 mPageStarted = true;
2856 // if onResume() has been called, resumeWebView() does nothing.
2857 resumeWebView();
2858 }
2859
2860 // reset sync timer to avoid sync starts during loading a page
2861 CookieSyncManager.getInstance().resetSync();
2862
2863 mInLoad = true;
2864 updateInLoadMenuItems();
2865 if (!mIsNetworkUp) {
2866 if ( mAlertDialog == null) {
2867 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2868 .setTitle(R.string.loadSuspendedTitle)
2869 .setMessage(R.string.loadSuspended)
2870 .setPositiveButton(R.string.ok, null)
2871 .show();
2872 }
2873 if (view != null) {
2874 view.setNetworkAvailable(false);
2875 }
2876 }
2877
2878 // schedule to check memory condition
2879 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2880 CHECK_MEMORY_INTERVAL);
2881 }
2882
2883 @Override
2884 public void onPageFinished(WebView view, String url) {
2885 // Reset the title and icon in case we stopped a provisional
2886 // load.
2887 resetTitleAndIcon(view);
2888
2889 // Update the lock icon image only once we are done loading
2890 updateLockIconImage(mLockIconType);
2891
2892 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002893 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002894 long[] sysCpu = new long[7];
2895 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2896 sysCpu, null)) {
2897 String uiInfo = "UI thread used "
2898 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2899 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002900 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 Log.d(LOGTAG, uiInfo);
2902 }
2903 //The string that gets written to the log
2904 String performanceString = "It took total "
2905 + (SystemClock.uptimeMillis() - mStart)
2906 + " ms clock time to load the page."
2907 + "\nbrowser process used "
2908 + (Process.getElapsedCpuTime() - mProcessStart)
2909 + " ms, user processes used "
2910 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2911 + " ms, kernel used "
2912 + (sysCpu[2] - mSystemStart) * 10
2913 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2914 + " ms and irq took "
2915 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2916 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002917 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002918 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2919 }
2920 if (url != null) {
2921 // strip the url to maintain consistency
2922 String newUrl = new String(url);
2923 if (newUrl.startsWith("http://www.")) {
2924 newUrl = newUrl.substring(11);
2925 } else if (newUrl.startsWith("http://")) {
2926 newUrl = newUrl.substring(7);
2927 } else if (newUrl.startsWith("https://www.")) {
2928 newUrl = newUrl.substring(12);
2929 } else if (newUrl.startsWith("https://")) {
2930 newUrl = newUrl.substring(8);
2931 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002932 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 Log.d(LOGTAG, newUrl + " loaded");
2934 }
2935 /*
2936 if (sWhiteList.contains(newUrl)) {
2937 // The string that gets pushed to the statistcs
2938 // service
2939 performanceString = performanceString
2940 + "\nWebpage: "
2941 + newUrl
2942 + "\nCarrier: "
2943 + android.os.SystemProperties
2944 .get("gsm.sim.operator.alpha");
2945 if (mWebView != null
2946 && mWebView.getContext() != null
2947 && mWebView.getContext().getSystemService(
2948 Context.CONNECTIVITY_SERVICE) != null) {
2949 ConnectivityManager cManager =
2950 (ConnectivityManager) mWebView
2951 .getContext().getSystemService(
2952 Context.CONNECTIVITY_SERVICE);
2953 NetworkInfo nInfo = cManager
2954 .getActiveNetworkInfo();
2955 if (nInfo != null) {
2956 performanceString = performanceString
2957 + "\nNetwork Type: "
2958 + nInfo.getType().toString();
2959 }
2960 }
2961 Checkin.logEvent(mResolver,
2962 Checkin.Events.Tag.WEBPAGE_LOAD,
2963 performanceString);
2964 Log.w(LOGTAG, "pushed to the statistics service");
2965 }
2966 */
2967 }
2968 }
2969 }
2970
2971 if (mInTrace) {
2972 mInTrace = false;
2973 Debug.stopMethodTracing();
2974 }
2975
2976 if (mPageStarted) {
2977 mPageStarted = false;
2978 // pauseWebView() will do nothing and return false if onPause()
2979 // is not called yet.
2980 if (pauseWebView()) {
2981 if (mWakeLock.isHeld()) {
2982 mHandler.removeMessages(RELEASE_WAKELOCK);
2983 mWakeLock.release();
2984 }
2985 }
2986 }
2987
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 mHandler.removeMessages(CHECK_MEMORY);
2989 checkMemory();
2990 }
2991
2992 // return true if want to hijack the url to let another app to handle it
2993 @Override
2994 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2995 if (url.startsWith(SCHEME_WTAI)) {
2996 // wtai://wp/mc;number
2997 // number=string(phone-number)
2998 if (url.startsWith(SCHEME_WTAI_MC)) {
2999 Intent intent = new Intent(Intent.ACTION_VIEW,
3000 Uri.parse(WebView.SCHEME_TEL +
3001 url.substring(SCHEME_WTAI_MC.length())));
3002 startActivity(intent);
3003 return true;
3004 }
3005 // wtai://wp/sd;dtmf
3006 // dtmf=string(dialstring)
3007 if (url.startsWith(SCHEME_WTAI_SD)) {
3008 // TODO
3009 // only send when there is active voice connection
3010 return false;
3011 }
3012 // wtai://wp/ap;number;name
3013 // number=string(phone-number)
3014 // name=string
3015 if (url.startsWith(SCHEME_WTAI_AP)) {
3016 // TODO
3017 return false;
3018 }
3019 }
3020
Dianne Hackborn99189432009-06-17 18:06:18 -07003021 // The "about:" schemes are internal to the browser; don't
3022 // want these to be dispatched to other apps.
3023 if (url.startsWith("about:")) {
3024 return false;
3025 }
3026
3027 Intent intent;
3028
3029 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003031 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3032 } catch (URISyntaxException ex) {
3033 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003034 return false;
3035 }
3036
Dianne Hackborn99189432009-06-17 18:06:18 -07003037 // sanitize the Intent, ensuring web pages can not bypass browser
3038 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003040 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 try {
3042 if (startActivityIfNeeded(intent, -1)) {
3043 return true;
3044 }
3045 } catch (ActivityNotFoundException ex) {
3046 // ignore the error. If no application can handle the URL,
3047 // eg about:blank, assume the browser can handle it.
3048 }
3049
3050 if (mMenuIsDown) {
3051 openTab(url);
3052 closeOptionsMenu();
3053 return true;
3054 }
3055
3056 return false;
3057 }
3058
3059 /**
3060 * Updates the lock icon. This method is called when we discover another
3061 * resource to be loaded for this page (for example, javascript). While
3062 * we update the icon type, we do not update the lock icon itself until
3063 * we are done loading, it is slightly more secure this way.
3064 */
3065 @Override
3066 public void onLoadResource(WebView view, String url) {
3067 if (url != null && url.length() > 0) {
3068 // It is only if the page claims to be secure
3069 // that we may have to update the lock:
3070 if (mLockIconType == LOCK_ICON_SECURE) {
3071 // If NOT a 'safe' url, change the lock to mixed content!
3072 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3073 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003074 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3076 " updated lock icon to " + mLockIconType + " due to " + url);
3077 }
3078 }
3079 }
3080 }
3081 }
3082
3083 /**
3084 * Show the dialog, asking the user if they would like to continue after
3085 * an excessive number of HTTP redirects.
3086 */
3087 @Override
3088 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3089 final Message continueMsg) {
3090 new AlertDialog.Builder(BrowserActivity.this)
3091 .setTitle(R.string.browserFrameRedirect)
3092 .setMessage(R.string.browserFrame307Post)
3093 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3094 public void onClick(DialogInterface dialog, int which) {
3095 continueMsg.sendToTarget();
3096 }})
3097 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3098 public void onClick(DialogInterface dialog, int which) {
3099 cancelMsg.sendToTarget();
3100 }})
3101 .setOnCancelListener(new OnCancelListener() {
3102 public void onCancel(DialogInterface dialog) {
3103 cancelMsg.sendToTarget();
3104 }})
3105 .show();
3106 }
3107
Patrick Scotta6555242009-03-24 18:01:26 -07003108 // Container class for the next error dialog that needs to be
3109 // displayed.
3110 class ErrorDialog {
3111 public final int mTitle;
3112 public final String mDescription;
3113 public final int mError;
3114 ErrorDialog(int title, String desc, int error) {
3115 mTitle = title;
3116 mDescription = desc;
3117 mError = error;
3118 }
3119 };
3120
3121 private void processNextError() {
3122 if (mQueuedErrors == null) {
3123 return;
3124 }
3125 // The first one is currently displayed so just remove it.
3126 mQueuedErrors.removeFirst();
3127 if (mQueuedErrors.size() == 0) {
3128 mQueuedErrors = null;
3129 return;
3130 }
3131 showError(mQueuedErrors.getFirst());
3132 }
3133
3134 private DialogInterface.OnDismissListener mDialogListener =
3135 new DialogInterface.OnDismissListener() {
3136 public void onDismiss(DialogInterface d) {
3137 processNextError();
3138 }
3139 };
3140 private LinkedList<ErrorDialog> mQueuedErrors;
3141
3142 private void queueError(int err, String desc) {
3143 if (mQueuedErrors == null) {
3144 mQueuedErrors = new LinkedList<ErrorDialog>();
3145 }
3146 for (ErrorDialog d : mQueuedErrors) {
3147 if (d.mError == err) {
3148 // Already saw a similar error, ignore the new one.
3149 return;
3150 }
3151 }
3152 ErrorDialog errDialog = new ErrorDialog(
3153 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3154 R.string.browserFrameFileErrorLabel :
3155 R.string.browserFrameNetworkErrorLabel,
3156 desc, err);
3157 mQueuedErrors.addLast(errDialog);
3158
3159 // Show the dialog now if the queue was empty.
3160 if (mQueuedErrors.size() == 1) {
3161 showError(errDialog);
3162 }
3163 }
3164
3165 private void showError(ErrorDialog errDialog) {
3166 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3167 .setTitle(errDialog.mTitle)
3168 .setMessage(errDialog.mDescription)
3169 .setPositiveButton(R.string.ok, null)
3170 .create();
3171 d.setOnDismissListener(mDialogListener);
3172 d.show();
3173 }
3174
The Android Open Source Project0c908882009-03-03 19:32:16 -08003175 /**
3176 * Show a dialog informing the user of the network error reported by
3177 * WebCore.
3178 */
3179 @Override
3180 public void onReceivedError(WebView view, int errorCode,
3181 String description, String failingUrl) {
3182 if (errorCode != EventHandler.ERROR_LOOKUP &&
3183 errorCode != EventHandler.ERROR_CONNECT &&
3184 errorCode != EventHandler.ERROR_BAD_URL &&
3185 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3186 errorCode != EventHandler.FILE_ERROR) {
Patrick Scotta6555242009-03-24 18:01:26 -07003187 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 }
Patrick Scotta6555242009-03-24 18:01:26 -07003189 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3190 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003191
3192 // We need to reset the title after an error.
3193 resetTitleAndRevertLockIcon();
3194 }
3195
3196 /**
3197 * Check with the user if it is ok to resend POST data as the page they
3198 * are trying to navigate to is the result of a POST.
3199 */
3200 @Override
3201 public void onFormResubmission(WebView view, final Message dontResend,
3202 final Message resend) {
3203 new AlertDialog.Builder(BrowserActivity.this)
3204 .setTitle(R.string.browserFrameFormResubmitLabel)
3205 .setMessage(R.string.browserFrameFormResubmitMessage)
3206 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3207 public void onClick(DialogInterface dialog, int which) {
3208 resend.sendToTarget();
3209 }})
3210 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3211 public void onClick(DialogInterface dialog, int which) {
3212 dontResend.sendToTarget();
3213 }})
3214 .setOnCancelListener(new OnCancelListener() {
3215 public void onCancel(DialogInterface dialog) {
3216 dontResend.sendToTarget();
3217 }})
3218 .show();
3219 }
3220
3221 /**
3222 * Insert the url into the visited history database.
3223 * @param url The url to be inserted.
3224 * @param isReload True if this url is being reloaded.
3225 * FIXME: Not sure what to do when reloading the page.
3226 */
3227 @Override
3228 public void doUpdateVisitedHistory(WebView view, String url,
3229 boolean isReload) {
3230 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3231 return;
3232 }
3233 Browser.updateVisitedHistory(mResolver, url, true);
3234 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3235 }
3236
3237 /**
3238 * Displays SSL error(s) dialog to the user.
3239 */
3240 @Override
3241 public void onReceivedSslError(
3242 final WebView view, final SslErrorHandler handler, final SslError error) {
3243
3244 if (mSettings.showSecurityWarnings()) {
3245 final LayoutInflater factory =
3246 LayoutInflater.from(BrowserActivity.this);
3247 final View warningsView =
3248 factory.inflate(R.layout.ssl_warnings, null);
3249 final LinearLayout placeholder =
3250 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3251
3252 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3253 LinearLayout ll = (LinearLayout)factory
3254 .inflate(R.layout.ssl_warning, null);
3255 ((TextView)ll.findViewById(R.id.warning))
3256 .setText(R.string.ssl_untrusted);
3257 placeholder.addView(ll);
3258 }
3259
3260 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3261 LinearLayout ll = (LinearLayout)factory
3262 .inflate(R.layout.ssl_warning, null);
3263 ((TextView)ll.findViewById(R.id.warning))
3264 .setText(R.string.ssl_mismatch);
3265 placeholder.addView(ll);
3266 }
3267
3268 if (error.hasError(SslError.SSL_EXPIRED)) {
3269 LinearLayout ll = (LinearLayout)factory
3270 .inflate(R.layout.ssl_warning, null);
3271 ((TextView)ll.findViewById(R.id.warning))
3272 .setText(R.string.ssl_expired);
3273 placeholder.addView(ll);
3274 }
3275
3276 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3277 LinearLayout ll = (LinearLayout)factory
3278 .inflate(R.layout.ssl_warning, null);
3279 ((TextView)ll.findViewById(R.id.warning))
3280 .setText(R.string.ssl_not_yet_valid);
3281 placeholder.addView(ll);
3282 }
3283
3284 new AlertDialog.Builder(BrowserActivity.this)
3285 .setTitle(R.string.security_warning)
3286 .setIcon(android.R.drawable.ic_dialog_alert)
3287 .setView(warningsView)
3288 .setPositiveButton(R.string.ssl_continue,
3289 new DialogInterface.OnClickListener() {
3290 public void onClick(DialogInterface dialog, int whichButton) {
3291 handler.proceed();
3292 }
3293 })
3294 .setNeutralButton(R.string.view_certificate,
3295 new DialogInterface.OnClickListener() {
3296 public void onClick(DialogInterface dialog, int whichButton) {
3297 showSSLCertificateOnError(view, handler, error);
3298 }
3299 })
3300 .setNegativeButton(R.string.cancel,
3301 new DialogInterface.OnClickListener() {
3302 public void onClick(DialogInterface dialog, int whichButton) {
3303 handler.cancel();
3304 BrowserActivity.this.resetTitleAndRevertLockIcon();
3305 }
3306 })
3307 .setOnCancelListener(
3308 new DialogInterface.OnCancelListener() {
3309 public void onCancel(DialogInterface dialog) {
3310 handler.cancel();
3311 BrowserActivity.this.resetTitleAndRevertLockIcon();
3312 }
3313 })
3314 .show();
3315 } else {
3316 handler.proceed();
3317 }
3318 }
3319
3320 /**
3321 * Handles an HTTP authentication request.
3322 *
3323 * @param handler The authentication handler
3324 * @param host The host
3325 * @param realm The realm
3326 */
3327 @Override
3328 public void onReceivedHttpAuthRequest(WebView view,
3329 final HttpAuthHandler handler, final String host, final String realm) {
3330 String username = null;
3331 String password = null;
3332
3333 boolean reuseHttpAuthUsernamePassword =
3334 handler.useHttpAuthUsernamePassword();
3335
3336 if (reuseHttpAuthUsernamePassword &&
3337 (mTabControl.getCurrentWebView() != null)) {
3338 String[] credentials =
3339 mTabControl.getCurrentWebView()
3340 .getHttpAuthUsernamePassword(host, realm);
3341 if (credentials != null && credentials.length == 2) {
3342 username = credentials[0];
3343 password = credentials[1];
3344 }
3345 }
3346
3347 if (username != null && password != null) {
3348 handler.proceed(username, password);
3349 } else {
3350 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3351 }
3352 }
3353
3354 @Override
3355 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3356 if (mMenuIsDown) {
3357 // only check shortcut key when MENU is held
3358 return getWindow().isShortcutKey(event.getKeyCode(), event);
3359 } else {
3360 return false;
3361 }
3362 }
3363
3364 @Override
3365 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3366 if (view != mTabControl.getCurrentTopWebView()) {
3367 return;
3368 }
3369 if (event.isDown()) {
3370 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3371 } else {
3372 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3373 }
3374 }
3375 };
3376
3377 //--------------------------------------------------------------------------
3378 // WebChromeClient implementation
3379 //--------------------------------------------------------------------------
3380
3381 /* package */ WebChromeClient getWebChromeClient() {
3382 return mWebChromeClient;
3383 }
3384
3385 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3386 // Helper method to create a new tab or sub window.
3387 private void createWindow(final boolean dialog, final Message msg) {
3388 if (dialog) {
3389 mTabControl.createSubWindow();
3390 final TabControl.Tab t = mTabControl.getCurrentTab();
3391 attachSubWindow(t);
3392 WebView.WebViewTransport transport =
3393 (WebView.WebViewTransport) msg.obj;
3394 transport.setWebView(t.getSubWebView());
3395 msg.sendToTarget();
3396 } else {
3397 final TabControl.Tab parent = mTabControl.getCurrentTab();
3398 // openTabAndShow will dispatch the message after creating the
3399 // new WebView. This will prevent another request from coming
3400 // in during the animation.
Patrick Scott95d601f2009-06-11 10:06:46 -04003401 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 parent.addChildTab(mTabControl.getCurrentTab());
3403 WebView.WebViewTransport transport =
3404 (WebView.WebViewTransport) msg.obj;
3405 transport.setWebView(mTabControl.getCurrentWebView());
3406 }
3407 }
3408
3409 @Override
3410 public boolean onCreateWindow(WebView view, final boolean dialog,
3411 final boolean userGesture, final Message resultMsg) {
3412 // Ignore these requests during tab animations or if the tab
3413 // overview is showing.
3414 if (mAnimationCount > 0 || mTabOverview != null) {
3415 return false;
3416 }
3417 // Short-circuit if we can't create any more tabs or sub windows.
3418 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3419 new AlertDialog.Builder(BrowserActivity.this)
3420 .setTitle(R.string.too_many_subwindows_dialog_title)
3421 .setIcon(android.R.drawable.ic_dialog_alert)
3422 .setMessage(R.string.too_many_subwindows_dialog_message)
3423 .setPositiveButton(R.string.ok, null)
3424 .show();
3425 return false;
3426 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3427 new AlertDialog.Builder(BrowserActivity.this)
3428 .setTitle(R.string.too_many_windows_dialog_title)
3429 .setIcon(android.R.drawable.ic_dialog_alert)
3430 .setMessage(R.string.too_many_windows_dialog_message)
3431 .setPositiveButton(R.string.ok, null)
3432 .show();
3433 return false;
3434 }
3435
3436 // Short-circuit if this was a user gesture.
3437 if (userGesture) {
3438 // createWindow will call openTabAndShow for new Windows and
3439 // that will call tabPicker which will increment
3440 // mAnimationCount.
3441 createWindow(dialog, resultMsg);
3442 return true;
3443 }
3444
3445 // Allow the popup and create the appropriate window.
3446 final AlertDialog.OnClickListener allowListener =
3447 new AlertDialog.OnClickListener() {
3448 public void onClick(DialogInterface d,
3449 int which) {
3450 // Same comment as above for setting
3451 // mAnimationCount.
3452 createWindow(dialog, resultMsg);
3453 // Since we incremented mAnimationCount while the
3454 // dialog was up, we have to decrement it here.
3455 mAnimationCount--;
3456 }
3457 };
3458
3459 // Block the popup by returning a null WebView.
3460 final AlertDialog.OnClickListener blockListener =
3461 new AlertDialog.OnClickListener() {
3462 public void onClick(DialogInterface d, int which) {
3463 resultMsg.sendToTarget();
3464 // We are not going to trigger an animation so
3465 // unblock keys and animation requests.
3466 mAnimationCount--;
3467 }
3468 };
3469
3470 // Build a confirmation dialog to display to the user.
3471 final AlertDialog d =
3472 new AlertDialog.Builder(BrowserActivity.this)
3473 .setTitle(R.string.attention)
3474 .setIcon(android.R.drawable.ic_dialog_alert)
3475 .setMessage(R.string.popup_window_attempt)
3476 .setPositiveButton(R.string.allow, allowListener)
3477 .setNegativeButton(R.string.block, blockListener)
3478 .setCancelable(false)
3479 .create();
3480
3481 // Show the confirmation dialog.
3482 d.show();
3483 // We want to increment mAnimationCount here to prevent a
3484 // potential race condition. If the user allows a pop-up from a
3485 // site and that pop-up then triggers another pop-up, it is
3486 // possible to get the BACK key between here and when the dialog
3487 // appears.
3488 mAnimationCount++;
3489 return true;
3490 }
3491
3492 @Override
3493 public void onCloseWindow(WebView window) {
3494 final int currentIndex = mTabControl.getCurrentIndex();
3495 final TabControl.Tab parent =
3496 mTabControl.getCurrentTab().getParentTab();
3497 if (parent != null) {
3498 // JavaScript can only close popup window.
3499 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3500 }
3501 }
3502
3503 @Override
3504 public void onProgressChanged(WebView view, int newProgress) {
3505 // Block progress updates to the title bar while the tab overview
3506 // is animating or being displayed.
3507 if (mAnimationCount == 0 && mTabOverview == null) {
3508 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3509 newProgress * 100);
3510 }
3511
3512 if (newProgress == 100) {
3513 // onProgressChanged() is called for sub-frame too while
3514 // onPageFinished() is only called for the main frame. sync
3515 // cookie and cache promptly here.
3516 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003517 if (mInLoad) {
3518 mInLoad = false;
3519 updateInLoadMenuItems();
3520 }
3521 } else {
3522 // onPageFinished may have already been called but a subframe
3523 // is still loading and updating the progress. Reset mInLoad
3524 // and update the menu items.
3525 if (!mInLoad) {
3526 mInLoad = true;
3527 updateInLoadMenuItems();
3528 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003529 }
3530 }
3531
3532 @Override
3533 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003534 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535
3536 // here, if url is null, we want to reset the title
3537 setUrlTitle(url, title);
3538
3539 if (url == null ||
3540 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3541 return;
3542 }
3543 if (url.startsWith("http://www.")) {
3544 url = url.substring(11);
3545 } else if (url.startsWith("http://")) {
3546 url = url.substring(4);
3547 }
3548 try {
3549 url = "%" + url;
3550 String [] selArgs = new String[] { url };
3551
3552 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3553 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3554 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3555 Browser.HISTORY_PROJECTION, where, selArgs, null);
3556 if (c.moveToFirst()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003557 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 Log.v(LOGTAG, "updating cursor");
3559 }
3560 // Current implementation of database only has one entry per
3561 // url.
3562 int titleIndex =
3563 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3564 c.updateString(titleIndex, title);
3565 c.commitUpdates();
3566 }
3567 c.close();
3568 } catch (IllegalStateException e) {
3569 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3570 } catch (SQLiteException ex) {
3571 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3572 }
3573 }
3574
3575 @Override
3576 public void onReceivedIcon(WebView view, Bitmap icon) {
3577 updateIcon(view.getUrl(), icon);
3578 }
3579 };
3580
3581 /**
3582 * Notify the host application a download should be done, or that
3583 * the data should be streamed if a streaming viewer is available.
3584 * @param url The full url to the content that should be downloaded
3585 * @param contentDisposition Content-disposition http header, if
3586 * present.
3587 * @param mimetype The mimetype of the content reported by the server
3588 * @param contentLength The file size reported by the server
3589 */
3590 public void onDownloadStart(String url, String userAgent,
3591 String contentDisposition, String mimetype, long contentLength) {
3592 // if we're dealing wih A/V content that's not explicitly marked
3593 // for download, check if it's streamable.
3594 if (contentDisposition == null
3595 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3596 // query the package manager to see if there's a registered handler
3597 // that matches.
3598 Intent intent = new Intent(Intent.ACTION_VIEW);
3599 intent.setDataAndType(Uri.parse(url), mimetype);
3600 if (getPackageManager().resolveActivity(intent,
3601 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3602 // someone knows how to handle this mime type with this scheme, don't download.
3603 try {
3604 startActivity(intent);
3605 return;
3606 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003607 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 Log.d(LOGTAG, "activity not found for " + mimetype
3609 + " over " + Uri.parse(url).getScheme(), ex);
3610 }
3611 // Best behavior is to fall back to a download in this case
3612 }
3613 }
3614 }
3615 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3616 }
3617
3618 /**
3619 * Notify the host application a download should be done, even if there
3620 * is a streaming viewer available for thise type.
3621 * @param url The full url to the content that should be downloaded
3622 * @param contentDisposition Content-disposition http header, if
3623 * present.
3624 * @param mimetype The mimetype of the content reported by the server
3625 * @param contentLength The file size reported by the server
3626 */
3627 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3628 String contentDisposition, String mimetype, long contentLength) {
3629
3630 String filename = URLUtil.guessFileName(url,
3631 contentDisposition, mimetype);
3632
3633 // Check to see if we have an SDCard
3634 String status = Environment.getExternalStorageState();
3635 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3636 int title;
3637 String msg;
3638
3639 // Check to see if the SDCard is busy, same as the music app
3640 if (status.equals(Environment.MEDIA_SHARED)) {
3641 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3642 title = R.string.download_sdcard_busy_dlg_title;
3643 } else {
3644 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3645 title = R.string.download_no_sdcard_dlg_title;
3646 }
3647
3648 new AlertDialog.Builder(this)
3649 .setTitle(title)
3650 .setIcon(android.R.drawable.ic_dialog_alert)
3651 .setMessage(msg)
3652 .setPositiveButton(R.string.ok, null)
3653 .show();
3654 return;
3655 }
3656
3657 // java.net.URI is a lot stricter than KURL so we have to undo
3658 // KURL's percent-encoding and redo the encoding using java.net.URI.
3659 URI uri = null;
3660 try {
3661 // Undo the percent-encoding that KURL may have done.
3662 String newUrl = new String(URLUtil.decode(url.getBytes()));
3663 // Parse the url into pieces
3664 WebAddress w = new WebAddress(newUrl);
3665 String frag = null;
3666 String query = null;
3667 String path = w.mPath;
3668 // Break the path into path, query, and fragment
3669 if (path.length() > 0) {
3670 // Strip the fragment
3671 int idx = path.lastIndexOf('#');
3672 if (idx != -1) {
3673 frag = path.substring(idx + 1);
3674 path = path.substring(0, idx);
3675 }
3676 idx = path.lastIndexOf('?');
3677 if (idx != -1) {
3678 query = path.substring(idx + 1);
3679 path = path.substring(0, idx);
3680 }
3681 }
3682 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3683 query, frag);
3684 } catch (Exception e) {
3685 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3686 return;
3687 }
3688
3689 // XXX: Have to use the old url since the cookies were stored using the
3690 // old percent-encoded url.
3691 String cookies = CookieManager.getInstance().getCookie(url);
3692
3693 ContentValues values = new ContentValues();
3694 values.put(Downloads.URI, uri.toString());
3695 values.put(Downloads.COOKIE_DATA, cookies);
3696 values.put(Downloads.USER_AGENT, userAgent);
3697 values.put(Downloads.NOTIFICATION_PACKAGE,
3698 getPackageName());
3699 values.put(Downloads.NOTIFICATION_CLASS,
3700 BrowserDownloadPage.class.getCanonicalName());
3701 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3702 values.put(Downloads.MIMETYPE, mimetype);
3703 values.put(Downloads.FILENAME_HINT, filename);
3704 values.put(Downloads.DESCRIPTION, uri.getHost());
3705 if (contentLength > 0) {
3706 values.put(Downloads.TOTAL_BYTES, contentLength);
3707 }
3708 if (mimetype == null) {
3709 // We must have long pressed on a link or image to download it. We
3710 // are not sure of the mimetype in this case, so do a head request
3711 new FetchUrlMimeType(this).execute(values);
3712 } else {
3713 final Uri contentUri =
3714 getContentResolver().insert(Downloads.CONTENT_URI, values);
3715 viewDownloads(contentUri);
3716 }
3717
3718 }
3719
3720 /**
3721 * Resets the lock icon. This method is called when we start a new load and
3722 * know the url to be loaded.
3723 */
3724 private void resetLockIcon(String url) {
3725 // Save the lock-icon state (we revert to it if the load gets cancelled)
3726 saveLockIcon();
3727
3728 mLockIconType = LOCK_ICON_UNSECURE;
3729 if (URLUtil.isHttpsUrl(url)) {
3730 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003731 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3733 " reset lock icon to " + mLockIconType);
3734 }
3735 }
3736
3737 updateLockIconImage(LOCK_ICON_UNSECURE);
3738 }
3739
3740 /**
3741 * Resets the lock icon. This method is called when the icon needs to be
3742 * reset but we do not know whether we are loading a secure or not secure
3743 * page.
3744 */
3745 private void resetLockIcon() {
3746 // Save the lock-icon state (we revert to it if the load gets cancelled)
3747 saveLockIcon();
3748
3749 mLockIconType = LOCK_ICON_UNSECURE;
3750
Dave Bort31a6d1c2009-04-13 15:56:49 -07003751 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3753 " reset lock icon to " + mLockIconType);
3754 }
3755
3756 updateLockIconImage(LOCK_ICON_UNSECURE);
3757 }
3758
3759 /**
3760 * Updates the lock-icon image in the title-bar.
3761 */
3762 private void updateLockIconImage(int lockIconType) {
3763 Drawable d = null;
3764 if (lockIconType == LOCK_ICON_SECURE) {
3765 d = mSecLockIcon;
3766 } else if (lockIconType == LOCK_ICON_MIXED) {
3767 d = mMixLockIcon;
3768 }
3769 // If the tab overview is animating or being shown, do not update the
3770 // lock icon.
3771 if (mAnimationCount == 0 && mTabOverview == null) {
3772 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3773 }
3774 }
3775
3776 /**
3777 * Displays a page-info dialog.
3778 * @param tab The tab to show info about
3779 * @param fromShowSSLCertificateOnError The flag that indicates whether
3780 * this dialog was opened from the SSL-certificate-on-error dialog or
3781 * not. This is important, since we need to know whether to return to
3782 * the parent dialog or simply dismiss.
3783 */
3784 private void showPageInfo(final TabControl.Tab tab,
3785 final boolean fromShowSSLCertificateOnError) {
3786 final LayoutInflater factory = LayoutInflater
3787 .from(this);
3788
3789 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3790
3791 final WebView view = tab.getWebView();
3792
3793 String url = null;
3794 String title = null;
3795
3796 if (view == null) {
3797 url = tab.getUrl();
3798 title = tab.getTitle();
3799 } else if (view == mTabControl.getCurrentWebView()) {
3800 // Use the cached title and url if this is the current WebView
3801 url = mUrl;
3802 title = mTitle;
3803 } else {
3804 url = view.getUrl();
3805 title = view.getTitle();
3806 }
3807
3808 if (url == null) {
3809 url = "";
3810 }
3811 if (title == null) {
3812 title = "";
3813 }
3814
3815 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3816 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3817
3818 mPageInfoView = tab;
3819 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3820
3821 AlertDialog.Builder alertDialogBuilder =
3822 new AlertDialog.Builder(this)
3823 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3824 .setView(pageInfoView)
3825 .setPositiveButton(
3826 R.string.ok,
3827 new DialogInterface.OnClickListener() {
3828 public void onClick(DialogInterface dialog,
3829 int whichButton) {
3830 mPageInfoDialog = null;
3831 mPageInfoView = null;
3832 mPageInfoFromShowSSLCertificateOnError = null;
3833
3834 // if we came here from the SSL error dialog
3835 if (fromShowSSLCertificateOnError) {
3836 // go back to the SSL error dialog
3837 showSSLCertificateOnError(
3838 mSSLCertificateOnErrorView,
3839 mSSLCertificateOnErrorHandler,
3840 mSSLCertificateOnErrorError);
3841 }
3842 }
3843 })
3844 .setOnCancelListener(
3845 new DialogInterface.OnCancelListener() {
3846 public void onCancel(DialogInterface dialog) {
3847 mPageInfoDialog = null;
3848 mPageInfoView = null;
3849 mPageInfoFromShowSSLCertificateOnError = null;
3850
3851 // if we came here from the SSL error dialog
3852 if (fromShowSSLCertificateOnError) {
3853 // go back to the SSL error dialog
3854 showSSLCertificateOnError(
3855 mSSLCertificateOnErrorView,
3856 mSSLCertificateOnErrorHandler,
3857 mSSLCertificateOnErrorError);
3858 }
3859 }
3860 });
3861
3862 // if we have a main top-level page SSL certificate set or a certificate
3863 // error
3864 if (fromShowSSLCertificateOnError ||
3865 (view != null && view.getCertificate() != null)) {
3866 // add a 'View Certificate' button
3867 alertDialogBuilder.setNeutralButton(
3868 R.string.view_certificate,
3869 new DialogInterface.OnClickListener() {
3870 public void onClick(DialogInterface dialog,
3871 int whichButton) {
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 } else {
3884 // otherwise, display the top-most certificate from
3885 // the chain
3886 if (view.getCertificate() != null) {
3887 showSSLCertificate(tab);
3888 }
3889 }
3890 }
3891 });
3892 }
3893
3894 mPageInfoDialog = alertDialogBuilder.show();
3895 }
3896
3897 /**
3898 * Displays the main top-level page SSL certificate dialog
3899 * (accessible from the Page-Info dialog).
3900 * @param tab The tab to show certificate for.
3901 */
3902 private void showSSLCertificate(final TabControl.Tab tab) {
3903 final View certificateView =
3904 inflateCertificateView(tab.getWebView().getCertificate());
3905 if (certificateView == null) {
3906 return;
3907 }
3908
3909 LayoutInflater factory = LayoutInflater.from(this);
3910
3911 final LinearLayout placeholder =
3912 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3913
3914 LinearLayout ll = (LinearLayout) factory.inflate(
3915 R.layout.ssl_success, placeholder);
3916 ((TextView)ll.findViewById(R.id.success))
3917 .setText(R.string.ssl_certificate_is_valid);
3918
3919 mSSLCertificateView = tab;
3920 mSSLCertificateDialog =
3921 new AlertDialog.Builder(this)
3922 .setTitle(R.string.ssl_certificate).setIcon(
3923 R.drawable.ic_dialog_browser_certificate_secure)
3924 .setView(certificateView)
3925 .setPositiveButton(R.string.ok,
3926 new DialogInterface.OnClickListener() {
3927 public void onClick(DialogInterface dialog,
3928 int whichButton) {
3929 mSSLCertificateDialog = null;
3930 mSSLCertificateView = null;
3931
3932 showPageInfo(tab, false);
3933 }
3934 })
3935 .setOnCancelListener(
3936 new DialogInterface.OnCancelListener() {
3937 public void onCancel(DialogInterface dialog) {
3938 mSSLCertificateDialog = null;
3939 mSSLCertificateView = null;
3940
3941 showPageInfo(tab, false);
3942 }
3943 })
3944 .show();
3945 }
3946
3947 /**
3948 * Displays the SSL error certificate dialog.
3949 * @param view The target web-view.
3950 * @param handler The SSL error handler responsible for cancelling the
3951 * connection that resulted in an SSL error or proceeding per user request.
3952 * @param error The SSL error object.
3953 */
3954 private void showSSLCertificateOnError(
3955 final WebView view, final SslErrorHandler handler, final SslError error) {
3956
3957 final View certificateView =
3958 inflateCertificateView(error.getCertificate());
3959 if (certificateView == null) {
3960 return;
3961 }
3962
3963 LayoutInflater factory = LayoutInflater.from(this);
3964
3965 final LinearLayout placeholder =
3966 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3967
3968 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3969 LinearLayout ll = (LinearLayout)factory
3970 .inflate(R.layout.ssl_warning, placeholder);
3971 ((TextView)ll.findViewById(R.id.warning))
3972 .setText(R.string.ssl_untrusted);
3973 }
3974
3975 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3976 LinearLayout ll = (LinearLayout)factory
3977 .inflate(R.layout.ssl_warning, placeholder);
3978 ((TextView)ll.findViewById(R.id.warning))
3979 .setText(R.string.ssl_mismatch);
3980 }
3981
3982 if (error.hasError(SslError.SSL_EXPIRED)) {
3983 LinearLayout ll = (LinearLayout)factory
3984 .inflate(R.layout.ssl_warning, placeholder);
3985 ((TextView)ll.findViewById(R.id.warning))
3986 .setText(R.string.ssl_expired);
3987 }
3988
3989 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3990 LinearLayout ll = (LinearLayout)factory
3991 .inflate(R.layout.ssl_warning, placeholder);
3992 ((TextView)ll.findViewById(R.id.warning))
3993 .setText(R.string.ssl_not_yet_valid);
3994 }
3995
3996 mSSLCertificateOnErrorHandler = handler;
3997 mSSLCertificateOnErrorView = view;
3998 mSSLCertificateOnErrorError = error;
3999 mSSLCertificateOnErrorDialog =
4000 new AlertDialog.Builder(this)
4001 .setTitle(R.string.ssl_certificate).setIcon(
4002 R.drawable.ic_dialog_browser_certificate_partially_secure)
4003 .setView(certificateView)
4004 .setPositiveButton(R.string.ok,
4005 new DialogInterface.OnClickListener() {
4006 public void onClick(DialogInterface dialog,
4007 int whichButton) {
4008 mSSLCertificateOnErrorDialog = null;
4009 mSSLCertificateOnErrorView = null;
4010 mSSLCertificateOnErrorHandler = null;
4011 mSSLCertificateOnErrorError = null;
4012
4013 mWebViewClient.onReceivedSslError(
4014 view, handler, error);
4015 }
4016 })
4017 .setNeutralButton(R.string.page_info_view,
4018 new DialogInterface.OnClickListener() {
4019 public void onClick(DialogInterface dialog,
4020 int whichButton) {
4021 mSSLCertificateOnErrorDialog = null;
4022
4023 // do not clear the dialog state: we will
4024 // need to show the dialog again once the
4025 // user is done exploring the page-info details
4026
4027 showPageInfo(mTabControl.getTabFromView(view),
4028 true);
4029 }
4030 })
4031 .setOnCancelListener(
4032 new DialogInterface.OnCancelListener() {
4033 public void onCancel(DialogInterface dialog) {
4034 mSSLCertificateOnErrorDialog = null;
4035 mSSLCertificateOnErrorView = null;
4036 mSSLCertificateOnErrorHandler = null;
4037 mSSLCertificateOnErrorError = null;
4038
4039 mWebViewClient.onReceivedSslError(
4040 view, handler, error);
4041 }
4042 })
4043 .show();
4044 }
4045
4046 /**
4047 * Inflates the SSL certificate view (helper method).
4048 * @param certificate The SSL certificate.
4049 * @return The resultant certificate view with issued-to, issued-by,
4050 * issued-on, expires-on, and possibly other fields set.
4051 * If the input certificate is null, returns null.
4052 */
4053 private View inflateCertificateView(SslCertificate certificate) {
4054 if (certificate == null) {
4055 return null;
4056 }
4057
4058 LayoutInflater factory = LayoutInflater.from(this);
4059
4060 View certificateView = factory.inflate(
4061 R.layout.ssl_certificate, null);
4062
4063 // issued to:
4064 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4065 if (issuedTo != null) {
4066 ((TextView) certificateView.findViewById(R.id.to_common))
4067 .setText(issuedTo.getCName());
4068 ((TextView) certificateView.findViewById(R.id.to_org))
4069 .setText(issuedTo.getOName());
4070 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4071 .setText(issuedTo.getUName());
4072 }
4073
4074 // issued by:
4075 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4076 if (issuedBy != null) {
4077 ((TextView) certificateView.findViewById(R.id.by_common))
4078 .setText(issuedBy.getCName());
4079 ((TextView) certificateView.findViewById(R.id.by_org))
4080 .setText(issuedBy.getOName());
4081 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4082 .setText(issuedBy.getUName());
4083 }
4084
4085 // issued on:
4086 String issuedOn = reformatCertificateDate(
4087 certificate.getValidNotBefore());
4088 ((TextView) certificateView.findViewById(R.id.issued_on))
4089 .setText(issuedOn);
4090
4091 // expires on:
4092 String expiresOn = reformatCertificateDate(
4093 certificate.getValidNotAfter());
4094 ((TextView) certificateView.findViewById(R.id.expires_on))
4095 .setText(expiresOn);
4096
4097 return certificateView;
4098 }
4099
4100 /**
4101 * Re-formats the certificate date (Date.toString()) string to
4102 * a properly localized date string.
4103 * @return Properly localized version of the certificate date string and
4104 * the original certificate date string if fails to localize.
4105 * If the original string is null, returns an empty string "".
4106 */
4107 private String reformatCertificateDate(String certificateDate) {
4108 String reformattedDate = null;
4109
4110 if (certificateDate != null) {
4111 Date date = null;
4112 try {
4113 date = java.text.DateFormat.getInstance().parse(certificateDate);
4114 } catch (ParseException e) {
4115 date = null;
4116 }
4117
4118 if (date != null) {
4119 reformattedDate =
4120 DateFormat.getDateFormat(this).format(date);
4121 }
4122 }
4123
4124 return reformattedDate != null ? reformattedDate :
4125 (certificateDate != null ? certificateDate : "");
4126 }
4127
4128 /**
4129 * Displays an http-authentication dialog.
4130 */
4131 private void showHttpAuthentication(final HttpAuthHandler handler,
4132 final String host, final String realm, final String title,
4133 final String name, final String password, int focusId) {
4134 LayoutInflater factory = LayoutInflater.from(this);
4135 final View v = factory
4136 .inflate(R.layout.http_authentication, null);
4137 if (name != null) {
4138 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4139 }
4140 if (password != null) {
4141 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4142 }
4143
4144 String titleText = title;
4145 if (titleText == null) {
4146 titleText = getText(R.string.sign_in_to).toString().replace(
4147 "%s1", host).replace("%s2", realm);
4148 }
4149
4150 mHttpAuthHandler = handler;
4151 AlertDialog dialog = new AlertDialog.Builder(this)
4152 .setTitle(titleText)
4153 .setIcon(android.R.drawable.ic_dialog_alert)
4154 .setView(v)
4155 .setPositiveButton(R.string.action,
4156 new DialogInterface.OnClickListener() {
4157 public void onClick(DialogInterface dialog,
4158 int whichButton) {
4159 String nm = ((EditText) v
4160 .findViewById(R.id.username_edit))
4161 .getText().toString();
4162 String pw = ((EditText) v
4163 .findViewById(R.id.password_edit))
4164 .getText().toString();
4165 BrowserActivity.this.setHttpAuthUsernamePassword
4166 (host, realm, nm, pw);
4167 handler.proceed(nm, pw);
4168 mHttpAuthenticationDialog = null;
4169 mHttpAuthHandler = null;
4170 }})
4171 .setNegativeButton(R.string.cancel,
4172 new DialogInterface.OnClickListener() {
4173 public void onClick(DialogInterface dialog,
4174 int whichButton) {
4175 handler.cancel();
4176 BrowserActivity.this.resetTitleAndRevertLockIcon();
4177 mHttpAuthenticationDialog = null;
4178 mHttpAuthHandler = null;
4179 }})
4180 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4181 public void onCancel(DialogInterface dialog) {
4182 handler.cancel();
4183 BrowserActivity.this.resetTitleAndRevertLockIcon();
4184 mHttpAuthenticationDialog = null;
4185 mHttpAuthHandler = null;
4186 }})
4187 .create();
4188 // Make the IME appear when the dialog is displayed if applicable.
4189 dialog.getWindow().setSoftInputMode(
4190 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4191 dialog.show();
4192 if (focusId != 0) {
4193 dialog.findViewById(focusId).requestFocus();
4194 } else {
4195 v.findViewById(R.id.username_edit).requestFocus();
4196 }
4197 mHttpAuthenticationDialog = dialog;
4198 }
4199
4200 public int getProgress() {
4201 WebView w = mTabControl.getCurrentWebView();
4202 if (w != null) {
4203 return w.getProgress();
4204 } else {
4205 return 100;
4206 }
4207 }
4208
4209 /**
4210 * Set HTTP authentication password.
4211 *
4212 * @param host The host for the password
4213 * @param realm The realm for the password
4214 * @param username The username for the password. If it is null, it means
4215 * password can't be saved.
4216 * @param password The password
4217 */
4218 public void setHttpAuthUsernamePassword(String host, String realm,
4219 String username,
4220 String password) {
4221 WebView w = mTabControl.getCurrentWebView();
4222 if (w != null) {
4223 w.setHttpAuthUsernamePassword(host, realm, username, password);
4224 }
4225 }
4226
4227 /**
4228 * connectivity manager says net has come or gone... inform the user
4229 * @param up true if net has come up, false if net has gone down
4230 */
4231 public void onNetworkToggle(boolean up) {
4232 if (up == mIsNetworkUp) {
4233 return;
4234 } else if (up) {
4235 mIsNetworkUp = true;
4236 if (mAlertDialog != null) {
4237 mAlertDialog.cancel();
4238 mAlertDialog = null;
4239 }
4240 } else {
4241 mIsNetworkUp = false;
4242 if (mInLoad && mAlertDialog == null) {
4243 mAlertDialog = new AlertDialog.Builder(this)
4244 .setTitle(R.string.loadSuspendedTitle)
4245 .setMessage(R.string.loadSuspended)
4246 .setPositiveButton(R.string.ok, null)
4247 .show();
4248 }
4249 }
4250 WebView w = mTabControl.getCurrentWebView();
4251 if (w != null) {
4252 w.setNetworkAvailable(up);
4253 }
4254 }
4255
4256 @Override
4257 protected void onActivityResult(int requestCode, int resultCode,
4258 Intent intent) {
4259 switch (requestCode) {
4260 case COMBO_PAGE:
4261 if (resultCode == RESULT_OK && intent != null) {
4262 String data = intent.getAction();
4263 Bundle extras = intent.getExtras();
4264 if (extras != null && extras.getBoolean("new_window", false)) {
4265 openTab(data);
4266 } else {
4267 final TabControl.Tab currentTab =
4268 mTabControl.getCurrentTab();
4269 // If the Window overview is up and we are not in the
4270 // middle of an animation, animate away from it to the
4271 // current tab.
4272 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004273 sendAnimateFromOverview(currentTab, false, new UrlData(data),
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 TAB_OVERVIEW_DELAY, null);
4275 } else {
4276 dismissSubWindow(currentTab);
4277 if (data != null && data.length() != 0) {
4278 getTopWindow().loadUrl(data);
4279 }
4280 }
4281 }
4282 }
4283 break;
4284 default:
4285 break;
4286 }
4287 getTopWindow().requestFocus();
4288 }
4289
4290 /*
4291 * This method is called as a result of the user selecting the options
4292 * menu to see the download window, or when a download changes state. It
4293 * shows the download window ontop of the current window.
4294 */
4295 /* package */ void viewDownloads(Uri downloadRecord) {
4296 Intent intent = new Intent(this,
4297 BrowserDownloadPage.class);
4298 intent.setData(downloadRecord);
4299 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4300
4301 }
4302
4303 /**
4304 * Handle results from Tab Switcher mTabOverview tool
4305 */
4306 private class TabListener implements ImageGrid.Listener {
4307 public void remove(int position) {
4308 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004309 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004310 throw new AssertionError();
4311 }
4312
4313 // Remember the current tab.
4314 TabControl.Tab current = mTabControl.getCurrentTab();
4315 final TabControl.Tab remove = mTabControl.getTab(position);
4316 mTabControl.removeTab(remove);
4317 // If we removed the current tab, use the tab at position - 1 if
4318 // possible.
4319 if (current == remove) {
4320 // If the user removes the last tab, act like the New Tab item
4321 // was clicked on.
4322 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004323 current = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004324 sendAnimateFromOverview(current, true,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004325 new UrlData(mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004326 } else {
4327 final int index = position > 0 ? (position - 1) : 0;
4328 current = mTabControl.getTab(index);
4329 }
4330 }
4331
4332 // The tab overview could have been dismissed before this method is
4333 // called.
4334 if (mTabOverview != null) {
4335 // Remove the tab and change the index.
4336 mTabOverview.remove(position);
4337 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4338 }
4339
4340 // Only the current tab ensures its WebView is non-null. This
4341 // implies that we are reloading the freed tab.
4342 mTabControl.setCurrentTab(current);
4343 }
4344 public void onClick(int index) {
4345 // Change the tab if necessary.
4346 // Index equals ImageGrid.CANCEL when pressing back from the tab
4347 // overview.
4348 if (index == ImageGrid.CANCEL) {
4349 index = mTabControl.getCurrentIndex();
4350 // The current index is -1 if the current tab was removed.
4351 if (index == -1) {
4352 // Take the last tab as a fallback.
4353 index = mTabControl.getTabCount() - 1;
4354 }
4355 }
4356
The Android Open Source Project0c908882009-03-03 19:32:16 -08004357 // NEW_TAB means that the "New Tab" cell was clicked on.
4358 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004359 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004360 } else {
4361 sendAnimateFromOverview(mTabControl.getTab(index),
Patrick Scott95d601f2009-06-11 10:06:46 -04004362 false, EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363 }
4364 }
4365 }
4366
4367 // A fake View that draws the WebView's picture with a fast zoom filter.
4368 // The View is used in case the tab is freed during the animation because
4369 // of low memory.
4370 private static class AnimatingView extends View {
4371 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4372 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4373 private static final DrawFilter sZoomFilter =
4374 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4375 private final Picture mPicture;
4376 private final float mScale;
4377 private final int mScrollX;
4378 private final int mScrollY;
4379 final TabControl.Tab mTab;
4380
4381 AnimatingView(Context ctxt, TabControl.Tab t) {
4382 super(ctxt);
4383 mTab = t;
4384 // Use the top window in the animation since the tab overview will
4385 // display the top window in each cell.
4386 final WebView w = t.getTopWindow();
4387 mPicture = w.capturePicture();
4388 mScale = w.getScale() / w.getWidth();
4389 mScrollX = w.getScrollX();
4390 mScrollY = w.getScrollY();
4391 }
4392
4393 @Override
4394 protected void onDraw(Canvas canvas) {
4395 canvas.save();
4396 canvas.drawColor(Color.WHITE);
4397 if (mPicture != null) {
4398 canvas.setDrawFilter(sZoomFilter);
4399 float scale = getWidth() * mScale;
4400 canvas.scale(scale, scale);
4401 canvas.translate(-mScrollX, -mScrollY);
4402 canvas.drawPicture(mPicture);
4403 }
4404 canvas.restore();
4405 }
4406 }
4407
4408 /**
4409 * Open the tab picker. This function will always use the current tab in
4410 * its animation.
4411 * @param stay boolean stating whether the tab picker is to remain open
4412 * (in which case it needs a listener and its menu) or not.
4413 * @param index The index of the tab to show as the selection in the tab
4414 * overview.
4415 * @param remove If true, the tab at index will be removed after the
4416 * animation completes.
4417 */
4418 private void tabPicker(final boolean stay, final int index,
4419 final boolean remove) {
4420 if (mTabOverview != null) {
4421 return;
4422 }
4423
4424 int size = mTabControl.getTabCount();
4425
4426 TabListener l = null;
4427 if (stay) {
4428 l = mTabListener = new TabListener();
4429 }
4430 mTabOverview = new ImageGrid(this, stay, l);
4431
4432 for (int i = 0; i < size; i++) {
4433 final TabControl.Tab t = mTabControl.getTab(i);
4434 mTabControl.populatePickerData(t);
4435 mTabOverview.add(t);
4436 }
4437
4438 // Tell the tab overview to show the current tab, the tab overview will
4439 // handle the "New Tab" case.
4440 int currentIndex = mTabControl.getCurrentIndex();
4441 mTabOverview.setCurrentIndex(currentIndex);
4442
4443 // Attach the tab overview.
4444 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4445
4446 // Create a fake AnimatingView to animate the WebView's picture.
4447 final TabControl.Tab current = mTabControl.getCurrentTab();
4448 final AnimatingView v = new AnimatingView(this, current);
4449 mContentView.addView(v, COVER_SCREEN_PARAMS);
4450 removeTabFromContentView(current);
4451 // Pause timers to get the animation smoother.
4452 current.getWebView().pauseTimers();
4453
4454 // Send a message so the tab picker has a chance to layout and get
4455 // positions for all the cells.
4456 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4457 index, remove ? 1 : 0, v));
4458 // Setting this will indicate that we are animating to the overview. We
4459 // set it here to prevent another request to animate from coming in
4460 // between now and when ANIMATE_TO_OVERVIEW is handled.
4461 mAnimationCount++;
4462 // Always change the title bar to the window overview title while
4463 // animating.
4464 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4465 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4466 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4467 Window.PROGRESS_VISIBILITY_OFF);
4468 setTitle(R.string.tab_picker_title);
4469 // Make the menu empty until the animation completes.
4470 mMenuState = EMPTY_MENU;
4471 }
4472
4473 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4474 WebView current = mTabControl.getCurrentWebView();
4475 if (current == null) {
4476 return;
4477 }
4478 Intent intent = new Intent(this,
4479 CombinedBookmarkHistoryActivity.class);
4480 String title = current.getTitle();
4481 String url = current.getUrl();
4482 // Just in case the user opens bookmarks before a page finishes loading
4483 // so the current history item, and therefore the page, is null.
4484 if (null == url) {
4485 url = mLastEnteredUrl;
4486 // This can happen.
4487 if (null == url) {
4488 url = mSettings.getHomePage();
4489 }
4490 }
4491 // In case the web page has not yet received its associated title.
4492 if (title == null) {
4493 title = url;
4494 }
4495 intent.putExtra("title", title);
4496 intent.putExtra("url", url);
4497 intent.putExtra("maxTabsOpen",
4498 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4499 if (startWithHistory) {
4500 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4501 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4502 }
4503 startActivityForResult(intent, COMBO_PAGE);
4504 }
4505
4506 // Called when loading from context menu or LOAD_URL message
4507 private void loadURL(WebView view, String url) {
4508 // In case the user enters nothing.
4509 if (url != null && url.length() != 0 && view != null) {
4510 url = smartUrlFilter(url);
4511 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4512 view.loadUrl(url);
4513 }
4514 }
4515 }
4516
4517 private void checkMemory() {
4518 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4519 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4520 .getMemoryInfo(mi);
4521 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4522 // mi.threshold) for now
4523 // if (mi.lowMemory) {
4524 if (mi.availMem < mi.threshold) {
4525 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4526 + (mi.availMem / 1024) + "K threshold="
4527 + (mi.threshold / 1024) + "K");
4528 mTabControl.freeMemory();
4529 }
4530 }
4531
4532 private String smartUrlFilter(Uri inUri) {
4533 if (inUri != null) {
4534 return smartUrlFilter(inUri.toString());
4535 }
4536 return null;
4537 }
4538
4539
4540 // get window count
4541
4542 int getWindowCount(){
4543 if(mTabControl != null){
4544 return mTabControl.getTabCount();
4545 }
4546 return 0;
4547 }
4548
4549 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4550 "(?i)" + // switch on case insensitive matching
4551 "(" + // begin group for schema
4552 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004553 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004554 ")" +
4555 "(.*)" );
4556
4557 /**
4558 * Attempts to determine whether user input is a URL or search
4559 * terms. Anything with a space is passed to search.
4560 *
4561 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4562 * "Http://" converts to "http://"
4563 *
4564 * @return Original or modified URL
4565 *
4566 */
4567 String smartUrlFilter(String url) {
4568
4569 String inUrl = url.trim();
4570 boolean hasSpace = inUrl.indexOf(' ') != -1;
4571
4572 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4573 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004574 // force scheme to lowercase
4575 String scheme = matcher.group(1);
4576 String lcScheme = scheme.toLowerCase();
4577 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004578 inUrl = lcScheme + matcher.group(2);
4579 }
4580 if (hasSpace) {
4581 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004582 }
4583 return inUrl;
4584 }
4585 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004586 // FIXME: Is this the correct place to add to searches?
4587 // what if someone else calls this function?
4588 int shortcut = parseUrlShortcut(inUrl);
4589 if (shortcut != SHORTCUT_INVALID) {
4590 Browser.addSearchUrl(mResolver, inUrl);
4591 String query = inUrl.substring(2);
4592 switch (shortcut) {
4593 case SHORTCUT_GOOGLE_SEARCH:
4594 return composeSearchUrl(query);
4595 case SHORTCUT_WIKIPEDIA_SEARCH:
4596 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4597 case SHORTCUT_DICTIONARY_SEARCH:
4598 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4599 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004600 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004601 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004602 }
4603 }
4604 } else {
4605 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4606 return URLUtil.guessUrl(inUrl);
4607 }
4608 }
4609
4610 Browser.addSearchUrl(mResolver, inUrl);
4611 return composeSearchUrl(inUrl);
4612 }
4613
4614 /* package */ String composeSearchUrl(String search) {
4615 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4616 QUERY_PLACE_HOLDER);
4617 }
4618
4619 /* package */void setBaseSearchUrl(String url) {
4620 if (url == null || url.length() == 0) {
4621 /*
4622 * get the google search url based on the SIM. Default is US. NOTE:
4623 * This code uses resources to optionally select the search Uri,
4624 * based on the MCC value from the SIM. The default string will most
4625 * likely be fine. It is parameterized to accept info from the
4626 * Locale, the language code is the first parameter (%1$s) and the
4627 * country code is the second (%2$s). This code must function in the
4628 * same way as a similar lookup in
4629 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4630 * change either of these functions, change them both. (The same is
4631 * true for the underlying resource strings, which are stored in
4632 * mcc-specific xml files.)
4633 */
4634 Locale l = Locale.getDefault();
Bill Napiere9651c32009-05-05 13:16:30 -07004635 String language = l.getLanguage();
4636 String country = l.getCountry().toLowerCase();
4637 // Chinese and Portuguese have two langauge variants.
4638 if ("zh".equals(language)) {
4639 if ("cn".equals(country)) {
4640 language = "zh-CN";
4641 } else if ("tw".equals(country)) {
4642 language = "zh-TW";
4643 }
4644 } else if ("pt".equals(language)) {
4645 if ("br".equals(country)) {
4646 language = "pt-BR";
4647 } else if ("pt".equals(country)) {
4648 language = "pt-PT";
4649 }
4650 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004651 QuickSearch_G = getResources().getString(
Bill Napiere9651c32009-05-05 13:16:30 -07004652 R.string.google_search_base,
4653 language,
4654 country)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004655 + "client=ms-"
Ramanan Rajeswaranf447f262009-03-24 20:40:12 -07004656 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004657 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4658 } else {
4659 QuickSearch_G = url;
4660 }
4661 }
4662
4663 private final static int LOCK_ICON_UNSECURE = 0;
4664 private final static int LOCK_ICON_SECURE = 1;
4665 private final static int LOCK_ICON_MIXED = 2;
4666
4667 private int mLockIconType = LOCK_ICON_UNSECURE;
4668 private int mPrevLockType = LOCK_ICON_UNSECURE;
4669
4670 private BrowserSettings mSettings;
4671 private TabControl mTabControl;
4672 private ContentResolver mResolver;
4673 private FrameLayout mContentView;
4674 private ImageGrid mTabOverview;
4675
4676 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4677 // view, we should rewrite this.
4678 private int mCurrentMenuState = 0;
4679 private int mMenuState = R.id.MAIN_MENU;
4680 private static final int EMPTY_MENU = -1;
4681 private Menu mMenu;
4682
4683 private FindDialog mFindDialog;
4684 // Used to prevent chording to result in firing two shortcuts immediately
4685 // one after another. Fixes bug 1211714.
4686 boolean mCanChord;
4687
4688 private boolean mInLoad;
4689 private boolean mIsNetworkUp;
4690
4691 private boolean mPageStarted;
4692 private boolean mActivityInPause = true;
4693
4694 private boolean mMenuIsDown;
4695
4696 private final KeyTracker mKeyTracker = new KeyTracker(this);
4697
4698 // As trackball doesn't send repeat down, we have to track it ourselves
4699 private boolean mTrackTrackball;
4700
4701 private static boolean mInTrace;
4702
4703 // Performance probe
4704 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4705 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4706 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4707 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4708 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4709 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4710 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4711 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4712 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4713 };
4714
4715 private long mStart;
4716 private long mProcessStart;
4717 private long mUserStart;
4718 private long mSystemStart;
4719 private long mIdleStart;
4720 private long mIrqStart;
4721
4722 private long mUiStart;
4723
4724 private Drawable mMixLockIcon;
4725 private Drawable mSecLockIcon;
4726 private Drawable mGenericFavicon;
4727
4728 /* hold a ref so we can auto-cancel if necessary */
4729 private AlertDialog mAlertDialog;
4730
4731 // Wait for credentials before loading google.com
4732 private ProgressDialog mCredsDlg;
4733
4734 // The up-to-date URL and title (these can be different from those stored
4735 // in WebView, since it takes some time for the information in WebView to
4736 // get updated)
4737 private String mUrl;
4738 private String mTitle;
4739
4740 // As PageInfo has different style for landscape / portrait, we have
4741 // to re-open it when configuration changed
4742 private AlertDialog mPageInfoDialog;
4743 private TabControl.Tab mPageInfoView;
4744 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4745 // dialog, we should not just dismiss it, but should get back to the
4746 // SSL-certificate-on-error dialog. This flag is used to store this state
4747 private Boolean mPageInfoFromShowSSLCertificateOnError;
4748
4749 // as SSLCertificateOnError has different style for landscape / portrait,
4750 // we have to re-open it when configuration changed
4751 private AlertDialog mSSLCertificateOnErrorDialog;
4752 private WebView mSSLCertificateOnErrorView;
4753 private SslErrorHandler mSSLCertificateOnErrorHandler;
4754 private SslError mSSLCertificateOnErrorError;
4755
4756 // as SSLCertificate has different style for landscape / portrait, we
4757 // have to re-open it when configuration changed
4758 private AlertDialog mSSLCertificateDialog;
4759 private TabControl.Tab mSSLCertificateView;
4760
4761 // as HttpAuthentication has different style for landscape / portrait, we
4762 // have to re-open it when configuration changed
4763 private AlertDialog mHttpAuthenticationDialog;
4764 private HttpAuthHandler mHttpAuthHandler;
4765
4766 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4767 new FrameLayout.LayoutParams(
4768 ViewGroup.LayoutParams.FILL_PARENT,
4769 ViewGroup.LayoutParams.FILL_PARENT);
4770 // We may provide UI to customize these
4771 // Google search from the browser
4772 static String QuickSearch_G;
4773 // Wikipedia search
4774 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4775 // Dictionary search
4776 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4777 // Google Mobile Local search
4778 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4779
4780 final static String QUERY_PLACE_HOLDER = "%s";
4781
4782 // "source" parameter for Google search through search key
4783 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4784 // "source" parameter for Google search through goto menu
4785 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4786 // "source" parameter for Google search through simplily type
4787 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4788 // "source" parameter for Google search suggested by the browser
4789 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4790 // "source" parameter for Google search from unknown source
4791 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4792
4793 private final static String LOGTAG = "browser";
4794
4795 private TabListener mTabListener;
4796
4797 private String mLastEnteredUrl;
4798
4799 private PowerManager.WakeLock mWakeLock;
4800 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4801
4802 private Toast mStopToast;
4803
4804 // Used during animations to prevent other animations from being triggered.
4805 // A count is used since the animation to and from the Window overview can
4806 // overlap. A count of 0 means no animation where a count of > 0 means
4807 // there are animations in progress.
4808 private int mAnimationCount;
4809
4810 // As the ids are dynamically created, we can't guarantee that they will
4811 // be in sequence, so this static array maps ids to a window number.
4812 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4813 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4814 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4815 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4816
4817 // monitor platform changes
4818 private IntentFilter mNetworkStateChangedFilter;
4819 private BroadcastReceiver mNetworkStateIntentReceiver;
4820
4821 // activity requestCode
4822 final static int COMBO_PAGE = 1;
4823 final static int DOWNLOAD_PAGE = 2;
4824 final static int PREFERENCES_PAGE = 3;
4825
4826 // the frenquency of checking whether system memory is low
4827 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004828
4829 /**
4830 * A UrlData class to abstract how the content will be set to WebView.
4831 * This base class uses loadUrl to show the content.
4832 */
4833 private static class UrlData {
4834 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004835 byte[] mPostData;
4836
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004837 UrlData(String url) {
4838 this.mUrl = url;
4839 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004840
4841 void setPostData(byte[] postData) {
4842 mPostData = postData;
4843 }
4844
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004845 boolean isEmpty() {
4846 return mUrl == null || mUrl.length() == 0;
4847 }
4848
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004849 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004850 if (mPostData != null) {
4851 webView.postUrl(mUrl, mPostData);
4852 } else {
4853 webView.loadUrl(mUrl);
4854 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004855 }
4856 };
4857
4858 /**
4859 * A subclass of UrlData class that can display inlined content using
4860 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4861 */
4862 private static class InlinedUrlData extends UrlData {
4863 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4864 super(failUrl);
4865 mInlined = inlined;
4866 mMimeType = mimeType;
4867 mEncoding = encoding;
4868 }
4869 String mMimeType;
4870 String mInlined;
4871 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004872 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004873 boolean isEmpty() {
4874 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4875 }
4876
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004877 @Override
4878 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004879 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4880 }
4881 }
4882
4883 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004884}