Merge "fix SurfaceView visibility state changes" into jb-dev
diff --git a/Android.mk b/Android.mk
index eef900a..b0a3dac 100644
--- a/Android.mk
+++ b/Android.mk
@@ -61,7 +61,6 @@
 LOCAL_SRC_FILES += \
 	core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl \
 	core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl \
-	core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.aidl \
 	core/java/android/accounts/IAccountManager.aidl \
 	core/java/android/accounts/IAccountManagerResponse.aidl \
 	core/java/android/accounts/IAccountAuthenticator.aidl \
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 939c117..539b84e 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -129,6 +129,9 @@
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/accessibilityservice/IEventListener.java)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/accessibilityservice/IEventListener.P)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/view/accessibility/IAccessibilityManager.P)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.java)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.P)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/accessibilityservice/IAccessibilityServiceClient.P)
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index c0fb06f..1d5f207 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -55,6 +55,10 @@
 #define SYSTEM_BOOTANIMATION_FILE "/system/media/bootanimation.zip"
 #define SYSTEM_ENCRYPTED_BOOTANIMATION_FILE "/system/media/bootanimation-encrypted.zip"
 
+extern "C" int clock_nanosleep(clockid_t clock_id, int flags,
+                           const struct timespec *request,
+                           struct timespec *remain);
+
 namespace android {
 
 // ---------------------------------------------------------------------------
@@ -476,6 +480,7 @@
         for (int r=0 ; !part.count || r<part.count ; r++) {
             for (int j=0 ; j<fcount && !exitPending(); j++) {
                 const Animation::Frame& frame(part.frames[j]);
+                nsecs_t lastFrame = systemTime();
 
                 if (r > 0) {
                     glBindTexture(GL_TEXTURE_2D, frame.tid);
@@ -508,10 +513,18 @@
 
                 nsecs_t now = systemTime();
                 nsecs_t delay = frameDuration - (now - lastFrame);
+                //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
                 lastFrame = now;
-                long wait = ns2us(delay);
-                if (wait > 0)
-                    usleep(wait);
+
+                if (delay > 0) {
+                    struct timespec spec;
+                    spec.tv_sec  = (now + delay) / 1000000000;
+                    spec.tv_nsec = (now + delay) % 1000000000;
+                    int err;
+                    do {
+                        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
+                    } while (err<0 && errno == EINTR);
+                }
             }
             usleep(part.pause * ns2us(frameDuration));
         }
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 850fe48..044c0c2 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -371,7 +371,7 @@
      *
      * <strong>Note:</strong> To receive gestures an accessibility service must
      * request that the device is in touch exploration mode by setting the
-     * {@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS}
+     * {@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE}
      * flag.
      *
      * @param gestureId The unique id of the performed gesture.
@@ -565,10 +565,8 @@
             mCaller.sendMessage(message);
         }
 
-        public void onGesture(int gestureId, IAccessibilityServiceClientCallback callback,
-                int interactionId) {
-            Message message = mCaller.obtainMessageIIO(DO_ON_GESTURE, gestureId, interactionId,
-                    callback);
+        public void onGesture(int gestureId) {
+            Message message = mCaller.obtainMessageI(DO_ON_GESTURE, gestureId);
             mCaller.sendMessage(message);
         }
 
@@ -601,15 +599,7 @@
                     return;
                 case DO_ON_GESTURE :
                     final int gestureId = message.arg1;
-                    final int interactionId = message.arg2;
-                    IAccessibilityServiceClientCallback callback =
-                        (IAccessibilityServiceClientCallback) message.obj;
-                    final boolean handled = mCallback.onGesture(gestureId);
-                    try {
-                        callback.setGestureResult(gestureId, handled, interactionId);
-                    } catch (RemoteException re) {
-                        Log.e(LOG_TAG, "Error calling back with the gesture resut.", re);
-                    }
+                    mCallback.onGesture(gestureId);
                     return;
                 default :
                     Log.w(LOG_TAG, "Unknown message type " + message.what);
diff --git a/core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl b/core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl
index 0257aa4..d459fd5 100644
--- a/core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl
+++ b/core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl
@@ -16,7 +16,6 @@
 
 package android.accessibilityservice;
 
-import android.accessibilityservice.IAccessibilityServiceClientCallback;
 import android.accessibilityservice.IAccessibilityServiceConnection;
 import android.view.accessibility.AccessibilityEvent;
 
@@ -33,5 +32,5 @@
 
     void onInterrupt();
 
-    void onGesture(int gesture, in IAccessibilityServiceClientCallback callback, int interactionId);
+    void onGesture(int gesture);
 }
diff --git a/core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.aidl b/core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.aidl
deleted file mode 100644
index 9061398..0000000
--- a/core/java/android/accessibilityservice/IAccessibilityServiceClientCallback.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
-** Copyright 2012, 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.accessibilityservice;
-
-import android.accessibilityservice.IAccessibilityServiceConnection;
-import android.view.accessibility.AccessibilityEvent;
-
-/**
- * Callback for IAccessibilityServiceClient.
- *
- * @hide
- */
- oneway interface IAccessibilityServiceClientCallback {
-
-    void setGestureResult(int gestureId, boolean handled, int interactionId);
-}
diff --git a/core/java/android/os/Power.java b/core/java/android/os/Power.java
deleted file mode 100644
index 58df940..0000000
--- a/core/java/android/os/Power.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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 android.os;
-
-import java.io.IOException;
-import android.os.ServiceManager;
-
-/**
- * Class that provides access to some of the power management functions.
- *
- * {@hide}
- */
-public class Power
-{
-    // can't instantiate this class
-    private Power()
-    {
-    }
-
-    /**
-     * Wake lock that ensures that the CPU is running.  The screen might
-     * not be on.
-     */
-    public static final int PARTIAL_WAKE_LOCK = 1;
-
-    /**
-     * Wake lock that ensures that the screen is on.
-     */
-    public static final int FULL_WAKE_LOCK = 2;
-
-    public static native void acquireWakeLock(int lock, String id);
-    public static native void releaseWakeLock(String id);
-
-    /**
-     * Brightness value for fully off
-     */
-    public static final int BRIGHTNESS_OFF = 0;
-
-    /**
-     * Brightness value for dim backlight
-     */
-    public static final int BRIGHTNESS_DIM = 20;
-
-    /**
-     * Brightness value for fully on
-     */
-    public static final int BRIGHTNESS_ON = 255;
-
-    /**
-     * Brightness value to use when battery is low
-     */
-    public static final int BRIGHTNESS_LOW_BATTERY = 10;
-
-    /**
-     * Threshold for BRIGHTNESS_LOW_BATTERY (percentage)
-     * Screen will stay dim if battery level is <= LOW_BATTERY_THRESHOLD
-     */
-    public static final int LOW_BATTERY_THRESHOLD = 10;
-
-    /**
-     * Turn the screen on or off
-     *
-     * @param on Whether you want the screen on or off
-     */
-    public static native int setScreenState(boolean on);
-
-    public static native int setLastUserActivityTimeout(long ms);
-
-    /**
-     * Low-level function turn the device off immediately, without trying
-     * to be clean.  Most people should use
-     * {@link android.internal.app.ShutdownThread} for a clean shutdown.
-     *
-     * @deprecated
-     * @hide
-     */
-    @Deprecated
-    public static native void shutdown();
-
-    /**
-     * Reboot the device.
-     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
-     *
-     * @throws IOException if reboot fails for some reason (eg, lack of
-     *         permission)
-     */
-    public static void reboot(String reason) throws IOException
-    {
-        rebootNative(reason);
-    }
-
-    private static native void rebootNative(String reason) throws IOException ;
-
-    public static native int powerInitNative();
-}
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 21373ec..903c8b3 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -197,7 +197,31 @@
      * Does not work with PARTIAL_WAKE_LOCKs.
      */
     public static final int ON_AFTER_RELEASE = 0x20000000;
-    
+
+    /**
+     * Brightness value to use when battery is low.
+     * @hide
+     */
+    public static final int BRIGHTNESS_LOW_BATTERY = 10;
+
+    /**
+     * Brightness value for fully on.
+     * @hide
+     */
+    public static final int BRIGHTNESS_ON = 255;
+
+    /**
+     * Brightness value for dim backlight.
+     * @hide
+     */
+    public static final int BRIGHTNESS_DIM = 20;
+
+    /**
+     * Brightness value for fully off.
+     * @hide
+     */
+    public static final int BRIGHTNESS_OFF = 0;
+
     /**
      * Class lets you say that you need to have the device on.
      * <p>
diff --git a/core/java/android/service/wallpaper/WallpaperService.java b/core/java/android/service/wallpaper/WallpaperService.java
index 9d36677..3e0942c 100644
--- a/core/java/android/service/wallpaper/WallpaperService.java
+++ b/core/java/android/service/wallpaper/WallpaperService.java
@@ -154,7 +154,6 @@
         int mCurWindowPrivateFlags = mWindowPrivateFlags;
         final Rect mVisibleInsets = new Rect();
         final Rect mWinFrame = new Rect();
-        final Rect mSystemInsets = new Rect();
         final Rect mContentInsets = new Rect();
         final Configuration mConfiguration = new Configuration();
         
@@ -254,7 +253,7 @@
 
         final BaseIWindow mWindow = new BaseIWindow() {
             @Override
-            public void resized(int w, int h, Rect systemInsets, Rect contentInsets,
+            public void resized(int w, int h, Rect contentInsets,
                     Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
                 Message msg = mCaller.obtainMessageI(MSG_WINDOW_RESIZED,
                         reportDraw ? 1 : 0);
@@ -621,7 +620,7 @@
 
                     final int relayoutResult = mSession.relayout(
                         mWindow, mWindow.mSeq, mLayout, mWidth, mHeight,
-                            View.VISIBLE, 0, mWinFrame, mSystemInsets, mContentInsets,
+                            View.VISIBLE, 0, mWinFrame, mContentInsets,
                             mVisibleInsets, mConfiguration, mSurfaceHolder.mSurface);
 
                     if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface
diff --git a/core/java/android/view/IWindow.aidl b/core/java/android/view/IWindow.aidl
index 555f306..b4caad3 100644
--- a/core/java/android/view/IWindow.aidl
+++ b/core/java/android/view/IWindow.aidl
@@ -45,7 +45,7 @@
      */
     void executeCommand(String command, String parameters, in ParcelFileDescriptor descriptor);
 
-    void resized(int w, int h, in Rect systemInsets, in Rect contentInsets,
+    void resized(int w, int h, in Rect contentInsets,
             in Rect visibleInsets, boolean reportDraw, in Configuration newConfig);
     void dispatchAppVisibility(boolean visible);
     void dispatchGetNewSurface();
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index f26d5e1..d4a03ce 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -58,10 +58,6 @@
      * {@link WindowManagerImpl#RELAYOUT_DEFER_SURFACE_DESTROY}.
      * @param outFrame Rect in which is placed the new position/size on
      * screen.
-     * @param outSystemInsets Rect in which is placed the offsets from
-     * <var>outFrame</var> over which any core system UI elements are
-     * currently covering the window.  This is not generally used for
-     * layout, but just to know where the window is obscured.
      * @param outContentInsets Rect in which is placed the offsets from
      * <var>outFrame</var> in which the content of the window should be
      * placed.  This can be used to modify the window layout to ensure its
@@ -83,7 +79,7 @@
      */
     int relayout(IWindow window, int seq, in WindowManager.LayoutParams attrs,
             int requestedWidth, int requestedHeight, int viewVisibility,
-            int flags, out Rect outFrame, out Rect outSystemInsets,
+            int flags, out Rect outFrame,
             out Rect outContentInsets, out Rect outVisibleInsets,
             out Configuration outConfig, out Surface outSurface);
 
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 5e7a12b..fd302dc 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -98,7 +98,6 @@
     MyWindow mWindow;
     final Rect mVisibleInsets = new Rect();
     final Rect mWinFrame = new Rect();
-    final Rect mSystemInsets = new Rect();
     final Rect mContentInsets = new Rect();
     final Configuration mConfiguration = new Configuration();
     
@@ -482,7 +481,7 @@
                         mWindow, mWindow.mSeq, mLayout, mWidth, mHeight,
                             visible ? VISIBLE : GONE,
                             WindowManagerImpl.RELAYOUT_DEFER_SURFACE_DESTROY,
-                            mWinFrame, mSystemInsets, mContentInsets,
+                            mWinFrame, mContentInsets,
                             mVisibleInsets, mConfiguration, mNewSurface);
                     if ((relayoutResult&WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) {
                         mReportDrawNeeded = true;
@@ -616,7 +615,7 @@
             mSurfaceView = new WeakReference<SurfaceView>(surfaceView);
         }
 
-        public void resized(int w, int h, Rect systemInsets, Rect contentInsets,
+        public void resized(int w, int h, Rect contentInsets,
                 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
             SurfaceView surfaceView = mSurfaceView.get();
             if (surfaceView != null) {
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 4d13e8a..501cf29 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -666,7 +666,7 @@
     protected static final String VIEW_LOG_TAG = "View";
 
     /**
-     * When set to true, apps will draw debugging information about their layouts. 
+     * When set to true, apps will draw debugging information about their layouts.
      *
      * @hide
      */
@@ -4801,17 +4801,46 @@
      * entirely by its predecessors, and has an alpha greater than zero.
      *
      * @return Whether the view is visible on the screen.
+     *
+     * @hide
      */
-    private boolean isVisibleToUser() {
+    protected boolean isVisibleToUser() {
+        return isVisibleToUser(null);
+    }
+
+    /**
+     * Computes whether the given portion of this view is visible to the user. Such a view is
+     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
+     * the specified portion is not clipped entirely by its predecessors.
+     *
+     * @param boundInView the portion of the view to test; coordinates should be relative; may be
+     *                    <code>null</code>, and the entire view will be tested in this case.
+     *                    When <code>true</code> is returned by the function, the actual visible
+     *                    region will be stored in this parameter; that is, if boundInView is fully
+     *                    contained within the view, no modification will be made, otherwise regions
+     *                    outside of the visible area of the view will be clipped.
+     *
+     * @return Whether the specified portion of the view is visible on the screen.
+     *
+     * @hide
+     */
+    protected boolean isVisibleToUser(Rect boundInView) {
+        Rect visibleRect = mAttachInfo.mTmpInvalRect;
+        Point offset = mAttachInfo.mPoint;
         // The first two checks are made also made by isShown() which
         // however traverses the tree up to the parent to catch that.
         // Therefore, we do some fail fast check to minimize the up
         // tree traversal.
-        return (mAttachInfo != null
-                && mAttachInfo.mWindowVisibility == View.VISIBLE
-                && getAlpha() > 0
-                && isShown()
-                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
+        boolean isVisible = mAttachInfo != null
+            && mAttachInfo.mWindowVisibility == View.VISIBLE
+            && getAlpha() > 0
+            && isShown()
+            && getGlobalVisibleRect(visibleRect, offset);
+            if (isVisible && boundInView != null) {
+                visibleRect.offset(-offset.x, -offset.y);
+                isVisible &= boundInView.intersect(visibleRect);
+            }
+            return isVisible;
     }
 
     /**
@@ -17161,12 +17190,6 @@
         boolean mUse32BitDrawingCache;
 
         /**
-         * Describes the parts of the window that are currently completely
-         * obscured by system UI elements.
-         */
-        final Rect mSystemInsets = new Rect();
-
-        /**
          * For windows that are full-screen but using insets to layout inside
          * of the screen decorations, these are the current insets for the
          * content of the window.
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 1310719..90e6034 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -262,7 +262,6 @@
 
     final Rect mPendingVisibleInsets = new Rect();
     final Rect mPendingContentInsets = new Rect();
-    final Rect mPendingSystemInsets = new Rect();
     final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
             = new ViewTreeObserver.InternalInsetsInfo();
 
@@ -272,7 +271,6 @@
     final Configuration mPendingConfiguration = new Configuration();
 
     class ResizedInfo {
-        Rect systemInsets;
         Rect contentInsets;
         Rect visibleInsets;
         Configuration newConfig;
@@ -568,7 +566,6 @@
                 if (mTranslator != null) {
                     mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
                 }
-                mPendingSystemInsets.set(0, 0, 0, 0);
                 mPendingContentInsets.set(mAttachInfo.mContentInsets);
                 mPendingVisibleInsets.set(0, 0, 0, 0);
                 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
@@ -1235,7 +1232,6 @@
         getRunQueue().executeActions(attachInfo.mHandler);
 
         boolean insetsChanged = false;
-        boolean activeRectChanged = false;
 
         boolean layoutRequested = mLayoutRequested && !mStopped;
         if (layoutRequested) {
@@ -1247,12 +1243,7 @@
                 // to opposite of the added touch mode.
                 mAttachInfo.mInTouchMode = !mAddedTouchMode;
                 ensureTouchModeLocally(mAddedTouchMode);
-                activeRectChanged = true;
             } else {
-                if (!mPendingSystemInsets.equals(mAttachInfo.mSystemInsets)) {
-                    mAttachInfo.mSystemInsets.set(mPendingSystemInsets);
-                    activeRectChanged = true;
-                }
                 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
                     insetsChanged = true;
                 }
@@ -1406,10 +1397,6 @@
                     mPendingConfiguration.seq = 0;
                 }
 
-                if (!mPendingSystemInsets.equals(mAttachInfo.mSystemInsets)) {
-                    activeRectChanged = true;
-                    mAttachInfo.mSystemInsets.set(mPendingSystemInsets);
-                }
                 contentInsetsChanged = !mPendingContentInsets.equals(
                         mAttachInfo.mContentInsets);
                 visibleInsetsChanged = !mPendingVisibleInsets.equals(
@@ -1512,7 +1499,6 @@
                         // before actually drawing them, so it can display then
                         // all at once.
                         newSurface = true;
-                        activeRectChanged = true;
                         mFullRedrawNeeded = true;
                         mPreviousTransparentRegion.setEmpty();
 
@@ -1578,7 +1564,6 @@
             // window size we asked for. We should avoid this by getting a maximum size from
             // the window session beforehand.
             if (mWidth != frame.width() || mHeight != frame.height()) {
-                activeRectChanged = true;
                 mWidth = frame.width();
                 mHeight = frame.height();
             }
@@ -2814,7 +2799,6 @@
                 ResizedInfo ri = (ResizedInfo)msg.obj;
 
                 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
-                        && mPendingSystemInsets.equals(ri.systemInsets)
                         && mPendingContentInsets.equals(ri.contentInsets)
                         && mPendingVisibleInsets.equals(ri.visibleInsets)
                         && ((ResizedInfo)msg.obj).newConfig == null) {
@@ -2831,7 +2815,6 @@
                     mWinFrame.right = msg.arg1;
                     mWinFrame.top = 0;
                     mWinFrame.bottom = msg.arg2;
-                    mPendingSystemInsets.set(((ResizedInfo)msg.obj).systemInsets);
                     mPendingContentInsets.set(((ResizedInfo)msg.obj).contentInsets);
                     mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
                     if (msg.what == MSG_RESIZED_REPORT) {
@@ -3866,7 +3849,7 @@
                 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
                 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
                 viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0,
-                mWinFrame, mPendingSystemInsets, mPendingContentInsets, mPendingVisibleInsets,
+                mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
                 mPendingConfiguration, mSurface);
         //Log.d(TAG, "<<<<<< BACK FROM relayout");
         if (restore) {
@@ -4062,11 +4045,10 @@
         mHandler.sendMessage(msg);
     }
 
-    public void dispatchResized(int w, int h, Rect systemInsets, Rect contentInsets,
+    public void dispatchResized(int w, int h, Rect contentInsets,
             Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
         if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
-                + " h=" + h + " systemInsets=" + systemInsets.toShortString()
-                + " contentInsets=" + contentInsets.toShortString()
+                + " h=" + h + " contentInsets=" + contentInsets.toShortString()
                 + " visibleInsets=" + visibleInsets.toShortString()
                 + " reportDraw=" + reportDraw);
         Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED);
@@ -4079,7 +4061,6 @@
         msg.arg1 = w;
         msg.arg2 = h;
         ResizedInfo ri = new ResizedInfo();
-        ri.systemInsets = new Rect(systemInsets);
         ri.contentInsets = new Rect(contentInsets);
         ri.visibleInsets = new Rect(visibleInsets);
         ri.newConfig = newConfig;
@@ -4735,11 +4716,11 @@
             mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
         }
 
-        public void resized(int w, int h, Rect systemInsets, Rect contentInsets,
+        public void resized(int w, int h, Rect contentInsets,
                 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
             final ViewRootImpl viewAncestor = mViewAncestor.get();
             if (viewAncestor != null) {
-                viewAncestor.dispatchResized(w, h, systemInsets, contentInsets,
+                viewAncestor.dispatchResized(w, h, contentInsets,
                         visibleInsets, reportDraw, newConfig);
             }
         }
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index 388cfb3..0c5d6ea 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -145,10 +145,6 @@
          * @param displayFrame The frame of the overall display in which this
          * window can appear, used for constraining the overall dimensions
          * of the window.
-         * @param systemFrame The frame within the display that any system
-         * elements are currently covering.  These indicate which parts of
-         * the window should be considered completely obscured by the screen
-         * decorations.
          * @param contentFrame The frame within the display in which we would
          * like active content to appear.  This will cause windows behind to
          * be resized to match the given content frame.
@@ -160,7 +156,7 @@
          * are visible.
          */
         public void computeFrameLw(Rect parentFrame, Rect displayFrame,
-                Rect systemFrame, Rect contentFrame, Rect visibleFrame);
+                Rect contentFrame, Rect visibleFrame);
 
         /**
          * Retrieve the current frame of the window that has been assigned by
@@ -188,14 +184,6 @@
         public Rect getDisplayFrameLw();
 
         /**
-         * Retrieve the frame of the system elements that last covered the window.
-         * Must be called with the window manager lock held.
-         *
-         * @return Rect The rectangle holding the system frame.
-         */
-        public Rect getSystemFrameLw();
-
-        /**
          * Retrieve the frame of the content area that this window was last
          * laid out in.  This is the area in which the content of the window
          * should be placed.  It will be smaller than the display frame to
@@ -397,6 +385,9 @@
          * Creates an input channel that will receive all input from the input dispatcher.
          */
         public InputChannel monitorInput(String name);
+
+        public void shutdown();
+        public void rebootSafeMode();
     }
 
     /**
@@ -770,6 +761,21 @@
     public void beginLayoutLw(int displayWidth, int displayHeight, int displayRotation);
 
     /**
+     * Return the rectangle of the screen currently covered by system decorations.
+     * This will be called immediately after {@link #layoutWindowLw}.  It can
+     * fill in the rectangle to indicate any part of the screen that it knows
+     * for sure is covered by system decor such as the status bar.  The rectangle
+     * is initially set to the actual size of the screen, indicating nothing is
+     * covered.
+     *
+     * @param systemRect The rectangle of the screen that is not covered by
+     * system decoration.
+     * @return Returns the layer above which the system rectangle should
+     * not be applied.
+     */
+    public int getSystemDecorRectLw(Rect systemRect);
+
+    /**
      * Called for each window attached to the window manager as layout is
      * proceeding.  The implementation of this function must take care of
      * setting the window's frame, either here or in finishLayout().
@@ -794,7 +800,7 @@
      * 
      */
     public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset);
-    
+
     /**
      * Called when layout of the windows is finished.  After this function has
      * returned, all windows given to layoutWindow() <em>must</em> have had a
diff --git a/core/java/android/webkit/WebViewClassic.java b/core/java/android/webkit/WebViewClassic.java
index 057c3d1..eb6b7e3 100644
--- a/core/java/android/webkit/WebViewClassic.java
+++ b/core/java/android/webkit/WebViewClassic.java
@@ -7452,18 +7452,12 @@
 
                 case SHOW_RECT_MSG_ID: {
                     WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
-                    int x = getScrollX();
                     int left = contentToViewX(data.mLeft);
                     int width = contentToViewDimension(data.mWidth);
                     int maxWidth = contentToViewDimension(data.mContentWidth);
                     int viewWidth = getViewWidth();
-                    if (width < viewWidth) {
-                        // center align
-                        x += left + width / 2 - getScrollX() - viewWidth / 2;
-                    } else {
-                        x += (int) (left + data.mXPercentInDoc * width
-                                - getScrollX() - data.mXPercentInView * viewWidth);
-                    }
+                    int x = (int) (left + data.mXPercentInDoc * width -
+                                   data.mXPercentInView * viewWidth);
                     if (DebugFlags.WEB_VIEW) {
                         Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
                               width + ",maxWidth=" + maxWidth +
diff --git a/core/java/android/widget/NumberPicker.java b/core/java/android/widget/NumberPicker.java
index 6ff924b..7c809b3 100644
--- a/core/java/android/widget/NumberPicker.java
+++ b/core/java/android/widget/NumberPicker.java
@@ -2239,20 +2239,17 @@
             info.setPackageName(mContext.getPackageName());
             info.setSource(NumberPicker.this, virtualViewId);
             info.setParent(NumberPicker.this);
-            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_DECREMENT);
-            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT);
-            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INCREMENT);
             info.setText(text);
             info.setClickable(true);
             info.setLongClickable(true);
             info.setEnabled(NumberPicker.this.isEnabled());
             Rect boundsInParent = mTempRect;
             boundsInParent.set(left, top, right, bottom);
+            info.setVisibleToUser(isVisibleToUser(boundsInParent));
             info.setBoundsInParent(boundsInParent);
             Rect boundsInScreen = boundsInParent;
             int[] locationOnScreen = mTempArray;
             getLocationOnScreen(locationOnScreen);
-            boundsInScreen.offsetTo(0, 0);
             boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]);
             info.setBoundsInScreen(boundsInScreen);
             return info;
@@ -2261,19 +2258,22 @@
         private AccessibilityNodeInfo createAccessibilityNodeInfoForNumberPicker(int left, int top,
                 int right, int bottom) {
             AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain();
-            info.setClassName(Button.class.getName());
+            info.setClassName(NumberPicker.class.getName());
             info.setPackageName(mContext.getPackageName());
             info.setSource(NumberPicker.this);
+            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_DECREMENT);
+            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT);
+            info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INCREMENT);
             info.setParent((View) getParent());
             info.setEnabled(NumberPicker.this.isEnabled());
             info.setScrollable(true);
             Rect boundsInParent = mTempRect;
             boundsInParent.set(left, top, right, bottom);
             info.setBoundsInParent(boundsInParent);
+            info.setVisibleToUser(isVisibleToUser());
             Rect boundsInScreen = boundsInParent;
             int[] locationOnScreen = mTempArray;
             getLocationOnScreen(locationOnScreen);
-            boundsInScreen.offsetTo(0, 0);
             boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]);
             info.setBoundsInScreen(boundsInScreen);
             return info;
diff --git a/core/java/com/android/internal/view/BaseIWindow.java b/core/java/com/android/internal/view/BaseIWindow.java
index fbed4859..4c34d73 100644
--- a/core/java/com/android/internal/view/BaseIWindow.java
+++ b/core/java/com/android/internal/view/BaseIWindow.java
@@ -33,7 +33,7 @@
         mSession = session;
     }
     
-    public void resized(int w, int h, Rect systemInsets, Rect contentInsets,
+    public void resized(int w, int h, Rect contentInsets,
             Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
         if (reportDraw) {
             try {
diff --git a/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java b/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
index d6ffba2..60cd895 100644
--- a/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
+++ b/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
@@ -258,14 +258,14 @@
     protected int getSuggestedMinimumWidth() {
         // View should be large enough to contain the background + handle and
         // target drawable on either edge.
-        return mOuterRing.getWidth() + mMaxTargetWidth;
+        return (int) (Math.max(mOuterRing.getWidth(), 2 * mOuterRadius) + mMaxTargetWidth);
     }
 
     @Override
     protected int getSuggestedMinimumHeight() {
         // View should be large enough to contain the unlock ring + target and
         // target drawable on either edge
-        return mOuterRing.getHeight() + mMaxTargetHeight;
+        return (int) (Math.max(mOuterRing.getHeight(), 2 * mOuterRadius) + mMaxTargetHeight);
     }
 
     private int resolveMeasured(int measureSpec, int desired)
@@ -941,10 +941,14 @@
         super.onLayout(changed, left, top, right, bottom);
         final int width = right - left;
         final int height = bottom - top;
+        // Target placement width/height. This puts the targets on the greater of the ring
+        // width or the specified outer radius.
+        final float placementWidth = Math.max(mOuterRing.getWidth(), 2 * mOuterRadius);
+        final float placementHeight = Math.max(mOuterRing.getHeight(), 2 * mOuterRadius);
         float newWaveCenterX = mHorizontalOffset + mHorizontalInset
-                + Math.max(width, mMaxTargetWidth + mOuterRing.getWidth()) / 2;
+                + Math.max(width, mMaxTargetWidth + placementWidth) / 2;
         float newWaveCenterY = mVerticalOffset + mVerticalInset
-                + Math.max(height, + mMaxTargetHeight + mOuterRing.getHeight()) / 2;
+                + Math.max(height, + mMaxTargetHeight + placementHeight) / 2;
 
         assignDefaultsIfNeeded(newWaveCenterX, newWaveCenterY);
 
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index cd0959b..c24f6c6 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -66,7 +66,6 @@
 	android_os_MessageQueue.cpp \
 	android_os_ParcelFileDescriptor.cpp \
 	android_os_Parcel.cpp \
-	android_os_Power.cpp \
 	android_os_StatFs.cpp \
 	android_os_SystemClock.cpp \
 	android_os_SystemProperties.cpp \
@@ -217,8 +216,7 @@
 	libjpeg \
 	libusbhost \
 	libharfbuzz \
-	libz \
-	libsuspend \
+	libz
 
 ifeq ($(USE_OPENGL_RENDERER),true)
 	LOCAL_SHARED_LIBRARIES += libhwui
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index b877071..241a905 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -133,7 +133,6 @@
 extern int register_android_os_MessageQueue(JNIEnv* env);
 extern int register_android_os_Parcel(JNIEnv* env);
 extern int register_android_os_ParcelFileDescriptor(JNIEnv *env);
-extern int register_android_os_Power(JNIEnv *env);
 extern int register_android_os_StatFs(JNIEnv *env);
 extern int register_android_os_SystemProperties(JNIEnv *env);
 extern int register_android_os_SystemClock(JNIEnv* env);
@@ -1147,7 +1146,6 @@
     REG_JNI(register_android_os_FileUtils),
     REG_JNI(register_android_os_MessageQueue),
     REG_JNI(register_android_os_ParcelFileDescriptor),
-    REG_JNI(register_android_os_Power),
     REG_JNI(register_android_os_StatFs),
     REG_JNI(register_android_os_Trace),
     REG_JNI(register_android_os_UEventObserver),
diff --git a/core/jni/android_os_Power.cpp b/core/jni/android_os_Power.cpp
deleted file mode 100644
index 373abd4..0000000
--- a/core/jni/android_os_Power.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/* //device/libs/android_runtime/android_os_Power.cpp
-**
-** Copyright 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.
-*/
-
-#define LOG_TAG "Power-JNI"
-
-#include "JNIHelp.h"
-#include "jni.h"
-#include "android_runtime/AndroidRuntime.h"
-#include <utils/misc.h>
-#include <hardware/power.h>
-#include <hardware_legacy/power.h>
-#include <cutils/android_reboot.h>
-#include <suspend/autosuspend.h>
-
-static struct power_module *sPowerModule;
-
-namespace android
-{
-
-static void
-acquireWakeLock(JNIEnv *env, jobject clazz, jint lock, jstring idObj)
-{
-    if (idObj == NULL) {
-        jniThrowNullPointerException(env, "id is null");
-        return ;
-    }
-
-    const char *id = env->GetStringUTFChars(idObj, NULL);
-
-    acquire_wake_lock(lock, id);
-
-    env->ReleaseStringUTFChars(idObj, id);
-}
-
-static void
-releaseWakeLock(JNIEnv *env, jobject clazz, jstring idObj)
-{
-    if (idObj == NULL) {
-        jniThrowNullPointerException(env, "id is null");
-        return ;
-    }
-
-    const char *id = env->GetStringUTFChars(idObj, NULL);
-
-    release_wake_lock(id);
-
-    env->ReleaseStringUTFChars(idObj, id);
-
-}
-
-static int
-setLastUserActivityTimeout(JNIEnv *env, jobject clazz, jlong timeMS)
-{
-    return set_last_user_activity_timeout(timeMS/1000);
-}
-
-static int
-setScreenState(JNIEnv *env, jobject clazz, jboolean on)
-{
-    if (on) {
-        autosuspend_disable();
-        if (sPowerModule) {
-            sPowerModule->setInteractive(sPowerModule, true);
-        }
-    } else {
-        if (sPowerModule) {
-            sPowerModule->setInteractive(sPowerModule, false);
-        }
-        autosuspend_enable();
-    }
-
-    return 0;
-}
-
-static void android_os_Power_shutdown(JNIEnv *env, jobject clazz)
-{
-    android_reboot(ANDROID_RB_POWEROFF, 0, 0);
-}
-
-static void android_os_Power_reboot(JNIEnv *env, jobject clazz, jstring reason)
-{
-    if (reason == NULL) {
-        android_reboot(ANDROID_RB_RESTART, 0, 0);
-    } else {
-        const char *chars = env->GetStringUTFChars(reason, NULL);
-        android_reboot(ANDROID_RB_RESTART2, 0, (char *) chars);
-        env->ReleaseStringUTFChars(reason, chars);  // In case it fails.
-    }
-    jniThrowIOException(env, errno);
-}
-
-static int android_os_Power_init(JNIEnv *env, jobject clazz)
-{
-    status_t err = hw_get_module(POWER_HARDWARE_MODULE_ID,
-        (hw_module_t const**)&sPowerModule);
-    ALOGE_IF(err, "couldn't load %s module (%s)",
-             POWER_HARDWARE_MODULE_ID, strerror(-err));
-
-    if (!err)
-        sPowerModule->init(sPowerModule);
-
-    return err;
-}
-
-static JNINativeMethod method_table[] = {
-    { "acquireWakeLock", "(ILjava/lang/String;)V", (void*)acquireWakeLock },
-    { "releaseWakeLock", "(Ljava/lang/String;)V", (void*)releaseWakeLock },
-    { "setLastUserActivityTimeout", "(J)I", (void*)setLastUserActivityTimeout },
-    { "setScreenState", "(Z)I", (void*)setScreenState },
-    { "shutdown", "()V", (void*)android_os_Power_shutdown },
-    { "powerInitNative", "()I", (void*)android_os_Power_init },
-    { "rebootNative", "(Ljava/lang/String;)V", (void*)android_os_Power_reboot },
-};
-
-int register_android_os_Power(JNIEnv *env)
-{
-    return AndroidRuntime::registerNativeMethods(
-        env, "android/os/Power",
-        method_table, NELEM(method_table));
-}
-
-};
diff --git a/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock.xml b/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock.xml
index 055955e..efd406d 100644
--- a/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock.xml
+++ b/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock.xml
@@ -31,7 +31,7 @@
     <!-- top: status -->
     <RelativeLayout
         android:layout_height="0dip"
-        android:layout_weight="1"
+        android:layout_weight="0.42"
         android:layout_width="match_parent"
         android:gravity="center">
 
@@ -69,8 +69,9 @@
     <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="0dip"
-            android:layout_weight="1"
-            android:orientation="vertical">
+            android:layout_weight="0.58"
+            android:orientation="vertical"
+            android:gravity="bottom">
 
         <TextView
             android:id="@+id/screenLocked"
@@ -87,7 +88,7 @@
             android:orientation="horizontal"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_gravity="center"
+            android:layout_gravity="center_horizontal"
             android:gravity="center"
 
             android:targetDrawables="@array/lockscreen_targets_with_camera"
diff --git a/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock_land.xml b/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock_land.xml
index e68a0c1..de64a51 100644
--- a/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock_land.xml
+++ b/core/res/res/layout-sw600dp/keyguard_screen_tab_unlock_land.xml
@@ -30,7 +30,7 @@
     <!-- left side: status and music -->
     <RelativeLayout
         android:layout_height="match_parent"
-        android:layout_weight="1"
+        android:layout_weight="0.42"
         android:layout_width="0dip"
         android:gravity="center">
 
@@ -67,7 +67,7 @@
     <!-- right side -->
     <RelativeLayout
         android:layout_height="match_parent"
-        android:layout_weight="1"
+        android:layout_weight="0.58"
         android:layout_width="0dip"
         android:gravity="center_horizontal|center_vertical">
 
@@ -87,7 +87,7 @@
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_rowSpan="7"
-            android:layout_gravity="center_vertical|center_horizontal"
+            android:layout_gravity="center_vertical|right"
             android:gravity="center"
 
             android:targetDrawables="@array/lockscreen_targets_with_camera"
diff --git a/graphics/java/android/graphics/Rect.java b/graphics/java/android/graphics/Rect.java
index ec911b0..6c204ab 100644
--- a/graphics/java/android/graphics/Rect.java
+++ b/graphics/java/android/graphics/Rect.java
@@ -49,9 +49,9 @@
      * checking is performed, so the caller must ensure that left <= right and
      * top <= bottom.
      *
-     * @param left   The X coordinate of the left side of the rectagle
+     * @param left   The X coordinate of the left side of the rectangle
      * @param top    The Y coordinate of the top of the rectangle
-     * @param right  The X coordinate of the right side of the rectagle
+     * @param right  The X coordinate of the right side of the rectangle
      * @param bottom The Y coordinate of the bottom of the rectangle
      */
     public Rect(int left, int top, int right, int bottom) {
@@ -235,9 +235,9 @@
      * checking is performed, so it is up to the caller to ensure that
      * left <= right and top <= bottom.
      *
-     * @param left   The X coordinate of the left side of the rectagle
+     * @param left   The X coordinate of the left side of the rectangle
      * @param top    The Y coordinate of the top of the rectangle
-     * @param right  The X coordinate of the right side of the rectagle
+     * @param right  The X coordinate of the right side of the rectangle
      * @param bottom The Y coordinate of the bottom of the rectangle
      */
     public void set(int left, int top, int right, int bottom) {
diff --git a/graphics/java/android/graphics/RectF.java b/graphics/java/android/graphics/RectF.java
index c633d84..108b7f9 100644
--- a/graphics/java/android/graphics/RectF.java
+++ b/graphics/java/android/graphics/RectF.java
@@ -46,9 +46,9 @@
      * checking is performed, so the caller must ensure that left <= right and
      * top <= bottom.
      *
-     * @param left   The X coordinate of the left side of the rectagle
+     * @param left   The X coordinate of the left side of the rectangle
      * @param top    The Y coordinate of the top of the rectangle
-     * @param right  The X coordinate of the right side of the rectagle
+     * @param right  The X coordinate of the right side of the rectangle
      * @param bottom The Y coordinate of the bottom of the rectangle
      */
     public RectF(float left, float top, float right, float bottom) {
@@ -182,9 +182,9 @@
      * checking is performed, so it is up to the caller to ensure that
      * left <= right and top <= bottom.
      *
-     * @param left   The X coordinate of the left side of the rectagle
+     * @param left   The X coordinate of the left side of the rectangle
      * @param top    The Y coordinate of the top of the rectangle
-     * @param right  The X coordinate of the right side of the rectagle
+     * @param right  The X coordinate of the right side of the rectangle
      * @param bottom The Y coordinate of the bottom of the rectangle
      */
     public void set(float left, float top, float right, float bottom) {
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 123695a..f210820 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -48,25 +48,9 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 Caches::Caches(): Singleton<Caches>(), mInitialized(false) {
-    GLint maxTextureUnits;
-    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
-    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
-        ALOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
-    }
-
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
-
-    if (extensions.hasDebugMarker()) {
-        eventMark = glInsertEventMarkerEXT;
-        startMark = glPushGroupMarkerEXT;
-        endMark = glPopGroupMarkerEXT;
-    } else {
-        eventMark = eventMarkNull;
-        startMark = startMarkNull;
-        endMark = endMarkNull;
-    }
-
     init();
+    initExtensions();
+    initConstraints();
 
     mDebugLevel = readDebugLevel();
     ALOGD("Enabling debug mode %d", mDebugLevel);
@@ -105,6 +89,36 @@
     mInitialized = true;
 }
 
+void Caches::initExtensions() {
+    if (extensions.hasDebugMarker()) {
+        eventMark = glInsertEventMarkerEXT;
+        startMark = glPushGroupMarkerEXT;
+        endMark = glPopGroupMarkerEXT;
+    } else {
+        eventMark = eventMarkNull;
+        startMark = startMarkNull;
+        endMark = endMarkNull;
+    }
+
+    if (extensions.hasDebugLabel()) {
+        setLabel = glLabelObjectEXT;
+        getLabel = glGetObjectLabelEXT;
+    } else {
+        setLabel = setLabelNull;
+        getLabel = getLabelNull;
+    }
+}
+
+void Caches::initConstraints() {
+    GLint maxTextureUnits;
+    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
+    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
+        ALOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
+    }
+
+    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
+}
+
 void Caches::terminate() {
     if (!mInitialized) return;
 
diff --git a/libs/hwui/Caches.h b/libs/hwui/Caches.h
index 65ff9ad..58361c9 100644
--- a/libs/hwui/Caches.h
+++ b/libs/hwui/Caches.h
@@ -107,7 +107,7 @@
     };
 
     /**
-     * Initializes the cache.
+     * Initialize caches.
      */
     void init();
 
@@ -247,15 +247,30 @@
     GammaFontRenderer fontRenderer;
     ResourceCache resourceCache;
 
+    // Debug methods
     PFNGLINSERTEVENTMARKEREXTPROC eventMark;
     PFNGLPUSHGROUPMARKEREXTPROC startMark;
     PFNGLPOPGROUPMARKEREXTPROC endMark;
 
+    PFNGLLABELOBJECTEXTPROC setLabel;
+    PFNGLGETOBJECTLABELEXTPROC getLabel;
+
 private:
-    static void eventMarkNull(GLsizei length, const GLchar *marker) { }
-    static void startMarkNull(GLsizei length, const GLchar *marker) { }
+    void initExtensions();
+    void initConstraints();
+
+    static void eventMarkNull(GLsizei length, const GLchar* marker) { }
+    static void startMarkNull(GLsizei length, const GLchar* marker) { }
     static void endMarkNull() { }
 
+    static void setLabelNull(GLenum type, uint object, GLsizei length,
+            const char* label) { }
+    static void getLabelNull(GLenum type, uint object, GLsizei bufferSize,
+            GLsizei* length, char* label) {
+        if (length) *length = 0;
+        if (label) *label = '\0';
+    }
+
     GLuint mCurrentBuffer;
     GLuint mCurrentIndicesBuffer;
     void* mCurrentPositionPointer;
diff --git a/libs/hwui/Extensions.h b/libs/hwui/Extensions.h
index f11fecc..6b174d6 100644
--- a/libs/hwui/Extensions.h
+++ b/libs/hwui/Extensions.h
@@ -40,7 +40,6 @@
 #endif
 
 // Vendor strings
-
 #define VENDOR_IMG "Imagination Technologies"
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -68,6 +67,7 @@
         mHasFramebufferFetch = hasExtension("GL_NV_shader_framebuffer_fetch");
         mHasDiscardFramebuffer = hasExtension("GL_EXT_discard_framebuffer");
         mHasDebugMarker = hasExtension("GL_EXT_debug_marker");
+        mHasDebugLabel = hasExtension("GL_EXT_debug_label");
 
         const char* vendor = (const char*) glGetString(GL_VENDOR);
         EXT_LOGD("Vendor: %s", vendor);
@@ -84,6 +84,7 @@
     inline bool needsHighpTexCoords() const { return mNeedsHighpTexCoords; }
     inline bool hasDiscardFramebuffer() const { return mHasDiscardFramebuffer; }
     inline bool hasDebugMarker() const { return mHasDebugMarker; }
+    inline bool hasDebugLabel() const { return mHasDebugLabel; }
 
     bool hasExtension(const char* extension) const {
         const String8 s(extension);
@@ -104,6 +105,7 @@
     bool mHasFramebufferFetch;
     bool mHasDiscardFramebuffer;
     bool mHasDebugMarker;
+    bool mHasDebugLabel;
 }; // class Extensions
 
 }; // namespace uirenderer
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index f412b9b..8015203 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -33,6 +33,7 @@
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothHeadset;
 import android.bluetooth.BluetoothProfile;
+import android.content.ActivityNotFoundException;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.ContentResolver;
@@ -3607,24 +3608,20 @@
     // RemoteControl
     //==========================================================================================
     public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
-        dispatchMediaKeyEvent(keyEvent, false /*needWakeLock*/);
+        filterMediaKeyEvent(keyEvent, false /*needWakeLock*/);
     }
 
     public void dispatchMediaKeyEventUnderWakelock(KeyEvent keyEvent) {
-        dispatchMediaKeyEvent(keyEvent, true /*needWakeLock*/);
+        filterMediaKeyEvent(keyEvent, true /*needWakeLock*/);
     }
 
-    /**
-     * Handles the dispatching of the media button events to one of the registered listeners,
-     * or if there was none, broadcast a ACTION_MEDIA_BUTTON intent to the rest of the system.
-     */
-    private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
+    private void filterMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
         // sanity check on the incoming key event
         if (!isValidMediaKeyEvent(keyEvent)) {
             Log.e(TAG, "not dispatching invalid media key event " + keyEvent);
             return;
         }
-        // event filtering
+        // event filtering based on audio mode
         synchronized(mRingingLock) {
             if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
                     (getMode() == AudioSystem.MODE_IN_COMMUNICATION) ||
@@ -3632,6 +3629,22 @@
                 return;
             }
         }
+        // event filtering based on voice-based interactions
+        if (isValidVoiceInputKeyCode(keyEvent.getKeyCode())) {
+            filterVoiceInputKeyEvent(keyEvent, needWakeLock);
+        } else {
+            dispatchMediaKeyEvent(keyEvent, needWakeLock);
+        }
+    }
+
+    /**
+     * Handles the dispatching of the media button events to one of the registered listeners,
+     * or if there was none, broadcast an ACTION_MEDIA_BUTTON intent to the rest of the system.
+     * @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons
+     * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
+     *     is dispatched.
+     */
+    private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
         if (needWakeLock) {
             mMediaEventWakeLock.acquire();
         }
@@ -3660,6 +3673,140 @@
         }
     }
 
+    /**
+     * The minimum duration during which a user must press to trigger voice-based interactions
+     */
+    private final static int MEDIABUTTON_LONG_PRESS_DURATION_MS = 300;
+    /**
+     * The different states of the state machine to handle the launch of voice-based interactions,
+     * stored in mVoiceButtonState.
+     */
+    private final static int VOICEBUTTON_STATE_IDLE = 0;
+    private final static int VOICEBUTTON_STATE_DOWN = 1;
+    private final static int VOICEBUTTON_STATE_DOWN_IGNORE_NEW = 2;
+    /**
+     * The different actions after state transitions on mVoiceButtonState.
+     */
+    private final static int VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS = 1;
+    private final static int VOICEBUTTON_ACTION_START_VOICE_INPUT = 2;
+    private final static int VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS = 3;
+
+    private final Object mVoiceEventLock = new Object();
+    private int mVoiceButtonState = VOICEBUTTON_STATE_IDLE;
+    private long mVoiceButtonDownTime = 0;
+
+    /**
+     * Log an error when an unexpected action is encountered in the state machine to filter
+     * key events.
+     * @param keyAction the unexpected action of the key event being filtered
+     * @param stateName the string corresponding to the state in which the error occurred
+     */
+    private static void logErrorForKeyAction(int keyAction, String stateName) {
+        Log.e(TAG, "unexpected action "
+                + KeyEvent.actionToString(keyAction)
+                + " in " + stateName + " state");
+    }
+
+    /**
+     * Filter key events that may be used for voice-based interactions
+     * @param keyEvent a non-null KeyEvent whose key code is that of one of the supported
+     *    media buttons that can be used to trigger voice-based interactions.
+     * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
+     *     is dispatched.
+     */
+    private void filterVoiceInputKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
+        int voiceButtonAction = VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS;
+        int keyAction = keyEvent.getAction();
+        synchronized (mVoiceEventLock) {
+            // state machine on mVoiceButtonState
+            switch (mVoiceButtonState) {
+
+                case VOICEBUTTON_STATE_IDLE:
+                    if (keyAction == KeyEvent.ACTION_DOWN) {
+                        mVoiceButtonDownTime = keyEvent.getDownTime();
+                        // valid state transition
+                        mVoiceButtonState = VOICEBUTTON_STATE_DOWN;
+                    } else if (keyAction == KeyEvent.ACTION_UP) {
+                        // no state transition
+                        // action is still VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS
+                    } else {
+                        logErrorForKeyAction(keyAction, "VOICEBUTTON_STATE_IDLE");
+                    }
+                    break;
+
+                case VOICEBUTTON_STATE_DOWN:
+                    if ((keyEvent.getEventTime() - mVoiceButtonDownTime)
+                            >= MEDIABUTTON_LONG_PRESS_DURATION_MS) {
+                        // press was long enough, start voice-based interactions, regardless of
+                        //   whether this was a DOWN or UP key event
+                        voiceButtonAction = VOICEBUTTON_ACTION_START_VOICE_INPUT;
+                        if (keyAction == KeyEvent.ACTION_UP) {
+                            // done tracking the key press, so transition back to idle state
+                            mVoiceButtonState = VOICEBUTTON_STATE_IDLE;
+                        } else if (keyAction == KeyEvent.ACTION_DOWN) {
+                            // no need to observe the upcoming key events
+                            mVoiceButtonState = VOICEBUTTON_STATE_DOWN_IGNORE_NEW;
+                        } else {
+                            logErrorForKeyAction(keyAction, "VOICEBUTTON_STATE_DOWN");
+                        }
+                    } else {
+                        if (keyAction == KeyEvent.ACTION_UP) {
+                            // press wasn't long enough, simulate complete key press
+                            voiceButtonAction = VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS;
+                            // not tracking the key press anymore, so transition back to idle state
+                            mVoiceButtonState = VOICEBUTTON_STATE_IDLE;
+                        } else if (keyAction == KeyEvent.ACTION_DOWN) {
+                            // no state transition
+                            // action is still VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS
+                        } else {
+                            logErrorForKeyAction(keyAction, "VOICEBUTTON_STATE_DOWN");
+                        }
+                    }
+                    break;
+
+                case VOICEBUTTON_STATE_DOWN_IGNORE_NEW:
+                    if (keyAction == KeyEvent.ACTION_UP) {
+                        // done tracking the key press, so transition back to idle state
+                        mVoiceButtonState = VOICEBUTTON_STATE_IDLE;
+                        // action is still VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS
+                    } else if (keyAction == KeyEvent.ACTION_DOWN) {
+                        // no state transition: we've already launched voice-based interactions
+                        // action is still VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS
+                    } else  {
+                        logErrorForKeyAction(keyAction, "VOICEBUTTON_STATE_DOWN_IGNORE_NEW");
+                    }
+                    break;
+            }
+        }//synchronized (mVoiceEventLock)
+
+        // take action after media button event filtering for voice-based interactions
+        switch (voiceButtonAction) {
+            case VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS:
+                if (DEBUG_RC) Log.v(TAG, "   ignore key event");
+                break;
+            case VOICEBUTTON_ACTION_START_VOICE_INPUT:
+                if (DEBUG_RC) Log.v(TAG, "   start voice-based interactions");
+                // then start the voice-based interactions
+                startVoiceBasedInteractions(needWakeLock);
+                break;
+            case VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS:
+                if (DEBUG_RC) Log.v(TAG, "   send simulated key event");
+                sendSimulatedMediaButtonEvent(keyEvent, needWakeLock);
+                break;
+        }
+    }
+
+    private void sendSimulatedMediaButtonEvent(KeyEvent originalKeyEvent, boolean needWakeLock) {
+        // send DOWN event
+        KeyEvent keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_DOWN);
+        dispatchMediaKeyEvent(keyEvent, needWakeLock);
+        // send UP event
+        keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_UP);
+        dispatchMediaKeyEvent(keyEvent, needWakeLock);
+
+    }
+
+
     private static boolean isValidMediaKeyEvent(KeyEvent keyEvent) {
         if (keyEvent == null) {
             return false;
@@ -3686,6 +3833,63 @@
         return true;
     }
 
+    /**
+     * Checks whether the given key code is one that can trigger the launch of voice-based
+     *   interactions.
+     * @param keyCode the key code associated with the key event
+     * @return true if the key is one of the supported voice-based interaction triggers
+     */
+    private static boolean isValidVoiceInputKeyCode(int keyCode) {
+        if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Tell the system to start voice-based interactions / voice commands
+     */
+    private void startVoiceBasedInteractions(boolean needWakeLock) {
+        Intent voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
+        if (needWakeLock) {
+            mMediaEventWakeLock.acquire();
+        }
+        voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+        try {
+            if (mKeyguardManager != null) {
+                // it's ok to start voice-based interactions when:
+                // - the device is locked but doesn't require a password to be unlocked
+                // - the device is not locked
+                if ((mKeyguardManager.isKeyguardLocked() && !mKeyguardManager.isKeyguardSecure())
+                        || !mKeyguardManager.isKeyguardLocked()) {
+                    mContext.startActivity(voiceIntent);
+                }
+            }
+        } catch (ActivityNotFoundException e) {
+            Log.e(TAG, "Error launching activity for ACTION_WEB_SEARCH: " + e);
+        } finally {
+            if (needWakeLock) {
+                mMediaEventWakeLock.release();
+            }
+        }
+    }
+
+    /**
+     * Verify whether it is safe to start voice-based interactions given the state of the system
+     * @return false is the Keyguard is locked and secure, true otherwise
+     */
+    private boolean safeToStartVoiceBasedInteractions() {
+        KeyguardManager keyguard =
+                (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
+        if (keyguard == null) {
+            return false;
+        }
+        
+        return true;
+    }
+
     private PowerManager.WakeLock mMediaEventWakeLock;
 
     private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; //magic number
@@ -3703,7 +3907,14 @@
 
     BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
         public void onReceive(Context context, Intent intent) {
-            if (intent.getExtras().containsKey(EXTRA_WAKELOCK_ACQUIRED)) {
+            if (intent == null) {
+                return;
+            }
+            Bundle extras = intent.getExtras();
+            if (extras == null) {
+                return;
+            }
+            if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)) {
                 mMediaEventWakeLock.release();
             }
         }
diff --git a/packages/SystemUI/res/layout-land/status_bar_recent_panel.xml b/packages/SystemUI/res/layout-land/status_bar_recent_panel.xml
index 869b164..8a21117 100644
--- a/packages/SystemUI/res/layout-land/status_bar_recent_panel.xml
+++ b/packages/SystemUI/res/layout-land/status_bar_recent_panel.xml
@@ -27,12 +27,6 @@
     systemui:recentItemLayout="@layout/status_bar_recent_item"
     >
 
-    <ImageView
-        android:id="@+id/recents_transition_placeholder_icon"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:visibility="invisible" />
-
     <FrameLayout
         android:id="@+id/recents_bg_protect"
         android:background="@drawable/status_bar_recents_background"
@@ -42,6 +36,12 @@
         android:clipToPadding="false"
         android:clipChildren="false">
 
+        <ImageView
+            android:id="@+id/recents_transition_placeholder_icon"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:visibility="invisible" />
+
         <com.android.systemui.recent.RecentsHorizontalScrollView android:id="@+id/recents_container"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
diff --git a/packages/SystemUI/res/layout-land/status_bar_search_panel.xml b/packages/SystemUI/res/layout-land/status_bar_search_panel.xml
index 5d4d989..392a8b5 100644
--- a/packages/SystemUI/res/layout-land/status_bar_search_panel.xml
+++ b/packages/SystemUI/res/layout-land/status_bar_search_panel.xml
@@ -52,7 +52,6 @@
                 prvandroid:directionDescriptions="@array/navbar_search_direction_descriptions"
                 prvandroid:handleDrawable="@drawable/navbar_search_handle"
                 prvandroid:waveDrawable="@drawable/navbar_search_outerring"
-                prvandroid:outerRadius="@dimen/navbar_search_target_placement_radius"
                 prvandroid:snapMargin="@dimen/navbar_search_snap_margin"
                 prvandroid:hitRadius="@dimen/navbar_search_hit_radius"
                 prvandroid:feedbackCount="0"
diff --git a/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml b/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
index fc9fcf4..1d29c5a 100644
--- a/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
+++ b/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
@@ -27,12 +27,6 @@
     systemui:recentItemLayout="@layout/status_bar_recent_item"
     >
 
-    <ImageView
-        android:id="@+id/recents_transition_placeholder_icon"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:visibility="invisible" />
-
     <FrameLayout
         android:id="@+id/recents_bg_protect"
         android:background="@drawable/status_bar_recents_background"
@@ -40,6 +34,12 @@
         android:layout_height="match_parent"
         android:layout_alignParentBottom="true">
 
+        <ImageView
+            android:id="@+id/recents_transition_placeholder_icon"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:visibility="invisible" />
+
         <com.android.systemui.recent.RecentsVerticalScrollView
             android:id="@+id/recents_container"
             android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/layout-port/status_bar_search_panel.xml b/packages/SystemUI/res/layout-port/status_bar_search_panel.xml
index 2486b75..371c575 100644
--- a/packages/SystemUI/res/layout-port/status_bar_search_panel.xml
+++ b/packages/SystemUI/res/layout-port/status_bar_search_panel.xml
@@ -52,7 +52,6 @@
                 prvandroid:directionDescriptions="@array/navbar_search_direction_descriptions"
                 prvandroid:handleDrawable="@drawable/navbar_search_handle"
                 prvandroid:waveDrawable="@drawable/navbar_search_outerring"
-                prvandroid:outerRadius="@dimen/navbar_search_target_placement_radius"
                 prvandroid:snapMargin="@dimen/navbar_search_snap_margin"
                 prvandroid:hitRadius="@dimen/navbar_search_hit_radius"
                 prvandroid:feedbackCount="0"
diff --git a/packages/SystemUI/res/layout-sw600dp/status_bar_search_panel.xml b/packages/SystemUI/res/layout-sw600dp/status_bar_search_panel.xml
index 4b2fbc7..0ccfe95 100644
--- a/packages/SystemUI/res/layout-sw600dp/status_bar_search_panel.xml
+++ b/packages/SystemUI/res/layout-sw600dp/status_bar_search_panel.xml
@@ -61,7 +61,6 @@
                 prvandroid:directionDescriptions="@array/navbar_search_direction_descriptions"
                 prvandroid:handleDrawable="@drawable/navbar_search_handle"
                 prvandroid:waveDrawable="@drawable/navbar_search_outerring"
-                prvandroid:outerRadius="@dimen/navbar_search_target_placement_radius"
                 prvandroid:snapMargin="@dimen/navbar_search_snap_margin"
                 prvandroid:hitRadius="@dimen/navbar_search_hit_radius"
                 prvandroid:feedbackCount="0"
diff --git a/packages/SystemUI/res/layout-sw720dp/status_bar_search_panel.xml b/packages/SystemUI/res/layout-sw720dp/status_bar_search_panel.xml
index ac2472c..0a5390a 100644
--- a/packages/SystemUI/res/layout-sw720dp/status_bar_search_panel.xml
+++ b/packages/SystemUI/res/layout-sw720dp/status_bar_search_panel.xml
@@ -61,7 +61,6 @@
                 prvandroid:directionDescriptions="@array/navbar_search_direction_descriptions"
                 prvandroid:handleDrawable="@drawable/navbar_search_handle"
                 prvandroid:waveDrawable="@drawable/navbar_search_outerring"
-                prvandroid:outerRadius="@dimen/navbar_search_target_placement_radius"
                 prvandroid:snapMargin="@dimen/navbar_search_snap_margin"
                 prvandroid:hitRadius="@dimen/navbar_search_hit_radius"
                 prvandroid:feedbackCount="0"
diff --git a/packages/SystemUI/res/values-sw600dp/dimens.xml b/packages/SystemUI/res/values-sw600dp/dimens.xml
index 2cb99ff..07d55f1 100644
--- a/packages/SystemUI/res/values-sw600dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw600dp/dimens.xml
@@ -27,9 +27,6 @@
     <!-- 0x33 = center_horizontal|top -->
     <integer name="notification_panel_layout_gravity">0x31</integer>
 
-    <!-- Default target placement radius for navigation bar search target -->
-    <dimen name="navbar_search_target_placement_radius">182dip</dimen>
-
     <!-- Diameter of outer shape drawable shown in navbar search-->
     <dimen name="navbar_search_outerring_diameter">364dp</dimen>
 
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 21e5fd7..f548166 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -105,9 +105,6 @@
     <!-- The width of the view containing the menu status bar icon -->
     <dimen name="navigation_menu_key_width">40dip</dimen>
 
-    <!-- Default target placement radius for navigation bar search target -->
-    <dimen name="navbar_search_target_placement_radius">150dip</dimen>
-
     <!-- Default distance beyond which snaps to the target radius -->
     <dimen name="navbar_search_snap_margin">20dip</dimen>
 
diff --git a/packages/SystemUI/src/com/android/systemui/recent/Choreographer.java b/packages/SystemUI/src/com/android/systemui/recent/Choreographer.java
index a8c2020..ccdf038 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/Choreographer.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/Choreographer.java
@@ -102,12 +102,14 @@
             builder.with(noRecentAppsFadeAnim);
         }
 
-        Drawable background = mScrimView.getBackground();
-        if (background != null) {
-            Animator bgAnim = ObjectAnimator.ofInt(background,
-                "alpha", appearing ? 0 : 255, appearing ? 255 : 0);
-            bgAnim.setDuration(appearing ? SCRIM_DURATION : CLOSE_DURATION);
-            builder.with(bgAnim);
+        if (appearing) {
+            Drawable background = mScrimView.getBackground();
+            if (background != null) {
+                Animator bgAnim = ObjectAnimator.ofInt(background,
+                    "alpha", appearing ? 0 : 255, appearing ? 255 : 0);
+                bgAnim.setDuration(appearing ? SCRIM_DURATION : CLOSE_DURATION);
+                builder.with(bgAnim);
+            }
         }
         mContentAnim.addListener(this);
         if (mListener != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
index feb1ac8..6785c29 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
@@ -469,7 +469,7 @@
             Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
                 .getDefaultDisplay();
             if (!ActivityManager.isHighEndGfx(d)) {
-                mRecentsScrim.setBackgroundDrawable(null);
+                mRecentsScrim.setBackground(null);
             } else if (mRecentsScrim.getBackground() instanceof BitmapDrawable) {
                 // In order to save space, we make the background texture repeat in the Y direction
                 ((BitmapDrawable) mRecentsScrim.getBackground()).setTileModeY(TileMode.REPEAT);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index a310b1d..a44279a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -751,6 +751,7 @@
     protected abstract void tick(IBinder key, StatusBarNotification n, boolean firstTime);
     protected abstract void updateExpandedViewPos(int expandedPosition);
     protected abstract int getExpandedViewMaxHeight();
+    protected abstract boolean isStatusBarExpanded();
 
     protected boolean isTopNotification(ViewGroup parent, NotificationData.Entry entry) {
         return parent.indexOfChild(entry.row) == 0;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/DelegateViewHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/DelegateViewHelper.java
index e074a80..912a165 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/DelegateViewHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/DelegateViewHelper.java
@@ -53,6 +53,9 @@
     }
 
     public boolean onInterceptTouchEvent(MotionEvent event) {
+        if (mBar.isStatusBarExpanded()) {
+            return false;
+        }
         switch (event.getAction()) {
             case MotionEvent.ACTION_DOWN:
                 mDownPoint[0] = event.getX();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index d3fbdab..6122390 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -2109,5 +2109,10 @@
     protected void haltTicker() {
         mTicker.halt();
     }
+
+    @Override
+    protected boolean isStatusBarExpanded() {
+        return mExpanded;
+    }
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessController.java
index 72fdfad..3ba36af 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessController.java
@@ -31,8 +31,8 @@
 public class BrightnessController implements ToggleSlider.Listener {
     private static final String TAG = "StatusBar.BrightnessController";
 
-    private static final int MINIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_DIM;
-    private static final int MAXIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_ON;
+    private static final int MINIMUM_BACKLIGHT = android.os.PowerManager.BRIGHTNESS_DIM;
+    private static final int MAXIMUM_BACKLIGHT = android.os.PowerManager.BRIGHTNESS_ON;
 
     private Context mContext;
     private ToggleSlider mControl;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
index 906d1aa..a2c7637 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
@@ -1618,6 +1618,11 @@
     @Override
     protected void updateExpandedViewPos(int expandedPosition) {
     }
+
+    @Override
+    protected boolean isStatusBarExpanded() {
+        return mNotificationPanel.getVisibility() == View.VISIBLE;
+    }
 }
 
 
diff --git a/policy/src/com/android/internal/policy/impl/GlobalActions.java b/policy/src/com/android/internal/policy/impl/GlobalActions.java
index 3fa79b6..aa73de4 100644
--- a/policy/src/com/android/internal/policy/impl/GlobalActions.java
+++ b/policy/src/com/android/internal/policy/impl/GlobalActions.java
@@ -16,14 +16,12 @@
 
 package com.android.internal.policy.impl;
 
-import com.android.internal.app.ShutdownThread;
 import com.android.internal.telephony.TelephonyIntents;
 import com.android.internal.telephony.TelephonyProperties;
 import com.android.internal.R;
 
 import android.app.ActivityManagerNative;
 import android.app.AlertDialog;
-import android.app.admin.DevicePolicyManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -48,6 +46,7 @@
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.WindowManager;
+import android.view.WindowManagerPolicy.WindowManagerFuncs;
 import android.widget.AdapterView;
 import android.widget.BaseAdapter;
 import android.widget.ImageView;
@@ -68,6 +67,7 @@
     private static final boolean SHOW_SILENT_TOGGLE = true;
 
     private final Context mContext;
+    private final WindowManagerFuncs mWindowManagerFuncs;
     private final AudioManager mAudioManager;
 
     private ArrayList<Action> mItems;
@@ -88,8 +88,9 @@
     /**
      * @param context everything needs a context :(
      */
-    public GlobalActions(Context context) {
+    public GlobalActions(Context context, WindowManagerFuncs windowManagerFuncs) {
         mContext = context;
+        mWindowManagerFuncs = windowManagerFuncs;
         mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
 
         // receive broadcasts
@@ -186,11 +187,11 @@
 
                 public void onPress() {
                     // shutdown by making sure radio and power are handled accordingly.
-                    ShutdownThread.shutdown(mContext, true);
+                    mWindowManagerFuncs.shutdown();
                 }
 
                 public boolean onLongPress() {
-                    ShutdownThread.rebootSafeMode(mContext, true);
+                    mWindowManagerFuncs.rebootSafeMode();
                     return true;
                 }
 
diff --git a/policy/src/com/android/internal/policy/impl/LockScreen.java b/policy/src/com/android/internal/policy/impl/LockScreen.java
index f34f9a9..8ea334e 100644
--- a/policy/src/com/android/internal/policy/impl/LockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/LockScreen.java
@@ -129,6 +129,9 @@
 
         // Get the target position for the given resource. Returns -1 if not found.
         public int getTargetPosition(int resourceId);
+
+        // Clean up when this widget is going away
+        public void cleanUp();
     }
 
     class SlidingTabMethods implements SlidingTab.OnTriggerListener, UnlockWidgetCommonMethods {
@@ -197,6 +200,10 @@
         public int getTargetPosition(int resourceId) {
             return -1; // Not supported
         }
+
+        public void cleanUp() {
+            mSlidingTab.setOnTriggerListener(null);
+        }
     }
 
     class WaveViewMethods implements WaveView.OnTriggerListener, UnlockWidgetCommonMethods {
@@ -240,6 +247,9 @@
         public int getTargetPosition(int resourceId) {
             return -1; // Not supported
         }
+        public void cleanUp() {
+            mWaveView.setOnTriggerListener(null);
+        }
     }
 
     private Intent getAssistIntent() {
@@ -374,6 +384,10 @@
         public int getTargetPosition(int resourceId) {
             return mMultiWaveView.getTargetPosition(resourceId);
         }
+
+        public void cleanUp() {
+            mMultiWaveView.setOnTriggerListener(null);
+        }
     }
 
     private void requestUnlockScreen() {
@@ -592,6 +606,7 @@
     public void cleanUp() {
         mUpdateMonitor.removeCallback(mInfoCallback); // this must be first
         mUpdateMonitor.removeCallback(mSimStateCallback);
+        mUnlockWidgetMethods.cleanUp();
         mLockPatternUtils = null;
         mUpdateMonitor = null;
         mCallback = null;
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 794ed15..3147ba7 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -15,7 +15,6 @@
 
 package com.android.internal.policy.impl;
 
-import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.ActivityManagerNative;
 import android.app.IUiModeManager;
@@ -37,8 +36,6 @@
 import android.database.ContentObserver;
 import android.graphics.PixelFormat;
 import android.graphics.Rect;
-import android.graphics.RectF;
-import android.hardware.input.InputManager;
 import android.media.AudioManager;
 import android.media.IAudioService;
 import android.os.BatteryManager;
@@ -60,7 +57,6 @@
 import android.provider.Settings;
 
 import com.android.internal.R;
-import com.android.internal.app.ShutdownThread;
 import com.android.internal.policy.PolicyManager;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.telephony.ITelephony;
@@ -149,7 +145,6 @@
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.util.ArrayList;
 
 /**
  * WindowManagerPolicy implementation for the Android phone UI.  This
@@ -248,8 +243,6 @@
     static final int SYSTEM_UI_CHANGING_LAYOUT =
             View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
 
-    private static final int BTN_MOUSE = 0x110;
-
     /* Table of Application Launch keys.  Maps from key codes to intent categories.
      *
      * These are special keys that are used to launch particular kinds of applications,
@@ -448,7 +441,6 @@
 
     static final Rect mTmpParentFrame = new Rect();
     static final Rect mTmpDisplayFrame = new Rect();
-    static final Rect mTmpSystemFrame = new Rect();
     static final Rect mTmpContentFrame = new Rect();
     static final Rect mTmpVisibleFrame = new Rect();
     static final Rect mTmpNavigationFrame = new Rect();
@@ -727,7 +719,7 @@
                 mPowerKeyHandled = true;
                 performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
                 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
-                ShutdownThread.shutdown(mContext, true);
+                mWindowManagerFuncs.shutdown();
                 break;
             }
         }
@@ -741,7 +733,7 @@
 
     void showGlobalActionsDialog() {
         if (mGlobalActions == null) {
-            mGlobalActions = new GlobalActions(mContext);
+            mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
         }
         final boolean keyguardShowing = keyguardIsShowingTq();
         mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
@@ -2302,7 +2294,7 @@
             mStatusBarLayer = mNavigationBar.getSurfaceLayer();
             // And compute the final frame.
             mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
-                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame);
+                    mTmpNavigationFrame, mTmpNavigationFrame);
             if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
         }
         if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
@@ -2323,7 +2315,7 @@
             mStatusBarLayer = mStatusBar.getSurfaceLayer();
 
             // Let the status bar determine its size.
-            mStatusBar.computeFrameLw(pf, df, df, vf, vf);
+            mStatusBar.computeFrameLw(pf, df, vf, vf);
 
             // For layout, the status bar is always at the top with our fixed height.
             mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
@@ -2357,6 +2349,17 @@
         }
     }
 
+    /** {@inheritDoc} */
+    public int getSystemDecorRectLw(Rect systemRect) {
+        systemRect.left = mSystemLeft;
+        systemRect.top = mSystemTop;
+        systemRect.right = mSystemRight;
+        systemRect.bottom = mSystemBottom;
+        if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
+        if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
+        return 0;
+    }
+
     void setAttachedWindowFrames(WindowState win, int fl, int adjust,
             WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
         if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
@@ -2427,7 +2430,6 @@
 
         final Rect pf = mTmpParentFrame;
         final Rect df = mTmpDisplayFrame;
-        final Rect sf = mTmpSystemFrame;
         final Rect cf = mTmpContentFrame;
         final Rect vf = mTmpVisibleFrame;
         
@@ -2671,20 +2673,6 @@
             df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
         }
 
-        // Compute the system frame.  This is easy: for things behind the
-        // status bar, it is any application windows; otherwise it is not set.
-        int parentType = attached != null ? attached.getAttrs().type : attrs.type;
-        if (win.getSurfaceLayer() < mStatusBarLayer
-                && parentType < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) {
-            sf.left = mSystemLeft;
-            sf.top = mSystemTop;
-            sf.right = mSystemRight;
-            sf.bottom = mSystemBottom;
-        } else {
-            sf.left = sf.top = -10000;
-            sf.right = sf.bottom = 10000;
-        }
-
         if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
                 + ": sim=#" + Integer.toHexString(sim)
                 + " attach=" + attached + " type=" + attrs.type 
@@ -2692,7 +2680,7 @@
                 + " pf=" + pf.toShortString() + " df=" + df.toShortString()
                 + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
         
-        win.computeFrameLw(pf, df, sf, cf, vf);
+        win.computeFrameLw(pf, df, cf, vf);
         
         // Dock windows carve out the bottom of the screen, so normal windows
         // can't appear underneath them.
diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index 289ab2a..2cc2704 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -17,8 +17,8 @@
 package com.android.server;
 
 import com.android.internal.app.IBatteryStats;
-import com.android.internal.app.ShutdownThread;
 import com.android.server.am.BatteryStatsService;
+import com.android.server.pm.ShutdownThread;
 
 import android.app.ActivityManagerNative;
 import android.app.IActivityManager;
@@ -47,7 +47,6 @@
 import android.os.IPowerManager;
 import android.os.LocalPowerManager;
 import android.os.Message;
-import android.os.Power;
 import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteException;
@@ -71,6 +70,7 @@
 import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
 
 import java.io.FileDescriptor;
+import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -84,6 +84,12 @@
     private static final String TAG = "PowerManagerService";
     static final String PARTIAL_NAME = "PowerManagerService";
 
+    // Wake lock that ensures that the CPU is running.  The screen might not be on.
+    private static final int PARTIAL_WAKE_LOCK_ID = 1;
+
+    // Wake lock that ensures that the screen is on.
+    private static final int FULL_WAKE_LOCK_ID = 2;
+
     static final boolean DEBUG_SCREEN_ON = false;
 
     private static final boolean LOG_PARTIAL_WL = false;
@@ -134,6 +140,10 @@
     // Screen brightness should always have a value, but just in case...
     private static final int DEFAULT_SCREEN_BRIGHTNESS = 192;
 
+    // Threshold for BRIGHTNESS_LOW_BATTERY (percentage)
+    // Screen will stay dim if battery level is <= LOW_BATTERY_THRESHOLD
+    private static final int LOW_BATTERY_THRESHOLD = 10;
+
     // flags for setPowerState
     private static final int ALL_LIGHTS_OFF         = 0x00000000;
     private static final int SCREEN_ON_BIT          = 0x00000001;
@@ -175,8 +185,8 @@
     // we should read them from the driver, but our current hardware returns 0
     // for the initial value.  Oops!
     static final int INITIAL_SCREEN_BRIGHTNESS = 255;
-    static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
-    static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
+    static final int INITIAL_BUTTON_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF;
+    static final int INITIAL_KEYBOARD_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF;
 
     private final int MY_UID;
     private final int MY_PID;
@@ -296,6 +306,11 @@
     private native void nativeInit();
     private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
     private native void nativeStartSurfaceFlingerAnimation(int mode);
+    private static native void nativeAcquireWakeLock(int lock, String id);
+    private static native void nativeReleaseWakeLock(String id);
+    private static native int nativeSetScreenState(boolean on);
+    private static native void nativeShutdown();
+    private static native void nativeReboot(String reason) throws IOException;
 
     /*
     static PrintStream mLog;
@@ -515,14 +530,13 @@
         MY_PID = Process.myPid();
         Binder.restoreCallingIdentity(token);
 
-        // XXX remove this when the kernel doesn't timeout wake locks
-        Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
-
         // assume nothing is on yet
         mUserState = mPowerState = 0;
 
         // Add ourself to the Watchdog monitors.
         Watchdog.getInstance().addMonitor(this);
+
+        nativeInit();
     }
 
     private ContentQueryMap mSettings;
@@ -541,11 +555,6 @@
         mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
         mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
 
-        nativeInit();
-        synchronized (mLocks) {
-            updateNativePowerStateLocked();
-        }
-
         mInitComplete = false;
         mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread",
                 Process.THREAD_PRIORITY_DISPLAY);
@@ -581,8 +590,6 @@
             }
         }
 
-        nativeInit();
-        Power.powerInitNative();
         synchronized (mLocks) {
             updateNativePowerStateLocked();
             // We make sure to start out with the screen on due to user activity.
@@ -686,6 +693,26 @@
         }
     }
 
+    /**
+     * Low-level function turn the device off immediately, without trying
+     * to be clean.  Most people should use
+     * {@link com.android.server.pm.internal.app.ShutdownThread} for a clean shutdown.
+     */
+    public static void lowLevelShutdown() {
+        nativeShutdown();
+    }
+
+    /**
+     * Low-level function to reboot the device.
+     *
+     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
+     * @throws IOException if reboot fails for some reason (eg, lack of
+     *         permission)
+     */
+    public static void lowLevelReboot(String reason) throws IOException {
+        nativeReboot(reason);
+    }
+
     private class WakeLock implements IBinder.DeathRecipient
     {
         WakeLock(int f, IBinder b, String t, int u, int p) {
@@ -926,7 +953,7 @@
                     if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
                 }
             }
-            Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
+            nativeAcquireWakeLock(PARTIAL_WAKE_LOCK_ID, PARTIAL_NAME);
         }
 
         if (diffsource) {
@@ -1010,7 +1037,7 @@
             mPartialCount--;
             if (mPartialCount == 0) {
                 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
-                Power.releaseWakeLock(PARTIAL_NAME);
+                nativeReleaseWakeLock(PARTIAL_NAME);
             }
         }
         // Unlink the lock from the binder.
@@ -1719,10 +1746,10 @@
                             + " mSkippedScreenOn=" + mSkippedScreenOn);
                 }
                 mScreenBrightnessHandler.removeMessages(ScreenBrightnessAnimator.ANIMATE_LIGHTS);
-                mScreenBrightnessAnimator.animateTo(Power.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
+                mScreenBrightnessAnimator.animateTo(PowerManager.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
             }
         }
-        int err = Power.setScreenState(on);
+        int err = nativeSetScreenState(on);
         if (err == 0) {
             mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
             if (mUseSoftwareAutoBrightness) {
@@ -1934,7 +1961,7 @@
 
     private boolean batteryIsLow() {
         return (!mIsPowered &&
-                mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
+                mBatteryService.getBatteryLevel() <= LOW_BATTERY_THRESHOLD);
     }
 
     private boolean shouldDeferScreenOnLocked() {
@@ -2024,7 +2051,7 @@
                         nominalCurrentValue = mScreenBrightnessDim;
                         break;
                     case 0:
-                        nominalCurrentValue = Power.BRIGHTNESS_OFF;
+                        nominalCurrentValue = PowerManager.BRIGHTNESS_OFF;
                         break;
                     case SCREEN_BRIGHT_BIT:
                     default:
@@ -2050,7 +2077,7 @@
                         // was dim
                         steps = (int)(ANIM_STEPS*ratio*scale);
                     }
-                    brightness = Power.BRIGHTNESS_OFF;
+                    brightness = PowerManager.BRIGHTNESS_OFF;
                 } else {
                     if ((oldState & SCREEN_ON_BIT) != 0) {
                         // was bright
@@ -2101,13 +2128,13 @@
 
         if (offMask != 0) {
             if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
-            setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
+            setLightBrightness(offMask, PowerManager.BRIGHTNESS_OFF);
         }
         if (dimMask != 0) {
             int brightness = mScreenBrightnessDim;
             if ((newState & BATTERY_LOW_BIT) != 0 &&
-                    brightness > Power.BRIGHTNESS_LOW_BATTERY) {
-                brightness = Power.BRIGHTNESS_LOW_BATTERY;
+                    brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) {
+                brightness = PowerManager.BRIGHTNESS_LOW_BATTERY;
             }
             if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
             setLightBrightness(dimMask, brightness);
@@ -2115,8 +2142,8 @@
         if (onMask != 0) {
             int brightness = getPreferredBrightness();
             if ((newState & BATTERY_LOW_BIT) != 0 &&
-                    brightness > Power.BRIGHTNESS_LOW_BATTERY) {
-                brightness = Power.BRIGHTNESS_LOW_BATTERY;
+                    brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) {
+                brightness = PowerManager.BRIGHTNESS_LOW_BATTERY;
             }
             if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
             setLightBrightness(onMask, brightness);
@@ -2198,8 +2225,8 @@
                     if (elapsed < duration) {
                         int delta = endValue - startValue;
                         newValue = startValue + delta * elapsed / duration;
-                        newValue = Math.max(Power.BRIGHTNESS_OFF, newValue);
-                        newValue = Math.min(Power.BRIGHTNESS_ON, newValue);
+                        newValue = Math.max(PowerManager.BRIGHTNESS_OFF, newValue);
+                        newValue = Math.min(PowerManager.BRIGHTNESS_ON, newValue);
                     } else {
                         newValue = endValue;
                         mInitialAnimation = false;
@@ -2249,7 +2276,7 @@
 
                 if (target != currentValue) {
                     final boolean doScreenAnim = (mask & (SCREEN_BRIGHT_BIT | SCREEN_ON_BIT)) != 0;
-                    final boolean turningOff = endValue == Power.BRIGHTNESS_OFF;
+                    final boolean turningOff = endValue == PowerManager.BRIGHTNESS_OFF;
                     if (turningOff && doScreenAnim) {
                         // Cancel all pending animations since we're turning off
                         mScreenBrightnessHandler.removeCallbacksAndMessages(null);
@@ -2353,7 +2380,7 @@
 
     private boolean isScreenTurningOffLocked() {
         return (mScreenBrightnessAnimator.isAnimating()
-                && mScreenBrightnessAnimator.endValue == Power.BRIGHTNESS_OFF);
+                && mScreenBrightnessAnimator.endValue == PowerManager.BRIGHTNESS_OFF);
     }
 
     private boolean shouldLog(long time) {
diff --git a/services/java/com/android/server/ShutdownActivity.java b/services/java/com/android/server/ShutdownActivity.java
index c9d4d01..d85abe6 100644
--- a/services/java/com/android/server/ShutdownActivity.java
+++ b/services/java/com/android/server/ShutdownActivity.java
@@ -22,7 +22,8 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.util.Slog;
-import com.android.internal.app.ShutdownThread;
+
+import com.android.server.pm.ShutdownThread;
 
 public class ShutdownActivity extends Activity {
 
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 849281d..d9833ab 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -46,7 +46,6 @@
 import android.util.Slog;
 import android.view.WindowManager;
 
-import com.android.internal.app.ShutdownThread;
 import com.android.internal.os.BinderInternal;
 import com.android.internal.os.SamplingProfilerIntegration;
 import com.android.internal.widget.LockSettingsService;
@@ -56,6 +55,7 @@
 import com.android.server.net.NetworkPolicyManagerService;
 import com.android.server.net.NetworkStatsService;
 import com.android.server.pm.PackageManagerService;
+import com.android.server.pm.ShutdownThread;
 import com.android.server.usb.UsbService;
 import com.android.server.wm.WindowManagerService;
 
diff --git a/services/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/java/com/android/server/accessibility/AccessibilityManagerService.java
index 0c6d85d..28ce1df 100644
--- a/services/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -23,7 +23,6 @@
 import android.accessibilityservice.AccessibilityService;
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.accessibilityservice.IAccessibilityServiceClient;
-import android.accessibilityservice.IAccessibilityServiceClientCallback;
 import android.accessibilityservice.IAccessibilityServiceConnection;
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
@@ -44,7 +43,6 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
-import android.os.Looper;
 import android.os.Message;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -58,9 +56,7 @@
 import android.view.InputDevice;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
-import android.view.View;
 import android.view.accessibility.AccessibilityEvent;
-import android.view.accessibility.AccessibilityInteractionClient;
 import android.view.accessibility.AccessibilityManager;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.accessibility.IAccessibilityInteractionConnection;
@@ -69,8 +65,6 @@
 import android.view.accessibility.IAccessibilityManagerClient;
 
 import com.android.internal.content.PackageMonitor;
-import com.android.internal.os.HandlerCaller;
-import com.android.internal.os.HandlerCaller.Callback;
 import com.android.server.accessibility.TouchExplorer.GestureListener;
 import com.android.server.wm.WindowManagerService;
 
@@ -85,7 +79,6 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * This class is instantiated by the system as a system level service and can be
@@ -107,8 +100,6 @@
 
     private static final int OWN_PROCESS_ID = android.os.Process.myPid();
 
-    private static final int UNDEFINED = -1;
-
     private static int sIdCounter = 0;
 
     private static int sNextWindowId;
@@ -155,10 +146,6 @@
 
     private Service mUiAutomationService;
 
-    private GestureHandler mGestureHandler;
-
-    private int mDefaultGestureHandlingHelperServiceId = UNDEFINED;
-
     /**
      * Handler for delayed event dispatch.
      */
@@ -416,7 +403,6 @@
             IAccessibilityInteractionConnection connection) throws RemoteException {
         synchronized (mLock) {
             final IWindow addedWindowToken = windowToken;
-            final IAccessibilityInteractionConnection addedConnection = connection;
             final int windowId = sNextWindowId++;
             AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper(windowId,
                     connection);
@@ -486,44 +472,15 @@
 
     @Override
     public boolean onGesture(int gestureId) {
-        // Lazily instantiate the gesture handler.
-        if (mGestureHandler == null) {
-            mGestureHandler = new GestureHandler();
-        }
         synchronized (mLock) {
             boolean handled = notifyGestureLocked(gestureId, false);
             if (!handled) {
                 handled = notifyGestureLocked(gestureId, true);
             }
-            if (!handled) {
-                mGestureHandler.scheduleHandleGestureDefault(gestureId);
-            }
             return handled;
         }
     }
 
-    private Service getDefaultGestureHandlingHelperService() {
-        // Since querying of screen content is done through the
-        // AccessibilityInteractionClient which talks to an
-        // IAccessibilityServiceConnection implementation we create a proxy
-        // Service when necessary to enable interaction with the remote
-        // view tree. Note that this service is just a stateless proxy
-        // that does not get any events or interrupts.
-        if (mDefaultGestureHandlingHelperServiceId == UNDEFINED) {
-            ComponentName name = new ComponentName("android",
-                    "DefaultGestureHandlingHelperService");
-            AccessibilityServiceInfo info = new AccessibilityServiceInfo();
-            Service service = new Service(name, info, true);
-            mDefaultGestureHandlingHelperServiceId = service.mId;
-            AccessibilityInteractionClient.getInstance().addConnection(
-                    mDefaultGestureHandlingHelperServiceId, service);
-            return service;
-        } else {
-            return (Service) AccessibilityInteractionClient.getInstance()
-                .getConnection(mDefaultGestureHandlingHelperServiceId);
-        }
-    }
-
     private boolean notifyGestureLocked(int gestureId, boolean isDefault) {
         // TODO: Now we are giving the gestures to the last enabled
         //       service that can handle them which is the last one
@@ -537,7 +494,12 @@
         for (int i = mServices.size() - 1; i >= 0; i--) {
             Service service = mServices.get(i);
             if (service.mReqeustTouchExplorationMode && service.mIsDefault == isDefault) {
-                mGestureHandler.scheduleHandleGesture(gestureId, service.mServiceInterface);
+                try {
+                    service.mServiceInterface.onGesture(gestureId);
+                } catch (RemoteException re) {
+                    Slog.e(LOG_TAG, "Error during sending gesture " + gestureId
+                            + " to " + service.mService, re);
+                }
                 return true;
             }
         }
@@ -983,212 +945,6 @@
         }
     }
 
-    class GestureHandler extends IAccessibilityServiceClientCallback.Stub
-            implements Runnable, Callback {
-
-        private static final String THREAD_NAME = "AccessibilityGestureHandler";
-
-        private static final long TIMEOUT_INTERACTION_MILLIS = 5000;
-
-        private static final int MSG_HANDLE_GESTURE = 1;
-
-        private static final int MSG_HANDLE_GESTURE_DEFAULT = 2;
-
-        private final AtomicInteger mInteractionCounter = new AtomicInteger();
-
-        private final Object mGestureLock = new Object();
-
-        private HandlerCaller mHandlerCaller;
-
-        private volatile int mInteractionId = -1;
-
-        private volatile boolean mGestureResult;
-
-        public GestureHandler() {
-            synchronized (mGestureLock) {
-                Thread worker = new Thread(this, THREAD_NAME);
-                worker.start();
-                while (mHandlerCaller == null) {
-                    try {
-                        mGestureLock.wait();
-                    } catch (InterruptedException ie) {
-                        /*  ignore */
-                    }
-                }
-            }
-        }
-
-        @Override
-        public void run() {
-            Looper.prepare();
-            synchronized (mGestureLock) {
-                mHandlerCaller = new HandlerCaller(mContext, Looper.myLooper(), this);
-                mGestureLock.notifyAll();
-            }
-            Looper.loop();
-        }
-
-        @Override
-        public void setGestureResult(int gestureId, boolean handled, int interactionId) {
-            synchronized (mGestureLock) {
-                if (interactionId > mInteractionId) {
-                    mGestureResult = handled;
-                    mInteractionId = interactionId;
-                }
-                mGestureLock.notifyAll();
-            }
-        }
-
-        @Override
-        public void executeMessage(Message message) {
-            final int type = message.what;
-            switch (type) {
-                case MSG_HANDLE_GESTURE: {
-                    IAccessibilityServiceClient service =
-                        (IAccessibilityServiceClient) message.obj;
-                    final int gestureId = message.arg1;
-                    final int interactionId = message.arg2;
-
-                    try {
-                        service.onGesture(gestureId, this, interactionId);
-                    } catch (RemoteException re) {
-                        Slog.e(LOG_TAG, "Error dispatching a gesture to a client.", re);
-                        return;
-                    }
-
-                    long waitTimeMillis = 0;
-                    final long startTimeMillis = SystemClock.uptimeMillis();
-                    synchronized (mGestureLock) {
-                        while (true) {
-                            try {
-                                // Did we get the expected callback?
-                                if (mInteractionId == interactionId) {
-                                    break;
-                                }
-                                // Did we get an obsolete callback?
-                                if (mInteractionId > interactionId) {
-                                    break;
-                                }
-                                // Did we time out?
-                                final long elapsedTimeMillis =
-                                    SystemClock.uptimeMillis() - startTimeMillis;
-                                waitTimeMillis = TIMEOUT_INTERACTION_MILLIS - elapsedTimeMillis;
-                                if (waitTimeMillis <= 0) {
-                                    break;
-                                }
-                                mGestureLock.wait(waitTimeMillis);
-                            } catch (InterruptedException ie) {
-                                /* ignore */
-                            }
-                        }
-                        handleGestureIfNeededAndResetLocked(gestureId);
-                    }
-                } break;
-                case MSG_HANDLE_GESTURE_DEFAULT: {
-                    final int gestureId = message.arg1;
-                    handleGestureDefault(gestureId);
-                } break;
-                default: {
-                    throw new IllegalArgumentException("Unknown message type: " + type);
-                }
-            }
-        }
-
-        private void handleGestureIfNeededAndResetLocked(int gestureId) {
-            if (!mGestureResult) {
-                handleGestureDefault(gestureId);
-            }
-            mGestureResult = false;
-            mInteractionId = -1;
-        }
-
-        public void scheduleHandleGesture(int gestureId, IAccessibilityServiceClient service) {
-            final int interactionId = mInteractionCounter.incrementAndGet();
-            mHandlerCaller.obtainMessageIIO(MSG_HANDLE_GESTURE, gestureId, interactionId,
-                    service).sendToTarget();
-        }
-
-        public void scheduleHandleGestureDefault(int gestureId) {
-            final int interactionId = mInteractionCounter.incrementAndGet();
-            mHandlerCaller.obtainMessageI(MSG_HANDLE_GESTURE_DEFAULT, gestureId).sendToTarget();
-        }
-
-        private void handleGestureDefault(int gestureId) {
-            Service service = getDefaultGestureHandlingHelperService();
-
-            // Global actions.
-            switch (gestureId) {
-                case AccessibilityService.GESTURE_SWIPE_DOWN_AND_LEFT: {
-                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
-                } return;
-                case AccessibilityService.GESTURE_SWIPE_DOWN_AND_RIGHT: {
-                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
-                } return;
-                case AccessibilityService.GESTURE_SWIPE_UP_AND_LEFT: {
-                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
-                } return;
-                case AccessibilityService.GESTURE_SWIPE_UP_AND_RIGHT: {
-                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS);
-                } return;
-            }
-
-            AccessibilityInteractionClient client = AccessibilityInteractionClient.getInstance();
-
-            AccessibilityNodeInfo root = client.getRootInActiveWindow(service.mId);
-            if (root == null) {
-                return;
-            }
-
-            AccessibilityNodeInfo current = root.findFocus(
-                    AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
-            if (current == null) {
-                current = root;
-            }
-
-            // Local actions.
-            AccessibilityNodeInfo next = null;
-            switch (gestureId) {
-                case AccessibilityService.GESTURE_SWIPE_UP: {
-                    // TODO:
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_DOWN: {
-                    // TODO:
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_LEFT: {
-                    // TODO: Implement the RTL support.
-//                     if (mLayoutDirection == View.LAYOUT_DIRECTION_LTR) {
-                        next = current.focusSearch(View.ACCESSIBILITY_FOCUS_BACKWARD);
-//                     } else { // LAYOUT_DIRECTION_RTL
-//                        next = current.focusSearch(View.ACCESSIBILITY_FOCUS_FORWARD);
-//                     }
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_RIGHT: {
-                    // TODO: Implement the RTL support.
-//                    if (mLayoutDirection == View.LAYOUT_DIRECTION_LTR) {
-                        next = current.focusSearch(View.ACCESSIBILITY_FOCUS_FORWARD);
-//                    } else { // LAYOUT_DIRECTION_RTL
-//                        next = current.focusSearch(View.ACCESSIBILITY_FOCUS_BACKWARD);
-//                    }
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_UP_AND_DOWN: {
-                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_UP);
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_DOWN_AND_UP: {
-                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_DOWN);
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_LEFT_AND_RIGHT: {
-                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_LEFT);
-                } break;
-                case AccessibilityService.GESTURE_SWIPE_RIGHT_AND_LEFT: {
-                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_RIGHT);
-                } break;
-            }
-            if (next != null && !next.equals(current)) {
-                next.performAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
-            }
-        }
-    }
-
     /**
      * This class represents an accessibility service. It stores all per service
      * data required for the service management, provides API for starting/stopping the
@@ -1268,10 +1024,7 @@
             mIsDefault = (info.flags & DEFAULT) != 0;
 
             if (mIsAutomation || info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion
-                    // TODO: Uncomment this line and remove the line below when JellyBean
-                    // SDK version is finalized.
-                    // >= Build.VERSION_CODES.JELLY_BEAN) {
-                    > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
+                    >= Build.VERSION_CODES.JELLY_BEAN) {
                 mIncludeNotImportantViews =
                     (info.flags & FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0;
             }
diff --git a/core/java/com/android/internal/app/ShutdownThread.java b/services/java/com/android/server/pm/ShutdownThread.java
similarity index 98%
rename from core/java/com/android/internal/app/ShutdownThread.java
rename to services/java/com/android/server/pm/ShutdownThread.java
index d867ff9..1d6e068 100644
--- a/core/java/com/android/internal/app/ShutdownThread.java
+++ b/services/java/com/android/server/pm/ShutdownThread.java
@@ -15,7 +15,7 @@
  */
 
  
-package com.android.internal.app;
+package com.android.server.pm;
 
 import android.app.ActivityManagerNative;
 import android.app.AlertDialog;
@@ -32,7 +32,6 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Handler;
-import android.os.Power;
 import android.os.PowerManager;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -44,6 +43,8 @@
 import android.os.storage.IMountShutdownObserver;
 
 import com.android.internal.telephony.ITelephony;
+import com.android.server.PowerManagerService;
+
 import android.util.Log;
 import android.view.WindowManager;
 
@@ -456,7 +457,7 @@
         if (reboot) {
             Log.i(TAG, "Rebooting, reason: " + reason);
             try {
-                Power.reboot(reason);
+                PowerManagerService.lowLevelReboot(reason);
             } catch (Exception e) {
                 Log.e(TAG, "Reboot failed, will attempt shutdown instead", e);
             }
@@ -479,6 +480,6 @@
 
         // Shutdown power
         Log.i(TAG, "Performing low-level shutdown...");
-        Power.shutdown();
+        PowerManagerService.lowLevelShutdown();
     }
 }
diff --git a/services/java/com/android/server/wm/Session.java b/services/java/com/android/server/wm/Session.java
index 53c0e07..61c0e9c 100644
--- a/services/java/com/android/server/wm/Session.java
+++ b/services/java/com/android/server/wm/Session.java
@@ -151,13 +151,13 @@
 
     public int relayout(IWindow window, int seq, WindowManager.LayoutParams attrs,
             int requestedWidth, int requestedHeight, int viewFlags,
-            int flags, Rect outFrame, Rect outSystemInsets, Rect outContentInsets,
+            int flags, Rect outFrame, Rect outContentInsets,
             Rect outVisibleInsets, Configuration outConfig, Surface outSurface) {
         if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED relayout from "
                 + Binder.getCallingPid());
         int res = mService.relayoutWindow(this, window, seq, attrs,
                 requestedWidth, requestedHeight, viewFlags, flags,
-                outFrame, outSystemInsets, outContentInsets, outVisibleInsets,
+                outFrame, outContentInsets, outVisibleInsets,
                 outConfig, outSurface);
         if (false) Slog.d(WindowManagerService.TAG, "<<<<<< EXITING relayout to "
                 + Binder.getCallingPid());
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 2efcb8e..b3ac6f1 100755
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -34,7 +34,6 @@
 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
 
 import com.android.internal.app.IBatteryStats;
-import com.android.internal.app.ShutdownThread;
 import com.android.internal.policy.PolicyManager;
 import com.android.internal.policy.impl.PhoneWindowManager;
 import com.android.internal.view.IInputContext;
@@ -48,6 +47,7 @@
 import com.android.server.am.BatteryStatsService;
 import com.android.server.input.InputFilter;
 import com.android.server.input.InputManagerService;
+import com.android.server.pm.ShutdownThread;
 
 import android.Manifest;
 import android.app.ActivityManagerNative;
@@ -82,7 +82,6 @@
 import android.os.Message;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
-import android.os.Power;
 import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteException;
@@ -480,6 +479,9 @@
             = new ArrayList<IRotationWatcher>();
     int mDeferredRotationPauseCount;
 
+    final Rect mSystemDecorRect = new Rect();
+    int mSystemDecorLayer = 0;
+
     int mPendingLayoutChanges = 0;
     boolean mLayoutNeeded = true;
     boolean mTraversalScheduled = false;
@@ -2647,7 +2649,7 @@
     public int relayoutWindow(Session session, IWindow client, int seq,
             WindowManager.LayoutParams attrs, int requestedWidth,
             int requestedHeight, int viewVisibility, int flags,
-            Rect outFrame, Rect outSystemInsets, Rect outContentInsets,
+            Rect outFrame, Rect outContentInsets,
             Rect outVisibleInsets, Configuration outConfig, Surface outSurface) {
         boolean displayed = false;
         boolean inTouchMode;
@@ -2939,7 +2941,6 @@
                 win.mAppToken.updateReportedVisibilityLocked();
             }
             outFrame.set(win.mCompatFrame);
-            outSystemInsets.set(win.mSystemInsets);
             outContentInsets.set(win.mContentInsets);
             outVisibleInsets.set(win.mVisibleInsets);
             if (localLOGV) Slog.v(
@@ -3222,28 +3223,23 @@
             // Entering app zooms out from the center of the thumbnail.
             float scaleW = thumbWidth / mAppDisplayWidth;
             float scaleH = thumbHeight / mAppDisplayHeight;
-            AnimationSet set = new AnimationSet(true);
             Animation scale = new ScaleAnimation(scaleW, 1, scaleH, 1,
                     computePivot(mNextAppTransitionStartX, scaleW),
                     computePivot(mNextAppTransitionStartY, scaleH));
             scale.setDuration(duration);
             scale.setFillBefore(true);
-            set.addAnimation(scale);
-            // Need to set an alpha animation on the entering app window
-            // in case it appears one frame before the thumbnail window
-            // (this solves flicker)
-            Animation alpha = new AlphaAnimation(0, 1);
-            alpha.setDuration(1);
-            alpha.setFillAfter(true);
-            set.addAnimation(alpha);
-            a = set;
             if (delayDuration > 0) {
-                a.setStartOffset(delayDuration);
+                scale.setStartOffset(delayDuration);
             }
+            a = scale;
         } else {
-            a = createExitAnimationLocked(transit, duration);
-            if (delayDuration > 0) {
-                a.setStartOffset(delayDuration);
+            if (delayed) {
+                a = new AlphaAnimation(1, 0);
+                a.setStartOffset(0);
+                a.setDuration(delayDuration - 50);
+                a.setBackgroundColor(0xFF000000);
+            } else {
+                a = createExitAnimationLocked(transit, duration);
             }
         }
         a.setFillAfter(true);
@@ -5025,6 +5021,18 @@
         return mInputManager.monitorInput(inputChannelName);
     }
 
+    // Called by window manager policy.  Not exposed externally.
+    @Override
+    public void shutdown() {
+        ShutdownThread.shutdown(mContext, true);
+    }
+
+    // Called by window manager policy.  Not exposed externally.
+    @Override
+    public void rebootSafeMode() {
+        ShutdownThread.rebootSafeMode(mContext, true);
+    }
+
     public void setInputFilter(InputFilter filter) {
         mInputManager.setInputFilter(filter);
     }
@@ -7710,6 +7718,7 @@
         }
         
         mPolicy.beginLayoutLw(dw, dh, mRotation);
+        mSystemDecorLayer = mPolicy.getSystemDecorRectLw(mSystemDecorRect);
 
         int seq = mLayoutSeq+1;
         if (seq < 0) seq = 0;
@@ -8172,8 +8181,6 @@
     private void updateResizingWindows(final WindowState w) {
         final WindowStateAnimator winAnimator = w.mWinAnimator;
         if (w.mHasSurface && !w.mAppFreezing && w.mLayoutSeq == mLayoutSeq) {
-            w.mSystemInsetsChanged |=
-                    !w.mLastSystemInsets.equals(w.mSystemInsets);
             w.mContentInsetsChanged |=
                     !w.mLastContentInsets.equals(w.mContentInsets);
             w.mVisibleInsetsChanged |=
@@ -8190,8 +8197,7 @@
                     + ": configChanged=" + configChanged
                     + " last=" + w.mLastFrame + " frame=" + w.mFrame);
             w.mLastFrame.set(w.mFrame);
-            if (w.mSystemInsetsChanged
-                    || w.mContentInsetsChanged
+            if (w.mContentInsetsChanged
                     || w.mVisibleInsetsChanged
                     || winAnimator.mSurfaceResized
                     || configChanged) {
@@ -8203,7 +8209,6 @@
                             + " configChanged=" + configChanged);
                 }
 
-                w.mLastSystemInsets.set(w.mSystemInsets);
                 w.mLastContentInsets.set(w.mContentInsets);
                 w.mLastVisibleInsets.set(w.mVisibleInsets);
                 makeWindowFreezingScreenIfNeededLocked(w);
@@ -8587,11 +8592,10 @@
                             winAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING) Slog.i(
                             TAG, "Resizing " + win + " WITH DRAW PENDING");
                     win.mClient.resized((int)winAnimator.mSurfaceW,
-                            (int)winAnimator.mSurfaceH, win.mLastSystemInsets,
+                            (int)winAnimator.mSurfaceH,
                             win.mLastContentInsets, win.mLastVisibleInsets,
                             winAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING,
                             configChanged ? win.mConfiguration : null);
-                    win.mSystemInsetsChanged = false;
                     win.mContentInsetsChanged = false;
                     win.mVisibleInsetsChanged = false;
                     winAnimator.mSurfaceResized = false;
@@ -8700,13 +8704,13 @@
                 mPowerManager.setScreenBrightnessOverride(-1);
             } else {
                 mPowerManager.setScreenBrightnessOverride((int)
-                        (mInnerFields.mScreenBrightness * Power.BRIGHTNESS_ON));
+                        (mInnerFields.mScreenBrightness * PowerManager.BRIGHTNESS_ON));
             }
             if (mInnerFields.mButtonBrightness < 0 || mInnerFields.mButtonBrightness > 1.0f) {
                 mPowerManager.setButtonBrightnessOverride(-1);
             } else {
                 mPowerManager.setButtonBrightnessOverride((int)
-                        (mInnerFields.mButtonBrightness * Power.BRIGHTNESS_ON));
+                        (mInnerFields.mButtonBrightness * PowerManager.BRIGHTNESS_ON));
             }
         }
         if (mInnerFields.mHoldScreen != mHoldingScreenOn) {
@@ -9582,6 +9586,8 @@
         pw.print("  mInTouchMode="); pw.print(mInTouchMode);
                 pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
         if (dumpAll) {
+            pw.print("  mSystemDecorRect="); pw.print(mSystemDecorRect.toShortString());
+                    pw.print(" mSystemDecorLayer="); pw.println(mSystemDecorLayer);
             if (mLastStatusBarVisibility != 0) {
                 pw.print("  mLastStatusBarVisibility=0x");
                         pw.println(Integer.toHexString(mLastStatusBarVisibility));
diff --git a/services/java/com/android/server/wm/WindowState.java b/services/java/com/android/server/wm/WindowState.java
index 05e7d3a..1fd80c2 100644
--- a/services/java/com/android/server/wm/WindowState.java
+++ b/services/java/com/android/server/wm/WindowState.java
@@ -133,14 +133,6 @@
     boolean mContentInsetsChanged;
 
     /**
-     * Insets that are covered by system windows such as the status bar.  These
-     * are in the application's coordinate space (without compatibility scale applied).
-     */
-    final Rect mSystemInsets = new Rect();
-    final Rect mLastSystemInsets = new Rect();
-    boolean mSystemInsetsChanged;
-
-    /**
      * Set to true if we are waiting for this window to receive its
      * given internal insets before laying out other windows based on it.
      */
@@ -171,6 +163,13 @@
      */
     int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
 
+    /**
+     * This is rectangle of the window's surface that is not covered by
+     * system decorations.
+     */
+    final Rect mSystemDecorRect = new Rect();
+    final Rect mLastSystemDecorRect = new Rect();
+
     // Current transformation being applied.
     float mGlobalScale=1;
     float mInvGlobalScale=1;
@@ -187,7 +186,6 @@
 
     final Rect mContainingFrame = new Rect();
     final Rect mDisplayFrame = new Rect();
-    final Rect mSystemFrame = new Rect();
     final Rect mContentFrame = new Rect();
     final Rect mParentFrame = new Rect();
     final Rect mVisibleFrame = new Rect();
@@ -356,7 +354,7 @@
     }
 
     @Override
-    public void computeFrameLw(Rect pf, Rect df, Rect sf, Rect cf, Rect vf) {
+    public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
         mHaveFrame = true;
 
         final Rect container = mContainingFrame;
@@ -413,9 +411,6 @@
             mContentChanged = true;
         }
 
-        final Rect system = mSystemFrame;
-        system.set(sf);
-
         final Rect content = mContentFrame;
         content.set(cf);
 
@@ -449,10 +444,6 @@
 
         // Make sure the system, content and visible frames are inside of the
         // final window frame.
-        if (system.left < frame.left) system.left = frame.left;
-        if (system.top < frame.top) system.top = frame.top;
-        if (system.right > frame.right) system.right = frame.right;
-        if (system.bottom > frame.bottom) system.bottom = frame.bottom;
         if (content.left < frame.left) content.left = frame.left;
         if (content.top < frame.top) content.top = frame.top;
         if (content.right > frame.right) content.right = frame.right;
@@ -462,12 +453,6 @@
         if (visible.right > frame.right) visible.right = frame.right;
         if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
 
-        final Rect systemInsets = mSystemInsets;
-        systemInsets.left = system.left-frame.left;
-        systemInsets.top = system.top-frame.top;
-        systemInsets.right = frame.right-system.right;
-        systemInsets.bottom = frame.bottom-system.bottom;
-
         final Rect contentInsets = mContentInsets;
         contentInsets.left = content.left-frame.left;
         contentInsets.top = content.top-frame.top;
@@ -485,7 +470,6 @@
             // If there is a size compatibility scale being applied to the
             // window, we need to apply this to its insets so that they are
             // reported to the app in its coordinate space.
-            systemInsets.scale(mInvGlobalScale);
             contentInsets.scale(mInvGlobalScale);
             visibleInsets.scale(mInvGlobalScale);
 
@@ -506,7 +490,6 @@
                         + mRequestedWidth + ", mRequestedheight="
                         + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
                         + "): frame=" + mFrame.toShortString()
-                        + " si=" + systemInsets.toShortString()
                         + " ci=" + contentInsets.toShortString()
                         + " vi=" + visibleInsets.toShortString());
             //}
@@ -529,11 +512,6 @@
     }
 
     @Override
-    public Rect getSystemFrameLw() {
-        return mSystemFrame;
-    }
-
-    @Override
     public Rect getContentFrameLw() {
         return mContentFrame;
     }
@@ -1067,6 +1045,9 @@
             pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
                     pw.print(" last="); mLastFrame.printShortString(pw);
                     pw.println();
+            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
+                    pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
+                    pw.println();
         }
         if (mEnforceSizeCompat) {
             pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
@@ -1078,16 +1059,15 @@
                     pw.print(" parent="); mParentFrame.printShortString(pw);
                     pw.print(" display="); mDisplayFrame.printShortString(pw);
                     pw.println();
-            pw.print(prefix); pw.print("    system="); mSystemFrame.printShortString(pw);
-                    pw.print(" content="); mContentFrame.printShortString(pw);
+            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
                     pw.print(" visible="); mVisibleFrame.printShortString(pw);
                     pw.println();
-            pw.print(prefix); pw.print("Cur insets: system="); mSystemInsets.printShortString(pw);
-                    pw.print(" content="); mContentInsets.printShortString(pw);;
+            pw.print(prefix); pw.print("Cur insets: content=");
+                    mContentInsets.printShortString(pw);
                     pw.print(" visible="); mVisibleInsets.printShortString(pw);
                     pw.println();
-            pw.print(prefix); pw.print("Lst insets: system="); mLastSystemInsets.printShortString(pw);
-                    pw.print(" content="); mLastContentInsets.printShortString(pw);;
+            pw.print(prefix); pw.print("Lst insets: content=");
+                    mLastContentInsets.printShortString(pw);
                     pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
                     pw.println();
         }
diff --git a/services/java/com/android/server/wm/WindowStateAnimator.java b/services/java/com/android/server/wm/WindowStateAnimator.java
index 293d3e8..0aa1b45 100644
--- a/services/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/java/com/android/server/wm/WindowStateAnimator.java
@@ -436,8 +436,9 @@
 
         private float mSurfaceTraceAlpha = 0;
         private int mLayer;
-        private PointF mPosition = new PointF();
-        private Point mSize;
+        private final PointF mPosition = new PointF();
+        private final Point mSize = new Point();
+        private final Rect mWindowCrop = new Rect();
         private boolean mShown = false;
         private String mName = "Not named";
 
@@ -445,7 +446,7 @@
                        int pid, int display, int w, int h, int format, int flags) throws
                        OutOfResourcesException {
             super(s, pid, display, w, h, format, flags);
-            mSize = new Point(w, h);
+            mSize.set(w, h);
             Slog.v(SURFACE_TAG, "ctor: " + this + ". Called by "
                     + Debug.getCallers(3));
         }
@@ -455,7 +456,7 @@
                    throws OutOfResourcesException {
             super(s, pid, name, display, w, h, format, flags);
             mName = name;
-            mSize = new Point(w, h);
+            mSize.set(w, h);
             Slog.v(SURFACE_TAG, "ctor: " + this + ". Called by "
                     + Debug.getCallers(3));
         }
@@ -489,7 +490,7 @@
         @Override
         public void setPosition(float x, float y) {
             super.setPosition(x, y);
-            mPosition = new PointF(x, y);
+            mPosition.set(x, y);
             Slog.v(SURFACE_TAG, "setPosition: " + this + ". Called by "
                     + Debug.getCallers(3));
         }
@@ -497,12 +498,20 @@
         @Override
         public void setSize(int w, int h) {
             super.setSize(w, h);
-            mSize = new Point(w, h);
+            mSize.set(w, h);
             Slog.v(SURFACE_TAG, "setSize: " + this + ". Called by "
                     + Debug.getCallers(3));
         }
 
         @Override
+        public void setWindowCrop(Rect crop) {
+            super.setWindowCrop(crop);
+            mWindowCrop.set(crop);
+            Slog.v(SURFACE_TAG, "setWindowCrop: " + this + ". Called by "
+                    + Debug.getCallers(3));
+        }
+
+        @Override
         public void hide() {
             super.hide();
             mShown = false;
@@ -545,7 +554,8 @@
             return "Surface " + Integer.toHexString(System.identityHashCode(this)) + " "
                     + mName + ": shown=" + mShown + " layer=" + mLayer
                     + " alpha=" + mSurfaceTraceAlpha + " " + mPosition.x + "," + mPosition.y
-                    + " " + mSize.x + "x" + mSize.y;
+                    + " " + mSize.x + "x" + mSize.y
+                    + " crop=" + mWindowCrop.toShortString();
         }
     }
 
@@ -596,6 +606,7 @@
             mSurfaceY = 0;
             mSurfaceW = w;
             mSurfaceH = h;
+            mWin.mLastSystemDecorRect.set(0, 0, 0, 0);
             try {
                 final boolean isHwAccelerated = (attrs.flags &
                         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
@@ -991,6 +1002,55 @@
                 }
             }
         }
+
+        // Need to recompute a new system decor rect each time.
+        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
+            // Currently can't do this cropping for scaled windows.  We'll
+            // just keep the crop rect the same as the source surface.
+            w.mSystemDecorRect.set(0, 0, w.mRequestedWidth, w.mRequestedHeight);
+        } else if (w.mLayer >= mService.mSystemDecorLayer) {
+            // Above the decor layer is easy, just use the entire window.
+            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(),
+                    w.mCompatFrame.height());
+        } else {
+            final Rect decorRect = mService.mSystemDecorRect;
+            // Compute the offset of the window in relation to the decor rect.
+            final int offX = w.mXOffset + w.mFrame.left;
+            final int offY = w.mYOffset + w.mFrame.top;
+            // Initialize the decor rect to the entire frame.
+            w.mSystemDecorRect.set(0, 0, w.mFrame.width(), w.mFrame.height());
+            // Intersect with the decor rect, offsetted by window position.
+            w.mSystemDecorRect.intersect(decorRect.left-offX, decorRect.top-offY,
+                    decorRect.right-offX, decorRect.bottom-offY);
+            // If size compatibility is being applied to the window, the
+            // surface is scaled relative to the screen.  Also apply this
+            // scaling to the crop rect.  We aren't using the standard rect
+            // scale function because we want to round things to make the crop
+            // always round to a larger rect to ensure we don't crop too
+            // much and hide part of the window that should be seen.
+            if (w.mEnforceSizeCompat && w.mInvGlobalScale != 1.0f) {
+                final float scale = w.mInvGlobalScale;
+                w.mSystemDecorRect.left = (int) (w.mSystemDecorRect.left * scale - 0.5f);
+                w.mSystemDecorRect.top = (int) (w.mSystemDecorRect.top * scale - 0.5f);
+                w.mSystemDecorRect.right = (int) ((w.mSystemDecorRect.right+1) * scale - 0.5f);
+                w.mSystemDecorRect.bottom = (int) ((w.mSystemDecorRect.bottom+1) * scale - 0.5f);
+            }
+        }
+
+        if (!w.mSystemDecorRect.equals(w.mLastSystemDecorRect)) {
+            w.mLastSystemDecorRect.set(w.mSystemDecorRect);
+            try {
+                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
+                        "CROP " + w.mSystemDecorRect.toShortString(), null);
+                mSurface.setWindowCrop(w.mSystemDecorRect);
+            } catch (RuntimeException e) {
+                Slog.w(TAG, "Error setting crop surface of " + w
+                        + " crop=" + w.mSystemDecorRect.toShortString(), e);
+                if (!recoveringMemory) {
+                    mService.reclaimSomeSurfaceMemoryLocked(this, "crop", true);
+                }
+            }
+        }
     }
 
     public void prepareSurfaceLocked(final boolean recoveringMemory) {
diff --git a/services/jni/Android.mk b/services/jni/Android.mk
index e2bd622..e0a14af 100644
--- a/services/jni/Android.mk
+++ b/services/jni/Android.mk
@@ -23,7 +23,10 @@
     frameworks/base/services \
     frameworks/base/core/jni \
     external/skia/include/core \
-    libcore/include
+    libcore/include \
+    libcore/include/libsuspend \
+	$(call include-path-for, libhardware)/hardware \
+	$(call include-path-for, libhardware_legacy)/hardware_legacy \
 
 LOCAL_SHARED_LIBRARIES := \
     libandroid_runtime \
@@ -38,7 +41,8 @@
     libinput \
     libskia \
     libgui \
-    libusbhost
+    libusbhost \
+    libsuspend
 
 ifeq ($(WITH_MALLOC_LEAK_CHECK),true)
     LOCAL_CFLAGS += -DMALLOC_LEAK_CHECK
diff --git a/services/jni/com_android_server_PowerManagerService.cpp b/services/jni/com_android_server_PowerManagerService.cpp
index ce80c1f..a47f8fd 100644
--- a/services/jni/com_android_server_PowerManagerService.cpp
+++ b/services/jni/com_android_server_PowerManagerService.cpp
@@ -24,8 +24,14 @@
 #include <limits.h>
 
 #include <android_runtime/AndroidRuntime.h>
-#include <utils/Timers.h>
 #include <gui/ISurfaceComposer.h>
+#include <utils/Timers.h>
+#include <utils/misc.h>
+#include <utils/String8.h>
+#include <hardware/power.h>
+#include <hardware_legacy/power.h>
+#include <cutils/android_reboot.h>
+#include <suspend/autosuspend.h>
 
 #include <private/gui/ComposerService.h>
 
@@ -43,6 +49,7 @@
 // ----------------------------------------------------------------------------
 
 static jobject gPowerManagerServiceObj;
+static struct power_module* gPowerModule;
 
 static Mutex gPowerManagerLock;
 static bool gScreenOn;
@@ -76,6 +83,13 @@
 }
 
 void android_server_PowerManagerService_userActivity(nsecs_t eventTime, int32_t eventType) {
+    if (gPowerModule) {
+        // Tell the power HAL when user activity occurs.
+        if (gPowerModule->powerHint) {
+            gPowerModule->powerHint(gPowerModule, POWER_HINT_INTERACTION, NULL);
+        }
+    }
+
     if (gPowerManagerServiceObj) {
         // Throttle calls into user activity by event type.
         // We're a little conservative about argument checking here in case the caller
@@ -112,33 +126,115 @@
 
 // ----------------------------------------------------------------------------
 
-static void android_server_PowerManagerService_nativeInit(JNIEnv* env, jobject obj) {
+static void nativeInit(JNIEnv* env, jobject obj) {
     gPowerManagerServiceObj = env->NewGlobalRef(obj);
+
+    status_t err = hw_get_module(POWER_HARDWARE_MODULE_ID,
+            (hw_module_t const**)&gPowerModule);
+    if (err) {
+        String8 msg;
+        msg.appendFormat("Couldn't load %s module (%s)",
+                POWER_HARDWARE_MODULE_ID, strerror(-err));
+        ALOGE("%s", msg.string());
+        jniThrowRuntimeException(env, msg.string());
+        return;
+    }
+
+    gPowerModule->init(gPowerModule);
 }
 
-static void android_server_PowerManagerService_nativeSetPowerState(JNIEnv* env,
+static void nativeSetPowerState(JNIEnv* env,
         jobject serviceObj, jboolean screenOn, jboolean screenBright) {
     AutoMutex _l(gPowerManagerLock);
     gScreenOn = screenOn;
     gScreenBright = screenBright;
 }
 
-static void android_server_PowerManagerService_nativeStartSurfaceFlingerAnimation(JNIEnv* env,
+static void nativeStartSurfaceFlingerAnimation(JNIEnv* env,
         jobject obj, jint mode) {
     sp<ISurfaceComposer> s(ComposerService::getComposerService());
     s->turnElectronBeamOff(mode);
 }
 
+static void nativeAcquireWakeLock(JNIEnv *env, jobject clazz, jint lock, jstring idObj) {
+    if (idObj == NULL) {
+        jniThrowNullPointerException(env, "id is null");
+        return;
+    }
+
+    const char *id = env->GetStringUTFChars(idObj, NULL);
+
+    acquire_wake_lock(lock, id);
+
+    env->ReleaseStringUTFChars(idObj, id);
+}
+
+static void nativeReleaseWakeLock(JNIEnv *env, jobject clazz, jstring idObj) {
+    if (idObj == NULL) {
+        jniThrowNullPointerException(env, "id is null");
+        return ;
+    }
+
+    const char *id = env->GetStringUTFChars(idObj, NULL);
+
+    release_wake_lock(id);
+
+    env->ReleaseStringUTFChars(idObj, id);
+
+}
+
+static int nativeSetScreenState(JNIEnv *env, jobject clazz, jboolean on) {
+    if (on) {
+        autosuspend_disable();
+        if (gPowerModule) {
+            gPowerModule->setInteractive(gPowerModule, true);
+        }
+    } else {
+        if (gPowerModule) {
+            gPowerModule->setInteractive(gPowerModule, false);
+        }
+        autosuspend_enable();
+    }
+
+    return 0;
+}
+
+static void nativeShutdown(JNIEnv *env, jobject clazz) {
+    android_reboot(ANDROID_RB_POWEROFF, 0, 0);
+}
+
+static void nativeReboot(JNIEnv *env, jobject clazz, jstring reason) {
+    if (reason == NULL) {
+        android_reboot(ANDROID_RB_RESTART, 0, 0);
+    } else {
+        const char *chars = env->GetStringUTFChars(reason, NULL);
+        android_reboot(ANDROID_RB_RESTART2, 0, (char *) chars);
+        env->ReleaseStringUTFChars(reason, chars);  // In case it fails.
+    }
+    jniThrowIOException(env, errno);
+}
+
+
 // ----------------------------------------------------------------------------
 
 static JNINativeMethod gPowerManagerServiceMethods[] = {
     /* name, signature, funcPtr */
     { "nativeInit", "()V",
-            (void*) android_server_PowerManagerService_nativeInit },
+            (void*) nativeInit },
     { "nativeSetPowerState", "(ZZ)V",
-            (void*) android_server_PowerManagerService_nativeSetPowerState },
+            (void*) nativeSetPowerState },
     { "nativeStartSurfaceFlingerAnimation", "(I)V",
-            (void*) android_server_PowerManagerService_nativeStartSurfaceFlingerAnimation },
+            (void*) nativeStartSurfaceFlingerAnimation },
+    { "nativeAcquireWakeLock", "(ILjava/lang/String;)V",
+            (void*) nativeAcquireWakeLock },
+    { "nativeReleaseWakeLock", "(Ljava/lang/String;)V",
+            (void*) nativeReleaseWakeLock },
+    { "nativeSetScreenState", "(Z)I",
+            (void*) nativeSetScreenState },
+    { "nativeShutdown", "()V",
+            (void*) nativeShutdown },
+    { "nativeReboot", "(Ljava/lang/String;)V",
+            (void*) nativeReboot },
 };
 
 #define FIND_CLASS(var, className) \
@@ -175,6 +271,8 @@
     }
     gScreenOn = true;
     gScreenBright = true;
+    gPowerManagerServiceObj = NULL;
+    gPowerModule = NULL;
     return 0;
 }
 
diff --git a/telephony/java/com/android/internal/telephony/IccCard.java b/telephony/java/com/android/internal/telephony/IccCard.java
index 92024cd..d738d7b 100644
--- a/telephony/java/com/android/internal/telephony/IccCard.java
+++ b/telephony/java/com/android/internal/telephony/IccCard.java
@@ -26,7 +26,6 @@
 import android.os.AsyncResult;
 import android.os.Handler;
 import android.os.Message;
-import android.os.Power;
 import android.os.PowerManager;
 import android.os.Registrant;
 import android.os.RegistrantList;
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java
index c44ddc6..379fb81 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java
@@ -47,7 +47,7 @@
     }
 
     @Override
-    public void resized(int arg0, int arg1, Rect argBlah, Rect arg2, Rect arg3,
+    public void resized(int arg0, int arg1, Rect arg2, Rect arg3,
             boolean arg4, Configuration arg5) throws RemoteException {
         // pass for now.
     }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
index 3996d26..6fb599d 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
@@ -69,7 +69,7 @@
     }
     @Override
     public int relayout(IWindow arg0, int seq, LayoutParams arg1, int arg2, int arg3, int arg4,
-            int arg4_5, Rect arg4_6, Rect arg5, Rect arg6, Rect arg7, Configuration arg7b,
+            int arg4_5, Rect arg5, Rect arg6, Rect arg7, Configuration arg7b,
             Surface arg8) throws RemoteException {
         // pass for now.
         return 0;