Merge "Add new shutdown observer for MountService. Use new observer before rebooting and shutting down. Add some unit tests for unmount and shutdown code paths Fix registering/unregistering part in MountService Use ShutdownThread in PowerManager.reboot() Add reboot support to ShutdownThread. Remove MountService code from PowerManagerService.java and Power.java. Clean shutdown/reboot is handled exclusively by ShutdownThread now."
diff --git a/api/current.xml b/api/current.xml
index dd0a804..ed3f696 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -45243,6 +45243,17 @@
  visibility="public"
 >
 </field>
+<field name="FEATURE_BLUETOOTH"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.bluetooth&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FEATURE_CAMERA"
  type="java.lang.String"
  transient="false"
@@ -45287,6 +45298,72 @@
  visibility="public"
 >
 </field>
+<field name="FEATURE_LOCATION"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_LOCATION_GPS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location.gps&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_LOCATION_NETWORK"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location.network&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_MICROPHONE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.microphone&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_SENSOR_ACCELEROMETER"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.sensor.accelerometer&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_SENSOR_COMPASS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.sensor.compass&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FEATURE_SENSOR_LIGHT"
  type="java.lang.String"
  transient="false"
@@ -45364,61 +45441,6 @@
  visibility="public"
 >
 </field>
-<field name="FEATURE_BLUETOOTH"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.bluetooth&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION_GPS"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location.gps&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION_NETWORK"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location.network&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_MICROPHONE"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.microphone&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
 <field name="FEATURE_WIFI"
  type="java.lang.String"
  transient="false"
@@ -45430,28 +45452,6 @@
  visibility="public"
 >
 </field>
-<field name="FEATURE_SENSOR_ACCELEROMETER"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.sensor.accelerometer&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_SENSOR_COMPASS"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.sensor.compass&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
 <field name="GET_ACTIVITIES"
  type="int"
  transient="false"
@@ -71563,6 +71563,19 @@
  deprecated="not deprecated"
  visibility="public"
 >
+<method name="addCallbackBuffer"
+ return="void"
+ abstract="false"
+ native="true"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callbackBuffer" type="byte[]">
+</parameter>
+</method>
 <method name="autoFocus"
  return="void"
  abstract="false"
@@ -71709,6 +71722,19 @@
 <parameter name="cb" type="android.hardware.Camera.PreviewCallback">
 </parameter>
 </method>
+<method name="setPreviewCallbackWithBuffer"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cb" type="android.hardware.Camera.PreviewCallback">
+</parameter>
+</method>
 <method name="setPreviewDisplay"
  return="void"
  abstract="false"
@@ -80262,6 +80288,19 @@
  deprecated="not deprecated"
  visibility="public"
 >
+<method name="abandonAudioFocus"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="l" type="android.media.AudioManager.OnAudioFocusChangeListener">
+</parameter>
+</method>
 <method name="adjustStreamVolume"
  return="void"
  abstract="false"
@@ -80503,6 +80542,36 @@
 <parameter name="volume" type="float">
 </parameter>
 </method>
+<method name="registerAudioFocusListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="l" type="android.media.AudioManager.OnAudioFocusChangeListener">
+</parameter>
+</method>
+<method name="requestAudioFocus"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="l" type="android.media.AudioManager.OnAudioFocusChangeListener">
+</parameter>
+<parameter name="streamType" type="int">
+</parameter>
+<parameter name="durationHint" type="int">
+</parameter>
+</method>
 <method name="setBluetoothA2dpOn"
  return="void"
  abstract="false"
@@ -80710,6 +80779,19 @@
  visibility="public"
 >
 </method>
+<method name="unregisterAudioFocusListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="l" type="android.media.AudioManager.OnAudioFocusChangeListener">
+</parameter>
+</method>
 <field name="ACTION_AUDIO_BECOMING_NOISY"
  type="java.lang.String"
  transient="false"
@@ -80754,6 +80836,72 @@
  visibility="public"
 >
 </field>
+<field name="AUDIOFOCUS_GAIN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUDIOFOCUS_GAIN_TRANSIENT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUDIOFOCUS_LOSS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="-1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUDIOFOCUS_LOSS_TRANSIENT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="-2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUDIOFOCUS_REQUEST_FAILED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUDIOFOCUS_REQUEST_GRANTED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="EXTRA_RINGER_MODE"
  type="java.lang.String"
  transient="false"
@@ -81283,6 +81431,27 @@
 >
 </field>
 </class>
+<interface name="AudioManager.OnAudioFocusChangeListener"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onAudioFocusChanged"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="focusChange" type="int">
+</parameter>
+</method>
+</interface>
 <class name="AudioRecord"
  extends="java.lang.Object"
  abstract="false"
@@ -193281,6 +193450,17 @@
  visibility="public"
 >
 </method>
+<method name="getUseSystemOverscrollBackground"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getUseWideViewPort"
  return="boolean"
  abstract="false"
@@ -193860,6 +194040,19 @@
 <parameter name="use" type="boolean">
 </parameter>
 </method>
+<method name="setUseSystemOverscrollBackground"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="system" type="boolean">
+</parameter>
+</method>
 <method name="setUseWideViewPort"
  return="void"
  abstract="false"
diff --git a/common/java/com/android/common/speech/LoggingEvents.java b/common/java/com/android/common/speech/LoggingEvents.java
index 3b3ecb8..1f3c6ef 100644
--- a/common/java/com/android/common/speech/LoggingEvents.java
+++ b/common/java/com/android/common/speech/LoggingEvents.java
@@ -117,6 +117,12 @@
         public static final String EXTRA_N_BEST_CHOOSE_INDEX = "index";  // value should be int
 
         public static final int TEXT_MODIFIED = 17;
+        public static final String EXTRA_TEXT_MODIFIED_LENGTH = "length";  // value should be int
+        public static final String EXTRA_TEXT_MODIFIED_TYPE = "type";  // value should be int below
+        public static final int TEXT_MODIFIED_TYPE_CHOOSE_SUGGESTION = 1;
+        public static final int TEXT_MODIFIED_TYPE_TYPING_DELETION = 2;
+        public static final int TEXT_MODIFIED_TYPE_TYPING_INSERTION = 3;
+        public static final int TEXT_MODIFIED_TYPE_TYPING_INSERTION_PUNCTUATION = 4;
 
         public static final int INPUT_ENDED = 18;
 
diff --git a/core/java/android/accounts/AbstractAccountAuthenticator.java b/core/java/android/accounts/AbstractAccountAuthenticator.java
index 8bc7428..c0c4c17 100644
--- a/core/java/android/accounts/AbstractAccountAuthenticator.java
+++ b/core/java/android/accounts/AbstractAccountAuthenticator.java
@@ -24,6 +24,10 @@
 import android.content.Context;
 import android.content.Intent;
 import android.Manifest;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.util.Arrays;
 
 /**
  * Abstract base class for creating AccountAuthenticators.
@@ -103,6 +107,8 @@
  * writing activities to handle these requests.
  */
 public abstract class AbstractAccountAuthenticator {
+    private static final String TAG = "AccountAuthenticator";
+
     private final Context mContext;
 
     public AbstractAccountAuthenticator(Context context) {
@@ -111,19 +117,34 @@
 
     private class Transport extends IAccountAuthenticator.Stub {
         public void addAccount(IAccountAuthenticatorResponse response, String accountType,
-                String authTokenType, String[] requiredFeatures, Bundle options)
+                String authTokenType, String[] features, Bundle options)
                 throws RemoteException {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "addAccount: accountType " + accountType
+                        + ", authTokenType " + authTokenType
+                        + ", features " + (features == null ? "[]" : Arrays.toString(features)));
+            }
             checkBinderPermission();
             try {
                 final Bundle result = AbstractAccountAuthenticator.this.addAccount(
                     new AccountAuthenticatorResponse(response),
-                        accountType, authTokenType, requiredFeatures, options);
+                        accountType, authTokenType, features, options);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    result.keySet(); // force it to be unparcelled
+                    Log.v(TAG, "addAccount: result " + AccountManager.sanitizeResult(result));
+                }
                 if (result != null) {
                     response.onResult(result);
                 }
             } catch (NetworkErrorException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "addAccount", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_NETWORK_ERROR, e.getMessage());
             } catch (UnsupportedOperationException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "addAccount", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
                         "addAccount not supported");
             }
@@ -131,16 +152,30 @@
 
         public void confirmCredentials(IAccountAuthenticatorResponse response,
                 Account account, Bundle options) throws RemoteException {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "confirmCredentials: " + account);
+            }
             checkBinderPermission();
             try {
                 final Bundle result = AbstractAccountAuthenticator.this.confirmCredentials(
                     new AccountAuthenticatorResponse(response), account, options);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    result.keySet(); // force it to be unparcelled
+                    Log.v(TAG, "confirmCredentials: result "
+                            + AccountManager.sanitizeResult(result));
+                }
                 if (result != null) {
                     response.onResult(result);
                 }
             } catch (NetworkErrorException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "confirmCredentials", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_NETWORK_ERROR, e.getMessage());
             } catch (UnsupportedOperationException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "confirmCredentials", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
                         "confirmCredentials not supported");
             }
@@ -149,16 +184,32 @@
         public void getAuthTokenLabel(IAccountAuthenticatorResponse response,
                 String authTokenType)
                 throws RemoteException {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "getAuthTokenLabel: authTokenType " + authTokenType);
+            }
             checkBinderPermission();
             try {
                 Bundle result = new Bundle();
                 result.putString(AccountManager.KEY_AUTH_TOKEN_LABEL,
                         AbstractAccountAuthenticator.this.getAuthTokenLabel(authTokenType));
-                response.onResult(result);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    result.keySet(); // force it to be unparcelled
+                    Log.v(TAG, "getAuthTokenLabel: result "
+                            + AccountManager.sanitizeResult(result));
+                }
+                if (result != null) {
+                    response.onResult(result);
+                }
             } catch (IllegalArgumentException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "getAuthTokenLabel", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS,
                         "unknown authTokenType");
             } catch (UnsupportedOperationException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "getAuthTokenLabel", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
                         "getAuthTokenTypeLabel not supported");
             }
@@ -167,35 +218,64 @@
         public void getAuthToken(IAccountAuthenticatorResponse response,
                 Account account, String authTokenType, Bundle loginOptions)
                 throws RemoteException {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "getAuthToken: " + account
+                        + ", authTokenType " + authTokenType);
+            }
             checkBinderPermission();
             try {
                 final Bundle result = AbstractAccountAuthenticator.this.getAuthToken(
                         new AccountAuthenticatorResponse(response), account,
                         authTokenType, loginOptions);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    result.keySet(); // force it to be unparcelled
+                    Log.v(TAG, "getAuthToken: result " + AccountManager.sanitizeResult(result));
+                }
                 if (result != null) {
                     response.onResult(result);
                 }
             } catch (UnsupportedOperationException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "getAuthToken", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
                         "getAuthToken not supported");
             } catch (NetworkErrorException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "getAuthToken", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_NETWORK_ERROR, e.getMessage());
             }
         }
 
         public void updateCredentials(IAccountAuthenticatorResponse response, Account account,
                 String authTokenType, Bundle loginOptions) throws RemoteException {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "updateCredentials: " + account
+                        + ", authTokenType " + authTokenType);
+            }
             checkBinderPermission();
             try {
                 final Bundle result = AbstractAccountAuthenticator.this.updateCredentials(
                     new AccountAuthenticatorResponse(response), account,
                         authTokenType, loginOptions);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    result.keySet(); // force it to be unparcelled
+                    Log.v(TAG, "updateCredentials: result "
+                            + AccountManager.sanitizeResult(result));
+                }
                 if (result != null) {
                     response.onResult(result);
                 }
             } catch (NetworkErrorException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "updateCredentials", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_NETWORK_ERROR, e.getMessage());
             } catch (UnsupportedOperationException e) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "updateCredentials", e);
+                }
                 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
                         "updateCredentials not supported");
             }
diff --git a/core/java/android/accounts/AccountAuthenticatorResponse.java b/core/java/android/accounts/AccountAuthenticatorResponse.java
index 7c09fbf..614e139 100644
--- a/core/java/android/accounts/AccountAuthenticatorResponse.java
+++ b/core/java/android/accounts/AccountAuthenticatorResponse.java
@@ -20,11 +20,14 @@
 import android.os.Parcelable;
 import android.os.Parcel;
 import android.os.RemoteException;
+import android.util.Log;
 
 /**
  * Object used to communicate responses back to the AccountManager
  */
 public class AccountAuthenticatorResponse implements Parcelable {
+    private static final String TAG = "AccountAuthenticator";
+
     private IAccountAuthenticatorResponse mAccountAuthenticatorResponse;
 
     /**
@@ -40,6 +43,11 @@
     }
 
     public void onResult(Bundle result) {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            result.keySet(); // force it to be unparcelled
+            Log.v(TAG, "AccountAuthenticatorResponse.onResult: "
+                    + AccountManager.sanitizeResult(result));
+        }
         try {
             mAccountAuthenticatorResponse.onResult(result);
         } catch (RemoteException e) {
@@ -48,6 +56,9 @@
     }
 
     public void onRequestContinued() {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "AccountAuthenticatorResponse.onRequestContinued");
+        }
         try {
             mAccountAuthenticatorResponse.onRequestContinued();
         } catch (RemoteException e) {
@@ -56,6 +67,9 @@
     }
 
     public void onError(int errorCode, String errorMessage) {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "AccountAuthenticatorResponse.onError: " + errorCode + ", " + errorMessage);
+        }
         try {
             mAccountAuthenticatorResponse.onError(errorCode, errorMessage);
         } catch (RemoteException e) {
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index 1bb1d0f..8356029 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -29,6 +29,7 @@
 import android.os.Parcelable;
 import android.os.Build;
 import android.util.Log;
+import android.text.TextUtils;
 
 import java.io.IOException;
 import java.util.concurrent.Callable;
@@ -223,6 +224,19 @@
     }
 
     /**
+     * @hide for internal use only
+     */
+    public static Bundle sanitizeResult(Bundle result) {
+        if (result.containsKey(KEY_AUTHTOKEN)
+                && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
+            final Bundle newResult = new Bundle(result);
+            newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
+            return newResult;
+        }
+        return result;
+    }
+
+    /**
      * Gets an AccountManager instance associated with a Context.
      * The {@link Context} will be used as long as the AccountManager is
      * active, so make sure to use a {@link Context} whose lifetime is
@@ -1447,6 +1461,7 @@
         final Bundle mAddAccountOptions;
         final Bundle mLoginOptions;
         final AccountManagerCallback<Bundle> mMyCallback;
+        private volatile int mNumAccounts = 0;
 
         public void doWork() throws RemoteException {
             getAccountsByTypeAndFeatures(mAccountType, mFeatures,
@@ -1466,6 +1481,8 @@
                                 return;
                             }
 
+                            mNumAccounts = accounts.length;
+
                             if (accounts.length == 0) {
                                 if (mActivity != null) {
                                     // no accounts, add one now. pretend that the user directly
@@ -1538,7 +1555,21 @@
 
         public void run(AccountManagerFuture<Bundle> future) {
             try {
-                set(future.getResult());
+                final Bundle result = future.getResult();
+                if (mNumAccounts == 0) {
+                    final String accountName = result.getString(KEY_ACCOUNT_NAME);
+                    final String accountType = result.getString(KEY_ACCOUNT_TYPE);
+                    if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
+                        setException(new AuthenticatorException("account not in result"));
+                        return;
+                    }
+                    final Account account = new Account(accountName, accountType);
+                    mNumAccounts = 1;
+                    getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
+                            mMyCallback, mHandler);
+                    return;
+                }
+                set(result);
             } catch (OperationCanceledException e) {
                 cancel(true /* mayInterruptIfRUnning */);
             } catch (IOException e) {
diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java
index c003355..0964425 100644
--- a/core/java/android/content/pm/PackageInfo.java
+++ b/core/java/android/content/pm/PackageInfo.java
@@ -151,7 +151,7 @@
      */
     public static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;
     /**
-     * The launch mode style requested by the activity.  From the
+     * The install location requested by the activity.  From the
      * {@link android.R.attr#installLocation} attribute, one of
      * {@link #INSTALL_LOCATION_AUTO},
      * {@link #INSTALL_LOCATION_INTERNAL_ONLY},
diff --git a/core/java/android/content/pm/PackageInfoLite.aidl b/core/java/android/content/pm/PackageInfoLite.aidl
new file mode 100755
index 0000000..2c80942
--- /dev/null
+++ b/core/java/android/content/pm/PackageInfoLite.aidl
@@ -0,0 +1,20 @@
+/* //device/java/android/android/view/WindowManager.aidl
+**
+** Copyright 2007, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License"); 
+** you may not use this file except in compliance with the License. 
+** You may obtain a copy of the License at 
+**
+**     http://www.apache.org/licenses/LICENSE-2.0 
+**
+** Unless required by applicable law or agreed to in writing, software 
+** distributed under the License is distributed on an "AS IS" BASIS, 
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
+** See the License for the specific language governing permissions and 
+** limitations under the License.
+*/
+
+package android.content.pm;
+
+parcelable PackageInfoLite;
diff --git a/core/java/android/content/pm/PackageInfoLite.java b/core/java/android/content/pm/PackageInfoLite.java
new file mode 100644
index 0000000..2f38ece
--- /dev/null
+++ b/core/java/android/content/pm/PackageInfoLite.java
@@ -0,0 +1,63 @@
+package android.content.pm;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * Basic information about a package as specified in its manifest.
+ * Utility class used in PackageManager methods
+ * @hide
+ */
+public class PackageInfoLite implements Parcelable {
+    /**
+     * The name of this package.  From the &lt;manifest&gt; tag's "name"
+     * attribute.
+     */
+    public String packageName;
+
+    /**
+     * Specifies the recommended install location. Can be one of
+     * {@link #PackageHelper.RECOMMEND_INSTALL_INTERNAL} to install on internal storage
+     * {@link #PackageHelper.RECOMMEND_INSTALL_EXTERNAL} to install on external media
+     * {@link PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE} for storage errors
+     * {@link PackageHelper.RECOMMEND_FAILED_INVALID_APK} for parse errors.
+     */
+    public int recommendedInstallLocation;
+    public int installLocation;
+
+    public PackageInfoLite() {
+    }
+
+    public String toString() {
+        return "PackageInfoLite{"
+            + Integer.toHexString(System.identityHashCode(this))
+            + " " + packageName + "}";
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int parcelableFlags) {
+        dest.writeString(packageName);
+        dest.writeInt(recommendedInstallLocation);
+        dest.writeInt(installLocation);
+    }
+
+    public static final Parcelable.Creator<PackageInfoLite> CREATOR
+            = new Parcelable.Creator<PackageInfoLite>() {
+        public PackageInfoLite createFromParcel(Parcel source) {
+            return new PackageInfoLite(source);
+        }
+
+        public PackageInfoLite[] newArray(int size) {
+            return new PackageInfoLite[size];
+        }
+    };
+
+    private PackageInfoLite(Parcel source) {
+        packageName = source.readString();
+        recommendedInstallLocation = source.readInt();
+        installLocation = source.readInt();
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 7a0337cd..5da7fd1 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -136,7 +136,20 @@
             enabledRes = _enabledRes;
         }
     }
-    
+
+    /* Light weight package info.
+     * @hide
+     */
+    public static class PackageLite {
+        public String packageName;
+        public int installLocation;
+        public String mScanPath;
+        public PackageLite(String packageName, int installLocation) {
+            this.packageName = packageName;
+            this.installLocation = installLocation;
+        }
+    }
+
     private ParsePackageItemArgs mParseInstrumentationArgs;
     private ParseComponentArgs mParseActivityArgs;
     private ParseComponentArgs mParseActivityAliasArgs;
@@ -562,7 +575,14 @@
         return true;
     }
 
-    public static String parsePackageName(String packageFilePath, int flags) {
+    /*
+     * Utility method that retrieves just the package name and install
+     * location from the apk location at the given file path.
+     * @param packageFilePath file location of the apk
+     * @param flags Special parse flags
+     * @return PackageLite object with package information.
+     */
+    public static PackageLite parsePackageLite(String packageFilePath, int flags) {
         XmlResourceParser parser = null;
         AssetManager assmgr = null;
         try {
@@ -577,9 +597,9 @@
         }
         AttributeSet attrs = parser;
         String errors[] = new String[1];
-        String packageName = null;
+        PackageLite packageLite = null;
         try {
-            packageName = parsePackageName(parser, attrs, flags, errors);
+            packageLite = parsePackageLite(parser, attrs, flags, errors);
         } catch (IOException e) {
             Log.w(TAG, packageFilePath, e);
         } catch (XmlPullParserException e) {
@@ -588,11 +608,11 @@
             if (parser != null) parser.close();
             if (assmgr != null) assmgr.close();
         }
-        if (packageName == null) {
-            Log.e(TAG, "parsePackageName error: " + errors[0]);
+        if (packageLite == null) {
+            Log.e(TAG, "parsePackageLite error: " + errors[0]);
             return null;
         }
-        return packageName;
+        return packageLite;
     }
 
     private static String validateName(String name, boolean requiresSeparator) {
@@ -656,6 +676,49 @@
         return pkgName.intern();
     }
 
+    private static PackageLite parsePackageLite(XmlPullParser parser,
+            AttributeSet attrs, int flags, String[] outError)
+            throws IOException, XmlPullParserException {
+
+        int type;
+        while ((type=parser.next()) != parser.START_TAG
+                   && type != parser.END_DOCUMENT) {
+            ;
+        }
+
+        if (type != parser.START_TAG) {
+            outError[0] = "No start tag found";
+            return null;
+        }
+        if ((flags&PARSE_CHATTY) != 0 && Config.LOGV) Log.v(
+            TAG, "Root element name: '" + parser.getName() + "'");
+        if (!parser.getName().equals("manifest")) {
+            outError[0] = "No <manifest> tag";
+            return null;
+        }
+        String pkgName = attrs.getAttributeValue(null, "package");
+        if (pkgName == null || pkgName.length() == 0) {
+            outError[0] = "<manifest> does not specify package";
+            return null;
+        }
+        String nameError = validateName(pkgName, true);
+        if (nameError != null && !"android".equals(pkgName)) {
+            outError[0] = "<manifest> specifies bad package name \""
+                + pkgName + "\": " + nameError;
+            return null;
+        }
+        int installLocation = PackageInfo.INSTALL_LOCATION_AUTO;
+        for (int i = 0; i < attrs.getAttributeCount(); i++) {
+            String attr = attrs.getAttributeName(i);
+            if (attr.equals("installLocation")) {
+                installLocation = attrs.getAttributeIntValue(i,
+                        PackageInfo.INSTALL_LOCATION_AUTO);
+                break;
+            }
+        }
+        return new PackageLite(pkgName.intern(), installLocation);
+    }
+
     /**
      * Temporary.
      */
diff --git a/core/java/android/database/sqlite/SQLiteCompiledSql.java b/core/java/android/database/sqlite/SQLiteCompiledSql.java
index 4ccf6b0..18cc1d5 100644
--- a/core/java/android/database/sqlite/SQLiteCompiledSql.java
+++ b/core/java/android/database/sqlite/SQLiteCompiledSql.java
@@ -23,8 +23,8 @@
  * Once a sql statement is compiled, it is cached in {@link SQLiteDatabase}
  * and it is released in one of the 2 following ways
  * 1. when {@link SQLiteDatabase} object is closed.
- * 2. dalvikVM wants to reclaim some memory and releases it from the cache in
- * {@link SQLiteDatabase}.
+ * 2. if this is not cached in {@link SQLiteDatabase}, {@link android.database.Cursor#close()}
+ * releaases this obj.
  */
 /* package */ class SQLiteCompiledSql {
 
@@ -127,7 +127,7 @@
         try {
             if (nStatement == 0) return;
             // finalizer should NEVER get called
-            Log.w(TAG, "finalizer should never be called. sql: " + mSqlStmt, mStackTrace);
+            Log.w(TAG, "finalizer should never be called on sql: " + mSqlStmt, mStackTrace);
             releaseSqlStatement();
         } finally {
             super.finalize();
diff --git a/core/java/android/database/sqlite/SQLiteProgram.java b/core/java/android/database/sqlite/SQLiteProgram.java
index 6636473..5b4516d 100644
--- a/core/java/android/database/sqlite/SQLiteProgram.java
+++ b/core/java/android/database/sqlite/SQLiteProgram.java
@@ -61,6 +61,7 @@
         // only cache CRUD statements
         String prefixSql = mSql.substring(0, 6);
         if (!prefixSql.equalsIgnoreCase("INSERT") && !prefixSql.equalsIgnoreCase("UPDATE") &&
+                !prefixSql.equalsIgnoreCase("REPLAC") &&
                 !prefixSql.equalsIgnoreCase("DELETE") && !prefixSql.equalsIgnoreCase("SELECT")) {
             mCompiledSql = new SQLiteCompiledSql(db, sql);
             nStatement = mCompiledSql.nStatement;
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 85d52ec..3484d55 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -261,7 +261,6 @@
      * setPreviewCallback, or to this method with a null callback parameter.
      *
      * @param cb A callback object that receives a copy of the preview frame.  A null value will clear the queue.
-     * @hide
      */
     public final void setPreviewCallbackWithBuffer(PreviewCallback cb) {
         mPreviewCallback = cb;
@@ -271,16 +270,22 @@
     }
 
     /**
-     * Adds a pre-allocated buffer to the callback buffer queue.
+     * Adds a pre-allocated buffer to the callback buffer queue. Applications
+     * can add one or more buffers to the queue. When a preview frame arrives
+     * and there is still available buffer, buffer will be filled and it is
+     * removed from the queue. Then preview callback is invoked with the buffer.
+     * If a frame arrives and there is no buffer left, the frame is discarded.
+     * Applications should add the buffers back when they finish the processing.
+     *
      * Preview width and height can be determined from getPreviewSize, and bitsPerPixel can be
-     * found from from  {@link android.hardware.Camera.Parameters#getPreviewFormat()} and
-     * {@link android.graphics.ImageFormat#getBitsPerPixel(int)}
+     * found from {@link android.hardware.Camera.Parameters#getPreviewFormat()}
+     * and {@link android.graphics.ImageFormat#getBitsPerPixel(int)}.
      *
      * Alternatively, a buffer from a previous callback may be passed in or used
      * to determine the size of new preview frame buffers.
      *
      * @param callbackBuffer The buffer to register. Size should be width * height * bitsPerPixel / 8.
-     * @hide
+     * @see #setPreviewCallbackWithBuffer(PreviewCallback)
      */
     public native final void addCallbackBuffer(byte[] callbackBuffer);
 
diff --git a/core/java/android/speech/tts/TextToSpeech.java b/core/java/android/speech/tts/TextToSpeech.java
index 9e04cf8..80b3a74 100755
--- a/core/java/android/speech/tts/TextToSpeech.java
+++ b/core/java/android/speech/tts/TextToSpeech.java
@@ -1211,9 +1211,8 @@
                         mCachedParams[Engine.PARAM_POSITION_ENGINE + 1] = extra;
                     }
                 }
-                if (mITts.synthesizeToFile(mPackageName, text, mCachedParams, filename)){
-                    result = SUCCESS;
-                }
+                result = mITts.synthesizeToFile(mPackageName, text, mCachedParams, filename) ?
+                        SUCCESS : ERROR;
             } catch (RemoteException e) {
                 // TTS died; restart it.
                 Log.e("TextToSpeech.java - synthesizeToFile", "RemoteException");
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 8981419..fb15f78 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -192,6 +192,7 @@
     private boolean         mBuiltInZoomControls = false;
     private boolean         mAllowFileAccess = true;
     private boolean         mLoadWithOverviewMode = false;
+    private boolean         mUseSystemOverscrollBackground = false;
 
     // private WebSettings, not accessible by the host activity
     static private int      mDoubleTapToastCount = 3;
@@ -470,6 +471,23 @@
     }
 
     /**
+     * Set whether the WebView uses system background for over scroll
+     * background. If false, it will use the WebView's background. Default is
+     * false.
+     */
+    public void setUseSystemOverscrollBackground(boolean system) {
+        mUseSystemOverscrollBackground = system;
+    }
+
+    /**
+     * Returns true if this WebView uses system background instead of WebView
+     * background for over scroll background.
+     */
+    public boolean getUseSystemOverscrollBackground() {
+        return mUseSystemOverscrollBackground;
+    }
+
+    /**
      * Store whether the WebView is saving form data.
      */
     public void setSaveFormData(boolean save) {
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index a889476..6f6ee1d 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -68,6 +68,7 @@
 import android.view.inputmethod.InputMethodManager;
 import android.webkit.WebTextView.AutoCompleteAdapter;
 import android.webkit.WebViewCore.EventHub;
+import android.webkit.WebViewCore.TouchEventData;
 import android.widget.AbsoluteLayout;
 import android.widget.Adapter;
 import android.widget.AdapterView;
@@ -375,27 +376,29 @@
     // Whether to forward the touch events to WebCore
     private boolean mForwardTouchEvents = false;
 
-    // Whether to prevent drag during touch. The initial value depends on
-    // mForwardTouchEvents. If WebCore wants touch events, we assume it will
-    // take control of touch events unless it says no for touch down event.
-    private static final int PREVENT_DRAG_NO = 0;
-    private static final int PREVENT_DRAG_MAYBE_YES = 1;
-    private static final int PREVENT_DRAG_YES = 2;
-    private static final int PREVENT_DRAG_CANCEL = 3;
-    private int mPreventDrag = PREVENT_DRAG_NO;
+    // Whether to prevent default during touch. The initial value depends on
+    // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
+    // for touch down. Otherwise UI will wait for the answer of the first
+    // confirmed move before taking over the control.
+    private static final int PREVENT_DEFAULT_NO = 0;
+    private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
+    private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
+    private static final int PREVENT_DEFAULT_YES = 3;
+    private static final int PREVENT_DEFAULT_IGNORE = 4;
+    private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
 
-    // by default mPreventLongPress is false. If it is true, long press event
-    // will be handled by WebKit instead of UI.
-    private boolean mPreventLongPress = false;
-    // by default mPreventDoubleTap is false. If it is true, double tap event
-    // will be handled by WebKit instead of UI.
-    private boolean mPreventDoubleTap = false;
+    // true when the touch movement exceeds the slop
+    private boolean mConfirmMove;
 
-    // this needs to be in sync with the logic in WebKit's
-    // EventHandler::handleTouchEvent()
-    private static final int TOUCH_PREVENT_DRAG         = 0x1;
-    private static final int TOUCH_PREVENT_LONGPRESS    = 0x2;
-    private static final int TOUCH_PREVENT_DOUBLETAP    = 0x4;
+    // if true, touch events will be first processed by WebCore, if prevent
+    // default is not set, the UI will continue handle them.
+    private boolean mDeferTouchProcess;
+
+    // to avoid interfering with the current touch events, track them
+    // separately. Currently no snapping or fling in the deferred process mode
+    private int mDeferTouchMode = TOUCH_DONE_MODE;
+    private float mLastDeferTouchX;
+    private float mLastDeferTouchY;
 
     // To keep track of whether the current drag was initiated by a WebTextView,
     // so that we know not to hide the cursor
@@ -484,7 +487,7 @@
     private int mAnchorX;
     private int mAnchorY;
 
-    /**
+    /*
      * Private message ids
      */
     private static final int REMEMBER_PASSWORD          = 1;
@@ -496,39 +499,49 @@
     private static final int RESUME_WEBCORE_PRIORITY    = 7;
     private static final int DRAG_HELD_MOTIONLESS       = 8;
     private static final int AWAKEN_SCROLL_BARS         = 9;
+    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
 
+    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
+    private static final int LAST_PRIVATE_MSG_ID = PREVENT_DEFAULT_TIMEOUT;
+
+    /*
+     * Package message ids
+     */
     //! arg1=x, arg2=y
-    static final int SCROLL_TO_MSG_ID                   = 10;
-    static final int SCROLL_BY_MSG_ID                   = 11;
+    static final int SCROLL_TO_MSG_ID                   = 101;
+    static final int SCROLL_BY_MSG_ID                   = 102;
     //! arg1=x, arg2=y
-    static final int SPAWN_SCROLL_TO_MSG_ID             = 12;
+    static final int SPAWN_SCROLL_TO_MSG_ID             = 103;
     //! arg1=x, arg2=y
-    static final int SYNC_SCROLL_TO_MSG_ID              = 13;
-    static final int NEW_PICTURE_MSG_ID                 = 14;
-    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 15;
-    static final int WEBCORE_INITIALIZED_MSG_ID         = 16;
-    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 17;
-    static final int UPDATE_ZOOM_RANGE                  = 18;
-    static final int MOVE_OUT_OF_PLUGIN                 = 19;
-    static final int CLEAR_TEXT_ENTRY                   = 20;
-    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 21;
-    static final int SHOW_RECT_MSG_ID                   = 22;
-    static final int LONG_PRESS_CENTER                  = 23;
-    static final int PREVENT_TOUCH_ID                   = 24;
-    static final int WEBCORE_NEED_TOUCH_EVENTS          = 25;
+    static final int SYNC_SCROLL_TO_MSG_ID              = 104;
+    static final int NEW_PICTURE_MSG_ID                 = 105;
+    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 106;
+    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
+    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
+    static final int UPDATE_ZOOM_RANGE                  = 109;
+    static final int MOVE_OUT_OF_PLUGIN                 = 110;
+    static final int CLEAR_TEXT_ENTRY                   = 111;
+    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
+    static final int SHOW_RECT_MSG_ID                   = 113;
+    static final int LONG_PRESS_CENTER                  = 114;
+    static final int PREVENT_TOUCH_ID                   = 115;
+    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
     // obj=Rect in doc coordinates
-    static final int INVAL_RECT_MSG_ID                  = 26;
-    static final int REQUEST_KEYBOARD                   = 27;
-    static final int DO_MOTION_UP                       = 28;
-    static final int SHOW_FULLSCREEN                    = 29;
-    static final int HIDE_FULLSCREEN                    = 30;
-    static final int DOM_FOCUS_CHANGED                  = 31;
-    static final int IMMEDIATE_REPAINT_MSG_ID           = 32;
-    static final int SET_ROOT_LAYER_MSG_ID              = 33;
-    static final int RETURN_LABEL                       = 34;
-    static final int FIND_AGAIN                         = 35;
+    static final int INVAL_RECT_MSG_ID                  = 117;
+    static final int REQUEST_KEYBOARD                   = 118;
+    static final int DO_MOTION_UP                       = 119;
+    static final int SHOW_FULLSCREEN                    = 120;
+    static final int HIDE_FULLSCREEN                    = 121;
+    static final int DOM_FOCUS_CHANGED                  = 122;
+    static final int IMMEDIATE_REPAINT_MSG_ID           = 123;
+    static final int SET_ROOT_LAYER_MSG_ID              = 124;
+    static final int RETURN_LABEL                       = 125;
+    static final int FIND_AGAIN                         = 126;
 
-    static final String[] HandlerDebugString = {
+    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
+    private static final int LAST_PACKAGE_MSG_ID = FIND_AGAIN;
+
+    static final String[] HandlerPrivateDebugString = {
         "REMEMBER_PASSWORD", //              = 1;
         "NEVER_REMEMBER_PASSWORD", //        = 2;
         "SWITCH_TO_SHORTPRESS", //           = 3;
@@ -538,32 +551,36 @@
         "RESUME_WEBCORE_PRIORITY", //        = 7;
         "DRAG_HELD_MOTIONLESS", //           = 8;
         "AWAKEN_SCROLL_BARS", //             = 9;
-        "SCROLL_TO_MSG_ID", //               = 10;
-        "SCROLL_BY_MSG_ID", //               = 11;
-        "SPAWN_SCROLL_TO_MSG_ID", //         = 12;
-        "SYNC_SCROLL_TO_MSG_ID", //          = 13;
-        "NEW_PICTURE_MSG_ID", //             = 14;
-        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 15;
-        "WEBCORE_INITIALIZED_MSG_ID", //     = 16;
-        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 17;
-        "UPDATE_ZOOM_RANGE", //              = 18;
-        "MOVE_OUT_OF_PLUGIN", //             = 19;
-        "CLEAR_TEXT_ENTRY", //               = 20;
-        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 21;
-        "SHOW_RECT_MSG_ID", //               = 22;
-        "LONG_PRESS_CENTER", //              = 23;
-        "PREVENT_TOUCH_ID", //               = 24;
-        "WEBCORE_NEED_TOUCH_EVENTS", //      = 25;
-        "INVAL_RECT_MSG_ID", //              = 26;
-        "REQUEST_KEYBOARD", //               = 27;
-        "DO_MOTION_UP", //                   = 28;
-        "SHOW_FULLSCREEN", //                = 29;
-        "HIDE_FULLSCREEN", //                = 30;
-        "DOM_FOCUS_CHANGED", //              = 31;
-        "IMMEDIATE_REPAINT_MSG_ID", //       = 32;
-        "SET_ROOT_LAYER_MSG_ID", //          = 33;
-        "RETURN_LABEL", //                   = 34;
-        "FIND_AGAIN" //                      = 35;
+        "PREVENT_DEFAULT_TIMEOUT" //         = 10;
+    };
+
+    static final String[] HandlerPackageDebugString = {
+        "SCROLL_TO_MSG_ID", //               = 101;
+        "SCROLL_BY_MSG_ID", //               = 102;
+        "SPAWN_SCROLL_TO_MSG_ID", //         = 103;
+        "SYNC_SCROLL_TO_MSG_ID", //          = 104;
+        "NEW_PICTURE_MSG_ID", //             = 105;
+        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
+        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
+        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
+        "UPDATE_ZOOM_RANGE", //              = 109;
+        "MOVE_OUT_OF_PLUGIN", //             = 110;
+        "CLEAR_TEXT_ENTRY", //               = 111;
+        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
+        "SHOW_RECT_MSG_ID", //               = 113;
+        "LONG_PRESS_CENTER", //              = 114;
+        "PREVENT_TOUCH_ID", //               = 115;
+        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
+        "INVAL_RECT_MSG_ID", //              = 117;
+        "REQUEST_KEYBOARD", //               = 118;
+        "DO_MOTION_UP", //                   = 119;
+        "SHOW_FULLSCREEN", //                = 120;
+        "HIDE_FULLSCREEN", //                = 121;
+        "DOM_FOCUS_CHANGED", //              = 122;
+        "IMMEDIATE_REPAINT_MSG_ID", //       = 123;
+        "SET_ROOT_LAYER_MSG_ID", //          = 124;
+        "RETURN_LABEL", //                   = 125;
+        "FIND_AGAIN" //                      = 126;
     };
 
     // If the site doesn't use the viewport meta tag to specify the viewport,
@@ -1125,9 +1142,11 @@
             mCallbackProxy.setWebViewClient(null);
             mCallbackProxy.setWebChromeClient(null);
             // Tell WebViewCore to destroy itself
-            WebViewCore webViewCore = mWebViewCore;
-            mWebViewCore = null; // prevent using partial webViewCore
-            webViewCore.destroy();
+            synchronized (this) {
+                WebViewCore webViewCore = mWebViewCore;
+                mWebViewCore = null; // prevent using partial webViewCore
+                webViewCore.destroy();
+            }
             // Remove any pending messages that might not be serviced yet.
             mPrivateHandler.removeCallbacksAndMessages(null);
             mCallbackProxy.removeCallbacksAndMessages(null);
@@ -2286,9 +2305,11 @@
             boolean clampedY) {
         mInOverScrollMode = false;
         int maxX = computeMaxScrollX();
-        if (Math.abs(mMinZoomScale - mMaxZoomScale) < 0.01f && maxX == 0) {
-            // do not over scroll x if the page can't be zoomed and it just fits
-            // the screen
+        if (maxX == 0 && (Math.abs(mMinZoomScale - mMaxZoomScale) < 0.01f)
+                || !getSettings().supportZoom()
+                || !getSettings().getUseWideViewPort()) {
+            // do not over scroll x if the page just fits the screen and it
+            // can't zoom or the view doesn't use wide viewport
             scrollX = pinLocX(scrollX);
         } else if (scrollX < 0 || scrollX > maxX) {
             mInOverScrollMode = true;
@@ -3093,7 +3114,8 @@
         }
 
         int saveCount = canvas.save();
-        if (mInOverScrollMode) {
+        if (mInOverScrollMode
+                && getSettings().getUseSystemOverscrollBackground()) {
             if (mOverScrollBackground == null) {
                 mOverScrollBackground = new Paint();
                 Bitmap bm = BitmapFactory.decodeResource(
@@ -3236,10 +3258,11 @@
         }
 
         boolean animateZoom = mZoomScale != 0;
-        boolean animateScroll = (!mScroller.isFinished()
+        boolean animateScroll = ((!mScroller.isFinished()
                 || mVelocityTracker != null)
                 && (mTouchMode != TOUCH_DRAG_MODE ||
-                mHeldMotionless != MOTIONLESS_TRUE);
+                mHeldMotionless != MOTIONLESS_TRUE))
+                || mDeferTouchMode == TOUCH_DRAG_MODE;
         if (mTouchMode == TOUCH_DRAG_MODE) {
             if (mHeldMotionless == MOTIONLESS_PENDING) {
                 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
@@ -3336,11 +3359,9 @@
             if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
                 mTouchMode = TOUCH_SHORTPRESS_MODE;
                 HitTestResult hitTest = getHitTestResult();
-                if (mPreventLongPress || (hitTest != null &&
-                        hitTest.mType != HitTestResult.UNKNOWN_TYPE)) {
-                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                            .obtainMessage(SWITCH_TO_LONGPRESS),
-                            LONG_PRESS_TIMEOUT);
+                if (hitTest == null
+                        || hitTest.mType == HitTestResult.UNKNOWN_TYPE) {
+                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                 }
             }
         }
@@ -3673,11 +3694,13 @@
             return false;
         }
 
-        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
-                && !nativeFocusIsPlugin()
-                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
-                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
-            setUpSelectXY();
+        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
+                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
+            if (nativeFocusIsPlugin()) {
+                mShiftIsPressed = true;
+            } else if (!nativeCursorWantsKeyEvents() && !mShiftIsPressed) {
+                setUpSelectXY();
+            }
         }
 
         if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
@@ -3816,7 +3839,10 @@
 
         if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
                 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
-            if (commitCopy()) {
+            if (nativeFocusIsPlugin()) {
+                mShiftIsPressed = false;
+                return true;
+            } else if (commitCopy()) {
                 return true;
             }
         }
@@ -4177,7 +4203,9 @@
     public boolean dispatchKeyEvent(KeyEvent event) {
         boolean dispatch = true;
 
-        if (!inEditingMode()) {
+        // Textfields and plugins need to receive the shift up key even if
+        // another key was released while the shift key was held down.
+        if (!inEditingMode() && !nativeFocusIsPlugin()) {
             if (event.getAction() == KeyEvent.ACTION_DOWN) {
                 mGotKeyDown = true;
             } else {
@@ -4456,6 +4484,7 @@
             // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it
             // may trigger the unwanted fling.
             mTouchMode = TOUCH_PINCH_DRAG;
+            mConfirmMove = true;
             startTouch(detector.getFocusX(), detector.getFocusY(),
                     mLastTouchTime);
         }
@@ -4481,6 +4510,22 @@
         }
     }
 
+    private boolean hitFocusedPlugin(int contentX, int contentY) {
+        return nativeFocusIsPlugin()
+                && nativePointInNavCache(contentX, contentY, mNavSlop)
+                && nativeCacheHitNodePointer() == nativeFocusNodePointer();
+    }
+
+    private boolean shouldForwardTouchEvent() {
+        return mFullScreenHolder != null || (mForwardTouchEvents
+                && mTouchMode != TOUCH_SELECT_MODE
+                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
+    }
+
+    private boolean inFullScreenMode() {
+        return mFullScreenHolder != null;
+    }
+
     @Override
     public boolean onTouchEvent(MotionEvent ev) {
         if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
@@ -4542,46 +4587,33 @@
             y = getViewHeightWithTitle() - 1;
         }
 
-        // pass the touch events, except ACTION_MOVE which will be handled
-        // later, from UI thread to WebCore thread
-        if (mFullScreenHolder != null || (mForwardTouchEvents
-                && action != MotionEvent.ACTION_MOVE
-                && (action == MotionEvent.ACTION_DOWN || mPreventDrag
-                        != PREVENT_DRAG_CANCEL))) {
-            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-            ted.mAction = action;
-            ted.mX = viewToContentX((int) x + mScrollX);
-            ted.mY = viewToContentY((int) y + mScrollY);
-            ted.mEventTime = eventTime;
-            ted.mMetaState = ev.getMetaState();
-            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-            mLastSentTouchTime = eventTime;
-        }
-
         float fDeltaX = mLastTouchX - x;
         float fDeltaY = mLastTouchY - y;
         int deltaX = (int) fDeltaX;
         int deltaY = (int) fDeltaY;
+        int contentX = viewToContentX((int) x + mScrollX);
+        int contentY = viewToContentY((int) y + mScrollY);
 
         switch (action) {
             case MotionEvent.ACTION_DOWN: {
-                mPreventDrag = PREVENT_DRAG_NO;
+                mPreventDefault = PREVENT_DEFAULT_NO;
+                mConfirmMove = false;
                 if (!mScroller.isFinished()) {
                     // stop the current scroll animation, but if this is
                     // the start of a fling, allow it to add to the current
                     // fling's velocity
                     mScroller.abortAnimation();
                     mTouchMode = TOUCH_DRAG_START_MODE;
+                    mConfirmMove = true;
                     mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
-                } else if (mShiftIsPressed) {
+                } else if (!inFullScreenMode() && mShiftIsPressed) {
                     mSelectX = mScrollX + (int) x;
                     mSelectY = mScrollY + (int) y;
                     mTouchMode = TOUCH_SELECT_MODE;
                     if (DebugFlags.WEB_VIEW) {
                         Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
                     }
-                    nativeMoveSelection(viewToContentX(mSelectX),
-                            viewToContentY(mSelectY), false);
+                    nativeMoveSelection(contentX, contentY, false);
                     mTouchSelection = mExtendSelection = true;
                     invalidate(); // draw the i-beam instead of the arrow
                 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
@@ -4591,15 +4623,17 @@
                     } else {
                         // commit the short press action for the previous tap
                         doShortPress();
-                        // continue, mTouchMode should be still TOUCH_INIT_MODE
+                        mTouchMode = TOUCH_INIT_MODE;
+                        mDeferTouchProcess = (!inFullScreenMode()
+                                && mForwardTouchEvents) ? hitFocusedPlugin(
+                                contentX, contentY) : false;
                     }
-                } else {
+                } else { // the normal case
                     mPreviewZoomOnly = false;
                     mTouchMode = TOUCH_INIT_MODE;
-                    mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
-                            : PREVENT_DRAG_NO;
-                    mPreventLongPress = false;
-                    mPreventDoubleTap = false;
+                    mDeferTouchProcess = (!inFullScreenMode()
+                            && mForwardTouchEvents) ? hitFocusedPlugin(
+                            contentX, contentY) : false;
                     mWebViewCore.sendMessage(
                             EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
                     if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
@@ -4610,19 +4644,87 @@
                 // Trigger the link
                 if (mTouchMode == TOUCH_INIT_MODE
                         || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
-                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
+                    mPrivateHandler.sendEmptyMessageDelayed(
+                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
+                    mPrivateHandler.sendEmptyMessageDelayed(
+                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
+                    if (inFullScreenMode() || mDeferTouchProcess) {
+                        mPreventDefault = PREVENT_DEFAULT_YES;
+                    } else if (mForwardTouchEvents) {
+                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
+                    } else {
+                        mPreventDefault = PREVENT_DEFAULT_NO;
+                    }
+                    // pass the touch events from UI thread to WebCore thread
+                    if (shouldForwardTouchEvent()) {
+                        TouchEventData ted = new TouchEventData();
+                        ted.mAction = action;
+                        ted.mX = contentX;
+                        ted.mY = contentY;
+                        ted.mMetaState = ev.getMetaState();
+                        ted.mReprocess = mDeferTouchProcess;
+                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                        if (mDeferTouchProcess) {
+                            // still needs to set them for compute deltaX/Y
+                            mLastTouchX = x;
+                            mLastTouchY = y;
+                            break;
+                        }
+                        if (!inFullScreenMode()) {
+                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
+                                            action, 0), TAP_TIMEOUT);
+                        }
+                    }
                 }
                 startTouch(x, y, eventTime);
                 break;
             }
             case MotionEvent.ACTION_MOVE: {
-                if (mTouchMode == TOUCH_DONE_MODE) {
-                    // no dragging during scroll zoom animation
+                boolean firstMove = false;
+                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
+                        >= mTouchSlopSquare) {
+                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
+                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
+                    mConfirmMove = true;
+                    firstMove = true;
+                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
+                        mTouchMode = TOUCH_INIT_MODE;
+                    }
+                }
+                // pass the touch events from UI thread to WebCore thread
+                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
+                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
+                    TouchEventData ted = new TouchEventData();
+                    ted.mAction = action;
+                    ted.mX = contentX;
+                    ted.mY = contentY;
+                    ted.mMetaState = ev.getMetaState();
+                    ted.mReprocess = mDeferTouchProcess;
+                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                    mLastSentTouchTime = eventTime;
+                    if (mDeferTouchProcess) {
+                        break;
+                    }
+                    if (firstMove && !inFullScreenMode()) {
+                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
+                                        action, 0), TAP_TIMEOUT);
+                    }
+                }
+                if (mTouchMode == TOUCH_DONE_MODE
+                        || mPreventDefault == PREVENT_DEFAULT_YES) {
+                    // no dragging during scroll zoom animation, or when prevent
+                    // default is yes
                     break;
                 }
+                if (mVelocityTracker == null) {
+                    Log.e(LOGTAG, "Got null mVelocityTracker when "
+                            + "mPreventDefault = " + mPreventDefault
+                            + " mDeferTouchProcess = " + mDeferTouchProcess
+                            + " mTouchMode = " + mTouchMode);
+                }
                 mVelocityTracker.addMovement(ev);
-
                 if (mTouchMode != TOUCH_DRAG_MODE) {
                     if (mTouchMode == TOUCH_SELECT_MODE) {
                         mSelectX = mScrollX + (int) x;
@@ -4630,48 +4732,20 @@
                         if (DebugFlags.WEB_VIEW) {
                             Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
                         }
-                        nativeMoveSelection(viewToContentX(mSelectX),
-                               viewToContentY(mSelectY), true);
+                        nativeMoveSelection(contentX, contentY, true);
                         invalidate();
                         break;
                     }
-                    if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
+                    if (!mConfirmMove) {
                         break;
                     }
-
-                    // pass the first ACTION_MOVE from UI thread to WebCore
-                    // thread after the distance is confirmed that it is a drag
-                    if (mFullScreenHolder == null && mForwardTouchEvents
-                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = action;
-                        ted.mX = viewToContentX((int) x + mScrollX);
-                        ted.mY = viewToContentY((int) y + mScrollY);
-                        ted.mEventTime = eventTime;
-                        ted.mMetaState = ev.getMetaState();
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        mLastSentTouchTime = eventTime;
-                    }
-
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
+                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
+                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
                         // track mLastTouchTime as we may need to do fling at
                         // ACTION_UP
                         mLastTouchTime = eventTime;
                         break;
                     }
-                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
-                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
-                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
-                    } else if (mTouchMode == TOUCH_INIT_MODE
-                            || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
-                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
-                    }
-                    if (mFullScreenHolder != null) {
-                        // in full screen mode, the WebView can't be panned.
-                        mTouchMode = TOUCH_DONE_MODE;
-                        break;
-                    }
-
                     // if it starts nearly horizontal or vertical, enforce it
                     int ax = Math.abs(deltaX);
                     int ay = Math.abs(deltaY);
@@ -4691,38 +4765,11 @@
                     deltaX = 0;
                     deltaY = 0;
 
-                    WebViewCore.reducePriority();
-                    if (!mDragFromTextInput) {
-                        nativeHideCursor();
-                    }
-                    WebSettings settings = getSettings();
-                    if (settings.supportZoom()
-                            && settings.getBuiltInZoomControls()
-                            && !mZoomButtonsController.isVisible()
-                            && mMinZoomScale < mMaxZoomScale) {
-                        mZoomButtonsController.setVisible(true);
-                        int count = settings.getDoubleTapToastCount();
-                        if (mInZoomOverview && count > 0) {
-                            settings.setDoubleTapToastCount(--count);
-                            Toast.makeText(mContext,
-                                    com.android.internal.R.string.double_tap_toast,
-                                    Toast.LENGTH_LONG).show();
-                        }
-                    }
-                } else {
-                    // pass the touch events from UI thread to WebCore thread
-                    if (mFullScreenHolder == null && mForwardTouchEvents
-                            && eventTime - mLastSentTouchTime > mCurrentTouchInterval
-                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = action;
-                        ted.mX = viewToContentX((int) x + mScrollX);
-                        ted.mY = viewToContentY((int) y + mScrollY);
-                        ted.mEventTime = eventTime;
-                        ted.mMetaState = ev.getMetaState();
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        mLastSentTouchTime = eventTime;
-                    }
+                    startDrag();
+                }
+
+                if (mDragTrackerHandler != null) {
+                    mDragTrackerHandler.dragTo(x, y);
                 }
 
                 // do pan
@@ -4770,9 +4817,6 @@
                         }
                     }
                     if ((deltaX | deltaY) != 0) {
-                        overscrollBy(deltaX, deltaY, mScrollX, mScrollY,
-                                computeMaxScrollX(), computeMaxScrollY(),
-                                getViewWidth() / 3, getViewHeight() / 3);
                         if (deltaX != 0) {
                             mLastTouchX = x;
                         }
@@ -4789,22 +4833,7 @@
                     mUserScroll = true;
                 }
 
-                if (!getSettings().getBuiltInZoomControls()) {
-                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
-                    if (mZoomControls != null && showPlusMinus) {
-                        if (mZoomControls.getVisibility() == View.VISIBLE) {
-                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
-                        } else {
-                            mZoomControls.show(showPlusMinus, false);
-                        }
-                        mPrivateHandler.postDelayed(mZoomControlRunnable,
-                                ZOOM_CONTROLS_TIMEOUT);
-                    }
-                }
-
-                if (mDragTrackerHandler != null) {
-                    mDragTrackerHandler.dragTo(x, y);
-                }
+                doDrag(deltaX, deltaY);
 
                 if (keepScrollBarsVisible) {
                     if (mHeldMotionless != MOTIONLESS_TRUE) {
@@ -4821,25 +4850,32 @@
                 break;
             }
             case MotionEvent.ACTION_UP: {
-                if (mDragTrackerHandler != null) {
-                    mDragTrackerHandler.stopDrag();
+                // pass the touch events from UI thread to WebCore thread
+                if (shouldForwardTouchEvent()) {
+                    TouchEventData ted = new TouchEventData();
+                    ted.mAction = action;
+                    ted.mX = contentX;
+                    ted.mY = contentY;
+                    ted.mMetaState = ev.getMetaState();
+                    ted.mReprocess = mDeferTouchProcess;
+                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
                 }
                 mLastTouchUpTime = eventTime;
                 switch (mTouchMode) {
                     case TOUCH_DOUBLE_TAP_MODE: // double tap
                         mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
-                        mTouchMode = TOUCH_DONE_MODE;
-                        if (mPreventDoubleTap) {
-                            WebViewCore.TouchEventData ted
-                                    = new WebViewCore.TouchEventData();
+                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
+                        if (inFullScreenMode() || mDeferTouchProcess) {
+                            TouchEventData ted = new TouchEventData();
                             ted.mAction = WebViewCore.ACTION_DOUBLETAP;
-                            ted.mX = viewToContentX((int) x + mScrollX);
-                            ted.mY = viewToContentY((int) y + mScrollY);
-                            ted.mEventTime = eventTime;
+                            ted.mX = contentX;
+                            ted.mY = contentY;
                             ted.mMetaState = ev.getMetaState();
+                            ted.mReprocess = mDeferTouchProcess;
                             mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        } else if (mFullScreenHolder == null) {
+                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
                             doDoubleTap();
+                            mTouchMode = TOUCH_DONE_MODE;
                         }
                         break;
                     case TOUCH_SELECT_MODE:
@@ -4851,20 +4887,15 @@
                     case TOUCH_SHORTPRESS_MODE:
                         mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                         mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
-                        if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
+                        if (mConfirmMove) {
                             Log.w(LOGTAG, "Miss a drag as we are waiting for" +
                                     " WebCore's response for touch down.");
-                            if (mFullScreenHolder == null
+                            if (mPreventDefault != PREVENT_DEFAULT_YES
                                     && (computeMaxScrollX() > 0
                                             || computeMaxScrollY() > 0)) {
-                                // remove the pending TOUCH_EVENT and send a
-                                // cancel
-                                mWebViewCore
-                                        .removeMessages(EventHub.TOUCH_EVENT);
-                                WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                                ted.mAction = MotionEvent.ACTION_CANCEL;
-                                mWebViewCore.sendMessage(EventHub.TOUCH_EVENT,
-                                        ted);
+                                // UI takes control back, cancel WebCore touch
+                                cancelWebCoreTouchEvent(contentX, contentY,
+                                        true);
                                 // we will not rewrite drag code here, but we
                                 // will try fling if it applies.
                                 WebViewCore.reducePriority();
@@ -4873,20 +4904,12 @@
                                 break;
                             }
                         } else {
-                            // mPreventDrag can be PREVENT_DRAG_MAYBE_YES in
-                            // TOUCH_INIT_MODE. To give WebCoreThread a little
-                            // more time to send PREVENT_TOUCH_ID, we check
-                            // again in responding RELEASE_SINGLE_TAP.
-                            if (mPreventDrag != PREVENT_DRAG_YES) {
-                                if (mTouchMode == TOUCH_INIT_MODE) {
-                                    mPrivateHandler.sendMessageDelayed(
-                                            mPrivateHandler.obtainMessage(
-                                            RELEASE_SINGLE_TAP),
-                                            ViewConfiguration.getDoubleTapTimeout());
-                                } else {
-                                    mTouchMode = TOUCH_DONE_MODE;
-                                    doShortPress();
-                                }
+                            if (mTouchMode == TOUCH_INIT_MODE) {
+                                mPrivateHandler.sendEmptyMessageDelayed(
+                                        RELEASE_SINGLE_TAP, ViewConfiguration
+                                                .getDoubleTapTimeout());
+                            } else {
+                                doShortPress();
                             }
                             break;
                         }
@@ -4899,6 +4922,13 @@
                         // if the user waits a while w/o moving before the
                         // up, we don't want to do a fling
                         if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
+                            if (mVelocityTracker == null) {
+                                Log.e(LOGTAG, "Got null mVelocityTracker when "
+                                        + "mPreventDefault = "
+                                        + mPreventDefault
+                                        + " mDeferTouchProcess = "
+                                        + mDeferTouchProcess);
+                            }
                             mVelocityTracker.addMovement(ev);
                             doFling();
                             break;
@@ -4912,34 +4942,38 @@
                         mLastVelocity = 0;
                         WebViewCore.resumePriority();
                         break;
-                    case TOUCH_DRAG_START_MODE:
-                    case TOUCH_DONE_MODE:
-                        // do nothing
-                        break;
                 }
-                // we also use mVelocityTracker == null to tell us that we are
-                // not "moving around", so we can take the slower/prettier
-                // mode in the drawing code
-                if (mVelocityTracker != null) {
-                    mVelocityTracker.recycle();
-                    mVelocityTracker = null;
-                }
+                stopTouch();
                 break;
             }
             case MotionEvent.ACTION_CANCEL: {
-                cancelTouch();
                 if (mTouchMode == TOUCH_DRAG_MODE) {
-                    if (mScroller.springback(mScrollX, mScrollY, 0,
-                            computeMaxScrollX(), 0, computeMaxScrollY())) {
-                        invalidate();
-                    }
+                    mScroller.springback(mScrollX, mScrollY, 0,
+                            computeMaxScrollX(), 0, computeMaxScrollY());
+                    invalidate();
                 }
+                cancelWebCoreTouchEvent(contentX, contentY, false);
+                cancelTouch();
                 break;
             }
         }
         return true;
     }
 
+    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
+        if (shouldForwardTouchEvent()) {
+            if (removeEvents) {
+                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
+            }
+            TouchEventData ted = new TouchEventData();
+            ted.mX = x;
+            ted.mY = y;
+            ted.mAction = MotionEvent.ACTION_CANCEL;
+            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+            mPreventDefault = PREVENT_DEFAULT_IGNORE;
+        }
+    }
+
     private void startTouch(float x, float y, long eventTime) {
         // Remember where the motion event started
         mLastTouchX = x;
@@ -4952,6 +4986,60 @@
         }
     }
 
+    private void startDrag() {
+        WebViewCore.reducePriority();
+        if (!mDragFromTextInput) {
+            nativeHideCursor();
+        }
+        WebSettings settings = getSettings();
+        if (settings.supportZoom()
+                && settings.getBuiltInZoomControls()
+                && !mZoomButtonsController.isVisible()
+                && mMinZoomScale < mMaxZoomScale) {
+            mZoomButtonsController.setVisible(true);
+            int count = settings.getDoubleTapToastCount();
+            if (mInZoomOverview && count > 0) {
+                settings.setDoubleTapToastCount(--count);
+                Toast.makeText(mContext,
+                        com.android.internal.R.string.double_tap_toast,
+                        Toast.LENGTH_LONG).show();
+            }
+        }
+    }
+
+    private void doDrag(int deltaX, int deltaY) {
+        if ((deltaX | deltaY) != 0) {
+            overscrollBy(deltaX, deltaY, mScrollX, mScrollY,
+                    computeMaxScrollX(), computeMaxScrollY(),
+                    getViewWidth() / 3, getViewHeight() / 3);
+        }
+        if (!getSettings().getBuiltInZoomControls()) {
+            boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
+            if (mZoomControls != null && showPlusMinus) {
+                if (mZoomControls.getVisibility() == View.VISIBLE) {
+                    mPrivateHandler.removeCallbacks(mZoomControlRunnable);
+                } else {
+                    mZoomControls.show(showPlusMinus, false);
+                }
+                mPrivateHandler.postDelayed(mZoomControlRunnable,
+                        ZOOM_CONTROLS_TIMEOUT);
+            }
+        }
+    }
+
+    private void stopTouch() {
+        if (mDragTrackerHandler != null) {
+            mDragTrackerHandler.stopDrag();
+        }
+        // we also use mVelocityTracker == null to tell us that we are
+        // not "moving around", so we can take the slower/prettier
+        // mode in the drawing code
+        if (mVelocityTracker != null) {
+            mVelocityTracker.recycle();
+            mVelocityTracker = null;
+        }
+    }
+
     private void cancelTouch() {
         if (mDragTrackerHandler != null) {
             mDragTrackerHandler.stopDrag();
@@ -5226,8 +5314,8 @@
             if (nativeFocusIsPlugin()) {
                 for (int i = 0; i < count; i++) {
                     letPluginHandleNavKey(selectKeyCode, time, true);
-                    letPluginHandleNavKey(selectKeyCode, time, false);
                 }
+                letPluginHandleNavKey(selectKeyCode, time, false);
             } else if (navHandledKey(selectKeyCode, count, false, time)) {
                 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
             }
@@ -5571,6 +5659,10 @@
         if (mNativeClass == 0) {
             return;
         }
+        if (mPreventDefault == PREVENT_DEFAULT_YES) {
+            return;
+        }
+        mTouchMode = TOUCH_DONE_MODE;
         switchOutDrawHistory();
         // mLastTouchX and mLastTouchY are the point in the current viewport
         int contentX = viewToContentX((int) mLastTouchX + mScrollX);
@@ -5767,10 +5859,15 @@
         rect.offset(child.getLeft() - child.getScrollX(),
                 child.getTop() - child.getScrollY());
 
-        int height = getViewHeightWithTitle();
-        int screenTop = mScrollY;
-        int screenBottom = screenTop + height;
-
+        Rect content = new Rect(viewToContentX(mScrollX),
+                viewToContentY(mScrollY),
+                viewToContentX(mScrollX + getWidth()
+                - getVerticalScrollbarWidth()),
+                viewToContentY(mScrollY + getViewHeightWithTitle()));
+        content = nativeSubtractLayers(content);
+        int screenTop = contentToViewY(content.top);
+        int screenBottom = contentToViewY(content.bottom);
+        int height = screenBottom - screenTop;
         int scrollYDelta = 0;
 
         if (rect.bottom > screenBottom) {
@@ -5788,10 +5885,9 @@
             scrollYDelta = rect.top - screenTop;
         }
 
-        int width = getWidth() - getVerticalScrollbarWidth();
-        int screenLeft = mScrollX;
-        int screenRight = screenLeft + width;
-
+        int screenLeft = contentToViewX(content.left);
+        int screenRight = contentToViewX(content.right);
+        int width = screenRight - screenLeft;
         int scrollXDelta = 0;
 
         if (rect.right > screenRight && rect.left > screenLeft) {
@@ -5838,7 +5934,7 @@
                 cursorData(), 1000);
     }
 
-    /* package */ WebViewCore getWebViewCore() {
+    /* package */ synchronized WebViewCore getWebViewCore() {
         return mWebViewCore;
     }
 
@@ -5855,9 +5951,17 @@
         public void handleMessage(Message msg) {
             // exclude INVAL_RECT_MSG_ID since it is frequently output
             if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
-                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
-                        > FIND_AGAIN ? Integer.toString(msg.what)
-                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
+                if (msg.what >= FIRST_PRIVATE_MSG_ID
+                        && msg.what <= LAST_PRIVATE_MSG_ID) {
+                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
+                            - FIRST_PRIVATE_MSG_ID]);
+                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
+                        && msg.what <= LAST_PACKAGE_MSG_ID) {
+                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
+                            - FIRST_PACKAGE_MSG_ID]);
+                } else {
+                    Log.v(LOGTAG, Integer.toString(msg.what));
+                }
             }
             if (mWebViewCore == null) {
                 // after WebView's destroy() is called, skip handling messages.
@@ -5878,70 +5982,57 @@
                     ((Message) msg.obj).sendToTarget();
                     break;
                 }
-                case SWITCH_TO_SHORTPRESS: {
-                    // if mPreventDrag is not confirmed, cancel it so that it
-                    // won't block panning the page.
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                        mPreventDrag = PREVENT_DRAG_CANCEL;
-                        mPreventLongPress = false;
-                        mPreventDoubleTap = false;
-                        // remove the pending TOUCH_EVENT and send a cancel
-                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = MotionEvent.ACTION_CANCEL;
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                case PREVENT_DEFAULT_TIMEOUT: {
+                    // if timeout happens, cancel it so that it won't block UI
+                    // to continue handling touch events
+                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
+                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
+                            || (msg.arg1 == MotionEvent.ACTION_MOVE
+                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
+                        cancelWebCoreTouchEvent(
+                                viewToContentX((int) mLastTouchX + mScrollX),
+                                viewToContentY((int) mLastTouchY + mScrollY),
+                                true);
                     }
+                    break;
+                }
+                case SWITCH_TO_SHORTPRESS: {
                     if (mTouchMode == TOUCH_INIT_MODE) {
-                        mTouchMode = mFullScreenHolder == null
-                                ? TOUCH_SHORTPRESS_START_MODE
-                                        : TOUCH_SHORTPRESS_MODE;
-                        updateSelection();
+                        if (mPreventDefault != PREVENT_DEFAULT_YES) {
+                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
+                            updateSelection();
+                        } else {
+                            // set to TOUCH_SHORTPRESS_MODE so that it won't
+                            // trigger double tap any more
+                            mTouchMode = TOUCH_SHORTPRESS_MODE;
+                        }
                     } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
                         mTouchMode = TOUCH_DONE_MODE;
                     }
                     break;
                 }
                 case SWITCH_TO_LONGPRESS: {
-                    if (mPreventLongPress) {
-                        mTouchMode = TOUCH_DONE_MODE;
-                        WebViewCore.TouchEventData ted
-                                = new WebViewCore.TouchEventData();
+                    if (inFullScreenMode() || mDeferTouchProcess) {
+                        TouchEventData ted = new TouchEventData();
                         ted.mAction = WebViewCore.ACTION_LONGPRESS;
                         ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
                         ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
-                        ted.mEventTime = SystemClock.uptimeMillis();
-                        // metaState for long press is tricky. Should it be the state
-                        // when the press started or when the press was released? Or
-                        // some intermediary key state? For simplicity for now, we
-                        // don't set it.
+                        // metaState for long press is tricky. Should it be the
+                        // state when the press started or when the press was
+                        // released? Or some intermediary key state? For
+                        // simplicity for now, we don't set it.
                         ted.mMetaState = 0;
+                        ted.mReprocess = mDeferTouchProcess;
                         mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                    } else if (mPreventDrag != PREVENT_DRAG_YES) {
+                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
                         mTouchMode = TOUCH_DONE_MODE;
-                        if (mFullScreenHolder == null) {
-                            performLongClick();
-                            rebuildWebTextView();
-                        }
+                        performLongClick();
+                        rebuildWebTextView();
                     }
                     break;
                 }
                 case RELEASE_SINGLE_TAP: {
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                        // if mPreventDrag is not confirmed, cancel it so that
-                        // it won't block panning the page.
-                        mPreventDrag = PREVENT_DRAG_CANCEL;
-                        mPreventLongPress = false;
-                        mPreventDoubleTap = false;
-                        // remove the pending TOUCH_EVENT and send a cancel
-                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = MotionEvent.ACTION_CANCEL;
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                    }
-                    if (mPreventDrag != PREVENT_DRAG_YES) {
-                        mTouchMode = TOUCH_DONE_MODE;
-                        doShortPress();
-                    }
+                    doShortPress();
                     break;
                 }
                 case SCROLL_BY_MSG_ID:
@@ -6187,23 +6278,81 @@
                     break;
 
                 case PREVENT_TOUCH_ID:
-                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
-                        // dont override if mPreventDrag has been set to no due
-                        // to time out
-                        if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                            mPreventDrag = (msg.arg2 & TOUCH_PREVENT_DRAG)
-                                    == TOUCH_PREVENT_DRAG ? PREVENT_DRAG_YES
-                                    : PREVENT_DRAG_NO;
-                            if (mPreventDrag == PREVENT_DRAG_YES) {
-                                mTouchMode = TOUCH_DONE_MODE;
-                            } else {
-                                mPreventLongPress =
-                                        (msg.arg2 & TOUCH_PREVENT_LONGPRESS)
-                                        == TOUCH_PREVENT_LONGPRESS;
-                                mPreventDoubleTap =
-                                        (msg.arg2 & TOUCH_PREVENT_DOUBLETAP)
-                                        == TOUCH_PREVENT_DOUBLETAP;
+                    if (inFullScreenMode()) {
+                        break;
+                    }
+                    if (msg.obj == null) {
+                        if (msg.arg1 == MotionEvent.ACTION_DOWN
+                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
+                            // if prevent default is called from WebCore, UI
+                            // will not handle the rest of the touch events any
+                            // more.
+                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
+                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
+                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
+                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
+                            // the return for the first ACTION_MOVE will decide
+                            // whether UI will handle touch or not. Currently no
+                            // support for alternating prevent default
+                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
+                                    : PREVENT_DEFAULT_NO;
+                        }
+                    } else if (msg.arg2 == 0) {
+                        // prevent default is not called in WebCore, so the
+                        // message needs to be reprocessed in UI
+                        TouchEventData ted = (TouchEventData) msg.obj;
+                        switch (ted.mAction) {
+                            case MotionEvent.ACTION_DOWN:
+                                mLastDeferTouchX = contentToViewX(ted.mX)
+                                        - mScrollX;
+                                mLastDeferTouchY = contentToViewY(ted.mY)
+                                        - mScrollY;
+                                mDeferTouchMode = TOUCH_INIT_MODE;
+                                break;
+                            case MotionEvent.ACTION_MOVE: {
+                                // no snapping in defer process
+                                int x = contentToViewX(ted.mX) - mScrollX;
+                                int y = contentToViewY(ted.mY) - mScrollY;
+                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
+                                    mDeferTouchMode = TOUCH_DRAG_MODE;
+                                    mLastDeferTouchX = x;
+                                    mLastDeferTouchY = y;
+                                    startDrag();
+                                }
+                                doDrag((int) (mLastDeferTouchX - x),
+                                        (int) (mLastDeferTouchY - y));
+                                mLastDeferTouchX = x;
+                                mLastDeferTouchY = y;
+                                break;
                             }
+                            case MotionEvent.ACTION_UP:
+                            case MotionEvent.ACTION_CANCEL:
+                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
+                                    // no fling in defer process
+                                    mScroller.springback(mScrollX, mScrollY, 0,
+                                            computeMaxScrollX(), 0,
+                                            computeMaxScrollY());
+                                    invalidate();
+                                    WebViewCore.resumePriority();
+                                }
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
+                            case WebViewCore.ACTION_DOUBLETAP:
+                                // doDoubleTap() needs mLastTouchX/Y as anchor
+                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
+                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
+                                doDoubleTap();
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
+                            case WebViewCore.ACTION_LONGPRESS:
+                                HitTestResult hitTest = getHitTestResult();
+                                if (hitTest != null && hitTest.mType
+                                        != HitTestResult.UNKNOWN_TYPE) {
+                                    performLongClick();
+                                    rebuildWebTextView();
+                                }
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
                         }
                     }
                     break;
@@ -6247,7 +6396,7 @@
                     WebViewCore.PluginFullScreenData data
                             = (WebViewCore.PluginFullScreenData) msg.obj;
                     if (data.mNpp != 0 && data.mView != null) {
-                        if (mFullScreenHolder != null) {
+                        if (inFullScreenMode()) {
                             Log.w(LOGTAG,
                                     "Should not have another full screen.");
                             mFullScreenHolder.dismiss();
@@ -6265,7 +6414,7 @@
                         mFullScreenHolder.setCancelable(false);
                         mFullScreenHolder.setCanceledOnTouchOutside(false);
                         mFullScreenHolder.show();
-                    } else if (mFullScreenHolder == null) {
+                    } else if (!inFullScreenMode()) {
                         // this may happen if user dismisses the fullscreen and
                         // then the WebCore re-position message finally reached
                         // the UI thread.
@@ -6319,7 +6468,7 @@
                     break;
 
                 case HIDE_FULLSCREEN:
-                    if (mFullScreenHolder != null) {
+                    if (inFullScreenMode()) {
                         mFullScreenHolder.dismiss();
                         mFullScreenHolder = null;
                     }
@@ -6995,6 +7144,7 @@
     private native void     nativeSetSelectionPointer(boolean set,
             float scale, int x, int y, boolean extendSelection);
     private native void     nativeSetSelectionRegion(boolean set);
+    private native Rect     nativeSubtractLayers(Rect content);
     private native int      nativeTextGeneration();
     // Never call this version except by updateCachedTextfield(String) -
     // we always want to pass in our generation number.
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index b339015..27c7208 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -515,7 +515,8 @@
     private native void nativeTouchUp(int touchGeneration,
             int framePtr, int nodePtr, int x, int y);
 
-    private native int nativeHandleTouchEvent(int action, int x, int y, long time, int metaState);
+    private native boolean nativeHandleTouchEvent(int action, int x, int y,
+            int metaState);
 
     private native void nativeUpdateFrameCache();
 
@@ -705,8 +706,8 @@
         int mAction;
         int mX;
         int mY;
-        long mEventTime;
         int mMetaState;
+        boolean mReprocess;
     }
 
     static class GeolocationPermissionsData {
@@ -1160,9 +1161,11 @@
                             TouchEventData ted = (TouchEventData) msg.obj;
                             Message.obtain(
                                     mWebView.mPrivateHandler,
-                                    WebView.PREVENT_TOUCH_ID, ted.mAction,
+                                    WebView.PREVENT_TOUCH_ID,
+                                    ted.mAction,
                                     nativeHandleTouchEvent(ted.mAction, ted.mX,
-                                    ted.mY, ted.mEventTime, ted.mMetaState)).sendToTarget();
+                                            ted.mY, ted.mMetaState) ? 1 : 0,
+                                    ted.mReprocess ? ted : null).sendToTarget();
                             break;
                         }
 
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index e87455c..ae4d409 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -2773,7 +2773,7 @@
             final int lastPos = firstPos + getChildCount() - 1;
             
             int viewTravelCount = 0;
-            if (position < firstPos) {
+            if (position <= firstPos) {
                 final int boundPosFromLast = lastPos - boundPosition;
                 if (boundPosFromLast < 1) {
                     // Moving would shift our bound position off the screen. Abort.
@@ -2789,7 +2789,7 @@
                     viewTravelCount = posTravel;
                     mMode = MOVE_UP_POS;
                 }
-            } else if (position > lastPos) {
+            } else if (position >= lastPos) {
                 final int boundPosFromFirst = boundPosition - firstPos;
                 if (boundPosFromFirst < 1) {
                     // Moving would shift our bound position off the screen. Abort.
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 1a9c0df5..d4552e3 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -3480,10 +3480,41 @@
      * @return A new array which contains the id of each checked item in the
      *         list.
      *         
-     * @deprecated Use {@link #getCheckedItemIds()} instead. 
+     * @deprecated Use {@link #getCheckedItemIds()} instead.
      */
     public long[] getCheckItemIds() {
-        return getCheckedItemIds();
+        // Use new behavior that correctly handles stable ID mapping.
+        if (mAdapter != null && mAdapter.hasStableIds()) {
+            return getCheckedItemIds();
+        }
+
+        // Old behavior was buggy, but would sort of work for adapters without stable IDs.
+        // Fall back to it to support legacy apps.
+        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
+            final SparseBooleanArray states = mCheckStates;
+            final int count = states.size();
+            final long[] ids = new long[count];
+            final ListAdapter adapter = mAdapter;
+
+            int checkedCount = 0;
+            for (int i = 0; i < count; i++) {
+                if (states.valueAt(i)) {
+                    ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
+                }
+            }
+
+            // Trim array if needed. mCheckStates may contain false values
+            // resulting in checkedCount being smaller than count.
+            if (checkedCount == count) {
+                return ids;
+            } else {
+                final long[] result = new long[checkedCount];
+                System.arraycopy(ids, 0, result, 0, checkedCount);
+
+                return result;
+            }
+        }
+        return new long[0];
     }
     
     /**
diff --git a/core/java/android/widget/VideoView.java b/core/java/android/widget/VideoView.java
index fb8b5aa..ded0559 100644
--- a/core/java/android/widget/VideoView.java
+++ b/core/java/android/widget/VideoView.java
@@ -291,7 +291,7 @@
                 mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
                         || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
             } else {
-                mCanPause = mCanSeekForward = mCanSeekForward = true;
+                mCanPause = mCanSeekBack = mCanSeekForward = true;
             }
 
             if (mOnPreparedListener != null) {
diff --git a/core/java/com/android/internal/app/IMediaContainerService.aidl b/core/java/com/android/internal/app/IMediaContainerService.aidl
index c0e9587..fd1fd58 100755
--- a/core/java/com/android/internal/app/IMediaContainerService.aidl
+++ b/core/java/com/android/internal/app/IMediaContainerService.aidl
@@ -18,6 +18,7 @@
 
 import android.net.Uri;
 import android.os.ParcelFileDescriptor;
+import android.content.pm.PackageInfoLite;
 
 interface IMediaContainerService {
     String copyResourceToContainer(in Uri packageURI,
@@ -25,5 +26,5 @@
                 String key, String resFileName);
     boolean copyResource(in Uri packageURI,
                 in ParcelFileDescriptor outStream);
-    int getRecommendedInstallLocation(in Uri fileUri);
+    PackageInfoLite getMinimalPackageInfo(in Uri fileUri);
 }
\ No newline at end of file
diff --git a/core/java/com/android/internal/content/PackageHelper.java b/core/java/com/android/internal/content/PackageHelper.java
index 04a10b9..de6a175 100644
--- a/core/java/com/android/internal/content/PackageHelper.java
+++ b/core/java/com/android/internal/content/PackageHelper.java
@@ -36,6 +36,8 @@
     public static final int RECOMMEND_INSTALL_EXTERNAL = 2;
     public static final int RECOMMEND_FAILED_INSUFFICIENT_STORAGE = -1;
     public static final int RECOMMEND_FAILED_INVALID_APK = -2;
+    public static final int RECOMMEND_FAILED_INVALID_LOCATION = -3;
+    public static final int RECOMMEND_FAILED_ALREADY_EXISTS = -4;
     private static final boolean localLOGV = true;
     private static final String TAG = "PackageHelper";
 
diff --git a/core/jni/android/graphics/Graphics.cpp b/core/jni/android/graphics/Graphics.cpp
index 01aad93..5659ba2 100644
--- a/core/jni/android/graphics/Graphics.cpp
+++ b/core/jni/android/graphics/Graphics.cpp
@@ -1,3 +1,5 @@
+#define LOG_TAG "GraphicsJNI"
+
 #include "jni.h"
 #include "GraphicsJNI.h"
 #include "NIOBuffer.h"
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png b/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png
new file mode 100644
index 0000000..e43fbae
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_general.png b/core/res/res/drawable-hdpi/stat_sys_tether_general.png
new file mode 100644
index 0000000..e43fbae
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_general.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_usb.png b/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
old mode 100755
new mode 100644
index 4c14c07..c6c533d
--- a/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
new file mode 100644
index 0000000..9fcadef
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png b/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png
new file mode 100644
index 0000000..efb64ad
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_general.png b/core/res/res/drawable-mdpi/stat_sys_tether_general.png
new file mode 100644
index 0000000..efb64ad
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_general.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_usb.png b/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
index 2d0da4c..73f1a81 100644
--- a/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png b/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png
new file mode 100644
index 0000000..d448491
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png
Binary files differ
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index e68f214..3fb9607 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -2251,4 +2251,8 @@
     <string name="car_mode_disable_notification_title">Car mode enabled</string>
     <string name="car_mode_disable_notification_message">Select to exit car mode.</string>
 
+    <!-- Strings for tethered notification -->
+    <!-- Shown when the device is tethered -->
+    <string name="tethered_notification_title">Tethering active</string>
+    <string name="tethered_notification_message">Touch to configure</string>
 </resources>
diff --git a/libs/audioflinger/AudioPolicyManagerBase.cpp b/libs/audioflinger/AudioPolicyManagerBase.cpp
index cfcc3ea..2b0a6c8 100644
--- a/libs/audioflinger/AudioPolicyManagerBase.cpp
+++ b/libs/audioflinger/AudioPolicyManagerBase.cpp
@@ -344,6 +344,7 @@
 {
     LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
 
+    bool forceVolumeReeval = false;
     switch(usage) {
     case AudioSystem::FOR_COMMUNICATION:
         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
@@ -374,6 +375,7 @@
             config != AudioSystem::FORCE_BT_DESK_DOCK && config != AudioSystem::FORCE_WIRED_ACCESSORY) {
             LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
         }
+        forceVolumeReeval = true;
         mForceUse[usage] = config;
         break;
     default:
@@ -388,6 +390,9 @@
 #endif
     updateDeviceForStrategy();
     setOutputDevice(mHardwareOutput, newDevice);
+    if (forceVolumeReeval) {
+        applyStreamVolumes(mHardwareOutput, newDevice);
+    }
 }
 
 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index b0a179f..4fa3327 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -1132,41 +1132,31 @@
     }
 
     /**
-     * TODO unhide for SDK
      * Used to indicate a loss of audio focus of unknown duration.
      * @see OnAudioFocusChangeListener#onAudioFocusChanged(int)
-     * {@hide}
      */
     public static final int AUDIOFOCUS_LOSS = -1;
     /**
-     * TODO unhide for SDK
      * Used to indicate a transient loss of audio focus.
      * @see OnAudioFocusChangeListener#onAudioFocusChanged(int)
-     * {@hide}
      */
     public static final int AUDIOFOCUS_LOSS_TRANSIENT = -2;
     /**
-     * TODO unhide for SDK
      * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
      * @see OnAudioFocusChangeListener#onAudioFocusChanged(int)
      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
-     * {@hide}
      */
     public static final int AUDIOFOCUS_GAIN = 1;
     /**
-     * TODO unhide for SDK
      * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
      * amount of time. Examples of temporary changes are the playback of driving directions, or an
      * event notification.
      * @see OnAudioFocusChangeListener#onAudioFocusChanged(int)
      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
-     * {@hide}
      */
     public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
 
     /**
-     * TODO unhide for SDK
-     * {@hide}
      * Interface definition for a callback to be invoked when the audio focus of the system is
      * updated.
      */
@@ -1267,8 +1257,6 @@
     }
 
     /**
-     * TODO unhide for SDK
-     * {@hide}
      * Register a listener for audio focus updates.
      */
     public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
@@ -1284,9 +1272,7 @@
     }
 
     /**
-     * TODO unhide for SDK
      * TODO document for SDK
-     * {@hide}
      */
     public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
         // notify service to remove it from audio focus stack
@@ -1304,22 +1290,16 @@
 
 
     /**
-     * TODO unhide for SDK
      * TODO document for SDK
-     * {@hide}
      */
     public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
     /**
-     * TODO unhide for SDK
      * TODO document for SDK
-     * {@hide}
      */
     public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
 
 
     /**
-     *  TODO unhide for SDK
-     *  {@hide}
      *  Request audio focus.
      *  Send a request to obtain the audio focus for a specific stream type
      *  @param l the listener to be notified of audio focus changes
@@ -1347,9 +1327,7 @@
 
 
     /**
-     *  TODO unhide for SDK
      *  TODO document for SDK
-     *  {@hide}
      *  Abandon audio focus.
      *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
      */
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index e586869..618f239 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -113,9 +113,6 @@
     private Object mSettingsLock = new Object();
     private boolean mMediaServerOk;
 
-    /** cached value of the BT dock address to recognize undocking events */
-    private static String sBtDockAddress = "";
-
     private SoundPool mSoundPool;
     private Object mSoundEffectsLock = new Object();
     private static final int NUM_SOUNDPOOL_CHANNELS = 4;
@@ -269,6 +266,7 @@
                 new IntentFilter(Intent.ACTION_HEADSET_PLUG);
         intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
         intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED);
+        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
         context.registerReceiver(mReceiver, intentFilter);
 
     }
@@ -1498,7 +1496,23 @@
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
 
-            if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
+            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
+                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
+                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
+                int config;
+                switch (dockState) {
+                    case Intent.EXTRA_DOCK_STATE_DESK:
+                        config = AudioSystem.FORCE_BT_DESK_DOCK;
+                        break;
+                    case Intent.EXTRA_DOCK_STATE_CAR:
+                        config = AudioSystem.FORCE_BT_CAR_DOCK;
+                        break;
+                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
+                    default:
+                        config = AudioSystem.FORCE_NONE;
+                }
+                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
+            } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
                 int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE,
                                                BluetoothA2dp.STATE_DISCONNECTED);
                 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
@@ -1508,10 +1522,6 @@
 
                 if (isConnected &&
                     state != BluetoothA2dp.STATE_CONNECTED && state != BluetoothA2dp.STATE_PLAYING) {
-                    if (address.equals(sBtDockAddress)) {
-                        Log.v(TAG, "Recognized undocking from BT dock");
-                        AudioSystem.setForceUse(AudioSystem.FOR_DOCK, AudioSystem.FORCE_NONE);
-                    }
                     AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
                             address);
@@ -1519,27 +1529,6 @@
                 } else if (!isConnected &&
                              (state == BluetoothA2dp.STATE_CONNECTED ||
                               state == BluetoothA2dp.STATE_PLAYING)) {
-                    if (btDevice.isBluetoothDock()) {
-                        Log.v(TAG, "Recognized connection to BT dock");
-                        sBtDockAddress = address;
-                        Intent i = context.registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT));
-                        if (i != null) {
-                            int dockState = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED);
-                            int config;
-                            switch (dockState) {
-                                case Intent.EXTRA_DOCK_STATE_DESK:
-                                    config = AudioSystem.FORCE_BT_DESK_DOCK;
-                                    break;
-                                case Intent.EXTRA_DOCK_STATE_CAR:
-                                    config = AudioSystem.FORCE_BT_CAR_DOCK;
-                                    break;
-                                case Intent.EXTRA_DOCK_STATE_UNDOCKED:
-                                default:
-                                    config = AudioSystem.FORCE_NONE;
-                            }
-                            AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
-                        }
-                    }
                     AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
                                                          AudioSystem.DEVICE_STATE_AVAILABLE,
                                                          address);
diff --git a/media/libstagefright/HTTPDataSource.cpp b/media/libstagefright/HTTPDataSource.cpp
index bf020e9..d79c1bd 100644
--- a/media/libstagefright/HTTPDataSource.cpp
+++ b/media/libstagefright/HTTPDataSource.cpp
@@ -23,13 +23,12 @@
 
 #include <stdlib.h>
 
+#include <cutils/properties.h>
 #include <media/stagefright/HTTPDataSource.h>
 #include <media/stagefright/MediaDebug.h>
 
 namespace android {
 
-static const char *kUserAgent = "stagefright-http";
-
 // Given a connected HTTPStream, determine if the given path redirects
 // somewhere else, if so, disconnect the stream, update host path and port
 // accordingly and return true, otherwise return false and leave the stream
@@ -341,9 +340,16 @@
         const KeyedVector<String8, String8> *overrides) {
     mHeaders = String8();
 
-    mHeaders.append("User-Agent: ");
-    mHeaders.append(kUserAgent);
-    mHeaders.append("\r\n");
+    mHeaders.append("User-Agent: stagefright/1.0 (Linux;Android ");
+
+#if (PROPERTY_VALUE_MAX < 8)
+#error "PROPERTY_VALUE_MAX must be at least 8"
+#endif
+
+    char value[PROPERTY_VALUE_MAX];
+    property_get("ro.build.version.release", value, "Unknown");
+    mHeaders.append(value);
+    mHeaders.append(")\r\n");
 
     if (overrides == NULL) {
         return;
diff --git a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
index 02e1f07..4635f48 100644
--- a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
+++ b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
@@ -5,6 +5,7 @@
 import android.content.Intent;
 import android.content.pm.IPackageManager;
 import android.content.pm.PackageInfo;
+import android.content.pm.PackageInfoLite;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageParser;
 import android.content.pm.PackageParser.Package;
@@ -28,6 +29,7 @@
 import java.io.InputStream;
 
 import android.os.FileUtils;
+import android.os.storage.IMountService;
 import android.provider.Settings;
 
 /*
@@ -86,46 +88,51 @@
          * specified by file uri location.
          * @param fileUri the uri of resource to be copied. Should be a
          * file uri
-         * @return Returns
-         *  PackageHelper.RECOMMEND_INSTALL_INTERNAL to install on internal storage
-         *  PackageHelper.RECOMMEND_INSTALL_EXTERNAL to install on external media
-         *  PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE for storage errors
-         *  PackageHelper.RECOMMEND_FAILED_INVALID_APK for parse errors.
+         * @return Returns PackageInfoLite object containing
+         * the package info and recommended app location.
          */
-        public int getRecommendedInstallLocation(final Uri fileUri) {
+        public PackageInfoLite getMinimalPackageInfo(final Uri fileUri) {
+            PackageInfoLite ret = new PackageInfoLite();
             if (fileUri == null) {
                 Log.i(TAG, "Invalid package uri " + fileUri);
-                return PackageHelper.RECOMMEND_FAILED_INVALID_APK;
+                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
+                return ret;
             }
             String scheme = fileUri.getScheme();
             if (scheme != null && !scheme.equals("file")) {
                 Log.w(TAG, "Falling back to installing on internal storage only");
-                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                return ret;
             }
             String archiveFilePath = fileUri.getPath();
             PackageParser packageParser = new PackageParser(archiveFilePath);
             File sourceFile = new File(archiveFilePath);
             DisplayMetrics metrics = new DisplayMetrics();
             metrics.setToDefaults();
-            PackageParser.Package pkg = packageParser.parsePackage(sourceFile,
-                    archiveFilePath, metrics, 0);
+            PackageParser.PackageLite pkg = packageParser.parsePackageLite(
+                    archiveFilePath, 0);
+            ret.packageName = pkg.packageName;
+            ret.installLocation = pkg.installLocation;
             // Nuke the parser reference right away and force a gc
             Runtime.getRuntime().gc();
             packageParser = null;
             if (pkg == null) {
                 Log.w(TAG, "Failed to parse package");
-                return PackageHelper.RECOMMEND_FAILED_INVALID_APK;
+                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
+                return ret;
             }
-            int loc = recommendAppInstallLocation(pkg);
+            ret.packageName = pkg.packageName;
+            int loc = recommendAppInstallLocation(pkg.installLocation, archiveFilePath);
             if (loc == PackageManager.INSTALL_EXTERNAL) {
-                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
+                ret.recommendedInstallLocation =  PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
             } else if (loc == ERR_LOC) {
                 Log.i(TAG, "Failed to install insufficient storage");
-                return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
+                ret.recommendedInstallLocation =  PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
             } else {
                 // Implies install on internal storage.
-                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                ret.recommendedInstallLocation =  PackageHelper.RECOMMEND_INSTALL_INTERNAL;
             }
+            return ret;
         }
     };
 
@@ -171,62 +178,37 @@
         String codePath = packageURI.getPath();
         File codeFile = new File(codePath);
         String newCachePath = null;
-        final int CREATE_FAILED = 1;
-        final int COPY_FAILED = 2;
-        final int FINALIZE_FAILED = 3;
-        final int PASS = 4;
-        int errCode = CREATE_FAILED;
         // Create new container
         if ((newCachePath = PackageHelper.createSdDir(codeFile,
-                newCid, key, Process.myUid())) != null) {
-            if (localLOGV) Log.i(TAG, "Created container for " + newCid
-                    + " at path : " + newCachePath);
-            File resFile = new File(newCachePath, resFileName);
-            errCode = COPY_FAILED;
-            // Copy file from codePath
-            if (FileUtils.copyFile(new File(codePath), resFile)) {
-                if (localLOGV) Log.i(TAG, "Copied " + codePath + " to " + resFile);
-                errCode = FINALIZE_FAILED;
-                if (PackageHelper.finalizeSdDir(newCid)) {
-                    if (localLOGV) Log.i(TAG, "Finalized container " + newCid);
-                    errCode = PASS;
-                }
-            }
-        }
-        // Print error based on errCode
-        String errMsg = "";
-        switch (errCode) {
-            case CREATE_FAILED:
-                errMsg = "CREATE_FAILED";
-                break;
-            case COPY_FAILED:
-                errMsg = "COPY_FAILED";
-                if (localLOGV) Log.i(TAG, "Destroying " + newCid +
-                        " at path " + newCachePath + " after " + errMsg);
-                PackageHelper.destroySdDir(newCid);
-                break;
-            case FINALIZE_FAILED:
-                errMsg = "FINALIZE_FAILED";
-                if (localLOGV) Log.i(TAG, "Destroying " + newCid +
-                        " at path " + newCachePath + " after " + errMsg);
-                PackageHelper.destroySdDir(newCid);
-                break;
-            default:
-                errMsg = "PASS";
-                if (PackageHelper.isContainerMounted(newCid)) {
-                    if (localLOGV) Log.i(TAG, "Unmounting " + newCid +
-                            " at path " + newCachePath + " after " + errMsg);
-                    // Force a gc to avoid being killed.
-                    Runtime.getRuntime().gc();
-                    PackageHelper.unMountSdDir(newCid);
-                } else {
-                    if (localLOGV) Log.i(TAG, "Container " + newCid + " not mounted");
-                }
-                break;
-        }
-        if (errCode != PASS) {
+                newCid, key, Process.myUid())) == null) {
+            Log.e(TAG, "Failed to create container " + newCid);
             return null;
         }
+        if (localLOGV) Log.i(TAG, "Created container for " + newCid
+                + " at path : " + newCachePath);
+        File resFile = new File(newCachePath, resFileName);
+        if (!FileUtils.copyFile(new File(codePath), resFile)) {
+            Log.e(TAG, "Failed to copy " + codePath + " to " + resFile);
+            // Clean up container
+            PackageHelper.destroySdDir(newCid);
+            return null;
+        }
+        if (localLOGV) Log.i(TAG, "Copied " + codePath + " to " + resFile);
+        if (!PackageHelper.finalizeSdDir(newCid)) {
+            Log.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
+            // Clean up container
+            PackageHelper.destroySdDir(newCid);
+        }
+        if (localLOGV) Log.i(TAG, "Finalized container " + newCid);
+        if (PackageHelper.isContainerMounted(newCid)) {
+            if (localLOGV) Log.i(TAG, "Unmounting " + newCid +
+                    " at path " + newCachePath);
+            // Force a gc to avoid being killed.
+            Runtime.getRuntime().gc();
+            PackageHelper.unMountSdDir(newCid);
+        } else {
+            if (localLOGV) Log.i(TAG, "Container " + newCid + " not mounted");
+        }
         return newCachePath;
     }
 
@@ -307,29 +289,28 @@
     private static final long INSTALL_ON_SD_THRESHOLD = (1024 * 1024);
     private static final int ERR_LOC = -1;
 
-    public int recommendAppInstallLocation(Package pkg) {
+    private int recommendAppInstallLocation(int installLocation,
+            String archiveFilePath) {
         // Initial implementation:
         // Package size = code size + cache size + data size
         // If code size > 1 MB, install on SD card.
         // Else install on internal NAND flash, unless space on NAND is less than 10%
-
-        if (pkg == null) {
-            return ERR_LOC;
+        String status = Environment.getExternalStorageState();
+        long availSDSize = -1;
+        if (status.equals(Environment.MEDIA_MOUNTED)) {
+            StatFs sdStats = new StatFs(
+                    Environment.getExternalStorageDirectory().getPath());
+            availSDSize = (long)sdStats.getAvailableBlocks() *
+                    (long)sdStats.getBlockSize();
         }
+        StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
+        long totalInternalSize = (long)internalStats.getBlockCount() *
+                (long)internalStats.getBlockSize();
+        long availInternalSize = (long)internalStats.getAvailableBlocks() *
+                (long)internalStats.getBlockSize();
 
-        StatFs internalFlashStats = new StatFs(Environment.getDataDirectory().getPath());
-        StatFs sdcardStats = new StatFs(Environment.getExternalStorageDirectory().getPath());
+        double pctNandFree = (double)availInternalSize / (double)totalInternalSize;
 
-        long totalInternalFlashSize = (long)internalFlashStats.getBlockCount() *
-                (long)internalFlashStats.getBlockSize();
-        long availInternalFlashSize = (long)internalFlashStats.getAvailableBlocks() *
-                (long)internalFlashStats.getBlockSize();
-        long availSDSize = (long)sdcardStats.getAvailableBlocks() *
-                (long)sdcardStats.getBlockSize();
-
-        double pctNandFree = (double)availInternalFlashSize / (double)totalInternalFlashSize;
-
-        final String archiveFilePath = pkg.mScanPath;
         File apkFile = new File(archiveFilePath);
         long pkgLen = apkFile.length();
 
@@ -339,15 +320,15 @@
         // For dex files. Just ignore and fail when extracting. Max limit of 2Gig for now.
         long reqInternalSize = 0;
         boolean intThresholdOk = (pctNandFree >= LOW_NAND_FLASH_TRESHOLD);
-        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalFlashSize);
+        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalSize);
         boolean fitsOnSd = (reqInstallSize < availSDSize) && intThresholdOk &&
-                (reqInternalSize < availInternalFlashSize);
+                (reqInternalSize < availInternalSize);
         boolean fitsOnInt = intThresholdOk && intAvailOk;
 
         // Consider application flags preferences as well...
-        boolean installOnlyOnSd = (pkg.installLocation ==
+        boolean installOnlyOnSd = (installLocation ==
                 PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
-        boolean installOnlyInternal = (pkg.installLocation ==
+        boolean installOnlyInternal = (installLocation ==
                 PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
         if (installOnlyInternal) {
             // If set explicitly in manifest,
diff --git a/packages/TtsService/src/android/tts/TtsService.java b/packages/TtsService/src/android/tts/TtsService.java
index 7f76425..6b7ab3f 100755
--- a/packages/TtsService/src/android/tts/TtsService.java
+++ b/packages/TtsService/src/android/tts/TtsService.java
@@ -38,6 +38,7 @@
 import android.util.Log;
 
 import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -1112,7 +1113,7 @@
      * @param filename
      *            The string that gives the full output filename; it should be
      *            something like "/sdcard/myappsounds/mysound.wav".
-     * @return A boolean that indicates if the synthesis succeeded
+     * @return A boolean that indicates if the synthesis can be started
      */
     private boolean synthesizeToFile(String callingApp, String text, ArrayList<String> params,
             String filename) {
@@ -1125,6 +1126,22 @@
         if (text.length() >= MAX_SPEECH_ITEM_CHAR_LENGTH){
             return false;
         }
+        // Check that the output file can be created
+        try {
+            File tempFile = new File(filename);
+            if (tempFile.exists()) {
+                Log.v("TtsService", "File " + filename + " exists, deleting.");
+                tempFile.delete();
+            }
+            if (!tempFile.createNewFile()) {
+                Log.e("TtsService", "Unable to synthesize to file: can't create " + filename);
+                return false;
+            }
+            tempFile.delete();
+        } catch (IOException e) {
+            Log.e("TtsService", "Can't create " + filename + " due to exception " + e);
+            return false;
+        }
         mSpeechQueue.add(new SpeechItem(callingApp, text, params, SpeechItem.TEXT_TO_FILE, filename));
         if (!mIsSpeaking) {
             processSpeechQueue();
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 1ff0244..371fa37 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -51,6 +51,7 @@
 import android.content.pm.IPackageStatsObserver;
 import android.content.pm.InstrumentationInfo;
 import android.content.pm.PackageInfo;
+import android.content.pm.PackageInfoLite;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageStats;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
@@ -78,12 +79,14 @@
 import android.os.FileObserver;
 import android.os.FileUtils;
 import android.os.Handler;
+import android.os.StatFs;
 import android.os.storage.StorageResultCode;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.SystemProperties;
+import android.provider.Settings;
 import android.security.SystemKeyStore;
 import android.util.*;
 import android.view.Display;
@@ -4568,21 +4571,79 @@
             this.installerPackageName = installerPackageName;
         }
 
+        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
+            String packageName = pkgLite.packageName;
+            int installLocation = pkgLite.installLocation;
+            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
+            synchronized (mPackages) {
+                PackageParser.Package pkg = mPackages.get(packageName);
+                if (pkg != null) {
+                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
+                        // Check for updated system application.
+                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
+                            if (onSd) {
+                                Log.w(TAG, "Cannot install update to system app on sdcard");
+                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
+                            }
+                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                        } else {
+                            // When replacing apps make sure we honour
+                            // the existing app location if not overwritten by other options
+                            boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0;
+                            if (onSd) {
+                                // Install flag overrides everything.
+                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
+                            }
+                            // If current upgrade does not specify install location.
+                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
+                                // Application explicitly specified internal.
+                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
+                                // App explictly prefers external. Let policy decide
+                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
+                                // Prefer previous location
+                                return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
+                                    PackageHelper.RECOMMEND_INSTALL_INTERNAL;
+                            }
+                        }
+                    } else {
+                        // Invalid install. Return error code
+                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
+                    }
+                }
+            }
+            // All the special cases have been taken care of.
+            // Return result based on recommended install location.
+            if (onSd) {
+                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
+            }
+            return pkgLite.recommendedInstallLocation;
+        }
+
         public void handleStartCopy() throws RemoteException {
             int ret = PackageManager.INSTALL_SUCCEEDED;
+            boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
+            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
             // Dont need to invoke getInstallLocation for forward locked apps.
-            if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
-                flags &= ~PackageManager.INSTALL_EXTERNAL;
+            if (fwdLocked && onSd) {
+                Log.w(TAG, "Cannot install fwd locked apps on sdcard");
+                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
             } else {
                 // Remote call to find out default install location
-                int loc = mContainerService.getRecommendedInstallLocation(packageURI);
+                PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI);
+                int loc = installLocationPolicy(pkgLite, flags);
                 // Use install location to create InstallArgs and temporary
                 // install location
-                if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
+                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
+                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
+                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
+                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
+                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
                 } else {
+                    // Override install location with flags
                     if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
                             // Set the flag to install on external media.
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index 78329db..e52cd47 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -54,14 +54,12 @@
  * @hide
  *
  * Timeout
- * TODO - review error states - they currently are dead-ends with no recovery possible
  *
  * TODO - look for parent classes and code sharing
  */
 
 public class Tethering extends INetworkManagementEventObserver.Stub {
 
-    private Notification mTetheringNotification;
     private Context mContext;
     private final String TAG = "Tethering";
 
@@ -92,7 +90,9 @@
     private boolean mUseHiPri;
     private String mUpstreamIfaceName;
 
-    HierarchicalStateMachine mTetherMasterSM;
+    private HierarchicalStateMachine mTetherMasterSM;
+
+    private Notification mTetheredNotification;
 
     public Tethering(Context context) {
         Log.d(TAG, "Tethering starting");
@@ -152,18 +152,11 @@
         Log.d(TAG, "interfaceLinkStatusChanged " + iface + ", " + link);
         boolean found = false;
         boolean usb = false;
-        for (String regex : mTetherableWifiRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                break;
-            }
-        }
-        for (String regex: mTetherableUsbRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                usb = true;
-                break;
-            }
+        if (isWifi(iface)) {
+            found = true;
+        } else if (isUsb(iface)) {
+            found = true;
+            usb = true;
         }
         if (found == false) return;
 
@@ -184,23 +177,31 @@
         }
     }
 
+    private boolean isUsb(String iface) {
+        for (String regex : mTetherableUsbRegexs) {
+            if (iface.matches(regex)) return true;
+        }
+        return false;
+    }
+
+    public boolean isWifi(String iface) {
+        for (String regex : mTetherableWifiRegexs) {
+            if (iface.matches(regex)) return true;
+        }
+        return false;
+    }
+
     public void interfaceAdded(String iface) {
         IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
         INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
         boolean found = false;
         boolean usb = false;
-        for (String regex : mTetherableWifiRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                break;
-            }
+        if (isWifi(iface)) {
+            found = true;
         }
-        for (String regex : mTetherableUsbRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                usb = true;
-                break;
-            }
+        if (isUsb(iface)) {
+            found = true;
+            usb = true;
         }
         if (found == false) {
             Log.d(TAG, iface + " is not a tetherable iface, ignoring");
@@ -293,6 +294,9 @@
         ArrayList<String> activeList = new ArrayList<String>();
         ArrayList<String> erroredList = new ArrayList<String>();
 
+        boolean wifiTethered = false;
+        boolean usbTethered = false;
+
         synchronized (mIfaces) {
             Set ifaces = mIfaces.keySet();
             for (Object iface : ifaces) {
@@ -303,6 +307,11 @@
                     } else if (sm.isAvailable()) {
                         availableList.add((String)iface);
                     } else if (sm.isTethered()) {
+                        if (isUsb((String)iface)) {
+                            usbTethered = true;
+                        } else if (isWifi((String)iface)) {
+                            wifiTethered = true;
+                        }
                         activeList.add((String)iface);
                     }
                 }
@@ -318,6 +327,58 @@
         mContext.sendStickyBroadcast(broadcast);
         Log.d(TAG, "sendTetherStateChangedBroadcast " + availableList.size() + ", " +
                 activeList.size() + ", " + erroredList.size());
+
+        if (usbTethered) {
+            if (wifiTethered) {
+                showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_general);
+            } else {
+                showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_usb);
+            }
+        } else if (wifiTethered) {
+            showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_wifi);
+        } else {
+            clearTetheredNotification();
+        }
+    }
+
+    private void showTetheredNotification(int icon) {
+        NotificationManager notificationManager =
+                (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+        if (notificationManager == null) {
+            return;
+        }
+
+        Intent intent = new Intent();
+        intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
+        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+
+        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
+
+        Resources r = Resources.getSystem();
+        CharSequence title = r.getText(com.android.internal.R.string.tethered_notification_title);
+        CharSequence message = r.getText(com.android.internal.R.string.
+                tethered_notification_message);
+
+        if(mTetheredNotification == null) {
+            mTetheredNotification = new Notification();
+            mTetheredNotification.when = 0;
+        }
+        mTetheredNotification.icon = icon;
+        mTetheredNotification.defaults &= ~Notification.DEFAULT_SOUND;
+        mTetheredNotification.flags = Notification.FLAG_ONGOING_EVENT;
+        mTetheredNotification.tickerText = title;
+        mTetheredNotification.setLatestEventInfo(mContext, title, message, pi);
+
+        notificationManager.notify(mTetheredNotification.icon, mTetheredNotification);
+    }
+
+    private void clearTetheredNotification() {
+        NotificationManager notificationManager =
+            (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+        if (notificationManager != null && mTetheredNotification != null) {
+            notificationManager.cancel(mTetheredNotification.icon);
+            mTetheredNotification = null;
+        }
     }
 
     private class StateReceiver extends BroadcastReceiver {
@@ -367,13 +428,11 @@
             return;
         }
         for (String iface : ifaces) {
-            for (String regex : mTetherableUsbRegexs) {
-                if (iface.matches(regex)) {
-                    if (enable) {
-                        interfaceAdded(iface);
-                    } else {
-                        interfaceRemoved(iface);
-                    }
+            if (isUsb(iface)) {
+                if (enable) {
+                    interfaceAdded(iface);
+                } else {
+                    interfaceRemoved(iface);
                 }
             }
         }
@@ -420,27 +479,25 @@
             return false;
         }
         for (String iface : ifaces) {
-            for (String regex : mTetherableUsbRegexs) {
-                if (iface.matches(regex)) {
-                    InterfaceConfiguration ifcg = null;
-                    try {
-                        ifcg = service.getInterfaceConfig(iface);
-                        if (ifcg != null) {
-                            ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
-                            ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
-                            if (enabled) {
-                                ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
-                            } else {
-                                ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
-                            }
-                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("running", "");
-                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("  "," ");
-                            service.setInterfaceConfig(iface, ifcg);
+            if (isUsb(iface)) {
+                InterfaceConfiguration ifcg = null;
+                try {
+                    ifcg = service.getInterfaceConfig(iface);
+                    if (ifcg != null) {
+                        ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
+                        ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
+                        if (enabled) {
+                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
+                        } else {
+                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
                         }
-                    } catch (Exception e) {
-                        Log.e(TAG, "Error configuring interface " + iface + ", :" + e);
-                        return false;
+                        ifcg.interfaceFlags = ifcg.interfaceFlags.replace("running", "");
+                        ifcg.interfaceFlags = ifcg.interfaceFlags.replace("  "," ");
+                        service.setInterfaceConfig(iface, ifcg);
                     }
+                } catch (Exception e) {
+                    Log.e(TAG, "Error configuring interface " + iface + ", :" + e);
+                    return false;
                 }
             }
         }
diff --git a/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java b/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
index 50eca02..0b69020 100755
--- a/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
@@ -932,11 +932,86 @@
                 0, true, false, -1, PackageInfo.INSTALL_LOCATION_AUTO);
     }
 
+    public void testManifestInstallLocationFwdLockedFlagSdcard() {
+        installFromRawResource("install.apk", R.raw.install_loc_unspecified,
+                PackageManager.INSTALL_FORWARD_LOCK |
+                PackageManager.INSTALL_EXTERNAL, true, true,
+                PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION,
+                PackageInfo.INSTALL_LOCATION_AUTO);
+    }
+
     public void testManifestInstallLocationFwdLockedSdcard() {
         installFromRawResource("install.apk", R.raw.install_loc_sdcard,
                 PackageManager.INSTALL_FORWARD_LOCK, true, false,
                 -1,
-                PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
+                PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
+    }
+
+    private void replaceManifestLocation(int iFlags, int rFlags) {
+        InstallParams ip = sampleInstallFromRawResource(iFlags, false);
+        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
+        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
+        try {
+            assertEquals(invokeInstallPackage(ip.packageURI, replaceFlags,
+                    ip.pkg.packageName, receiver), true);
+            assertInstall(ip.pkg, replaceFlags, ip.pkg.installLocation);
+        } catch (Exception e) {
+            failStr("Failed with exception : " + e);
+        } finally {
+            cleanUpInstall(ip);
+        }
+    }
+
+    public void testReplaceFlagInternalSdcard() {
+        replaceManifestLocation(0, PackageManager.INSTALL_EXTERNAL);
+    }
+
+    public void testReplaceFlagSdcardInternal() {
+        replaceManifestLocation(PackageManager.INSTALL_EXTERNAL, 0);
+    }
+
+    public void testManifestInstallLocationReplaceInternalSdcard() {
+        int iFlags = 0;
+        int iApk = R.raw.install_loc_unspecified;
+        int rFlags = 0;
+        int rApk = R.raw.install_loc_sdcard;
+        InstallParams ip = installFromRawResource("install.apk", iApk,
+                iFlags, false,
+                false, -1, PackageInfo.INSTALL_LOCATION_AUTO);
+        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
+        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
+        try {
+            InstallParams rp = installFromRawResource("install.apk", rApk,
+                    rFlags, false,
+                    false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
+            assertInstall(rp.pkg, replaceFlags, rp.pkg.installLocation);
+        } catch (Exception e) {
+            failStr("Failed with exception : " + e);
+        } finally {
+            cleanUpInstall(ip);
+        }
+    }
+
+    public void testManifestInstallLocationReplaceSdcardInternal() {
+        int iFlags = 0;
+        int iApk = R.raw.install_loc_sdcard;
+        int rFlags = 0;
+        int rApk = R.raw.install_loc_unspecified;
+        InstallParams ip = installFromRawResource("install.apk", iApk,
+                iFlags, false,
+                false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
+        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
+        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
+        try {
+            InstallParams rp = installFromRawResource("install.apk", rApk,
+                    rFlags, false,
+                    false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
+            assertInstall(rp.pkg, replaceFlags, ip.pkg.installLocation);
+        } catch (Exception e) {
+            failStr("Failed with exception : " + e);
+        } finally {
+            cleanUpInstall(ip);
+        }
     }
 
     public void xxxtestClearAllSecureContainers() {
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
index d9ec3fa..ac6933fc 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
@@ -38,15 +38,15 @@
 import java.io.OutputStream;
 import java.util.Vector;
 
-//TestRecorder creates two files, one for passing tests
-//and another for failing tests and writes the paths to
-//layout tests one line at a time. TestRecorder does not
-//have ability to clear the results.
+// TestRecorder creates three files ...
+// - passing tests
+// - failing tests
+// - tests with no text results available
+// TestRecorder does not have the ability to clear the results.
 class MyTestRecorder {
     private BufferedOutputStream mBufferedOutputPassedStream;
     private BufferedOutputStream mBufferedOutputFailedStream;
-    private BufferedOutputStream mBufferedOutputNoresultStream;
-    private BufferedOutputStream mBufferedOutputTimedoutStream;
+    private BufferedOutputStream mBufferedOutputNoResultStream;
 
     public void passed(String layout_file) {
         try {
@@ -68,41 +68,28 @@
         }
     }
 
-    public void noresult(String layout_file) {
+    public void noResult(String layout_file) {
         try {
-            mBufferedOutputNoresultStream.write(layout_file.getBytes());
-            mBufferedOutputNoresultStream.write('\n');
-            mBufferedOutputNoresultStream.flush();
+            mBufferedOutputNoResultStream.write(layout_file.getBytes());
+            mBufferedOutputNoResultStream.write('\n');
+            mBufferedOutputNoResultStream.flush();
         } catch(Exception e) {
             e.printStackTrace();
         }
     }
 
-    public void timedout(String url) {
-        try {
-            mBufferedOutputTimedoutStream.write(url.getBytes());
-            mBufferedOutputTimedoutStream.write('\n');
-            mBufferedOutputTimedoutStream.flush();
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
     public MyTestRecorder(boolean resume) {
         try {
             File resultsPassedFile = new File("/sdcard/layout_tests_passed.txt");
             File resultsFailedFile = new File("/sdcard/layout_tests_failed.txt");
             File noExpectedResultFile = new File("/sdcard/layout_tests_nontext.txt");
-            File resultTimedoutFile = new File("/sdcard/layout_tests_timedout.txt");
 
             mBufferedOutputPassedStream =
                 new BufferedOutputStream(new FileOutputStream(resultsPassedFile, resume));
             mBufferedOutputFailedStream =
                 new BufferedOutputStream(new FileOutputStream(resultsFailedFile, resume));
-            mBufferedOutputNoresultStream =
+            mBufferedOutputNoResultStream =
                 new BufferedOutputStream(new FileOutputStream(noExpectedResultFile, resume));
-            mBufferedOutputTimedoutStream =
-                new BufferedOutputStream(new FileOutputStream(resultTimedoutFile, resume));
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -112,8 +99,7 @@
         try {
             mBufferedOutputPassedStream.close();
             mBufferedOutputFailedStream.close();
-            mBufferedOutputNoresultStream.close();
-            mBufferedOutputTimedoutStream.close();
+            mBufferedOutputNoResultStream.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -250,9 +236,9 @@
         mResultRecorder.passed(file);
     }
 
-    private void noresultCase(String file) {
+    private void noResultCase(String file) {
         Log.v("Layout test:", file + " no expected result");
-        mResultRecorder.noresult(file);
+        mResultRecorder.noResult(file);
     }
 
     private void processResult(String testFile, String actualResultFile, String expectedResultFile) {
@@ -276,7 +262,7 @@
         }
 
         if (!expected.exists()) {
-            noresultCase(testFile);
+            noResultCase(testFile);
         }
     }