blob: eae24f1a1bef29c05d81c871a31cc1b4ebeaaa55 [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) {
Patrick Scottd068f802009-06-22 11:46:06 -04002115 if (mTabOverview != null) {
2116 mTabOverview.requestFocus();
2117 // Clear the listener so we don't trigger a tab
2118 // selection.
2119 mTabOverview.setListener(null);
2120 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 }
2122 public void onAnimationRepeat(Animation a) {}
2123 public void onAnimationEnd(Animation a) {
2124 // We are no longer animating so decrement the count.
2125 mAnimationCount--;
2126 // Make the view GONE so that it will not draw between
2127 // now and when the Runnable is handled.
2128 view.setVisibility(View.GONE);
2129 // Post a runnable since we can't modify the view
2130 // hierarchy during this callback.
2131 mHandler.post(new Runnable() {
2132 public void run() {
2133 // Remove the AnimatingView.
2134 mContentView.removeView(view);
2135 if (mTabOverview != null) {
2136 // Make newIndex visible.
2137 mTabOverview.setCurrentIndex(newIndex);
2138 // Restore the listener.
2139 mTabOverview.setListener(mTabListener);
2140 // Change the menu to TAB_MENU if the
2141 // ImageGrid is interactive.
2142 if (mTabOverview.isLive()) {
2143 mMenuState = R.id.TAB_MENU;
2144 mTabOverview.requestFocus();
2145 }
2146 }
2147 // If a remove was requested, remove the tab.
2148 if (remove) {
2149 // During a remove, the current tab has
2150 // already changed. Remember the current one
2151 // here.
2152 final TabControl.Tab currentTab =
2153 mTabControl.getCurrentTab();
2154 // Remove the tab at newIndex from
2155 // TabControl and the tab overview.
2156 final TabControl.Tab tab =
2157 mTabControl.getTab(newIndex);
2158 mTabControl.removeTab(tab);
2159 // Restore the current tab.
2160 if (currentTab != tab) {
2161 mTabControl.setCurrentTab(currentTab);
2162 }
2163 if (mTabOverview != null) {
2164 mTabOverview.remove(newIndex);
2165 // Make the current tab visible.
2166 mTabOverview.setCurrentIndex(
2167 mTabControl.getCurrentIndex());
2168 }
2169 }
2170 }
2171 });
2172 }
2173 };
2174
2175 // Do an animation if there is a view to animate to.
2176 if (v != null) {
2177 // Create our animation
2178 final Animation anim = createTabAnimation(view, v, true);
2179 anim.setAnimationListener(l);
2180 // Start animating
2181 view.startAnimation(anim);
2182 } else {
2183 // If something goes wrong and we didn't find a view to animate to,
2184 // just do everything here.
2185 l.onAnimationStart(null);
2186 l.onAnimationEnd(null);
2187 }
2188 }
2189
2190 // Animate from the tab picker. The index supplied is the index to animate
2191 // from.
2192 private void animateFromTabOverview(final AnimatingView view,
2193 final boolean newTab, final Message msg) {
2194 // firstVisible is the first visible tab on the screen. This helps
2195 // to know which corner of the screen the selected tab is.
2196 int firstVisible = mTabOverview.getFirstVisiblePosition();
2197 // tabPosition is the 0-based index of of the tab being opened
2198 int tabPosition = mTabControl.getTabIndex(view.mTab);
2199 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2200 // Add one to make room for the "New Tab" cell.
2201 tabPosition++;
2202 }
2203 // If this is a new tab, animate from the "New Tab" cell.
2204 if (newTab) {
2205 tabPosition = 0;
2206 }
2207 // Location corresponds to the four corners of the screen.
2208 // A new tab or 0 is upper left, 0 for an old tab is upper
2209 // right, 1 is lower left, and 2 is lower right
2210 int location = tabPosition - firstVisible;
2211
2212 // Find the view at this location.
2213 final View v = mTabOverview.getChildAt(location);
2214
2215 // Wait until the animation completes to replace the AnimatingView.
2216 final Animation.AnimationListener l =
2217 new Animation.AnimationListener() {
2218 public void onAnimationStart(Animation a) {}
2219 public void onAnimationRepeat(Animation a) {}
2220 public void onAnimationEnd(Animation a) {
2221 mHandler.post(new Runnable() {
2222 public void run() {
2223 mContentView.removeView(view);
2224 // Dismiss the tab overview. If the cell at the
2225 // given location is null, set the fade
2226 // parameter to true.
2227 dismissTabOverview(v == null);
2228 TabControl.Tab t =
2229 mTabControl.getCurrentTab();
2230 mMenuState = R.id.MAIN_MENU;
2231 // Resume regular updates.
2232 t.getWebView().resumeTimers();
2233 // Dispatch the message after the animation
2234 // completes.
2235 if (msg != null) {
2236 msg.sendToTarget();
2237 }
2238 // The animation is done and the tab overview is
2239 // gone so allow key events and other animations
2240 // to begin.
2241 mAnimationCount--;
2242 // Reset all the title bar info.
2243 resetTitle();
2244 }
2245 });
2246 }
2247 };
2248
2249 if (v != null) {
2250 final Animation anim = createTabAnimation(view, v, false);
2251 // Set the listener and start animating
2252 anim.setAnimationListener(l);
2253 view.startAnimation(anim);
2254 // Make the view VISIBLE during the animation.
2255 view.setVisibility(View.VISIBLE);
2256 } else {
2257 // Go ahead and do all the cleanup.
2258 l.onAnimationEnd(null);
2259 }
2260 }
2261
2262 // Dismiss the tab overview applying a fade if needed.
2263 private void dismissTabOverview(final boolean fade) {
2264 if (fade) {
2265 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2266 anim.setDuration(500);
2267 anim.startNow();
2268 mTabOverview.startAnimation(anim);
2269 }
2270 // Just in case there was a problem with animating away from the tab
2271 // overview
2272 WebView current = mTabControl.getCurrentWebView();
2273 if (current != null) {
2274 current.setVisibility(View.VISIBLE);
2275 } else {
2276 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2277 }
2278 // Make the sub window container visible.
2279 if (mTabControl.getCurrentSubWindow() != null) {
2280 mTabControl.getCurrentTab().getSubWebViewContainer()
2281 .setVisibility(View.VISIBLE);
2282 }
2283 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002284 // Clear all the data for tab picker so next time it will be
2285 // recreated.
2286 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 mTabOverview.clear();
2288 mTabOverview = null;
2289 mTabListener = null;
2290 }
2291
2292 private void openTab(String url) {
2293 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002294 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 if (t != null) {
2296 t.getWebView().loadUrl(url);
2297 }
2298 } else {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002299 openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002300 }
2301 }
2302
2303 private class Copy implements OnMenuItemClickListener {
2304 private CharSequence mText;
2305
2306 public boolean onMenuItemClick(MenuItem item) {
2307 copy(mText);
2308 return true;
2309 }
2310
2311 public Copy(CharSequence toCopy) {
2312 mText = toCopy;
2313 }
2314 }
2315
2316 private class Download implements OnMenuItemClickListener {
2317 private String mText;
2318
2319 public boolean onMenuItemClick(MenuItem item) {
2320 onDownloadStartNoStream(mText, null, null, null, -1);
2321 return true;
2322 }
2323
2324 public Download(String toDownload) {
2325 mText = toDownload;
2326 }
2327 }
2328
2329 private void copy(CharSequence text) {
2330 try {
2331 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2332 if (clip != null) {
2333 clip.setClipboardText(text);
2334 }
2335 } catch (android.os.RemoteException e) {
2336 Log.e(LOGTAG, "Copy failed", e);
2337 }
2338 }
2339
2340 /**
2341 * Resets the browser title-view to whatever it must be (for example, if we
2342 * load a page from history).
2343 */
2344 private void resetTitle() {
2345 resetLockIcon();
2346 resetTitleIconAndProgress();
2347 }
2348
2349 /**
2350 * Resets the browser title-view to whatever it must be
2351 * (for example, if we had a loading error)
2352 * When we have a new page, we call resetTitle, when we
2353 * have to reset the titlebar to whatever it used to be
2354 * (for example, if the user chose to stop loading), we
2355 * call resetTitleAndRevertLockIcon.
2356 */
2357 /* package */ void resetTitleAndRevertLockIcon() {
2358 revertLockIcon();
2359 resetTitleIconAndProgress();
2360 }
2361
2362 /**
2363 * Reset the title, favicon, and progress.
2364 */
2365 private void resetTitleIconAndProgress() {
2366 WebView current = mTabControl.getCurrentWebView();
2367 if (current == null) {
2368 return;
2369 }
2370 resetTitleAndIcon(current);
2371 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 mWebChromeClient.onProgressChanged(current, progress);
2373 }
2374
2375 // Reset the title and the icon based on the given item.
2376 private void resetTitleAndIcon(WebView view) {
2377 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2378 if (item != null) {
2379 setUrlTitle(item.getUrl(), item.getTitle());
2380 setFavicon(item.getFavicon());
2381 } else {
2382 setUrlTitle(null, null);
2383 setFavicon(null);
2384 }
2385 }
2386
2387 /**
2388 * Sets a title composed of the URL and the title string.
2389 * @param url The URL of the site being loaded.
2390 * @param title The title of the site being loaded.
2391 */
2392 private void setUrlTitle(String url, String title) {
2393 mUrl = url;
2394 mTitle = title;
2395
2396 // While the tab overview is animating or being shown, block changes
2397 // to the title.
2398 if (mAnimationCount == 0 && mTabOverview == null) {
2399 setTitle(buildUrlTitle(url, title));
2400 }
2401 }
2402
2403 /**
2404 * Builds and returns the page title, which is some
2405 * combination of the page URL and title.
2406 * @param url The URL of the site being loaded.
2407 * @param title The title of the site being loaded.
2408 * @return The page title.
2409 */
2410 private String buildUrlTitle(String url, String title) {
2411 String urlTitle = "";
2412
2413 if (url != null) {
2414 String titleUrl = buildTitleUrl(url);
2415
2416 if (title != null && 0 < title.length()) {
2417 if (titleUrl != null && 0 < titleUrl.length()) {
2418 urlTitle = titleUrl + ": " + title;
2419 } else {
2420 urlTitle = title;
2421 }
2422 } else {
2423 if (titleUrl != null) {
2424 urlTitle = titleUrl;
2425 }
2426 }
2427 }
2428
2429 return urlTitle;
2430 }
2431
2432 /**
2433 * @param url The URL to build a title version of the URL from.
2434 * @return The title version of the URL or null if fails.
2435 * The title version of the URL can be either the URL hostname,
2436 * or the hostname with an "https://" prefix (for secure URLs),
2437 * or an empty string if, for example, the URL in question is a
2438 * file:// URL with no hostname.
2439 */
2440 private static String buildTitleUrl(String url) {
2441 String titleUrl = null;
2442
2443 if (url != null) {
2444 try {
2445 // parse the url string
2446 URL urlObj = new URL(url);
2447 if (urlObj != null) {
2448 titleUrl = "";
2449
2450 String protocol = urlObj.getProtocol();
2451 String host = urlObj.getHost();
2452
2453 if (host != null && 0 < host.length()) {
2454 titleUrl = host;
2455 if (protocol != null) {
2456 // if a secure site, add an "https://" prefix!
2457 if (protocol.equalsIgnoreCase("https")) {
2458 titleUrl = protocol + "://" + host;
2459 }
2460 }
2461 }
2462 }
2463 } catch (MalformedURLException e) {}
2464 }
2465
2466 return titleUrl;
2467 }
2468
2469 // Set the favicon in the title bar.
2470 private void setFavicon(Bitmap icon) {
2471 // While the tab overview is animating or being shown, block changes to
2472 // the favicon.
2473 if (mAnimationCount > 0 || mTabOverview != null) {
2474 return;
2475 }
2476 Drawable[] array = new Drawable[2];
2477 PaintDrawable p = new PaintDrawable(Color.WHITE);
2478 p.setCornerRadius(3f);
2479 array[0] = p;
2480 if (icon == null) {
2481 array[1] = mGenericFavicon;
2482 } else {
2483 array[1] = new BitmapDrawable(icon);
2484 }
2485 LayerDrawable d = new LayerDrawable(array);
2486 d.setLayerInset(1, 2, 2, 2, 2);
2487 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2488 }
2489
2490 /**
2491 * Saves the current lock-icon state before resetting
2492 * the lock icon. If we have an error, we may need to
2493 * roll back to the previous state.
2494 */
2495 private void saveLockIcon() {
2496 mPrevLockType = mLockIconType;
2497 }
2498
2499 /**
2500 * Reverts the lock-icon state to the last saved state,
2501 * for example, if we had an error, and need to cancel
2502 * the load.
2503 */
2504 private void revertLockIcon() {
2505 mLockIconType = mPrevLockType;
2506
Dave Bort31a6d1c2009-04-13 15:56:49 -07002507 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2509 " revert lock icon to " + mLockIconType);
2510 }
2511
2512 updateLockIconImage(mLockIconType);
2513 }
2514
2515 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2516 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2517 // Animate to the tab picker, remove the current tab, then
2518 // animate away from the tab picker to the parent WebView.
2519 tabPicker(false, indexFrom, remove);
2520 // Change to the parent tab
2521 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2522 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002523 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002524 } else {
2525 // Increment this here so that no other animations can happen in
2526 // between the end of the tab picker transition and the beginning
2527 // of openTabAndShow. This has a matching decrement in the handler
2528 // of OPEN_TAB_AND_SHOW.
2529 mAnimationCount++;
2530 // Send a message to open a new tab.
2531 mHandler.sendMessageDelayed(
2532 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2533 mSettings.getHomePage()), delay);
2534 }
2535 }
2536
2537 private void goBackOnePageOrQuit() {
2538 TabControl.Tab current = mTabControl.getCurrentTab();
2539 if (current == null) {
2540 /*
2541 * Instead of finishing the activity, simply push this to the back
2542 * of the stack and let ActivityManager to choose the foreground
2543 * activity. As BrowserActivity is singleTask, it will be always the
2544 * root of the task. So we can use either true or false for
2545 * moveTaskToBack().
2546 */
2547 moveTaskToBack(true);
2548 }
2549 WebView w = current.getWebView();
2550 if (w.canGoBack()) {
2551 w.goBack();
2552 } else {
2553 // Check to see if we are closing a window that was created by
2554 // another window. If so, we switch back to that window.
2555 TabControl.Tab parent = current.getParentTab();
2556 if (parent != null) {
2557 switchTabs(mTabControl.getCurrentIndex(),
2558 mTabControl.getTabIndex(parent), true);
2559 } else {
2560 if (current.closeOnExit()) {
2561 if (mTabControl.getTabCount() == 1) {
2562 finish();
2563 return;
2564 }
2565 // call pauseWebView() now, we won't be able to call it in
2566 // onPause() as the WebView won't be valid.
2567 pauseWebView();
2568 removeTabFromContentView(current);
2569 mTabControl.removeTab(current);
2570 }
2571 /*
2572 * Instead of finishing the activity, simply push this to the back
2573 * of the stack and let ActivityManager to choose the foreground
2574 * activity. As BrowserActivity is singleTask, it will be always the
2575 * root of the task. So we can use either true or false for
2576 * moveTaskToBack().
2577 */
2578 moveTaskToBack(true);
2579 }
2580 }
2581 }
2582
2583 public KeyTracker.State onKeyTracker(int keyCode,
2584 KeyEvent event,
2585 KeyTracker.Stage stage,
2586 int duration) {
2587 // if onKeyTracker() is called after activity onStop()
2588 // because of accumulated key events,
2589 // we should ignore it as browser is not active any more.
2590 WebView topWindow = getTopWindow();
2591 if (topWindow == null)
2592 return KeyTracker.State.NOT_TRACKING;
2593
2594 if (keyCode == KeyEvent.KEYCODE_BACK) {
2595 // During animations, block the back key so that other animations
2596 // are not triggered and so that we don't end up destroying all the
2597 // WebViews before finishing the animation.
2598 if (mAnimationCount > 0) {
2599 return KeyTracker.State.DONE_TRACKING;
2600 }
2601 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2602 bookmarksOrHistoryPicker(true);
2603 return KeyTracker.State.DONE_TRACKING;
2604 } else if (stage == KeyTracker.Stage.UP) {
2605 // FIXME: Currently, we do not have a notion of the
2606 // history picker for the subwindow, but maybe we
2607 // should?
2608 WebView subwindow = mTabControl.getCurrentSubWindow();
2609 if (subwindow != null) {
2610 if (subwindow.canGoBack()) {
2611 subwindow.goBack();
2612 } else {
2613 dismissSubWindow(mTabControl.getCurrentTab());
2614 }
2615 } else {
2616 goBackOnePageOrQuit();
2617 }
2618 return KeyTracker.State.DONE_TRACKING;
2619 }
2620 return KeyTracker.State.KEEP_TRACKING;
2621 }
2622 return KeyTracker.State.NOT_TRACKING;
2623 }
2624
2625 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2626 if (keyCode == KeyEvent.KEYCODE_MENU) {
2627 mMenuIsDown = true;
2628 }
2629 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2630 if (!handled) {
2631 switch (keyCode) {
2632 case KeyEvent.KEYCODE_SPACE:
2633 if (event.isShiftPressed()) {
2634 getTopWindow().pageUp(false);
2635 } else {
2636 getTopWindow().pageDown(false);
2637 }
2638 handled = true;
2639 break;
2640
2641 default:
2642 break;
2643 }
2644 }
2645 return handled || super.onKeyDown(keyCode, event);
2646 }
2647
2648 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2649 if (keyCode == KeyEvent.KEYCODE_MENU) {
2650 mMenuIsDown = false;
2651 }
2652 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2653 }
2654
2655 private void stopLoading() {
2656 resetTitleAndRevertLockIcon();
2657 WebView w = getTopWindow();
2658 w.stopLoading();
2659 mWebViewClient.onPageFinished(w, w.getUrl());
2660
2661 cancelStopToast();
2662 mStopToast = Toast
2663 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2664 mStopToast.show();
2665 }
2666
2667 private void cancelStopToast() {
2668 if (mStopToast != null) {
2669 mStopToast.cancel();
2670 mStopToast = null;
2671 }
2672 }
2673
2674 // called by a non-UI thread to post the message
2675 public void postMessage(int what, int arg1, int arg2, Object obj) {
2676 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2677 }
2678
2679 // public message ids
2680 public final static int LOAD_URL = 1001;
2681 public final static int STOP_LOAD = 1002;
2682
2683 // Message Ids
2684 private static final int FOCUS_NODE_HREF = 102;
2685 private static final int CANCEL_CREDS_REQUEST = 103;
2686 private static final int ANIMATE_FROM_OVERVIEW = 104;
2687 private static final int ANIMATE_TO_OVERVIEW = 105;
2688 private static final int OPEN_TAB_AND_SHOW = 106;
2689 private static final int CHECK_MEMORY = 107;
2690 private static final int RELEASE_WAKELOCK = 108;
2691
2692 // Private handler for handling javascript and saving passwords
2693 private Handler mHandler = new Handler() {
2694
2695 public void handleMessage(Message msg) {
2696 switch (msg.what) {
2697 case ANIMATE_FROM_OVERVIEW:
2698 final HashMap map = (HashMap) msg.obj;
2699 animateFromTabOverview((AnimatingView) map.get("view"),
2700 msg.arg1 == 1, (Message) map.get("msg"));
2701 break;
2702
2703 case ANIMATE_TO_OVERVIEW:
2704 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2705 (AnimatingView) msg.obj);
2706 break;
2707
2708 case OPEN_TAB_AND_SHOW:
2709 // Decrement mAnimationCount before openTabAndShow because
2710 // the method relies on the value being 0 to start the next
2711 // animation.
2712 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002713 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714 break;
2715
2716 case FOCUS_NODE_HREF:
2717 String url = (String) msg.getData().get("url");
2718 if (url == null || url.length() == 0) {
2719 break;
2720 }
2721 HashMap focusNodeMap = (HashMap) msg.obj;
2722 WebView view = (WebView) focusNodeMap.get("webview");
2723 // Only apply the action if the top window did not change.
2724 if (getTopWindow() != view) {
2725 break;
2726 }
2727 switch (msg.arg1) {
2728 case R.id.open_context_menu_id:
2729 case R.id.view_image_context_menu_id:
2730 loadURL(getTopWindow(), url);
2731 break;
2732 case R.id.open_newtab_context_menu_id:
2733 openTab(url);
2734 break;
2735 case R.id.bookmark_context_menu_id:
2736 Intent intent = new Intent(BrowserActivity.this,
2737 AddBookmarkPage.class);
2738 intent.putExtra("url", url);
2739 startActivity(intent);
2740 break;
2741 case R.id.share_link_context_menu_id:
2742 Browser.sendString(BrowserActivity.this, url);
2743 break;
2744 case R.id.copy_link_context_menu_id:
2745 copy(url);
2746 break;
2747 case R.id.save_link_context_menu_id:
2748 case R.id.download_context_menu_id:
2749 onDownloadStartNoStream(url, null, null, null, -1);
2750 break;
2751 }
2752 break;
2753
2754 case LOAD_URL:
2755 loadURL(getTopWindow(), (String) msg.obj);
2756 break;
2757
2758 case STOP_LOAD:
2759 stopLoading();
2760 break;
2761
2762 case CANCEL_CREDS_REQUEST:
2763 resumeAfterCredentials();
2764 break;
2765
2766 case CHECK_MEMORY:
2767 // reschedule to check memory condition
2768 mHandler.removeMessages(CHECK_MEMORY);
2769 mHandler.sendMessageDelayed(mHandler.obtainMessage
2770 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2771 checkMemory();
2772 break;
2773
2774 case RELEASE_WAKELOCK:
2775 if (mWakeLock.isHeld()) {
2776 mWakeLock.release();
2777 }
2778 break;
2779 }
2780 }
2781 };
2782
2783 // -------------------------------------------------------------------------
2784 // WebViewClient implementation.
2785 //-------------------------------------------------------------------------
2786
2787 // Use in overrideUrlLoading
2788 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2789 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2790 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2791 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2792
2793 /* package */ WebViewClient getWebViewClient() {
2794 return mWebViewClient;
2795 }
2796
2797 private void updateIcon(String url, Bitmap icon) {
2798 if (icon != null) {
2799 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2800 url, icon);
2801 }
2802 setFavicon(icon);
2803 }
2804
2805 private final WebViewClient mWebViewClient = new WebViewClient() {
2806 @Override
2807 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2808 resetLockIcon(url);
2809 setUrlTitle(url, null);
2810 // Call updateIcon instead of setFavicon so the bookmark
2811 // database can be updated.
2812 updateIcon(url, favicon);
2813
2814 if (mSettings.isTracing() == true) {
2815 // FIXME: we should save the trace file somewhere other than data.
2816 // I can't use "/tmp" as it competes for system memory.
2817 File file = getDir("browserTrace", 0);
2818 String baseDir = file.getPath();
2819 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2820 String host;
2821 try {
2822 WebAddress uri = new WebAddress(url);
2823 host = uri.mHost;
2824 } catch (android.net.ParseException ex) {
2825 host = "unknown_host";
2826 }
2827 host = host.replace('.', '_');
2828 baseDir = baseDir + host;
2829 file = new File(baseDir+".data");
2830 if (file.exists() == true) {
2831 file.delete();
2832 }
2833 file = new File(baseDir+".key");
2834 if (file.exists() == true) {
2835 file.delete();
2836 }
2837 mInTrace = true;
2838 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2839 }
2840
2841 // Performance probe
2842 if (false) {
2843 mStart = SystemClock.uptimeMillis();
2844 mProcessStart = Process.getElapsedCpuTime();
2845 long[] sysCpu = new long[7];
2846 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2847 sysCpu, null)) {
2848 mUserStart = sysCpu[0] + sysCpu[1];
2849 mSystemStart = sysCpu[2];
2850 mIdleStart = sysCpu[3];
2851 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2852 }
2853 mUiStart = SystemClock.currentThreadTimeMillis();
2854 }
2855
2856 if (!mPageStarted) {
2857 mPageStarted = true;
2858 // if onResume() has been called, resumeWebView() does nothing.
2859 resumeWebView();
2860 }
2861
2862 // reset sync timer to avoid sync starts during loading a page
2863 CookieSyncManager.getInstance().resetSync();
2864
2865 mInLoad = true;
2866 updateInLoadMenuItems();
2867 if (!mIsNetworkUp) {
2868 if ( mAlertDialog == null) {
2869 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2870 .setTitle(R.string.loadSuspendedTitle)
2871 .setMessage(R.string.loadSuspended)
2872 .setPositiveButton(R.string.ok, null)
2873 .show();
2874 }
2875 if (view != null) {
2876 view.setNetworkAvailable(false);
2877 }
2878 }
2879
2880 // schedule to check memory condition
2881 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2882 CHECK_MEMORY_INTERVAL);
2883 }
2884
2885 @Override
2886 public void onPageFinished(WebView view, String url) {
2887 // Reset the title and icon in case we stopped a provisional
2888 // load.
2889 resetTitleAndIcon(view);
2890
2891 // Update the lock icon image only once we are done loading
2892 updateLockIconImage(mLockIconType);
2893
2894 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002895 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002896 long[] sysCpu = new long[7];
2897 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2898 sysCpu, null)) {
2899 String uiInfo = "UI thread used "
2900 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2901 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002902 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 Log.d(LOGTAG, uiInfo);
2904 }
2905 //The string that gets written to the log
2906 String performanceString = "It took total "
2907 + (SystemClock.uptimeMillis() - mStart)
2908 + " ms clock time to load the page."
2909 + "\nbrowser process used "
2910 + (Process.getElapsedCpuTime() - mProcessStart)
2911 + " ms, user processes used "
2912 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2913 + " ms, kernel used "
2914 + (sysCpu[2] - mSystemStart) * 10
2915 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2916 + " ms and irq took "
2917 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2918 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002919 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2921 }
2922 if (url != null) {
2923 // strip the url to maintain consistency
2924 String newUrl = new String(url);
2925 if (newUrl.startsWith("http://www.")) {
2926 newUrl = newUrl.substring(11);
2927 } else if (newUrl.startsWith("http://")) {
2928 newUrl = newUrl.substring(7);
2929 } else if (newUrl.startsWith("https://www.")) {
2930 newUrl = newUrl.substring(12);
2931 } else if (newUrl.startsWith("https://")) {
2932 newUrl = newUrl.substring(8);
2933 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002934 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002935 Log.d(LOGTAG, newUrl + " loaded");
2936 }
2937 /*
2938 if (sWhiteList.contains(newUrl)) {
2939 // The string that gets pushed to the statistcs
2940 // service
2941 performanceString = performanceString
2942 + "\nWebpage: "
2943 + newUrl
2944 + "\nCarrier: "
2945 + android.os.SystemProperties
2946 .get("gsm.sim.operator.alpha");
2947 if (mWebView != null
2948 && mWebView.getContext() != null
2949 && mWebView.getContext().getSystemService(
2950 Context.CONNECTIVITY_SERVICE) != null) {
2951 ConnectivityManager cManager =
2952 (ConnectivityManager) mWebView
2953 .getContext().getSystemService(
2954 Context.CONNECTIVITY_SERVICE);
2955 NetworkInfo nInfo = cManager
2956 .getActiveNetworkInfo();
2957 if (nInfo != null) {
2958 performanceString = performanceString
2959 + "\nNetwork Type: "
2960 + nInfo.getType().toString();
2961 }
2962 }
2963 Checkin.logEvent(mResolver,
2964 Checkin.Events.Tag.WEBPAGE_LOAD,
2965 performanceString);
2966 Log.w(LOGTAG, "pushed to the statistics service");
2967 }
2968 */
2969 }
2970 }
2971 }
2972
2973 if (mInTrace) {
2974 mInTrace = false;
2975 Debug.stopMethodTracing();
2976 }
2977
2978 if (mPageStarted) {
2979 mPageStarted = false;
2980 // pauseWebView() will do nothing and return false if onPause()
2981 // is not called yet.
2982 if (pauseWebView()) {
2983 if (mWakeLock.isHeld()) {
2984 mHandler.removeMessages(RELEASE_WAKELOCK);
2985 mWakeLock.release();
2986 }
2987 }
2988 }
2989
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 mHandler.removeMessages(CHECK_MEMORY);
2991 checkMemory();
2992 }
2993
2994 // return true if want to hijack the url to let another app to handle it
2995 @Override
2996 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2997 if (url.startsWith(SCHEME_WTAI)) {
2998 // wtai://wp/mc;number
2999 // number=string(phone-number)
3000 if (url.startsWith(SCHEME_WTAI_MC)) {
3001 Intent intent = new Intent(Intent.ACTION_VIEW,
3002 Uri.parse(WebView.SCHEME_TEL +
3003 url.substring(SCHEME_WTAI_MC.length())));
3004 startActivity(intent);
3005 return true;
3006 }
3007 // wtai://wp/sd;dtmf
3008 // dtmf=string(dialstring)
3009 if (url.startsWith(SCHEME_WTAI_SD)) {
3010 // TODO
3011 // only send when there is active voice connection
3012 return false;
3013 }
3014 // wtai://wp/ap;number;name
3015 // number=string(phone-number)
3016 // name=string
3017 if (url.startsWith(SCHEME_WTAI_AP)) {
3018 // TODO
3019 return false;
3020 }
3021 }
3022
Dianne Hackborn99189432009-06-17 18:06:18 -07003023 // The "about:" schemes are internal to the browser; don't
3024 // want these to be dispatched to other apps.
3025 if (url.startsWith("about:")) {
3026 return false;
3027 }
3028
3029 Intent intent;
3030
3031 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003033 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3034 } catch (URISyntaxException ex) {
3035 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 return false;
3037 }
3038
Dianne Hackborn99189432009-06-17 18:06:18 -07003039 // sanitize the Intent, ensuring web pages can not bypass browser
3040 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003042 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 try {
3044 if (startActivityIfNeeded(intent, -1)) {
3045 return true;
3046 }
3047 } catch (ActivityNotFoundException ex) {
3048 // ignore the error. If no application can handle the URL,
3049 // eg about:blank, assume the browser can handle it.
3050 }
3051
3052 if (mMenuIsDown) {
3053 openTab(url);
3054 closeOptionsMenu();
3055 return true;
3056 }
3057
3058 return false;
3059 }
3060
3061 /**
3062 * Updates the lock icon. This method is called when we discover another
3063 * resource to be loaded for this page (for example, javascript). While
3064 * we update the icon type, we do not update the lock icon itself until
3065 * we are done loading, it is slightly more secure this way.
3066 */
3067 @Override
3068 public void onLoadResource(WebView view, String url) {
3069 if (url != null && url.length() > 0) {
3070 // It is only if the page claims to be secure
3071 // that we may have to update the lock:
3072 if (mLockIconType == LOCK_ICON_SECURE) {
3073 // If NOT a 'safe' url, change the lock to mixed content!
3074 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3075 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003076 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3078 " updated lock icon to " + mLockIconType + " due to " + url);
3079 }
3080 }
3081 }
3082 }
3083 }
3084
3085 /**
3086 * Show the dialog, asking the user if they would like to continue after
3087 * an excessive number of HTTP redirects.
3088 */
3089 @Override
3090 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3091 final Message continueMsg) {
3092 new AlertDialog.Builder(BrowserActivity.this)
3093 .setTitle(R.string.browserFrameRedirect)
3094 .setMessage(R.string.browserFrame307Post)
3095 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3096 public void onClick(DialogInterface dialog, int which) {
3097 continueMsg.sendToTarget();
3098 }})
3099 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3100 public void onClick(DialogInterface dialog, int which) {
3101 cancelMsg.sendToTarget();
3102 }})
3103 .setOnCancelListener(new OnCancelListener() {
3104 public void onCancel(DialogInterface dialog) {
3105 cancelMsg.sendToTarget();
3106 }})
3107 .show();
3108 }
3109
Patrick Scotta6555242009-03-24 18:01:26 -07003110 // Container class for the next error dialog that needs to be
3111 // displayed.
3112 class ErrorDialog {
3113 public final int mTitle;
3114 public final String mDescription;
3115 public final int mError;
3116 ErrorDialog(int title, String desc, int error) {
3117 mTitle = title;
3118 mDescription = desc;
3119 mError = error;
3120 }
3121 };
3122
3123 private void processNextError() {
3124 if (mQueuedErrors == null) {
3125 return;
3126 }
3127 // The first one is currently displayed so just remove it.
3128 mQueuedErrors.removeFirst();
3129 if (mQueuedErrors.size() == 0) {
3130 mQueuedErrors = null;
3131 return;
3132 }
3133 showError(mQueuedErrors.getFirst());
3134 }
3135
3136 private DialogInterface.OnDismissListener mDialogListener =
3137 new DialogInterface.OnDismissListener() {
3138 public void onDismiss(DialogInterface d) {
3139 processNextError();
3140 }
3141 };
3142 private LinkedList<ErrorDialog> mQueuedErrors;
3143
3144 private void queueError(int err, String desc) {
3145 if (mQueuedErrors == null) {
3146 mQueuedErrors = new LinkedList<ErrorDialog>();
3147 }
3148 for (ErrorDialog d : mQueuedErrors) {
3149 if (d.mError == err) {
3150 // Already saw a similar error, ignore the new one.
3151 return;
3152 }
3153 }
3154 ErrorDialog errDialog = new ErrorDialog(
3155 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3156 R.string.browserFrameFileErrorLabel :
3157 R.string.browserFrameNetworkErrorLabel,
3158 desc, err);
3159 mQueuedErrors.addLast(errDialog);
3160
3161 // Show the dialog now if the queue was empty.
3162 if (mQueuedErrors.size() == 1) {
3163 showError(errDialog);
3164 }
3165 }
3166
3167 private void showError(ErrorDialog errDialog) {
3168 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3169 .setTitle(errDialog.mTitle)
3170 .setMessage(errDialog.mDescription)
3171 .setPositiveButton(R.string.ok, null)
3172 .create();
3173 d.setOnDismissListener(mDialogListener);
3174 d.show();
3175 }
3176
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 /**
3178 * Show a dialog informing the user of the network error reported by
3179 * WebCore.
3180 */
3181 @Override
3182 public void onReceivedError(WebView view, int errorCode,
3183 String description, String failingUrl) {
3184 if (errorCode != EventHandler.ERROR_LOOKUP &&
3185 errorCode != EventHandler.ERROR_CONNECT &&
3186 errorCode != EventHandler.ERROR_BAD_URL &&
3187 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3188 errorCode != EventHandler.FILE_ERROR) {
Patrick Scotta6555242009-03-24 18:01:26 -07003189 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003190 }
Patrick Scotta6555242009-03-24 18:01:26 -07003191 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3192 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193
3194 // We need to reset the title after an error.
3195 resetTitleAndRevertLockIcon();
3196 }
3197
3198 /**
3199 * Check with the user if it is ok to resend POST data as the page they
3200 * are trying to navigate to is the result of a POST.
3201 */
3202 @Override
3203 public void onFormResubmission(WebView view, final Message dontResend,
3204 final Message resend) {
3205 new AlertDialog.Builder(BrowserActivity.this)
3206 .setTitle(R.string.browserFrameFormResubmitLabel)
3207 .setMessage(R.string.browserFrameFormResubmitMessage)
3208 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3209 public void onClick(DialogInterface dialog, int which) {
3210 resend.sendToTarget();
3211 }})
3212 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3213 public void onClick(DialogInterface dialog, int which) {
3214 dontResend.sendToTarget();
3215 }})
3216 .setOnCancelListener(new OnCancelListener() {
3217 public void onCancel(DialogInterface dialog) {
3218 dontResend.sendToTarget();
3219 }})
3220 .show();
3221 }
3222
3223 /**
3224 * Insert the url into the visited history database.
3225 * @param url The url to be inserted.
3226 * @param isReload True if this url is being reloaded.
3227 * FIXME: Not sure what to do when reloading the page.
3228 */
3229 @Override
3230 public void doUpdateVisitedHistory(WebView view, String url,
3231 boolean isReload) {
3232 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3233 return;
3234 }
3235 Browser.updateVisitedHistory(mResolver, url, true);
3236 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3237 }
3238
3239 /**
3240 * Displays SSL error(s) dialog to the user.
3241 */
3242 @Override
3243 public void onReceivedSslError(
3244 final WebView view, final SslErrorHandler handler, final SslError error) {
3245
3246 if (mSettings.showSecurityWarnings()) {
3247 final LayoutInflater factory =
3248 LayoutInflater.from(BrowserActivity.this);
3249 final View warningsView =
3250 factory.inflate(R.layout.ssl_warnings, null);
3251 final LinearLayout placeholder =
3252 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3253
3254 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3255 LinearLayout ll = (LinearLayout)factory
3256 .inflate(R.layout.ssl_warning, null);
3257 ((TextView)ll.findViewById(R.id.warning))
3258 .setText(R.string.ssl_untrusted);
3259 placeholder.addView(ll);
3260 }
3261
3262 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3263 LinearLayout ll = (LinearLayout)factory
3264 .inflate(R.layout.ssl_warning, null);
3265 ((TextView)ll.findViewById(R.id.warning))
3266 .setText(R.string.ssl_mismatch);
3267 placeholder.addView(ll);
3268 }
3269
3270 if (error.hasError(SslError.SSL_EXPIRED)) {
3271 LinearLayout ll = (LinearLayout)factory
3272 .inflate(R.layout.ssl_warning, null);
3273 ((TextView)ll.findViewById(R.id.warning))
3274 .setText(R.string.ssl_expired);
3275 placeholder.addView(ll);
3276 }
3277
3278 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3279 LinearLayout ll = (LinearLayout)factory
3280 .inflate(R.layout.ssl_warning, null);
3281 ((TextView)ll.findViewById(R.id.warning))
3282 .setText(R.string.ssl_not_yet_valid);
3283 placeholder.addView(ll);
3284 }
3285
3286 new AlertDialog.Builder(BrowserActivity.this)
3287 .setTitle(R.string.security_warning)
3288 .setIcon(android.R.drawable.ic_dialog_alert)
3289 .setView(warningsView)
3290 .setPositiveButton(R.string.ssl_continue,
3291 new DialogInterface.OnClickListener() {
3292 public void onClick(DialogInterface dialog, int whichButton) {
3293 handler.proceed();
3294 }
3295 })
3296 .setNeutralButton(R.string.view_certificate,
3297 new DialogInterface.OnClickListener() {
3298 public void onClick(DialogInterface dialog, int whichButton) {
3299 showSSLCertificateOnError(view, handler, error);
3300 }
3301 })
3302 .setNegativeButton(R.string.cancel,
3303 new DialogInterface.OnClickListener() {
3304 public void onClick(DialogInterface dialog, int whichButton) {
3305 handler.cancel();
3306 BrowserActivity.this.resetTitleAndRevertLockIcon();
3307 }
3308 })
3309 .setOnCancelListener(
3310 new DialogInterface.OnCancelListener() {
3311 public void onCancel(DialogInterface dialog) {
3312 handler.cancel();
3313 BrowserActivity.this.resetTitleAndRevertLockIcon();
3314 }
3315 })
3316 .show();
3317 } else {
3318 handler.proceed();
3319 }
3320 }
3321
3322 /**
3323 * Handles an HTTP authentication request.
3324 *
3325 * @param handler The authentication handler
3326 * @param host The host
3327 * @param realm The realm
3328 */
3329 @Override
3330 public void onReceivedHttpAuthRequest(WebView view,
3331 final HttpAuthHandler handler, final String host, final String realm) {
3332 String username = null;
3333 String password = null;
3334
3335 boolean reuseHttpAuthUsernamePassword =
3336 handler.useHttpAuthUsernamePassword();
3337
3338 if (reuseHttpAuthUsernamePassword &&
3339 (mTabControl.getCurrentWebView() != null)) {
3340 String[] credentials =
3341 mTabControl.getCurrentWebView()
3342 .getHttpAuthUsernamePassword(host, realm);
3343 if (credentials != null && credentials.length == 2) {
3344 username = credentials[0];
3345 password = credentials[1];
3346 }
3347 }
3348
3349 if (username != null && password != null) {
3350 handler.proceed(username, password);
3351 } else {
3352 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3353 }
3354 }
3355
3356 @Override
3357 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3358 if (mMenuIsDown) {
3359 // only check shortcut key when MENU is held
3360 return getWindow().isShortcutKey(event.getKeyCode(), event);
3361 } else {
3362 return false;
3363 }
3364 }
3365
3366 @Override
3367 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3368 if (view != mTabControl.getCurrentTopWebView()) {
3369 return;
3370 }
3371 if (event.isDown()) {
3372 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3373 } else {
3374 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3375 }
3376 }
3377 };
3378
3379 //--------------------------------------------------------------------------
3380 // WebChromeClient implementation
3381 //--------------------------------------------------------------------------
3382
3383 /* package */ WebChromeClient getWebChromeClient() {
3384 return mWebChromeClient;
3385 }
3386
3387 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3388 // Helper method to create a new tab or sub window.
3389 private void createWindow(final boolean dialog, final Message msg) {
3390 if (dialog) {
3391 mTabControl.createSubWindow();
3392 final TabControl.Tab t = mTabControl.getCurrentTab();
3393 attachSubWindow(t);
3394 WebView.WebViewTransport transport =
3395 (WebView.WebViewTransport) msg.obj;
3396 transport.setWebView(t.getSubWebView());
3397 msg.sendToTarget();
3398 } else {
3399 final TabControl.Tab parent = mTabControl.getCurrentTab();
3400 // openTabAndShow will dispatch the message after creating the
3401 // new WebView. This will prevent another request from coming
3402 // in during the animation.
Patrick Scott95d601f2009-06-11 10:06:46 -04003403 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 parent.addChildTab(mTabControl.getCurrentTab());
3405 WebView.WebViewTransport transport =
3406 (WebView.WebViewTransport) msg.obj;
3407 transport.setWebView(mTabControl.getCurrentWebView());
3408 }
3409 }
3410
3411 @Override
3412 public boolean onCreateWindow(WebView view, final boolean dialog,
3413 final boolean userGesture, final Message resultMsg) {
3414 // Ignore these requests during tab animations or if the tab
3415 // overview is showing.
3416 if (mAnimationCount > 0 || mTabOverview != null) {
3417 return false;
3418 }
3419 // Short-circuit if we can't create any more tabs or sub windows.
3420 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3421 new AlertDialog.Builder(BrowserActivity.this)
3422 .setTitle(R.string.too_many_subwindows_dialog_title)
3423 .setIcon(android.R.drawable.ic_dialog_alert)
3424 .setMessage(R.string.too_many_subwindows_dialog_message)
3425 .setPositiveButton(R.string.ok, null)
3426 .show();
3427 return false;
3428 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3429 new AlertDialog.Builder(BrowserActivity.this)
3430 .setTitle(R.string.too_many_windows_dialog_title)
3431 .setIcon(android.R.drawable.ic_dialog_alert)
3432 .setMessage(R.string.too_many_windows_dialog_message)
3433 .setPositiveButton(R.string.ok, null)
3434 .show();
3435 return false;
3436 }
3437
3438 // Short-circuit if this was a user gesture.
3439 if (userGesture) {
3440 // createWindow will call openTabAndShow for new Windows and
3441 // that will call tabPicker which will increment
3442 // mAnimationCount.
3443 createWindow(dialog, resultMsg);
3444 return true;
3445 }
3446
3447 // Allow the popup and create the appropriate window.
3448 final AlertDialog.OnClickListener allowListener =
3449 new AlertDialog.OnClickListener() {
3450 public void onClick(DialogInterface d,
3451 int which) {
3452 // Same comment as above for setting
3453 // mAnimationCount.
3454 createWindow(dialog, resultMsg);
3455 // Since we incremented mAnimationCount while the
3456 // dialog was up, we have to decrement it here.
3457 mAnimationCount--;
3458 }
3459 };
3460
3461 // Block the popup by returning a null WebView.
3462 final AlertDialog.OnClickListener blockListener =
3463 new AlertDialog.OnClickListener() {
3464 public void onClick(DialogInterface d, int which) {
3465 resultMsg.sendToTarget();
3466 // We are not going to trigger an animation so
3467 // unblock keys and animation requests.
3468 mAnimationCount--;
3469 }
3470 };
3471
3472 // Build a confirmation dialog to display to the user.
3473 final AlertDialog d =
3474 new AlertDialog.Builder(BrowserActivity.this)
3475 .setTitle(R.string.attention)
3476 .setIcon(android.R.drawable.ic_dialog_alert)
3477 .setMessage(R.string.popup_window_attempt)
3478 .setPositiveButton(R.string.allow, allowListener)
3479 .setNegativeButton(R.string.block, blockListener)
3480 .setCancelable(false)
3481 .create();
3482
3483 // Show the confirmation dialog.
3484 d.show();
3485 // We want to increment mAnimationCount here to prevent a
3486 // potential race condition. If the user allows a pop-up from a
3487 // site and that pop-up then triggers another pop-up, it is
3488 // possible to get the BACK key between here and when the dialog
3489 // appears.
3490 mAnimationCount++;
3491 return true;
3492 }
3493
3494 @Override
3495 public void onCloseWindow(WebView window) {
3496 final int currentIndex = mTabControl.getCurrentIndex();
3497 final TabControl.Tab parent =
3498 mTabControl.getCurrentTab().getParentTab();
3499 if (parent != null) {
3500 // JavaScript can only close popup window.
3501 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3502 }
3503 }
3504
3505 @Override
3506 public void onProgressChanged(WebView view, int newProgress) {
3507 // Block progress updates to the title bar while the tab overview
3508 // is animating or being displayed.
3509 if (mAnimationCount == 0 && mTabOverview == null) {
3510 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3511 newProgress * 100);
3512 }
3513
3514 if (newProgress == 100) {
3515 // onProgressChanged() is called for sub-frame too while
3516 // onPageFinished() is only called for the main frame. sync
3517 // cookie and cache promptly here.
3518 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003519 if (mInLoad) {
3520 mInLoad = false;
3521 updateInLoadMenuItems();
3522 }
3523 } else {
3524 // onPageFinished may have already been called but a subframe
3525 // is still loading and updating the progress. Reset mInLoad
3526 // and update the menu items.
3527 if (!mInLoad) {
3528 mInLoad = true;
3529 updateInLoadMenuItems();
3530 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 }
3532 }
3533
3534 @Override
3535 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003536 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537
3538 // here, if url is null, we want to reset the title
3539 setUrlTitle(url, title);
3540
3541 if (url == null ||
3542 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3543 return;
3544 }
3545 if (url.startsWith("http://www.")) {
3546 url = url.substring(11);
3547 } else if (url.startsWith("http://")) {
3548 url = url.substring(4);
3549 }
3550 try {
3551 url = "%" + url;
3552 String [] selArgs = new String[] { url };
3553
3554 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3555 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3556 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3557 Browser.HISTORY_PROJECTION, where, selArgs, null);
3558 if (c.moveToFirst()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003559 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 Log.v(LOGTAG, "updating cursor");
3561 }
3562 // Current implementation of database only has one entry per
3563 // url.
3564 int titleIndex =
3565 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3566 c.updateString(titleIndex, title);
3567 c.commitUpdates();
3568 }
3569 c.close();
3570 } catch (IllegalStateException e) {
3571 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3572 } catch (SQLiteException ex) {
3573 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3574 }
3575 }
3576
3577 @Override
3578 public void onReceivedIcon(WebView view, Bitmap icon) {
3579 updateIcon(view.getUrl(), icon);
3580 }
3581 };
3582
3583 /**
3584 * Notify the host application a download should be done, or that
3585 * the data should be streamed if a streaming viewer is available.
3586 * @param url The full url to the content that should be downloaded
3587 * @param contentDisposition Content-disposition http header, if
3588 * present.
3589 * @param mimetype The mimetype of the content reported by the server
3590 * @param contentLength The file size reported by the server
3591 */
3592 public void onDownloadStart(String url, String userAgent,
3593 String contentDisposition, String mimetype, long contentLength) {
3594 // if we're dealing wih A/V content that's not explicitly marked
3595 // for download, check if it's streamable.
3596 if (contentDisposition == null
3597 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3598 // query the package manager to see if there's a registered handler
3599 // that matches.
3600 Intent intent = new Intent(Intent.ACTION_VIEW);
3601 intent.setDataAndType(Uri.parse(url), mimetype);
3602 if (getPackageManager().resolveActivity(intent,
3603 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3604 // someone knows how to handle this mime type with this scheme, don't download.
3605 try {
3606 startActivity(intent);
3607 return;
3608 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003609 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 Log.d(LOGTAG, "activity not found for " + mimetype
3611 + " over " + Uri.parse(url).getScheme(), ex);
3612 }
3613 // Best behavior is to fall back to a download in this case
3614 }
3615 }
3616 }
3617 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3618 }
3619
3620 /**
3621 * Notify the host application a download should be done, even if there
3622 * is a streaming viewer available for thise type.
3623 * @param url The full url to the content that should be downloaded
3624 * @param contentDisposition Content-disposition http header, if
3625 * present.
3626 * @param mimetype The mimetype of the content reported by the server
3627 * @param contentLength The file size reported by the server
3628 */
3629 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3630 String contentDisposition, String mimetype, long contentLength) {
3631
3632 String filename = URLUtil.guessFileName(url,
3633 contentDisposition, mimetype);
3634
3635 // Check to see if we have an SDCard
3636 String status = Environment.getExternalStorageState();
3637 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3638 int title;
3639 String msg;
3640
3641 // Check to see if the SDCard is busy, same as the music app
3642 if (status.equals(Environment.MEDIA_SHARED)) {
3643 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3644 title = R.string.download_sdcard_busy_dlg_title;
3645 } else {
3646 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3647 title = R.string.download_no_sdcard_dlg_title;
3648 }
3649
3650 new AlertDialog.Builder(this)
3651 .setTitle(title)
3652 .setIcon(android.R.drawable.ic_dialog_alert)
3653 .setMessage(msg)
3654 .setPositiveButton(R.string.ok, null)
3655 .show();
3656 return;
3657 }
3658
3659 // java.net.URI is a lot stricter than KURL so we have to undo
3660 // KURL's percent-encoding and redo the encoding using java.net.URI.
3661 URI uri = null;
3662 try {
3663 // Undo the percent-encoding that KURL may have done.
3664 String newUrl = new String(URLUtil.decode(url.getBytes()));
3665 // Parse the url into pieces
3666 WebAddress w = new WebAddress(newUrl);
3667 String frag = null;
3668 String query = null;
3669 String path = w.mPath;
3670 // Break the path into path, query, and fragment
3671 if (path.length() > 0) {
3672 // Strip the fragment
3673 int idx = path.lastIndexOf('#');
3674 if (idx != -1) {
3675 frag = path.substring(idx + 1);
3676 path = path.substring(0, idx);
3677 }
3678 idx = path.lastIndexOf('?');
3679 if (idx != -1) {
3680 query = path.substring(idx + 1);
3681 path = path.substring(0, idx);
3682 }
3683 }
3684 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3685 query, frag);
3686 } catch (Exception e) {
3687 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3688 return;
3689 }
3690
3691 // XXX: Have to use the old url since the cookies were stored using the
3692 // old percent-encoded url.
3693 String cookies = CookieManager.getInstance().getCookie(url);
3694
3695 ContentValues values = new ContentValues();
3696 values.put(Downloads.URI, uri.toString());
3697 values.put(Downloads.COOKIE_DATA, cookies);
3698 values.put(Downloads.USER_AGENT, userAgent);
3699 values.put(Downloads.NOTIFICATION_PACKAGE,
3700 getPackageName());
3701 values.put(Downloads.NOTIFICATION_CLASS,
3702 BrowserDownloadPage.class.getCanonicalName());
3703 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3704 values.put(Downloads.MIMETYPE, mimetype);
3705 values.put(Downloads.FILENAME_HINT, filename);
3706 values.put(Downloads.DESCRIPTION, uri.getHost());
3707 if (contentLength > 0) {
3708 values.put(Downloads.TOTAL_BYTES, contentLength);
3709 }
3710 if (mimetype == null) {
3711 // We must have long pressed on a link or image to download it. We
3712 // are not sure of the mimetype in this case, so do a head request
3713 new FetchUrlMimeType(this).execute(values);
3714 } else {
3715 final Uri contentUri =
3716 getContentResolver().insert(Downloads.CONTENT_URI, values);
3717 viewDownloads(contentUri);
3718 }
3719
3720 }
3721
3722 /**
3723 * Resets the lock icon. This method is called when we start a new load and
3724 * know the url to be loaded.
3725 */
3726 private void resetLockIcon(String url) {
3727 // Save the lock-icon state (we revert to it if the load gets cancelled)
3728 saveLockIcon();
3729
3730 mLockIconType = LOCK_ICON_UNSECURE;
3731 if (URLUtil.isHttpsUrl(url)) {
3732 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003733 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3735 " reset lock icon to " + mLockIconType);
3736 }
3737 }
3738
3739 updateLockIconImage(LOCK_ICON_UNSECURE);
3740 }
3741
3742 /**
3743 * Resets the lock icon. This method is called when the icon needs to be
3744 * reset but we do not know whether we are loading a secure or not secure
3745 * page.
3746 */
3747 private void resetLockIcon() {
3748 // Save the lock-icon state (we revert to it if the load gets cancelled)
3749 saveLockIcon();
3750
3751 mLockIconType = LOCK_ICON_UNSECURE;
3752
Dave Bort31a6d1c2009-04-13 15:56:49 -07003753 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003754 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3755 " reset lock icon to " + mLockIconType);
3756 }
3757
3758 updateLockIconImage(LOCK_ICON_UNSECURE);
3759 }
3760
3761 /**
3762 * Updates the lock-icon image in the title-bar.
3763 */
3764 private void updateLockIconImage(int lockIconType) {
3765 Drawable d = null;
3766 if (lockIconType == LOCK_ICON_SECURE) {
3767 d = mSecLockIcon;
3768 } else if (lockIconType == LOCK_ICON_MIXED) {
3769 d = mMixLockIcon;
3770 }
3771 // If the tab overview is animating or being shown, do not update the
3772 // lock icon.
3773 if (mAnimationCount == 0 && mTabOverview == null) {
3774 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3775 }
3776 }
3777
3778 /**
3779 * Displays a page-info dialog.
3780 * @param tab The tab to show info about
3781 * @param fromShowSSLCertificateOnError The flag that indicates whether
3782 * this dialog was opened from the SSL-certificate-on-error dialog or
3783 * not. This is important, since we need to know whether to return to
3784 * the parent dialog or simply dismiss.
3785 */
3786 private void showPageInfo(final TabControl.Tab tab,
3787 final boolean fromShowSSLCertificateOnError) {
3788 final LayoutInflater factory = LayoutInflater
3789 .from(this);
3790
3791 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3792
3793 final WebView view = tab.getWebView();
3794
3795 String url = null;
3796 String title = null;
3797
3798 if (view == null) {
3799 url = tab.getUrl();
3800 title = tab.getTitle();
3801 } else if (view == mTabControl.getCurrentWebView()) {
3802 // Use the cached title and url if this is the current WebView
3803 url = mUrl;
3804 title = mTitle;
3805 } else {
3806 url = view.getUrl();
3807 title = view.getTitle();
3808 }
3809
3810 if (url == null) {
3811 url = "";
3812 }
3813 if (title == null) {
3814 title = "";
3815 }
3816
3817 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3818 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3819
3820 mPageInfoView = tab;
3821 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3822
3823 AlertDialog.Builder alertDialogBuilder =
3824 new AlertDialog.Builder(this)
3825 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3826 .setView(pageInfoView)
3827 .setPositiveButton(
3828 R.string.ok,
3829 new DialogInterface.OnClickListener() {
3830 public void onClick(DialogInterface dialog,
3831 int whichButton) {
3832 mPageInfoDialog = null;
3833 mPageInfoView = null;
3834 mPageInfoFromShowSSLCertificateOnError = null;
3835
3836 // if we came here from the SSL error dialog
3837 if (fromShowSSLCertificateOnError) {
3838 // go back to the SSL error dialog
3839 showSSLCertificateOnError(
3840 mSSLCertificateOnErrorView,
3841 mSSLCertificateOnErrorHandler,
3842 mSSLCertificateOnErrorError);
3843 }
3844 }
3845 })
3846 .setOnCancelListener(
3847 new DialogInterface.OnCancelListener() {
3848 public void onCancel(DialogInterface dialog) {
3849 mPageInfoDialog = null;
3850 mPageInfoView = null;
3851 mPageInfoFromShowSSLCertificateOnError = null;
3852
3853 // if we came here from the SSL error dialog
3854 if (fromShowSSLCertificateOnError) {
3855 // go back to the SSL error dialog
3856 showSSLCertificateOnError(
3857 mSSLCertificateOnErrorView,
3858 mSSLCertificateOnErrorHandler,
3859 mSSLCertificateOnErrorError);
3860 }
3861 }
3862 });
3863
3864 // if we have a main top-level page SSL certificate set or a certificate
3865 // error
3866 if (fromShowSSLCertificateOnError ||
3867 (view != null && view.getCertificate() != null)) {
3868 // add a 'View Certificate' button
3869 alertDialogBuilder.setNeutralButton(
3870 R.string.view_certificate,
3871 new DialogInterface.OnClickListener() {
3872 public void onClick(DialogInterface dialog,
3873 int whichButton) {
3874 mPageInfoDialog = null;
3875 mPageInfoView = null;
3876 mPageInfoFromShowSSLCertificateOnError = null;
3877
3878 // if we came here from the SSL error dialog
3879 if (fromShowSSLCertificateOnError) {
3880 // go back to the SSL error dialog
3881 showSSLCertificateOnError(
3882 mSSLCertificateOnErrorView,
3883 mSSLCertificateOnErrorHandler,
3884 mSSLCertificateOnErrorError);
3885 } else {
3886 // otherwise, display the top-most certificate from
3887 // the chain
3888 if (view.getCertificate() != null) {
3889 showSSLCertificate(tab);
3890 }
3891 }
3892 }
3893 });
3894 }
3895
3896 mPageInfoDialog = alertDialogBuilder.show();
3897 }
3898
3899 /**
3900 * Displays the main top-level page SSL certificate dialog
3901 * (accessible from the Page-Info dialog).
3902 * @param tab The tab to show certificate for.
3903 */
3904 private void showSSLCertificate(final TabControl.Tab tab) {
3905 final View certificateView =
3906 inflateCertificateView(tab.getWebView().getCertificate());
3907 if (certificateView == null) {
3908 return;
3909 }
3910
3911 LayoutInflater factory = LayoutInflater.from(this);
3912
3913 final LinearLayout placeholder =
3914 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3915
3916 LinearLayout ll = (LinearLayout) factory.inflate(
3917 R.layout.ssl_success, placeholder);
3918 ((TextView)ll.findViewById(R.id.success))
3919 .setText(R.string.ssl_certificate_is_valid);
3920
3921 mSSLCertificateView = tab;
3922 mSSLCertificateDialog =
3923 new AlertDialog.Builder(this)
3924 .setTitle(R.string.ssl_certificate).setIcon(
3925 R.drawable.ic_dialog_browser_certificate_secure)
3926 .setView(certificateView)
3927 .setPositiveButton(R.string.ok,
3928 new DialogInterface.OnClickListener() {
3929 public void onClick(DialogInterface dialog,
3930 int whichButton) {
3931 mSSLCertificateDialog = null;
3932 mSSLCertificateView = null;
3933
3934 showPageInfo(tab, false);
3935 }
3936 })
3937 .setOnCancelListener(
3938 new DialogInterface.OnCancelListener() {
3939 public void onCancel(DialogInterface dialog) {
3940 mSSLCertificateDialog = null;
3941 mSSLCertificateView = null;
3942
3943 showPageInfo(tab, false);
3944 }
3945 })
3946 .show();
3947 }
3948
3949 /**
3950 * Displays the SSL error certificate dialog.
3951 * @param view The target web-view.
3952 * @param handler The SSL error handler responsible for cancelling the
3953 * connection that resulted in an SSL error or proceeding per user request.
3954 * @param error The SSL error object.
3955 */
3956 private void showSSLCertificateOnError(
3957 final WebView view, final SslErrorHandler handler, final SslError error) {
3958
3959 final View certificateView =
3960 inflateCertificateView(error.getCertificate());
3961 if (certificateView == null) {
3962 return;
3963 }
3964
3965 LayoutInflater factory = LayoutInflater.from(this);
3966
3967 final LinearLayout placeholder =
3968 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3969
3970 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3971 LinearLayout ll = (LinearLayout)factory
3972 .inflate(R.layout.ssl_warning, placeholder);
3973 ((TextView)ll.findViewById(R.id.warning))
3974 .setText(R.string.ssl_untrusted);
3975 }
3976
3977 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3978 LinearLayout ll = (LinearLayout)factory
3979 .inflate(R.layout.ssl_warning, placeholder);
3980 ((TextView)ll.findViewById(R.id.warning))
3981 .setText(R.string.ssl_mismatch);
3982 }
3983
3984 if (error.hasError(SslError.SSL_EXPIRED)) {
3985 LinearLayout ll = (LinearLayout)factory
3986 .inflate(R.layout.ssl_warning, placeholder);
3987 ((TextView)ll.findViewById(R.id.warning))
3988 .setText(R.string.ssl_expired);
3989 }
3990
3991 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3992 LinearLayout ll = (LinearLayout)factory
3993 .inflate(R.layout.ssl_warning, placeholder);
3994 ((TextView)ll.findViewById(R.id.warning))
3995 .setText(R.string.ssl_not_yet_valid);
3996 }
3997
3998 mSSLCertificateOnErrorHandler = handler;
3999 mSSLCertificateOnErrorView = view;
4000 mSSLCertificateOnErrorError = error;
4001 mSSLCertificateOnErrorDialog =
4002 new AlertDialog.Builder(this)
4003 .setTitle(R.string.ssl_certificate).setIcon(
4004 R.drawable.ic_dialog_browser_certificate_partially_secure)
4005 .setView(certificateView)
4006 .setPositiveButton(R.string.ok,
4007 new DialogInterface.OnClickListener() {
4008 public void onClick(DialogInterface dialog,
4009 int whichButton) {
4010 mSSLCertificateOnErrorDialog = null;
4011 mSSLCertificateOnErrorView = null;
4012 mSSLCertificateOnErrorHandler = null;
4013 mSSLCertificateOnErrorError = null;
4014
4015 mWebViewClient.onReceivedSslError(
4016 view, handler, error);
4017 }
4018 })
4019 .setNeutralButton(R.string.page_info_view,
4020 new DialogInterface.OnClickListener() {
4021 public void onClick(DialogInterface dialog,
4022 int whichButton) {
4023 mSSLCertificateOnErrorDialog = null;
4024
4025 // do not clear the dialog state: we will
4026 // need to show the dialog again once the
4027 // user is done exploring the page-info details
4028
4029 showPageInfo(mTabControl.getTabFromView(view),
4030 true);
4031 }
4032 })
4033 .setOnCancelListener(
4034 new DialogInterface.OnCancelListener() {
4035 public void onCancel(DialogInterface dialog) {
4036 mSSLCertificateOnErrorDialog = null;
4037 mSSLCertificateOnErrorView = null;
4038 mSSLCertificateOnErrorHandler = null;
4039 mSSLCertificateOnErrorError = null;
4040
4041 mWebViewClient.onReceivedSslError(
4042 view, handler, error);
4043 }
4044 })
4045 .show();
4046 }
4047
4048 /**
4049 * Inflates the SSL certificate view (helper method).
4050 * @param certificate The SSL certificate.
4051 * @return The resultant certificate view with issued-to, issued-by,
4052 * issued-on, expires-on, and possibly other fields set.
4053 * If the input certificate is null, returns null.
4054 */
4055 private View inflateCertificateView(SslCertificate certificate) {
4056 if (certificate == null) {
4057 return null;
4058 }
4059
4060 LayoutInflater factory = LayoutInflater.from(this);
4061
4062 View certificateView = factory.inflate(
4063 R.layout.ssl_certificate, null);
4064
4065 // issued to:
4066 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4067 if (issuedTo != null) {
4068 ((TextView) certificateView.findViewById(R.id.to_common))
4069 .setText(issuedTo.getCName());
4070 ((TextView) certificateView.findViewById(R.id.to_org))
4071 .setText(issuedTo.getOName());
4072 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4073 .setText(issuedTo.getUName());
4074 }
4075
4076 // issued by:
4077 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4078 if (issuedBy != null) {
4079 ((TextView) certificateView.findViewById(R.id.by_common))
4080 .setText(issuedBy.getCName());
4081 ((TextView) certificateView.findViewById(R.id.by_org))
4082 .setText(issuedBy.getOName());
4083 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4084 .setText(issuedBy.getUName());
4085 }
4086
4087 // issued on:
4088 String issuedOn = reformatCertificateDate(
4089 certificate.getValidNotBefore());
4090 ((TextView) certificateView.findViewById(R.id.issued_on))
4091 .setText(issuedOn);
4092
4093 // expires on:
4094 String expiresOn = reformatCertificateDate(
4095 certificate.getValidNotAfter());
4096 ((TextView) certificateView.findViewById(R.id.expires_on))
4097 .setText(expiresOn);
4098
4099 return certificateView;
4100 }
4101
4102 /**
4103 * Re-formats the certificate date (Date.toString()) string to
4104 * a properly localized date string.
4105 * @return Properly localized version of the certificate date string and
4106 * the original certificate date string if fails to localize.
4107 * If the original string is null, returns an empty string "".
4108 */
4109 private String reformatCertificateDate(String certificateDate) {
4110 String reformattedDate = null;
4111
4112 if (certificateDate != null) {
4113 Date date = null;
4114 try {
4115 date = java.text.DateFormat.getInstance().parse(certificateDate);
4116 } catch (ParseException e) {
4117 date = null;
4118 }
4119
4120 if (date != null) {
4121 reformattedDate =
4122 DateFormat.getDateFormat(this).format(date);
4123 }
4124 }
4125
4126 return reformattedDate != null ? reformattedDate :
4127 (certificateDate != null ? certificateDate : "");
4128 }
4129
4130 /**
4131 * Displays an http-authentication dialog.
4132 */
4133 private void showHttpAuthentication(final HttpAuthHandler handler,
4134 final String host, final String realm, final String title,
4135 final String name, final String password, int focusId) {
4136 LayoutInflater factory = LayoutInflater.from(this);
4137 final View v = factory
4138 .inflate(R.layout.http_authentication, null);
4139 if (name != null) {
4140 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4141 }
4142 if (password != null) {
4143 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4144 }
4145
4146 String titleText = title;
4147 if (titleText == null) {
4148 titleText = getText(R.string.sign_in_to).toString().replace(
4149 "%s1", host).replace("%s2", realm);
4150 }
4151
4152 mHttpAuthHandler = handler;
4153 AlertDialog dialog = new AlertDialog.Builder(this)
4154 .setTitle(titleText)
4155 .setIcon(android.R.drawable.ic_dialog_alert)
4156 .setView(v)
4157 .setPositiveButton(R.string.action,
4158 new DialogInterface.OnClickListener() {
4159 public void onClick(DialogInterface dialog,
4160 int whichButton) {
4161 String nm = ((EditText) v
4162 .findViewById(R.id.username_edit))
4163 .getText().toString();
4164 String pw = ((EditText) v
4165 .findViewById(R.id.password_edit))
4166 .getText().toString();
4167 BrowserActivity.this.setHttpAuthUsernamePassword
4168 (host, realm, nm, pw);
4169 handler.proceed(nm, pw);
4170 mHttpAuthenticationDialog = null;
4171 mHttpAuthHandler = null;
4172 }})
4173 .setNegativeButton(R.string.cancel,
4174 new DialogInterface.OnClickListener() {
4175 public void onClick(DialogInterface dialog,
4176 int whichButton) {
4177 handler.cancel();
4178 BrowserActivity.this.resetTitleAndRevertLockIcon();
4179 mHttpAuthenticationDialog = null;
4180 mHttpAuthHandler = null;
4181 }})
4182 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4183 public void onCancel(DialogInterface dialog) {
4184 handler.cancel();
4185 BrowserActivity.this.resetTitleAndRevertLockIcon();
4186 mHttpAuthenticationDialog = null;
4187 mHttpAuthHandler = null;
4188 }})
4189 .create();
4190 // Make the IME appear when the dialog is displayed if applicable.
4191 dialog.getWindow().setSoftInputMode(
4192 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4193 dialog.show();
4194 if (focusId != 0) {
4195 dialog.findViewById(focusId).requestFocus();
4196 } else {
4197 v.findViewById(R.id.username_edit).requestFocus();
4198 }
4199 mHttpAuthenticationDialog = dialog;
4200 }
4201
4202 public int getProgress() {
4203 WebView w = mTabControl.getCurrentWebView();
4204 if (w != null) {
4205 return w.getProgress();
4206 } else {
4207 return 100;
4208 }
4209 }
4210
4211 /**
4212 * Set HTTP authentication password.
4213 *
4214 * @param host The host for the password
4215 * @param realm The realm for the password
4216 * @param username The username for the password. If it is null, it means
4217 * password can't be saved.
4218 * @param password The password
4219 */
4220 public void setHttpAuthUsernamePassword(String host, String realm,
4221 String username,
4222 String password) {
4223 WebView w = mTabControl.getCurrentWebView();
4224 if (w != null) {
4225 w.setHttpAuthUsernamePassword(host, realm, username, password);
4226 }
4227 }
4228
4229 /**
4230 * connectivity manager says net has come or gone... inform the user
4231 * @param up true if net has come up, false if net has gone down
4232 */
4233 public void onNetworkToggle(boolean up) {
4234 if (up == mIsNetworkUp) {
4235 return;
4236 } else if (up) {
4237 mIsNetworkUp = true;
4238 if (mAlertDialog != null) {
4239 mAlertDialog.cancel();
4240 mAlertDialog = null;
4241 }
4242 } else {
4243 mIsNetworkUp = false;
4244 if (mInLoad && mAlertDialog == null) {
4245 mAlertDialog = new AlertDialog.Builder(this)
4246 .setTitle(R.string.loadSuspendedTitle)
4247 .setMessage(R.string.loadSuspended)
4248 .setPositiveButton(R.string.ok, null)
4249 .show();
4250 }
4251 }
4252 WebView w = mTabControl.getCurrentWebView();
4253 if (w != null) {
4254 w.setNetworkAvailable(up);
4255 }
4256 }
4257
4258 @Override
4259 protected void onActivityResult(int requestCode, int resultCode,
4260 Intent intent) {
4261 switch (requestCode) {
4262 case COMBO_PAGE:
4263 if (resultCode == RESULT_OK && intent != null) {
4264 String data = intent.getAction();
4265 Bundle extras = intent.getExtras();
4266 if (extras != null && extras.getBoolean("new_window", false)) {
4267 openTab(data);
4268 } else {
4269 final TabControl.Tab currentTab =
4270 mTabControl.getCurrentTab();
4271 // If the Window overview is up and we are not in the
4272 // middle of an animation, animate away from it to the
4273 // current tab.
4274 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004275 sendAnimateFromOverview(currentTab, false, new UrlData(data),
The Android Open Source Project0c908882009-03-03 19:32:16 -08004276 TAB_OVERVIEW_DELAY, null);
4277 } else {
4278 dismissSubWindow(currentTab);
4279 if (data != null && data.length() != 0) {
4280 getTopWindow().loadUrl(data);
4281 }
4282 }
4283 }
4284 }
4285 break;
4286 default:
4287 break;
4288 }
4289 getTopWindow().requestFocus();
4290 }
4291
4292 /*
4293 * This method is called as a result of the user selecting the options
4294 * menu to see the download window, or when a download changes state. It
4295 * shows the download window ontop of the current window.
4296 */
4297 /* package */ void viewDownloads(Uri downloadRecord) {
4298 Intent intent = new Intent(this,
4299 BrowserDownloadPage.class);
4300 intent.setData(downloadRecord);
4301 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4302
4303 }
4304
4305 /**
4306 * Handle results from Tab Switcher mTabOverview tool
4307 */
4308 private class TabListener implements ImageGrid.Listener {
4309 public void remove(int position) {
4310 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004311 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 throw new AssertionError();
4313 }
4314
4315 // Remember the current tab.
4316 TabControl.Tab current = mTabControl.getCurrentTab();
4317 final TabControl.Tab remove = mTabControl.getTab(position);
4318 mTabControl.removeTab(remove);
4319 // If we removed the current tab, use the tab at position - 1 if
4320 // possible.
4321 if (current == remove) {
4322 // If the user removes the last tab, act like the New Tab item
4323 // was clicked on.
4324 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004325 current = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004326 sendAnimateFromOverview(current, true,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004327 new UrlData(mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004328 } else {
4329 final int index = position > 0 ? (position - 1) : 0;
4330 current = mTabControl.getTab(index);
4331 }
4332 }
4333
4334 // The tab overview could have been dismissed before this method is
4335 // called.
4336 if (mTabOverview != null) {
4337 // Remove the tab and change the index.
4338 mTabOverview.remove(position);
4339 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4340 }
4341
4342 // Only the current tab ensures its WebView is non-null. This
4343 // implies that we are reloading the freed tab.
4344 mTabControl.setCurrentTab(current);
4345 }
4346 public void onClick(int index) {
4347 // Change the tab if necessary.
4348 // Index equals ImageGrid.CANCEL when pressing back from the tab
4349 // overview.
4350 if (index == ImageGrid.CANCEL) {
4351 index = mTabControl.getCurrentIndex();
4352 // The current index is -1 if the current tab was removed.
4353 if (index == -1) {
4354 // Take the last tab as a fallback.
4355 index = mTabControl.getTabCount() - 1;
4356 }
4357 }
4358
The Android Open Source Project0c908882009-03-03 19:32:16 -08004359 // NEW_TAB means that the "New Tab" cell was clicked on.
4360 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004361 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004362 } else {
4363 sendAnimateFromOverview(mTabControl.getTab(index),
Patrick Scott95d601f2009-06-11 10:06:46 -04004364 false, EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004365 }
4366 }
4367 }
4368
4369 // A fake View that draws the WebView's picture with a fast zoom filter.
4370 // The View is used in case the tab is freed during the animation because
4371 // of low memory.
4372 private static class AnimatingView extends View {
4373 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4374 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4375 private static final DrawFilter sZoomFilter =
4376 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4377 private final Picture mPicture;
4378 private final float mScale;
4379 private final int mScrollX;
4380 private final int mScrollY;
4381 final TabControl.Tab mTab;
4382
4383 AnimatingView(Context ctxt, TabControl.Tab t) {
4384 super(ctxt);
4385 mTab = t;
4386 // Use the top window in the animation since the tab overview will
4387 // display the top window in each cell.
4388 final WebView w = t.getTopWindow();
4389 mPicture = w.capturePicture();
4390 mScale = w.getScale() / w.getWidth();
4391 mScrollX = w.getScrollX();
4392 mScrollY = w.getScrollY();
4393 }
4394
4395 @Override
4396 protected void onDraw(Canvas canvas) {
4397 canvas.save();
4398 canvas.drawColor(Color.WHITE);
4399 if (mPicture != null) {
4400 canvas.setDrawFilter(sZoomFilter);
4401 float scale = getWidth() * mScale;
4402 canvas.scale(scale, scale);
4403 canvas.translate(-mScrollX, -mScrollY);
4404 canvas.drawPicture(mPicture);
4405 }
4406 canvas.restore();
4407 }
4408 }
4409
4410 /**
4411 * Open the tab picker. This function will always use the current tab in
4412 * its animation.
4413 * @param stay boolean stating whether the tab picker is to remain open
4414 * (in which case it needs a listener and its menu) or not.
4415 * @param index The index of the tab to show as the selection in the tab
4416 * overview.
4417 * @param remove If true, the tab at index will be removed after the
4418 * animation completes.
4419 */
4420 private void tabPicker(final boolean stay, final int index,
4421 final boolean remove) {
4422 if (mTabOverview != null) {
4423 return;
4424 }
4425
4426 int size = mTabControl.getTabCount();
4427
4428 TabListener l = null;
4429 if (stay) {
4430 l = mTabListener = new TabListener();
4431 }
4432 mTabOverview = new ImageGrid(this, stay, l);
4433
4434 for (int i = 0; i < size; i++) {
4435 final TabControl.Tab t = mTabControl.getTab(i);
4436 mTabControl.populatePickerData(t);
4437 mTabOverview.add(t);
4438 }
4439
4440 // Tell the tab overview to show the current tab, the tab overview will
4441 // handle the "New Tab" case.
4442 int currentIndex = mTabControl.getCurrentIndex();
4443 mTabOverview.setCurrentIndex(currentIndex);
4444
4445 // Attach the tab overview.
4446 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4447
4448 // Create a fake AnimatingView to animate the WebView's picture.
4449 final TabControl.Tab current = mTabControl.getCurrentTab();
4450 final AnimatingView v = new AnimatingView(this, current);
4451 mContentView.addView(v, COVER_SCREEN_PARAMS);
4452 removeTabFromContentView(current);
4453 // Pause timers to get the animation smoother.
4454 current.getWebView().pauseTimers();
4455
4456 // Send a message so the tab picker has a chance to layout and get
4457 // positions for all the cells.
4458 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4459 index, remove ? 1 : 0, v));
4460 // Setting this will indicate that we are animating to the overview. We
4461 // set it here to prevent another request to animate from coming in
4462 // between now and when ANIMATE_TO_OVERVIEW is handled.
4463 mAnimationCount++;
4464 // Always change the title bar to the window overview title while
4465 // animating.
4466 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4467 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4468 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4469 Window.PROGRESS_VISIBILITY_OFF);
4470 setTitle(R.string.tab_picker_title);
4471 // Make the menu empty until the animation completes.
4472 mMenuState = EMPTY_MENU;
4473 }
4474
4475 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4476 WebView current = mTabControl.getCurrentWebView();
4477 if (current == null) {
4478 return;
4479 }
4480 Intent intent = new Intent(this,
4481 CombinedBookmarkHistoryActivity.class);
4482 String title = current.getTitle();
4483 String url = current.getUrl();
4484 // Just in case the user opens bookmarks before a page finishes loading
4485 // so the current history item, and therefore the page, is null.
4486 if (null == url) {
4487 url = mLastEnteredUrl;
4488 // This can happen.
4489 if (null == url) {
4490 url = mSettings.getHomePage();
4491 }
4492 }
4493 // In case the web page has not yet received its associated title.
4494 if (title == null) {
4495 title = url;
4496 }
4497 intent.putExtra("title", title);
4498 intent.putExtra("url", url);
4499 intent.putExtra("maxTabsOpen",
4500 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4501 if (startWithHistory) {
4502 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4503 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4504 }
4505 startActivityForResult(intent, COMBO_PAGE);
4506 }
4507
4508 // Called when loading from context menu or LOAD_URL message
4509 private void loadURL(WebView view, String url) {
4510 // In case the user enters nothing.
4511 if (url != null && url.length() != 0 && view != null) {
4512 url = smartUrlFilter(url);
4513 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4514 view.loadUrl(url);
4515 }
4516 }
4517 }
4518
4519 private void checkMemory() {
4520 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4521 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4522 .getMemoryInfo(mi);
4523 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4524 // mi.threshold) for now
4525 // if (mi.lowMemory) {
4526 if (mi.availMem < mi.threshold) {
4527 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4528 + (mi.availMem / 1024) + "K threshold="
4529 + (mi.threshold / 1024) + "K");
4530 mTabControl.freeMemory();
4531 }
4532 }
4533
4534 private String smartUrlFilter(Uri inUri) {
4535 if (inUri != null) {
4536 return smartUrlFilter(inUri.toString());
4537 }
4538 return null;
4539 }
4540
4541
4542 // get window count
4543
4544 int getWindowCount(){
4545 if(mTabControl != null){
4546 return mTabControl.getTabCount();
4547 }
4548 return 0;
4549 }
4550
4551 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4552 "(?i)" + // switch on case insensitive matching
4553 "(" + // begin group for schema
4554 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004555 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004556 ")" +
4557 "(.*)" );
4558
4559 /**
4560 * Attempts to determine whether user input is a URL or search
4561 * terms. Anything with a space is passed to search.
4562 *
4563 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4564 * "Http://" converts to "http://"
4565 *
4566 * @return Original or modified URL
4567 *
4568 */
4569 String smartUrlFilter(String url) {
4570
4571 String inUrl = url.trim();
4572 boolean hasSpace = inUrl.indexOf(' ') != -1;
4573
4574 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4575 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004576 // force scheme to lowercase
4577 String scheme = matcher.group(1);
4578 String lcScheme = scheme.toLowerCase();
4579 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004580 inUrl = lcScheme + matcher.group(2);
4581 }
4582 if (hasSpace) {
4583 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004584 }
4585 return inUrl;
4586 }
4587 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004588 // FIXME: Is this the correct place to add to searches?
4589 // what if someone else calls this function?
4590 int shortcut = parseUrlShortcut(inUrl);
4591 if (shortcut != SHORTCUT_INVALID) {
4592 Browser.addSearchUrl(mResolver, inUrl);
4593 String query = inUrl.substring(2);
4594 switch (shortcut) {
4595 case SHORTCUT_GOOGLE_SEARCH:
4596 return composeSearchUrl(query);
4597 case SHORTCUT_WIKIPEDIA_SEARCH:
4598 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4599 case SHORTCUT_DICTIONARY_SEARCH:
4600 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4601 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004602 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004603 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004604 }
4605 }
4606 } else {
4607 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4608 return URLUtil.guessUrl(inUrl);
4609 }
4610 }
4611
4612 Browser.addSearchUrl(mResolver, inUrl);
4613 return composeSearchUrl(inUrl);
4614 }
4615
4616 /* package */ String composeSearchUrl(String search) {
4617 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4618 QUERY_PLACE_HOLDER);
4619 }
4620
4621 /* package */void setBaseSearchUrl(String url) {
4622 if (url == null || url.length() == 0) {
4623 /*
4624 * get the google search url based on the SIM. Default is US. NOTE:
4625 * This code uses resources to optionally select the search Uri,
4626 * based on the MCC value from the SIM. The default string will most
4627 * likely be fine. It is parameterized to accept info from the
4628 * Locale, the language code is the first parameter (%1$s) and the
4629 * country code is the second (%2$s). This code must function in the
4630 * same way as a similar lookup in
4631 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4632 * change either of these functions, change them both. (The same is
4633 * true for the underlying resource strings, which are stored in
4634 * mcc-specific xml files.)
4635 */
4636 Locale l = Locale.getDefault();
Bill Napiere9651c32009-05-05 13:16:30 -07004637 String language = l.getLanguage();
4638 String country = l.getCountry().toLowerCase();
4639 // Chinese and Portuguese have two langauge variants.
4640 if ("zh".equals(language)) {
4641 if ("cn".equals(country)) {
4642 language = "zh-CN";
4643 } else if ("tw".equals(country)) {
4644 language = "zh-TW";
4645 }
4646 } else if ("pt".equals(language)) {
4647 if ("br".equals(country)) {
4648 language = "pt-BR";
4649 } else if ("pt".equals(country)) {
4650 language = "pt-PT";
4651 }
4652 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004653 QuickSearch_G = getResources().getString(
Bill Napiere9651c32009-05-05 13:16:30 -07004654 R.string.google_search_base,
4655 language,
4656 country)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004657 + "client=ms-"
Ramanan Rajeswaranf447f262009-03-24 20:40:12 -07004658 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004659 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4660 } else {
4661 QuickSearch_G = url;
4662 }
4663 }
4664
4665 private final static int LOCK_ICON_UNSECURE = 0;
4666 private final static int LOCK_ICON_SECURE = 1;
4667 private final static int LOCK_ICON_MIXED = 2;
4668
4669 private int mLockIconType = LOCK_ICON_UNSECURE;
4670 private int mPrevLockType = LOCK_ICON_UNSECURE;
4671
4672 private BrowserSettings mSettings;
4673 private TabControl mTabControl;
4674 private ContentResolver mResolver;
4675 private FrameLayout mContentView;
4676 private ImageGrid mTabOverview;
4677
4678 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4679 // view, we should rewrite this.
4680 private int mCurrentMenuState = 0;
4681 private int mMenuState = R.id.MAIN_MENU;
4682 private static final int EMPTY_MENU = -1;
4683 private Menu mMenu;
4684
4685 private FindDialog mFindDialog;
4686 // Used to prevent chording to result in firing two shortcuts immediately
4687 // one after another. Fixes bug 1211714.
4688 boolean mCanChord;
4689
4690 private boolean mInLoad;
4691 private boolean mIsNetworkUp;
4692
4693 private boolean mPageStarted;
4694 private boolean mActivityInPause = true;
4695
4696 private boolean mMenuIsDown;
4697
4698 private final KeyTracker mKeyTracker = new KeyTracker(this);
4699
4700 // As trackball doesn't send repeat down, we have to track it ourselves
4701 private boolean mTrackTrackball;
4702
4703 private static boolean mInTrace;
4704
4705 // Performance probe
4706 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4707 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4708 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4709 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4710 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4711 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4712 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4713 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4714 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4715 };
4716
4717 private long mStart;
4718 private long mProcessStart;
4719 private long mUserStart;
4720 private long mSystemStart;
4721 private long mIdleStart;
4722 private long mIrqStart;
4723
4724 private long mUiStart;
4725
4726 private Drawable mMixLockIcon;
4727 private Drawable mSecLockIcon;
4728 private Drawable mGenericFavicon;
4729
4730 /* hold a ref so we can auto-cancel if necessary */
4731 private AlertDialog mAlertDialog;
4732
4733 // Wait for credentials before loading google.com
4734 private ProgressDialog mCredsDlg;
4735
4736 // The up-to-date URL and title (these can be different from those stored
4737 // in WebView, since it takes some time for the information in WebView to
4738 // get updated)
4739 private String mUrl;
4740 private String mTitle;
4741
4742 // As PageInfo has different style for landscape / portrait, we have
4743 // to re-open it when configuration changed
4744 private AlertDialog mPageInfoDialog;
4745 private TabControl.Tab mPageInfoView;
4746 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4747 // dialog, we should not just dismiss it, but should get back to the
4748 // SSL-certificate-on-error dialog. This flag is used to store this state
4749 private Boolean mPageInfoFromShowSSLCertificateOnError;
4750
4751 // as SSLCertificateOnError has different style for landscape / portrait,
4752 // we have to re-open it when configuration changed
4753 private AlertDialog mSSLCertificateOnErrorDialog;
4754 private WebView mSSLCertificateOnErrorView;
4755 private SslErrorHandler mSSLCertificateOnErrorHandler;
4756 private SslError mSSLCertificateOnErrorError;
4757
4758 // as SSLCertificate has different style for landscape / portrait, we
4759 // have to re-open it when configuration changed
4760 private AlertDialog mSSLCertificateDialog;
4761 private TabControl.Tab mSSLCertificateView;
4762
4763 // as HttpAuthentication has different style for landscape / portrait, we
4764 // have to re-open it when configuration changed
4765 private AlertDialog mHttpAuthenticationDialog;
4766 private HttpAuthHandler mHttpAuthHandler;
4767
4768 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4769 new FrameLayout.LayoutParams(
4770 ViewGroup.LayoutParams.FILL_PARENT,
4771 ViewGroup.LayoutParams.FILL_PARENT);
4772 // We may provide UI to customize these
4773 // Google search from the browser
4774 static String QuickSearch_G;
4775 // Wikipedia search
4776 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4777 // Dictionary search
4778 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4779 // Google Mobile Local search
4780 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4781
4782 final static String QUERY_PLACE_HOLDER = "%s";
4783
4784 // "source" parameter for Google search through search key
4785 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4786 // "source" parameter for Google search through goto menu
4787 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4788 // "source" parameter for Google search through simplily type
4789 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4790 // "source" parameter for Google search suggested by the browser
4791 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4792 // "source" parameter for Google search from unknown source
4793 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4794
4795 private final static String LOGTAG = "browser";
4796
4797 private TabListener mTabListener;
4798
4799 private String mLastEnteredUrl;
4800
4801 private PowerManager.WakeLock mWakeLock;
4802 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4803
4804 private Toast mStopToast;
4805
4806 // Used during animations to prevent other animations from being triggered.
4807 // A count is used since the animation to and from the Window overview can
4808 // overlap. A count of 0 means no animation where a count of > 0 means
4809 // there are animations in progress.
4810 private int mAnimationCount;
4811
4812 // As the ids are dynamically created, we can't guarantee that they will
4813 // be in sequence, so this static array maps ids to a window number.
4814 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4815 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4816 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4817 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4818
4819 // monitor platform changes
4820 private IntentFilter mNetworkStateChangedFilter;
4821 private BroadcastReceiver mNetworkStateIntentReceiver;
4822
4823 // activity requestCode
4824 final static int COMBO_PAGE = 1;
4825 final static int DOWNLOAD_PAGE = 2;
4826 final static int PREFERENCES_PAGE = 3;
4827
4828 // the frenquency of checking whether system memory is low
4829 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004830
4831 /**
4832 * A UrlData class to abstract how the content will be set to WebView.
4833 * This base class uses loadUrl to show the content.
4834 */
4835 private static class UrlData {
4836 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004837 byte[] mPostData;
4838
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004839 UrlData(String url) {
4840 this.mUrl = url;
4841 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004842
4843 void setPostData(byte[] postData) {
4844 mPostData = postData;
4845 }
4846
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004847 boolean isEmpty() {
4848 return mUrl == null || mUrl.length() == 0;
4849 }
4850
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004851 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004852 if (mPostData != null) {
4853 webView.postUrl(mUrl, mPostData);
4854 } else {
4855 webView.loadUrl(mUrl);
4856 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004857 }
4858 };
4859
4860 /**
4861 * A subclass of UrlData class that can display inlined content using
4862 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4863 */
4864 private static class InlinedUrlData extends UrlData {
4865 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4866 super(failUrl);
4867 mInlined = inlined;
4868 mMimeType = mimeType;
4869 mEncoding = encoding;
4870 }
4871 String mMimeType;
4872 String mInlined;
4873 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004874 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004875 boolean isEmpty() {
4876 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4877 }
4878
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004879 @Override
4880 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004881 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4882 }
4883 }
4884
4885 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004886}