Merge "Don't poke user activity when unplugging unless screen is already on."
diff --git a/api/current.xml b/api/current.xml
index 189835e..85367d0 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -42377,6 +42377,17 @@
  visibility="public"
 >
 </field>
+<field name="CONFIG_UI_MODE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="512"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="CREATOR"
  type="android.os.Parcelable.Creator"
  transient="false"
@@ -47830,6 +47841,94 @@
  visibility="public"
 >
 </field>
+<field name="UI_MODE_NIGHT_MASK"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="48"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_NIGHT_NO"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_NIGHT_UNDEFINED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_NIGHT_YES"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="32"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_TYPE_CAR"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_TYPE_MASK"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="15"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_TYPE_NORMAL"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="UI_MODE_TYPE_UNDEFINED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="fontScale"
  type="float"
  transient="false"
@@ -47950,6 +48049,16 @@
  visibility="public"
 >
 </field>
+<field name="uiMode"
+ type="int"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 </class>
 <class name="Resources"
  extends="java.lang.Object"
diff --git a/calendar/Android.mk b/calendar/Android.mk
index fd20dfa..7f9ee0a 100644
--- a/calendar/Android.mk
+++ b/calendar/Android.mk
@@ -10,7 +10,6 @@
 	../core/java/android/pim/ICalendar.java \
 	../core/java/android/pim/RecurrenceSet.java \
 	../core/java/android/pim/ContactsAsyncHelper.java \
-	../core/java/android/pim/DateException.java
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index a13f7f9..91b2be7 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -253,7 +253,6 @@
      * Bit in {@link #configChanges} that indicates that the activity
      * can itself handle the ui mode. Set from the
      * {@link android.R.attr#configChanges} attribute.
-     * @hide (UIMODE) Pending API council approval
      */
     public static final int CONFIG_UI_MODE = 0x0200;
     /**
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index 6490b65..a737283 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -162,20 +162,14 @@
      */
     public int orientation;
 
-    /** @hide (UIMODE) Pending API council approval */
     public static final int UI_MODE_TYPE_MASK = 0x0f;
-    /** @hide (UIMODE) Pending API council approval */
-    public static final int UI_MODE_TYPE_NORMAL = 0x00;
-    /** @hide (UIMODE) Pending API council approval */
-    public static final int UI_MODE_TYPE_CAR = 0x01;
+    public static final int UI_MODE_TYPE_UNDEFINED = 0x00;
+    public static final int UI_MODE_TYPE_NORMAL = 0x01;
+    public static final int UI_MODE_TYPE_CAR = 0x02;
 
-    /** @hide (UIMODE) Pending API council approval */
     public static final int UI_MODE_NIGHT_MASK = 0x30;
-    /** @hide (UIMODE) Pending API council approval */
     public static final int UI_MODE_NIGHT_UNDEFINED = 0x00;
-    /** @hide (UIMODE) Pending API council approval */
     public static final int UI_MODE_NIGHT_NO = 0x10;
-    /** @hide (UIMODE) Pending API council approval */
     public static final int UI_MODE_NIGHT_YES = 0x20;
 
     /**
@@ -187,8 +181,6 @@
      * <p>The {@link #UI_MODE_NIGHT_MASK} defines whether the screen
      * is in a special mode. They may be one of
      * {@link #UI_MODE_NIGHT_NO} or {@link #UI_MODE_NIGHT_YES}.
-     *
-     * @hide (UIMODE) Pending API council approval
      */
     public int uiMode;
 
diff --git a/core/java/android/pim/DateException.java b/core/java/android/pim/DateException.java
deleted file mode 100644
index 90bfe7f..0000000
--- a/core/java/android/pim/DateException.java
+++ /dev/null
@@ -1,26 +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 android.pim;
-
-public class DateException extends Exception
-{
-    public DateException(String message)
-    {
-        super(message);
-    }
-}
-
diff --git a/core/java/android/speech/tts/TextToSpeech.java b/core/java/android/speech/tts/TextToSpeech.java
index 0db2198..9e04cf8 100755
--- a/core/java/android/speech/tts/TextToSpeech.java
+++ b/core/java/android/speech/tts/TextToSpeech.java
@@ -410,17 +410,17 @@
         mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID] = Engine.KEY_PARAM_UTTERANCE_ID;
         mCachedParams[Engine.PARAM_POSITION_ENGINE] = Engine.KEY_PARAM_ENGINE;
 
-        mCachedParams[Engine.PARAM_POSITION_RATE + 1] =
-                String.valueOf(Engine.DEFAULT_RATE);
-        // initialize the language cached parameters with the current Locale
-        Locale defaultLoc = Locale.getDefault();
-        mCachedParams[Engine.PARAM_POSITION_LANGUAGE + 1] = defaultLoc.getISO3Language();
-        mCachedParams[Engine.PARAM_POSITION_COUNTRY + 1] = defaultLoc.getISO3Country();
-        mCachedParams[Engine.PARAM_POSITION_VARIANT + 1] = defaultLoc.getVariant();
+        // Leave all defaults that are shown in Settings uninitialized so that
+        // the values set in Settings will take effect if the application does
+        // not try to change these settings itself.
+        mCachedParams[Engine.PARAM_POSITION_RATE + 1] = "";
+        mCachedParams[Engine.PARAM_POSITION_LANGUAGE + 1] = "";
+        mCachedParams[Engine.PARAM_POSITION_COUNTRY + 1] = "";
+        mCachedParams[Engine.PARAM_POSITION_VARIANT + 1] = "";
         mCachedParams[Engine.PARAM_POSITION_STREAM + 1] =
                 String.valueOf(Engine.DEFAULT_STREAM);
         mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID + 1] = "";
-        mCachedParams[Engine.PARAM_POSITION_ENGINE + 1] = Engine.DEFAULT_SYNTH;
+        mCachedParams[Engine.PARAM_POSITION_ENGINE + 1] = "";
 
         initTts();
     }
diff --git a/core/java/android/text/format/DateUtils.java b/core/java/android/text/format/DateUtils.java
index 9dd8ceb..dde0889 100644
--- a/core/java/android/text/format/DateUtils.java
+++ b/core/java/android/text/format/DateUtils.java
@@ -21,7 +21,6 @@
 import android.content.Context;
 import android.content.res.Configuration;
 import android.content.res.Resources;
-import android.pim.DateException;
 
 import java.util.Calendar;
 import java.util.Date;
@@ -814,35 +813,6 @@
                 && (thenMonth == time.month) 
                 && (thenMonthDay == time.monthDay);
     }
-    
-    /**
-     * @hide
-     * @deprecated use {@link android.text.format.Time}
-     */
-    private static final int ctoi(String str, int index)
-                                                throws DateException
-    {
-        char c = str.charAt(index);
-        if (c >= '0' && c <= '9') {
-            return (int)(c - '0');
-        }
-        throw new DateException("Expected numeric character.  Got '" +
-                                            c + "'");
-    }
-
-    /**
-     * @hide
-     * @deprecated use {@link android.text.format.Time}
-     */
-    private static final int check(int lowerBound, int upperBound, int value)
-                                                throws DateException
-    {
-        if (value >= lowerBound && value <= upperBound) {
-            return value;
-        }
-        throw new DateException("field out of bounds.  max=" + upperBound
-                                        + " value=" + value);
-    }
 
     /**
      * @hide
@@ -861,81 +831,6 @@
         return false;
     }
 
-
-    // note that month in Calendar is 0 based and in all other human
-    // representations, it's 1 based.
-    // Returns if the Z was present, meaning that the time is in UTC
-    /**
-     * @hide
-     * @deprecated use {@link android.text.format.Time}
-     */
-    public static boolean parseDateTime(String str, Calendar cal)
-                                                throws DateException
-    {
-        int len = str.length();
-        boolean dateTime = (len == 15 || len == 16) && str.charAt(8) == 'T';
-        boolean justDate = len == 8;
-        if (dateTime || justDate) {
-            cal.clear();
-            cal.set(Calendar.YEAR, 
-                            ctoi(str, 0)*1000 + ctoi(str, 1)*100
-                            + ctoi(str, 2)*10 + ctoi(str, 3));
-            cal.set(Calendar.MONTH,
-                            check(0, 11, ctoi(str, 4)*10 + ctoi(str, 5) - 1));
-            cal.set(Calendar.DAY_OF_MONTH,
-                            check(1, 31, ctoi(str, 6)*10 + ctoi(str, 7)));
-            if (dateTime) {
-                cal.set(Calendar.HOUR_OF_DAY,
-                            check(0, 23, ctoi(str, 9)*10 + ctoi(str, 10)));
-                cal.set(Calendar.MINUTE,
-                            check(0, 59, ctoi(str, 11)*10 + ctoi(str, 12)));
-                cal.set(Calendar.SECOND,
-                            check(0, 59, ctoi(str, 13)*10 + ctoi(str, 14)));
-            }
-            if (justDate) {
-                cal.set(Calendar.HOUR_OF_DAY, 0);
-                cal.set(Calendar.MINUTE, 0);
-                cal.set(Calendar.SECOND, 0);
-                return true;
-            }
-            if (len == 15) {
-                return false;
-            }
-            if (str.charAt(15) == 'Z') {
-                return true;
-            }
-        }
-        throw new DateException("Invalid time (expected "
-                                + "YYYYMMDDThhmmssZ? got '" + str + "').");
-    }
-
-    /**
-     * Given a timezone string which can be null, and a dateTime string,
-     * set that time into a calendar.
-     * @hide
-     * @deprecated use {@link android.text.format.Time}
-     */
-    public static void parseDateTime(String tz, String dateTime, Calendar out)
-                                                throws DateException
-    {
-        TimeZone timezone;
-        if (DateUtils.isUTC(dateTime)) {
-            timezone = TimeZone.getTimeZone("UTC");
-        }
-        else if (tz == null) {
-            timezone = TimeZone.getDefault();
-        }
-        else {
-            timezone = TimeZone.getTimeZone(tz);
-        }
-
-        Calendar local = new GregorianCalendar(timezone);
-        DateUtils.parseDateTime(dateTime, local);
-
-        out.setTimeInMillis(local.getTimeInMillis());
-    }
-
-
     /**
      * Return a string containing the date and time in RFC2445 format.
      * Ensures that the time is written in UTC.  The Calendar class doesn't
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index b85667b..183fce3 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -182,7 +182,18 @@
             int pid, int display, int w, int h, int format, int flags)
         throws OutOfResourcesException {
         mCanvas = new CompatibleCanvas();
-        init(s,pid,display,w,h,format,flags);
+        init(s,pid,null,display,w,h,format,flags);
+    }
+
+    /**
+     * create a surface with a name
+     * {@hide}
+     */
+    public Surface(SurfaceSession s,
+            int pid, String name, int display, int w, int h, int format, int flags)
+        throws OutOfResourcesException {
+        mCanvas = new CompatibleCanvas();
+        init(s,pid,name,display,w,h,format,flags);
     }
 
     /**
@@ -400,7 +411,7 @@
     }
     
     private native void init(SurfaceSession s,
-            int pid, int display, int w, int h, int format, int flags)
+            int pid, String name, int display, int w, int h, int format, int flags)
             throws OutOfResourcesException;
 
     private native void init(Parcel source);
diff --git a/common/java/com/android/common/ui/PointerLocationView.java b/core/java/com/android/internal/widget/PointerLocationView.java
similarity index 99%
rename from common/java/com/android/common/ui/PointerLocationView.java
rename to core/java/com/android/internal/widget/PointerLocationView.java
index 7bdb0bc..999b27d 100644
--- a/common/java/com/android/common/ui/PointerLocationView.java
+++ b/core/java/com/android/internal/widget/PointerLocationView.java
@@ -1,4 +1,4 @@
-package com.android.common.ui;
+package com.android.internal.widget;
 
 import android.content.Context;
 import android.graphics.Canvas;
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index 723205a..060ca50 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -185,7 +185,8 @@
 
 static void Surface_init(
         JNIEnv* env, jobject clazz, 
-        jobject session, jint pid, jint dpy, jint w, jint h, jint format, jint flags)
+        jobject session,
+        jint pid, jstring jname, jint dpy, jint w, jint h, jint format, jint flags)
 {
     if (session == NULL) {
         doThrow(env, "java/lang/NullPointerException");
@@ -195,7 +196,16 @@
     SurfaceComposerClient* client =
             (SurfaceComposerClient*)env->GetIntField(session, sso.client);
 
-    sp<SurfaceControl> surface(client->createSurface(pid, dpy, w, h, format, flags));
+    sp<SurfaceControl> surface;
+    if (jname == NULL) {
+        surface = client->createSurface(pid, dpy, w, h, format, flags);
+    } else {
+        const jchar* str = env->GetStringCritical(jname, 0);
+        const String8 name(str, env->GetStringLength(jname));
+        env->ReleaseStringCritical(jname, str);
+        surface = client->createSurface(pid, name, dpy, w, h, format, flags);
+    }
+
     if (surface == 0) {
         doThrow(env, OutOfResourcesException);
         return;
@@ -620,7 +630,7 @@
 
 static JNINativeMethod gSurfaceMethods[] = {
     {"nativeClassInit",     "()V",  (void*)nativeClassInit },
-    {"init",                "(Landroid/view/SurfaceSession;IIIIII)V",  (void*)Surface_init },
+    {"init",                "(Landroid/view/SurfaceSession;ILjava/lang/String;IIIII)V",  (void*)Surface_init },
     {"init",                "(Landroid/os/Parcel;)V",  (void*)Surface_initParcel },
     {"destroy",             "()V",  (void*)Surface_destroy },
     {"release",             "()V",  (void*)Surface_release },
diff --git a/core/tests/coretests/src/android/widget/listview/focus/ListWithEditTextHeaderTest.java b/core/tests/coretests/src/android/widget/listview/focus/ListWithEditTextHeaderTest.java
index 93bddb0..b9051e9 100644
--- a/core/tests/coretests/src/android/widget/listview/focus/ListWithEditTextHeaderTest.java
+++ b/core/tests/coretests/src/android/widget/listview/focus/ListWithEditTextHeaderTest.java
@@ -16,21 +16,21 @@
 
 package android.widget.listview.focus;
 
-import android.test.ActivityInstrumentationTestCase;
+import android.test.ActivityInstrumentationTestCase2;
 import android.test.FlakyTest;
+import android.test.TouchUtils;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.MediumTest;
-import android.test.TouchUtils;
 import android.view.KeyEvent;
 import android.widget.AbsListView;
 import android.widget.ListView;
 import android.widget.listview.ListWithEditTextHeader;
 
-public class ListWithEditTextHeaderTest extends ActivityInstrumentationTestCase<ListWithEditTextHeader> {
+public class ListWithEditTextHeaderTest extends ActivityInstrumentationTestCase2<ListWithEditTextHeader> {
     private ListView mListView;
 
     public ListWithEditTextHeaderTest() {
-        super("com.android.frameworks.coretests", ListWithEditTextHeader.class);
+        super(ListWithEditTextHeader.class);
     }
 
     @Override
@@ -44,15 +44,15 @@
         assertTrue("listview.getItemsCanFocus()", mListView.getItemsCanFocus());
         assertFalse("out of touch-mode", mListView.isInTouchMode());
         assertEquals("header view count", 1, mListView.getHeaderViewsCount());
-        assertTrue("header has focus", mListView.getChildAt(0).isFocused());
+        assertTrue("header does not have focus", mListView.getChildAt(0).isFocused());
     }
 
     @FlakyTest(tolerance=2)
     @LargeTest
     public void testClickingHeaderKeepsFocus() {
         TouchUtils.clickView(this, mListView.getChildAt(0));
-        assertTrue("header has focus", mListView.getChildAt(0).isFocused());
-        assertEquals("nothing selected", AbsListView.INVALID_POSITION, mListView.getSelectedItemPosition());
+        assertTrue("header does not have focus", mListView.getChildAt(0).isFocused());
+        assertEquals("something is selected", AbsListView.INVALID_POSITION, mListView.getSelectedItemPosition());
     }
 
     @LargeTest
@@ -60,7 +60,7 @@
         sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
         assertEquals("selected position", 1, mListView.getSelectedItemPosition());
         TouchUtils.clickView(this, mListView.getChildAt(0));
-        assertTrue("header has focus", mListView.getChildAt(0).isFocused());        
-        assertEquals("nothing selected", AbsListView.INVALID_POSITION, mListView.getSelectedItemPosition());
+        assertTrue("header does not have focus", mListView.getChildAt(0).isFocused());
+        assertEquals("something is selected", AbsListView.INVALID_POSITION, mListView.getSelectedItemPosition());
     }
 }
diff --git a/include/surfaceflinger/ISurfaceFlingerClient.h b/include/surfaceflinger/ISurfaceFlingerClient.h
index 1fba162..d257645 100644
--- a/include/surfaceflinger/ISurfaceFlingerClient.h
+++ b/include/surfaceflinger/ISurfaceFlingerClient.h
@@ -61,6 +61,7 @@
 
     virtual sp<ISurface> createSurface( surface_data_t* data,
                                         int pid, 
+                                        const String8& name,
                                         DisplayID display,
                                         uint32_t w,
                                         uint32_t h,
diff --git a/include/surfaceflinger/SurfaceComposerClient.h b/include/surfaceflinger/SurfaceComposerClient.h
index 49e83c0..9d0f0cb 100644
--- a/include/surfaceflinger/SurfaceComposerClient.h
+++ b/include/surfaceflinger/SurfaceComposerClient.h
@@ -65,6 +65,7 @@
     //! Create a surface
     sp<SurfaceControl> createSurface(
             int pid,            // pid of the process the surface is for
+            const String8& name,// name of the surface
             DisplayID display,  // Display to create this surface on
             uint32_t w,         // width in pixel
             uint32_t h,         // height in pixel
@@ -72,6 +73,16 @@
             uint32_t flags = 0  // usage flags
     );
 
+    sp<SurfaceControl> createSurface(
+            int pid,            // pid of the process the surface is for
+            DisplayID display,  // Display to create this surface on
+            uint32_t w,         // width in pixel
+            uint32_t h,         // height in pixel
+            PixelFormat format, // pixel-format desired
+            uint32_t flags = 0  // usage flags
+    );
+
+
     // ------------------------------------------------------------------------
     // Composer parameters
     // All composer parameters must be changed within a transaction
diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h
index cd657e8..cbcef4e 100644
--- a/include/utils/ResourceTypes.h
+++ b/include/utils/ResourceTypes.h
@@ -944,8 +944,9 @@
     enum {
         // uiMode bits for the mode type.
         MASK_UI_MODE_TYPE = 0x0f,
-        UI_MODE_TYPE_NORMAL = 0x00,
-        UI_MODE_TYPE_CAR = 0x01,
+        UI_MODE_TYPE_ANY = 0x00,
+        UI_MODE_TYPE_NORMAL = 0x01,
+        UI_MODE_TYPE_CAR = 0x02,
 
         // uiMode bits for the night switch.
         MASK_UI_MODE_NIGHT = 0x30,
@@ -1086,7 +1087,7 @@
             }
         }
 
-        if (screenConfig || o.screenConfig) {
+        if (screenLayout || o.screenLayout) {
             if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
                 if (!(screenLayout & MASK_SCREENSIZE)) return false;
                 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
@@ -1102,7 +1103,7 @@
             if (!o.orientation) return true;
         }
 
-        if (screenConfig || o.screenConfig) {
+        if (uiMode || o.uiMode) {
             if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
                 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
                 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
@@ -1203,7 +1204,7 @@
                 }
             }
 
-            if (screenConfig || o.screenConfig) {
+            if (screenLayout || o.screenLayout) {
                 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
                         && (requested->screenLayout & MASK_SCREENSIZE)) {
                     return (screenLayout & MASK_SCREENSIZE);
@@ -1218,7 +1219,7 @@
                 return (orientation);
             }
 
-            if (screenConfig || o.screenConfig) {
+            if (uiMode || o.uiMode) {
                 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
                         && (requested->uiMode & MASK_UI_MODE_TYPE)) {
                     return (uiMode & MASK_UI_MODE_TYPE);
diff --git a/libs/surfaceflinger/LayerBase.cpp b/libs/surfaceflinger/LayerBase.cpp
index a3d293f..b0109ca 100644
--- a/libs/surfaceflinger/LayerBase.cpp
+++ b/libs/surfaceflinger/LayerBase.cpp
@@ -728,6 +728,14 @@
     delete lcblk;
 }
 
+void LayerBaseClient::setName(const String8& name) {
+    mName = name;
+}
+
+String8 LayerBaseClient::getName() const {
+    return mName;
+}
+
 int32_t LayerBaseClient::serverIndex() const 
 {
     sp<Client> client(this->client.promote());
diff --git a/libs/surfaceflinger/LayerBase.h b/libs/surfaceflinger/LayerBase.h
index 6aacd82..7ac8bc5 100644
--- a/libs/surfaceflinger/LayerBase.h
+++ b/libs/surfaceflinger/LayerBase.h
@@ -320,6 +320,8 @@
             const sp<Client>& client, int32_t i);
     virtual ~LayerBaseClient();
     virtual void onFirstRef();
+    void setName(const String8& name);
+    String8 getName() const;
 
     const wp<Client>    client;
 
@@ -333,6 +335,7 @@
     
     virtual void onRemoved();
 
+
     class Surface : public BnSurface 
     {
     public:
@@ -371,6 +374,7 @@
     mutable     Mutex           mLock;
     mutable     wp<Surface>     mClientSurface;
     // only read
+                String8         mName;
     const       uint32_t        mIdentity;
     static      int32_t         sIdentity;
 };
diff --git a/libs/surfaceflinger/SurfaceFlinger.cpp b/libs/surfaceflinger/SurfaceFlinger.cpp
index 4555b3c..2598440 100644
--- a/libs/surfaceflinger/SurfaceFlinger.cpp
+++ b/libs/surfaceflinger/SurfaceFlinger.cpp
@@ -625,12 +625,13 @@
 
             mVisibleRegionsDirty = true;
             mDirtyRegion.set(hw.bounds());
-            mFreezeDisplayTime = 0;
         }
 
         if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
             // freezing or unfreezing the display -> trigger animation if needed
             mFreezeDisplay = mCurrentState.freezeDisplay;
+            if (mFreezeDisplay)
+                 mFreezeDisplayTime = 0;
         }
 
         if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
@@ -1186,7 +1187,7 @@
 }
 
 sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
-        ISurfaceFlingerClient::surface_data_t* params,
+        const String8& name, ISurfaceFlingerClient::surface_data_t* params,
         DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
         uint32_t flags)
 {
@@ -1232,6 +1233,7 @@
     }
 
     if (layer != 0) {
+        layer->setName(name);
         setTransactionFlags(eTransactionNeeded);
         surfaceHandle = layer->getSurface();
         if (surfaceHandle != 0) { 
@@ -1506,8 +1508,10 @@
             if (lbc != 0) {
                 sp<Client> client(lbc->client.promote());
                 snprintf(buffer, SIZE,
-                        "      "
-                        "id=0x%08x, client=0x%08x, identity=%u\n",
+                        "      name=%s\n", lbc->getName().string());
+                result.append(buffer);
+                snprintf(buffer, SIZE,
+                        "      id=0x%08x, client=0x%08x, identity=%u\n",
                         lbc->clientIndex(), client.get() ? client->cid : 0,
                         lbc->getIdentity());
 
@@ -1760,10 +1764,12 @@
 
 sp<ISurface> BClient::createSurface(
         ISurfaceFlingerClient::surface_data_t* params, int pid,
+        const String8& name,
         DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
         uint32_t flags)
 {
-    return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
+    return mFlinger->createSurface(mId, pid, name, params, display, w, h,
+            format, flags);
 }
 
 status_t BClient::destroySurface(SurfaceID sid)
diff --git a/libs/surfaceflinger/SurfaceFlinger.h b/libs/surfaceflinger/SurfaceFlinger.h
index 4520c0e..d75dc15 100644
--- a/libs/surfaceflinger/SurfaceFlinger.h
+++ b/libs/surfaceflinger/SurfaceFlinger.h
@@ -189,7 +189,7 @@
     friend class LayerBlur;
     friend class LayerDim;
 
-    sp<ISurface> createSurface(ClientID client, int pid, 
+    sp<ISurface> createSurface(ClientID client, int pid, const String8& name,
             ISurfaceFlingerClient::surface_data_t* params,
             DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
             uint32_t flags);
@@ -401,7 +401,7 @@
     virtual sp<IMemoryHeap> getControlBlock() const;
 
     virtual sp<ISurface> createSurface(
-            surface_data_t* params, int pid,
+            surface_data_t* params, int pid, const String8& name,
             DisplayID display, uint32_t w, uint32_t h,PixelFormat format,
             uint32_t flags);
 
diff --git a/libs/surfaceflinger_client/ISurfaceFlingerClient.cpp b/libs/surfaceflinger_client/ISurfaceFlingerClient.cpp
index e636c52..def96d7 100644
--- a/libs/surfaceflinger_client/ISurfaceFlingerClient.cpp
+++ b/libs/surfaceflinger_client/ISurfaceFlingerClient.cpp
@@ -74,6 +74,7 @@
 
     virtual sp<ISurface> createSurface( surface_data_t* params,
                                         int pid,
+                                        const String8& name,
                                         DisplayID display,
                                         uint32_t w,
                                         uint32_t h,
@@ -83,6 +84,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceFlingerClient::getInterfaceDescriptor());
         data.writeInt32(pid);
+        data.writeString8(name);
         data.writeInt32(display);
         data.writeInt32(w);
         data.writeInt32(h);
@@ -154,12 +156,14 @@
             CHECK_INTERFACE(ISurfaceFlingerClient, data, reply);
             surface_data_t params;
             int32_t pid = data.readInt32();
+            String8 name = data.readString8();
             DisplayID display = data.readInt32();
             uint32_t w = data.readInt32();
             uint32_t h = data.readInt32();
             PixelFormat format = data.readInt32();
             uint32_t flags = data.readInt32();
-            sp<ISurface> s = createSurface(&params, pid, display, w, h, format, flags);
+            sp<ISurface> s = createSurface(&params, pid, name, display, w, h,
+                    format, flags);
             params.writeToParcel(reply);
             reply->writeStrongBinder(s->asBinder());
             return NO_ERROR;
diff --git a/libs/surfaceflinger_client/SurfaceComposerClient.cpp b/libs/surfaceflinger_client/SurfaceComposerClient.cpp
index 0b5e504..3117495 100644
--- a/libs/surfaceflinger_client/SurfaceComposerClient.cpp
+++ b/libs/surfaceflinger_client/SurfaceComposerClient.cpp
@@ -319,10 +319,30 @@
         PixelFormat format,
         uint32_t flags)
 {
+    String8 name;
+    const size_t SIZE = 128;
+    char buffer[SIZE];
+    snprintf(buffer, SIZE, "<pid_%d>", getpid());
+    name.append(buffer);
+
+    return SurfaceComposerClient::createSurface(pid, name, display,
+            w, h, format, flags);
+
+}
+
+sp<SurfaceControl> SurfaceComposerClient::createSurface(
+        int pid,
+        const String8& name,
+        DisplayID display,
+        uint32_t w,
+        uint32_t h,
+        PixelFormat format,
+        uint32_t flags)
+{
     sp<SurfaceControl> result;
     if (mStatus == NO_ERROR) {
         ISurfaceFlingerClient::surface_data_t data;
-        sp<ISurface> surface = mClient->createSurface(&data, pid,
+        sp<ISurface> surface = mClient->createSurface(&data, pid, name,
                 display, w, h, format, flags);
         if (surface != 0) {
             if (uint32_t(data.token) < NUM_LAYERS_MAX) {
diff --git a/libs/utils/ResourceTypes.cpp b/libs/utils/ResourceTypes.cpp
index 5f89788..6da11b5 100644
--- a/libs/utils/ResourceTypes.cpp
+++ b/libs/utils/ResourceTypes.cpp
@@ -4149,22 +4149,165 @@
                     } else {
                         sprintf(density, "%d", (int)dval);
                     }
-                    printf("      config %d lang=%c%c cnt=%c%c orien=%d touch=%d density=%s key=%d infl=%d nav=%d w=%d h=%d sz=%d lng=%d\n",
-                           (int)configIndex,
-                           type->config.language[0] ? type->config.language[0] : '-',
-                           type->config.language[1] ? type->config.language[1] : '-',
-                           type->config.country[0] ? type->config.country[0] : '-',
-                           type->config.country[1] ? type->config.country[1] : '-',
-                           type->config.orientation,
-                           type->config.touchscreen,
-                           density,
-                           type->config.keyboard,
-                           type->config.inputFlags,
-                           type->config.navigation,
-                           dtohs(type->config.screenWidth),
-                           dtohs(type->config.screenHeight),
-                           type->config.screenLayout&ResTable_config::MASK_SCREENSIZE,
-                           type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
+                    printf("      config %d", (int)configIndex);
+                    if (type->config.mcc != 0) {
+                        printf(" mcc=%d", dtohs(type->config.mcc));
+                    }
+                    if (type->config.mnc != 0) {
+                        printf(" mnc=%d", dtohs(type->config.mnc));
+                    }
+                    if (type->config.locale != 0) {
+                        printf(" lang=%c%c cnt=%c%c",
+                               type->config.language[0] ? type->config.language[0] : '-',
+                               type->config.language[1] ? type->config.language[1] : '-',
+                               type->config.country[0] ? type->config.country[0] : '-',
+                               type->config.country[1] ? type->config.country[1] : '-');
+                    }
+                    if (type->config.screenLayout != 0) {
+                        printf(" sz=%d",
+                                type->config.screenLayout&ResTable_config::MASK_SCREENSIZE);
+                        switch (type->config.screenLayout&ResTable_config::MASK_SCREENSIZE) {
+                            case ResTable_config::SCREENSIZE_SMALL:
+                                printf(" (small)");
+                                break;
+                            case ResTable_config::SCREENSIZE_NORMAL:
+                                printf(" (normal)");
+                                break;
+                            case ResTable_config::SCREENSIZE_LARGE:
+                                printf(" (large)");
+                                break;
+                        }
+                        printf(" lng=%d",
+                                type->config.screenLayout&ResTable_config::MASK_SCREENLONG);
+                        switch (type->config.screenLayout&ResTable_config::MASK_SCREENLONG) {
+                            case ResTable_config::SCREENLONG_NO:
+                                printf(" (notlong)");
+                                break;
+                            case ResTable_config::SCREENLONG_YES:
+                                printf(" (long)");
+                                break;
+                        }
+                    }
+                    if (type->config.orientation != 0) {
+                        printf(" orient=%d", type->config.orientation);
+                        switch (type->config.orientation) {
+                            case ResTable_config::ORIENTATION_PORT:
+                                printf(" (port)");
+                                break;
+                            case ResTable_config::ORIENTATION_LAND:
+                                printf(" (land)");
+                                break;
+                            case ResTable_config::ORIENTATION_SQUARE:
+                                printf(" (square)");
+                                break;
+                        }
+                    }
+                    if (type->config.uiMode != 0) {
+                        printf(" type=%d",
+                                type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
+                        switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_TYPE) {
+                            case ResTable_config::UI_MODE_TYPE_NORMAL:
+                                printf(" (normal)");
+                                break;
+                            case ResTable_config::UI_MODE_TYPE_CAR:
+                                printf(" (car)");
+                                break;
+                        }
+                        printf(" night=%d",
+                                type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
+                        switch (type->config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT) {
+                            case ResTable_config::UI_MODE_NIGHT_NO:
+                                printf(" (no)");
+                                break;
+                            case ResTable_config::UI_MODE_NIGHT_YES:
+                                printf(" (yes)");
+                                break;
+                        }
+                    }
+                    if (dval != 0) {
+                        printf(" density=%s", density);
+                    }
+                    if (type->config.touchscreen != 0) {
+                        printf(" touch=%d", type->config.touchscreen);
+                        switch (type->config.touchscreen) {
+                            case ResTable_config::TOUCHSCREEN_NOTOUCH:
+                                printf(" (notouch)");
+                                break;
+                            case ResTable_config::TOUCHSCREEN_STYLUS:
+                                printf(" (stylus)");
+                                break;
+                            case ResTable_config::TOUCHSCREEN_FINGER:
+                                printf(" (finger)");
+                                break;
+                        }
+                    }
+                    if (type->config.inputFlags != 0) {
+                        printf(" keyhid=%d", type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN);
+                        switch (type->config.inputFlags&ResTable_config::MASK_KEYSHIDDEN) {
+                            case ResTable_config::KEYSHIDDEN_NO:
+                                printf(" (no)");
+                                break;
+                            case ResTable_config::KEYSHIDDEN_YES:
+                                printf(" (yes)");
+                                break;
+                            case ResTable_config::KEYSHIDDEN_SOFT:
+                                printf(" (soft)");
+                                break;
+                        }
+                        printf(" navhid=%d", type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN);
+                        switch (type->config.inputFlags&ResTable_config::MASK_NAVHIDDEN) {
+                            case ResTable_config::NAVHIDDEN_NO:
+                                printf(" (no)");
+                                break;
+                            case ResTable_config::NAVHIDDEN_YES:
+                                printf(" (yes)");
+                                break;
+                        }
+                    }
+                    if (type->config.keyboard != 0) {
+                        printf(" kbd=%d", type->config.keyboard);
+                        switch (type->config.keyboard) {
+                            case ResTable_config::KEYBOARD_NOKEYS:
+                                printf(" (nokeys)");
+                                break;
+                            case ResTable_config::KEYBOARD_QWERTY:
+                                printf(" (qwerty)");
+                                break;
+                            case ResTable_config::KEYBOARD_12KEY:
+                                printf(" (12key)");
+                                break;
+                        }
+                    }
+                    if (type->config.navigation != 0) {
+                        printf(" nav=%d", type->config.navigation);
+                        switch (type->config.navigation) {
+                            case ResTable_config::NAVIGATION_NONAV:
+                                printf(" (nonav)");
+                                break;
+                            case ResTable_config::NAVIGATION_DPAD:
+                                printf(" (dpad)");
+                                break;
+                            case ResTable_config::NAVIGATION_TRACKBALL:
+                                printf(" (trackball)");
+                                break;
+                            case ResTable_config::NAVIGATION_WHEEL:
+                                printf(" (wheel)");
+                                break;
+                        }
+                    }
+                    if (type->config.screenWidth != 0) {
+                        printf(" w=%d", dtohs(type->config.screenWidth));
+                    }
+                    if (type->config.screenHeight != 0) {
+                        printf(" h=%d", dtohs(type->config.screenHeight));
+                    }
+                    if (type->config.sdkVersion != 0) {
+                        printf(" sdk=%d", dtohs(type->config.sdkVersion));
+                    }
+                    if (type->config.minorVersion != 0) {
+                        printf(" mver=%d", dtohs(type->config.minorVersion));
+                    }
+                    printf("\n");
                     size_t entryCount = dtohl(type->entryCount);
                     uint32_t entriesStart = dtohl(type->entriesStart);
                     if ((entriesStart&0x3) != 0) {
diff --git a/packages/TtsService/src/android/tts/TtsService.java b/packages/TtsService/src/android/tts/TtsService.java
index c0e4cc0..7f76425 100755
--- a/packages/TtsService/src/android/tts/TtsService.java
+++ b/packages/TtsService/src/android/tts/TtsService.java
@@ -206,6 +206,9 @@
 
     private int setEngine(String enginePackageName) {
         String soFilename = "";
+        if (isDefaultEnforced()) {
+            enginePackageName = getDefaultEngine();
+        }
         // The SVOX TTS is an exception to how the TTS packaging scheme works
         // because it is part of the system and not a 3rd party add-on; thus
         // its binary is actually located under /system/lib/
@@ -779,12 +782,19 @@
                     if (mKillList.get(speechItem) == null) {
                         if (engine.length() > 0) {
                             setEngine(engine);
+                        } else {
+                            setEngine(getDefaultEngine());
                         }
                         if (language.length() > 0){
                             setLanguage("", language, country, variant);
+                        } else {
+                            setLanguage("", getDefaultLanguage(), getDefaultCountry(),
+                                    getDefaultLocVariant());
                         }
                         if (speechRate.length() > 0){
                             setSpeechRate("", Integer.parseInt(speechRate));
+                        } else {
+                            setSpeechRate("", getDefaultRate());
                         }
                         try {
                             sNativeSynth.speak(speechItem.mText, streamType);
@@ -864,12 +874,19 @@
                     if (mKillList.get(speechItem) == null){
                         if (engine.length() > 0) {
                             setEngine(engine);
+                        } else {
+                            setEngine(getDefaultEngine());
                         }
                         if (language.length() > 0){
                             setLanguage("", language, country, variant);
+                        } else {
+                            setLanguage("", getDefaultLanguage(), getDefaultCountry(),
+                                    getDefaultLocVariant());
                         }
                         if (speechRate.length() > 0){
                             setSpeechRate("", Integer.parseInt(speechRate));
+                        } else {
+                            setSpeechRate("", getDefaultRate());
                         }
                         try {
                             sNativeSynth.synthesizeToFile(speechItem.mText, speechItem.mFilename);
diff --git a/services/java/com/android/server/SensorService.java b/services/java/com/android/server/SensorService.java
index 01d64a7..9f5718f 100644
--- a/services/java/com/android/server/SensorService.java
+++ b/services/java/com/android/server/SensorService.java
@@ -24,7 +24,11 @@
 import android.os.IBinder;
 import android.util.Config;
 import android.util.Slog;
+import android.util.PrintWriterPrinter;
+import android.util.Printer;
 
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
 import java.util.ArrayList;
 
 import com.android.internal.app.IBatteryStats;
@@ -43,6 +47,7 @@
     private static final boolean DEBUG = false;
     private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
     private static final int SENSOR_DISABLE = -1;
+    private int mCurrentDelay = 0;
     
     /**
      * Battery statistics to be updated when sensors are enabled and disabled.
@@ -51,17 +56,19 @@
 
     private final class Listener implements IBinder.DeathRecipient {
         final IBinder mToken;
+        final int mUid;
 
         int mSensors = 0;
         int mDelay = 0x7FFFFFFF;
         
-        Listener(IBinder token) {
+        Listener(IBinder token, int uid) {
             mToken = token;
+            mUid = uid;
         }
         
         void addSensor(int sensor, int delay) {
             mSensors |= (1<<sensor);
-            if (mDelay > delay)
+            if (delay < mDelay)
             	mDelay = delay;
         }
         
@@ -83,16 +90,20 @@
                 for (int sensor=0 ; sensor<32 && mSensors!=0 ; sensor++) {
                     if (hasSensor(sensor)) {
                         removeSensor(sensor);
+                        deactivateIfUnusedLocked(sensor);
                         try {
-                            deactivateIfUnusedLocked(sensor);
+                            mBatteryStats.noteStopSensor(mUid, sensor);
                         } catch (RemoteException e) {
-                            Slog.w(TAG, "RemoteException in binderDied");
+                            // oops. not a big deal.
                         }
                     }
                 }
                 if (mListeners.size() == 0) {
                     _sensors_control_wake();
                     _sensors_control_close();
+                } else {
+                    // TODO: we should recalculate the delay, since removing
+                    // a listener may increase the overall rate.
                 }
                 mListeners.notify();
             }
@@ -113,86 +124,151 @@
     }
 
     public boolean enableSensor(IBinder binder, String name, int sensor, int enable)
-             throws RemoteException {
-        if (localLOGV) Slog.d(TAG, "enableSensor " + name + "(#" + sensor + ") " + enable);
+            throws RemoteException {
         
-        // Inform battery statistics service of status change
-        int uid = Binder.getCallingUid();
-        long identity = Binder.clearCallingIdentity();
-        if (enable == SENSOR_DISABLE) {
-            mBatteryStats.noteStopSensor(uid, sensor);
-        } else {
-            mBatteryStats.noteStartSensor(uid, sensor);
-        }
-        Binder.restoreCallingIdentity(identity);
+        if (localLOGV) Slog.d(TAG, "enableSensor " + name + "(#" + sensor + ") " + enable);
 
         if (binder == null) {
-            Slog.w(TAG, "listener is null (sensor=" + name + ", id=" + sensor + ")");
+            Slog.e(TAG, "listener is null (sensor=" + name + ", id=" + sensor + ")");
             return false;
         }
 
+        if (enable < 0 && (enable != SENSOR_DISABLE)) {
+            Slog.e(TAG, "invalid enable parameter (enable=" + enable +
+                    ", sensor=" + name + ", id=" + sensor + ")");
+            return false;
+        }
+
+        boolean res;
+        int uid = Binder.getCallingUid();
         synchronized(mListeners) {
-            if (enable!=SENSOR_DISABLE && !_sensors_control_activate(sensor, true)) {
+            res = enableSensorInternalLocked(binder, uid, name, sensor, enable);
+            if (res == true) {
+                // Inform battery statistics service of status change
+                long identity = Binder.clearCallingIdentity();
+                if (enable == SENSOR_DISABLE) {
+                    mBatteryStats.noteStopSensor(uid, sensor);
+                } else {
+                    mBatteryStats.noteStartSensor(uid, sensor);
+                }
+                Binder.restoreCallingIdentity(identity);
+            }
+        }
+        return res;
+    }
+
+    private boolean enableSensorInternalLocked(IBinder binder, int uid,
+            String name, int sensor, int enable) throws RemoteException {
+
+        // check if we have this listener
+        Listener l = null;
+        for (Listener listener : mListeners) {
+            if (binder == listener.mToken) {
+                l = listener;
+                break;
+            }
+        }
+
+        if (enable != SENSOR_DISABLE) {
+            // Activate the requested sensor
+            if (_sensors_control_activate(sensor, true) == false) {
                 Slog.w(TAG, "could not enable sensor " + sensor);
                 return false;
             }
-                    
-            Listener l = null;
-            int minDelay = enable;
-            for (Listener listener : mListeners) {
-                if (binder == listener.mToken) {
-                    l = listener;
-                }
-                if (minDelay > listener.mDelay)
-                    minDelay = listener.mDelay;
-            }
-            
-            if (l == null && enable!=SENSOR_DISABLE) {
-                l = new Listener(binder);
+
+            if (l == null) {
+                /*
+                 * we don't have a listener for this binder yet, so
+                 * create a new one and add it to the list.
+                 */
+                l = new Listener(binder, uid);
                 binder.linkToDeath(l, 0);
                 mListeners.add(l);
                 mListeners.notify();
             }
-            
+
+            // take note that this sensor is now used by this client
+            l.addSensor(sensor, enable);
+
+        } else {
+
             if (l == null) {
-                // by construction, this means we're disabling a listener we
-                // don't know about...
-                Slog.w(TAG, "listener with binder " + binder + 
-                        ", doesn't exist (sensor=" + name + ", id=" + sensor + ")");
+                /*
+                 *  This client isn't in the list, this usually happens
+                 *  when enabling the sensor failed, but the client
+                 *  didn't handle the error and later tries to shut that
+                 *  sensor off.
+                 */
+                Slog.w(TAG, "listener with binder " + binder +
+                        ", doesn't exist (sensor=" + name +
+                        ", id=" + sensor + ")");
                 return false;
             }
-            
-            if (minDelay >= 0) {
-                _sensors_control_set_delay(minDelay);
-            }
-            
-            if (enable != SENSOR_DISABLE) {
-                l.addSensor(sensor, enable);
-            } else {
-                l.removeSensor(sensor);
-                deactivateIfUnusedLocked(sensor);
-                if (l.mSensors == 0) {
-                    mListeners.remove(l);
-                    binder.unlinkToDeath(l, 0);
-                    mListeners.notify();
+
+            // remove this sensor from this client
+            l.removeSensor(sensor);
+
+            // see if we need to deactivate this sensors=
+            deactivateIfUnusedLocked(sensor);
+
+            // if the listener doesn't have any more sensors active
+            // we can get rid of it
+            if (l.mSensors == 0) {
+                // we won't need this death notification anymore
+                binder.unlinkToDeath(l, 0);
+                // remove the listener from the list
+                mListeners.remove(l);
+                // and if the list is empty, turn off the whole sensor h/w
+                if (mListeners.size() == 0) {
+                    _sensors_control_wake();
+                    _sensors_control_close();
                 }
+                mListeners.notify();
             }
-            
-            if (mListeners.size() == 0) {
-                _sensors_control_wake();
-                _sensors_control_close();
-            }
-        }        
+        }
+
+        // calculate and set the new delay
+        int minDelay = 0x7FFFFFFF;
+        for (Listener listener : mListeners) {
+            if (listener.mDelay < minDelay)
+                minDelay = listener.mDelay;
+        }
+        if (minDelay != 0x7FFFFFFF) {
+            mCurrentDelay = minDelay;
+            _sensors_control_set_delay(minDelay);
+        }
+
         return true;
     }
 
-    private void deactivateIfUnusedLocked(int sensor) throws RemoteException {
+    private void deactivateIfUnusedLocked(int sensor) {
         int size = mListeners.size();
         for (int i=0 ; i<size ; i++) {
-            if (mListeners.get(i).hasSensor(sensor))
+            if (mListeners.get(i).hasSensor(sensor)) {
+                // this sensor is still in use, don't turn it off
                 return;
+            }
         }
-        _sensors_control_activate(sensor, false);
+        if (_sensors_control_activate(sensor, false) == false) {
+            Slog.w(TAG, "could not disable sensor " + sensor);
+        }
+    }
+
+    @Override
+    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        synchronized (mListeners) {
+            Printer pr = new PrintWriterPrinter(pw);
+            int c = 0;
+            pr.println(mListeners.size() + " listener(s), delay=" + mCurrentDelay + " ms");
+            for (Listener l : mListeners) {
+                pr.println("listener[" + c + "] " +
+                        "sensors=0x" + Integer.toString(l.mSensors, 16) +
+                        ", uid=" + l.mUid +
+                        ", delay=" +
+                        l.mDelay + " ms");
+                c++;
+            }
+        }
     }
 
     private ArrayList<Listener> mListeners = new ArrayList<Listener>();
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index a75e05d..ba1efb9 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -7292,6 +7292,7 @@
                 try {
                     mSurface = new Surface(
                             mSession.mSurfaceSession, mSession.mPid,
+                            mAttrs.getTitle().toString(),
                             0, w, h, mAttrs.format, flags);
                     if (SHOW_TRANSACTIONS) Slog.i(TAG, "  CREATE SURFACE "
                             + mSurface + " IN SESSION "
@@ -10248,6 +10249,7 @@
                         if (mBackgroundFillerSurface == null) {
                             try {
                                 mBackgroundFillerSurface = new Surface(mFxSession, 0,
+                                        "BackGroundFiller",
                                         0, dw, dh,
                                         PixelFormat.OPAQUE,
                                         Surface.FX_SURFACE_NORMAL);
@@ -10294,6 +10296,7 @@
                                             + mBlurSurface + ": CREATE");
                                     try {
                                         mBlurSurface = new Surface(mFxSession, 0,
+                                                "BlurSurface",
                                                 -1, 16, 16,
                                                 PixelFormat.OPAQUE,
                                                 Surface.FX_SURFACE_BLUR);
@@ -11073,7 +11076,9 @@
                 if (SHOW_TRANSACTIONS) Slog.i(TAG, "  DIM "
                         + mDimSurface + ": CREATE");
                 try {
-                    mDimSurface = new Surface(session, 0, -1, 16, 16, PixelFormat.OPAQUE,
+                    mDimSurface = new Surface(session, 0,
+                            "DimSurface",
+                            -1, 16, 16, PixelFormat.OPAQUE,
                             Surface.FX_SURFACE_DIM);
                 } catch (Exception e) {
                     Slog.e(TAG, "Exception creating Dim surface", e);
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index 69b2207..6e7a66d 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -1133,6 +1133,26 @@
     getNavigationName(navigation.string(), &params);
     getScreenSizeName(screenSize.string(), &params);
     getVersionName(version.string(), &params);
+    
+    // Fix up version number based on specified parameters.
+    int minSdk = 0;
+    if ((params.uiMode&ResTable_config::MASK_UI_MODE_TYPE)
+                != ResTable_config::UI_MODE_TYPE_ANY
+            ||  (params.uiMode&ResTable_config::MASK_UI_MODE_NIGHT)
+                != ResTable_config::UI_MODE_NIGHT_ANY) {
+        minSdk = SDK_FROYO;
+    } else if ((params.screenLayout&ResTable_config::MASK_SCREENSIZE)
+                != ResTable_config::SCREENSIZE_ANY
+            ||  (params.screenLayout&ResTable_config::MASK_SCREENLONG)
+                != ResTable_config::SCREENLONG_ANY
+            || params.density != ResTable_config::DENSITY_DEFAULT) {
+        minSdk = SDK_DONUT;
+    }
+    
+    if (minSdk > params.sdkVersion) {
+        params.sdkVersion = minSdk;
+    }
+    
     return params;
 }
 
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index 9a848e4..eeb00c0 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -45,6 +45,15 @@
     AXIS_VERSION
 };
 
+enum {
+    SDK_CUPCAKE = 3,
+    SDK_DONUT = 4,
+    SDK_ECLAIR = 5,
+    SDK_ECLAIR_0_1 = 6,
+    SDK_MR1 = 7,
+    SDK_FROYO = 8,
+};
+
 /**
  * This structure contains a specific variation of a single file out
  * of all the variations it can have that we can have.
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index 558b587..08530a0 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -38,7 +38,8 @@
           mUpdate(false), mExtending(false),
           mRequireLocalization(false), mPseudolocalize(false),
           mUTF8(false), mEncodingSpecified(false), mValues(false),
-          mCompressionMethod(0), mOutputAPKFile(NULL), mManifestPackageNameOverride(NULL),
+          mCompressionMethod(0), mOutputAPKFile(NULL),
+          mManifestPackageNameOverride(NULL), mInstrumentationPackageNameOverride(NULL),
           mAutoAddOverlay(false), mAssetSourceDir(NULL), mProguardFile(NULL),
           mAndroidManifestFile(NULL), mPublicOutputFile(NULL),
           mRClassDir(NULL), mResourceIntermediatesDir(NULL),
@@ -90,6 +91,8 @@
     void setOutputAPKFile(const char* val) { mOutputAPKFile = val; }
     const char* getManifestPackageNameOverride() const { return mManifestPackageNameOverride; }
     void setManifestPackageNameOverride(const char * val) { mManifestPackageNameOverride = val; }
+    const char* getInstrumentationPackageNameOverride() const { return mInstrumentationPackageNameOverride; }
+    void setInstrumentationPackageNameOverride(const char * val) { mInstrumentationPackageNameOverride = val; }
     bool getAutoAddOverlay() { return mAutoAddOverlay; }
     void setAutoAddOverlay(bool val) { mAutoAddOverlay = val; }
 
@@ -183,6 +186,7 @@
     bool        mJunkPath;
     const char* mOutputAPKFile;
     const char* mManifestPackageNameOverride;
+    const char* mInstrumentationPackageNameOverride;
     bool        mAutoAddOverlay;
     const char* mAssetSourceDir;
     const char* mProguardFile;
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index ee07415..537ae5e 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -525,6 +525,8 @@
             bool actWallpaperService = false;
             bool specCameraFeature = false;
             bool hasCameraPermission = false;
+            bool specGpsFeature = false;
+            bool hasGpsPermission = false;
             int targetSdk = 0;
             int smallScreen = 1;
             int normalScreen = 1;
@@ -719,6 +721,8 @@
                                     REQUIRED_ATTR, NULL, 1);
                             if (name == "android.hardware.camera") {
                                 specCameraFeature = true;
+                            } else if (name == "android.hardware.location.gps") {
+                                specGpsFeature = true;
                             }
                             printf("uses-feature%s:'%s'\n",
                                     req ? "" : "-not-required", name.string());
@@ -734,6 +738,8 @@
                         if (name != "" && error == "") {
                             if (name == "android.permission.CAMERA") {
                                 hasCameraPermission = true;
+                            } else if (name == "android.permission.ACCESS_FINE_LOCATION") {
+                                hasGpsPermission = true;
                             }
                             printf("uses-permission:'%s'\n", name.string());
                         } else {
@@ -859,6 +865,14 @@
                 printf("uses-feature:'android.hardware.camera.autofocus'\n");
             }
 
+            if (!specGpsFeature && hasGpsPermission) {
+                // For applications that have not explicitly stated their
+                // GPS feature requirements, but have requested the "fine" (GPS)
+                // permission, we are going to give them compatibility treatment
+                // of requiring the equivalent to original android devices.
+                printf("uses-feature:'android.hardware.location.gps'\n");
+            }
+
             if (hasMainActivity) {
                 printf("main\n");
             }
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 6d0a351..dd98c85 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -58,9 +58,10 @@
         " %s p[ackage] [-d][-f][-m][-u][-v][-x][-z][-M AndroidManifest.xml] \\\n"
         "        [-0 extension [-0 extension ...]] [-g tolerance] [-j jarfile] \\\n"
         "        [--min-sdk-version VAL] [--target-sdk-version VAL] \\\n"
-        "        [--max-sdk-version VAL] [--app-version VAL] \\\n"
-        "        [--app-version-name TEXT] [--custom-package VAL] [--utf16] \\\n"
-        "        [--auto-add-overlay] \\\n"
+        "        [--app-version VAL] [--app-version-name TEXT] [--custom-package VAL] \\\n"
+        "        [--rename-manifest-package PACKAGE] \\\n"
+        "        [--rename-instrumentation-target-package PACKAGE] \\\n"
+        "        [--utf16] [--auto-add-overlay] \\\n"
         "        [-I base-package [-I base-package ...]] \\\n"
         "        [-A asset-source-dir]  [-G class-list-file] [-P public-definitions-file] \\\n"
         "        [-S resource-sources [-S resource-sources ...]] "
@@ -127,8 +128,6 @@
         "       higher, the default encoding for resources will be in UTF-8.\n"
         "   --target-sdk-version\n"
         "       inserts android:targetSdkVersion in to manifest.\n"
-        "   --max-sdk-version\n"
-        "       inserts android:maxSdkVersion in to manifest.\n"
         "   --values\n"
         "       when used with \"dump resources\" also includes resource values.\n"
         "   --version-code\n"
@@ -139,6 +138,16 @@
         "       generates R.java into a different package.\n"
         "   --auto-add-overlay\n"
         "       Automatically add resources that are only in overlays.\n"
+        "   --rename-manifest-package\n"
+        "       Rewrite the manifest so that its package name is the package name\n"
+        "       given here.  Relative class names (for example .Foo) will be\n"
+        "       changed to absolute names with the old package so that the code\n"
+        "       does not need to change.\n"
+        "   --rename-instrumentation-target-package\n"
+        "       Rewrite the manifest so that all of its instrumentation\n"
+        "       components target the given package.  Useful when used in\n"
+        "       conjunction with --rename-manifest-package to fix tests against\n"
+        "       a package that has been renamed.\n"
         "   --utf16\n"
         "       changes default encoding for resources to UTF-16.  Only useful when API\n"
         "       level is set to 7 or higher where the default encoding is UTF-8.\n");
@@ -448,6 +457,15 @@
                         goto bail;
                     }
                     bundle.setManifestPackageNameOverride(argv[0]);
+                } else if (strcmp(cp, "-rename-instrumentation-target-package") == 0) {
+                    argc--;
+                    argv++;
+                    if (!argc) {
+                        fprintf(stderr, "ERROR: No argument supplied for '--rename-instrumentation-target-package' option\n");
+                        wantUsage = true;
+                        goto bail;
+                    }
+                    bundle.setInstrumentationPackageNameOverride(argv[0]);
                 } else if (strcmp(cp, "-auto-add-overlay") == 0) {
                     bundle.setAutoAddOverlay(true);
                 } else {
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index ae4bd14..7142b1c 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -562,9 +562,10 @@
     node->addAttribute(ns, attr, String16(value));
 }
 
-static void fullyQualifyClassName(String8& package, sp<XMLNode> node) {
+static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
+        const String16& attrName) {
     XMLNode::attribute_entry* attr = node->editAttribute(
-            String16("http://schemas.android.com/apk/res/android"), String16("name"));
+            String16("http://schemas.android.com/apk/res/android"), attrName);
     if (attr != NULL) {
         String8 name(attr->string);
 
@@ -635,19 +636,40 @@
         // Make class names fully qualified
         sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
         if (application != NULL) {
-            fullyQualifyClassName(origPackage, application);
+            fullyQualifyClassName(origPackage, application, String16("name"));
 
             Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
             for (size_t i = 0; i < children.size(); i++) {
                 sp<XMLNode> child = children.editItemAt(i);
                 String8 tag(child->getElementName());
                 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
-                    fullyQualifyClassName(origPackage, child);
+                    fullyQualifyClassName(origPackage, child, String16("name"));
+                } else if (tag == "activity-alias") {
+                    fullyQualifyClassName(origPackage, child, String16("name"));
+                    fullyQualifyClassName(origPackage, child, String16("targetActivity"));
                 }
             }
         }
     }
 
+    // Deal with manifest package name overrides
+    const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
+    if (instrumentationPackageNameOverride != NULL) {
+        // Fix up instrumentation targets.
+        Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
+        for (size_t i = 0; i < children.size(); i++) {
+            sp<XMLNode> child = children.editItemAt(i);
+            String8 tag(child->getElementName());
+            if (tag == "instrumentation") {
+                XMLNode::attribute_entry* attr = child->editAttribute(
+                        String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
+                if (attr != NULL) {
+                    attr->string.setTo(String16(instrumentationPackageNameOverride));
+                }
+            }
+        }
+    }
+    
     return NO_ERROR;
 }