Merge "Add an API to set the link timeout."
diff --git a/Android.mk b/Android.mk
index 35ee3fd..95f38c5 100644
--- a/Android.mk
+++ b/Android.mk
@@ -120,6 +120,7 @@
 	core/java/android/os/IMessenger.aidl \
 	core/java/android/os/storage/IMountService.aidl \
 	core/java/android/os/storage/IMountServiceListener.aidl \
+	core/java/android/os/storage/IMountShutdownObserver.aidl \
 	core/java/android/os/INetworkManagementService.aidl \
 	core/java/android/os/INetStatService.aidl \
 	core/java/android/os/IPermissionController.aidl \
diff --git a/CleanSpec.mk b/CleanSpec.mk
index b6b8640..de0fd2f 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -1,6 +1,55 @@
+# Copyright (C) 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.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list.  These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+#     $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+#     $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list.  E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/com/android/internal/os/IDropBoxService.java)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/backup)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/com/android/internal/backup)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/backup)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/com/android/internal/backup)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/app)
+
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
diff --git a/api/current.xml b/api/current.xml
index 4146859..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"
@@ -45353,6 +45430,28 @@
  visibility="public"
 >
 </field>
+<field name="FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.touchscreen.multitouch.distinct&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_WIFI"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.wifi&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="GET_ACTIVITIES"
  type="int"
  transient="false"
@@ -71464,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"
@@ -71610,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"
@@ -80163,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"
@@ -80404,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"
@@ -80611,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"
@@ -80655,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"
@@ -81184,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"
@@ -114301,6 +114569,23 @@
 <exception name="IOException" type="java.io.IOException">
 </exception>
 </method>
+<method name="dumpService"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="name" type="java.lang.String">
+</parameter>
+<parameter name="fd" type="java.io.FileDescriptor">
+</parameter>
+<parameter name="args" type="java.lang.String[]">
+</parameter>
+</method>
 <method name="enableEmulatorTraceOutput"
  return="void"
  abstract="false"
@@ -135531,6 +135816,39 @@
  visibility="public"
 >
 </field>
+<field name="LOCK_PATTERN_ENABLED"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;lock_pattern_autolock&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;lock_pattern_tactile_feedback_enabled&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="LOCK_PATTERN_VISIBLE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;lock_pattern_visible_pattern&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="LOGGING_ID"
  type="java.lang.String"
  transient="false"
@@ -136508,7 +136826,7 @@
  value="&quot;lock_pattern_autolock&quot;"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -136519,7 +136837,7 @@
  value="&quot;lock_pattern_tactile_feedback_enabled&quot;"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -136530,7 +136848,7 @@
  value="&quot;lock_pattern_visible_pattern&quot;"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -193132,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"
@@ -193711,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/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c
index eaa34c8..cc1167f 100644
--- a/cmds/dumpstate/dumpstate.c
+++ b/cmds/dumpstate/dumpstate.c
@@ -23,6 +23,7 @@
 #include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/time.h>
+#include <sys/wait.h>
 #include <unistd.h>
 
 #include <cutils/properties.h>
@@ -86,7 +87,11 @@
     struct stat st;
     char anr_traces_path[PATH_MAX];
     property_get("dalvik.vm.stack-trace-file", anr_traces_path, "");
-    if (anr_traces_path[0] && !stat(anr_traces_path, &st) && time(NULL) - st.st_mtime < 15 * 60) {
+    if (!anr_traces_path[0]) {
+        printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
+    } else if (stat(anr_traces_path, &st)) {
+        printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno));
+    } else {
         dump_file("VM TRACES AT LAST ANR", anr_traces_path);
     }
 
diff --git a/cmds/dumpstate/utils.c b/cmds/dumpstate/utils.c
index 6a79c6d..c21dace 100644
--- a/cmds/dumpstate/utils.c
+++ b/cmds/dumpstate/utils.c
@@ -33,6 +33,7 @@
 
 #include <cutils/properties.h>
 #include <cutils/sockets.h>
+#include <private/android_filesystem_config.h>
 
 #include "dumpstate.h"
 
@@ -273,6 +274,20 @@
         return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
     }
 
+    /* make the directory if necessary */
+    char anr_traces_dir[PATH_MAX];
+    strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
+    char *slash = strrchr(anr_traces_dir, '/');
+    if (slash != NULL) {
+        *slash = '\0';
+        if (!mkdir(anr_traces_dir, 0775)) {
+            chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
+        } else if (errno != EEXIST) {
+            fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
+            return NULL;
+        }
+    }
+
     /* create a new, empty traces.txt file to receive stack dumps */
     int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC, 0666);  /* -rw-rw-rw- */
     if (fd < 0) {
@@ -302,6 +317,7 @@
     }
 
     struct dirent *d;
+    int dalvik_found = 0;
     while ((d = readdir(proc))) {
         int pid = atoi(d->d_name);
         if (pid <= 0) continue;
@@ -319,6 +335,7 @@
         close(fd);
         if (len <= 0 || !memcmp(data, "zygote", 6)) continue;
 
+        ++dalvik_found;
         if (kill(pid, SIGQUIT)) {
             fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
             continue;
@@ -338,6 +355,9 @@
     }
 
     close(ifd);
+    if (dalvik_found == 0) {
+        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
+    }
 
     static char dump_traces_path[PATH_MAX];
     strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
diff --git a/cmds/keystore/keystore.c b/cmds/keystore/keystore.c
index 4426874..60cc521 100644
--- a/cmds/keystore/keystore.c
+++ b/cmds/keystore/keystore.c
@@ -46,7 +46,7 @@
  * user-defined password. To keep things simple, buffers are always larger than
  * the maximum space we needed, so boundary checks on buffers are omitted. */
 
-#define KEY_SIZE        120
+#define KEY_SIZE        ((NAME_MAX - 15) / 2)
 #define VALUE_SIZE      32768
 #define PASSWORD_SIZE   VALUE_SIZE
 
@@ -442,10 +442,11 @@
     uid_t euid;
     uint32_t perms;
 } users[] = {
-    {AID_SYSTEM,   0,          ~GET},
+    {AID_SYSTEM,   ~0,         ~GET},
     {AID_VPN,      AID_SYSTEM, GET},
     {AID_WIFI,     AID_SYSTEM, GET},
-    {0,            0,          TEST | GET | INSERT | DELETE | EXIST | SAW},
+    {AID_ROOT,     AID_SYSTEM, GET},
+    {~0,           ~0,         TEST | GET | INSERT | DELETE | EXIST | SAW},
 };
 
 static int8_t process(int8_t code) {
@@ -453,7 +454,7 @@
     struct action *action = actions;
     int i;
 
-    while (user->uid && user->uid != uid) {
+    while (~user->uid && user->uid != uid) {
         ++user;
     }
     while (action->code && action->code != code) {
@@ -468,7 +469,7 @@
     if (action->state && action->state != state) {
         return state;
     }
-    if (user->euid) {
+    if (~user->euid) {
         uid = user->euid;
     }
     for (i = 0; i < MAX_PARAM && action->lengths[i]; ++i) {
diff --git a/cmds/servicemanager/Android.mk b/cmds/servicemanager/Android.mk
index 25266a2..392e727 100644
--- a/cmds/servicemanager/Android.mk
+++ b/cmds/servicemanager/Android.mk
@@ -10,5 +10,10 @@
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SRC_FILES := service_manager.c binder.c
 LOCAL_MODULE := servicemanager
+ifeq ($(LVMX),true)
+  ifeq ($(TARGET_ARCH),arm)
+    LOCAL_CFLAGS += -DLVMX
+  endif
+endif
 include $(BUILD_EXECUTABLE)
 endif
diff --git a/cmds/servicemanager/service_manager.c b/cmds/servicemanager/service_manager.c
index f3a4713..a2006c1 100644
--- a/cmds/servicemanager/service_manager.c
+++ b/cmds/servicemanager/service_manager.c
@@ -27,6 +27,9 @@
     unsigned uid;
     const char *name;
 } allowed[] = {
+#ifdef LVMX
+    { AID_MEDIA, "com.lifevibes.mx.ipc" },
+#endif
     { AID_MEDIA, "media.audio_flinger" },
     { AID_MEDIA, "media.player" },
     { AID_MEDIA, "media.camera" },
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/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index 81b8055..fdb3d20 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -73,7 +73,10 @@
                 case QUERY_TRANSACTION:
                 {
                     data.enforceInterface(IContentProvider.descriptor);
+
                     Uri url = Uri.CREATOR.createFromParcel(data);
+
+                    // String[] projection
                     int num = data.readInt();
                     String[] projection = null;
                     if (num > 0) {
@@ -82,6 +85,8 @@
                             projection[i] = data.readString();
                         }
                     }
+
+                    // String selection, String[] selectionArgs...
                     String selection = data.readString();
                     num = data.readInt();
                     String[] selectionArgs = null;
@@ -91,19 +96,33 @@
                             selectionArgs[i] = data.readString();
                         }
                     }
+
                     String sortOrder = data.readString();
                     IContentObserver observer = IContentObserver.Stub.
                         asInterface(data.readStrongBinder());
                     CursorWindow window = CursorWindow.CREATOR.createFromParcel(data);
 
+                    // Flag for whether caller wants the number of
+                    // rows in the cursor and the position of the
+                    // "_id" column index (or -1 if non-existent)
+                    // Only to be returned if binder != null.
+                    boolean wantsCursorMetadata = data.readInt() != 0;
+
                     IBulkCursor bulkCursor = bulkQuery(url, projection, selection,
                             selectionArgs, sortOrder, observer, window);
                     reply.writeNoException();
                     if (bulkCursor != null) {
                         reply.writeStrongBinder(bulkCursor.asBinder());
+
+                        if (wantsCursorMetadata) {
+                            reply.writeInt(bulkCursor.count());
+                            reply.writeInt(BulkCursorToCursorAdaptor.findRowIdColumnIndex(
+                                bulkCursor.getColumnNames()));
+                        }
                     } else {
                         reply.writeStrongBinder(null);
                     }
+
                     return true;
                 }
 
@@ -266,9 +285,12 @@
         return mRemote;
     }
 
-    public IBulkCursor bulkQuery(Uri url, String[] projection,
-            String selection, String[] selectionArgs, String sortOrder, IContentObserver observer,
-            CursorWindow window) throws RemoteException {
+    // Like bulkQuery() but sets up provided 'adaptor' if not null.
+    private IBulkCursor bulkQueryInternal(
+        Uri url, String[] projection,
+        String selection, String[] selectionArgs, String sortOrder,
+        IContentObserver observer, CursorWindow window,
+        BulkCursorToCursorAdaptor adaptor) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
 
@@ -297,6 +319,12 @@
         data.writeStrongBinder(observer.asBinder());
         window.writeToParcel(data, 0);
 
+        // Flag for whether or not we want the number of rows in the
+        // cursor and the position of the "_id" column index (or -1 if
+        // non-existent).  Only to be returned if binder != null.
+        final boolean wantsCursorMetadata = (adaptor != null);
+        data.writeInt(wantsCursorMetadata ? 1 : 0);
+
         mRemote.transact(IContentProvider.QUERY_TRANSACTION, data, reply, 0);
 
         DatabaseUtils.readExceptionFromParcel(reply);
@@ -305,26 +333,43 @@
         IBinder bulkCursorBinder = reply.readStrongBinder();
         if (bulkCursorBinder != null) {
             bulkCursor = BulkCursorNative.asInterface(bulkCursorBinder);
+
+            if (wantsCursorMetadata) {
+                int rowCount = reply.readInt();
+                int idColumnPosition = reply.readInt();
+                if (bulkCursor != null) {
+                    adaptor.set(bulkCursor, rowCount, idColumnPosition);
+                }
+            }
         }
-        
+
         data.recycle();
         reply.recycle();
-        
+
         return bulkCursor;
     }
 
+    public IBulkCursor bulkQuery(Uri url, String[] projection,
+            String selection, String[] selectionArgs, String sortOrder, IContentObserver observer,
+            CursorWindow window) throws RemoteException {
+        return bulkQueryInternal(
+            url, projection, selection, selectionArgs, sortOrder,
+            observer, window,
+            null /* BulkCursorToCursorAdaptor */);
+    }
+
     public Cursor query(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) throws RemoteException {
         //TODO make a pool of windows so we can reuse memory dealers
         CursorWindow window = new CursorWindow(false /* window will be used remotely */);
         BulkCursorToCursorAdaptor adaptor = new BulkCursorToCursorAdaptor();
-        IBulkCursor bulkCursor = bulkQuery(url, projection, selection, selectionArgs, sortOrder,
-                adaptor.getObserver(), window);
-
+        IBulkCursor bulkCursor = bulkQueryInternal(
+            url, projection, selection, selectionArgs, sortOrder,
+            adaptor.getObserver(), window,
+            adaptor);
         if (bulkCursor == null) {
             return null;
         }
-        adaptor.set(bulkCursor);
         return adaptor;
     }
 
@@ -515,7 +560,12 @@
         mRemote.transact(IContentProvider.CALL_TRANSACTION, data, reply, 0);
 
         DatabaseUtils.readExceptionFromParcel(reply);
-        return reply.readBundle();
+        Bundle bundle = reply.readBundle();
+
+        data.recycle();
+        reply.recycle();
+
+        return bundle;
     }
 
     private IBinder mRemote;
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/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index dc8f386..efd7bbc 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -602,33 +602,87 @@
 
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device is capable of communicating with
+     * other devices via Bluetooth.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device has a camera facing away
      * from the screen.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_CAMERA = "android.hardware.camera";
-    
+
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device's camera supports auto-focus.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_CAMERA_AUTOFOCUS = "android.hardware.camera.autofocus";
-    
+
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device's camera supports flash.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_CAMERA_FLASH = "android.hardware.camera.flash";
-    
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device supports one or more methods of
+     * reporting current location.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_LOCATION = "android.hardware.location";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device has a Global Positioning System
+     * receiver and can report precise location.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_LOCATION_GPS = "android.hardware.location.gps";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device can report location with coarse
+     * accuracy using a network-based geolocation system.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_LOCATION_NETWORK = "android.hardware.location.network";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device can record audio via a
+     * microphone.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_MICROPHONE = "android.hardware.microphone";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device includes a magnetometer (compass).
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_SENSOR_COMPASS = "android.hardware.sensor.compass";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device includes an accelerometer.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_SENSOR_ACCELEROMETER = "android.hardware.sensor.accelerometer";
+
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device includes a light sensor.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_SENSOR_LIGHT = "android.hardware.sensor.light";
-    
+
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device includes a proximity sensor.
@@ -660,19 +714,35 @@
     
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
-     * {@link #hasSystemFeature}: The device's touch screen supports multitouch.
+     * {@link #hasSystemFeature}: The device's touch screen supports
+     * multitouch sufficient for basic two-finger gesture detection.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_TOUCHSCREEN_MULTITOUCH = "android.hardware.touchscreen.multitouch";
     
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device's touch screen is capable of
+     * tracking two or more fingers fully independently.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT = "android.hardware.touchscreen.multitouch.distinct";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device supports live wallpapers.
      */
     @SdkConstant(SdkConstantType.FEATURE)
     public static final String FEATURE_LIVE_WALLPAPER = "android.software.live_wallpaper";
 
     /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device supports WiFi (802.11) networking.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_WIFI = "android.hardware.wifi";
+
+    /**
      * Action to external storage service to clean out removed apps.
      * @hide
      */
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/BulkCursorToCursorAdaptor.java b/core/java/android/database/BulkCursorToCursorAdaptor.java
index cf30dd9..1469ea2 100644
--- a/core/java/android/database/BulkCursorToCursorAdaptor.java
+++ b/core/java/android/database/BulkCursorToCursorAdaptor.java
@@ -43,25 +43,43 @@
         try {
             mCount = mBulkCursor.count();
             mWantsAllOnMoveCalls = mBulkCursor.getWantsAllOnMoveCalls();
-    
+
             // Search for the rowID column index and set it for our parent
             mColumns = mBulkCursor.getColumnNames();
-            int length = mColumns.length;
-            for (int i = 0; i < length; i++) {
-                if (mColumns[i].equals("_id")) {
-                    mRowIdColumnIndex = i;
-                    break;
-                }
-            }
+            mRowIdColumnIndex = findRowIdColumnIndex(mColumns);
         } catch (RemoteException ex) {
             Log.e(TAG, "Setup failed because the remote process is dead");
         }
     }
 
     /**
+     * Version of set() that does fewer Binder calls if the caller
+     * already knows BulkCursorToCursorAdaptor's properties.
+     */
+    public void set(IBulkCursor bulkCursor, int count, int idIndex) {
+        mBulkCursor = bulkCursor;
+        mColumns = null;  // lazily retrieved
+        mCount = count;
+        mRowIdColumnIndex = idIndex;
+    }
+
+    /**
+     * Returns column index of "_id" column, or -1 if not found.
+     */
+    public static int findRowIdColumnIndex(String[] columnNames) {
+        int length = columnNames.length;
+        for (int i = 0; i < length; i++) {
+            if (columnNames[i].equals("_id")) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
      * Gets a SelfDataChangeOberserver that can be sent to a remote
      * process to receive change notifications over IPC.
-     * 
+     *
      * @return A SelfContentObserver hooked up to this Cursor
      */
     public synchronized IContentObserver getObserver() {
@@ -190,6 +208,14 @@
 
     @Override
     public String[] getColumnNames() {
+        if (mColumns == null) {
+            try {
+                mColumns = mBulkCursor.getColumnNames();
+            } catch (RemoteException ex) {
+                Log.e(TAG, "Unable to fetch column names because the remote process is dead");
+                return null;
+            }
+        }
         return mColumns;
     }
 
@@ -255,4 +281,3 @@
         }
     }
 }
-
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index 99db81b..c756825 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -44,7 +44,7 @@
     /**
      * Returns the starting position of this window within the entire
      * Cursor's result set.
-     * 
+     *
      * @return the starting position of this window within the entire
      * Cursor's result set.
      */
diff --git a/core/java/android/database/IBulkCursor.java b/core/java/android/database/IBulkCursor.java
index 24354fd..46790a3 100644
--- a/core/java/android/database/IBulkCursor.java
+++ b/core/java/android/database/IBulkCursor.java
@@ -27,11 +27,10 @@
  * This interface provides a low-level way to pass bulk cursor data across
  * both process and language boundries. Application code should use the Cursor
  * interface directly.
- * 
+ *
  * {@hide}
  */
-public interface IBulkCursor extends IInterface 
-{
+public interface IBulkCursor extends IInterface  {
     /**
      * Returns a BulkCursorWindow, which either has a reference to a shared
      * memory segment with the rows, or an array of JSON strings.
@@ -60,7 +59,7 @@
     public boolean deleteRow(int position) throws RemoteException;
 
     public void deactivate() throws RemoteException;
-    
+
     public void close() throws RemoteException;
 
     public int requery(IContentObserver observer, CursorWindow window) throws RemoteException;
@@ -87,4 +86,3 @@
     static final int RESPOND_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 10;
     static final int CLOSE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 11;
 }
-
diff --git a/core/java/android/database/sqlite/SQLiteClosable.java b/core/java/android/database/sqlite/SQLiteClosable.java
index e589f34..71fa2c2 100644
--- a/core/java/android/database/sqlite/SQLiteClosable.java
+++ b/core/java/android/database/sqlite/SQLiteClosable.java
@@ -19,14 +19,15 @@
 import android.database.CursorWindow;
 
 /**
- * An object create from a SQLiteDatabase that can be closed.
+ * An object created from a SQLiteDatabase that can be closed.
  */
-public abstract class SQLiteClosable {    
+public abstract class SQLiteClosable {
     private int mReferenceCount = 1;
     private Object mLock = new Object();
+
     protected abstract void onAllReferencesReleased();
-    protected void onAllReferencesReleasedFromContainer(){}
-    
+    protected void onAllReferencesReleasedFromContainer() {}
+
     public void acquireReference() {
         synchronized(mLock) {
             if (mReferenceCount <= 0) {
@@ -36,7 +37,7 @@
             mReferenceCount++;
         }
     }
-    
+
     public void releaseReference() {
         synchronized(mLock) {
             mReferenceCount--;
@@ -45,14 +46,14 @@
             }
         }
     }
-    
+
     public void releaseReferenceFromContainer() {
         synchronized(mLock) {
             mReferenceCount--;
             if (mReferenceCount == 0) {
                 onAllReferencesReleasedFromContainer();
             }
-        }        
+        }
     }
 
     private String getObjInfo() {
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/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index 2974981..dfd4024 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -261,7 +261,7 @@
     public static final int MAX_SQL_CACHE_SIZE = 250;
     private int mMaxSqlCacheSize = MAX_SQL_CACHE_SIZE; // max cache size per Database instance
     private int mCacheFullWarnings;
-    private static final int MAX_WARNINGS_ON_CACHESIZE_CONDITION = 5;
+    private static final int MAX_WARNINGS_ON_CACHESIZE_CONDITION = 1;
 
     /** maintain stats about number of cache hits and misses */
     private int mNumCacheHits;
@@ -1909,43 +1909,28 @@
             }
             // add this <sql, compiledStatement> to the cache
             if (mCompiledQueries.size() == mMaxSqlCacheSize) {
-                /* reached max cachesize. before adding new entry, remove an entry from the
-                 * cache. we don't want to wipe out the entire cache because of this:
-                 * GCing {@link SQLiteCompiledSql} requires call to sqlite3_finalize
-                 * JNI method. If entire cache is wiped out, it could cause a big GC activity
-                 * just because a (rogue) process is using the cache incorrectly.
+                /*
+                 * cache size of {@link #mMaxSqlCacheSize} is not enough for this app.
+                 * log a warning MAX_WARNINGS_ON_CACHESIZE_CONDITION times
+                 * chances are it is NOT using ? for bindargs - so caching is useless.
+                 * TODO: either let the callers set max cchesize for their app, or intelligently
+                 * figure out what should be cached for a given app.
                  */
-                Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
-                        getPath() + "; i.e., NO space for this sql statement in cache: " +
-                        sql + ". Please change your sql statements to use '?' for " +
-                        "bindargs, instead of using actual values");
-                
-                /* increment the number of times this warnings has been printed.
-                 * if this warning is printed too many times, clear the whole cache - the app
-                 * is doing something weird or incorrect and printing more warnings will only
-                 * flood the logfile.
-                 */
-                if (++mCacheFullWarnings > MAX_WARNINGS_ON_CACHESIZE_CONDITION) {
-                    mCacheFullWarnings = 0;
-                    // clear the cache
-                    mCompiledQueries.clear();
-                    Log.w(TAG, "Compiled-sql statement cache for database: " +
-                            getPath() + " hit MAX size-limit too many times. " +
-                            "Removing all compiled-sql statements from the cache.");
-                } else {
-                    // clear just a single entry from cache
-                    Set<String> keySet = mCompiledQueries.keySet();
-                    for (String s : keySet) {
-                        mCompiledQueries.remove(s);
-                        break;
-                    }
+                if (++mCacheFullWarnings == MAX_WARNINGS_ON_CACHESIZE_CONDITION) {
+                    Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
+                            getPath() + "; i.e., NO space for this sql statement in cache: " +
+                            sql + ". Please change your sql statements to use '?' for " +
+                            "bindargs, instead of using actual values");
+                }
+                // don't add this entry to cache
+            } else {
+                // cache is NOT full. add this to cache.
+                mCompiledQueries.put(sql, compiledStatement);
+                if (SQLiteDebug.DEBUG_SQL_CACHE) {
+                    Log.v(TAG, "|adding_sql_to_cache|" + getPath() + "|" +
+                            mCompiledQueries.size() + "|" + sql);
                 }
             }
-            mCompiledQueries.put(sql, compiledStatement);
-        }
-        if (SQLiteDebug.DEBUG_SQL_CACHE) {
-            Log.v(TAG, "|adding_sql_to_cache|" + getPath() + "|" + mCompiledQueries.size() + "|" +
-                    sql);
         }
         return;
     }
diff --git a/core/java/android/database/sqlite/SQLiteProgram.java b/core/java/android/database/sqlite/SQLiteProgram.java
index 389e15e..5b4516d 100644
--- a/core/java/android/database/sqlite/SQLiteProgram.java
+++ b/core/java/android/database/sqlite/SQLiteProgram.java
@@ -58,11 +58,11 @@
         db.addSQLiteClosable(this);
         this.nHandle = db.mNativeHandle;
 
-        // shouldn't reuse compiled-plans of PRAGMA sql statements
-        // because sqlite returns OLD values if compiled-pragma-statements are reused
-        //TODO: remove this code when sqlite fixes it (and add tests too)
+        // only cache CRUD statements
         String prefixSql = mSql.substring(0, 6);
-        if (prefixSql.toLowerCase().startsWith("pragma")) {
+        if (!prefixSql.equalsIgnoreCase("INSERT") && !prefixSql.equalsIgnoreCase("UPDATE") &&
+                !prefixSql.equalsIgnoreCase("REPLAC") &&
+                !prefixSql.equalsIgnoreCase("DELETE") && !prefixSql.equalsIgnoreCase("SELECT")) {
             mCompiledSql = new SQLiteCompiledSql(db, sql);
             nStatement = mCompiledSql.nStatement;
             // since it is not in the cache, no need to acquire() it.
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/net/WebAddress.java b/core/java/android/net/WebAddress.java
index a572f60..e5bc6e3 100644
--- a/core/java/android/net/WebAddress.java
+++ b/core/java/android/net/WebAddress.java
@@ -57,7 +57,7 @@
             /* scheme    */ "(?:(http|HTTP|https|HTTPS|file|FILE)\\:\\/\\/)?" +
             /* authority */ "(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" +
             /* host      */ "([-" + GOOD_IRI_CHAR + "%_]+(?:\\.[-" + GOOD_IRI_CHAR + "%_]+)*|\\[[0-9a-fA-F:\\.]+\\])?" +
-            /* port      */ "(?:\\:([0-9]+))?" +
+            /* port      */ "(?:\\:([0-9]*))?" +
             /* path      */ "(\\/?[^#]*)?" +
             /* anchor    */ ".*");
 
@@ -85,7 +85,8 @@
             t = m.group(MATCH_GROUP_HOST);
             if (t != null) mHost = t;
             t = m.group(MATCH_GROUP_PORT);
-            if (t != null) {
+            if (t != null && t.length() > 0) {
+                // The ':' character is not returned by the regex.
                 try {
                     mPort = Integer.parseInt(t);
                 } catch (NumberFormatException ex) {
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index a4c595d..2e14667 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -57,6 +57,8 @@
  */
 public final class Debug
 {
+    private static final String TAG = "Debug";
+
     /**
      * Flags for startMethodTracing().  These can be ORed together.
      *
@@ -1111,7 +1113,7 @@
                 }
             }
         } else {
-            Log.w("android.os.Debug",
+            Log.wtf(TAG,
                   "setFieldsOn(" + (cl == null ? "null" : cl.getName()) +
                   ") called in non-DEBUG build");
         }
@@ -1127,4 +1129,31 @@
     @Retention(RetentionPolicy.RUNTIME)
     public @interface DebugProperty {
     }
+
+    /**
+     * Get a debugging dump of a system service by name.
+     *
+     * <p>Most services require the caller to hold android.permission.DUMP.
+     *
+     * @param name of the service to dump
+     * @param fd to write dump output to (usually an output log file)
+     * @param args to pass to the service's dump method, may be null
+     * @return true if the service was dumped successfully, false if
+     *     the service could not be found or had an error while dumping
+     */
+    public static boolean dumpService(String name, FileDescriptor fd, String[] args) {
+        IBinder service = ServiceManager.getService(name);
+        if (service == null) {
+            Log.e(TAG, "Can't find service to dump: " + name);
+            return false;
+        }
+
+        try {
+            service.dump(fd, args);
+            return true;
+        } catch (RemoteException e) {
+            Log.e(TAG, "Can't dump service: " + name, e);
+            return false;
+        }
+    }
 }
diff --git a/core/java/android/os/Power.java b/core/java/android/os/Power.java
index b3df522..5a79215 100644
--- a/core/java/android/os/Power.java
+++ b/core/java/android/os/Power.java
@@ -18,7 +18,6 @@
 
 import java.io.IOException;
 import android.os.ServiceManager;
-import android.os.storage.IMountService;
 
 /**
  * Class that provides access to some of the power management functions.
@@ -101,15 +100,6 @@
      */
     public static void reboot(String reason) throws IOException
     {
-        IMountService mSvc = IMountService.Stub.asInterface(
-                ServiceManager.getService("mount"));
-
-        if (mSvc != null) {
-            try {
-                mSvc.shutdown();
-            } catch (Exception e) {
-            }
-        }
         rebootNative(reason);
     }
 
diff --git a/core/java/android/os/storage/IMountService.aidl b/core/java/android/os/storage/IMountService.aidl
index ad4cb10..75455ab 100644
--- a/core/java/android/os/storage/IMountService.aidl
+++ b/core/java/android/os/storage/IMountService.aidl
@@ -18,6 +18,7 @@
 package android.os.storage;
 
 import android.os.storage.IMountServiceListener;
+import android.os.storage.IMountShutdownObserver;
 
 /** WARNING! Update IMountService.h and IMountService.cpp if you change this file.
  * In particular, the ordering of the methods below must match the 
@@ -142,6 +143,7 @@
 
     /**
      * Shuts down the MountService and gracefully unmounts all external media.
+     * Invokes call back once the shutdown is complete.
      */
-    void shutdown();
+    void shutdown(IMountShutdownObserver observer);
 }
diff --git a/core/java/android/os/storage/IMountShutdownObserver.aidl b/core/java/android/os/storage/IMountShutdownObserver.aidl
new file mode 100644
index 0000000..0aa8a45
--- /dev/null
+++ b/core/java/android/os/storage/IMountShutdownObserver.aidl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2009 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.os.storage;
+
+/**
+ * Callback class for receiving events related
+ * to shutdown.
+ *
+ * @hide - For internal consumption only.
+ */
+interface IMountShutdownObserver {
+    /**
+     * This method is called when the shutdown
+     * of MountService completed.
+     * @param statusCode indicates success or failure
+     * of the shutdown.
+     */
+    void onShutDownComplete(int statusCode);
+}
diff --git a/core/java/android/pim/vcard/VCardEntry.java b/core/java/android/pim/vcard/VCardEntry.java
index f6135fc..61012c9 100644
--- a/core/java/android/pim/vcard/VCardEntry.java
+++ b/core/java/android/pim/vcard/VCardEntry.java
@@ -17,6 +17,7 @@
 
 import android.accounts.Account;
 import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
 import android.content.ContentResolver;
 import android.content.OperationApplicationException;
 import android.database.Cursor;
@@ -90,7 +91,7 @@
             this.label = label;
             this.isPrimary = isPrimary;
         }
-        
+
         @Override
         public boolean equals(Object obj) {
             if (!(obj instanceof PhoneData)) {
@@ -100,7 +101,7 @@
             return (type == phoneData.type && data.equals(phoneData.data) &&
                     label.equals(phoneData.label) && isPrimary == phoneData.isPrimary);
         }
-        
+
         @Override
         public String toString() {
             return String.format("type: %d, data: %s, label: %s, isPrimary: %s",
@@ -122,7 +123,7 @@
             this.label = label;
             this.isPrimary = isPrimary;
         }
-        
+
         @Override
         public boolean equals(Object obj) {
             if (!(obj instanceof EmailData)) {
@@ -132,7 +133,7 @@
             return (type == emailData.type && data.equals(emailData.data) &&
                     label.equals(emailData.label) && isPrimary == emailData.isPrimary);
         }
-        
+
         @Override
         public String toString() {
             return String.format("type: %d, data: %s, label: %s, isPrimary: %s",
@@ -193,14 +194,14 @@
             this.label = label;
             this.isPrimary = isPrimary;
         }
-        
+
         @Override
         public boolean equals(Object obj) {
             if (!(obj instanceof PostalData)) {
                 return false;
             }
             final PostalData postalData = (PostalData)obj;
-            return (Arrays.equals(dataArray, postalData.dataArray) && 
+            return (Arrays.equals(dataArray, postalData.dataArray) &&
                     (type == postalData.type &&
                             (type == StructuredPostal.TYPE_CUSTOM ?
                                     (label == postalData.label) : true)) &&
@@ -239,7 +240,7 @@
 
             return builder.toString().trim();
         }
-        
+
         @Override
         public String toString() {
             return String.format("type: %d, label: %s, isPrimary: %s",
@@ -267,7 +268,7 @@
             this.titleName = titleName;
             this.isPrimary = isPrimary;
         }
-        
+
         @Override
         public boolean equals(Object obj) {
             if (!(obj instanceof OrganizationData)) {
@@ -311,7 +312,7 @@
                     type, companyName, departmentName, titleName, isPrimary);
         }
     }
-    
+
     static public class ImData {
         public final int protocol;
         public final String customProtocol;
@@ -348,7 +349,7 @@
                     type, protocol, customProtocol, data, isPrimary);
         }
     }
-    
+
     public static class PhotoData {
         public static final String FORMAT_FLASH = "SWF";
         public final int type;
@@ -382,7 +383,7 @@
                     type, formatName, photoBytes.length, isPrimary);
         }
     }
-    
+
     /* package */ static class Property {
         private String mPropertyName;
         private Map<String, Collection<String>> mParameterMap =
@@ -393,7 +394,7 @@
         public void setPropertyName(final String propertyName) {
             mPropertyName = propertyName;
         }
-        
+
         public void addParameter(final String paramName, final String paramValue) {
             Collection<String> values;
             if (!mParameterMap.containsKey(paramName)) {
@@ -408,11 +409,11 @@
             }
             values.add(paramValue);
         }
-        
+
         public void addToPropertyValueList(final String propertyValue) {
             mPropertyValueList.add(propertyValue);
         }
-        
+
         public void setPropertyBytes(final byte[] propertyBytes) {
             mPropertyBytes = propertyBytes;
         }
@@ -420,11 +421,11 @@
         public final Collection<String> getParameters(String type) {
             return mParameterMap.get(type);
         }
-        
+
         public final List<String> getPropertyValueList() {
             return mPropertyValueList;
         }
-        
+
         public void clear() {
             mPropertyName = null;
             mParameterMap.clear();
@@ -432,7 +433,7 @@
             mPropertyBytes = null;
         }
     }
-    
+
     private String mFamilyName;
     private String mGivenName;
     private String mMiddleName;
@@ -441,19 +442,19 @@
 
     // Used only when no family nor given name is found.
     private String mFullName;
-    
+
     private String mPhoneticFamilyName;
     private String mPhoneticGivenName;
     private String mPhoneticMiddleName;
-    
+
     private String mPhoneticFullName;
 
     private List<String> mNickNameList;
 
-    private String mDisplayName; 
+    private String mDisplayName;
 
     private String mBirthday;
-    
+
     private List<String> mNoteList;
     private List<PhoneData> mPhoneList;
     private List<EmailData> mEmailList;
@@ -513,21 +514,21 @@
         }
         mNickNameList.add(nickName);
     }
-    
+
     private void addEmail(int type, String data, String label, boolean isPrimary){
         if (mEmailList == null) {
             mEmailList = new ArrayList<EmailData>();
         }
         mEmailList.add(new EmailData(type, data, label, isPrimary));
     }
-    
+
     private void addPostal(int type, List<String> propValueList, String label, boolean isPrimary){
         if (mPostalList == null) {
             mPostalList = new ArrayList<PostalData>(0);
         }
         mPostalList.add(new PostalData(type, propValueList, label, isPrimary));
     }
-    
+
     /**
      * Should be called via {@link #handleOrgValue(int, List, boolean)} or
      * {@link #handleTitleValue(String)}.
@@ -640,14 +641,14 @@
         }
         mImList.add(new ImData(protocol, customProtocol, type, propValue, isPrimary));
     }
-    
+
     private void addNote(final String note) {
         if (mNoteList == null) {
             mNoteList = new ArrayList<String>(1);
         }
         mNoteList.add(note);
     }
-    
+
     private void addPhotoBytes(String formatName, byte[] photoBytes, boolean isPrimary) {
         if (mPhotoList == null) {
             mPhotoList = new ArrayList<PhotoData>(1);
@@ -745,12 +746,12 @@
         final Map<String, Collection<String>> paramMap = property.mParameterMap;
         final List<String> propValueList = property.mPropertyValueList;
         byte[] propBytes = property.mPropertyBytes;
-        
+
         if (propValueList.size() == 0) {
             return;
         }
         final String propValue = listToString(propValueList).trim();
-        
+
         if (propName.equals(VCardConstants.PROPERTY_VERSION)) {
             // vCard version. Ignore this.
         } else if (propName.equals(VCardConstants.PROPERTY_FN)) {
@@ -805,7 +806,7 @@
                     } else if (typeString.equals(VCardConstants.PARAM_TYPE_HOME)) {
                         type = StructuredPostal.TYPE_HOME;
                         label = "";
-                    } else if (typeString.equals(VCardConstants.PARAM_TYPE_WORK) || 
+                    } else if (typeString.equals(VCardConstants.PARAM_TYPE_WORK) ||
                             typeString.equalsIgnoreCase(VCardConstants.PARAM_EXTRA_TYPE_COMPANY)) {
                         // "COMPANY" seems emitted by Windows Mobile, which is not
                         // specifically supported by vCard 2.1. We assume this is same
@@ -916,7 +917,7 @@
                 type = Phone.TYPE_CUSTOM;
                 label = typeObject.toString();
             }
-            
+
             final boolean isPrimary;
             if (typeCollection != null && typeCollection.contains(VCardConstants.PARAM_TYPE_PREF)) {
                 isPrimary = true;
@@ -977,7 +978,7 @@
                 VCardUtils.constructListFromValue(propValue,
                         VCardConfig.isV30(mVCardType));
             handleAndroidCustomProperty(customPropertyList);
-        /*} else if (propName.equals("REV")) {                
+        /*} else if (propName.equals("REV")) {
             // Revision of this VCard entry. I think we can ignore this.
         } else if (propName.equals("UID")) {
         } else if (propName.equals("KEY")) {
@@ -1041,7 +1042,7 @@
     }
 
     /**
-     * Consolidate several fielsds (like mName) using name candidates, 
+     * Consolidate several fielsds (like mName) using name candidates,
      */
     public void consolidateFields() {
         constructDisplayName();
@@ -1051,9 +1052,9 @@
         }
     }
 
-    public void pushIntoContentResolver(ContentResolver resolver) {
+    public Uri pushIntoContentResolver(ContentResolver resolver) {
         ArrayList<ContentProviderOperation> operationList =
-            new ArrayList<ContentProviderOperation>();  
+            new ArrayList<ContentProviderOperation>();
         ContentProviderOperation.Builder builder =
             ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
         String myGroupsId = null;
@@ -1176,7 +1177,7 @@
                 operationList.add(builder.build());
             }
         }
-        
+
         if (mPostalList != null) {
             for (PostalData postalData : mPostalList) {
                 builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
@@ -1185,7 +1186,7 @@
                 operationList.add(builder.build());
             }
         }
-        
+
         if (mImList != null) {
             for (ImData imData : mImList) {
                 builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
@@ -1201,7 +1202,7 @@
                 }
             }
         }
-        
+
         if (mNoteList != null) {
             for (String note : mNoteList) {
                 builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
@@ -1232,7 +1233,7 @@
                 builder.withValue(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE);
                 builder.withValue(Website.URL, website);
                 // There's no information about the type of URL in vCard.
-                // We use TYPE_HOMEPAGE for safety. 
+                // We use TYPE_HOMEPAGE for safety.
                 builder.withValue(Website.TYPE, Website.TYPE_HOMEPAGE);
                 operationList.add(builder.build());
             }
@@ -1265,7 +1266,7 @@
                         builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
                         builder.withValueBackReference(GroupMembership.RAW_CONTACT_ID, 0);
                         builder.withValue(Data.MIMETYPE, mimeType);
-                    } else {  // 1 <= i && i <= MAX_DATA_COLUMNS  
+                    } else {  // 1 <= i && i <= MAX_DATA_COLUMNS
                         if (!TextUtils.isEmpty(customPropertyValue)) {
                             builder.withValue("data" + i, customPropertyValue);
                         }
@@ -1286,11 +1287,17 @@
         }
 
         try {
-            resolver.applyBatch(ContactsContract.AUTHORITY, operationList);
+            ContentProviderResult[] results = resolver.applyBatch(
+                        ContactsContract.AUTHORITY, operationList);
+            // the first result is always the raw_contact. return it's uri so
+            // that it can be found later
+            return results[0].uri;
         } catch (RemoteException e) {
             Log.e(LOG_TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+            return null;
         } catch (OperationApplicationException e) {
             Log.e(LOG_TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+            return null;
         }
     }
 
@@ -1319,7 +1326,7 @@
     public boolean isIgnorable() {
         return getDisplayName().length() == 0;
     }
-    
+
     private String listToString(List<String> list){
         final int size = list.size();
         if (size > 1) {
diff --git a/core/java/android/pim/vcard/VCardEntryCommitter.java b/core/java/android/pim/vcard/VCardEntryCommitter.java
index ebbbab6..3cd64b0 100644
--- a/core/java/android/pim/vcard/VCardEntryCommitter.java
+++ b/core/java/android/pim/vcard/VCardEntryCommitter.java
@@ -16,6 +16,7 @@
 package android.pim.vcard;
 
 import android.content.ContentResolver;
+import android.net.Uri;
 import android.util.Log;
 
 /**
@@ -34,6 +35,7 @@
 
     private final ContentResolver mContentResolver;
     private long mTimeToCommit;
+    private Uri mLastCreatedUri;
 
     public VCardEntryCommitter(ContentResolver resolver) {
         mContentResolver = resolver;
@@ -50,7 +52,11 @@
 
     public void onEntryCreated(final VCardEntry contactStruct) {
         long start = System.currentTimeMillis();
-        contactStruct.pushIntoContentResolver(mContentResolver);
+        mLastCreatedUri = contactStruct.pushIntoContentResolver(mContentResolver);
         mTimeToCommit += System.currentTimeMillis() - start;
     }
+
+    public Uri getLastCreatedUri() {
+        return mLastCreatedUri;
+    }
 }
\ No newline at end of file
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index 46c82e4..c06a1e2 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -5244,7 +5244,6 @@
      * </tr>
      * </table>
      */
-
     public static final class Settings implements SettingsColumns {
         /**
          * This utility class cannot be instantiated
@@ -5271,6 +5270,83 @@
     }
 
     /**
+     * Private API for inquiring about the general status of the provider.
+     *
+     * @hide
+     */
+    public static final class ProviderStatus {
+
+        /**
+         * Not instantiable.
+         */
+        private ProviderStatus() {
+        }
+
+        /**
+         * The content:// style URI for this table.  Requests to this URI can be
+         * performed on the UI thread because they are always unblocking.
+         *
+         * @hide
+         */
+        public static final Uri CONTENT_URI =
+                Uri.withAppendedPath(AUTHORITY_URI, "provider_status");
+
+        /**
+         * The MIME-type of {@link #CONTENT_URI} providing a directory of
+         * settings.
+         *
+         * @hide
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/provider_status";
+
+        /**
+         * An integer representing the current status of the provider.
+         *
+         * @hide
+         */
+        public static final String STATUS = "status";
+
+        /**
+         * Default status of the provider.
+         *
+         * @hide
+         */
+        public static final int STATUS_NORMAL = 0;
+
+        /**
+         * The status used when the provider is in the process of upgrading.  Contacts
+         * are temporarily unaccessible.
+         *
+         * @hide
+         */
+        public static final int STATUS_UPGRADING = 1;
+
+        /**
+         * The status used if the provider was in the process of upgrading but ran
+         * out of storage. The DATA1 column will contain the estimated amount of
+         * storage required (in bytes). Update status to STATUS_NORMAL to force
+         * the provider to retry the upgrade.
+         *
+         * @hide
+         */
+        public static final int STATUS_UPGRADE_OUT_OF_MEMORY = 2;
+
+        /**
+         * The status used during a locale change.
+         *
+         * @hide
+         */
+        public static final int STATUS_CHANGING_LOCALE = 3;
+
+        /**
+         * Additional data associated with the status.
+         *
+         * @hide
+         */
+        public static final String DATA1 = "data1";
+    }
+
+    /**
      * Helper methods to display QuickContact dialogs that allow users to pivot on
      * a specific {@link Contacts} entry.
      */
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 726f98a..fdde591 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -679,6 +679,9 @@
             MOVED_TO_SECURE.add(Secure.HTTP_PROXY);
             MOVED_TO_SECURE.add(Secure.INSTALL_NON_MARKET_APPS);
             MOVED_TO_SECURE.add(Secure.LOCATION_PROVIDERS_ALLOWED);
+            MOVED_TO_SECURE.add(Secure.LOCK_PATTERN_ENABLED);
+            MOVED_TO_SECURE.add(Secure.LOCK_PATTERN_VISIBLE);
+            MOVED_TO_SECURE.add(Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED);
             MOVED_TO_SECURE.add(Secure.LOGGING_ID);
             MOVED_TO_SECURE.add(Secure.PARENTAL_CONTROL_ENABLED);
             MOVED_TO_SECURE.add(Secure.PARENTAL_CONTROL_LAST_UPDATE);
@@ -1160,18 +1163,25 @@
             "bluetooth_discoverability_timeout";
 
         /**
-         * Whether autolock is enabled (0 = false, 1 = true)
+         * @deprecated Use {@link android.provider.Settings.Secure#LOCK_PATTERN_ENABLED}
+         * instead
          */
-        public static final String LOCK_PATTERN_ENABLED = "lock_pattern_autolock";
+        @Deprecated
+        public static final String LOCK_PATTERN_ENABLED = Secure.LOCK_PATTERN_ENABLED;
 
         /**
-         * Whether lock pattern is visible as user enters (0 = false, 1 = true)
+         * @deprecated Use {@link android.provider.Settings.Secure#LOCK_PATTERN_VISIBLE}
+         * instead
          */
+        @Deprecated
         public static final String LOCK_PATTERN_VISIBLE = "lock_pattern_visible_pattern";
 
         /**
-         * Whether lock pattern will vibrate as user enters (0 = false, 1 = true)
+         * @deprecated Use 
+         * {@link android.provider.Settings.Secure#LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED}
+         * instead
          */
+        @Deprecated
         public static final String LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED =
             "lock_pattern_tactile_feedback_enabled";
 
@@ -2297,6 +2307,22 @@
         public static final String LOCATION_PROVIDERS_ALLOWED = "location_providers_allowed";
 
         /**
+         * Whether autolock is enabled (0 = false, 1 = true)
+         */
+        public static final String LOCK_PATTERN_ENABLED = "lock_pattern_autolock";
+
+        /**
+         * Whether lock pattern is visible as user enters (0 = false, 1 = true)
+         */
+        public static final String LOCK_PATTERN_VISIBLE = "lock_pattern_visible_pattern";
+
+        /**
+         * Whether lock pattern will vibrate as user enters (0 = false, 1 = true)
+         */
+        public static final String LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED =
+            "lock_pattern_tactile_feedback_enabled";
+
+        /**
          * Whether assisted GPS should be enabled or not.
          * @hide
          */
diff --git a/core/java/android/speech/RecognizerResultsIntent.java b/core/java/android/speech/RecognizerResultsIntent.java
index 4997d50..b45e4b1 100644
--- a/core/java/android/speech/RecognizerResultsIntent.java
+++ b/core/java/android/speech/RecognizerResultsIntent.java
@@ -127,10 +127,11 @@
      * All the values and the keys are {@link String}s. Each key/value pair represents an extra HTTP
      * header. The keys can't be the standard HTTP headers as they are set by the WebView.
      *
-     * A list of size 1 may be provided to apply the same HTTP headers to all html results. A list 
-     * of the same size as {@link #EXTRA_VOICE_SEARCH_RESULT_STRINGS} may be provided to apply 
-     * different HTTP headers to each different html result in the 
-     * {@link #EXTRA_VOICE_SEARCH_RESULT_HTML} list.
+     * A list of size 1 may be provided to apply the same HTTP headers to all web results. A
+     * list of the same size as {@link #EXTRA_VOICE_SEARCH_RESULT_STRINGS} may be provided to
+     * apply different HTTP headers to each different web result in the list. These headers will
+     * only be used in the case that the url for a particular web result (from
+     * {@link #EXTRA_VOICE_SEARCH_RESULT_URLS}) is loaded.
      *
      * @hide not to be exposed immediately as the implementation details may change
      */
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/view/inputmethod/BaseInputConnection.java b/core/java/android/view/inputmethod/BaseInputConnection.java
index 7393737..6ac1633 100644
--- a/core/java/android/view/inputmethod/BaseInputConnection.java
+++ b/core/java/android/view/inputmethod/BaseInputConnection.java
@@ -328,6 +328,11 @@
             b = tmp;
         }
 
+        // Guard against the case where the cursor has not been positioned yet.
+        if (b < 0) {
+            b = 0;
+        }
+
         if (b + length > content.length()) {
             length = content.length() - b;
         }
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 6eca68c..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);
@@ -3319,7 +3342,7 @@
             if (!animateScroll) {
                 extras = DRAW_EXTRAS_FIND;
             }
-        } else if (mShiftIsPressed) {
+        } else if (mShiftIsPressed && !nativeFocusIsPlugin()) {
             if (!animateZoom && !mPreviewZoomOnly) {
                 extras = DRAW_EXTRAS_SELECTION;
                 nativeSetSelectionRegion(mTouchSelection || mExtendSelection);
@@ -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,16 +3694,22 @@
             return false;
         }
 
-        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
-                && (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
                 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
-            // always handle the navigation keys in the UI thread
             switchOutDrawHistory();
+            if (nativeFocusIsPlugin()) {
+                letPluginHandleNavKey(keyCode, event.getEventTime(), true);
+                return true;
+            }
             if (mShiftIsPressed) {
                 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
                     ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
@@ -3692,7 +3719,7 @@
                 moveSelection(xRate * multiplier, yRate * multiplier);
                 return true;
             }
-            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
+            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
                 playSoundEffect(keyCodeToSoundsEffect(keyCode));
                 return true;
             }
@@ -3703,7 +3730,7 @@
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             switchOutDrawHistory();
             if (event.getRepeatCount() == 0) {
-                if (mShiftIsPressed) {
+                if (mShiftIsPressed && !nativeFocusIsPlugin()) {
                     return true; // discard press if copy in progress
                 }
                 mGotCenterDown = true;
@@ -3812,13 +3839,20 @@
 
         if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
                 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
-            if (commitCopy()) {
+            if (nativeFocusIsPlugin()) {
+                mShiftIsPressed = false;
+                return true;
+            } else if (commitCopy()) {
                 return true;
             }
         }
 
         if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
                 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
+            if (nativeFocusIsPlugin()) {
+                letPluginHandleNavKey(keyCode, event.getEventTime(), false);
+                return true;
+            }
             // always handle the navigation keys in the UI thread
             // Bubble up the key event as WebView doesn't handle it
             return false;
@@ -3829,7 +3863,7 @@
             mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
             mGotCenterDown = false;
 
-            if (mShiftIsPressed) {
+            if (mShiftIsPressed && !nativeFocusIsPlugin()) {
                 if (mExtendSelection) {
                     commitCopy();
                 } else {
@@ -4169,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 {
@@ -4448,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);
         }
@@ -4473,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()) {
@@ -4534,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)) {
@@ -4583,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) {
@@ -4602,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;
@@ -4622,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);
@@ -4683,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
@@ -4762,9 +4817,6 @@
                         }
                     }
                     if ((deltaX | deltaY) != 0) {
-                        overscrollBy(deltaX, deltaY, mScrollX, mScrollY,
-                                computeMaxScrollX(), computeMaxScrollY(),
-                                getViewWidth() / 3, getViewHeight() / 3);
                         if (deltaX != 0) {
                             mLastTouchX = x;
                         }
@@ -4781,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) {
@@ -4813,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:
@@ -4843,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();
@@ -4865,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;
                         }
@@ -4891,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;
@@ -4904,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;
@@ -4944,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();
@@ -5014,7 +5110,7 @@
             return true;
         }
         if (ev.getAction() == MotionEvent.ACTION_DOWN) {
-            if (mShiftIsPressed) {
+            if (mShiftIsPressed && !nativeFocusIsPlugin()) {
                 return true; // discard press if copy in progress
             }
             mTrackballDown = true;
@@ -5039,7 +5135,7 @@
             mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
             mTrackballDown = false;
             mTrackballUpTime = time;
-            if (mShiftIsPressed) {
+            if (mShiftIsPressed && !nativeFocusIsPlugin()) {
                 if (mExtendSelection) {
                     commitCopy();
                 } else {
@@ -5177,7 +5273,7 @@
         float yRate = mTrackballRemainsY * 1000 / elapsed;
         int viewWidth = getViewWidth();
         int viewHeight = getViewHeight();
-        if (mShiftIsPressed) {
+        if (mShiftIsPressed && !nativeFocusIsPlugin()) {
             moveSelection(scaleTrackballX(xRate, viewWidth),
                     scaleTrackballY(yRate, viewHeight));
             mTrackballRemainsX = mTrackballRemainsY = 0;
@@ -5215,7 +5311,12 @@
                         + " mTrackballRemainsX=" + mTrackballRemainsX
                         + " mTrackballRemainsY=" + mTrackballRemainsY);
             }
-            if (navHandledKey(selectKeyCode, count, false, time, false)) {
+            if (nativeFocusIsPlugin()) {
+                for (int i = 0; i < count; i++) {
+                    letPluginHandleNavKey(selectKeyCode, time, true);
+                }
+                letPluginHandleNavKey(selectKeyCode, time, false);
+            } else if (navHandledKey(selectKeyCode, count, false, time)) {
                 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
             }
             mTrackballRemainsX = mTrackballRemainsY = 0;
@@ -5558,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);
@@ -5692,7 +5797,7 @@
                         return result;
                 }
                 if (mNativeClass != 0 && !nativeHasCursorNode()) {
-                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
+                    navHandledKey(fakeKeyDirection, 1, true, 0);
                 }
             }
         }
@@ -5754,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) {
@@ -5775,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) {
@@ -5825,7 +5934,7 @@
                 cursorData(), 1000);
     }
 
-    /* package */ WebViewCore getWebViewCore() {
+    /* package */ synchronized WebViewCore getWebViewCore() {
         return mWebViewCore;
     }
 
@@ -5842,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.
@@ -5865,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:
@@ -6118,7 +6222,7 @@
                     }
                     break;
                 case MOVE_OUT_OF_PLUGIN:
-                    navHandledKey(msg.arg1, 1, false, 0, true);
+                    navHandledKey(msg.arg1, 1, false, 0);
                     break;
                 case UPDATE_TEXT_ENTRY_MSG_ID:
                     // this is sent after finishing resize in WebViewCore. Make
@@ -6174,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;
@@ -6234,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();
@@ -6252,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.
@@ -6306,7 +6468,7 @@
                     break;
 
                 case HIDE_FULLSCREEN:
-                    if (mFullScreenHolder != null) {
+                    if (inFullScreenMode()) {
                         mFullScreenHolder.dismiss();
                         mFullScreenHolder = null;
                     }
@@ -6785,21 +6947,34 @@
         invalidate();
     }
 
-    // return true if the key was handled
-    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
-            long time, boolean ignorePlugin) {
-        if (mNativeClass == 0) {
-            return false;
+    /**
+     * Pass the key to the plugin.  This assumes that nativeFocusIsPlugin()
+     * returned true.
+     */
+    private void letPluginHandleNavKey(int keyCode, long time, boolean down) {
+        int keyEventAction;
+        int eventHubAction;
+        if (down) {
+            keyEventAction = KeyEvent.ACTION_DOWN;
+            eventHubAction = EventHub.KEY_DOWN;
+            playSoundEffect(keyCodeToSoundsEffect(keyCode));
+        } else {
+            keyEventAction = KeyEvent.ACTION_UP;
+            eventHubAction = EventHub.KEY_UP;
         }
-        if (ignorePlugin == false && nativeFocusIsPlugin()) {
-            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
-                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
+        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
+                1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
                 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
                 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
                 , 0, 0, 0);
-            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
-            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
-            return true;
+        mWebViewCore.sendMessage(eventHubAction, event);
+    }
+
+    // return true if the key was handled
+    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
+            long time) {
+        if (mNativeClass == 0) {
+            return false;
         }
         mLastCursorTime = time;
         mLastCursorBounds = nativeGetCursorRingBounds();
@@ -6969,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 06880a1..a1c3fa2 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -1641,7 +1641,7 @@
                 mResurrectToPosition = mSelectedPosition;
             }
         } else {
-            if (mFiltered) {
+            if (mFiltered && !mPopupHidden) {
                 // Show the type filter only if a filter is in effect
                 showPopup();
             }
@@ -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.
@@ -2849,8 +2849,9 @@
                 final int lastViewHeight = lastView.getHeight();
                 final int lastViewTop = lastView.getTop();
                 final int lastViewPixelsShowing = listHeight - lastViewTop;
+                final int extraScroll = lastPos < mItemCount - 1 ? mExtraScroll : mListPadding.bottom;
 
-                smoothScrollBy(lastViewHeight - lastViewPixelsShowing + mExtraScroll,
+                smoothScrollBy(lastViewHeight - lastViewPixelsShowing + extraScroll,
                         mScrollDuration);
 
                 mLastSeenPos = lastPos;
@@ -2862,7 +2863,10 @@
                 
             case MOVE_DOWN_BOUND: {
                 final int nextViewIndex = 1;
-                if (firstPos == mBoundPos || getChildCount() <= nextViewIndex) {
+                final int childCount = getChildCount();
+                
+                if (firstPos == mBoundPos || childCount <= nextViewIndex
+                        || firstPos + childCount >= mItemCount) {
                     return;
                 }
                 final int nextPos = firstPos + nextViewIndex;
@@ -2904,8 +2908,9 @@
                     return;
                 }
                 final int firstViewTop = firstView.getTop();
+                final int extraScroll = firstPos > 0 ? mExtraScroll : mListPadding.top;
 
-                smoothScrollBy(firstViewTop - mExtraScroll, mScrollDuration);
+                smoothScrollBy(firstViewTop - extraScroll, mScrollDuration);
 
                 mLastSeenPos = firstPos;
 
@@ -3075,7 +3080,10 @@
 
         final boolean down = incrementalDeltaY < 0;
 
-        hideSelector();
+        final boolean inTouchMode = isInTouchMode();
+        if (inTouchMode) {
+            hideSelector();
+        }
 
         final int headerViewsCount = getHeaderViewsCount();
         final int footerViewsStart = mItemCount - getFooterViewsCount();
@@ -3138,7 +3146,7 @@
         if (down) {
             mFirstPosition += count;
         }
-
+        
         invalidate();
 
         final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);
@@ -3146,6 +3154,10 @@
             fillGap(down);
         }
 
+        if (!inTouchMode && mSelectedPosition != INVALID_POSITION) {
+            positionSelector(getChildAt(mSelectedPosition - mFirstPosition));
+        }
+
         mBlockLayoutRequests = false;
 
         invokeOnItemScrollListener();
@@ -3498,7 +3510,6 @@
         if (mPopup != null) {
             mPopup.dismiss();
         }
-        mPopupHidden = false;
     }
 
     /**
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index 0f47b96..ed63787 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -1081,11 +1081,11 @@
     }
 
     @Override
-    protected boolean setFrame(int l, int t, int r, int b) {
+    protected boolean setFrame(final int l, int t, final int r, int b) {
         boolean result = super.setFrame(l, t, r, b);
 
         if (mPopup.isShowing()) {
-            mPopup.update(this, r - l, -1);
+            showDropDown();
         }
 
         return result;
diff --git a/core/java/android/widget/DatePicker.java b/core/java/android/widget/DatePicker.java
index 9ef5e0b..b3d5f1a 100644
--- a/core/java/android/widget/DatePicker.java
+++ b/core/java/android/widget/DatePicker.java
@@ -94,9 +94,7 @@
         mDayPicker.setOnChangeListener(new OnChangedListener() {
             public void onChanged(NumberPicker picker, int oldVal, int newVal) {
                 mDay = newVal;
-                if (mOnDateChangedListener != null) {
-                    mOnDateChangedListener.onDateChanged(DatePicker.this, mYear, mMonth, mDay);
-                }
+                notifyDateChanged();
             }
         });
         mMonthPicker = (NumberPicker) findViewById(R.id.month);
@@ -126,9 +124,7 @@
                 mMonth = newVal - 1;
                 // Adjust max day of the month
                 adjustMaxDay();
-                if (mOnDateChangedListener != null) {
-                    mOnDateChangedListener.onDateChanged(DatePicker.this, mYear, mMonth, mDay);
-                }
+                notifyDateChanged();
                 updateDaySpinner();
             }
         });
@@ -139,9 +135,7 @@
                 mYear = newVal;
                 // Adjust max day for leap years if needed
                 adjustMaxDay();
-                if (mOnDateChangedListener != null) {
-                    mOnDateChangedListener.onDateChanged(DatePicker.this, mYear, mMonth, mDay);
-                }
+                notifyDateChanged();
                 updateDaySpinner();
             }
         });
@@ -242,11 +236,14 @@
     }
 
     public void updateDate(int year, int monthOfYear, int dayOfMonth) {
-        mYear = year;
-        mMonth = monthOfYear;
-        mDay = dayOfMonth;
-        updateSpinners();
-        reorderPickers(new DateFormatSymbols().getShortMonths());
+        if (mYear != year || mMonth != monthOfYear || mDay != dayOfMonth) {
+            mYear = year;
+            mMonth = monthOfYear;
+            mDay = dayOfMonth;
+            updateSpinners();
+            reorderPickers(new DateFormatSymbols().getShortMonths());
+            notifyDateChanged();
+        }
     }
 
     private static class SavedState extends BaseSavedState {
@@ -388,4 +385,10 @@
             mDay = max;
         }
     }
+
+    private void notifyDateChanged() {
+        if (mOnDateChangedListener != null) {
+            mOnDateChangedListener.onDateChanged(DatePicker.this, mYear, mMonth, mDay);
+        }
+    }
 }
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index acb7e02..d80a5e3 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -318,11 +318,7 @@
     @Override
     public boolean dispatchKeyEvent(KeyEvent event) {
         // Let the focused view and/or our descendants get the key first
-        boolean handled = super.dispatchKeyEvent(event);
-        if (handled) {
-            return true;
-        }
-        return executeKeyEvent(event);
+        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
     }
 
     /**
@@ -509,8 +505,11 @@
                     final int deltaX = (int) (mLastMotionX - x);
                     mLastMotionX = x;
 
+                    final int oldX = mScrollX;
+                    final int oldY = mScrollY;                    
                     overscrollBy(deltaX, 0, mScrollX, 0, getScrollRange(), 0,
                             getOverscrollMax(), 0);
+                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
                 }
                 break;
             case MotionEvent.ACTION_UP:
@@ -524,7 +523,7 @@
                             fling(-initialVelocity);
                         } else {
                             final int right = getScrollRange();
-                            if (mScroller.springback(mScrollX, mScrollY, 0, 0, right, 0)) {
+                            if (mScroller.springback(mScrollX, mScrollY, 0, right, 0, 0)) {
                                 invalidate();
                             }
                         }
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/PopupWindow.java b/core/java/android/widget/PopupWindow.java
index d20ab3b..cf2ed86 100644
--- a/core/java/android/widget/PopupWindow.java
+++ b/core/java/android/widget/PopupWindow.java
@@ -126,7 +126,7 @@
                     WindowManager.LayoutParams p = (WindowManager.LayoutParams)
                             mPopupView.getLayoutParams();
 
-                    mAboveAnchor = findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff);
+                    updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff));
                     update(p.x, p.y, -1, -1, true);
                 }
             }
@@ -729,22 +729,8 @@
 
         WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());
         preparePopup(p);
-        mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff);
 
-        if (mBackground != null) {
-            // If the background drawable provided was a StateListDrawable with above-anchor
-            // and below-anchor states, use those. Otherwise rely on refreshDrawableState to
-            // do the job.
-            if (mAboveAnchorBackgroundDrawable != null) {
-                if (mAboveAnchor) {
-                    mPopupView.setBackgroundDrawable(mAboveAnchorBackgroundDrawable);
-                } else {
-                    mPopupView.setBackgroundDrawable(mBelowAnchorBackgroundDrawable);
-                }
-            } else {
-                mPopupView.refreshDrawableState();
-            }
-        }
+        updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));
 
         if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;
         if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;
@@ -754,6 +740,27 @@
         invokePopup(p);
     }
 
+    private void updateAboveAnchor(boolean aboveAnchor) {
+        if (aboveAnchor != mAboveAnchor) {
+            mAboveAnchor = aboveAnchor;
+
+            if (mBackground != null) {
+                // If the background drawable provided was a StateListDrawable with above-anchor
+                // and below-anchor states, use those. Otherwise rely on refreshDrawableState to
+                // do the job.
+                if (mAboveAnchorBackgroundDrawable != null) {
+                    if (mAboveAnchor) {
+                        mPopupView.setBackgroundDrawable(mAboveAnchorBackgroundDrawable);
+                    } else {
+                        mPopupView.setBackgroundDrawable(mBelowAnchorBackgroundDrawable);
+                    }
+                } else {
+                    mPopupView.refreshDrawableState();
+                }
+            }
+        }
+    }
+
     /**
      * Indicates whether the popup is showing above (the y coordinate of the popup's bottom
      * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate
@@ -915,7 +922,7 @@
 
         anchor.getLocationInWindow(mDrawingLocation);
         p.x = mDrawingLocation[0] + xoff;
-        p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff;
+        p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
         
         boolean onTop = false;
 
@@ -932,26 +939,26 @@
             // the edit box
             int scrollX = anchor.getScrollX();
             int scrollY = anchor.getScrollY();
-            Rect r = new Rect(scrollX, scrollY,  scrollX + mPopupWidth,
-                    scrollY + mPopupHeight + anchor.getMeasuredHeight());
+            Rect r = new Rect(scrollX, scrollY,  scrollX + mPopupWidth + xoff,
+                    scrollY + mPopupHeight + anchor.getHeight() + yoff);
             anchor.requestRectangleOnScreen(r, true);
-            
+
             // now we re-evaluate the space available, and decide from that
             // whether the pop-up will go above or below the anchor.
             anchor.getLocationInWindow(mDrawingLocation);
             p.x = mDrawingLocation[0] + xoff;
-            p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff;
+            p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
             
             // determine whether there is more space above or below the anchor
             anchor.getLocationOnScreen(mScreenLocation);
             
-            onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getMeasuredHeight() - yoff) <
+            onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getHeight() - yoff) <
                     (mScreenLocation[1] - yoff - displayFrame.top);
             if (onTop) {
                 p.gravity = Gravity.LEFT | Gravity.BOTTOM;
                 p.y = root.getHeight() - mDrawingLocation[1] + yoff;
             } else {
-                p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff;
+                p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
             }
         }
 
@@ -1257,13 +1264,16 @@
             }
         }
 
-        if (updateLocation) {
-            mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff);
-        } else {
-            mAboveAnchor = findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff);            
-        }
+        int x = p.x;
+        int y = p.y;
 
-        update(p.x, p.y, width, height);
+        if (updateLocation) {
+            updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));
+        } else {
+            updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff));            
+        }
+        
+        update(p.x, p.y, width, height, x != p.x || y != p.y);
     }
 
     /**
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 489c44d..d7dfa86 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -22,7 +22,6 @@
 import android.content.res.TypedArray;
 import android.graphics.Rect;
 import android.util.AttributeSet;
-import android.util.Log;
 import android.view.FocusFinder;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
@@ -52,8 +51,6 @@
  * <p>ScrollView only supports vertical scrolling.
  */
 public class ScrollView extends FrameLayout {
-    private static final String TAG = "ScrollView";
-
     static final int ANIMATED_SCROLL_GAP = 250;
 
     static final float MAX_SCROLL_FACTOR = 0.5f;
@@ -318,11 +315,7 @@
     @Override
     public boolean dispatchKeyEvent(KeyEvent event) {
         // Let the focused view and/or our descendants get the key first
-        boolean handled = super.dispatchKeyEvent(event);
-        if (handled) {
-            return true;
-        }
-        return executeKeyEvent(event);
+        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
     }
 
     /**
@@ -510,8 +503,11 @@
                     final int deltaY = (int) (mLastMotionY - y);
                     mLastMotionY = y;
 
+                    final int oldX = mScrollX;
+                    final int oldY = mScrollY;
                     overscrollBy(0, deltaY, 0, mScrollY, 0, getScrollRange(),
                             0, getOverscrollMax());
+                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
                 }
                 break;
             case MotionEvent.ACTION_UP: 
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 51e1c57..7b21be5 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -1376,15 +1376,18 @@
                 dr.mDrawableLeft.setCallback(null);
             }
             dr.mDrawableLeft = left;
-            if (dr.mDrawableTop != left && dr.mDrawableTop != null) {
+
+            if (dr.mDrawableTop != top && dr.mDrawableTop != null) {
                 dr.mDrawableTop.setCallback(null);
             }
             dr.mDrawableTop = top;
-            if (dr.mDrawableRight != left && dr.mDrawableRight != null) {
+
+            if (dr.mDrawableRight != right && dr.mDrawableRight != null) {
                 dr.mDrawableRight.setCallback(null);
             }
             dr.mDrawableRight = right;
-            if (dr.mDrawableBottom != left && dr.mDrawableBottom != null) {
+
+            if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) {
                 dr.mDrawableBottom.setCallback(null);
             }
             dr.mDrawableBottom = bottom;
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/app/ShutdownThread.java b/core/java/com/android/internal/app/ShutdownThread.java
index 2f48499..51cd0f8 100644
--- a/core/java/com/android/internal/app/ShutdownThread.java
+++ b/core/java/com/android/internal/app/ShutdownThread.java
@@ -28,11 +28,13 @@
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.os.Handler;
-import android.os.RemoteException;
 import android.os.Power;
+import android.os.PowerManager;
+import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.storage.IMountService;
+import android.os.storage.IMountShutdownObserver;
 
 import com.android.internal.telephony.ITelephony;
 import android.util.Log;
@@ -45,28 +47,35 @@
     private static final int PHONE_STATE_POLL_SLEEP_MSEC = 500;
     // maximum time we wait for the shutdown broadcast before going on.
     private static final int MAX_BROADCAST_TIME = 10*1000;
+    private static final int MAX_SHUTDOWN_WAIT_TIME = 20*1000;
     
     // state tracking
     private static Object sIsStartedGuard = new Object();
     private static boolean sIsStarted = false;
     
+    private static boolean mReboot;
+    private static String mRebootReason;
+
     // static instance of this thread
     private static final ShutdownThread sInstance = new ShutdownThread();
     
-    private final Object mBroadcastDoneSync = new Object();
-    private boolean mBroadcastDone;
+    private final Object mActionDoneSync = new Object();
+    private boolean mActionDone;
     private Context mContext;
+    private PowerManager mPowerManager;
+    private PowerManager.WakeLock mWakeLock;
     private Handler mHandler;
     
     private ShutdownThread() {
     }
  
-    /** 
+    /**
      * Request a clean shutdown, waiting for subsystems to clean up their
      * state etc.  Must be called from a Looper thread in which its UI
      * is shown.
-     * 
+     *
      * @param context Context used to display the shutdown progress dialog.
+     * @param confirm true if user confirmation is needed before shutting down.
      */
     public static void shutdown(final Context context, boolean confirm) {
         // ensure that only one thread is trying to power down.
@@ -103,6 +112,21 @@
         }
     }
 
+    /**
+     * Request a clean shutdown, waiting for subsystems to clean up their
+     * state etc.  Must be called from a Looper thread in which its UI
+     * is shown.
+     *
+     * @param context Context used to display the shutdown progress dialog.
+     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
+     * @param confirm true if user confirmation is needed before shutting down.
+     */
+    public static void reboot(final Context context, String reason, boolean confirm) {
+        mReboot = true;
+        mRebootReason = reason;
+        shutdown(context, confirm);
+    }
+
     private static void beginShutdownSequence(Context context) {
         synchronized (sIsStartedGuard) {
             sIsStarted = true;
@@ -125,18 +149,30 @@
 
         // start the thread that initiates shutdown
         sInstance.mContext = context;
+        sInstance.mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
+        sInstance.mWakeLock = null;
+        if (sInstance.mPowerManager.isScreenOn()) {
+            try {
+                sInstance.mWakeLock = sInstance.mPowerManager.newWakeLock(
+                        PowerManager.FULL_WAKE_LOCK, "Shutdown");
+                sInstance.mWakeLock.acquire();
+            } catch (SecurityException e) {
+                Log.w(TAG, "No permission to acquire wake lock", e);
+                sInstance.mWakeLock = null;
+            }
+        }
         sInstance.mHandler = new Handler() {
         };
         sInstance.start();
     }
 
-    void broadcastDone() {
-        synchronized (mBroadcastDoneSync) {
-            mBroadcastDone = true;
-            mBroadcastDoneSync.notifyAll();
+    void actionDone() {
+        synchronized (mActionDoneSync) {
+            mActionDone = true;
+            mActionDoneSync.notifyAll();
         }
     }
-    
+
     /**
      * Makes sure we handle the shutdown gracefully.
      * Shuts off power regardless of radio and bluetooth state if the alloted time has passed.
@@ -148,27 +184,27 @@
         BroadcastReceiver br = new BroadcastReceiver() {
             @Override public void onReceive(Context context, Intent intent) {
                 // We don't allow apps to cancel this, so ignore the result.
-                broadcastDone();
+                actionDone();
             }
         };
         
         Log.i(TAG, "Sending shutdown broadcast...");
         
         // First send the high-level shut down broadcast.
-        mBroadcastDone = false;
+        mActionDone = false;
         mContext.sendOrderedBroadcast(new Intent(Intent.ACTION_SHUTDOWN), null,
                 br, mHandler, 0, null, null);
         
         final long endTime = System.currentTimeMillis() + MAX_BROADCAST_TIME;
-        synchronized (mBroadcastDoneSync) {
-            while (!mBroadcastDone) {
+        synchronized (mActionDoneSync) {
+            while (!mActionDone) {
                 long delay = endTime - System.currentTimeMillis();
                 if (delay <= 0) {
                     Log.w(TAG, "Shutdown broadcast timed out");
                     break;
                 }
                 try {
-                    mBroadcastDoneSync.wait(delay);
+                    mActionDoneSync.wait(delay);
                 } catch (InterruptedException e) {
                 }
             }
@@ -247,17 +283,50 @@
         }
 
         // Shutdown MountService to ensure media is in a safe state
-        try {
-            if (mount != null) {
-                mount.shutdown();
-            } else {
-                Log.w(TAG, "MountService unavailable for shutdown");
+        IMountShutdownObserver observer = new IMountShutdownObserver.Stub() {
+            public void onShutDownComplete(int statusCode) throws RemoteException {
+                Log.w(TAG, "Result code " + statusCode + " from MountService.shutdown");
+                actionDone();
             }
-        } catch (Exception e) {
-            Log.e(TAG, "Exception during MountService shutdown", e);
+        };
+
+        Log.i(TAG, "Shutting down MountService");
+        // Set initial variables and time out time.
+        mActionDone = false;
+        final long endShutTime = System.currentTimeMillis() + MAX_SHUTDOWN_WAIT_TIME;
+        synchronized (mActionDoneSync) {
+            try {
+                if (mount != null) {
+                    mount.shutdown(observer);
+                } else {
+                    Log.w(TAG, "MountService unavailable for shutdown");
+                }
+            } catch (Exception e) {
+                Log.e(TAG, "Exception during MountService shutdown", e);
+            }
+            while (!mActionDone) {
+                long delay = endShutTime - System.currentTimeMillis();
+                if (delay <= 0) {
+                    Log.w(TAG, "Shutdown wait timed out");
+                    break;
+                }
+                try {
+                    mActionDoneSync.wait(delay);
+                } catch (InterruptedException e) {
+                }
+            }
         }
 
-        //shutdown power
+        if (mReboot) {
+            Log.i(TAG, "Rebooting, reason: " + mRebootReason);
+            try {
+                Power.reboot(mRebootReason);
+            } catch (Exception e) {
+                Log.e(TAG, "Reboot failed, will attempt shutdown instead", e);
+            }
+        }
+
+        // Shutdown power
         Log.i(TAG, "Performing low-level shutdown...");
         Power.shutdown();
     }
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/java/com/android/internal/widget/ContactHeaderWidget.java b/core/java/com/android/internal/widget/ContactHeaderWidget.java
index c4f9988..242f12e 100644
--- a/core/java/com/android/internal/widget/ContactHeaderWidget.java
+++ b/core/java/com/android/internal/widget/ContactHeaderWidget.java
@@ -99,6 +99,7 @@
             Contacts.LOOKUP_KEY,
             Contacts.PHOTO_ID,
             Contacts.DISPLAY_NAME,
+            Contacts.PHONETIC_NAME,
             Contacts.STARRED,
             Contacts.CONTACT_PRESENCE,
             Contacts.CONTACT_STATUS,
@@ -110,14 +111,15 @@
         int LOOKUP_KEY = 1;
         int PHOTO_ID = 2;
         int DISPLAY_NAME = 3;
+        int PHONETIC_NAME = 4;
         //TODO: We need to figure out how we're going to get the phonetic name.
         //static final int HEADER_PHONETIC_NAME_COLUMN_INDEX
-        int STARRED = 4;
-        int CONTACT_PRESENCE_STATUS = 5;
-        int CONTACT_STATUS = 6;
-        int CONTACT_STATUS_TIMESTAMP = 7;
-        int CONTACT_STATUS_RES_PACKAGE = 8;
-        int CONTACT_STATUS_LABEL = 9;
+        int STARRED = 5;
+        int CONTACT_PRESENCE_STATUS = 6;
+        int CONTACT_STATUS = 7;
+        int CONTACT_STATUS_TIMESTAMP = 8;
+        int CONTACT_STATUS_RES_PACKAGE = 9;
+        int CONTACT_STATUS_LABEL = 10;
     }
 
     private interface PhotoQuery {
@@ -321,7 +323,7 @@
     }
 
     /**
-     * Turn on/off showing of the aggregate bage element.
+     * Turn on/off showing of the aggregate badge element.
      */
     public void showAggregateBadge(boolean showBagde) {
         mAggregateBadge.setVisibility(showBagde ? View.VISIBLE : View.GONE);
@@ -380,8 +382,11 @@
      */
     public void setDisplayName(CharSequence displayName, CharSequence phoneticName) {
         mDisplayNameView.setText(displayName);
-        if (mPhoneticNameView != null) {
+        if (!TextUtils.isEmpty(phoneticName)) {
             mPhoneticNameView.setText(phoneticName);
+            mPhoneticNameView.setVisibility(View.VISIBLE);
+        } else {
+            mPhoneticNameView.setVisibility(View.GONE);
         }
     }
 
@@ -524,10 +529,9 @@
      * Bind the contact details provided by the given {@link Cursor}.
      */
     protected void bindContactInfo(Cursor c) {
-        // TODO: Bring back phonetic name
         final String displayName = c.getString(ContactQuery.DISPLAY_NAME);
-        final String phoneticName = null;
-        this.setDisplayName(displayName, null);
+        final String phoneticName = c.getString(ContactQuery.PHONETIC_NAME);
+        this.setDisplayName(displayName, phoneticName);
 
         final boolean starred = c.getInt(ContactQuery.STARRED) != 0;
         mStarredView.setChecked(starred);
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index d6b0808..efd025a 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -173,22 +173,6 @@
         getDevicePolicyManager().reportSuccessfulPasswordAttempt();
     }
 
-    public void setActivePasswordState(int mode, int length) {
-        int policyMode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-        switch (mode) {
-            case MODE_PATTERN:
-                policyMode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-                break;
-            case MODE_PIN:
-                policyMode = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
-                break;
-            case MODE_PASSWORD:
-                policyMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
-                break;
-        }
-        getDevicePolicyManager().setActivePasswordState(policyMode, length);
-    }
-
     /**
      * Check to see if a pattern matches the saved pattern.  If no pattern exists,
      * always returns true.
@@ -312,13 +296,15 @@
                 raf.write(hash, 0, hash.length);
             }
             raf.close();
+            DevicePolicyManager dpm = getDevicePolicyManager();
             if (pattern != null) {
                 setBoolean(PATTERN_EVER_CHOSEN_KEY, true);
                 setLong(PASSWORD_TYPE_KEY, MODE_PATTERN);
-                DevicePolicyManager dpm = (DevicePolicyManager)mContext.getSystemService(
-                        Context.DEVICE_POLICY_SERVICE);
                 dpm.setActivePasswordState(
                         DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, pattern.size());
+            } else {
+                dpm.setActivePasswordState(
+                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0);
             }
         } catch (FileNotFoundException fnfe) {
             // Cant do much, unless we want to fail over to using the settings provider
@@ -404,15 +390,17 @@
                 raf.write(hash, 0, hash.length);
             }
             raf.close();
+            DevicePolicyManager dpm = getDevicePolicyManager();
             if (password != null) {
                 int finalMode = adjustPasswordMode(password, mode);
                 if (mode < finalMode) {
                     mode = finalMode;
                 }
                 setLong(PASSWORD_TYPE_KEY, mode);
-                DevicePolicyManager dpm = (DevicePolicyManager)mContext.getSystemService(
-                        Context.DEVICE_POLICY_SERVICE);
                 dpm.setActivePasswordState(mode, password.length());
+            } else {
+                dpm.setActivePasswordState(
+                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0);
             }
         } catch (FileNotFoundException fnfe) {
             // Cant do much, unless we want to fail over to using the settings provider
@@ -550,7 +538,7 @@
      * @return Whether the lock pattern is enabled.
      */
     public boolean isLockPatternEnabled() {
-        return getBoolean(Settings.System.LOCK_PATTERN_ENABLED)
+        return getBoolean(Settings.Secure.LOCK_PATTERN_ENABLED)
                 && getLong(PASSWORD_TYPE_KEY, MODE_PATTERN) == MODE_PATTERN;
     }
 
@@ -558,35 +546,35 @@
      * Set whether the lock pattern is enabled.
      */
     public void setLockPatternEnabled(boolean enabled) {
-        setBoolean(Settings.System.LOCK_PATTERN_ENABLED, enabled);
+        setBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, enabled);
     }
 
     /**
      * @return Whether the visible pattern is enabled.
      */
     public boolean isVisiblePatternEnabled() {
-        return getBoolean(Settings.System.LOCK_PATTERN_VISIBLE);
+        return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE);
     }
 
     /**
      * Set whether the visible pattern is enabled.
      */
     public void setVisiblePatternEnabled(boolean enabled) {
-        setBoolean(Settings.System.LOCK_PATTERN_VISIBLE, enabled);
+        setBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, enabled);
     }
 
     /**
      * @return Whether tactile feedback for the pattern is enabled.
      */
     public boolean isTactileFeedbackEnabled() {
-        return getBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED);
+        return getBoolean(Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED);
     }
 
     /**
      * Set whether tactile feedback for the pattern is enabled.
      */
     public void setTactileFeedbackEnabled(boolean enabled) {
-        setBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, enabled);
+        setBoolean(Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, enabled);
     }
 
     /**
@@ -648,30 +636,22 @@
         return nextAlarm;
     }
 
-    private boolean getBoolean(String systemSettingKey) {
-        // STOPSHIP: these need to be moved to secure settings!
+    private boolean getBoolean(String secureSettingKey) {
         return 1 ==
-                android.provider.Settings.System.getInt(
-                        mContentResolver,
-                        systemSettingKey, 0);
+                android.provider.Settings.Secure.getInt(mContentResolver, secureSettingKey, 0);
     }
 
-    private void setBoolean(String systemSettingKey, boolean enabled) {
-        // STOPSHIP: these need to be moved to secure settings!
-        android.provider.Settings.System.putInt(
-                        mContentResolver,
-                        systemSettingKey,
-                        enabled ? 1 : 0);
+    private void setBoolean(String secureSettingKey, boolean enabled) {
+        android.provider.Settings.Secure.putInt(mContentResolver, secureSettingKey,
+                                                enabled ? 1 : 0);
     }
 
-    private long getLong(String systemSettingKey, long def) {
-        // STOPSHIP: these need to be moved to secure settings!
-        return android.provider.Settings.System.getLong(mContentResolver, systemSettingKey, def);
+    private long getLong(String secureSettingKey, long def) {
+        return android.provider.Settings.Secure.getLong(mContentResolver, secureSettingKey, def);
     }
 
-    private void setLong(String systemSettingKey, long value) {
-        // STOPSHIP: these need to be moved to secure settings!
-        android.provider.Settings.System.putLong(mContentResolver, systemSettingKey, value);
+    private void setLong(String secureSettingKey, long value) {
+        android.provider.Settings.Secure.putLong(mContentResolver, secureSettingKey, value);
     }
 
     public boolean isSecure() {
diff --git a/mms-common/java/com/android/mmscommon/mms/ContentType.java b/core/java/com/google/android/mms/ContentType.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/ContentType.java
rename to core/java/com/google/android/mms/ContentType.java
index f21eba8..94bc9fd 100644
--- a/mms-common/java/com/android/mmscommon/mms/ContentType.java
+++ b/core/java/com/google/android/mms/ContentType.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms;
+package com.google.android.mms;
 
 import java.util.ArrayList;
 
@@ -26,7 +26,6 @@
     public static final String MMS_GENERIC       = "application/vnd.wap.mms-generic";
     public static final String MULTIPART_MIXED   = "application/vnd.wap.multipart.mixed";
     public static final String MULTIPART_RELATED = "application/vnd.wap.multipart.related";
-    public static final String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative";
 
     public static final String TEXT_PLAIN        = "text/plain";
     public static final String TEXT_HTML         = "text/html";
diff --git a/mms-common/java/com/android/mmscommon/InvalidHeaderValueException.java b/core/java/com/google/android/mms/InvalidHeaderValueException.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/InvalidHeaderValueException.java
rename to core/java/com/google/android/mms/InvalidHeaderValueException.java
index 34d5871..73d7832 100644
--- a/mms-common/java/com/android/mmscommon/InvalidHeaderValueException.java
+++ b/core/java/com/google/android/mms/InvalidHeaderValueException.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon;
+package com.google.android.mms;
 
 /**
  * Thrown when an invalid header value was set.
diff --git a/mms-common/java/com/android/mmscommon/MmsException.java b/core/java/com/google/android/mms/MmsException.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/MmsException.java
rename to core/java/com/google/android/mms/MmsException.java
index 296a2c3..6ca0c7e 100644
--- a/mms-common/java/com/android/mmscommon/MmsException.java
+++ b/core/java/com/google/android/mms/MmsException.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon;
+package com.google.android.mms;
 
 /**
  * A generic exception that is thrown by the Mms client.
diff --git a/core/java/com/google/android/mms/package.html b/core/java/com/google/android/mms/package.html
new file mode 100755
index 0000000..c9f96a6
--- /dev/null
+++ b/core/java/com/google/android/mms/package.html
@@ -0,0 +1,5 @@
+<body>
+
+{@hide}
+
+</body>
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/AcknowledgeInd.java b/core/java/com/google/android/mms/pdu/AcknowledgeInd.java
similarity index 94%
rename from mms-common/java/com/android/mmscommon/mms/pdu/AcknowledgeInd.java
rename to core/java/com/google/android/mms/pdu/AcknowledgeInd.java
index d1243b2..0e96c60 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/AcknowledgeInd.java
+++ b/core/java/com/google/android/mms/pdu/AcknowledgeInd.java
@@ -15,10 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * M-Acknowledge.ind PDU.
diff --git a/core/java/com/google/android/mms/pdu/Base64.java b/core/java/com/google/android/mms/pdu/Base64.java
new file mode 100644
index 0000000..604bee0
--- /dev/null
+++ b/core/java/com/google/android/mms/pdu/Base64.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2007 Esmertec AG.
+ * Copyright (C) 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 com.google.android.mms.pdu;
+
+public class Base64 {
+    /**
+     * Used to get the number of Quadruples.
+     */
+    static final int FOURBYTE = 4;
+
+    /**
+     * Byte used to pad output.
+     */
+    static final byte PAD = (byte) '=';
+
+    /**
+     * The base length.
+     */
+    static final int BASELENGTH = 255;
+
+    // Create arrays to hold the base64 characters
+    private static byte[] base64Alphabet = new byte[BASELENGTH];
+
+    // Populating the character arrays
+    static {
+        for (int i = 0; i < BASELENGTH; i++) {
+            base64Alphabet[i] = (byte) -1;
+        }
+        for (int i = 'Z'; i >= 'A'; i--) {
+            base64Alphabet[i] = (byte) (i - 'A');
+        }
+        for (int i = 'z'; i >= 'a'; i--) {
+            base64Alphabet[i] = (byte) (i - 'a' + 26);
+        }
+        for (int i = '9'; i >= '0'; i--) {
+            base64Alphabet[i] = (byte) (i - '0' + 52);
+        }
+
+        base64Alphabet['+'] = 62;
+        base64Alphabet['/'] = 63;
+    }
+
+    /**
+     * Decodes Base64 data into octects
+     *
+     * @param base64Data Byte array containing Base64 data
+     * @return Array containing decoded data.
+     */
+    public static byte[] decodeBase64(byte[] base64Data) {
+        // RFC 2045 requires that we discard ALL non-Base64 characters
+        base64Data = discardNonBase64(base64Data);
+
+        // handle the edge case, so we don't have to worry about it later
+        if (base64Data.length == 0) {
+            return new byte[0];
+        }
+
+        int numberQuadruple = base64Data.length / FOURBYTE;
+        byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
+
+        // Throw away anything not in base64Data
+
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        {
+            // this sizes the output array properly - rlw
+            int lastData = base64Data.length;
+            // ignore the '=' padding
+            while (base64Data[lastData - 1] == PAD) {
+                if (--lastData == 0) {
+                    return new byte[0];
+                }
+            }
+            decodedData = new byte[lastData - numberQuadruple];
+        }
+
+        for (int i = 0; i < numberQuadruple; i++) {
+            dataIndex = i * 4;
+            marker0 = base64Data[dataIndex + 2];
+            marker1 = base64Data[dataIndex + 3];
+
+            b1 = base64Alphabet[base64Data[dataIndex]];
+            b2 = base64Alphabet[base64Data[dataIndex + 1]];
+
+            if (marker0 != PAD && marker1 != PAD) {
+                //No PAD e.g 3cQl
+                b3 = base64Alphabet[marker0];
+                b4 = base64Alphabet[marker1];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
+            } else if (marker0 == PAD) {
+                //Two PAD e.g. 3c[Pad][Pad]
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+            } else if (marker1 == PAD) {
+                //One PAD e.g. 3cQ[Pad]
+                b3 = base64Alphabet[marker0];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            }
+            encodedIndex += 3;
+        }
+        return decodedData;
+    }
+
+    /**
+     * Check octect wheter it is a base64 encoding.
+     *
+     * @param octect to be checked byte
+     * @return ture if it is base64 encoding, false otherwise.
+     */
+    private static boolean isBase64(byte octect) {
+        if (octect == PAD) {
+            return true;
+        } else if (base64Alphabet[octect] == -1) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    /**
+     * Discards any characters outside of the base64 alphabet, per
+     * the requirements on page 25 of RFC 2045 - "Any characters
+     * outside of the base64 alphabet are to be ignored in base64
+     * encoded data."
+     *
+     * @param data The base-64 encoded data to groom
+     * @return The data, less non-base64 characters (see RFC 2045).
+     */
+    static byte[] discardNonBase64(byte[] data) {
+        byte groomedData[] = new byte[data.length];
+        int bytesCopied = 0;
+
+        for (int i = 0; i < data.length; i++) {
+            if (isBase64(data[i])) {
+                groomedData[bytesCopied++] = data[i];
+            }
+        }
+
+        byte packedData[] = new byte[bytesCopied];
+
+        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+        return packedData;
+    }
+}
diff --git a/mms-common/java/com/android/mmscommon/CharacterSets.java b/core/java/com/google/android/mms/pdu/CharacterSets.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/CharacterSets.java
rename to core/java/com/google/android/mms/pdu/CharacterSets.java
index f19b078..4e22ca5 100644
--- a/mms-common/java/com/android/mmscommon/CharacterSets.java
+++ b/core/java/com/google/android/mms/pdu/CharacterSets.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon;
+package com.google.android.mms.pdu;
 
 import java.io.UnsupportedEncodingException;
 import java.util.HashMap;
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/DeliveryInd.java b/core/java/com/google/android/mms/pdu/DeliveryInd.java
similarity index 94%
rename from mms-common/java/com/android/mmscommon/mms/pdu/DeliveryInd.java
rename to core/java/com/google/android/mms/pdu/DeliveryInd.java
index e83729b..dafa8d1 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/DeliveryInd.java
+++ b/core/java/com/google/android/mms/pdu/DeliveryInd.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * M-Delivery.Ind Pdu.
diff --git a/mms-common/java/com/android/mmscommon/EncodedStringValue.java b/core/java/com/google/android/mms/pdu/EncodedStringValue.java
similarity index 99%
rename from mms-common/java/com/android/mmscommon/EncodedStringValue.java
rename to core/java/com/google/android/mms/pdu/EncodedStringValue.java
index 0a4424e..a27962d 100644
--- a/mms-common/java/com/android/mmscommon/EncodedStringValue.java
+++ b/core/java/com/google/android/mms/pdu/EncodedStringValue.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon;
+package com.google.android.mms.pdu;
 
 import android.util.Config;
 import android.util.Log;
@@ -269,7 +269,7 @@
 
         return new EncodedStringValue(value.mCharacterSet, value.mData);
     }
-
+    
     public static EncodedStringValue[] encodeStrings(String[] array) {
         int count = array.length;
         if (count > 0) {
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/GenericPdu.java b/core/java/com/google/android/mms/pdu/GenericPdu.java
similarity index 93%
rename from mms-common/java/com/android/mmscommon/mms/pdu/GenericPdu.java
rename to core/java/com/google/android/mms/pdu/GenericPdu.java
index c38e502..705de6a 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/GenericPdu.java
+++ b/core/java/com/google/android/mms/pdu/GenericPdu.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 public class GenericPdu {
     /**
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/MultimediaMessagePdu.java b/core/java/com/google/android/mms/pdu/MultimediaMessagePdu.java
similarity index 94%
rename from mms-common/java/com/android/mmscommon/mms/pdu/MultimediaMessagePdu.java
rename to core/java/com/google/android/mms/pdu/MultimediaMessagePdu.java
index 04fde2d..5a85e0e 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/MultimediaMessagePdu.java
+++ b/core/java/com/google/android/mms/pdu/MultimediaMessagePdu.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * Multimedia message PDU.
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/NotificationInd.java b/core/java/com/google/android/mms/pdu/NotificationInd.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/mms/pdu/NotificationInd.java
rename to core/java/com/google/android/mms/pdu/NotificationInd.java
index 24f17b09..c56cba6 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/NotificationInd.java
+++ b/core/java/com/google/android/mms/pdu/NotificationInd.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * M-Notification.ind PDU.
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/NotifyRespInd.java b/core/java/com/google/android/mms/pdu/NotifyRespInd.java
similarity index 95%
rename from mms-common/java/com/android/mmscommon/mms/pdu/NotifyRespInd.java
rename to core/java/com/google/android/mms/pdu/NotifyRespInd.java
index c2e2b26..2cc2fce 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/NotifyRespInd.java
+++ b/core/java/com/google/android/mms/pdu/NotifyRespInd.java
@@ -15,10 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * M-NofifyResp.ind PDU.
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduBody.java b/core/java/com/google/android/mms/pdu/PduBody.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduBody.java
rename to core/java/com/google/android/mms/pdu/PduBody.java
index cc28d80..fa0416c 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduBody.java
+++ b/core/java/com/google/android/mms/pdu/PduBody.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
 import java.util.HashMap;
 import java.util.Map;
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduComposer.java b/core/java/com/google/android/mms/pdu/PduComposer.java
similarity index 99%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduComposer.java
rename to core/java/com/google/android/mms/pdu/PduComposer.java
index bb3116d..8940945 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduComposer.java
+++ b/core/java/com/google/android/mms/pdu/PduComposer.java
@@ -15,10 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
-
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.PduHeaders;
+package com.google.android.mms.pdu;
 
 import android.content.ContentResolver;
 import android.content.Context;
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduContentTypes.java b/core/java/com/google/android/mms/pdu/PduContentTypes.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduContentTypes.java
rename to core/java/com/google/android/mms/pdu/PduContentTypes.java
index 3f971fd..7799e0e 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduContentTypes.java
+++ b/core/java/com/google/android/mms/pdu/PduContentTypes.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
 public class PduContentTypes {
     /**
diff --git a/mms-common/java/com/android/mmscommon/PduHeaders.java b/core/java/com/google/android/mms/pdu/PduHeaders.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/PduHeaders.java
rename to core/java/com/google/android/mms/pdu/PduHeaders.java
index d8f1211..4313815 100644
--- a/mms-common/java/com/android/mmscommon/PduHeaders.java
+++ b/core/java/com/google/android/mms/pdu/PduHeaders.java
@@ -15,7 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon;
+package com.google.android.mms.pdu;
+
+import com.google.android.mms.InvalidHeaderValueException;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -337,7 +339,7 @@
      *          with specified header field. Return 0 if
      *          the value is not set.
      */
-    public int getOctet(int field) {
+    protected int getOctet(int field) {
         Integer octet = (Integer) mHeaderMap.get(field);
         if (null == octet) {
             return 0;
@@ -353,7 +355,7 @@
      * @param field the field
      * @throws InvalidHeaderValueException if the value is invalid.
      */
-    public void setOctet(int value, int field)
+    protected void setOctet(int value, int field)
             throws InvalidHeaderValueException{
         /**
          * Check whether this field can be set for specific
@@ -497,7 +499,7 @@
      * @return the TextString value of the pdu header
      *          with specified header field
      */
-    public byte[] getTextString(int field) {
+    protected byte[] getTextString(int field) {
         return (byte[]) mHeaderMap.get(field);
     }
 
@@ -510,7 +512,7 @@
      *          with specified header field
      * @throws NullPointerException if the value is null.
      */
-    public void setTextString(byte[] value, int field) {
+    protected void setTextString(byte[] value, int field) {
         /**
          * Check whether this field can be set for specific
          * header and check validity of the field.
@@ -546,7 +548,7 @@
      * @return the EncodedStringValue value of the pdu header
      *          with specified header field
      */
-    public EncodedStringValue getEncodedStringValue(int field) {
+    protected EncodedStringValue getEncodedStringValue(int field) {
         return (EncodedStringValue) mHeaderMap.get(field);
     }
 
@@ -557,7 +559,7 @@
      * @return the EncodeStringValue array of the pdu header
      *          with specified header field
      */
-    public EncodedStringValue[] getEncodedStringValues(int field) {
+    protected EncodedStringValue[] getEncodedStringValues(int field) {
         ArrayList<EncodedStringValue> list =
                 (ArrayList<EncodedStringValue>) mHeaderMap.get(field);
         if (null == list) {
@@ -576,7 +578,7 @@
      *          with specified header field
      * @throws NullPointerException if the value is null.
      */
-    public void setEncodedStringValue(EncodedStringValue value, int field) {
+    protected void setEncodedStringValue(EncodedStringValue value, int field) {
         /**
          * Check whether this field can be set for specific
          * header and check validity of the field.
@@ -613,7 +615,7 @@
      *          with specified header field
      * @throws NullPointerException if the value is null.
      */
-    public void setEncodedStringValues(EncodedStringValue[] value, int field) {
+    protected void setEncodedStringValues(EncodedStringValue[] value, int field) {
         /**
          * Check whether this field can be set for specific
          * header and check validity of the field.
@@ -646,7 +648,7 @@
      * @param field the field
      * @throws NullPointerException if the value is null.
      */
-    public void appendEncodedStringValue(EncodedStringValue value,
+    protected void appendEncodedStringValue(EncodedStringValue value,
                                     int field) {
         if (null == value) {
             throw new NullPointerException();
@@ -678,7 +680,7 @@
      *          with specified header field. if return -1, the
      *          field is not existed in pdu header.
      */
-    public long getLongInteger(int field) {
+    protected long getLongInteger(int field) {
         Long longInteger = (Long) mHeaderMap.get(field);
         if (null == longInteger) {
             return -1;
@@ -693,7 +695,7 @@
      * @param value the value
      * @param field the field
      */
-    public void setLongInteger(long value, int field) {
+    protected void setLongInteger(long value, int field) {
         /**
          * Check whether this field can be set for specific
          * header and check validity of the field.
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduParser.java b/core/java/com/google/android/mms/pdu/PduParser.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduParser.java
rename to core/java/com/google/android/mms/pdu/PduParser.java
index 6a58ba6..d465c5a 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduParser.java
+++ b/core/java/com/google/android/mms/pdu/PduParser.java
@@ -15,17 +15,13 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.CharacterSets;
-import com.android.mmscommon.ContentType;
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.ContentType;
+import com.google.android.mms.InvalidHeaderValueException;
 
 import android.util.Config;
 import android.util.Log;
-import android.util.base64.Base64;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -161,11 +157,9 @@
                 }
                 String ctTypeStr = new String(contentType);
                 if (ctTypeStr.equals(ContentType.MULTIPART_MIXED)
-                        || ctTypeStr.equals(ContentType.MULTIPART_RELATED)
-                        || ctTypeStr.equals(ContentType.MULTIPART_ALTERNATIVE)) {
+                        || ctTypeStr.equals(ContentType.MULTIPART_RELATED)) {
                     // The MMS content type must be "application/vnd.wap.multipart.mixed"
                     // or "application/vnd.wap.multipart.related"
-                    // or "application/vnd.wap.multipart.alternative"
                     return retrieveConf;
                 }
                 return null;
@@ -791,7 +785,7 @@
                     String encoding = new String(partDataEncoding);
                     if (encoding.equalsIgnoreCase(PduPart.P_BASE64)) {
                         // Decode "base64" into "binary".
-                        partData = Base64.decode(partData, Base64.DEFAULT);
+                        partData = Base64.decodeBase64(partData);
                     } else if (encoding.equalsIgnoreCase(PduPart.P_QUOTED_PRINTABLE)) {
                         // Decode "quoted-printable" into "binary".
                         partData = QuotedPrintable.decodeQuotedPrintable(partData);
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduPart.java b/core/java/com/google/android/mms/pdu/PduPart.java
similarity index 99%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduPart.java
rename to core/java/com/google/android/mms/pdu/PduPart.java
index 7d51b86..b43e388 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduPart.java
+++ b/core/java/com/google/android/mms/pdu/PduPart.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
 import android.net.Uri;
 
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/PduPersister.java b/core/java/com/google/android/mms/pdu/PduPersister.java
similarity index 96%
rename from mms-common/java/com/android/mmscommon/mms/pdu/PduPersister.java
rename to core/java/com/google/android/mms/pdu/PduPersister.java
index d92f0e1..2a1f23a 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/PduPersister.java
+++ b/core/java/com/google/android/mms/pdu/PduPersister.java
@@ -15,19 +15,14 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.mms.pdu.PduPersister;
-
-import com.android.mmscommon.ContentType;
-import com.android.mmscommon.CharacterSets;
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.MmsException;
-import com.android.mmscommon.PduHeaders;
-import com.android.mmscommon.mms.util.PduCache;
-import com.android.mmscommon.mms.util.PduCacheEntry;
-import android.database.sqlite.SqliteWrapper;
+import com.google.android.mms.ContentType;
+import com.google.android.mms.InvalidHeaderValueException;
+import com.google.android.mms.MmsException;
+import com.google.android.mms.util.PduCache;
+import com.google.android.mms.util.PduCacheEntry;
+import com.google.android.mms.util.SqliteWrapper;
 
 import android.content.ContentResolver;
 import android.content.ContentUris;
@@ -36,13 +31,13 @@
 import android.database.Cursor;
 import android.database.DatabaseUtils;
 import android.net.Uri;
-import com.android.mmscommon.telephony.TelephonyProvider;
-import com.android.mmscommon.telephony.TelephonyProvider.Mms;
-import com.android.mmscommon.telephony.TelephonyProvider.MmsSms;
-import com.android.mmscommon.telephony.TelephonyProvider.Threads;
-import com.android.mmscommon.telephony.TelephonyProvider.Mms.Addr;
-import com.android.mmscommon.telephony.TelephonyProvider.Mms.Part;
-import com.android.mmscommon.telephony.TelephonyProvider.MmsSms.PendingMessages;
+import android.provider.Telephony;
+import android.provider.Telephony.Mms;
+import android.provider.Telephony.MmsSms;
+import android.provider.Telephony.Threads;
+import android.provider.Telephony.Mms.Addr;
+import android.provider.Telephony.Mms.Part;
+import android.provider.Telephony.MmsSms.PendingMessages;
 import android.text.TextUtils;
 import android.util.Config;
 import android.util.Log;
@@ -60,6 +55,7 @@
 import java.util.Set;
 import java.util.Map.Entry;
 
+import com.google.android.mms.pdu.EncodedStringValue;
 
 /**
  * This class is the high-level manager of PDU storage.
@@ -426,12 +422,8 @@
                     // Store simple string values directly in the database instead of an
                     // external file.  This makes the text searchable and retrieval slightly
                     // faster.
-                    if (ContentType.TEXT_PLAIN.equals(type) || ContentType.APP_SMIL.equals(type)
-                            || ContentType.TEXT_HTML.equals(type)) {
+                    if ("text/plain".equals(type) || "application/smil".equals(type)) {
                         String text = c.getString(PART_COLUMN_TEXT);
-                        if (text == null) {
-                            text = "";
-                        }
                         byte [] blob = new EncodedStringValue(text).getTextString();
                         baos.write(blob, 0, blob.length);
                     } else {
@@ -743,11 +735,9 @@
 
         try {
             byte[] data = part.getData();
-            if (ContentType.TEXT_PLAIN.equals(contentType)
-                    || ContentType.APP_SMIL.equals(contentType)
-                    || ContentType.TEXT_HTML.equals(contentType)) {
+            if ("text/plain".equals(contentType) || "application/smil".equals(contentType)) {
                 ContentValues cv = new ContentValues();
-                cv.put(TelephonyProvider.Mms.Part.TEXT, new EncodedStringValue(data).getString());
+                cv.put(Telephony.Mms.Part.TEXT, new EncodedStringValue(data).getString());
                 if (mContentResolver.update(uri, cv, null, null) != 1) {
                     throw new MmsException("unable to update " + uri.toString());
                 }
@@ -868,7 +858,7 @@
         } else {
             values.put(Mms.SUBJECT, "");
         }
-
+        
         long messageSize = sendReq.getMessageSize();
         if (messageSize > 0) {
             values.put(Mms.MESSAGE_SIZE, messageSize);
@@ -1145,10 +1135,6 @@
             }
         }
 
-        // mark "read" and "seen"
-        values.put(Mms.READ, 0);
-        values.put(Mms.SEEN, 0);
-
         Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
         if (res == null) {
             throw new MmsException("persist() failed: return null.");
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/QuotedPrintable.java b/core/java/com/google/android/mms/pdu/QuotedPrintable.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/mms/pdu/QuotedPrintable.java
rename to core/java/com/google/android/mms/pdu/QuotedPrintable.java
index e9da7df..a34ed12 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/QuotedPrintable.java
+++ b/core/java/com/google/android/mms/pdu/QuotedPrintable.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
 import java.io.ByteArrayOutputStream;
 
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/ReadOrigInd.java b/core/java/com/google/android/mms/pdu/ReadOrigInd.java
similarity index 95%
rename from mms-common/java/com/android/mmscommon/mms/pdu/ReadOrigInd.java
rename to core/java/com/google/android/mms/pdu/ReadOrigInd.java
index 9678784..1bfc0bb 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/ReadOrigInd.java
+++ b/core/java/com/google/android/mms/pdu/ReadOrigInd.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 public class ReadOrigInd extends GenericPdu {
     /**
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/ReadRecInd.java b/core/java/com/google/android/mms/pdu/ReadRecInd.java
similarity index 95%
rename from mms-common/java/com/android/mmscommon/mms/pdu/ReadRecInd.java
rename to core/java/com/google/android/mms/pdu/ReadRecInd.java
index c1efbbc..880e3ac 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/ReadRecInd.java
+++ b/core/java/com/google/android/mms/pdu/ReadRecInd.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 public class ReadRecInd extends GenericPdu {
     /**
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/RetrieveConf.java b/core/java/com/google/android/mms/pdu/RetrieveConf.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/mms/pdu/RetrieveConf.java
rename to core/java/com/google/android/mms/pdu/RetrieveConf.java
index 442949e..98e67c0 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/RetrieveConf.java
+++ b/core/java/com/google/android/mms/pdu/RetrieveConf.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 /**
  * M-Retrive.conf Pdu.
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/SendConf.java b/core/java/com/google/android/mms/pdu/SendConf.java
similarity index 94%
rename from mms-common/java/com/android/mmscommon/mms/pdu/SendConf.java
rename to core/java/com/google/android/mms/pdu/SendConf.java
index 0a57b6b..0568fe79 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/SendConf.java
+++ b/core/java/com/google/android/mms/pdu/SendConf.java
@@ -15,11 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 public class SendConf extends GenericPdu {
     /**
diff --git a/mms-common/java/com/android/mmscommon/mms/pdu/SendReq.java b/core/java/com/google/android/mms/pdu/SendReq.java
similarity index 97%
rename from mms-common/java/com/android/mmscommon/mms/pdu/SendReq.java
rename to core/java/com/google/android/mms/pdu/SendReq.java
index 5da4719..597cd00 100644
--- a/mms-common/java/com/android/mmscommon/mms/pdu/SendReq.java
+++ b/core/java/com/google/android/mms/pdu/SendReq.java
@@ -15,13 +15,11 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.pdu;
+package com.google.android.mms.pdu;
 
 import android.util.Log;
 
-import com.android.mmscommon.EncodedStringValue;
-import com.android.mmscommon.InvalidHeaderValueException;
-import com.android.mmscommon.PduHeaders;
+import com.google.android.mms.InvalidHeaderValueException;
 
 public class SendReq extends MultimediaMessagePdu {
     private static final String TAG = "SendReq";
diff --git a/core/java/com/google/android/mms/pdu/package.html b/core/java/com/google/android/mms/pdu/package.html
new file mode 100755
index 0000000..c9f96a6
--- /dev/null
+++ b/core/java/com/google/android/mms/pdu/package.html
@@ -0,0 +1,5 @@
+<body>
+
+{@hide}
+
+</body>
diff --git a/mms-common/java/com/android/mmscommon/mms/util/AbstractCache.java b/core/java/com/google/android/mms/util/AbstractCache.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/util/AbstractCache.java
rename to core/java/com/google/android/mms/util/AbstractCache.java
index 10a6fce..670439c 100644
--- a/mms-common/java/com/android/mmscommon/mms/util/AbstractCache.java
+++ b/core/java/com/google/android/mms/util/AbstractCache.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.util;
+package com.google.android.mms.util;
 
 import android.util.Config;
 import android.util.Log;
diff --git a/mms-common/java/com/android/mmscommon/mms/util/PduCache.java b/core/java/com/google/android/mms/util/PduCache.java
similarity index 98%
rename from mms-common/java/com/android/mmscommon/mms/util/PduCache.java
rename to core/java/com/google/android/mms/util/PduCache.java
index ca5432f..7c3fad7 100644
--- a/mms-common/java/com/android/mmscommon/mms/util/PduCache.java
+++ b/core/java/com/google/android/mms/util/PduCache.java
@@ -15,12 +15,12 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.util;
+package com.google.android.mms.util;
 
 import android.content.ContentUris;
 import android.content.UriMatcher;
 import android.net.Uri;
-import com.android.mmscommon.telephony.TelephonyProvider.Mms;
+import android.provider.Telephony.Mms;
 import android.util.Config;
 import android.util.Log;
 
diff --git a/mms-common/java/com/android/mmscommon/mms/util/PduCacheEntry.java b/core/java/com/google/android/mms/util/PduCacheEntry.java
similarity index 92%
rename from mms-common/java/com/android/mmscommon/mms/util/PduCacheEntry.java
rename to core/java/com/google/android/mms/util/PduCacheEntry.java
index aed741d..8b41386 100644
--- a/mms-common/java/com/android/mmscommon/mms/util/PduCacheEntry.java
+++ b/core/java/com/google/android/mms/util/PduCacheEntry.java
@@ -15,9 +15,9 @@
  * limitations under the License.
  */
 
-package com.android.mmscommon.mms.util;
+package com.google.android.mms.util;
 
-import com.android.mmscommon.mms.pdu.GenericPdu;
+import com.google.android.mms.pdu.GenericPdu;
 
 public final class PduCacheEntry {
     private final GenericPdu mPdu;
diff --git a/core/java/com/google/android/mms/util/SqliteWrapper.java b/core/java/com/google/android/mms/util/SqliteWrapper.java
new file mode 100644
index 0000000..bcdac22
--- /dev/null
+++ b/core/java/com/google/android/mms/util/SqliteWrapper.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2008 Esmertec AG.
+ * Copyright (C) 2008 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 com.google.android.mms.util;
+
+import android.app.ActivityManager;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteException;
+import android.net.Uri;
+import android.util.Log;
+import android.widget.Toast;
+
+public final class SqliteWrapper {
+    private static final String TAG = "SqliteWrapper";
+    private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE
+                = "unable to open database file";
+
+    private SqliteWrapper() {
+        // Forbidden being instantiated.
+    }
+
+    // FIXME: It looks like outInfo.lowMemory does not work well as we expected.
+    // after run command: adb shell fillup -p 100, outInfo.lowMemory is still false.
+    private static boolean isLowMemory(Context context) {
+        if (null == context) {
+            return false;
+        }
+
+        ActivityManager am = (ActivityManager)
+                        context.getSystemService(Context.ACTIVITY_SERVICE);
+        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
+        am.getMemoryInfo(outInfo);
+
+        return outInfo.lowMemory;
+    }
+
+    // FIXME: need to optimize this method.
+    private static boolean isLowMemory(SQLiteException e) {
+        return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE);
+    }
+
+    public static void checkSQLiteException(Context context, SQLiteException e) {
+        if (isLowMemory(e)) {
+            Toast.makeText(context, com.android.internal.R.string.low_memory,
+                    Toast.LENGTH_SHORT).show();
+        } else {
+            throw e;
+        }
+    }
+
+    public static Cursor query(Context context, ContentResolver resolver, Uri uri,
+            String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+        try {
+            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
+        } catch (SQLiteException e) {
+            Log.e(TAG, "Catch a SQLiteException when query: ", e);
+            checkSQLiteException(context, e);
+            return null;
+        }
+    }
+
+    public static boolean requery(Context context, Cursor cursor) {
+        try {
+            return cursor.requery();
+        } catch (SQLiteException e) {
+            Log.e(TAG, "Catch a SQLiteException when requery: ", e);
+            checkSQLiteException(context, e);
+            return false;
+        }
+    }
+    public static int update(Context context, ContentResolver resolver, Uri uri,
+            ContentValues values, String where, String[] selectionArgs) {
+        try {
+            return resolver.update(uri, values, where, selectionArgs);
+        } catch (SQLiteException e) {
+            Log.e(TAG, "Catch a SQLiteException when update: ", e);
+            checkSQLiteException(context, e);
+            return -1;
+        }
+    }
+
+    public static int delete(Context context, ContentResolver resolver, Uri uri,
+            String where, String[] selectionArgs) {
+        try {
+            return resolver.delete(uri, where, selectionArgs);
+        } catch (SQLiteException e) {
+            Log.e(TAG, "Catch a SQLiteException when delete: ", e);
+            checkSQLiteException(context, e);
+            return -1;
+        }
+    }
+
+    public static Uri insert(Context context, ContentResolver resolver,
+            Uri uri, ContentValues values) {
+        try {
+            return resolver.insert(uri, values);
+        } catch (SQLiteException e) {
+            Log.e(TAG, "Catch a SQLiteException when insert: ", e);
+            checkSQLiteException(context, e);
+            return null;
+        }
+    }
+}
diff --git a/core/java/com/google/android/mms/util/package.html b/core/java/com/google/android/mms/util/package.html
new file mode 100755
index 0000000..c9f96a6
--- /dev/null
+++ b/core/java/com/google/android/mms/util/package.html
@@ -0,0 +1,5 @@
+<body>
+
+{@hide}
+
+</body>
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/jni/android_database_SQLiteDatabase.cpp b/core/jni/android_database_SQLiteDatabase.cpp
index bd55e83..44e091d 100644
--- a/core/jni/android_database_SQLiteDatabase.cpp
+++ b/core/jni/android_database_SQLiteDatabase.cpp
@@ -367,7 +367,7 @@
     if (err != SQLITE_OK) {
         LOGE("register_localized_collators() failed setting locale\n");
         throw_sqlite3_exception(env, handle);
-        goto done;
+        goto rollback;
     }
 
     err = sqlite3_exec(handle, "DELETE FROM " ANDROID_TABLE, NULL, NULL, NULL);
@@ -415,7 +415,9 @@
     }
 
 rollback:
-    sqlite3_exec(handle, "ROLLBACK TRANSACTION", NULL, NULL, NULL);
+    if (err != SQLITE_OK) {
+        sqlite3_exec(handle, "ROLLBACK TRANSACTION", NULL, NULL, NULL);
+    }
 
 done:
     if (locale8 != NULL) env->ReleaseStringUTFChars(localeString, locale8);
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/layout-ja/contact_header_name.xml b/core/res/res/layout-ja/contact_header_name.xml
deleted file mode 100644
index 39d5593..0000000
--- a/core/res/res/layout-ja/contact_header_name.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2009 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.
--->
-
-<!-- In Japanese-language locales, the "Name" field contains two separate
-     TextViews: the name itself, and also the phonetic ("furigana") field. -->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
-    android:layout_width="0dip"
-    android:layout_weight="1"
-    android:layout_height="match_parent">
-
-    <TextView android:id="@+id/name"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:textAppearance="?android:attr/textAppearanceMedium"
-        android:textStyle="bold"
-        android:shadowColor="#BB000000"
-        android:shadowRadius="2.75"
-        />
-
-    <TextView android:id="@+id/phonetic_name"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:textAppearance="?android:attr/textAppearanceSmall"
-        />
-
-</LinearLayout>
diff --git a/core/res/res/layout/contact_header.xml b/core/res/res/layout/contact_header.xml
index e5b6c35..ecbe41b 100644
--- a/core/res/res/layout/contact_header.xml
+++ b/core/res/res/layout/contact_header.xml
@@ -50,18 +50,35 @@
                 android:src="@drawable/ic_aggregated"
             />
 
-            <!-- "Name" field is locale-specific. -->
-            <include layout="@layout/contact_header_name"/>
-
+            <TextView android:id="@+id/name"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:ellipsize="end"
+                android:textAppearance="?android:attr/textAppearanceMedium"
+                android:textStyle="bold"
+                android:shadowColor="#BB000000"
+                android:shadowRadius="2.75"
+                android:layout_marginBottom="-4dip"
+                />
         </LinearLayout>
 
+        <TextView android:id="@+id/phonetic_name"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:textAppearance="?android:attr/textAppearanceSmall"
+            android:singleLine="true"
+            android:ellipsize="end"
+            android:layout_marginTop="-2dip"
+        />
+
         <TextView android:id="@+id/status"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:textAppearance="?android:attr/textAppearanceSmall"
             android:singleLine="true"
             android:ellipsize="end"
-            android:layout_marginTop="-4dip"
+            android:layout_marginTop="-2dip"
         />
 
         <TextView android:id="@+id/status_date"
diff --git a/core/res/res/layout/contact_header_name.xml b/core/res/res/layout/contact_header_name.xml
deleted file mode 100644
index 24db2f2..0000000
--- a/core/res/res/layout/contact_header_name.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2009 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.
--->
-
-<!-- In the default locale, the "Name" field is a single TextView -->
-<TextView xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/name"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:textAppearance="?android:attr/textAppearanceMedium"
-    android:textStyle="bold"
-    android:singleLine="true"
-    android:ellipsize="end"
-    android:layout_gravity="center_vertical"
-    android:shadowColor="#BB000000"
-    android:shadowRadius="2.75"
-    />
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/data/etc/Android.mk b/data/etc/Android.mk
index 041c5d3..71a9a15 100644
--- a/data/etc/Android.mk
+++ b/data/etc/Android.mk
@@ -34,18 +34,18 @@
 include $(BUILD_PREBUILT)
 
 ########################
-include $(CLEAR_VARS)
+#include $(CLEAR_VARS)
 
-LOCAL_MODULE := required_hardware.xml
+#LOCAL_MODULE := required_hardware.xml
 
-LOCAL_MODULE_TAGS := user
+#LOCAL_MODULE_TAGS := user
 
-LOCAL_MODULE_CLASS := ETC
+#LOCAL_MODULE_CLASS := ETC
 
 # This will install the file in /system/etc/permissions
 #
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/permissions
+#LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/permissions
 
-LOCAL_SRC_FILES := $(LOCAL_MODULE)
+#LOCAL_SRC_FILES := $(LOCAL_MODULE)
 
-include $(BUILD_PREBUILT)
+#include $(BUILD_PREBUILT)
diff --git a/data/etc/android.hardware.camera.xml b/data/etc/android.hardware.camera.xml
new file mode 100644
index 0000000..00a1ed7
--- /dev/null
+++ b/data/etc/android.hardware.camera.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- This is the standard set of features for a non auto-focus camera. -->
+<permissions>
+    <feature name="android.hardware.camera" />
+</permissions>
diff --git a/data/etc/required_hardware.xml b/data/etc/android.hardware.location.gps.xml
similarity index 66%
rename from data/etc/required_hardware.xml
rename to data/etc/android.hardware.location.gps.xml
index 3ffe6b2..72ab732 100644
--- a/data/etc/required_hardware.xml
+++ b/data/etc/android.hardware.location.gps.xml
@@ -14,16 +14,9 @@
      limitations under the License.
 -->
 
-<!-- These are the hardware features that all devices must possess.
-     These are always added for you by the build system, you do not need
-     to add them yourself. -->
+<!-- These are the location-related features for devices that include GPS. -->
 <permissions>
     <feature name="android.hardware.location" />
     <feature name="android.hardware.location.network" />
     <feature name="android.hardware.location.gps" />
-    <feature name="android.hardware.sensor.compass" />
-    <feature name="android.hardware.sensor.accelerometer" />
-    <feature name="android.hardware.bluetooth" />
-    <feature name="android.hardware.wifi" />
-    <feature name="android.hardware.touchscreen" />
 </permissions>
diff --git a/data/etc/required_hardware.xml b/data/etc/android.hardware.location.xml
similarity index 62%
copy from data/etc/required_hardware.xml
copy to data/etc/android.hardware.location.xml
index 3ffe6b2..ab901cf 100644
--- a/data/etc/required_hardware.xml
+++ b/data/etc/android.hardware.location.xml
@@ -14,16 +14,9 @@
      limitations under the License.
 -->
 
-<!-- These are the hardware features that all devices must possess.
-     These are always added for you by the build system, you do not need
-     to add them yourself. -->
+<!-- These are the location features for devices that do not include GPS. Note
+     that network location is required for all devices. -->
 <permissions>
     <feature name="android.hardware.location" />
     <feature name="android.hardware.location.network" />
-    <feature name="android.hardware.location.gps" />
-    <feature name="android.hardware.sensor.compass" />
-    <feature name="android.hardware.sensor.accelerometer" />
-    <feature name="android.hardware.bluetooth" />
-    <feature name="android.hardware.wifi" />
-    <feature name="android.hardware.touchscreen" />
 </permissions>
diff --git a/data/etc/android.hardware.sensor.accelerometer.xml b/data/etc/android.hardware.sensor.accelerometer.xml
new file mode 100644
index 0000000..22f18b8
--- /dev/null
+++ b/data/etc/android.hardware.sensor.accelerometer.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- Feature for devices with an accelerometer sensor. -->
+<permissions>
+    <feature name="android.hardware.sensor.accelerometer" />
+</permissions>
diff --git a/data/etc/android.hardware.sensor.compass.xml b/data/etc/android.hardware.sensor.compass.xml
new file mode 100644
index 0000000..963847d
--- /dev/null
+++ b/data/etc/android.hardware.sensor.compass.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- Feature for devices with a compass. -->
+<permissions>
+    <feature name="android.hardware.sensor.compass" />
+</permissions>
diff --git a/data/etc/android.hardware.telephony.cdma.xml b/data/etc/android.hardware.telephony.cdma.xml
index 72e0485..082378d5 100644
--- a/data/etc/android.hardware.telephony.cdma.xml
+++ b/data/etc/android.hardware.telephony.cdma.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 
-<!-- This is the standard set of features for a CDMA phone. -->
+<!-- This is the standard set of telephony features for a CDMA phone. -->
 <permissions>
     <feature name="android.hardware.telephony" />
     <feature name="android.hardware.telephony.cdma" />
diff --git a/data/etc/android.hardware.telephony.gsm.xml b/data/etc/android.hardware.telephony.gsm.xml
index ffde433..7927fa8 100644
--- a/data/etc/android.hardware.telephony.gsm.xml
+++ b/data/etc/android.hardware.telephony.gsm.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 
-<!-- This is the standard set of features for a GSM phone. -->
+<!-- This is the standard set of telephony features for a GSM phone. -->
 <permissions>
     <feature name="android.hardware.telephony" />
     <feature name="android.hardware.telephony.gsm" />
diff --git a/data/etc/android.hardware.touchscreen.multitouch.distinct.xml b/data/etc/android.hardware.touchscreen.multitouch.distinct.xml
new file mode 100644
index 0000000..a3c116a
--- /dev/null
+++ b/data/etc/android.hardware.touchscreen.multitouch.distinct.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- This is the standard set of features for a touchscreen that supports
+     independently-trackable multiple-finger multitouch. -->
+<permissions>
+    <feature name="android.hardware.touchscreen" />
+    <feature name="android.hardware.touchscreen.multitouch" />
+    <feature name="android.hardware.touchscreen.multitouch.distinct" />
+</permissions>
diff --git a/data/etc/android.hardware.touchscreen.multitouch.xml b/data/etc/android.hardware.touchscreen.multitouch.xml
index 3d2399a..34b518a 100644
--- a/data/etc/android.hardware.touchscreen.multitouch.xml
+++ b/data/etc/android.hardware.touchscreen.multitouch.xml
@@ -15,7 +15,9 @@
 -->
 
 <!-- This is the standard set of features for a touchscreen that supports
-     multitouch. -->
+     basic multitouch capable of gestures but not fully-indendent finger
+     tracking. -->
 <permissions>
+    <feature name="android.hardware.touchscreen" />
     <feature name="android.hardware.touchscreen.multitouch" />
 </permissions>
diff --git a/data/etc/android.hardware.touchscreen.xml b/data/etc/android.hardware.touchscreen.xml
new file mode 100644
index 0000000..10c91f1
--- /dev/null
+++ b/data/etc/android.hardware.touchscreen.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- This is the standard set of features for a touchscreen that does not
+     support multitouch. -->
+<permissions>
+    <feature name="android.hardware.touchscreen" />
+</permissions>
diff --git a/data/etc/android.hardware.wifi.xml b/data/etc/android.hardware.wifi.xml
new file mode 100644
index 0000000..512570c
--- /dev/null
+++ b/data/etc/android.hardware.wifi.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- This is the standard feature indicating that the device includes WiFi. -->
+<permissions>
+    <feature name="android.hardware.wifi" />
+</permissions>
diff --git a/data/etc/handheld_core_hardware.xml b/data/etc/handheld_core_hardware.xml
new file mode 100644
index 0000000..564fa84
--- /dev/null
+++ b/data/etc/handheld_core_hardware.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- These are the hardware components that all handheld devices
+     must include. Devices with optional hardware must also include extra
+     hardware files, per the comments below.
+
+     Handheld devices include phones, mobile Internet devices (MIDs),
+     Personal Media Players (PMPs), small tablets (7" or less), and similar
+     devices.
+-->
+<permissions>
+    <feature name="android.hardware.camera" />
+    <feature name="android.hardware.location" />
+    <feature name="android.hardware.location.network" />
+    <feature name="android.hardware.sensor.compass" />
+    <feature name="android.hardware.sensor.accelerometer" />
+    <feature name="android.hardware.bluetooth" />
+    <feature name="android.hardware.touchscreen" />
+    <feature name="android.hardware.microphone" />
+    <!-- devices with GPS must include android.hardware.location.gps.xml -->
+    <!-- devices with an autofocus camera and/or flash must include either
+         android.hardware.camera.autofocus.xml or 
+         android.hardware.camera.autofocus-flash.xml -->
+    <!-- devices with WiFi must also include android.hardware.wifi.xml -->
+    <!-- devices with limited/gestural multitouch must also include
+         android.hardware.touchscreen.multitouch.xml -->
+    <!-- devices with full multitouch must also include
+         android.hardware.touchscreen.multitouch.distinct.xml -->
+    <!-- devices with an ambient light sensor must also include
+         android.hardware.sensor.light.xml -->
+    <!-- devices with a proximity sensor must also include
+         android.hardware.sensor.proximity.xml -->
+    <!-- GSM phones must also include android.hardware.telephony.gsm.xml -->
+    <!-- CDMA phones must also include android.hardware.telephony.cdma.xml -->
+</permissions>
diff --git a/include/camera/CameraParameters.h b/include/camera/CameraParameters.h
index 6c6d0bc..a7568d7 100644
--- a/include/camera/CameraParameters.h
+++ b/include/camera/CameraParameters.h
@@ -228,6 +228,9 @@
     // Example value: "true". Read only.
     static const char KEY_SMOOTH_ZOOM_SUPPORTED[];
 
+    // Value for KEY_ZOOM_SUPPORTED or KEY_SMOOTH_ZOOM_SUPPORTED.
+    static const char TRUE[];
+
     // Values for white balance settings.
     static const char WHITE_BALANCE_AUTO[];
     static const char WHITE_BALANCE_INCANDESCENT[];
diff --git a/include/media/stagefright/AudioPlayer.h b/include/media/stagefright/AudioPlayer.h
index ea15a5c..9af5871 100644
--- a/include/media/stagefright/AudioPlayer.h
+++ b/include/media/stagefright/AudioPlayer.h
@@ -44,7 +44,7 @@
     // Return time in us.
     virtual int64_t getRealTimeUs();
 
-    status_t start();
+    status_t start(bool sourceAlreadyStarted = false);
 
     void pause();
     void resume();
diff --git a/libs/audioflinger/Android.mk b/libs/audioflinger/Android.mk
index b68bfc1..29e4a57 100644
--- a/libs/audioflinger/Android.mk
+++ b/libs/audioflinger/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
-	libbinder \
+    libbinder \
     libmedia \
     libhardware_legacy
 
@@ -85,7 +85,7 @@
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
-	libbinder \
+    libbinder \
     libmedia \
     libhardware_legacy
 
@@ -114,9 +114,19 @@
 endif
 
 ifeq ($(TARGET_SIMULATOR),true)
-	ifeq ($(HOST_OS),linux)
-		LOCAL_LDLIBS += -lrt -lpthread
-	endif
+    ifeq ($(HOST_OS),linux)
+        LOCAL_LDLIBS += -lrt -lpthread
+    endif
+endif
+
+ifeq ($(LVMX),true)
+  ifeq ($(TARGET_ARCH),arm)
+    LOCAL_CFLAGS += -DLVMX
+    LOCAL_C_INCLUDES += vendor/nxp
+    LOCAL_STATIC_LIBRARIES += liblifevibes
+    LOCAL_SHARED_LIBRARIES += liblvmxservice
+#    LOCAL_SHARED_LIBRARIES += liblvmxipc
+  endif
 endif
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp
index 8089389..7902212 100644
--- a/libs/audioflinger/AudioFlinger.cpp
+++ b/libs/audioflinger/AudioFlinger.cpp
@@ -47,6 +47,10 @@
 #include "A2dpAudioInterface.h"
 #endif
 
+#ifdef LVMX
+#include "lifevibes.h"
+#endif
+
 // ----------------------------------------------------------------------------
 // the sim build doesn't have gettid
 
@@ -132,6 +136,9 @@
     } else {
         LOGE("Couldn't even initialize the stubbed audio hardware!");
     }
+#ifdef LVMX
+    LifeVibes::init();
+#endif
 }
 
 AudioFlinger::~AudioFlinger()
@@ -411,6 +418,11 @@
     AutoMutex lock(mHardwareLock);
     mHardwareStatus = AUDIO_HW_SET_MODE;
     status_t ret = mAudioHardware->setMode(mode);
+#ifdef LVMX
+    if (NO_ERROR == ret) {
+        LifeVibes::setMode(mode);
+    }
+#endif
     mHardwareStatus = AUDIO_HW_IDLE;
     return ret;
 }
@@ -566,11 +578,37 @@
         return PERMISSION_DENIED;
     }
 
+#ifdef LVMX
+    AudioParameter param = AudioParameter(keyValuePairs);
+    LifeVibes::setParameters(ioHandle,keyValuePairs);
+    String8 key = String8(AudioParameter::keyRouting);
+    int device;
+    if (NO_ERROR != param.getInt(key, device)) {
+        device = -1;
+    }
+
+    key = String8(LifevibesTag);
+    String8 value;
+    int musicEnabled = -1;
+    if (NO_ERROR == param.get(key, value)) {
+        if (value == LifevibesEnable) {
+            musicEnabled = 1;
+        } else if (value == LifevibesDisable) {
+            musicEnabled = 0;
+        }
+    }
+#endif
+
     // ioHandle == 0 means the parameters are global to the audio hardware interface
     if (ioHandle == 0) {
         AutoMutex lock(mHardwareLock);
         mHardwareStatus = AUDIO_SET_PARAMETER;
         result = mAudioHardware->setParameters(keyValuePairs);
+#ifdef LVMX
+        if ((NO_ERROR == result) && (musicEnabled != -1)) {
+            LifeVibes::enableMusic((bool) musicEnabled);
+        }
+#endif
         mHardwareStatus = AUDIO_HW_IDLE;
         return result;
     }
@@ -586,7 +624,13 @@
         }
     }
     if (thread != NULL) {
-        return thread->setParameters(keyValuePairs);
+        result = thread->setParameters(keyValuePairs);
+#ifdef LVMX
+        if ((NO_ERROR == result) && (device != -1)) {
+            LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
+        }
+#endif
+        return result;
     }
     return BAD_VALUE;
 }
@@ -1058,12 +1102,24 @@
 
 status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setMasterVolume(audioOutputType, value);
+    }
+#endif
     mMasterVolume = value;
     return NO_ERROR;
 }
 
 status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setMasterMute(audioOutputType, muted);
+    }
+#endif
     mMasterMute = muted;
     return NO_ERROR;
 }
@@ -1080,12 +1136,24 @@
 
 status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setStreamVolume(audioOutputType, stream, value);
+    }
+#endif
     mStreamTypes[stream].volume = value;
     return NO_ERROR;
 }
 
 status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setStreamMute(audioOutputType, stream, muted);
+    }
+#endif
     mStreamTypes[stream].mute = muted;
     return NO_ERROR;
 }
@@ -1333,6 +1401,12 @@
             mLastWriteTime = systemTime();
             mInWrite = true;
             mBytesWritten += mixBufferSize;
+#ifdef LVMX
+            int audioOutputType = LifeVibes::getMixerType(mId, mType);
+            if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+               LifeVibes::process(audioOutputType, curBuf, mixBufferSize);
+            }
+#endif
             int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
             if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
             mNumWrites++;
@@ -1376,6 +1450,29 @@
     uint32_t mixerStatus = MIXER_IDLE;
     // find out which tracks need to be processed
     size_t count = activeTracks.size();
+
+    float masterVolume = mMasterVolume;
+    bool  masterMute = mMasterMute;
+
+#ifdef LVMX
+    bool tracksConnectedChanged = false;
+    bool stateChanged = false;
+
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
+    {
+        int activeTypes = 0;
+        for (size_t i=0 ; i<count ; i++) {
+            sp<Track> t = activeTracks[i].promote();
+            if (t == 0) continue;
+            Track* const track = t.get();
+            int iTracktype=track->type();
+            activeTypes |= 1<<track->type();
+        }
+        LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
+    }
+#endif
+
     for (size_t i=0 ; i<count ; i++) {
         sp<Track> t = activeTracks[i].promote();
         if (t == 0) continue;
@@ -1393,15 +1490,27 @@
 
             // compute volume for this track
             int16_t left, right;
-            if (track->isMuted() || mMasterMute || track->isPausing() ||
+            if (track->isMuted() || masterMute || track->isPausing() ||
                 mStreamTypes[track->type()].mute) {
                 left = right = 0;
                 if (track->isPausing()) {
                     track->setPaused();
                 }
             } else {
+                // read original volumes with volume control
                 float typeVolume = mStreamTypes[track->type()].volume;
-                float v = mMasterVolume * typeVolume;
+#ifdef LVMX
+                bool streamMute=false;
+                // read the volume from the LivesVibes audio engine.
+                if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
+                {
+                    LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
+                    if (streamMute) {
+                        typeVolume = 0;
+                    }
+                }
+#endif
+                float v = masterVolume * typeVolume;
                 float v_clamped = v * cblk->volume[0];
                 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
                 left = int16_t(v_clamped);
@@ -1427,7 +1536,13 @@
                 // do not apply ramp
                 param = AudioMixer::RAMP_VOLUME;
             }
-
+#ifdef LVMX
+            if ( tracksConnectedChanged || stateChanged )
+            {
+                 // only do the ramp when the volume is changed by the user / application
+                 param = AudioMixer::VOLUME;
+            }
+#endif
             mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
             mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
             mAudioMixer->setParameter(
@@ -3652,6 +3767,18 @@
         } else {
             thread = new MixerThread(this, output, ++mNextThreadId);
             LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
+
+#ifdef LVMX
+            unsigned bitsPerSample =
+                (format == AudioSystem::PCM_16_BIT) ? 16 :
+                    ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
+            unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
+            int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
+
+            LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
+            LifeVibes::setDevice(audioOutputType, *pDevices);
+#endif
+
         }
         mPlaybackThreads.add(mNextThreadId, thread);
 
diff --git a/libs/audioflinger/AudioHardwareStub.cpp b/libs/audioflinger/AudioHardwareStub.cpp
index ae215d1..d481150 100644
--- a/libs/audioflinger/AudioHardwareStub.cpp
+++ b/libs/audioflinger/AudioHardwareStub.cpp
@@ -166,7 +166,7 @@
 // ----------------------------------------------------------------------------
 
 status_t AudioStreamInStub::set(int *pFormat, uint32_t *pChannels, uint32_t *pRate,
-				AudioSystem::audio_in_acoustics acoustics)
+                AudioSystem::audio_in_acoustics acoustics)
 {
     return NO_ERROR;
 }
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/libs/audioflinger/AudioResampler.h b/libs/audioflinger/AudioResampler.h
index 39656c0..2dfac76 100644
--- a/libs/audioflinger/AudioResampler.h
+++ b/libs/audioflinger/AudioResampler.h
@@ -76,8 +76,8 @@
     int32_t mInSampleRate;
     AudioBufferProvider::Buffer mBuffer;
     union {
-    	int16_t mVolume[2];
-    	uint32_t mVolumeRL;
+        int16_t mVolume[2];
+        uint32_t mVolumeRL;
     };
     int16_t mTargetVolume[2];
     format mFormat;
diff --git a/libs/camera/CameraParameters.cpp b/libs/camera/CameraParameters.cpp
index 65785c7..76a9715 100644
--- a/libs/camera/CameraParameters.cpp
+++ b/libs/camera/CameraParameters.cpp
@@ -70,6 +70,8 @@
 const char CameraParameters::KEY_ZOOM_SUPPORTED[] = "zoom-supported";
 const char CameraParameters::KEY_SMOOTH_ZOOM_SUPPORTED[] = "smooth-zoom-supported";
 
+const char CameraParameters::TRUE[] = "true";
+
 // Values for white balance settings.
 const char CameraParameters::WHITE_BALANCE_AUTO[] = "auto";
 const char CameraParameters::WHITE_BALANCE_INCANDESCENT[] = "incandescent";
diff --git a/libs/surfaceflinger/Layer.cpp b/libs/surfaceflinger/Layer.cpp
index c080513..7ca7875 100644
--- a/libs/surfaceflinger/Layer.cpp
+++ b/libs/surfaceflinger/Layer.cpp
@@ -156,7 +156,11 @@
     if (mFlags & DisplayHardware::DIRECT_TEXTURE) {
         if (buffer->usage & GraphicBuffer::USAGE_HW_TEXTURE) {
             if (mTextures[index].dirty) {
-                initializeEglImage(buffer, &mTextures[index]);
+                if (initializeEglImage(buffer, &mTextures[index]) != NO_ERROR) {
+                    // not sure what we can do here...
+                    mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
+                    goto slowpath;
+                }
             }
         } else {
             if (mHybridBuffer==0 || (mHybridBuffer->width != buffer->width ||
@@ -166,8 +170,13 @@
                         buffer->width, buffer->height, buffer->format,
                         GraphicBuffer::USAGE_SW_WRITE_OFTEN |
                         GraphicBuffer::USAGE_HW_TEXTURE);
-                initializeEglImage(
-                        mHybridBuffer, &mTextures[0]);
+                if (initializeEglImage(
+                        mHybridBuffer, &mTextures[0]) != NO_ERROR) {
+                    // not sure what we can do here...
+                    mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
+                    mHybridBuffer.clear();
+                    goto slowpath;
+                }
             }
 
             GGLSurface t;
@@ -236,6 +245,7 @@
     } else
 #endif
     {
+slowpath:
         for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
             mTextures[i].image = EGL_NO_IMAGE_KHR;
         }
diff --git a/libs/surfaceflinger/LayerBase.cpp b/libs/surfaceflinger/LayerBase.cpp
index b0109ca..fdf6627 100644
--- a/libs/surfaceflinger/LayerBase.cpp
+++ b/libs/surfaceflinger/LayerBase.cpp
@@ -666,22 +666,15 @@
             dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
             (EGLClientBuffer)clientBuf, attrs);
 
-    LOGE_IF(texture->image == EGL_NO_IMAGE_KHR,
-            "eglCreateImageKHR() failed. err=0x%4x",
-            eglGetError());
-
     if (texture->image != EGL_NO_IMAGE_KHR) {
         glBindTexture(GL_TEXTURE_2D, texture->name);
         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D,
                 (GLeglImageOES)texture->image);
         GLint error = glGetError();
         if (UNLIKELY(error != GL_NO_ERROR)) {
-            // this failed, for instance, because we don't support NPOT.
-            // FIXME: do something!
             LOGE("layer=%p, glEGLImageTargetTexture2DOES(%p) "
                  "failed err=0x%04x",
                  this, texture->image, error);
-            mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
             err = INVALID_OPERATION;
         } else {
             // Everything went okay!
@@ -691,6 +684,8 @@
             texture->height = clientBuf->height;
         }
     } else {
+        LOGE("layer=%p, eglCreateImageKHR() failed. err=0x%4x",
+                this, eglGetError());
         err = INVALID_OPERATION;
     }
     return err;
@@ -704,7 +699,8 @@
 LayerBaseClient::LayerBaseClient(SurfaceFlinger* flinger, DisplayID display,
         const sp<Client>& client, int32_t i)
     : LayerBase(flinger, display), lcblk(NULL), client(client),
-      mIndex(i), mIdentity(uint32_t(android_atomic_inc(&sIdentity)))
+      mDebug(false), mIndex(i),
+      mIdentity(uint32_t(android_atomic_inc(&sIdentity)))
 {
     lcblk = new SharedBufferServer(
             client->ctrlblk, i, NUM_BUFFERS,
diff --git a/libs/surfaceflinger/LayerBase.h b/libs/surfaceflinger/LayerBase.h
index 7ac8bc5..852b9f9 100644
--- a/libs/surfaceflinger/LayerBase.h
+++ b/libs/surfaceflinger/LayerBase.h
@@ -369,6 +369,9 @@
 
     friend class Surface;
 
+protected:
+    mutable     bool            mDebug;
+
 private:
                 int32_t         mIndex;
     mutable     Mutex           mLock;
diff --git a/libs/surfaceflinger/LayerBuffer.cpp b/libs/surfaceflinger/LayerBuffer.cpp
index 6d1685b..5c21593 100644
--- a/libs/surfaceflinger/LayerBuffer.cpp
+++ b/libs/surfaceflinger/LayerBuffer.cpp
@@ -261,7 +261,8 @@
 // LayerBuffer::Buffer
 // ============================================================================
 
-LayerBuffer::Buffer::Buffer(const ISurface::BufferHeap& buffers, ssize_t offset)
+LayerBuffer::Buffer::Buffer(const ISurface::BufferHeap& buffers,
+        ssize_t offset, size_t bufferSize)
     : mBufferHeap(buffers), mSupportsCopybit(false)
 {
     NativeBuffer& src(mNativeBuffer);
@@ -280,7 +281,7 @@
     if (module && module->perform) {
         int err = module->perform(module,
                 GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER,
-                buffers.heap->heapID(), buffers.heap->getSize(),
+                buffers.heap->heapID(), bufferSize,
                 offset, buffers.heap->base(),
                 &src.img.handle);
 
@@ -415,7 +416,7 @@
 
     sp<Buffer> buffer;
     if (buffers.heap != 0) {
-        buffer = new LayerBuffer::Buffer(buffers, offset);
+        buffer = new LayerBuffer::Buffer(buffers, offset, mBufferSize);
         if (buffer->getStatus() != NO_ERROR)
             buffer.clear();
         setBuffer(buffer);
@@ -469,6 +470,11 @@
     if (mLayer.mFlags & DisplayHardware::DIRECT_TEXTURE) {
         err = INVALID_OPERATION;
         if (ourBuffer->supportsCopybit()) {
+
+            // there are constraints on buffers used by the GPU and these may not
+            // be honored here. We need to change the API so the buffers
+            // are allocated with gralloc. For now disable this code-path
+#if 0
             // First, try to use the buffer as an EGLImage directly
             if (mUseEGLImageDirectly) {
                 // NOTE: Assume the buffer is allocated with the proper USAGE flags
@@ -483,6 +489,8 @@
                     mUseEGLImageDirectly = false;
                 }
             }
+#endif
+
             copybit_device_t* copybit = mLayer.mBlitEngine;
             if (copybit && err != NO_ERROR) {
                 // create our EGLImageKHR the first time
diff --git a/libs/surfaceflinger/LayerBuffer.h b/libs/surfaceflinger/LayerBuffer.h
index eb5b8eb..b176623 100644
--- a/libs/surfaceflinger/LayerBuffer.h
+++ b/libs/surfaceflinger/LayerBuffer.h
@@ -99,7 +99,8 @@
 
     class Buffer : public LightRefBase<Buffer> {
     public:
-        Buffer(const ISurface::BufferHeap& buffers, ssize_t offset);
+        Buffer(const ISurface::BufferHeap& buffers,
+                ssize_t offset, size_t bufferSize);
         inline bool supportsCopybit() const {
             return mSupportsCopybit;
         }
diff --git a/libs/surfaceflinger/SurfaceFlinger.cpp b/libs/surfaceflinger/SurfaceFlinger.cpp
index 2598440..26ee285 100644
--- a/libs/surfaceflinger/SurfaceFlinger.cpp
+++ b/libs/surfaceflinger/SurfaceFlinger.cpp
@@ -1523,10 +1523,6 @@
             if (l != 0) {
                 SharedBufferStack::Statistics stats = l->lcblk->getStats();
                 result.append( l->lcblk->dump("      ") );
-                snprintf(buffer, SIZE,
-                        "      front-index=%u\n", l->getFrontBufferIndex());
-                result.append(buffer);
-
                 sp<const GraphicBuffer> buf0(l->getBuffer(0));
                 sp<const GraphicBuffer> buf1(l->getBuffer(1));
                 uint32_t w0=0, h0=0, s0=0;
diff --git a/libs/surfaceflinger_client/SharedBufferStack.cpp b/libs/surfaceflinger_client/SharedBufferStack.cpp
index ceb5e59..65ce1c1 100644
--- a/libs/surfaceflinger_client/SharedBufferStack.cpp
+++ b/libs/surfaceflinger_client/SharedBufferStack.cpp
@@ -132,10 +132,11 @@
     char buffer[SIZE];
     String8 result;
     SharedBufferStack& stack( *mSharedStack );
+    int tail = (mNumBuffers + stack.head - stack.available + 1) % mNumBuffers;
     snprintf(buffer, SIZE, 
-            "%s[ head=%2d, available=%2d, queued=%2d ] "
+            "%s[ head=%2d, available=%2d, queued=%2d, tail=%2d ] "
             "reallocMask=%08x, inUse=%2d, identity=%d, status=%d\n",
-            prefix, stack.head, stack.available, stack.queued, 
+            prefix, stack.head, stack.available, stack.queued, tail,
             stack.reallocMask, stack.inUse, stack.identity, stack.status);
     result.append(buffer);
     return result;
@@ -269,6 +270,8 @@
     newTail = head - avail + 1;
     if (newTail < 0) {
         newTail += mNumBuffers;
+    } else if (newTail >= mNumBuffers) {
+        newTail -= mNumBuffers;
     }
     return newTail;
 }
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/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index 1f02608..1047fa4 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -630,13 +630,9 @@
                 map.put(Video.Media.ARTIST, (mArtist != null && mArtist.length() > 0 ? mArtist : MediaStore.UNKNOWN_STRING));
                 map.put(Video.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0 ? mAlbum : MediaStore.UNKNOWN_STRING));
                 map.put(Video.Media.DURATION, mDuration);
-                map.put(Video.Media.DATE_TAKEN, mLastModified * 1000);
                 // FIXME - add RESOLUTION
             } else if (MediaFile.isImageFileType(mFileType)) {
                 // FIXME - add DESCRIPTION
-                // DATE_TAKEN will be overridden later if this is a JPEG image whose EXIF data
-                // contains date time information.
-                map.put(Images.Media.DATE_TAKEN, mLastModified * 1000);
             } else if (MediaFile.isAudioFileType(mFileType)) {
                 map.put(Audio.Media.ARTIST, (mArtist != null && mArtist.length() > 0 ? mArtist : MediaStore.UNKNOWN_STRING));
                 map.put(Audio.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0 ? mAlbum : MediaStore.UNKNOWN_STRING));
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index 5e6e0da..005c64a 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -55,14 +55,17 @@
     mSource = source;
 }
 
-status_t AudioPlayer::start() {
+status_t AudioPlayer::start(bool sourceAlreadyStarted) {
     CHECK(!mStarted);
     CHECK(mSource != NULL);
 
-    status_t err = mSource->start();
+    status_t err;
+    if (!sourceAlreadyStarted) {
+        err = mSource->start();
 
-    if (err != OK) {
-        return err;
+        if (err != OK) {
+            return err;
+        }
     }
 
     sp<MetaData> format = mSource->getFormat();
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 5090c39..e00ba470 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -410,6 +410,9 @@
 
     if (mDurationUs >= 0) {
         int64_t cachedDurationUs = mPrefetcher->getCachedDurationUs();
+
+        LOGV("cache holds %.2f secs worth of data.", cachedDurationUs / 1E6);
+
         int64_t positionUs = 0;
         if (mVideoSource != NULL) {
             positionUs = mVideoTimeUs;
@@ -486,7 +489,11 @@
             if (mAudioSink != NULL) {
                 mAudioPlayer = new AudioPlayer(mAudioSink);
                 mAudioPlayer->setSource(mAudioSource);
-                status_t err = mAudioPlayer->start();
+
+                // We've already started the MediaSource in order to enable
+                // the prefetcher to read its data.
+                status_t err = mAudioPlayer->start(
+                        true /* sourceAlreadyStarted */);
 
                 if (err != OK) {
                     delete mAudioPlayer;
@@ -734,6 +741,8 @@
         }
     }
 
+    mAudioSource->start();
+
     return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
 }
 
@@ -1064,6 +1073,8 @@
 }
 
 void AwesomePlayer::onPrepareAsyncEvent() {
+    sp<Prefetcher> prefetcher;
+
     {
         Mutex::Autolock autoLock(mLock);
 
@@ -1075,12 +1086,25 @@
                 return;
             }
         }
-    }
 
-    sp<Prefetcher> prefetcher;
+        if (mVideoTrack != NULL && mVideoSource == NULL) {
+            status_t err = initVideoDecoder();
 
-    {
-        Mutex::Autolock autoLock(mLock);
+            if (err != OK) {
+                abortPrepare(err);
+                return;
+            }
+        }
+
+        if (mAudioTrack != NULL && mAudioSource == NULL) {
+            status_t err = initAudioDecoder();
+
+            if (err != OK) {
+                abortPrepare(err);
+                return;
+            }
+        }
+
         prefetcher = mPrefetcher;
     }
 
@@ -1091,24 +1115,6 @@
 
     Mutex::Autolock autoLock(mLock);
 
-    if (mVideoTrack != NULL && mVideoSource == NULL) {
-        status_t err = initVideoDecoder();
-
-        if (err != OK) {
-            abortPrepare(err);
-            return;
-        }
-    }
-
-    if (mAudioTrack != NULL && mAudioSource == NULL) {
-        status_t err = initAudioDecoder();
-
-        if (err != OK) {
-            abortPrepare(err);
-            return;
-        }
-    }
-
     if (mIsAsyncPrepare) {
         if (mVideoWidth < 0 || mVideoHeight < 0) {
             notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
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/media/libstagefright/Prefetcher.cpp b/media/libstagefright/Prefetcher.cpp
index 9c73f4a..debb60d 100644
--- a/media/libstagefright/Prefetcher.cpp
+++ b/media/libstagefright/Prefetcher.cpp
@@ -59,6 +59,7 @@
     int64_t mSeekTimeUs;
     int64_t mCacheDurationUs;
     bool mPrefetcherStopped;
+    bool mCurrentlyPrefetching;
 
     List<MediaBuffer *> mCachedBuffers;
 
@@ -194,6 +195,7 @@
 
     int64_t minCacheDurationUs = -1;
     ssize_t minIndex = -1;
+    bool anySourceActive = false;
     for (size_t i = 0; i < mSources.size(); ++i) {
         int64_t cacheDurationUs;
         sp<PrefetchedSource> source = mSources[i].promote();
@@ -201,12 +203,8 @@
             continue;
         }
 
-        if (!source->getCacheDurationUs(&cacheDurationUs)) {
-            continue;
-        }
-
-        if (cacheDurationUs >= kMaxCacheDurationUs) {
-            continue;
+        if (source->getCacheDurationUs(&cacheDurationUs)) {
+            anySourceActive = true;
         }
 
         if (minIndex < 0 || cacheDurationUs < minCacheDurationUs) {
@@ -216,20 +214,20 @@
     }
 
     if (noMoreData) {
-        *noMoreData = minCacheDurationUs < 0;
+        *noMoreData = !anySourceActive;
     }
 
     return minCacheDurationUs < 0 ? 0 : minCacheDurationUs;
 }
 
 status_t Prefetcher::prepare() {
-    // Buffer about 2 secs worth of data on prepare.
+    // Fill the cache.
 
     int64_t duration;
     bool noMoreData;
     do {
         duration = getCachedDurationUs(&noMoreData);
-    } while (!noMoreData && duration < 2000000);
+    } while (!noMoreData && duration < 2000000ll);
 
     return OK;
 }
@@ -245,7 +243,8 @@
       mReachedEOS(false),
       mSeekTimeUs(0),
       mCacheDurationUs(0),
-      mPrefetcherStopped(false) {
+      mPrefetcherStopped(false),
+      mCurrentlyPrefetching(false) {
 }
 
 PrefetchedSource::~PrefetchedSource() {
@@ -275,6 +274,10 @@
 
     Mutex::Autolock autoLock(mLock);
 
+    while (mCurrentlyPrefetching) {
+        mCondition.wait(mLock);
+    }
+
     clearCache_l();
 
     status_t err = mSource->stop();
@@ -324,14 +327,12 @@
 bool PrefetchedSource::getCacheDurationUs(int64_t *durationUs) {
     Mutex::Autolock autoLock(mLock);
 
-    if (!mStarted || mReachedEOS) {
-        *durationUs = 0;
+    *durationUs = mCacheDurationUs;
 
+    if (!mStarted || mReachedEOS) {
         return false;
     }
 
-    *durationUs = mCacheDurationUs;
-
     return true;
 }
 
@@ -344,15 +345,24 @@
         return;
     }
 
+    mCurrentlyPrefetching = true;
+
     if (mSeekTimeUs >= 0) {
         options.setSeekTo(mSeekTimeUs);
         mSeekTimeUs = -1;
     }
 
+    // Ensure our object does not go away while we're not holding
+    // the lock.
+    sp<PrefetchedSource> me = this;
+
+    mLock.unlock();
     MediaBuffer *buffer;
     status_t err = mSource->read(&buffer, &options);
+    mLock.lock();
 
     if (err != OK) {
+        mCurrentlyPrefetching = false;
         mReachedEOS = true;
         mFinalStatus = err;
         mCondition.signal();
@@ -380,6 +390,8 @@
 
     mCachedBuffers.push_back(copy);
     updateCacheDuration_l();
+
+    mCurrentlyPrefetching = false;
     mCondition.signal();
 }
 
diff --git a/media/libstagefright/colorconversion/SoftwareRenderer.cpp b/media/libstagefright/colorconversion/SoftwareRenderer.cpp
index 4c11c36..a6dbf69 100644
--- a/media/libstagefright/colorconversion/SoftwareRenderer.cpp
+++ b/media/libstagefright/colorconversion/SoftwareRenderer.cpp
@@ -45,7 +45,9 @@
         LOGI("Creating physical memory heap failed, reverting to regular heap.");
         mMemoryHeap = new MemoryHeapBase(2 * mFrameSize);
     } else {
-        mMemoryHeap = new MemoryHeapPmem(mMemoryHeap);
+        sp<MemoryHeapPmem> pmemHeap = new MemoryHeapPmem(mMemoryHeap);
+        pmemHeap->slap();
+        mMemoryHeap = pmemHeap;
     }
 
     CHECK(mISurface.get() != NULL);
diff --git a/mms-common/Android.mk b/mms-common/Android.mk
deleted file mode 100644
index 57f1ccc..0000000
--- a/mms-common/Android.mk
+++ /dev/null
@@ -1,30 +0,0 @@
-# Copyright (C) 2009 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.
-
-LOCAL_PATH := $(call my-dir)
-
-# Note: the source code is in java/, not src/, because this code is also part of
-# the framework library, and build/core/pathmap.mk expects a java/ subdirectory.
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := mms-common
-LOCAL_SRC_FILES := $(call all-java-files-under, java)
-LOCAL_STATIC_JAVA_LIBRARIES += android-common
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-# Include this library in the build server's output directory
-$(call dist-for-goals, droid, $(LOCAL_BUILT_MODULE):mms-common.jar)
-
-# Build the test package
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/mms-common/java/com/android/mmscommon/ContentType.java b/mms-common/java/com/android/mmscommon/ContentType.java
deleted file mode 100644
index ca449fe..0000000
--- a/mms-common/java/com/android/mmscommon/ContentType.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Copyright (C) 2007-2008 Esmertec AG.
- * Copyright (C) 2007-2008 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 com.android.mmscommon;
-
-import java.util.ArrayList;
-
-public class ContentType {
-    public static final String MMS_MESSAGE       = "application/vnd.wap.mms-message";
-    // The phony content type for generic PDUs (e.g. ReadOrig.ind,
-    // Notification.ind, Delivery.ind).
-    public static final String MMS_GENERIC       = "application/vnd.wap.mms-generic";
-    public static final String MULTIPART_MIXED   = "application/vnd.wap.multipart.mixed";
-    public static final String MULTIPART_RELATED = "application/vnd.wap.multipart.related";
-    public static final String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative";
-
-    public static final String TEXT_PLAIN        = "text/plain";
-    public static final String TEXT_HTML         = "text/html";
-    public static final String TEXT_VCALENDAR    = "text/x-vCalendar";
-    public static final String TEXT_VCARD        = "text/x-vCard";
-
-    public static final String IMAGE_UNSPECIFIED = "image/*";
-    public static final String IMAGE_JPEG        = "image/jpeg";
-    public static final String IMAGE_JPG         = "image/jpg";
-    public static final String IMAGE_GIF         = "image/gif";
-    public static final String IMAGE_WBMP        = "image/vnd.wap.wbmp";
-    public static final String IMAGE_PNG         = "image/png";
-
-    public static final String AUDIO_UNSPECIFIED = "audio/*";
-    public static final String AUDIO_AAC         = "audio/aac";
-    public static final String AUDIO_AMR         = "audio/amr";
-    public static final String AUDIO_IMELODY     = "audio/imelody";
-    public static final String AUDIO_MID         = "audio/mid";
-    public static final String AUDIO_MIDI        = "audio/midi";
-    public static final String AUDIO_MP3         = "audio/mp3";
-    public static final String AUDIO_MPEG3       = "audio/mpeg3";
-    public static final String AUDIO_MPEG        = "audio/mpeg";
-    public static final String AUDIO_MPG         = "audio/mpg";
-    public static final String AUDIO_MP4         = "audio/mp4";
-    public static final String AUDIO_X_MID       = "audio/x-mid";
-    public static final String AUDIO_X_MIDI      = "audio/x-midi";
-    public static final String AUDIO_X_MP3       = "audio/x-mp3";
-    public static final String AUDIO_X_MPEG3     = "audio/x-mpeg3";
-    public static final String AUDIO_X_MPEG      = "audio/x-mpeg";
-    public static final String AUDIO_X_MPG       = "audio/x-mpg";
-    public static final String AUDIO_3GPP        = "audio/3gpp";
-    public static final String AUDIO_OGG         = "application/ogg";
-
-    public static final String VIDEO_UNSPECIFIED = "video/*";
-    public static final String VIDEO_3GPP        = "video/3gpp";
-    public static final String VIDEO_3G2         = "video/3gpp2";
-    public static final String VIDEO_H263        = "video/h263";
-    public static final String VIDEO_MP4         = "video/mp4";
-
-    public static final String APP_SMIL          = "application/smil";
-    public static final String APP_WAP_XHTML     = "application/vnd.wap.xhtml+xml";
-    public static final String APP_XHTML         = "application/xhtml+xml";
-
-    public static final String APP_DRM_CONTENT   = "application/vnd.oma.drm.content";
-    public static final String APP_DRM_MESSAGE   = "application/vnd.oma.drm.message";
-
-    private static final ArrayList<String> sSupportedContentTypes = new ArrayList<String>();
-    private static final ArrayList<String> sSupportedImageTypes = new ArrayList<String>();
-    private static final ArrayList<String> sSupportedAudioTypes = new ArrayList<String>();
-    private static final ArrayList<String> sSupportedVideoTypes = new ArrayList<String>();
-
-    static {
-        sSupportedContentTypes.add(TEXT_PLAIN);
-        sSupportedContentTypes.add(TEXT_HTML);
-        sSupportedContentTypes.add(TEXT_VCALENDAR);
-        sSupportedContentTypes.add(TEXT_VCARD);
-
-        sSupportedContentTypes.add(IMAGE_JPEG);
-        sSupportedContentTypes.add(IMAGE_GIF);
-        sSupportedContentTypes.add(IMAGE_WBMP);
-        sSupportedContentTypes.add(IMAGE_PNG);
-        sSupportedContentTypes.add(IMAGE_JPG);
-        //supportedContentTypes.add(IMAGE_SVG); not yet supported.
-
-        sSupportedContentTypes.add(AUDIO_AAC);
-        sSupportedContentTypes.add(AUDIO_AMR);
-        sSupportedContentTypes.add(AUDIO_IMELODY);
-        sSupportedContentTypes.add(AUDIO_MID);
-        sSupportedContentTypes.add(AUDIO_MIDI);
-        sSupportedContentTypes.add(AUDIO_MP3);
-        sSupportedContentTypes.add(AUDIO_MPEG3);
-        sSupportedContentTypes.add(AUDIO_MPEG);
-        sSupportedContentTypes.add(AUDIO_MPG);
-        sSupportedContentTypes.add(AUDIO_X_MID);
-        sSupportedContentTypes.add(AUDIO_X_MIDI);
-        sSupportedContentTypes.add(AUDIO_X_MP3);
-        sSupportedContentTypes.add(AUDIO_X_MPEG3);
-        sSupportedContentTypes.add(AUDIO_X_MPEG);
-        sSupportedContentTypes.add(AUDIO_X_MPG);
-        sSupportedContentTypes.add(AUDIO_3GPP);
-        sSupportedContentTypes.add(AUDIO_OGG);
-
-        sSupportedContentTypes.add(VIDEO_3GPP);
-        sSupportedContentTypes.add(VIDEO_3G2);
-        sSupportedContentTypes.add(VIDEO_H263);
-        sSupportedContentTypes.add(VIDEO_MP4);
-
-        sSupportedContentTypes.add(APP_SMIL);
-        sSupportedContentTypes.add(APP_WAP_XHTML);
-        sSupportedContentTypes.add(APP_XHTML);
-
-        sSupportedContentTypes.add(APP_DRM_CONTENT);
-        sSupportedContentTypes.add(APP_DRM_MESSAGE);
-
-        // add supported image types
-        sSupportedImageTypes.add(IMAGE_JPEG);
-        sSupportedImageTypes.add(IMAGE_GIF);
-        sSupportedImageTypes.add(IMAGE_WBMP);
-        sSupportedImageTypes.add(IMAGE_PNG);
-        sSupportedImageTypes.add(IMAGE_JPG);
-
-        // add supported audio types
-        sSupportedAudioTypes.add(AUDIO_AAC);
-        sSupportedAudioTypes.add(AUDIO_AMR);
-        sSupportedAudioTypes.add(AUDIO_IMELODY);
-        sSupportedAudioTypes.add(AUDIO_MID);
-        sSupportedAudioTypes.add(AUDIO_MIDI);
-        sSupportedAudioTypes.add(AUDIO_MP3);
-        sSupportedAudioTypes.add(AUDIO_MPEG3);
-        sSupportedAudioTypes.add(AUDIO_MPEG);
-        sSupportedAudioTypes.add(AUDIO_MPG);
-        sSupportedAudioTypes.add(AUDIO_MP4);
-        sSupportedAudioTypes.add(AUDIO_X_MID);
-        sSupportedAudioTypes.add(AUDIO_X_MIDI);
-        sSupportedAudioTypes.add(AUDIO_X_MP3);
-        sSupportedAudioTypes.add(AUDIO_X_MPEG3);
-        sSupportedAudioTypes.add(AUDIO_X_MPEG);
-        sSupportedAudioTypes.add(AUDIO_X_MPG);
-        sSupportedAudioTypes.add(AUDIO_3GPP);
-        sSupportedAudioTypes.add(AUDIO_OGG);
-
-        // add supported video types
-        sSupportedVideoTypes.add(VIDEO_3GPP);
-        sSupportedVideoTypes.add(VIDEO_3G2);
-        sSupportedVideoTypes.add(VIDEO_H263);
-        sSupportedVideoTypes.add(VIDEO_MP4);
-    }
-
-    // This class should never be instantiated.
-    private ContentType() {
-    }
-
-    public static boolean isSupportedType(String contentType) {
-        return (null != contentType) && sSupportedContentTypes.contains(contentType);
-    }
-
-    public static boolean isSupportedImageType(String contentType) {
-        return isImageType(contentType) && isSupportedType(contentType);
-    }
-
-    public static boolean isSupportedAudioType(String contentType) {
-        return isAudioType(contentType) && isSupportedType(contentType);
-    }
-
-    public static boolean isSupportedVideoType(String contentType) {
-        return isVideoType(contentType) && isSupportedType(contentType);
-    }
-
-    public static boolean isTextType(String contentType) {
-        return (null != contentType) && contentType.startsWith("text/");
-    }
-
-    public static boolean isImageType(String contentType) {
-        return (null != contentType) && contentType.startsWith("image/");
-    }
-
-    public static boolean isAudioType(String contentType) {
-        return (null != contentType) && contentType.startsWith("audio/");
-    }
-
-    public static boolean isVideoType(String contentType) {
-        return (null != contentType) && contentType.startsWith("video/");
-    }
-
-    public static boolean isDrmType(String contentType) {
-        return (null != contentType)
-                && (contentType.equals(APP_DRM_CONTENT)
-                        || contentType.equals(APP_DRM_MESSAGE));
-    }
-
-    public static boolean isUnspecified(String contentType) {
-        return (null != contentType) && contentType.endsWith("*");
-    }
-
-    @SuppressWarnings("unchecked")
-    public static ArrayList<String> getImageTypes() {
-        return (ArrayList<String>) sSupportedImageTypes.clone();
-    }
-
-    @SuppressWarnings("unchecked")
-    public static ArrayList<String> getAudioTypes() {
-        return (ArrayList<String>) sSupportedAudioTypes.clone();
-    }
-
-    @SuppressWarnings("unchecked")
-    public static ArrayList<String> getVideoTypes() {
-        return (ArrayList<String>) sSupportedVideoTypes.clone();
-    }
-
-    @SuppressWarnings("unchecked")
-    public static ArrayList<String> getSupportedTypes() {
-        return (ArrayList<String>) sSupportedContentTypes.clone();
-    }
-}
diff --git a/mms-common/java/com/android/mmscommon/telephony/TelephonyProvider.java b/mms-common/java/com/android/mmscommon/telephony/TelephonyProvider.java
deleted file mode 100644
index cfc9231..0000000
--- a/mms-common/java/com/android/mmscommon/telephony/TelephonyProvider.java
+++ /dev/null
@@ -1,1779 +0,0 @@
-/*
- * Copyright (C) 2006 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 com.android.mmscommon.telephony;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import android.content.ContentResolver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.database.Cursor;
-import android.net.Uri;
-import android.provider.BaseColumns;
-import android.telephony.SmsMessage;
-import android.text.TextUtils;
-import android.util.Config;
-import android.util.Log;
-import android.util.Patterns;
-
-import android.database.sqlite.SqliteWrapper;
-
-/**
- * The Telephony provider contains data related to phone operation.
- *
- * @hide
- */
-
-// This is a copy of the private TelephoneProvider.java file found in:
-//      com.android.providers.telephony
-// TODO: keep these files in sync.
-
-public final class TelephonyProvider {
-    private static final String TAG = "Telephony";
-    private static final boolean DEBUG = true;
-    private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
-
-    // Constructor
-    public TelephonyProvider() {
-    }
-
-    /**
-     * Base columns for tables that contain text based SMSs.
-     */
-    public interface TextBasedSmsColumns {
-        /**
-         * The type of the message
-         * <P>Type: INTEGER</P>
-         */
-        public static final String TYPE = "type";
-
-        public static final int MESSAGE_TYPE_ALL    = 0;
-        public static final int MESSAGE_TYPE_INBOX  = 1;
-        public static final int MESSAGE_TYPE_SENT   = 2;
-        public static final int MESSAGE_TYPE_DRAFT  = 3;
-        public static final int MESSAGE_TYPE_OUTBOX = 4;
-        public static final int MESSAGE_TYPE_FAILED = 5; // for failed outgoing messages
-        public static final int MESSAGE_TYPE_QUEUED = 6; // for messages to send later
-
-
-        /**
-         * The thread ID of the message
-         * <P>Type: INTEGER</P>
-         */
-        public static final String THREAD_ID = "thread_id";
-
-        /**
-         * The address of the other party
-         * <P>Type: TEXT</P>
-         */
-        public static final String ADDRESS = "address";
-
-        /**
-         * The person ID of the sender
-         * <P>Type: INTEGER (long)</P>
-         */
-        public static final String PERSON_ID = "person";
-
-        /**
-         * The date the message was sent
-         * <P>Type: INTEGER (long)</P>
-         */
-        public static final String DATE = "date";
-
-        /**
-         * Has the message been read
-         * <P>Type: INTEGER (boolean)</P>
-         */
-        public static final String READ = "read";
-
-        /**
-         * Indicates whether this message has been seen by the user. The "seen" flag will be
-         * used to figure out whether we need to throw up a statusbar notification or not.
-         */
-        public static final String SEEN = "seen";
-
-        /**
-         * The TP-Status value for the message, or -1 if no status has
-         * been received
-         */
-        public static final String STATUS = "status";
-
-        public static final int STATUS_NONE = -1;
-        public static final int STATUS_COMPLETE = 0;
-        public static final int STATUS_PENDING = 64;
-        public static final int STATUS_FAILED = 128;
-
-        /**
-         * The subject of the message, if present
-         * <P>Type: TEXT</P>
-         */
-        public static final String SUBJECT = "subject";
-
-        /**
-         * The body of the message
-         * <P>Type: TEXT</P>
-         */
-        public static final String BODY = "body";
-
-        /**
-         * The id of the sender of the conversation, if present
-         * <P>Type: INTEGER (reference to item in content://contacts/people)</P>
-         */
-        public static final String PERSON = "person";
-
-        /**
-         * The protocol identifier code
-         * <P>Type: INTEGER</P>
-         */
-        public static final String PROTOCOL = "protocol";
-
-        /**
-         * Whether the <code>TP-Reply-Path</code> bit was set on this message
-         * <P>Type: BOOLEAN</P>
-         */
-        public static final String REPLY_PATH_PRESENT = "reply_path_present";
-
-        /**
-         * The service center (SC) through which to send the message, if present
-         * <P>Type: TEXT</P>
-         */
-        public static final String SERVICE_CENTER = "service_center";
-
-        /**
-         * Has the message been locked?
-         * <P>Type: INTEGER (boolean)</P>
-         */
-        public static final String LOCKED = "locked";
-
-        /**
-         * Error code associated with sending or receiving this message
-         * <P>Type: INTEGER</P>
-         */
-        public static final String ERROR_CODE = "error_code";
-}
-
-    /**
-     * Contains all text based SMS messages.
-     */
-    public static final class Sms implements BaseColumns, TextBasedSmsColumns {
-        public static final Cursor query(ContentResolver cr, String[] projection) {
-            return cr.query(CONTENT_URI, projection, null, null, DEFAULT_SORT_ORDER);
-        }
-
-        public static final Cursor query(ContentResolver cr, String[] projection,
-                String where, String orderBy) {
-            return cr.query(CONTENT_URI, projection, where,
-                                         null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);
-        }
-
-        /**
-         * The content:// style URL for this table
-         */
-        public static final Uri CONTENT_URI =
-            Uri.parse("content://sms");
-
-        /**
-         * The default sort order for this table
-         */
-        public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-        /**
-         * Add an SMS to the given URI.
-         *
-         * @param resolver the content resolver to use
-         * @param uri the URI to add the message to
-         * @param address the address of the sender
-         * @param body the body of the message
-         * @param subject the psuedo-subject of the message
-         * @param date the timestamp for the message
-         * @param read true if the message has been read, false if not
-         * @param deliveryReport true if a delivery report was requested, false if not
-         * @return the URI for the new message
-         */
-        public static Uri addMessageToUri(ContentResolver resolver,
-                Uri uri, String address, String body, String subject,
-                Long date, boolean read, boolean deliveryReport) {
-            return addMessageToUri(resolver, uri, address, body, subject,
-                    date, read, deliveryReport, -1L);
-        }
-
-        /**
-         * Add an SMS to the given URI with thread_id specified.
-         *
-         * @param resolver the content resolver to use
-         * @param uri the URI to add the message to
-         * @param address the address of the sender
-         * @param body the body of the message
-         * @param subject the psuedo-subject of the message
-         * @param date the timestamp for the message
-         * @param read true if the message has been read, false if not
-         * @param deliveryReport true if a delivery report was requested, false if not
-         * @param threadId the thread_id of the message
-         * @return the URI for the new message
-         */
-        public static Uri addMessageToUri(ContentResolver resolver,
-                Uri uri, String address, String body, String subject,
-                Long date, boolean read, boolean deliveryReport, long threadId) {
-            ContentValues values = new ContentValues(7);
-
-            values.put(ADDRESS, address);
-            if (date != null) {
-                values.put(DATE, date);
-            }
-            values.put(READ, read ? Integer.valueOf(1) : Integer.valueOf(0));
-            values.put(SUBJECT, subject);
-            values.put(BODY, body);
-            if (deliveryReport) {
-                values.put(STATUS, STATUS_PENDING);
-            }
-            if (threadId != -1L) {
-                values.put(THREAD_ID, threadId);
-            }
-            return resolver.insert(uri, values);
-        }
-
-        /**
-         * Move a message to the given folder.
-         *
-         * @param context the context to use
-         * @param uri the message to move
-         * @param folder the folder to move to
-         * @return true if the operation succeeded
-         */
-        public static boolean moveMessageToFolder(Context context,
-                Uri uri, int folder, int error) {
-            if (uri == null) {
-                return false;
-            }
-
-            boolean markAsUnread = false;
-            boolean markAsRead = false;
-            switch(folder) {
-            case MESSAGE_TYPE_INBOX:
-            case MESSAGE_TYPE_DRAFT:
-                break;
-            case MESSAGE_TYPE_OUTBOX:
-            case MESSAGE_TYPE_SENT:
-                markAsRead = true;
-                break;
-            case MESSAGE_TYPE_FAILED:
-            case MESSAGE_TYPE_QUEUED:
-                markAsUnread = true;
-                break;
-            default:
-                return false;
-            }
-
-            ContentValues values = new ContentValues(3);
-
-            values.put(TYPE, folder);
-            if (markAsUnread) {
-                values.put(READ, Integer.valueOf(0));
-            } else if (markAsRead) {
-                values.put(READ, Integer.valueOf(1));
-            }
-            values.put(ERROR_CODE, error);
-
-            return 1 == SqliteWrapper.update(context, context.getContentResolver(),
-                            uri, values, null, null);
-        }
-
-        /**
-         * Returns true iff the folder (message type) identifies an
-         * outgoing message.
-         */
-        public static boolean isOutgoingFolder(int messageType) {
-            return  (messageType == MESSAGE_TYPE_FAILED)
-                    || (messageType == MESSAGE_TYPE_OUTBOX)
-                    || (messageType == MESSAGE_TYPE_SENT)
-                    || (messageType == MESSAGE_TYPE_QUEUED);
-        }
-
-        /**
-         * Contains all text based SMS messages in the SMS app's inbox.
-         */
-        public static final class Inbox implements BaseColumns, TextBasedSmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI =
-                Uri.parse("content://sms/inbox");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-            /**
-             * Add an SMS to the Draft box.
-             *
-             * @param resolver the content resolver to use
-             * @param address the address of the sender
-             * @param body the body of the message
-             * @param subject the psuedo-subject of the message
-             * @param date the timestamp for the message
-             * @param read true if the message has been read, false if not
-             * @return the URI for the new message
-             */
-            public static Uri addMessage(ContentResolver resolver,
-                    String address, String body, String subject, Long date,
-                    boolean read) {
-                return addMessageToUri(resolver, CONTENT_URI, address, body,
-                        subject, date, read, false);
-            }
-        }
-
-        /**
-         * Contains all sent text based SMS messages in the SMS app's.
-         */
-        public static final class Sent implements BaseColumns, TextBasedSmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI =
-                    Uri.parse("content://sms/sent");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-            /**
-             * Add an SMS to the Draft box.
-             *
-             * @param resolver the content resolver to use
-             * @param address the address of the sender
-             * @param body the body of the message
-             * @param subject the psuedo-subject of the message
-             * @param date the timestamp for the message
-             * @return the URI for the new message
-             */
-            public static Uri addMessage(ContentResolver resolver,
-                    String address, String body, String subject, Long date) {
-                return addMessageToUri(resolver, CONTENT_URI, address, body,
-                        subject, date, true, false);
-            }
-        }
-
-        /**
-         * Contains all sent text based SMS messages in the SMS app's.
-         */
-        public static final class Draft implements BaseColumns, TextBasedSmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI =
-                    Uri.parse("content://sms/draft");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-            /**
-             * Add an SMS to the Draft box.
-             *
-             * @param resolver the content resolver to use
-             * @param address the address of the sender
-             * @param body the body of the message
-             * @param subject the psuedo-subject of the message
-             * @param date the timestamp for the message
-             * @return the URI for the new message
-             */
-            public static Uri addMessage(ContentResolver resolver,
-                    String address, String body, String subject, Long date) {
-                return addMessageToUri(resolver, CONTENT_URI, address, body,
-                        subject, date, true, false);
-            }
-
-            /**
-             * Save over an existing draft message.
-             *
-             * @param resolver the content resolver to use
-             * @param uri of existing message
-             * @param body the new body for the draft message
-             * @return true is successful, false otherwise
-             */
-            public static boolean saveMessage(ContentResolver resolver,
-                    Uri uri, String body) {
-                ContentValues values = new ContentValues(2);
-                values.put(BODY, body);
-                values.put(DATE, System.currentTimeMillis());
-                return resolver.update(uri, values, null, null) == 1;
-            }
-        }
-
-        /**
-         * Contains all pending outgoing text based SMS messages.
-         */
-        public static final class Outbox implements BaseColumns, TextBasedSmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI =
-                Uri.parse("content://sms/outbox");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-            /**
-             * Add an SMS to the Out box.
-             *
-             * @param resolver the content resolver to use
-             * @param address the address of the sender
-             * @param body the body of the message
-             * @param subject the psuedo-subject of the message
-             * @param date the timestamp for the message
-             * @param deliveryReport whether a delivery report was requested for the message
-             * @return the URI for the new message
-             */
-            public static Uri addMessage(ContentResolver resolver,
-                    String address, String body, String subject, Long date,
-                    boolean deliveryReport, long threadId) {
-                return addMessageToUri(resolver, CONTENT_URI, address, body,
-                        subject, date, true, deliveryReport, threadId);
-            }
-        }
-
-        /**
-         * Contains all sent text-based SMS messages in the SMS app's.
-         */
-        public static final class Conversations
-                implements BaseColumns, TextBasedSmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI =
-                Uri.parse("content://sms/conversations");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-            /**
-             * The first 45 characters of the body of the message
-             * <P>Type: TEXT</P>
-             */
-            public static final String SNIPPET = "snippet";
-
-            /**
-             * The number of messages in the conversation
-             * <P>Type: INTEGER</P>
-             */
-            public static final String MESSAGE_COUNT = "msg_count";
-        }
-
-        /**
-         * Contains info about SMS related Intents that are broadcast.
-         */
-        public static final class Intents {
-            /**
-             * Set by BroadcastReceiver. Indicates the message was handled
-             * successfully.
-             */
-            public static final int RESULT_SMS_HANDLED = 1;
-
-            /**
-             * Set by BroadcastReceiver. Indicates a generic error while
-             * processing the message.
-             */
-            public static final int RESULT_SMS_GENERIC_ERROR = 2;
-
-            /**
-             * Set by BroadcastReceiver. Indicates insufficient memory to store
-             * the message.
-             */
-            public static final int RESULT_SMS_OUT_OF_MEMORY = 3;
-
-            /**
-             * Set by BroadcastReceiver. Indicates the message, while
-             * possibly valid, is of a format or encoding that is not
-             * supported.
-             */
-            public static final int RESULT_SMS_UNSUPPORTED = 4;
-
-            /**
-             * Broadcast Action: A new text based SMS message has been received
-             * by the device. The intent will have the following extra
-             * values:</p>
-             *
-             * <ul>
-             *   <li><em>pdus</em> - An Object[] od byte[]s containing the PDUs
-             *   that make up the message.</li>
-             * </ul>
-             *
-             * <p>The extra values can be extracted using
-             * {@link #getMessagesFromIntent(Intent)}.</p>
-             *
-             * <p>If a BroadcastReceiver encounters an error while processing
-             * this intent it should set the result code appropriately.</p>
-             */
-            public static final String SMS_RECEIVED_ACTION =
-                    "android.provider.Telephony.SMS_RECEIVED";
-
-            /**
-             * Broadcast Action: A new data based SMS message has been received
-             * by the device. The intent will have the following extra
-             * values:</p>
-             *
-             * <ul>
-             *   <li><em>pdus</em> - An Object[] od byte[]s containing the PDUs
-             *   that make up the message.</li>
-             * </ul>
-             *
-             * <p>The extra values can be extracted using
-             * {@link #getMessagesFromIntent(Intent)}.</p>
-             *
-             * <p>If a BroadcastReceiver encounters an error while processing
-             * this intent it should set the result code appropriately.</p>
-             */
-            public static final String DATA_SMS_RECEIVED_ACTION =
-                    "android.intent.action.DATA_SMS_RECEIVED";
-
-            /**
-             * Broadcast Action: A new WAP PUSH message has been received by the
-             * device. The intent will have the following extra
-             * values:</p>
-             *
-             * <ul>
-             *   <li><em>transactionId (Integer)</em> - The WAP transaction
-             *    ID</li>
-             *   <li><em>pduType (Integer)</em> - The WAP PDU type</li>
-             *   <li><em>header (byte[])</em> - The header of the message</li>
-             *   <li><em>data (byte[])</em> - The data payload of the message</li>
-             * </ul>
-             *
-             * <p>If a BroadcastReceiver encounters an error while processing
-             * this intent it should set the result code appropriately.</p>
-             */
-            public static final String WAP_PUSH_RECEIVED_ACTION =
-                    "android.provider.Telephony.WAP_PUSH_RECEIVED";
-
-            /**
-             * Broadcast Action: The SIM storage for SMS messages is full.  If
-             * space is not freed, messages targeted for the SIM (class 2) may
-             * not be saved.
-             */
-            public static final String SIM_FULL_ACTION =
-                "android.provider.Telephony.SIM_FULL";
-
-            /**
-             * Broadcast Action: An incoming SMS has been rejected by the
-             * telephony framework.  This intent is sent in lieu of any
-             * of the RECEIVED_ACTION intents.  The intent will have the
-             * following extra value:</p>
-             *
-             * <ul>
-             *   <li><em>result</em> - An int result code, eg,
-             *   <code>{@link #RESULT_SMS_OUT_OF_MEMORY}</code>,
-             *   indicating the error returned to the network.</li>
-             * </ul>
-
-             */
-            public static final String SMS_REJECTED_ACTION =
-                "android.provider.Telephony.SMS_REJECTED";
-
-            /**
-             * Broadcast Action: The phone service state has changed. The intent will have the following
-             * extra values:</p>
-             * <ul>
-             *   <li><em>state</em> - An int with one of the following values:
-             *          {@link android.telephony.ServiceState#STATE_IN_SERVICE},
-             *          {@link android.telephony.ServiceState#STATE_OUT_OF_SERVICE},
-             *          {@link android.telephony.ServiceState#STATE_EMERGENCY_ONLY}
-             *          or {@link android.telephony.ServiceState#STATE_POWER_OFF}
-             *   <li><em>roaming</em> - A boolean value indicating whether the phone is roaming.</li>
-             *   <li><em>operator-alpha-long</em> - The carrier name as a string.</li>
-             *   <li><em>operator-alpha-short</em> - A potentially shortened version of the carrier name,
-             *          as a string.</li>
-             *   <li><em>operator-numeric</em> - A number representing the carrier, as a string. This is
-             *          a five or six digit number consisting of the MCC (Mobile Country Code, 3 digits)
-             *          and MNC (Mobile Network code, 2-3 digits).</li>
-             *   <li><em>manual</em> - A boolean, where true indicates that the user has chosen to select
-             *          the network manually, and false indicates that network selection is handled by the
-             *          phone.</li>
-             * </ul>
-             *
-             * <p class="note">
-             * Requires the READ_PHONE_STATE permission.
-             *
-             * <p class="note">This is a protected intent that can only be sent
-             * by the system.
-             */
-            public static final String ACTION_SERVICE_STATE_CHANGED =
-                "android.intent.action.SERVICE_STATE";
-
-            /**
-             * Read the PDUs out of an {@link #SMS_RECEIVED_ACTION} or a
-             * {@link #DATA_SMS_RECEIVED_ACTION} intent.
-             *
-             * @param intent the intent to read from
-             * @return an array of SmsMessages for the PDUs
-             */
-            public static final SmsMessage[] getMessagesFromIntent(
-                    Intent intent) {
-                Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
-                byte[][] pduObjs = new byte[messages.length][];
-
-                for (int i = 0; i < messages.length; i++) {
-                    pduObjs[i] = (byte[]) messages[i];
-                }
-                byte[][] pdus = new byte[pduObjs.length][];
-                int pduCount = pdus.length;
-                SmsMessage[] msgs = new SmsMessage[pduCount];
-                for (int i = 0; i < pduCount; i++) {
-                    pdus[i] = pduObjs[i];
-                    msgs[i] = SmsMessage.createFromPdu(pdus[i]);
-                }
-                return msgs;
-            }
-        }
-    }
-
-    /**
-     * Base columns for tables that contain MMSs.
-     */
-    public interface BaseMmsColumns extends BaseColumns {
-
-        public static final int MESSAGE_BOX_ALL    = 0;
-        public static final int MESSAGE_BOX_INBOX  = 1;
-        public static final int MESSAGE_BOX_SENT   = 2;
-        public static final int MESSAGE_BOX_DRAFTS = 3;
-        public static final int MESSAGE_BOX_OUTBOX = 4;
-
-        /**
-         * The date the message was sent.
-         * <P>Type: INTEGER (long)</P>
-         */
-        public static final String DATE = "date";
-
-        /**
-         * The box which the message belong to, for example, MESSAGE_BOX_INBOX.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MESSAGE_BOX = "msg_box";
-
-        /**
-         * Has the message been read.
-         * <P>Type: INTEGER (boolean)</P>
-         */
-        public static final String READ = "read";
-
-        /**
-         * Indicates whether this message has been seen by the user. The "seen" flag will be
-         * used to figure out whether we need to throw up a statusbar notification or not.
-         */
-        public static final String SEEN = "seen";
-
-        /**
-         * The Message-ID of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String MESSAGE_ID = "m_id";
-
-        /**
-         * The subject of the message, if present.
-         * <P>Type: TEXT</P>
-         */
-        public static final String SUBJECT = "sub";
-
-        /**
-         * The character set of the subject, if present.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String SUBJECT_CHARSET = "sub_cs";
-
-        /**
-         * The Content-Type of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CONTENT_TYPE = "ct_t";
-
-        /**
-         * The Content-Location of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CONTENT_LOCATION = "ct_l";
-
-        /**
-         * The address of the sender.
-         * <P>Type: TEXT</P>
-         */
-        public static final String FROM = "from";
-
-        /**
-         * The address of the recipients.
-         * <P>Type: TEXT</P>
-         */
-        public static final String TO = "to";
-
-        /**
-         * The address of the cc. recipients.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CC = "cc";
-
-        /**
-         * The address of the bcc. recipients.
-         * <P>Type: TEXT</P>
-         */
-        public static final String BCC = "bcc";
-
-        /**
-         * The expiry time of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String EXPIRY = "exp";
-
-        /**
-         * The class of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String MESSAGE_CLASS = "m_cls";
-
-        /**
-         * The type of the message defined by MMS spec.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MESSAGE_TYPE = "m_type";
-
-        /**
-         * The version of specification that this message conform.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MMS_VERSION = "v";
-
-        /**
-         * The size of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MESSAGE_SIZE = "m_size";
-
-        /**
-         * The priority of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String PRIORITY = "pri";
-
-        /**
-         * The read-report of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String READ_REPORT = "rr";
-
-        /**
-         * Whether the report is allowed.
-         * <P>Type: TEXT</P>
-         */
-        public static final String REPORT_ALLOWED = "rpt_a";
-
-        /**
-         * The response-status of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String RESPONSE_STATUS = "resp_st";
-
-        /**
-         * The status of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String STATUS = "st";
-
-        /**
-         * The transaction-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String TRANSACTION_ID = "tr_id";
-
-        /**
-         * The retrieve-status of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String RETRIEVE_STATUS = "retr_st";
-
-        /**
-         * The retrieve-text of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String RETRIEVE_TEXT = "retr_txt";
-
-        /**
-         * The character set of the retrieve-text.
-         * <P>Type: TEXT</P>
-         */
-        public static final String RETRIEVE_TEXT_CHARSET = "retr_txt_cs";
-
-        /**
-         * The read-status of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String READ_STATUS = "read_status";
-
-        /**
-         * The content-class of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String CONTENT_CLASS = "ct_cls";
-
-        /**
-         * The delivery-report of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String DELIVERY_REPORT = "d_rpt";
-
-        /**
-         * The delivery-time-token of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String DELIVERY_TIME_TOKEN = "d_tm_tok";
-
-        /**
-         * The delivery-time of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String DELIVERY_TIME = "d_tm";
-
-        /**
-         * The response-text of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String RESPONSE_TEXT = "resp_txt";
-
-        /**
-         * The sender-visibility of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String SENDER_VISIBILITY = "s_vis";
-
-        /**
-         * The reply-charging of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String REPLY_CHARGING = "r_chg";
-
-        /**
-         * The reply-charging-deadline-token of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String REPLY_CHARGING_DEADLINE_TOKEN = "r_chg_dl_tok";
-
-        /**
-         * The reply-charging-deadline of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String REPLY_CHARGING_DEADLINE = "r_chg_dl";
-
-        /**
-         * The reply-charging-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String REPLY_CHARGING_ID = "r_chg_id";
-
-        /**
-         * The reply-charging-size of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String REPLY_CHARGING_SIZE = "r_chg_sz";
-
-        /**
-         * The previously-sent-by of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String PREVIOUSLY_SENT_BY = "p_s_by";
-
-        /**
-         * The previously-sent-date of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String PREVIOUSLY_SENT_DATE = "p_s_d";
-
-        /**
-         * The store of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String STORE = "store";
-
-        /**
-         * The mm-state of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MM_STATE = "mm_st";
-
-        /**
-         * The mm-flags-token of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MM_FLAGS_TOKEN = "mm_flg_tok";
-
-        /**
-         * The mm-flags of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String MM_FLAGS = "mm_flg";
-
-        /**
-         * The store-status of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String STORE_STATUS = "store_st";
-
-        /**
-         * The store-status-text of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String STORE_STATUS_TEXT = "store_st_txt";
-
-        /**
-         * The stored of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String STORED = "stored";
-
-        /**
-         * The totals of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String TOTALS = "totals";
-
-        /**
-         * The mbox-totals of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String MBOX_TOTALS = "mb_t";
-
-        /**
-         * The mbox-totals-token of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MBOX_TOTALS_TOKEN = "mb_t_tok";
-
-        /**
-         * The quotas of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String QUOTAS = "qt";
-
-        /**
-         * The mbox-quotas of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String MBOX_QUOTAS = "mb_qt";
-
-        /**
-         * The mbox-quotas-token of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MBOX_QUOTAS_TOKEN = "mb_qt_tok";
-
-        /**
-         * The message-count of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MESSAGE_COUNT = "m_cnt";
-
-        /**
-         * The start of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String START = "start";
-
-        /**
-         * The distribution-indicator of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String DISTRIBUTION_INDICATOR = "d_ind";
-
-        /**
-         * The element-descriptor of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String ELEMENT_DESCRIPTOR = "e_des";
-
-        /**
-         * The limit of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String LIMIT = "limit";
-
-        /**
-         * The recommended-retrieval-mode of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String RECOMMENDED_RETRIEVAL_MODE = "r_r_mod";
-
-        /**
-         * The recommended-retrieval-mode-text of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String RECOMMENDED_RETRIEVAL_MODE_TEXT = "r_r_mod_txt";
-
-        /**
-         * The status-text of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String STATUS_TEXT = "st_txt";
-
-        /**
-         * The applic-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String APPLIC_ID = "apl_id";
-
-        /**
-         * The reply-applic-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String REPLY_APPLIC_ID = "r_apl_id";
-
-        /**
-         * The aux-applic-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String AUX_APPLIC_ID = "aux_apl_id";
-
-        /**
-         * The drm-content of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String DRM_CONTENT = "drm_c";
-
-        /**
-         * The adaptation-allowed of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String ADAPTATION_ALLOWED = "adp_a";
-
-        /**
-         * The replace-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String REPLACE_ID = "repl_id";
-
-        /**
-         * The cancel-id of the message.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CANCEL_ID = "cl_id";
-
-        /**
-         * The cancel-status of the message.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String CANCEL_STATUS = "cl_st";
-
-        /**
-         * The thread ID of the message
-         * <P>Type: INTEGER</P>
-         */
-        public static final String THREAD_ID = "thread_id";
-
-        /**
-         * Has the message been locked?
-         * <P>Type: INTEGER (boolean)</P>
-         */
-        public static final String LOCKED = "locked";
-    }
-
-    /**
-     * Columns for the "canonical_addresses" table used by MMS and
-     * SMS."
-     */
-    public interface CanonicalAddressesColumns extends BaseColumns {
-        /**
-         * An address used in MMS or SMS.  Email addresses are
-         * converted to lower case and are compared by string
-         * equality.  Other addresses are compared using
-         * PHONE_NUMBERS_EQUAL.
-         * <P>Type: TEXT</P>
-         */
-        public static final String ADDRESS = "address";
-    }
-
-    /**
-     * Columns for the "threads" table used by MMS and SMS.
-     */
-    public interface ThreadsColumns extends BaseColumns {
-        /**
-         * The date at which the thread was created.
-         *
-         * <P>Type: INTEGER (long)</P>
-         */
-        public static final String DATE = "date";
-
-        /**
-         * A string encoding of the recipient IDs of the recipients of
-         * the message, in numerical order and separated by spaces.
-         * <P>Type: TEXT</P>
-         */
-        public static final String RECIPIENT_IDS = "recipient_ids";
-
-        /**
-         * The message count of the thread.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String MESSAGE_COUNT = "message_count";
-        /**
-         * Indicates whether all messages of the thread have been read.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String READ = "read";
-
-        /**
-         * The snippet of the latest message in the thread.
-         * <P>Type: TEXT</P>
-         */
-        public static final String SNIPPET = "snippet";
-        /**
-         * The charset of the snippet.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String SNIPPET_CHARSET = "snippet_cs";
-        /**
-         * Type of the thread, either Threads.COMMON_THREAD or
-         * Threads.BROADCAST_THREAD.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String TYPE = "type";
-        /**
-         * Indicates whether there is a transmission error in the thread.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String ERROR = "error";
-        /**
-         * Indicates whether this thread contains any attachments.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String HAS_ATTACHMENT = "has_attachment";
-    }
-
-    /**
-     * Helper functions for the "threads" table used by MMS and SMS.
-     */
-    public static final class Threads implements ThreadsColumns {
-        private static final String[] ID_PROJECTION = { BaseColumns._ID };
-        private static final String STANDARD_ENCODING = "UTF-8";
-        private static final Uri THREAD_ID_CONTENT_URI = Uri.parse(
-                "content://mms-sms/threadID");
-        public static final Uri CONTENT_URI = Uri.withAppendedPath(
-                MmsSms.CONTENT_URI, "conversations");
-        public static final Uri OBSOLETE_THREADS_URI = Uri.withAppendedPath(
-                CONTENT_URI, "obsolete");
-
-        public static final int COMMON_THREAD    = 0;
-        public static final int BROADCAST_THREAD = 1;
-
-        // No one should construct an instance of this class.
-        private Threads() {
-        }
-
-        /**
-         * This is a single-recipient version of
-         * getOrCreateThreadId.  It's convenient for use with SMS
-         * messages.
-         */
-        public static long getOrCreateThreadId(Context context, String recipient) {
-            Set<String> recipients = new HashSet<String>();
-
-            recipients.add(recipient);
-            return getOrCreateThreadId(context, recipients);
-        }
-
-        /**
-         * Given the recipients list and subject of an unsaved message,
-         * return its thread ID.  If the message starts a new thread,
-         * allocate a new thread ID.  Otherwise, use the appropriate
-         * existing thread ID.
-         *
-         * Find the thread ID of the same set of recipients (in
-         * any order, without any additions). If one
-         * is found, return it.  Otherwise, return a unique thread ID.
-         */
-        public static long getOrCreateThreadId(
-                Context context, Set<String> recipients) {
-            Uri.Builder uriBuilder = THREAD_ID_CONTENT_URI.buildUpon();
-
-            for (String recipient : recipients) {
-                if (Mms.isEmailAddress(recipient)) {
-                    recipient = Mms.extractAddrSpec(recipient);
-                }
-
-                uriBuilder.appendQueryParameter("recipient", recipient);
-            }
-
-            Uri uri = uriBuilder.build();
-            if (DEBUG) {
-                Log.v(TAG, "getOrCreateThreadId uri: " + uri);
-            }
-            Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
-                    uri, ID_PROJECTION, null, null, null);
-            if (DEBUG) {
-                Log.v(TAG, "getOrCreateThreadId cursor cnt: " + cursor.getCount());
-            }
-            if (cursor != null) {
-                try {
-                    if (cursor.moveToFirst()) {
-                        return cursor.getLong(0);
-                    } else {
-                        Log.e(TAG, "getOrCreateThreadId returned no rows!");
-                    }
-                } finally {
-                    cursor.close();
-                }
-            }
-
-            Log.e(TAG, "getOrCreateThreadId failed with uri " + uri.toString());
-            throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
-        }
-    }
-
-    /**
-     * Contains all MMS messages.
-     */
-    public static final class Mms implements BaseMmsColumns {
-        /**
-         * The content:// style URL for this table
-         */
-        public static final Uri CONTENT_URI = Uri.parse("content://mms");
-
-        public static final Uri REPORT_REQUEST_URI = Uri.withAppendedPath(
-                                            CONTENT_URI, "report-request");
-
-        public static final Uri REPORT_STATUS_URI = Uri.withAppendedPath(
-                                            CONTENT_URI, "report-status");
-
-        /**
-         * The default sort order for this table
-         */
-        public static final String DEFAULT_SORT_ORDER = "date DESC";
-
-        /**
-         * mailbox         =       name-addr
-         * name-addr       =       [display-name] angle-addr
-         * angle-addr      =       [CFWS] "<" addr-spec ">" [CFWS]
-         */
-        public static final Pattern NAME_ADDR_EMAIL_PATTERN =
-                Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*");
-
-        /**
-         * quoted-string   =       [CFWS]
-         *                         DQUOTE *([FWS] qcontent) [FWS] DQUOTE
-         *                         [CFWS]
-         */
-        public static final Pattern QUOTED_STRING_PATTERN =
-                Pattern.compile("\\s*\"([^\"]*)\"\\s*");
-
-        public static final Cursor query(
-                ContentResolver cr, String[] projection) {
-            return cr.query(CONTENT_URI, projection, null, null, DEFAULT_SORT_ORDER);
-        }
-
-        public static final Cursor query(
-                ContentResolver cr, String[] projection,
-                String where, String orderBy) {
-            return cr.query(CONTENT_URI, projection,
-                    where, null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);
-        }
-
-        public static final String getMessageBoxName(int msgBox) {
-            switch (msgBox) {
-                case MESSAGE_BOX_ALL:
-                    return "all";
-                case MESSAGE_BOX_INBOX:
-                    return "inbox";
-                case MESSAGE_BOX_SENT:
-                    return "sent";
-                case MESSAGE_BOX_DRAFTS:
-                    return "drafts";
-                case MESSAGE_BOX_OUTBOX:
-                    return "outbox";
-                default:
-                    throw new IllegalArgumentException("Invalid message box: " + msgBox);
-            }
-        }
-
-        public static String extractAddrSpec(String address) {
-            Matcher match = NAME_ADDR_EMAIL_PATTERN.matcher(address);
-
-            if (match.matches()) {
-                return match.group(2);
-            }
-            return address;
-        }
-
-        /**
-         * Returns true if the address is an email address
-         *
-         * @param address the input address to be tested
-         * @return true if address is an email address
-         */
-        public static boolean isEmailAddress(String address) {
-            if (TextUtils.isEmpty(address)) {
-                return false;
-            }
-
-            String s = extractAddrSpec(address);
-            Matcher match = Patterns.EMAIL_ADDRESS.matcher(s);
-            return match.matches();
-        }
-
-        /**
-         * Returns true if the number is a Phone number
-         *
-         * @param number the input number to be tested
-         * @return true if number is a Phone number
-         */
-        public static boolean isPhoneNumber(String number) {
-            if (TextUtils.isEmpty(number)) {
-                return false;
-            }
-
-            Matcher match = Patterns.PHONE.matcher(number);
-            return match.matches();
-        }
-
-        /**
-         * Contains all MMS messages in the MMS app's inbox.
-         */
-        public static final class Inbox implements BaseMmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri
-                    CONTENT_URI = Uri.parse("content://mms/inbox");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-        }
-
-        /**
-         * Contains all MMS messages in the MMS app's sent box.
-         */
-        public static final class Sent implements BaseMmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri
-                    CONTENT_URI = Uri.parse("content://mms/sent");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-        }
-
-        /**
-         * Contains all MMS messages in the MMS app's drafts box.
-         */
-        public static final class Draft implements BaseMmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri
-                    CONTENT_URI = Uri.parse("content://mms/drafts");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-        }
-
-        /**
-         * Contains all MMS messages in the MMS app's outbox.
-         */
-        public static final class Outbox implements BaseMmsColumns {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri
-                    CONTENT_URI = Uri.parse("content://mms/outbox");
-
-            /**
-             * The default sort order for this table
-             */
-            public static final String DEFAULT_SORT_ORDER = "date DESC";
-        }
-
-        public static final class Addr implements BaseColumns {
-            /**
-             * The ID of MM which this address entry belongs to.
-             */
-            public static final String MSG_ID = "msg_id";
-
-            /**
-             * The ID of contact entry in Phone Book.
-             */
-            public static final String CONTACT_ID = "contact_id";
-
-            /**
-             * The address text.
-             */
-            public static final String ADDRESS = "address";
-
-            /**
-             * Type of address, must be one of PduHeaders.BCC,
-             * PduHeaders.CC, PduHeaders.FROM, PduHeaders.TO.
-             */
-            public static final String TYPE = "type";
-
-            /**
-             * Character set of this entry.
-             */
-            public static final String CHARSET = "charset";
-        }
-
-        public static final class Part implements BaseColumns {
-            /**
-             * The identifier of the message which this part belongs to.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String MSG_ID = "mid";
-
-            /**
-             * The order of the part.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String SEQ = "seq";
-
-            /**
-             * The content type of the part.
-             * <P>Type: TEXT</P>
-             */
-            public static final String CONTENT_TYPE = "ct";
-
-            /**
-             * The name of the part.
-             * <P>Type: TEXT</P>
-             */
-            public static final String NAME = "name";
-
-            /**
-             * The charset of the part.
-             * <P>Type: TEXT</P>
-             */
-            public static final String CHARSET = "chset";
-
-            /**
-             * The file name of the part.
-             * <P>Type: TEXT</P>
-             */
-            public static final String FILENAME = "fn";
-
-            /**
-             * The content disposition of the part.
-             * <P>Type: TEXT</P>
-             */
-            public static final String CONTENT_DISPOSITION = "cd";
-
-            /**
-             * The content ID of the part.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String CONTENT_ID = "cid";
-
-            /**
-             * The content location of the part.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String CONTENT_LOCATION = "cl";
-
-            /**
-             * The start of content-type of the message.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String CT_START = "ctt_s";
-
-            /**
-             * The type of content-type of the message.
-             * <P>Type: TEXT</P>
-             */
-            public static final String CT_TYPE = "ctt_t";
-
-            /**
-             * The location(on filesystem) of the binary data of the part.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String _DATA = "_data";
-
-            public static final String TEXT = "text";
-
-        }
-
-        public static final class Rate {
-            public static final Uri CONTENT_URI = Uri.withAppendedPath(
-                    Mms.CONTENT_URI, "rate");
-            /**
-             * When a message was successfully sent.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String SENT_TIME = "sent_time";
-        }
-
-        public static final class ScrapSpace {
-            /**
-             * The content:// style URL for this table
-             */
-            public static final Uri CONTENT_URI = Uri.parse("content://mms/scrapSpace");
-
-            /**
-             * This is the scrap file we use to store the media attachment when the user
-             * chooses to capture a photo to be attached . We pass {#link@Uri} to the Camera app,
-             * which streams the captured image to the uri. Internally we write the media content
-             * to this file. It's named '.temp.jpg' so Gallery won't pick it up.
-             */
-            public static final String SCRAP_FILE_PATH = "/sdcard/mms/scrapSpace/.temp.jpg";
-        }
-
-        public static final class Intents {
-            private Intents() {
-                // Non-instantiatable.
-            }
-
-            /**
-             * The extra field to store the contents of the Intent,
-             * which should be an array of Uri.
-             */
-            public static final String EXTRA_CONTENTS = "contents";
-            /**
-             * The extra field to store the type of the contents,
-             * which should be an array of String.
-             */
-            public static final String EXTRA_TYPES    = "types";
-            /**
-             * The extra field to store the 'Cc' addresses.
-             */
-            public static final String EXTRA_CC       = "cc";
-            /**
-             * The extra field to store the 'Bcc' addresses;
-             */
-            public static final String EXTRA_BCC      = "bcc";
-            /**
-             * The extra field to store the 'Subject'.
-             */
-            public static final String EXTRA_SUBJECT  = "subject";
-            /**
-             * Indicates that the contents of specified URIs were changed.
-             * The application which is showing or caching these contents
-             * should be updated.
-             */
-            public static final String
-            CONTENT_CHANGED_ACTION = "android.intent.action.CONTENT_CHANGED";
-            /**
-             * An extra field which stores the URI of deleted contents.
-             */
-            public static final String DELETED_CONTENTS = "deleted_contents";
-        }
-    }
-
-    /**
-     * Contains all MMS and SMS messages.
-     */
-    public static final class MmsSms implements BaseColumns {
-        /**
-         * The column to distinguish SMS &amp; MMS messages in query results.
-         */
-        public static final String TYPE_DISCRIMINATOR_COLUMN =
-                "transport_type";
-
-        public static final Uri CONTENT_URI = Uri.parse("content://mms-sms/");
-
-        public static final Uri CONTENT_CONVERSATIONS_URI = Uri.parse(
-                "content://mms-sms/conversations");
-
-        public static final Uri CONTENT_FILTER_BYPHONE_URI = Uri.parse(
-                "content://mms-sms/messages/byphone");
-
-        public static final Uri CONTENT_UNDELIVERED_URI = Uri.parse(
-                "content://mms-sms/undelivered");
-
-        public static final Uri CONTENT_DRAFT_URI = Uri.parse(
-                "content://mms-sms/draft");
-
-        public static final Uri CONTENT_LOCKED_URI = Uri.parse(
-                "content://mms-sms/locked");
-
-        /***
-         * Pass in a query parameter called "pattern" which is the text
-         * to search for.
-         * The sort order is fixed to be thread_id ASC,date DESC.
-         */
-        public static final Uri SEARCH_URI = Uri.parse(
-                "content://mms-sms/search");
-
-        // Constants for message protocol types.
-        public static final int SMS_PROTO = 0;
-        public static final int MMS_PROTO = 1;
-
-        // Constants for error types of pending messages.
-        public static final int NO_ERROR                      = 0;
-        public static final int ERR_TYPE_GENERIC              = 1;
-        public static final int ERR_TYPE_SMS_PROTO_TRANSIENT  = 2;
-        public static final int ERR_TYPE_MMS_PROTO_TRANSIENT  = 3;
-        public static final int ERR_TYPE_TRANSPORT_FAILURE    = 4;
-        public static final int ERR_TYPE_GENERIC_PERMANENT    = 10;
-        public static final int ERR_TYPE_SMS_PROTO_PERMANENT  = 11;
-        public static final int ERR_TYPE_MMS_PROTO_PERMANENT  = 12;
-
-        public static final class PendingMessages implements BaseColumns {
-            public static final Uri CONTENT_URI = Uri.withAppendedPath(
-                    MmsSms.CONTENT_URI, "pending");
-            /**
-             * The type of transport protocol(MMS or SMS).
-             * <P>Type: INTEGER</P>
-             */
-            public static final String PROTO_TYPE = "proto_type";
-            /**
-             * The ID of the message to be sent or downloaded.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String MSG_ID = "msg_id";
-            /**
-             * The type of the message to be sent or downloaded.
-             * This field is only valid for MM. For SM, its value is always
-             * set to 0.
-             */
-            public static final String MSG_TYPE = "msg_type";
-            /**
-             * The type of the error code.
-             * <P>Type: INTEGER</P>
-             */
-            public static final String ERROR_TYPE = "err_type";
-            /**
-             * The error code of sending/retrieving process.
-             * <P>Type:  INTEGER</P>
-             */
-            public static final String ERROR_CODE = "err_code";
-            /**
-             * How many times we tried to send or download the message.
-             * <P>Type:  INTEGER</P>
-             */
-            public static final String RETRY_INDEX = "retry_index";
-            /**
-             * The time to do next retry.
-             */
-            public static final String DUE_TIME = "due_time";
-            /**
-             * The time we last tried to send or download the message.
-             */
-            public static final String LAST_TRY = "last_try";
-        }
-
-        public static final class WordsTable {
-            public static final String ID = "_id";
-            public static final String SOURCE_ROW_ID = "source_id";
-            public static final String TABLE_ID = "table_to_use";
-            public static final String INDEXED_TEXT = "index_text";
-        }
-    }
-
-    public static final class Carriers implements BaseColumns {
-        /**
-         * The content:// style URL for this table
-         */
-        public static final Uri CONTENT_URI =
-            Uri.parse("content://telephony/carriers");
-
-        /**
-         * The default sort order for this table
-         */
-        public static final String DEFAULT_SORT_ORDER = "name ASC";
-
-        public static final String NAME = "name";
-
-        public static final String APN = "apn";
-
-        public static final String PROXY = "proxy";
-
-        public static final String PORT = "port";
-
-        public static final String MMSPROXY = "mmsproxy";
-
-        public static final String MMSPORT = "mmsport";
-
-        public static final String SERVER = "server";
-
-        public static final String USER = "user";
-
-        public static final String PASSWORD = "password";
-
-        public static final String MMSC = "mmsc";
-
-        public static final String MCC = "mcc";
-
-        public static final String MNC = "mnc";
-
-        public static final String NUMERIC = "numeric";
-
-        public static final String AUTH_TYPE = "authtype";
-
-        public static final String TYPE = "type";
-
-        public static final String CURRENT = "current";
-    }
-
-    public static final class Intents {
-        private Intents() {
-            // Not instantiable
-        }
-
-        /**
-         * Broadcast Action: A "secret code" has been entered in the dialer. Secret codes are
-         * of the form *#*#<code>#*#*. The intent will have the data URI:</p>
-         *
-         * <p><code>android_secret_code://&lt;code&gt;</code></p>
-         */
-        public static final String SECRET_CODE_ACTION =
-                "android.provider.Telephony.SECRET_CODE";
-
-        /**
-         * Broadcast Action: The Service Provider string(s) have been updated.  Activities or
-         * services that use these strings should update their display.
-         * The intent will have the following extra values:</p>
-         * <ul>
-         *   <li><em>showPlmn</em> - Boolean that indicates whether the PLMN should be shown.</li>
-         *   <li><em>plmn</em> - The operator name of the registered network, as a string.</li>
-         *   <li><em>showSpn</em> - Boolean that indicates whether the SPN should be shown.</li>
-         *   <li><em>spn</em> - The service provider name, as a string.</li>
-         * </ul>
-         * Note that <em>showPlmn</em> may indicate that <em>plmn</em> should be displayed, even
-         * though the value for <em>plmn</em> is null.  This can happen, for example, if the phone
-         * has not registered to a network yet.  In this case the receiver may substitute an
-         * appropriate placeholder string (eg, "No service").
-         *
-         * It is recommended to display <em>plmn</em> before / above <em>spn</em> if
-         * both are displayed.
-         *
-         * <p>Note this is a protected intent that can only be sent
-         * by the system.
-         */
-        public static final String SPN_STRINGS_UPDATED_ACTION =
-                "android.provider.Telephony.SPN_STRINGS_UPDATED";
-
-        public static final String EXTRA_SHOW_PLMN  = "showPlmn";
-        public static final String EXTRA_PLMN       = "plmn";
-        public static final String EXTRA_SHOW_SPN   = "showSpn";
-        public static final String EXTRA_SPN        = "spn";
-    }
-}
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/SettingsProvider/etc/Android.mk b/packages/SettingsProvider/etc/Android.mk
deleted file mode 100644
index 81ca4b1..0000000
--- a/packages/SettingsProvider/etc/Android.mk
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# Copyright (C) 2008 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.
-#
-
-LOCAL_PATH := $(my-dir)
-
-########################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := bookmarks.xml
-
-LOCAL_MODULE_TAGS := user
-
-# This will install the file in /system/etc
-#
-LOCAL_MODULE_CLASS := ETC
-
-LOCAL_SRC_FILES := $(LOCAL_MODULE)
-
-include $(BUILD_PREBUILT)
-
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index 1e9c312..bd131e0 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -60,7 +60,7 @@
 
     <!-- user interface sound effects -->
     <integer name="def_power_sounds_enabled">1</integer>
-    <string name="def_low_battery_sound" translatable="false">/system/media/ui/LowBattery.ogg</string>
+    <string name="def_low_battery_sound" translatable="false">/system/media/audio/ui/LowBattery.ogg</string>
     <integer name="def_dock_sounds_enabled">0</integer>
     <string name="def_desk_dock_sound" translatable="false">/system/media/audio/ui/Dock.ogg</string>
     <string name="def_desk_undock_sound" translatable="false">/system/media/audio/ui/Undock.ogg</string>
diff --git a/packages/SettingsProvider/etc/bookmarks.xml b/packages/SettingsProvider/res/xml/bookmarks.xml
similarity index 88%
rename from packages/SettingsProvider/etc/bookmarks.xml
rename to packages/SettingsProvider/res/xml/bookmarks.xml
index 734e0cd..dfaeeaf 100644
--- a/packages/SettingsProvider/etc/bookmarks.xml
+++ b/packages/SettingsProvider/res/xml/bookmarks.xml
@@ -32,8 +32,8 @@
         class="com.google.android.gm.ConversationListActivityGmail"
         shortcut="g" />
     <bookmark
-        package="com.android.providers.im"
-        class="com.android.providers.im.LandingPage"
+        package="com.android.im"
+        class="com.android.im.app.LandingPage"
         shortcut="i" />
     <bookmark
         package="com.android.calendar"
@@ -53,8 +53,4 @@
         package="com.android.mms"
         class="com.android.mms.ui.ConversationList"
         shortcut="s" />
-    <bookmark
-        package="com.google.android.youtube"
-        class="com.google.android.youtube.HomeActivity"
-        shortcut="y" />
 </bookmarks>
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 18e247e..b05f1b3 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -23,39 +23,29 @@
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDoneException;
-import android.database.sqlite.SQLiteException;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteStatement;
 import android.media.AudioManager;
 import android.media.AudioService;
 import android.net.ConnectivityManager;
-import android.os.Environment;
 import android.os.SystemProperties;
 import android.provider.Settings;
-import android.speech.RecognitionService;
-import android.speech.RecognizerIntent;
+import android.provider.Settings.Secure;
 import android.text.TextUtils;
+import android.util.AttributeSet;
 import android.util.Config;
 import android.util.Log;
 import android.util.Xml;
 import com.android.internal.telephony.RILConstants;
 import com.android.internal.util.XmlUtils;
-
 import com.android.internal.widget.LockPatternUtils;
 import com.android.internal.widget.LockPatternView;
-
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
 import java.io.IOException;
 import java.util.List;
 
@@ -64,11 +54,6 @@
  * Mostly just has a bit {@link #onCreate} to initialize the database.
  */
 public class DatabaseHelper extends SQLiteOpenHelper {
-    /**
-     * Path to file containing default bookmarks, relative to ANDROID_ROOT.
-     */
-    private static final String DEFAULT_BOOKMARKS_PATH = "etc/bookmarks.xml";
-
     private static final String TAG = "SettingsProvider";
     private static final String DATABASE_NAME = "settings.db";
 
@@ -76,7 +61,7 @@
     // database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
     // is properly propagated through your change.  Not doing so will result in a loss of user
     // settings.
-    private static final int DATABASE_VERSION = 51;
+    private static final int DATABASE_VERSION = 52;
 
     private Context mContext;
 
@@ -157,7 +142,6 @@
              * notification vibrate to on.
              */
             loadVibrateSetting(db, true);
-            if (Config.LOGD) Log.d(TAG, "Reset system vibrate setting");
 
             upgradeVersion = 21;
         }
@@ -232,18 +216,7 @@
         }
 
         if (upgradeVersion == 27) {
-            // Copy settings values from 'system' to 'secure' and delete them from 'system'
-            SQLiteStatement insertStmt = null;
-            SQLiteStatement deleteStmt = null;
-
-            db.beginTransaction();
-            try {
-                insertStmt =
-                    db.compileStatement("INSERT INTO secure (name,value) SELECT name,value FROM "
-                        + "system WHERE name=?");
-                deleteStmt = db.compileStatement("DELETE FROM system WHERE name=?");
-
-                String[] settingsToMove = {
+            String[] settingsToMove = {
                     Settings.Secure.ADB_ENABLED,
                     Settings.Secure.ANDROID_ID,
                     Settings.Secure.BLUETOOTH_ON,
@@ -276,24 +249,7 @@
                     Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS,
                     Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS,
                 };
-
-                for (String setting : settingsToMove) {
-                    insertStmt.bindString(1, setting);
-                    insertStmt.execute();
-
-                    deleteStmt.bindString(1, setting);
-                    deleteStmt.execute();
-                }
-                db.setTransactionSuccessful();
-            } finally {
-                db.endTransaction();
-                if (insertStmt != null) {
-                    insertStmt.close();
-                }
-                if (deleteStmt != null) {
-                    deleteStmt.close();
-                }
-            }
+            moveFromSystemToSecure(db, settingsToMove);
             upgradeVersion = 28;
         }
 
@@ -661,6 +617,23 @@
            upgradeVersion = 51;
        }
 
+       if (upgradeVersion == 51) {
+           /* Move the lockscreen related settings to Secure, including some private ones. */
+           String[] settingsToMove = {
+                   Secure.LOCK_PATTERN_ENABLED,
+                   Secure.LOCK_PATTERN_VISIBLE,
+                   Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED,
+                   "lockscreen.password_type",
+                   "lockscreen.lockoutattemptdeadline",
+                   "lockscreen.patterneverchosen",
+                   "lock_pattern_autolock",
+                   "lockscreen.lockedoutpermanently",
+                   "lockscreen.password_salt"
+           };
+           moveFromSystemToSecure(db, settingsToMove);
+           upgradeVersion = 52;
+       }
+
        if (upgradeVersion != currentVersion) {
             Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
                     + ", must wipe the settings provider");
@@ -684,6 +657,38 @@
         }
     }
 
+    private void moveFromSystemToSecure(SQLiteDatabase db, String [] settingsToMove) {
+        // Copy settings values from 'system' to 'secure' and delete them from 'system'
+        SQLiteStatement insertStmt = null;
+        SQLiteStatement deleteStmt = null;
+
+        db.beginTransaction();
+        try {
+            insertStmt =
+                db.compileStatement("INSERT INTO secure (name,value) SELECT name,value FROM "
+                    + "system WHERE name=?");
+            deleteStmt = db.compileStatement("DELETE FROM system WHERE name=?");
+
+
+            for (String setting : settingsToMove) {
+                insertStmt.bindString(1, setting);
+                insertStmt.execute();
+
+                deleteStmt.bindString(1, setting);
+                deleteStmt.execute();
+            }
+            db.setTransactionSuccessful();
+        } finally {
+            db.endTransaction();
+            if (insertStmt != null) {
+                insertStmt.close();
+            }
+            if (deleteStmt != null) {
+                deleteStmt.close();
+            }
+        }
+    }
+
     private void upgradeLockPatternLocation(SQLiteDatabase db) {
         Cursor c = db.query("system", new String[] {"_id", "value"}, "name='lock_pattern'",
                 null, null, null, null);
@@ -713,39 +718,28 @@
      *
      * @param db The database to write the values into
      * @param startingIndex The zero-based position at which bookmarks in this file should begin
-     * @param subPath The relative path from ANDROID_ROOT to the file to read
-     * @param quiet If true, do no complain if the file is missing
      */
-    private int loadBookmarks(SQLiteDatabase db, int startingIndex, String subPath,
-            boolean quiet) {
-        FileReader bookmarksReader;
-
-        // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
-        final File favFile = new File(Environment.getRootDirectory(), subPath);
-        try {
-            bookmarksReader = new FileReader(favFile);
-        } catch (FileNotFoundException e) {
-            if (!quiet) {
-                Log.e(TAG, "Couldn't find or open bookmarks file " + favFile);
-            }
-            return 0;
-        }
-
+    private int loadBookmarks(SQLiteDatabase db, int startingIndex) {
         Intent intent = new Intent(Intent.ACTION_MAIN, null);
         intent.addCategory(Intent.CATEGORY_LAUNCHER);
         ContentValues values = new ContentValues();
 
         PackageManager packageManager = mContext.getPackageManager();
-        ActivityInfo info;
         int i = startingIndex;
-        try {
-            XmlPullParser parser = Xml.newPullParser();
-            parser.setInput(bookmarksReader);
 
+        try {
+            XmlResourceParser parser = mContext.getResources().getXml(R.xml.bookmarks);
             XmlUtils.beginDocument(parser, "bookmarks");
 
-            while (true) {
-                XmlUtils.nextElement(parser);
+            final int depth = parser.getDepth();
+            int type;
+
+            while (((type = parser.next()) != XmlPullParser.END_TAG ||
+                    parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
+
+                if (type != XmlPullParser.START_TAG) {
+                    continue;
+                }
 
                 String name = parser.getName();
                 if (!"bookmark".equals(name)) {
@@ -755,23 +749,36 @@
                 String pkg = parser.getAttributeValue(null, "package");
                 String cls = parser.getAttributeValue(null, "class");
                 String shortcutStr = parser.getAttributeValue(null, "shortcut");
+
                 int shortcutValue = (int) shortcutStr.charAt(0);
                 if (TextUtils.isEmpty(shortcutStr)) {
                     Log.w(TAG, "Unable to get shortcut for: " + pkg + "/" + cls);
                 }
+
+                ActivityInfo info = null;                
+                ComponentName cn = new ComponentName(pkg, cls);
                 try {
-                    ComponentName cn = new ComponentName(pkg, cls);
                     info = packageManager.getActivityInfo(cn, 0);
+                } catch (PackageManager.NameNotFoundException e) {
+                    String[] packages = packageManager.canonicalToCurrentPackageNames(
+                            new String[] { pkg });
+                    cn = new ComponentName(packages[0], cls);
+                    try {
+                        info = packageManager.getActivityInfo(cn, 0);
+                    } catch (PackageManager.NameNotFoundException e1) {
+                        Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
+                    }
+                }
+                
+                if (info != null) {
                     intent.setComponent(cn);
                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                    values.put(Settings.Bookmarks.INTENT, intent.toURI());
+                    values.put(Settings.Bookmarks.INTENT, intent.toUri(0));
                     values.put(Settings.Bookmarks.TITLE,
                             info.loadLabel(packageManager).toString());
                     values.put(Settings.Bookmarks.SHORTCUT, shortcutValue);
                     db.insert("bookmarks", null, values);
                     i++;
-                } catch (PackageManager.NameNotFoundException e) {
-                    Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
                 }
             }
         } catch (XmlPullParserException e) {
@@ -789,7 +796,7 @@
      * @param db The database to write the values into
      */
     private void loadBookmarks(SQLiteDatabase db) {
-        loadBookmarks(db, 0, DEFAULT_BOOKMARKS_PATH, false);
+        loadBookmarks(db, 0);
     }
 
     /**
@@ -868,8 +875,6 @@
         SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                 + " VALUES(?,?);");
 
-        Resources r = mContext.getResources();
-
         loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
                 R.bool.def_dim_screen);
         loadSetting(stmt, Settings.System.STAY_ON_WHILE_PLUGGED_IN,
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 7d648d3..942d32d 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -20,6 +20,8 @@
 import java.io.UnsupportedEncodingException;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
+import java.util.LinkedHashMap;
+import java.util.Map;
 
 import android.app.backup.BackupManager;
 import android.content.ContentProvider;
@@ -52,6 +54,14 @@
 
     private static final String[] COLUMN_VALUE = new String[] { "value" };
 
+    // Cache for settings, access-ordered for acting as LRU.
+    // Guarded by themselves.
+    private static final int MAX_CACHE_ENTRIES = 50;
+    private static final SettingsCache sSystemCache = new SettingsCache();
+    private static final SettingsCache sSecureCache = new SettingsCache();
+
+    private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
+
     protected DatabaseHelper mOpenHelper;
     private BackupManager mBackupManager;
 
@@ -193,7 +203,7 @@
         final Cursor c = query(Settings.Secure.CONTENT_URI,
                 new String[] { Settings.NameValueTable.VALUE },
                 Settings.NameValueTable.NAME + "=?",
-                new String[]{Settings.Secure.ANDROID_ID}, null);
+                new String[] { Settings.Secure.ANDROID_ID }, null);
         try {
             final String value = c.moveToNext() ? c.getString(0) : null;
             if (value == null) {
@@ -230,19 +240,23 @@
     @Override
     public Bundle call(String method, String request, Bundle args) {
         if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
-            return lookupValue("system", request);
+            return lookupValue("system", sSystemCache, request);
         }
-
         if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
-            return lookupValue("secure", request);
+            return lookupValue("secure", sSecureCache, request);
         }
         return null;
     }
 
     // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
     // possibly with a null value, or null on failure.
-    private Bundle lookupValue(String table, String key) {
-        // TODO: avoid database lookup and serve from in-process cache.
+    private Bundle lookupValue(String table, SettingsCache cache, String key) {
+        synchronized (cache) {
+            if (cache.containsKey(key)) {
+                return cache.get(key);
+            }
+        }
+
         SQLiteDatabase db = mOpenHelper.getReadableDatabase();
         Cursor cursor = null;
         try {
@@ -251,7 +265,9 @@
             if (cursor != null && cursor.getCount() == 1) {
                 cursor.moveToFirst();
                 String value = cursor.getString(0);
-                return Bundle.forPair("value", value);
+                Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
+                cache.putIfAbsentLocked(key, bundle);
+                return bundle;
             }
         } catch (SQLiteException e) {
             Log.w(TAG, "settings lookup error", e);
@@ -259,7 +275,8 @@
         } finally {
             if (cursor != null) cursor.close();
         }
-        return Bundle.forPair("value", null);
+        cache.putIfAbsentLocked(key, NULL_SETTING);
+        return NULL_SETTING;
     }
 
     @Override
@@ -313,6 +330,7 @@
             return 0;
         }
         checkWritePermissions(args);
+        SettingsCache cache = SettingsCache.forTable(args.table);
 
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         db.beginTransaction();
@@ -320,6 +338,7 @@
             int numValues = values.length;
             for (int i = 0; i < numValues; i++) {
                 if (db.insert(args.table, null, values[i]) < 0) return 0;
+                SettingsCache.populate(cache, values[i]);
                 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
             }
             db.setTransactionSuccessful();
@@ -336,6 +355,9 @@
      * This setting contains a list of the currently enabled location providers.
      * But helper functions in android.providers.Settings can enable or disable
      * a single provider by using a "+" or "-" prefix before the provider name.
+     *
+     * @returns whether the database needs to be updated or not, also modifying
+     *     'initialValues' if needed.
      */
     private boolean parseProviderList(Uri url, ContentValues initialValues) {
         String value = initialValues.getAsString(Settings.Secure.VALUE);
@@ -393,7 +415,7 @@
                 }
             }
         }
-        
+
         return true;
     }
 
@@ -416,6 +438,9 @@
         final long rowId = db.insert(args.table, null, initialValues);
         if (rowId <= 0) return null;
 
+        SettingsCache cache = SettingsCache.forTable(args.table);
+        SettingsCache.populate(cache, initialValues);  // before we notify
+
         if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
         url = getUriFor(url, initialValues, rowId);
         sendNotify(url);
@@ -434,7 +459,10 @@
 
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         int count = db.delete(args.table, args.where, args.args);
-        if (count > 0) sendNotify(url);
+        if (count > 0) {
+            SettingsCache.wipe(args.table);  // before we notify
+            sendNotify(url);
+        }
         if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
         return count;
     }
@@ -449,7 +477,10 @@
 
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         int count = db.update(args.table, initialValues, args.where, args.args);
-        if (count > 0) sendNotify(url);
+        if (count > 0) {
+            SettingsCache.wipe(args.table);  // before we notify
+            sendNotify(url);
+        }
         if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
         return count;
     }
@@ -554,4 +585,73 @@
         // Note that this will end up calling openFile() above.
         return super.openAssetFile(uri, mode);
     }
+
+    /**
+     * In-memory LRU Cache of system and secure settings, along with
+     * associated helper functions to keep cache coherent with the
+     * database.
+     */
+    private static final class SettingsCache extends LinkedHashMap<String, Bundle> {
+        public SettingsCache() {
+            super(MAX_CACHE_ENTRIES, 0.75f /* load factor */, true /* access ordered */);
+        }
+
+        @Override
+        protected boolean removeEldestEntry(Map.Entry eldest) {
+            return size() > MAX_CACHE_ENTRIES;
+        }
+
+        public void putIfAbsentLocked(String key, Bundle value) {
+            synchronized (this) {
+                if (containsKey(key)) {
+                    // Lost a race.
+                    return;
+                }
+                put(key, value);
+            }
+        }
+
+        public static SettingsCache forTable(String tableName) {
+            if ("system".equals(tableName)) {
+                return SettingsProvider.sSystemCache;
+            }
+            if ("secure".equals(tableName)) {
+                return SettingsProvider.sSecureCache;
+            }
+            return null;
+        }
+
+        /**
+         * Populates a key in a given (possibly-null) cache.
+         */
+        public static void populate(SettingsCache cache, ContentValues contentValues) {
+            if (cache == null) {
+                return;
+            }
+            String name = contentValues.getAsString(Settings.NameValueTable.NAME);
+            if (name == null) {
+                Log.w(TAG, "null name populating settings cache.");
+                return;
+            }
+            String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
+            synchronized (cache) {
+                cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
+            }
+        }
+
+        /**
+         * Used for wiping a whole cache on deletes when we're not
+         * sure what exactly was deleted or changed.
+         */
+        public static void wipe(String tableName) {
+            SettingsCache cache = SettingsCache.forTable(tableName);
+            if (cache == null) {
+                return;
+            }
+            synchronized (cache) {
+                cache.clear();
+            }
+        }
+
+    }
 }
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/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index a1c45dc..70deb3e 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -995,6 +995,8 @@
                     }
                 } else {
                     newNet.reconnect();
+                    newNet = null; // not officially avail..  try anyway, but
+                                   // report no failover
                 }
             }
         }
diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java
index 0974f7f..713358d 100644
--- a/services/java/com/android/server/MountService.java
+++ b/services/java/com/android/server/MountService.java
@@ -26,6 +26,7 @@
 import android.net.Uri;
 import android.os.storage.IMountService;
 import android.os.storage.IMountServiceListener;
+import android.os.storage.IMountShutdownObserver;
 import android.os.storage.StorageResultCode;
 import android.os.Handler;
 import android.os.Message;
@@ -172,69 +173,110 @@
         }
     }
 
+    class ShutdownCallBack extends UnmountCallBack {
+        IMountShutdownObserver observer;
+        ShutdownCallBack(String path, IMountShutdownObserver observer) {
+            super(path, true);
+            this.observer = observer;
+        }
+
+        @Override
+        void handleFinished() {
+            int ret = doUnmountVolume(path, true);
+            if (observer != null) {
+                try {
+                    observer.onShutDownComplete(ret);
+                } catch (RemoteException e) {
+                    Log.w(TAG, "RemoteException when shutting down");
+                }
+            }
+        }
+    }
+
     final private Handler mHandler = new Handler() {
         ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
+        boolean mRegistered = false;
+
+        void registerReceiver() {
+            mRegistered = true;
+            mContext.registerReceiver(mPmReceiver, mPmFilter);
+        }
+
+        void unregisterReceiver() {
+            mRegistered = false;
+            mContext.unregisterReceiver(mPmReceiver);
+        }
 
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 case H_UNMOUNT_PM_UPDATE: {
                     UnmountCallBack ucb = (UnmountCallBack) msg.obj;
                     mForceUnmounts.add(ucb);
-                    mContext.registerReceiver(mPmReceiver, mPmFilter);
-                    boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
-                    if (!hasExtPkgs) {
-                        // Unregister right away
-                        mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
+                    // Register only if needed.
+                    if (!mRegistered) {
+                        registerReceiver();
+                        boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
+                        if (!hasExtPkgs) {
+                            // Unregister right away
+                            mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
+                        }
                     }
                     break;
                 }
                 case H_UNMOUNT_PM_DONE: {
-                    // Unregister receiver
-                    mContext.unregisterReceiver(mPmReceiver);
-                    UnmountCallBack ucb = mForceUnmounts.get(0);
-                    if (ucb == null || ucb.path == null) {
-                        // Just ignore
-                        return;
+                    // Unregister now.
+                    if (mRegistered) {
+                        unregisterReceiver();
                     }
-                    String path = ucb.path;
-                    boolean done = false;
-                    if (!ucb.force) {
-                        done = true;
-                    } else {
-                        int pids[] = getStorageUsers(path);
-                        if (pids == null || pids.length == 0) {
+                    int size = mForceUnmounts.size();
+                    int sizeArr[] = new int[size];
+                    int sizeArrN = 0;
+                    for (int i = 0; i < size; i++) {
+                        UnmountCallBack ucb = mForceUnmounts.get(i);
+                        String path = ucb.path;
+                        boolean done = false;
+                        if (!ucb.force) {
                             done = true;
                         } else {
-                            // Kill processes holding references first
-                            ActivityManagerService ams = (ActivityManagerService)
-                            ServiceManager.getService("activity");
-                            // Eliminate system process here?
-                            boolean ret = ams.killPidsForMemory(pids);
-                            if (ret) {
-                                // Confirm if file references have been freed.
-                                pids = getStorageUsers(path);
-                                if (pids == null || pids.length == 0) {
-                                    done = true;
+                            int pids[] = getStorageUsers(path);
+                            if (pids == null || pids.length == 0) {
+                                done = true;
+                            } else {
+                                // Kill processes holding references first
+                                ActivityManagerService ams = (ActivityManagerService)
+                                ServiceManager.getService("activity");
+                                // Eliminate system process here?
+                                boolean ret = ams.killPidsForMemory(pids);
+                                if (ret) {
+                                    // Confirm if file references have been freed.
+                                    pids = getStorageUsers(path);
+                                    if (pids == null || pids.length == 0) {
+                                        done = true;
+                                    }
                                 }
                             }
                         }
-                    }
-                    if (done) {
-                        mForceUnmounts.remove(0);
-                        mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
-                                ucb));
-                    } else {
-                        if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
-                            Log.i(TAG, "Cannot unmount inspite of " +
-                                    MAX_UNMOUNT_RETRIES + " to unmount media");
-                            // Send final broadcast indicating failure to unmount.                      
+                        if (done) {
+                            sizeArr[sizeArrN++] = i;
+                            mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
+                                    ucb));
                         } else {
-                            mHandler.sendMessageDelayed(
-                                    mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
-                                            ucb.retries++),
-                                    RETRY_UNMOUNT_DELAY);
+                            if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
+                                Log.i(TAG, "Cannot unmount inspite of " +
+                                        MAX_UNMOUNT_RETRIES + " to unmount media");
+                                // Send final broadcast indicating failure to unmount.                 
+                            } else {
+                                mHandler.sendMessageDelayed(
+                                        mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
+                                                ucb.retries++),
+                                        RETRY_UNMOUNT_DELAY);
+                            }
                         }
                     }
+                    // Remove already processed elements from list.
+                    for (int i = (sizeArrN-1); i >= 0; i--) {
+                        mForceUnmounts.remove(sizeArr[i]);
+                    }
                     break;
                 }
                 case H_UNMOUNT_MS : {
@@ -826,7 +868,7 @@
         }
     }
 
-    public void shutdown() {
+    public void shutdown(final IMountShutdownObserver observer) {
         validatePermission(android.Manifest.permission.SHUTDOWN);
 
         Log.i(TAG, "Shutting down");
@@ -865,12 +907,9 @@
         }
 
         if (state.equals(Environment.MEDIA_MOUNTED)) {
-            /*
-             * If the media is mounted, then gracefully unmount it.
-             */
-            if (doUnmountVolume(path, true) != StorageResultCode.OperationSucceeded) {
-                Log.e(TAG, "Failed to unmount media for shutdown");
-            }
+            // Post a unmount message.
+            ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
+            mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
         }
     }
 
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/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index 0189c60..fc6bfcd 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -17,6 +17,7 @@
 package com.android.server;
 
 import com.android.internal.app.IBatteryStats;
+import com.android.internal.app.ShutdownThread;
 import com.android.server.am.BatteryStatsService;
 
 import android.app.ActivityManagerNative;
@@ -41,7 +42,6 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
-import android.os.storage.IMountService;
 import android.os.IPowerManager;
 import android.os.LocalPowerManager;
 import android.os.Power;
@@ -2202,28 +2202,35 @@
     {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
 
-        /*
-         * Manually shutdown the MountService to ensure media is
-         * put into a safe state.
-         */
-        IMountService mSvc = IMountService.Stub.asInterface(
-                ServiceManager.getService("mount"));
-
-        if (mSvc != null) {
-            try {
-                mSvc.shutdown();
-            } catch (Exception e) {
-                Slog.e(TAG, "MountService shutdown failed", e);
+        if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
+            throw new IllegalStateException("Too early to call reboot()");
+        }
+        
+        final String finalReason = reason;
+        Runnable runnable = new Runnable() {
+            public void run() {
+                synchronized (this) {
+                    ShutdownThread.reboot(mContext, finalReason, false);
+                    // if we get here we failed
+                    notify();
+                }
+                
             }
-        } else {
-            Slog.w(TAG, "MountService unavailable for shutdown");
-        }
+        };
 
-        try {
-            Power.reboot(reason);
-        } catch (IOException e) {
-            Slog.e(TAG, "reboot failed", e);
+        mHandler.post(runnable);
+
+        // block until we reboot or fail.
+        // throw an exception if we failed to reboot
+        synchronized (runnable) {
+            try {
+                runnable.wait();
+            } catch (InterruptedException e) {
+            }
         }
+     
+        // if we get here we failed
+        throw new IllegalStateException("unable to reboot!");
     }
 
     /**
diff --git a/services/java/com/android/server/Watchdog.java b/services/java/com/android/server/Watchdog.java
index f97f50a..3f64b25 100644
--- a/services/java/com/android/server/Watchdog.java
+++ b/services/java/com/android/server/Watchdog.java
@@ -29,6 +29,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.os.Process;
+import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.provider.Settings;
@@ -676,11 +677,8 @@
      */
     void rebootSystem(String reason) {
         Slog.i(TAG, "Rebooting system because: " + reason);
-        try {
-            android.os.Power.reboot(reason);
-        } catch (IOException e) {
-            Slog.e(TAG, "Reboot failed!", e);
-        }
+        PowerManagerService pms = (PowerManagerService) ServiceManager.getService("power");
+        pms.reboot(reason);
     }
 
     /**
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index f5d3e8e..34a7fc0 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -10267,9 +10267,10 @@
                                 && buttonBrightness < 0) {
                             buttonBrightness = w.mAttrs.buttonBrightness;
                         }
-                        if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
-                                || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
-                                || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
+                        if (canBeSeen
+                                && (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
+                                 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
+                                 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR)) {
                             syswin = true;
                         }
                     }
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/telephony/java/com/android/internal/telephony/MccTable.java b/telephony/java/com/android/internal/telephony/MccTable.java
index 7f62169..b73c2f7 100644
--- a/telephony/java/com/android/internal/telephony/MccTable.java
+++ b/telephony/java/com/android/internal/telephony/MccTable.java
@@ -107,7 +107,7 @@
   (294, 'mk', 2, 'The Former Yugoslav Republic of Macedonia'),
   (295, 'li', 2, 'Liechtenstein (Principality of)'),
   (297, 'me', 2, 'Montenegro (Republic of)'),
-  (302, 'ca', 2, '', '', 11, 'Canada'),
+  (302, 'ca', 3, '', '', 11, 'Canada'),
   (308, 'pm', 2, 'Saint Pierre and Miquelon (Collectivit territoriale de la Rpublique franaise)'),
   (310, 'us', 3, '', 'en', 11, 'United States of America'),
   (311, 'us', 3, '', 'en', 11, 'United States of America'),
@@ -454,7 +454,7 @@
         0x6d640400, 0x706c04f0, 0x64656c72, 0x67690400, 0x70740400, 0x6c750400,
         0x69650483, 0x69730400, 0x616c0400, 0x6d740400, 0x63790400, 0x67650400,
         0x616d0400, 0x62670400, 0x74720400, 0x666f0400, 0x67650400, 0x676c0400,
-        0x736d0400, 0x736c0400, 0x6d6b0400, 0x6c690400, 0x6d650400, 0x63615c00,
+        0x736d0400, 0x736c0400, 0x6d6b0400, 0x6c690400, 0x6d650400, 0x63615e00,
         0x706d0400, 0x75735e03, 0x75735e03, 0x75735e03, 0x75735e03, 0x75735e03,
         0x75735e03, 0x75735e03, 0x70720400, 0x76690400, 0x6d780600, 0x6a6d0600,
         0x67700400, 0x62620600, 0x61670600, 0x6b790600, 0x76670600, 0x626d0400,
diff --git a/tests/AndroidTests/AndroidManifest.xml b/tests/AndroidTests/AndroidManifest.xml
index e06c3a8..1f0bf4d 100644
--- a/tests/AndroidTests/AndroidManifest.xml
+++ b/tests/AndroidTests/AndroidManifest.xml
@@ -35,6 +35,7 @@
     <uses-permission android:name="android.permission.ASEC_DESTROY" />
     <uses-permission android:name="android.permission.ASEC_MOUNT_UNMOUNT" />
     <uses-permission android:name="android.permission.ASEC_RENAME" />
+    <uses-permission android:name="android.permission.SHUTDOWN" />
     <uses-permission android:name="com.android.unit_tests.permission.TEST_GRANTED" />
     <uses-permission android:name="com.google.android.googleapps.permission.ACCESS_GOOGLE_PASSWORD" />
     <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />
diff --git a/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java b/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
index c7bacd4..9aed363 100755
--- a/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
@@ -16,6 +16,8 @@
 
 package com.android.unit_tests;
 
+import com.android.unit_tests.PackageManagerTests.StorageListener;
+
 import android.os.storage.IMountService.Stub;
 
 import android.net.Uri;
@@ -41,6 +43,9 @@
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.storage.IMountService;
+import android.os.storage.IMountShutdownObserver;
+import android.os.storage.StorageEventListener;
+import android.os.storage.StorageManager;
 import android.os.storage.StorageResultCode;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -365,4 +370,256 @@
         }
     }
 
+    /*------------ Tests for unmounting volume ---*/
+    public final long MAX_WAIT_TIME=120*1000;
+    public final long WAIT_TIME_INCR=20*1000;
+    boolean getMediaState() {
+        try {
+        String mPath = Environment.getExternalStorageDirectory().toString();
+        String state = getMs().getVolumeState(mPath);
+        return Environment.MEDIA_MOUNTED.equals(state);
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    boolean mountMedia() {
+        if (getMediaState()) {
+            return true;
+        }
+        try {
+        String mPath = Environment.getExternalStorageDirectory().toString();
+        int ret = getMs().mountVolume(mPath);
+        return ret == StorageResultCode.OperationSucceeded;
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    class StorageListener extends StorageEventListener {
+        String oldState;
+        String newState;
+        String path;
+        private boolean doneFlag = false;
+
+        public void action() {
+            synchronized (this) {
+                doneFlag = true;
+                notifyAll();
+            }
+        }
+
+        public boolean isDone() {
+            return doneFlag;
+        }
+
+        @Override
+        public void onStorageStateChanged(String path, String oldState, String newState) {
+            if (localLOGV) Log.i(TAG, "Storage state changed from " + oldState + " to " + newState);
+            this.oldState = oldState;
+            this.newState = newState;
+            this.path = path;
+            action();
+        }
+    }
+
+    private boolean unmountMedia() {
+        if (!getMediaState()) {
+            return true;
+        }
+        String path = Environment.getExternalStorageDirectory().toString();
+        StorageListener observer = new StorageListener();
+        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
+        sm.registerListener(observer);
+        try {
+            // Wait on observer
+            synchronized(observer) {
+                getMs().unmountVolume(path, false);
+                long waitTime = 0;
+                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
+                    observer.wait(WAIT_TIME_INCR);
+                    waitTime += WAIT_TIME_INCR;
+                }
+                if(!observer.isDone()) {
+                    throw new Exception("Timed out waiting for packageInstalled callback");
+                }
+                return true;
+            }
+        } catch (Exception e) {
+            return false;
+        } finally {
+            sm.unregisterListener(observer);
+        }
+    }
+    public void testUnmount() {
+        boolean oldStatus = getMediaState();
+        Log.i(TAG, "oldStatus="+oldStatus);
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            assertTrue(unmountMedia());
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
+    class MultipleStorageLis extends StorageListener {
+        int count = 0;
+        public void onStorageStateChanged(String path, String oldState, String newState) {
+            count++;
+            super.action();
+        }
+    }
+    /*
+     * This test invokes unmount multiple time and expects the call back
+     * to be invoked just once.
+     */
+    public void testUnmountMultiple() {
+        boolean oldStatus = getMediaState();
+        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
+        MultipleStorageLis observer = new MultipleStorageLis();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            String path = Environment.getExternalStorageDirectory().toString();
+            sm.registerListener(observer);
+            // Wait on observer
+            synchronized(observer) {
+                for (int i = 0; i < 5; i++) {
+                    getMs().unmountVolume(path, false);
+                }
+                long waitTime = 0;
+                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
+                    observer.wait(WAIT_TIME_INCR);
+                    waitTime += WAIT_TIME_INCR;
+                }
+                if(!observer.isDone()) {
+                    failStr("Timed out waiting for packageInstalled callback");
+                }
+            }
+            assertEquals(observer.count, 1);
+        } catch (Exception e) {
+            failStr(e);
+        } finally {
+            sm.unregisterListener(observer);
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+    
+    class ShutdownObserver extends  IMountShutdownObserver.Stub{
+        private boolean doneFlag = false;
+        int statusCode;
+
+        public void action() {
+            synchronized (this) {
+                doneFlag = true;
+                notifyAll();
+            }
+        }
+
+        public boolean isDone() {
+            return doneFlag;
+        }
+        public void onShutDownComplete(int statusCode) throws RemoteException {
+            this.statusCode = statusCode;
+            action();
+        }
+        
+    }
+
+    boolean invokeShutdown() {
+        IMountService ms = getMs();
+        ShutdownObserver observer = new ShutdownObserver();
+        synchronized (observer) {
+            try {
+                ms.shutdown(observer);
+                return true;
+            } catch (RemoteException e) {
+                failStr(e);
+            }
+        }
+        return false;
+    }
+
+    public void testShutdown() {
+        boolean oldStatus = getMediaState();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            assertTrue(invokeShutdown());
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
+    /*
+     * This test invokes unmount multiple time and expects the call back
+     * to be invoked just once.
+     */
+    public void testShutdownMultiple() {
+        boolean oldStatus = getMediaState();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            IMountService ms = getMs();
+            ShutdownObserver observer = new ShutdownObserver();
+            synchronized (observer) {
+                try {
+                    ms.shutdown(observer);
+                    for (int i = 0; i < 4; i++) {
+                        ms.shutdown(null);
+                    }
+                } catch (RemoteException e) {
+                    failStr(e);
+                }
+            }
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
 }
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/FileFilter.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
index 100a466..4250043 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
@@ -62,7 +62,6 @@
     static final String[] ignoreTestDirs = {
         ".", // ignore hidden directories and files
         "resources", // ignore resource directories
-        "AppleScript", // AppleScript not supported
         ".svn", // don't run anything under .svn folder
         "profiler",  // profiler is not supported
         "svg",  // svg is not supported
@@ -73,8 +72,6 @@
     static final String [] ignoreTestList = {
         "editing/selection/move-left-right.html",
         "fast/js/regexp-charclass-crash.html", // RegExp is too large, causing OOM
-        "fast/regex/test1.html", // RegExp is exponential
-        "fast/regex/slow.html", // RegExp is exponential
         "storage/domstorage/localstorage/private-browsing-affects-storage.html", // No notion of private browsing.
         "storage/domstorage/sessionstorage/private-browsing-affects-storage.html", // No notion of private browsing.
         "storage/private-browsing-readonly.html", // No notion of private browsing.
@@ -99,6 +96,24 @@
         ignoreResultList.add("http/tests/appcache/whitelist-wildcard.html"); // file not found
         ignoreResultList.add("storage/database-lock-after-reload.html"); // failure
 
+        // Will always fail
+        ignoreResultList.add("fast/workers/shared-worker-constructor.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-context-gc.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-event-listener.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-exception.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-frame-lifecycle.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-gc.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-lifecycle.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-load-error.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-location.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-name.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-navigator.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-replace-global-constructor.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-replace-self.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-script-error.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-shared.html"); // shared workers not supported
+        ignoreResultList.add("fast/workers/shared-worker-simple.html"); // shared workers not supported
+
         ignoreResultList.add("fast/css/case-transform.html"); // will not fix #619707
         ignoreResultList.add("fast/dom/Element/offsetLeft-offsetTop-body-quirk.html"); // different screen size result in extra spaces in Apple compared to us
         ignoreResultList.add("fast/dom/Window/Plug-ins.html"); // need test plugin
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);
         }
     }