Merge "Proper clean up when Ui test automation service is unregistered or dies."
diff --git a/api/current.txt b/api/current.txt
index ee4732d..2615e0b 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -13417,6 +13417,7 @@
     field public java.util.BitSet allowedKeyManagement;
     field public java.util.BitSet allowedPairwiseCiphers;
     field public java.util.BitSet allowedProtocols;
+    field public android.net.wifi.WifiEnterpriseConfig enterpriseConfig;
     field public boolean hiddenSSID;
     field public int networkId;
     field public java.lang.String preSharedKey;
@@ -13474,6 +13475,45 @@
     field public static final java.lang.String[] strings;
   }
 
+  public class WifiEnterpriseConfig implements android.os.Parcelable {
+    ctor public WifiEnterpriseConfig();
+    ctor public WifiEnterpriseConfig(android.net.wifi.WifiEnterpriseConfig);
+    method public int describeContents();
+    method public java.lang.String getAnonymousIdentity();
+    method public int getEapMethod();
+    method public java.lang.String getIdentity();
+    method public int getPhase2Method();
+    method public java.lang.String getSubjectMatch();
+    method public void setAnonymousIdentity(java.lang.String);
+    method public void setCaCertificate(java.security.cert.X509Certificate);
+    method public void setClientKeyEntry(java.security.PrivateKey, java.security.cert.X509Certificate);
+    method public void setEapMethod(int);
+    method public void setIdentity(java.lang.String);
+    method public void setPassword(java.lang.String);
+    method public void setPhase2Method(int);
+    method public void setSubjectMatch(java.lang.String);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator CREATOR;
+  }
+
+  public static final class WifiEnterpriseConfig.Eap {
+    ctor public WifiEnterpriseConfig.Eap();
+    field public static final int NONE = -1; // 0xffffffff
+    field public static final int PEAP = 0; // 0x0
+    field public static final int PWD = 3; // 0x3
+    field public static final int TLS = 1; // 0x1
+    field public static final int TTLS = 2; // 0x2
+  }
+
+  public static final class WifiEnterpriseConfig.Phase2 {
+    ctor public WifiEnterpriseConfig.Phase2();
+    field public static final int GTC = 4; // 0x4
+    field public static final int MSCHAP = 2; // 0x2
+    field public static final int MSCHAPV2 = 3; // 0x3
+    field public static final int NONE = 0; // 0x0
+    field public static final int PAP = 1; // 0x1
+  }
+
   public class WifiInfo implements android.os.Parcelable {
     method public int describeContents();
     method public java.lang.String getBSSID();
diff --git a/core/java/android/view/GLES20Canvas.java b/core/java/android/view/GLES20Canvas.java
index ec7c65a..1810205 100644
--- a/core/java/android/view/GLES20Canvas.java
+++ b/core/java/android/view/GLES20Canvas.java
@@ -515,22 +515,22 @@
 
     @Override
     public boolean quickReject(float left, float top, float right, float bottom, EdgeType type) {
-        return nQuickReject(mRenderer, left, top, right, bottom);
+        return nQuickReject(mRenderer, left, top, right, bottom, type.nativeInt);
     }
     
     private static native boolean nQuickReject(int renderer, float left, float top,
-            float right, float bottom);
+            float right, float bottom, int edge);
 
     @Override
     public boolean quickReject(Path path, EdgeType type) {
         path.computeBounds(mPathBounds, true);
         return nQuickReject(mRenderer, mPathBounds.left, mPathBounds.top,
-                mPathBounds.right, mPathBounds.bottom);
+                mPathBounds.right, mPathBounds.bottom, type.nativeInt);
     }
 
     @Override
     public boolean quickReject(RectF rect, EdgeType type) {
-        return nQuickReject(mRenderer, rect.left, rect.top, rect.right, rect.bottom);
+        return nQuickReject(mRenderer, rect.left, rect.top, rect.right, rect.bottom, type.nativeInt);
     }
 
     ///////////////////////////////////////////////////////////////////////////
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index c10f287..a972b75 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -215,6 +215,7 @@
     private int mNativeSurfaceControl; // SurfaceControl*
     private int mGenerationId; // incremented each time mNativeSurface changes
     private final Canvas mCanvas = new CompatibleCanvas();
+    private int mCanvasSaveCount; // Canvas save count at time of lockCanvas()
 
     // The Translator for density compatibility mode.  This is used for scaling
     // the canvas to perform the appropriate density transformation.
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 44e8757..d705024 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -160,8 +160,7 @@
 	external/skia/include/effects \
 	external/skia/include/images \
 	external/skia/include/ports \
-	external/skia/src/core \
-	external/skia/src/images \
+	external/skia/src/ports \
 	external/skia/include/utils \
 	external/sqlite/dist \
 	external/sqlite/android \
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index daabce3..b7fdecf 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -231,7 +231,7 @@
     }
 
     SkAutoTDelete<SkImageDecoder> add(decoder);
-    SkAutoTDelete<SkBitmap> adb(!useExistingBitmap ? bitmap : NULL);
+    SkAutoTDelete<SkBitmap> adb(bitmap, !useExistingBitmap);
 
     decoder->setPeeker(&peeker);
     if (!isPurgeable) {
diff --git a/core/jni/android/graphics/Canvas.cpp b/core/jni/android/graphics/Canvas.cpp
index 1f1f28f..46784ce 100644
--- a/core/jni/android/graphics/Canvas.cpp
+++ b/core/jni/android/graphics/Canvas.cpp
@@ -93,6 +93,14 @@
         return canvas->getDevice()->accessBitmap(false).height();
     }
 
+    static void setBitmap(JNIEnv* env, jobject, SkCanvas* canvas, SkBitmap* bitmap) {
+        if (bitmap) {
+            canvas->setBitmapDevice(*bitmap);
+        } else {
+            canvas->setDevice(NULL);
+        }
+    }
+ 
     static int saveAll(JNIEnv* env, jobject jcanvas) {
         NPE_CHECK_RETURN_ZERO(env, jcanvas);
         return GraphicsJNI::getNativeCanvas(env, jcanvas)->save();
@@ -270,25 +278,25 @@
         canvas->setDrawFilter(filter);
     }
     
-    static jboolean quickReject__RectF(JNIEnv* env, jobject, SkCanvas* canvas,
-                                        jobject rect) {
+    static jboolean quickReject__RectFI(JNIEnv* env, jobject, SkCanvas* canvas,
+                                        jobject rect, int edgetype) {
         SkRect rect_;
         GraphicsJNI::jrectf_to_rect(env, rect, &rect_);
-        return canvas->quickReject(rect_);
+        return canvas->quickReject(rect_, (SkCanvas::EdgeType)edgetype);
     }
-
-    static jboolean quickReject__Path(JNIEnv* env, jobject, SkCanvas* canvas,
-                                       SkPath* path) {
-        return canvas->quickReject(*path);
+ 
+    static jboolean quickReject__PathI(JNIEnv* env, jobject, SkCanvas* canvas,
+                                       SkPath* path, int edgetype) {
+        return canvas->quickReject(*path, (SkCanvas::EdgeType)edgetype);
     }
-
-    static jboolean quickReject__FFFF(JNIEnv* env, jobject, SkCanvas* canvas,
+ 
+    static jboolean quickReject__FFFFI(JNIEnv* env, jobject, SkCanvas* canvas,
                                        jfloat left, jfloat top, jfloat right,
-                                       jfloat bottom) {
+                                       jfloat bottom, int edgetype) {
         SkRect r;
         r.set(SkFloatToScalar(left), SkFloatToScalar(top),
               SkFloatToScalar(right), SkFloatToScalar(bottom));
-        return canvas->quickReject(r);
+        return canvas->quickReject(r, (SkCanvas::EdgeType)edgetype);
     }
  
     static void drawRGB(JNIEnv* env, jobject, SkCanvas* canvas,
@@ -922,19 +930,12 @@
                               jobject bounds) {
         SkRect   r;
         SkIRect ir;
-        bool     result = canvas->getClipBounds(&r);
+        bool     result = canvas->getClipBounds(&r, SkCanvas::kBW_EdgeType);
 
         if (!result) {
             r.setEmpty();
-        } else {
-            // ensure the clip is not larger than the canvas
-            SkRect canvasRect;
-            SkISize deviceSize = canvas->getDeviceSize();
-            canvasRect.iset(0, 0, deviceSize.fWidth, deviceSize.fHeight);
-            r.intersect(canvasRect);
         }
         r.round(&ir);
-
         (void)GraphicsJNI::irect_to_jrect(ir, env, bounds);
         return result;
     }
@@ -951,6 +952,7 @@
     {"isOpaque","()Z", (void*) SkCanvasGlue::isOpaque},
     {"getWidth","()I", (void*) SkCanvasGlue::getWidth},
     {"getHeight","()I", (void*) SkCanvasGlue::getHeight},
+    {"native_setBitmap","(II)V", (void*) SkCanvasGlue::setBitmap},
     {"save","()I", (void*) SkCanvasGlue::saveAll},
     {"save","(I)I", (void*) SkCanvasGlue::save},
     {"native_saveLayer","(ILandroid/graphics/RectF;II)I",
@@ -982,10 +984,10 @@
     {"native_getClipBounds","(ILandroid/graphics/Rect;)Z",
         (void*) SkCanvasGlue::getClipBounds},
     {"native_getCTM", "(II)V", (void*)SkCanvasGlue::getCTM},
-    {"native_quickReject","(ILandroid/graphics/RectF;)Z",
-        (void*) SkCanvasGlue::quickReject__RectF},
-    {"native_quickReject","(II)Z", (void*) SkCanvasGlue::quickReject__Path},
-    {"native_quickReject","(IFFFF)Z", (void*)SkCanvasGlue::quickReject__FFFF},
+    {"native_quickReject","(ILandroid/graphics/RectF;I)Z",
+        (void*) SkCanvasGlue::quickReject__RectFI},
+    {"native_quickReject","(III)Z", (void*) SkCanvasGlue::quickReject__PathI},
+    {"native_quickReject","(IFFFFI)Z", (void*)SkCanvasGlue::quickReject__FFFFI},
     {"native_drawRGB","(IIII)V", (void*) SkCanvasGlue::drawRGB},
     {"native_drawARGB","(IIIII)V", (void*) SkCanvasGlue::drawARGB},
     {"native_drawColor","(II)V", (void*) SkCanvasGlue::drawColor__I},
diff --git a/core/jni/android/graphics/NinePatchImpl.cpp b/core/jni/android/graphics/NinePatchImpl.cpp
index 01e7e3e..ff0eb45 100644
--- a/core/jni/android/graphics/NinePatchImpl.cpp
+++ b/core/jni/android/graphics/NinePatchImpl.cpp
@@ -105,7 +105,7 @@
 void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds,
                        const SkBitmap& bitmap, const android::Res_png_9patch& chunk,
                        const SkPaint* paint, SkRegion** outRegion) {
-    if (canvas && canvas->quickReject(bounds)) {
+    if (canvas && canvas->quickReject(bounds, SkCanvas::kBW_EdgeType)) {
         return;
     }
 
diff --git a/core/jni/android/graphics/Region.cpp b/core/jni/android/graphics/Region.cpp
index ded2186..ab7cf46 100644
--- a/core/jni/android/graphics/Region.cpp
+++ b/core/jni/android/graphics/Region.cpp
@@ -177,7 +177,7 @@
 
     SkRegion* region = new SkRegion;
     size_t size = p->readInt32();
-    region->readFromMemory(p->readInplace(size));
+    region->unflatten(p->readInplace(size));
 
     return region;
 }
@@ -190,9 +190,9 @@
 
     android::Parcel* p = android::parcelForJavaObject(env, parcel);
 
-    size_t size = region->writeToMemory(NULL);
+    size_t size = region->flatten(NULL);
     p->writeInt32(size);
-    region->writeToMemory(p->writeInplace(size));
+    region->flatten(p->writeInplace(size));
 
     return true;
 }
diff --git a/core/jni/android/graphics/TextLayoutCache.cpp b/core/jni/android/graphics/TextLayoutCache.cpp
index 1a8612e..60c6183 100644
--- a/core/jni/android/graphics/TextLayoutCache.cpp
+++ b/core/jni/android/graphics/TextLayoutCache.cpp
@@ -340,7 +340,7 @@
 }
 
 void TextLayoutShaper::init() {
-    mDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, SkTypeface::kNormal);
+    mDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, NULL, 0, SkTypeface::kNormal);
 }
 
 void TextLayoutShaper::unrefTypefaces() {
diff --git a/core/jni/android/graphics/Typeface.cpp b/core/jni/android/graphics/Typeface.cpp
index e056b61..7f4c37b 100644
--- a/core/jni/android/graphics/Typeface.cpp
+++ b/core/jni/android/graphics/Typeface.cpp
@@ -147,6 +147,25 @@
     return SkTypeface::CreateFromFile(str.c_str());
 }
 
+#define MIN_GAMMA   (0.1f)
+#define MAX_GAMMA   (10.0f)
+static float pinGamma(float gamma) {
+    if (gamma < MIN_GAMMA) {
+        gamma = MIN_GAMMA;
+    } else if (gamma > MAX_GAMMA) {
+        gamma = MAX_GAMMA;
+    }
+    return gamma;
+}
+
+extern void skia_set_text_gamma(float, float);
+
+static void Typeface_setGammaForText(JNIEnv* env, jobject, jfloat blackGamma,
+                                     jfloat whiteGamma) {
+    // Comment this out for release builds. This is only used during development
+    skia_set_text_gamma(pinGamma(blackGamma), pinGamma(whiteGamma));
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 
 static JNINativeMethod gTypefaceMethods[] = {
@@ -158,6 +177,7 @@
                                            (void*)Typeface_createFromAsset },
     { "nativeCreateFromFile",     "(Ljava/lang/String;)I",
                                            (void*)Typeface_createFromFile },
+    { "setGammaForText", "(FF)V", (void*)Typeface_setGammaForText },
 };
 
 int register_android_graphics_Typeface(JNIEnv* env)
diff --git a/core/jni/android_view_GLES20Canvas.cpp b/core/jni/android_view_GLES20Canvas.cpp
index c08178d..80573a7 100644
--- a/core/jni/android_view_GLES20Canvas.cpp
+++ b/core/jni/android_view_GLES20Canvas.cpp
@@ -269,7 +269,8 @@
 // ----------------------------------------------------------------------------
 
 static bool android_view_GLES20Canvas_quickReject(JNIEnv* env, jobject clazz,
-        OpenGLRenderer* renderer, jfloat left, jfloat top, jfloat right, jfloat bottom) {
+        OpenGLRenderer* renderer, jfloat left, jfloat top, jfloat right, jfloat bottom,
+        SkCanvas::EdgeType edge) {
     return renderer->quickReject(left, top, right, bottom);
 }
 
@@ -978,7 +979,7 @@
     { "nSaveLayerAlpha",    "(IFFFFII)I",      (void*) android_view_GLES20Canvas_saveLayerAlpha },
     { "nSaveLayerAlpha",    "(III)I",          (void*) android_view_GLES20Canvas_saveLayerAlphaClip },
 
-    { "nQuickReject",       "(IFFFF)Z",        (void*) android_view_GLES20Canvas_quickReject },
+    { "nQuickReject",       "(IFFFFI)Z",       (void*) android_view_GLES20Canvas_quickReject },
     { "nClipRect",          "(IFFFFI)Z",       (void*) android_view_GLES20Canvas_clipRectF },
     { "nClipRect",          "(IIIIII)Z",       (void*) android_view_GLES20Canvas_clipRect },
     { "nClipPath",          "(III)Z",          (void*) android_view_GLES20Canvas_clipPath },
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index ed92e43..1f15370 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -66,6 +66,7 @@
     jfieldID mNativeSurfaceControl;
     jfieldID mGenerationId;
     jfieldID mCanvas;
+    jfieldID mCanvasSaveCount;
     jmethodID ctor;
 } gSurfaceClassInfo;
 
@@ -77,16 +78,11 @@
 } gRectClassInfo;
 
 static struct {
-    jfieldID mFinalizer;
     jfieldID mNativeCanvas;
     jfieldID mSurfaceFormat;
 } gCanvasClassInfo;
 
 static struct {
-    jfieldID mNativeCanvas;
-} gCanvasFinalizerClassInfo;
-
-static struct {
     jfieldID width;
     jfieldID height;
     jfieldID refreshRate;
@@ -139,7 +135,6 @@
         return mScreenshot.getFormat();
     }
 
-    SK_DECLARE_UNFLATTENABLE_OBJECT()
 protected:
     // overrides from SkPixelRef
     virtual void* onLockPixels(SkColorTable** ct) {
@@ -378,15 +373,6 @@
     }
 }
 
-static inline void swapCanvasPtr(JNIEnv* env, jobject canvasObj, SkCanvas* newCanvas) {
-  jobject canvasFinalizerObj = env->GetObjectField(canvasObj, gCanvasClassInfo.mFinalizer);
-  SkCanvas* previousCanvas = reinterpret_cast<SkCanvas*>(
-          env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
-  env->SetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas, (int)newCanvas);
-  env->SetIntField(canvasFinalizerObj, gCanvasFinalizerClassInfo.mNativeCanvas, (int)newCanvas);
-  SkSafeUnref(previousCanvas);
-}
-
 static jobject nativeLockCanvas(JNIEnv* env, jobject surfaceObj, jobject dirtyRectObj) {
     sp<Surface> surface(getSurface(env, surfaceObj));
     if (!Surface::isValid(surface)) {
@@ -423,6 +409,8 @@
     jobject canvasObj = env->GetObjectField(surfaceObj, gSurfaceClassInfo.mCanvas);
     env->SetIntField(canvasObj, gCanvasClassInfo.mSurfaceFormat, info.format);
 
+    SkCanvas* nativeCanvas = reinterpret_cast<SkCanvas*>(
+            env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
     SkBitmap bitmap;
     ssize_t bpr = info.s * bytesPerPixel(info.format);
     bitmap.setConfig(convertPixelFormat(info.format), info.w, info.h, bpr);
@@ -435,9 +423,7 @@
         // be safe with an empty bitmap.
         bitmap.setPixels(NULL);
     }
-
-    SkCanvas* nativeCanvas = SkNEW_ARGS(SkCanvas, (bitmap));
-    swapCanvasPtr(env, canvasObj, nativeCanvas);
+    nativeCanvas->setBitmapDevice(bitmap);
 
     SkRegion clipReg;
     if (dirtyRegion.isRect()) { // very common case
@@ -454,6 +440,9 @@
 
     nativeCanvas->clipRegion(clipReg);
 
+    int saveCount = nativeCanvas->save();
+    env->SetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount, saveCount);
+
     if (dirtyRectObj) {
         const Rect& bounds(dirtyRegion.getBounds());
         env->SetIntField(dirtyRectObj, gRectClassInfo.left, bounds.left);
@@ -478,8 +467,12 @@
     }
 
     // detach the canvas from the surface
-    SkCanvas* nativeCanvas = SkNEW(SkCanvas);
-    swapCanvasPtr(env, canvasObj, nativeCanvas);
+    SkCanvas* nativeCanvas = reinterpret_cast<SkCanvas*>(
+            env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
+    int saveCount = env->GetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount);
+    nativeCanvas->restoreToCount(saveCount);
+    nativeCanvas->setBitmapDevice(SkBitmap());
+    env->SetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount, 0);
 
     // unlock surface
     status_t err = surface->unlockAndPost();
@@ -895,16 +888,14 @@
             env->GetFieldID(gSurfaceClassInfo.clazz, "mGenerationId", "I");
     gSurfaceClassInfo.mCanvas =
             env->GetFieldID(gSurfaceClassInfo.clazz, "mCanvas", "Landroid/graphics/Canvas;");
+    gSurfaceClassInfo.mCanvasSaveCount =
+            env->GetFieldID(gSurfaceClassInfo.clazz, "mCanvasSaveCount", "I");
     gSurfaceClassInfo.ctor = env->GetMethodID(gSurfaceClassInfo.clazz, "<init>", "()V");
 
     clazz = env->FindClass("android/graphics/Canvas");
-    gCanvasClassInfo.mFinalizer = env->GetFieldID(clazz, "mFinalizer", "Landroid/graphics/Canvas$CanvasFinalizer;");
     gCanvasClassInfo.mNativeCanvas = env->GetFieldID(clazz, "mNativeCanvas", "I");
     gCanvasClassInfo.mSurfaceFormat = env->GetFieldID(clazz, "mSurfaceFormat", "I");
 
-    clazz = env->FindClass("android/graphics/Canvas$CanvasFinalizer");
-    gCanvasFinalizerClassInfo.mNativeCanvas = env->GetFieldID(clazz, "mNativeCanvas", "I");
-
     clazz = env->FindClass("android/graphics/Rect");
     gRectClassInfo.left = env->GetFieldID(clazz, "left", "I");
     gRectClassInfo.top = env->GetFieldID(clazz, "top", "I");
diff --git a/core/jni/android_view_TextureView.cpp b/core/jni/android_view_TextureView.cpp
index 64cbda3..87b312f 100644
--- a/core/jni/android_view_TextureView.cpp
+++ b/core/jni/android_view_TextureView.cpp
@@ -43,16 +43,11 @@
 } gRectClassInfo;
 
 static struct {
-    jfieldID mFinalizer;
-    jfieldID mNativeCanvas;
-    jfieldID mSurfaceFormat;
+    jfieldID nativeCanvas;
+    jfieldID surfaceFormat;
 } gCanvasClassInfo;
 
 static struct {
-    jfieldID mNativeCanvas;
-} gCanvasFinalizerClassInfo;
-
-static struct {
     jfieldID nativeWindow;
 } gTextureViewClassInfo;
 
@@ -125,15 +120,6 @@
     }
 }
 
-static inline void swapCanvasPtr(JNIEnv* env, jobject canvasObj, SkCanvas* newCanvas) {
-  jobject canvasFinalizerObj = env->GetObjectField(canvasObj, gCanvasClassInfo.mFinalizer);
-  SkCanvas* previousCanvas = reinterpret_cast<SkCanvas*>(
-          env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
-  env->SetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas, (int)newCanvas);
-  env->SetIntField(canvasFinalizerObj, gCanvasFinalizerClassInfo.mNativeCanvas, (int)newCanvas);
-  SkSafeUnref(previousCanvas);
-}
-
 static void android_view_TextureView_lockCanvas(JNIEnv* env, jobject,
         jint nativeWindow, jobject canvas, jobject dirtyRect) {
 
@@ -171,10 +157,9 @@
         bitmap.setPixels(NULL);
     }
 
-    SET_INT(canvas, gCanvasClassInfo.mSurfaceFormat, buffer.format);
-
-    SkCanvas* nativeCanvas = SkNEW_ARGS(SkCanvas, (bitmap));
-    swapCanvasPtr(env, canvas, nativeCanvas);
+    SET_INT(canvas, gCanvasClassInfo.surfaceFormat, buffer.format);
+    SkCanvas* nativeCanvas = (SkCanvas*) GET_INT(canvas, gCanvasClassInfo.nativeCanvas);
+    nativeCanvas->setBitmapDevice(bitmap);
 
     SkRect clipRect;
     clipRect.set(rect.left, rect.top, rect.right, rect.bottom);
@@ -189,8 +174,8 @@
 static void android_view_TextureView_unlockCanvasAndPost(JNIEnv* env, jobject,
         jint nativeWindow, jobject canvas) {
 
-    SkCanvas* nativeCanvas = SkNEW(SkCanvas);
-    swapCanvasPtr(env, canvas, nativeCanvas);
+    SkCanvas* nativeCanvas = (SkCanvas*) GET_INT(canvas, gCanvasClassInfo.nativeCanvas);
+    nativeCanvas->setBitmapDevice(SkBitmap());
 
     if (nativeWindow) {
         sp<ANativeWindow> window((ANativeWindow*) nativeWindow);
@@ -241,12 +226,8 @@
     GET_FIELD_ID(gRectClassInfo.bottom, clazz, "bottom", "I");
 
     FIND_CLASS(clazz, "android/graphics/Canvas");
-    GET_FIELD_ID(gCanvasClassInfo.mFinalizer, clazz, "mFinalizer", "Landroid/graphics/Canvas$CanvasFinalizer;");
-    GET_FIELD_ID(gCanvasClassInfo.mNativeCanvas, clazz, "mNativeCanvas", "I");
-    GET_FIELD_ID(gCanvasClassInfo.mSurfaceFormat, clazz, "mSurfaceFormat", "I");
-
-    FIND_CLASS(clazz, "android/graphics/Canvas$CanvasFinalizer");
-    GET_FIELD_ID(gCanvasFinalizerClassInfo.mNativeCanvas, clazz, "mNativeCanvas", "I");
+    GET_FIELD_ID(gCanvasClassInfo.nativeCanvas, clazz, "mNativeCanvas", "I");
+    GET_FIELD_ID(gCanvasClassInfo.surfaceFormat, clazz, "mSurfaceFormat", "I");
 
     FIND_CLASS(clazz, "android/view/TextureView");
     GET_FIELD_ID(gTextureViewClassInfo.nativeWindow, clazz, "mNativeWindow", "I");
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index dff3a32..6307c69 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -26,19 +26,19 @@
 
 
 
-sdk.linux_download=android-sdk_r21.1.0-linux.tgz
+sdk.linux_download=android-sdk_r21.1-linux.tgz
 sdk.linux_bytes=91617112
 sdk.linux_checksum=3369a439240cf3dbe165d6b4173900a8
 
-sdk.mac_download=android-sdk_r21.1.0-macosx.zip
+sdk.mac_download=android-sdk_r21.1-macosx.zip
 sdk.mac_bytes=66077080
 sdk.mac_checksum=49903cf79e1f8e3fde54a95bd3666385
 
-sdk.win_download=android-sdk_r21.1.0-windows.zip
+sdk.win_download=android-sdk_r21.1-windows.zip
 sdk.win_bytes=99360755
 sdk.win_checksum=dbece8859da9b66a1e8e7cd47b1e647e
 
-sdk.win_installer=installer_r21.1.0-windows.exe
+sdk.win_installer=installer_r21.1-windows.exe
 sdk.win_installer_bytes=77767013
 sdk.win_installer_checksum=594d8ff8e349db9e783a5f2229561353
 
diff --git a/docs/html/tools/tools_toc.cs b/docs/html/tools/tools_toc.cs
index 4baa9c3..91a018c 100644
--- a/docs/html/tools/tools_toc.cs
+++ b/docs/html/tools/tools_toc.cs
@@ -32,33 +32,33 @@
 
   <li class="nav-section">
     <div class="nav-section-header">
-        <a href="/tools/workflow/index.html"><span class="en">Workflow</span></a>
+        <a href="<?cs var:toroot ?>tools/workflow/index.html"><span class="en">Workflow</span></a>
     </div>
     <ul>
       <li class="nav-section">
-        <div class="nav-section-header"><a href="/tools/devices/index.html"><span class="en">Setting Up Virtual Devices</span></a></div>
+        <div class="nav-section-header"><a href="<?cs var:toroot ?>tools/devices/index.html"><span class="en">Setting Up Virtual Devices</span></a></div>
         <ul>
-          <li><a href="/tools/devices/managing-avds.html"><span class="en">With AVD Manager</span></a></li>
-          <li><a href="/tools/devices/managing-avds-cmdline.html"><span class="en">From the Command Line</span></a></li>
-          <li><a href="/tools/devices/emulator.html"><span class="en">Using the Android Emulator</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/devices/managing-avds.html"><span class="en">With AVD Manager</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/devices/managing-avds-cmdline.html"><span class="en">From the Command Line</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/devices/emulator.html"><span class="en">Using the Android Emulator</span></a></li>
         </ul>
       </li>
-      <li><a href="/tools/device.html"><span class="en">Using Hardware Devices</span></a></li>
+      <li><a href="<?cs var:toroot ?>tools/device.html"><span class="en">Using Hardware Devices</span></a></li>
       <li class="nav-section">
-        <div class="nav-section-header"><a href="/tools/projects/index.html"><span class="en">Setting Up Projects</span></a></div>
+        <div class="nav-section-header"><a href="<?cs var:toroot ?>tools/projects/index.html"><span class="en">Setting Up Projects</span></a></div>
         <ul>
-          <li><a href="/tools/projects/projects-eclipse.html"><span class="en">From Eclipse with ADT</span></a></li>
-          <li><a href="/tools/projects/projects-cmdline.html"><span class="en">From the Command Line</span></a></li>
-          <li><a href="/tools/projects/templates.html"><span class="en">Using Code Templates</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/projects/projects-eclipse.html"><span class="en">From Eclipse with ADT</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/projects/projects-cmdline.html"><span class="en">From the Command Line</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/projects/templates.html"><span class="en">Using Code Templates</span></a></li>
         </ul>
       </li>
 
 
       <li class="nav-section">
-        <div class="nav-section-header"><a href="/tools/building/index.html"><span class="en">Building and Running</span></a></div>
+        <div class="nav-section-header"><a href="<?cs var:toroot ?>tools/building/index.html"><span class="en">Building and Running</span></a></div>
         <ul>
-          <li><a href="/tools/building/building-eclipse.html"><span class="en">From Eclipse with ADT</span></a></li>
-          <li><a href="/tools/building/building-cmdline.html"><span class="en">From the Command Line</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/building/building-eclipse.html"><span class="en">From Eclipse with ADT</span></a></li>
+          <li><a href="<?cs var:toroot ?>tools/building/building-cmdline.html"><span class="en">From the Command Line</span></a></li>
         </ul>
       </li>
 
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index 9684f20..8cbf299 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -37,8 +37,8 @@
  * Canvas and Drawables</a> developer guide.</p></div>
  */
 public class Canvas {
-    // assigned in constructors or setBitmap, freed in finalizer
-    int mNativeCanvas;
+    // assigned in constructors, freed in finalizer
+    final int mNativeCanvas;
     
     // may be null
     private Bitmap mBitmap;
@@ -71,7 +71,7 @@
     private final CanvasFinalizer mFinalizer;
 
     private static class CanvasFinalizer {
-        private int mNativeCanvas;
+        private final int mNativeCanvas;
 
         public CanvasFinalizer(int nativeCanvas) {
             mNativeCanvas = nativeCanvas;
@@ -131,17 +131,6 @@
     }
 
     /**
-     * Replace existing canvas while ensuring that the swap has occurred before
-     * the previous native canvas is unreferenced.
-     */
-    private void safeCanvasSwap(int nativeCanvas) {
-        final int oldCanvas = mNativeCanvas;
-        mNativeCanvas = nativeCanvas;
-        mFinalizer.mNativeCanvas = nativeCanvas;
-        finalizer(oldCanvas);
-    }
-    
-    /**
      * Returns null.
      * 
      * @deprecated This method is not supported and should not be invoked.
@@ -167,11 +156,11 @@
     }
 
     /**
-     * Specify a bitmap for the canvas to draw into. As a side-effect, the
-     * canvas' target density is updated to match that of the bitmap while all
-     * other state such as the layers, filters, matrix, and clip are reset.
+     * Specify a bitmap for the canvas to draw into.  As a side-effect, also
+     * updates the canvas's target density to match that of the bitmap.
      *
      * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
+     * 
      * @see #setDensity(int)
      * @see #getDensity()
      */
@@ -180,19 +169,17 @@
             throw new RuntimeException("Can't set a bitmap device on a GL canvas");
         }
 
-        if (bitmap == null) {
-            safeCanvasSwap(initRaster(0));
-            mDensity = Bitmap.DENSITY_NONE;
-        } else {
+        int pointer = 0;
+        if (bitmap != null) {
             if (!bitmap.isMutable()) {
                 throw new IllegalStateException();
             }
             throwIfRecycled(bitmap);
-
-            safeCanvasSwap(initRaster(bitmap.ni()));
             mDensity = bitmap.mDensity;
+            pointer = bitmap.ni();
         }
 
+        native_setBitmap(mNativeCanvas, pointer);
         mBitmap = bitmap;
     }
     
@@ -707,7 +694,7 @@
      *              does not intersect with the canvas' clip
      */
     public boolean quickReject(RectF rect, EdgeType type) {
-        return native_quickReject(mNativeCanvas, rect);
+        return native_quickReject(mNativeCanvas, rect, type.nativeInt);
     }
 
     /**
@@ -727,7 +714,7 @@
      *                    does not intersect with the canvas' clip
      */
     public boolean quickReject(Path path, EdgeType type) {
-        return native_quickReject(mNativeCanvas, path.ni());
+        return native_quickReject(mNativeCanvas, path.ni(), type.nativeInt);
     }
 
     /**
@@ -750,9 +737,9 @@
      * @return            true if the rect (transformed by the canvas' matrix)
      *                    does not intersect with the canvas' clip
      */
-    public boolean quickReject(float left, float top, float right, float bottom,
-                               EdgeType type) {
-        return native_quickReject(mNativeCanvas, left, top, right, bottom);
+    public boolean quickReject(float left, float top, float right, float bottom, EdgeType type) {
+        return native_quickReject(mNativeCanvas, left, top, right, bottom,
+                                  type.nativeInt);
     }
 
     /**
@@ -1612,6 +1599,7 @@
     public static native void freeTextLayoutCaches();
 
     private static native int initRaster(int nativeBitmapOrZero);
+    private static native void native_setBitmap(int nativeCanvas, int bitmap);
     private static native int native_saveLayer(int nativeCanvas, RectF bounds,
                                                int paint, int layerFlags);
     private static native int native_saveLayer(int nativeCanvas, float l,
@@ -1642,12 +1630,15 @@
                                                        Rect bounds);
     private static native void native_getCTM(int canvas, int matrix);
     private static native boolean native_quickReject(int nativeCanvas,
-                                                     RectF rect);
+                                                     RectF rect,
+                                                     int native_edgeType);
     private static native boolean native_quickReject(int nativeCanvas,
-                                                     int path);
+                                                     int path,
+                                                     int native_edgeType);
     private static native boolean native_quickReject(int nativeCanvas,
                                                      float left, float top,
-                                                     float right, float bottom);
+                                                     float right, float bottom,
+                                                     int native_edgeType);
     private static native void native_drawRGB(int nativeCanvas, int r, int g,
                                               int b);
     private static native void native_drawARGB(int nativeCanvas, int a, int r,
diff --git a/graphics/java/android/graphics/Path.java b/graphics/java/android/graphics/Path.java
index 157c7d1..f6b5ffc 100644
--- a/graphics/java/android/graphics/Path.java
+++ b/graphics/java/android/graphics/Path.java
@@ -375,9 +375,9 @@
      */
     public enum Direction {
         /** clockwise */
-        CW  (1),    // must match enum in SkPath.h
+        CW  (0),    // must match enum in SkPath.h
         /** counter-clockwise */
-        CCW (2);    // must match enum in SkPath.h
+        CCW (1);    // must match enum in SkPath.h
         
         Direction(int ni) {
             nativeInt = ni;
diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java
index c68c9f7..4487a3c 100644
--- a/graphics/java/android/graphics/Typeface.java
+++ b/graphics/java/android/graphics/Typeface.java
@@ -225,4 +225,16 @@
     private static native int  nativeGetStyle(int native_instance);
     private static native int  nativeCreateFromAsset(AssetManager mgr, String path);
     private static native int nativeCreateFromFile(String path);
+
+    /**
+     * Set the global gamma coefficients for black and white text. This call is
+     * usually a no-op in shipping products, and only exists for testing during
+     * development.
+     *
+     * @param blackGamma gamma coefficient for black text
+     * @param whiteGamma gamma coefficient for white text
+     *
+     * @hide - this is just for calibrating devices, not for normal apps
+     */
+    public static native void setGammaForText(float blackGamma, float whiteGamma);
 }
diff --git a/graphics/java/android/renderscript/RenderScript.java b/graphics/java/android/renderscript/RenderScript.java
index 50d888f..c3ddd32 100644
--- a/graphics/java/android/renderscript/RenderScript.java
+++ b/graphics/java/android/renderscript/RenderScript.java
@@ -519,6 +519,8 @@
     native void rsnScriptForEach(int con, int id, int slot, int ain, int aout);
     native void rsnScriptForEachClipped(int con, int id, int slot, int ain, int aout, byte[] params,
                                         int xstart, int xend, int ystart, int yend, int zstart, int zend);
+    native void rsnScriptForEachClipped(int con, int id, int slot, int ain, int aout,
+                                        int xstart, int xend, int ystart, int yend, int zstart, int zend);
     synchronized void nScriptForEach(int id, int slot, int ain, int aout, byte[] params) {
         validate();
         if (params == null) {
@@ -531,7 +533,11 @@
     synchronized void nScriptForEachClipped(int id, int slot, int ain, int aout, byte[] params,
                                             int xstart, int xend, int ystart, int yend, int zstart, int zend) {
         validate();
-        rsnScriptForEachClipped(mContext, id, slot, ain, aout, params, xstart, xend, ystart, yend, zstart, zend);
+        if (params == null) {
+            rsnScriptForEachClipped(mContext, id, slot, ain, aout, xstart, xend, ystart, yend, zstart, zend);
+        } else {
+            rsnScriptForEachClipped(mContext, id, slot, ain, aout, params, xstart, xend, ystart, yend, zstart, zend);
+        }
     }
 
     native void rsnScriptInvokeV(int con, int id, int slot, byte[] params);
diff --git a/graphics/jni/android_renderscript_RenderScript.cpp b/graphics/jni/android_renderscript_RenderScript.cpp
index 9a8a6e8..8830685 100644
--- a/graphics/jni/android_renderscript_RenderScript.cpp
+++ b/graphics/jni/android_renderscript_RenderScript.cpp
@@ -1055,10 +1055,30 @@
 static void
 nScriptForEachClipped(JNIEnv *_env, jobject _this, RsContext con,
                       jint script, jint slot, jint ain, jint aout,
-                      jbyteArray params, jint xstart, jint xend,
+                      jint xstart, jint xend,
                       jint ystart, jint yend, jint zstart, jint zend)
 {
     LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
+    RsScriptCall sc;
+    sc.xStart = xstart;
+    sc.xEnd = xend;
+    sc.yStart = ystart;
+    sc.yEnd = yend;
+    sc.zStart = zstart;
+    sc.zEnd = zend;
+    sc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
+    sc.arrayStart = 0;
+    sc.arrayEnd = 0;
+    rsScriptForEach(con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, NULL, 0, &sc, sizeof(sc));
+}
+
+static void
+nScriptForEachClippedV(JNIEnv *_env, jobject _this, RsContext con,
+                       jint script, jint slot, jint ain, jint aout,
+                       jbyteArray params, jint xstart, jint xend,
+                       jint ystart, jint yend, jint zstart, jint zend)
+{
+    LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
     jint len = _env->GetArrayLength(params);
     jbyte *ptr = _env->GetByteArrayElements(params, NULL);
     RsScriptCall sc;
@@ -1536,7 +1556,8 @@
 {"rsnScriptInvokeV",                 "(III[B)V",                              (void*)nScriptInvokeV },
 {"rsnScriptForEach",                 "(IIIII)V",                              (void*)nScriptForEach },
 {"rsnScriptForEach",                 "(IIIII[B)V",                            (void*)nScriptForEachV },
-{"rsnScriptForEachClipped",          "(IIIII[BIIIIII)V",                      (void*)nScriptForEachClipped },
+{"rsnScriptForEachClipped",          "(IIIIIIIIIII)V",                        (void*)nScriptForEachClipped },
+{"rsnScriptForEachClipped",          "(IIIII[BIIIIII)V",                      (void*)nScriptForEachClippedV },
 {"rsnScriptSetVarI",                 "(IIII)V",                               (void*)nScriptSetVarI },
 {"rsnScriptSetVarJ",                 "(IIIJ)V",                               (void*)nScriptSetVarJ },
 {"rsnScriptSetVarF",                 "(IIIF)V",                               (void*)nScriptSetVarF },
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index d533fa0..fcc1b81 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -44,7 +44,6 @@
 		external/skia/include/core \
 		external/skia/include/effects \
 		external/skia/include/images \
-		external/skia/src/core \
 		external/skia/src/ports \
 		external/skia/include/utils
 
diff --git a/libs/hwui/DisplayListRenderer.h b/libs/hwui/DisplayListRenderer.h
index f3bd188..b25288b 100644
--- a/libs/hwui/DisplayListRenderer.h
+++ b/libs/hwui/DisplayListRenderer.h
@@ -18,8 +18,7 @@
 #define ANDROID_HWUI_DISPLAY_LIST_RENDERER_H
 
 #include <SkChunkAlloc.h>
-#include <SkReader32.h>
-#include <SkWriter32.h>
+#include <SkFlattenable.h>
 #include <SkMatrix.h>
 #include <SkCamera.h>
 #include <SkPaint.h>
diff --git a/libs/hwui/FontRenderer.cpp b/libs/hwui/FontRenderer.cpp
index d8297da..97988f7 100644
--- a/libs/hwui/FontRenderer.cpp
+++ b/libs/hwui/FontRenderer.cpp
@@ -16,7 +16,6 @@
 
 #define LOG_TAG "OpenGLRenderer"
 
-#include <SkGlyph.h>
 #include <SkUtils.h>
 
 #include <cutils/properties.h>
diff --git a/libs/hwui/Layer.h b/libs/hwui/Layer.h
index ccf1da5..664b2f8 100644
--- a/libs/hwui/Layer.h
+++ b/libs/hwui/Layer.h
@@ -23,7 +23,6 @@
 
 #include <ui/Region.h>
 
-#include <SkPaint.h>
 #include <SkXfermode.h>
 
 #include "Rect.h"
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 2431e54..be3cff1 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -80,7 +80,7 @@
     { SkXfermode::kDstATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
     { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
     { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
-    { SkXfermode::kModulate_Mode, GL_ZERO,                GL_SRC_COLOR },
+    { SkXfermode::kMultiply_Mode, GL_ZERO,                GL_SRC_COLOR },
     { SkXfermode::kScreen_Mode,   GL_ONE,                 GL_ONE_MINUS_SRC_COLOR }
 };
 
@@ -101,7 +101,7 @@
     { SkXfermode::kDstATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
     { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
     { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
-    { SkXfermode::kModulate_Mode, GL_DST_COLOR,           GL_ZERO },
+    { SkXfermode::kMultiply_Mode, GL_DST_COLOR,           GL_ZERO },
     { SkXfermode::kScreen_Mode,   GL_ONE_MINUS_DST_COLOR, GL_ONE }
 };
 
diff --git a/libs/hwui/font/CacheTexture.cpp b/libs/hwui/font/CacheTexture.cpp
index 24b0523..f653592 100644
--- a/libs/hwui/font/CacheTexture.cpp
+++ b/libs/hwui/font/CacheTexture.cpp
@@ -14,7 +14,6 @@
  * limitations under the License.
  */
 
-#include <SkGlyph.h>
 #include <utils/Log.h>
 
 #include "Debug.h"
diff --git a/libs/hwui/font/Font.cpp b/libs/hwui/font/Font.cpp
index 1a75ea8..8c5a8ff 100644
--- a/libs/hwui/font/Font.cpp
+++ b/libs/hwui/font/Font.cpp
@@ -20,7 +20,6 @@
 
 #include <utils/JenkinsHash.h>
 
-#include <SkGlyph.h>
 #include <SkUtils.h>
 
 #include "Debug.h"
diff --git a/media/tests/omxjpegdecoder/SkOmxPixelRef.h b/media/tests/omxjpegdecoder/SkOmxPixelRef.h
index 374604c..afedcbd 100644
--- a/media/tests/omxjpegdecoder/SkOmxPixelRef.h
+++ b/media/tests/omxjpegdecoder/SkOmxPixelRef.h
@@ -33,7 +33,6 @@
      //! Return the allocation size for the pixels
     size_t getSize() const { return mSize; }
 
-    SK_DECLARE_UNFLATTENABLE_OBJECT()
 protected:
     // overrides from SkPixelRef
     virtual void* onLockPixels(SkColorTable**);
diff --git a/nfc-extras/java/com/android/nfc_extras/EeAlreadyOpenException.java b/nfc-extras/java/com/android/nfc_extras/EeAlreadyOpenException.java
new file mode 100644
index 0000000..9fde0a3
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeAlreadyOpenException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+public class EeAlreadyOpenException extends EeIOException {
+    public EeAlreadyOpenException() {
+        super();
+    }
+
+    public EeAlreadyOpenException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/EeExternalFieldException.java b/nfc-extras/java/com/android/nfc_extras/EeExternalFieldException.java
new file mode 100644
index 0000000..4326fab
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeExternalFieldException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+public class EeExternalFieldException extends EeIOException {
+    public EeExternalFieldException() {
+        super();
+    }
+
+    public EeExternalFieldException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/EeIOException.java b/nfc-extras/java/com/android/nfc_extras/EeIOException.java
new file mode 100644
index 0000000..66a3b25
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeIOException.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+import java.io.IOException;
+
+public class EeIOException extends IOException {
+    public EeIOException() {
+        super();
+    }
+
+    public EeIOException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/EeInitializationException.java b/nfc-extras/java/com/android/nfc_extras/EeInitializationException.java
new file mode 100644
index 0000000..00e5264
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeInitializationException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+public class EeInitializationException extends EeIOException {
+    public EeInitializationException() {
+        super();
+    }
+
+    public EeInitializationException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/EeListenModeException.java b/nfc-extras/java/com/android/nfc_extras/EeListenModeException.java
new file mode 100644
index 0000000..07f1980
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeListenModeException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+public class EeListenModeException extends EeIOException {
+    public EeListenModeException() {
+        super();
+    }
+
+    public EeListenModeException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/EeNfcDisabledException.java b/nfc-extras/java/com/android/nfc_extras/EeNfcDisabledException.java
new file mode 100644
index 0000000..091db28
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/EeNfcDisabledException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.nfc_extras;
+
+public class EeNfcDisabledException extends EeIOException {
+    public EeNfcDisabledException() {
+        super();
+    }
+
+    public EeNfcDisabledException(String message) {
+        super(message);
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
index f47327a..fd7cb33 100644
--- a/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
+++ b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
@@ -28,6 +28,15 @@
     private final NfcAdapterExtras mExtras;
     private final Binder mToken;
 
+    // Exception types that can be thrown by NfcService
+    // 1:1 mapped to EE_ERROR_ types in NfcService
+    private static final int EE_ERROR_IO = -1;
+    private static final int EE_ERROR_ALREADY_OPEN = -2;
+    private static final int EE_ERROR_INIT = -3;
+    private static final int EE_ERROR_LISTEN_MODE = -4;
+    private static final int EE_ERROR_EXT_FIELD = -5;
+    private static final int EE_ERROR_NFC_DISABLED = -6;
+
     /**
      * Broadcast Action: An ISO-DEP AID was selected.
      *
@@ -118,24 +127,49 @@
     /**
      * Open the NFC Execution Environment on its contact interface.
      *
-     * <p>Only one process may open the secure element at a time. If it is
-     * already open, an {@link IOException} is thrown.
+     * <p>Opening a channel to the the secure element may fail
+     * for a number of reasons:
+     * <ul>
+     * <li>NFC must be enabled for the connection to the SE to be opened.
+     * If it is disabled at the time of this call, an {@link EeNfcDisabledException}
+     * is thrown.
      *
+     * <li>Only one process may open the secure element at a time. Additionally,
+     * this method is not reentrant. If the secure element is already opened,
+     * either by this process or by a different process, an {@link EeAlreadyOpenException}
+     * is thrown.
+     *
+     * <li>If the connection to the secure element could not be initialized,
+     * an {@link EeInitializationException} is thrown.
+     *
+     * <li>If the secure element or the NFC controller is activated in listen
+     * mode - that is, it is talking over the contactless interface - an
+     * {@link EeListenModeException} is thrown.
+     *
+     * <li>If the NFC controller is in a field powered by a remote device,
+     * such as a payment terminal, an {@link EeExternalFieldException} is
+     * thrown.
+     * </ul>
      * <p>All other NFC functionality is disabled while the NFC-EE is open
      * on its contact interface, so make sure to call {@link #close} once complete.
      *
      * <p class="note">
      * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
      *
-     * @throws IOException if the NFC-EE is already open, or some other error occurs
+     * @throws EeAlreadyOpenException if the NFC-EE is already open
+     * @throws EeNfcDisabledException if NFC is disabled
+     * @throws EeInitializationException if the Secure Element could not be initialized
+     * @throws EeListenModeException if the NFCC or Secure Element is activated in listen mode
+     * @throws EeExternalFieldException if the NFCC is in the presence of a remote-powered field
+     * @throws EeIoException if an unknown error occurs
      */
-    public void open() throws IOException {
+    public void open() throws EeIOException {
         try {
             Bundle b = mExtras.getService().open(mExtras.mPackageName, mToken);
             throwBundle(b);
         } catch (RemoteException e) {
             mExtras.attemptDeadServiceRecovery(e);
-            throw new IOException("NFC Service was dead, try again");
+            throw new EeIOException("NFC Service was dead, try again");
         }
     }
 
@@ -176,9 +210,20 @@
         return b.getByteArray("out");
     }
 
-    private static void throwBundle(Bundle b) throws IOException {
-        if (b.getInt("e") == -1) {
-            throw new IOException(b.getString("m"));
+    private static void throwBundle(Bundle b) throws EeIOException {
+        switch (b.getInt("e")) {
+            case EE_ERROR_NFC_DISABLED:
+                throw new EeNfcDisabledException(b.getString("m"));
+            case EE_ERROR_IO:
+                throw new EeIOException(b.getString("m"));
+            case EE_ERROR_INIT:
+                throw new EeInitializationException(b.getString("m"));
+            case EE_ERROR_EXT_FIELD:
+                throw new EeExternalFieldException(b.getString("m"));
+            case EE_ERROR_LISTEN_MODE:
+                throw new EeListenModeException(b.getString("m"));
+            case EE_ERROR_ALREADY_OPEN:
+                throw new EeAlreadyOpenException(b.getString("m"));
         }
     }
 }
diff --git a/packages/SystemUI/res/values-sv/strings.xml b/packages/SystemUI/res/values-sv/strings.xml
index a58c9a0..a03ca33 100644
--- a/packages/SystemUI/res/values-sv/strings.xml
+++ b/packages/SystemUI/res/values-sv/strings.xml
@@ -196,7 +196,7 @@
     <string name="quick_settings_wifi_label" msgid="9135344704899546041">"Wi-Fi"</string>
     <string name="quick_settings_wifi_not_connected" msgid="7171904845345573431">"Ej ansluten"</string>
     <string name="quick_settings_wifi_no_network" msgid="2221993077220856376">"Inget nätverk"</string>
-    <string name="quick_settings_wifi_off_label" msgid="7558778100843885864">"Wi-Fi av"</string>
+    <string name="quick_settings_wifi_off_label" msgid="7558778100843885864">"Wi-Fi är inaktiverat"</string>
     <string name="quick_settings_wifi_display_label" msgid="6893592964463624333">"Trådlös skärm"</string>
     <string name="quick_settings_wifi_display_no_connection_label" msgid="2355298740765736918">"Trådlös skärm"</string>
     <string name="quick_settings_brightness_dialog_title" msgid="8599674057673605368">"Ljusstyrka"</string>
diff --git a/services/input/SpriteController.cpp b/services/input/SpriteController.cpp
index 8163ea0..1f3d2cf 100644
--- a/services/input/SpriteController.cpp
+++ b/services/input/SpriteController.cpp
@@ -208,7 +208,8 @@
                         surfaceInfo.w, surfaceInfo.h, bpr);
                 surfaceBitmap.setPixels(surfaceInfo.bits);
 
-                SkCanvas surfaceCanvas(surfaceBitmap);
+                SkCanvas surfaceCanvas;
+                surfaceCanvas.setBitmapDevice(surfaceBitmap);
 
                 SkPaint paint;
                 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index 4373502..84d5a72 100644
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -2113,7 +2113,7 @@
                             if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
                                     + " out to new task " + target.task);
                         }
-                        mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
+                        mService.mWindowManager.setAppGroupId(target.appToken, target.task.taskId);
                         if (replyChainEnd < 0) {
                             replyChainEnd = targetI;
                         }
@@ -2145,7 +2145,7 @@
                             }
                             mHistory.remove(srcPos);
                             mHistory.add(dstPos, p);
-                            mService.mWindowManager.moveAppToken(dstPos, p.appToken);
+//                            mService.mWindowManager.moveAppToken(dstPos, p.appToken);
                             mService.mWindowManager.setAppGroupId(p.appToken, taskId);
                             dstPos++;
                             i++;
@@ -2297,7 +2297,7 @@
                         if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
                                 + " from " + srcPos + " to " + lastReparentPos
                                 + " in to resetting task " + task);
-                        mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
+//                        mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
                         mService.mWindowManager.setAppGroupId(p.appToken, taskId);
                     }
                     // TODO: This is wrong because it doesn't take lastReparentPos into account.
@@ -4566,7 +4566,7 @@
             updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
         }
 
-        mService.mWindowManager.moveAppTokensToTop(moved);
+//        mService.mWindowManager.moveAppTokensToTop(moved);
         mService.mWindowManager.moveTaskToTop(task);
         if (VALIDATE_TOKENS) {
             validateAppTokensLocked();
@@ -4659,7 +4659,7 @@
             mService.mWindowManager.prepareAppTransition(
                     AppTransition.TRANSIT_TASK_TO_BACK, false);
         }
-        mService.mWindowManager.moveAppTokensToBottom(moved);
+//        mService.mWindowManager.moveAppTokensToBottom(moved);
         mService.mWindowManager.moveTaskToBottom(task);
         if (VALIDATE_TOKENS) {
             validateAppTokensLocked();
diff --git a/services/java/com/android/server/wm/DisplayContent.java b/services/java/com/android/server/wm/DisplayContent.java
index a592893..f8e779d 100644
--- a/services/java/com/android/server/wm/DisplayContent.java
+++ b/services/java/com/android/server/wm/DisplayContent.java
@@ -179,7 +179,10 @@
 
     void refillAnimatingAppTokens() {
         mAnimatingAppTokens.clear();
-        mAnimatingAppTokens.addAll(mAppTokens);
+        AppTokenIterator iterator = new AppTokenIterator();
+        while (iterator.hasNext()) {
+            mAnimatingAppTokens.add(iterator.next());
+        }
     }
 
     void setAppTaskId(AppWindowToken wtoken, int newTaskId) {
@@ -352,13 +355,16 @@
             pw.print("x"); pw.print(mDisplayInfo.smallestNominalAppHeight);
             pw.print("-"); pw.print(mDisplayInfo.largestNominalAppWidth);
             pw.print("x"); pw.println(mDisplayInfo.largestNominalAppHeight);
-            if (mAppTokens.size() > 0) {
+            AppTokenIterator iterator = new AppTokenIterator(true);
+            int ndx = iterator.size() - 1;
+            if (ndx >= 0) {
                 pw.println();
                 pw.println("  Application tokens in Z order:");
-                for (int i=mAppTokens.size()-1; i>=0; i--) {
-                    pw.print("  App #"); pw.print(i);
-                            pw.print(' '); pw.print(mAppTokens.get(i)); pw.println(":");
-                    mAppTokens.get(i).dump(pw, "    ");
+                while (iterator.hasNext()) {
+                    AppWindowToken wtoken = iterator.next();
+                    pw.print("  App #"); pw.print(ndx--);
+                            pw.print(' '); pw.print(wtoken); pw.println(":");
+                    wtoken.dump(pw, "    ");
                 }
             }
             if (mExitingTokens.size() > 0) {
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 7efc165..a4b5a56 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -197,6 +197,7 @@
     static final boolean DEBUG_LAYOUT_REPEATS = true;
     static final boolean DEBUG_SURFACE_TRACE = false;
     static final boolean DEBUG_WINDOW_TRACE = false;
+    static final boolean DEBUG_TASK_MOVEMENT = false;
     static final boolean SHOW_SURFACE_ALLOC = false;
     static final boolean SHOW_TRANSACTIONS = false;
     static final boolean SHOW_LIGHT_TRANSACTIONS = false || SHOW_TRANSACTIONS;
@@ -3313,7 +3314,6 @@
                 mTaskIdToDisplayContents.put(taskId, displayContent);
             }
             displayContent.addAppToken(addPos, atoken);
-            displayContent.verifyAppTokens();
             mTokenMap.put(token.asBinder(), atoken);
             mTaskIdToDisplayContents.put(taskId, displayContent);
 
@@ -4313,7 +4313,6 @@
                 if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG,
                         "removeAppToken: " + wtoken);
                 displayContent.removeAppToken(wtoken);
-                displayContent.verifyAppTokens();
                 wtoken.removed = true;
                 if (wtoken.startingData != null) {
                     startingToken = wtoken;
@@ -4453,6 +4452,58 @@
         return 0;
     }
 
+    private int findAppWindowInsertionPointLocked(AppWindowToken target) {
+        final int taskId = target.groupId;
+        DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
+        if (displayContent == null) {
+            Slog.w(TAG, "findTopAppWindowLocked: no DisplayContent for " + target);
+            return 0;
+        }
+        final WindowList windows = displayContent.getWindowList();
+        final int NW = windows.size();
+
+        AppTokenIterator iterator = displayContent.new AppTokenIterator(true);
+        while (iterator.hasNext()) {
+            if (iterator.next() == target) {
+                break;
+            }
+        }
+
+        while (iterator.hasNext()) {
+            // Find the first app token below the new position that has
+            // a window displayed.
+            final AppWindowToken wtoken = iterator.next();
+            if (DEBUG_REORDER) Slog.v(TAG, "Looking for lower windows in " + wtoken.token);
+            if (wtoken.sendingToBottom) {
+                if (DEBUG_REORDER) Slog.v(TAG, "Skipping token -- currently sending to bottom");
+                continue;
+            }
+            for (int i = wtoken.windows.size() - 1; i >= 0; --i) {
+                WindowState win = wtoken.windows.get(i);
+                for (int j = win.mChildWindows.size() - 1; j >= 0; --j) {
+                    WindowState cwin = win.mChildWindows.get(j);
+                    if (cwin.mSubLayer >= 0) {
+                        for (int pos = NW - 1; pos >= 0; pos--) {
+                            if (windows.get(pos) == cwin) {
+                                if (DEBUG_REORDER) Slog.v(TAG,
+                                        "Found child win @" + (pos + 1));
+                                return pos + 1;
+                            }
+                        }
+                    }
+                }
+                for (int pos = NW - 1; pos >= 0; pos--) {
+                    if (windows.get(pos) == win) {
+                        if (DEBUG_REORDER) Slog.v(TAG, "Found win @" + (pos + 1));
+                        return pos + 1;
+                    }
+                }
+            }
+        }
+
+        return 0;
+    }
+
     private final int reAddWindowLocked(int index, WindowState win) {
         final WindowList windows = win.getWindowList();
         final int NCW = win.mChildWindows.size();
@@ -4509,7 +4560,6 @@
             final AppWindowToken wtoken = findAppWindowToken(token);
             DisplayContent displayContent = mTaskIdToDisplayContents.get(wtoken.groupId);
             final AppTokenList appTokens = displayContent.mAppTokens;
-            final AppTokenList animatingAppTokens = displayContent.mAnimatingAppTokens;
             final int oldIndex = appTokens.indexOf(wtoken);
             if (DEBUG_TOKEN_MOVEMENT || DEBUG_REORDER) Slog.v(TAG,
                     "Start moving token " + wtoken + " initially at "
@@ -4571,7 +4621,7 @@
             if (wtoken != null) {
                 final DisplayContent displayContent = mTaskIdToDisplayContents.get(wtoken.groupId);
                 if (DEBUG_REORDER || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG, "Temporarily removing "
-                        + wtoken + " from " + displayContent.mAppTokens.indexOf(wtoken));
+                        + wtoken);
                 if (!displayContent.mAppTokens.remove(wtoken)) {
                     Slog.w(TAG, "Attempting to reorder token that doesn't exist: "
                             + token + " (" + wtoken + ")");
@@ -4582,8 +4632,12 @@
         }
     }
 
+    WindowList mSavedWindows;
     private void moveAppWindowsLocked(List<IBinder> tokens, DisplayContent displayContent,
             int tokenPos) {
+        if (DEBUG_TASK_MOVEMENT) {
+            mSavedWindows = new WindowList(displayContent.getWindowList());
+        }
         // First remove all of the windows from the list.
         final int N = tokens.size();
         int i;
@@ -4702,42 +4756,130 @@
         Binder.restoreCallingIdentity(origId);
     }
 
-    public void moveTaskToTop(int taskId) {
+    private void moveTaskWindowsLocked(int taskId) {
         DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
         if (displayContent == null) {
-            Slog.e(TAG, "moveTaskToTop: taskId=" + taskId
-                    + " not found in mTaskIdToDisplayContents");
+            Slog.w(TAG, "moveTaskWindowsLocked: can't find DisplayContent for taskId=" + taskId);
             return;
         }
+
+        WindowList windows;
+        WindowList windowsAtStart;
+        if (DEBUG_TASK_MOVEMENT) {
+            windows = displayContent.getWindowList();
+            windowsAtStart = new WindowList(windows);
+            windows.clear();
+            windows.addAll(mSavedWindows);
+        }
+
         TaskList taskList = displayContent.mTaskIdToTaskList.get(taskId);
         if (taskList == null) {
-            Slog.e(TAG, "moveTaskToTop: taskId=" + taskId + " not found in mTaskIdToTaskLists");
+            Slog.w(TAG, "moveTaskWindowsLocked: can't find TaskList for taskId=" + taskId);
             return;
         }
-        if (!displayContent.mTaskLists.remove(taskList)) {
-            Slog.e(TAG, "moveTaskToTop: taskId=" + taskId + " not found in mTaskLists");
+
+        // First remove all of the windows from the list.
+        for (AppWindowToken wtoken : taskList.mAppTokens) {
+            tmpRemoveAppWindowsLocked(wtoken);
         }
-        displayContent.mTaskLists.add(taskList);
-        displayContent.verifyAppTokens();
+
+        // And now add them back at the correct place.
+        // Where to start adding?
+        int pos = findAppWindowInsertionPointLocked(taskList.mAppTokens.get(0));
+        for (AppWindowToken wtoken : taskList.mAppTokens) {
+            if (wtoken != null) {
+                final int newPos = reAddAppWindowsLocked(displayContent, pos, wtoken);
+                if (newPos != pos) {
+                    displayContent.layoutNeeded = true;
+                }
+                pos = newPos;
+            }
+        }
+        if (!updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
+            false /*updateInputWindows*/)) {
+            assignLayersLocked(displayContent.getWindowList());
+        }
+
+        if (DEBUG_TASK_MOVEMENT) {
+            // Compare windowsAtStart with current windows.
+            if (windowsAtStart.size() != windows.size()) {
+                Slog.e(TAG, "moveTaskWindowsLocked: Mismatch in size!");
+            }
+            for (int i = 0; i < windowsAtStart.size(); i++) {
+                if (windowsAtStart.get(i) != windows.get(i)) {
+                    Slog.e(TAG, "moveTaskWindowsLocked: Mismatch at " + i
+                            + " app=" + windowsAtStart.get(i) + " task=" + windows.get(i));
+                }
+            }
+        }
+
+        updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
+                false /*updateInputWindows*/);
+        mInputMonitor.setUpdateInputWindowsNeededLw();
+        performLayoutAndPlaceSurfacesLocked();
+        mInputMonitor.updateInputWindowsLw(false /*force*/);
+
+        //dump();
+    }
+
+    public void moveTaskToTop(int taskId) {
+        final long origId = Binder.clearCallingIdentity();
+        try {
+            synchronized(mWindowMap) {
+                DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
+                if (displayContent == null) {
+                    Slog.e(TAG, "moveTaskToTop: taskId=" + taskId
+                            + " not found in mTaskIdToDisplayContents");
+                    return;
+                }
+                TaskList taskList = displayContent.mTaskIdToTaskList.get(taskId);
+                if (taskList == null) {
+                    Slog.e(TAG, "moveTaskToTop: taskId=" + taskId
+                            + " not found in mTaskIdToTaskLists");
+                    return;
+                }
+                if (!displayContent.mTaskLists.remove(taskList)) {
+                    Slog.e(TAG, "moveTaskToTop: taskId=" + taskId + " not found in mTaskLists");
+                }
+                displayContent.mTaskLists.add(taskList);
+                displayContent.verifyAppTokens();
+
+                displayContent.refillAnimatingAppTokens();
+                moveTaskWindowsLocked(taskId);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(origId);
+        }
     }
 
     public void moveTaskToBottom(int taskId) {
-        DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
-        if (displayContent == null) {
-            Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId
-                    + " not found in mTaskIdToDisplayContents");
-            return;
+        final long origId = Binder.clearCallingIdentity();
+        try {
+            synchronized(mWindowMap) {
+                DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
+                if (displayContent == null) {
+                    Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId
+                            + " not found in mTaskIdToDisplayContents");
+                    return;
+                }
+                TaskList taskList = displayContent.mTaskIdToTaskList.get(taskId);
+                if (taskList == null) {
+                    Slog.e(TAG, "moveTaskToTopBottom: taskId=" + taskId
+                            + " not found in mTaskIdToTaskLists");
+                    return;
+                }
+                if (!displayContent.mTaskLists.remove(taskList)) {
+                    Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId + " not found in mTaskLists");
+                }
+                displayContent.mTaskLists.add(0, taskList);
+                displayContent.verifyAppTokens();
+
+                displayContent.refillAnimatingAppTokens();
+                moveTaskWindowsLocked(taskId);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(origId);
         }
-        TaskList taskList = displayContent.mTaskIdToTaskList.get(taskId);
-        if (taskList == null) {
-            Slog.e(TAG, "moveTaskToTopBottomtaskId=" + taskId + " not found in mTaskIdToTaskLists");
-            return;
-        }
-        if (!displayContent.mTaskLists.remove(taskList)) {
-            Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId + " not found in mTaskLists");
-        }
-        displayContent.mTaskLists.add(0, taskList);
-        displayContent.verifyAppTokens();
     }
 
     // -------------------------------------------------------------
@@ -7028,11 +7170,9 @@
                     synchronized (mWindowMap) {
                         Slog.w(TAG, "App freeze timeout expired.");
                         DisplayContent displayContent = getDefaultDisplayContentLocked();
-                        AppTokenList appTokens = displayContent.mAppTokens;
-                        int i = appTokens.size();
-                        while (i > 0) {
-                            i--;
-                            AppWindowToken tok = appTokens.get(i);
+                        AppTokenIterator iterator = displayContent.new AppTokenIterator(true);
+                        while (iterator.hasNext()) {
+                            AppWindowToken tok = iterator.next();
                             if (tok.mAppAnimator.freezingScreen) {
                                 Slog.w(TAG, "Force clearing freeze: " + tok);
                                 unsetAppFreezingScreenLocked(tok, true, true);
diff --git a/services/java/com/android/server/wm/WindowState.java b/services/java/com/android/server/wm/WindowState.java
index 8dda544..e49d20b 100644
--- a/services/java/com/android/server/wm/WindowState.java
+++ b/services/java/com/android/server/wm/WindowState.java
@@ -52,6 +52,12 @@
 import java.util.ArrayList;
 
 class WindowList extends ArrayList<WindowState> {
+    WindowList() {
+        super();
+    }
+    WindowList(WindowList windows) {
+        super(windows);
+    }
 }
 
 /**
diff --git a/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/ImageProcessingActivity.java b/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/ImageProcessingActivity.java
index 32b2771..0a78908 100644
--- a/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/ImageProcessingActivity.java
+++ b/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/ImageProcessingActivity.java
@@ -32,6 +32,12 @@
 import android.widget.TextView;
 import android.view.View;
 import android.util.Log;
+import android.renderscript.ScriptC;
+import android.renderscript.RenderScript;
+import android.renderscript.Type;
+import android.renderscript.Allocation;
+import android.renderscript.Element;
+import android.renderscript.Script;
 
 import android.os.Environment;
 import java.io.BufferedWriter;
@@ -44,6 +50,11 @@
     private final String TAG = "Img";
     public final String RESULT_FILE = "image_processing_result.csv";
 
+    RenderScript mRS;
+    Allocation mInPixelsAllocation;
+    Allocation mInPixelsAllocation2;
+    Allocation mOutPixelsAllocation;
+
     /**
      * Define enum type for test names
      */
@@ -408,6 +419,13 @@
         mBenchmarkResult = (TextView) findViewById(R.id.benchmarkText);
         mBenchmarkResult.setText("Result: not run");
 
+
+        mRS = RenderScript.create(this);
+        mInPixelsAllocation = Allocation.createFromBitmap(mRS, mBitmapIn);
+        mInPixelsAllocation2 = Allocation.createFromBitmap(mRS, mBitmapIn2);
+        mOutPixelsAllocation = Allocation.createFromBitmap(mRS, mBitmapOut);
+
+
         setupTests();
         changeTest(TestName.LEVELS_VEC3_RELAXED);
     }
diff --git a/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/TestBase.java b/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/TestBase.java
index faef83aa..a353d9c 100644
--- a/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/TestBase.java
+++ b/tests/RenderScriptTests/ImageProcessing/src/com/android/rs/image/TestBase.java
@@ -45,7 +45,6 @@
     protected Allocation mInPixelsAllocation;
     protected Allocation mInPixelsAllocation2;
     protected Allocation mOutPixelsAllocation;
-
     protected ImageProcessingActivity act;
 
     private class MessageProcessor extends RenderScript.RSMessageHandler {
@@ -107,12 +106,12 @@
 
     public final void createBaseTest(ImageProcessingActivity ipact, Bitmap b, Bitmap b2, Bitmap outb) {
         act = ipact;
-        mRS = RenderScript.create(act);
+        mRS = ipact.mRS;
         mRS.setMessageHandler(new MessageProcessor(act));
 
-        mInPixelsAllocation = Allocation.createFromBitmap(mRS, b);
-        mInPixelsAllocation2 = Allocation.createFromBitmap(mRS, b2);
-        mOutPixelsAllocation = Allocation.createFromBitmap(mRS, outb);
+        mInPixelsAllocation = ipact.mInPixelsAllocation;
+        mInPixelsAllocation2 = ipact.mInPixelsAllocation2;
+        mOutPixelsAllocation = ipact.mOutPixelsAllocation;
 
         createTest(act.getResources());
     }
@@ -135,8 +134,7 @@
     }
 
     public void destroy() {
-        mRS.destroy();
-        mRS = null;
+        mRS.setMessageHandler(null);
     }
 
     public void updateBitmap(Bitmap b) {
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_foreach_bounds.java b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_foreach_bounds.java
index 782f788..97f3a32 100644
--- a/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_foreach_bounds.java
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_foreach_bounds.java
@@ -33,6 +33,10 @@
         Type.Builder typeBuilder = new Type.Builder(RS, Element.I32(RS));
         int X = 5;
         int Y = 7;
+        final int xStart = 2;
+        final int xEnd = 5;
+        final int yStart = 3;
+        final int yEnd = 6;
         s.set_dimX(X);
         s.set_dimY(Y);
         typeBuilder.setX(X).setY(Y);
@@ -41,12 +45,16 @@
         s.set_s(s);
         s.set_ain(A);
         s.set_aout(A);
-        s.set_xStart(2);
-        s.set_xEnd(5);
-        s.set_yStart(3);
-        s.set_yEnd(6);
+        s.set_xStart(xStart);
+        s.set_xEnd(xEnd);
+        s.set_yStart(yStart);
+        s.set_yEnd(yEnd);
         s.forEach_zero(A);
 
+        Script.LaunchOptions sc = new Script.LaunchOptions();
+        sc.setX(xStart, xEnd).setY(yStart, yEnd);
+        s.forEach_root(A, sc);
+
         return;
     }
 
@@ -55,6 +63,7 @@
         ScriptC_foreach_bounds s = new ScriptC_foreach_bounds(pRS);
         pRS.setMessageHandler(mRsMessage);
         initializeGlobals(pRS, s);
+        s.invoke_verify_root();
         s.invoke_foreach_bounds_test();
         pRS.finish();
         waitForMessage();
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/foreach_bounds.rs b/tests/RenderScriptTests/tests/src/com/android/rs/test/foreach_bounds.rs
index 89df090..fa76390 100644
--- a/tests/RenderScriptTests/tests/src/com/android/rs/test/foreach_bounds.rs
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/foreach_bounds.rs
@@ -7,6 +7,8 @@
 int yStart = 0;
 int yEnd = 0;
 
+static bool failed = false;
+
 rs_script s;
 rs_allocation aRaw;
 rs_allocation ain;
@@ -27,9 +29,6 @@
     for (j = 0; j < dimY; j++) {
         for (i = 0; i < dimX; i++) {
             int v = rsGetElementAt_int(aRaw, i, j);
-            rsDebug("i: ", i);
-            rsDebug("j: ", j);
-            rsDebug("a[j][i]: ", v);
             if (i < xStart || i >= xEnd || j < yStart || j >= yEnd) {
                 _RS_ASSERT(v == 0);
             } else {
@@ -48,20 +47,11 @@
     return failed;
 }
 
-void foreach_bounds_test() {
-    static bool failed = false;
-
-    rs_script_call_t rssc = {0};
-    rssc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
-    rssc.xStart = xStart;
-    rssc.xEnd = xEnd;
-    rssc.yStart = yStart;
-    rssc.yEnd = yEnd;
-
-    rsForEach(s, ain, aout, NULL, 0, &rssc);
-
+void verify_root() {
     failed |= test_root_output();
+}
 
+void foreach_bounds_test() {
     if (failed) {
         rsSendToClientBlocking(RS_MSG_TEST_FAILED);
     }
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
index 8701cc8..2414d70 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
@@ -188,6 +188,11 @@
         return delegate.mStyle;
     }
 
+    @LayoutlibDelegate
+    /*package*/ static void setGammaForText(float blackGamma, float whiteGamma) {
+        // This is for device testing only: pass
+    }
+
     // ---- Private delegate/helper methods ----
 
     private Typeface_Delegate(String family, int style) {
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index bf82792..b971fc33 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -277,7 +277,6 @@
     /**
      * The enterprise configuration details specifying the EAP method,
      * certificates and other settings associated with the EAP.
-     * @hide
      */
     public WifiEnterpriseConfig enterpriseConfig;
 
diff --git a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
index 7313e7e..95ffb1c 100644
--- a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
+++ b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
@@ -42,7 +42,10 @@
 import java.util.HashMap;
 import java.util.Map;
 
-/** Enterprise configuration details for Wi-Fi @hide */
+/** 
+ * Enterprise configuration details for Wi-Fi. Stores details about the EAP method
+ * and any associated credentials.
+ */
 public class WifiEnterpriseConfig implements Parcelable {
     private static final String TAG = "WifiEnterpriseConfig";
     /**
@@ -211,22 +214,32 @@
                 }
             };
 
+    /** The Extensible Authentication Protocol method used */
     public static final class Eap {
-        /* NONE represents an empty enterprise config */
+        /** No EAP method used. Represents an empty config */
         public static final int NONE    = -1;
+        /** Protected EAP */
         public static final int PEAP    = 0;
+        /** EAP-Transport Layer Security */
         public static final int TLS     = 1;
+        /** EAP-Tunneled Transport Layer Security */
         public static final int TTLS    = 2;
+        /** EAP-Password */
         public static final int PWD     = 3;
         /** @hide */
         public static final String[] strings = { "PEAP", "TLS", "TTLS", "PWD" };
     }
 
+    /** The inner authentication method used */
     public static final class Phase2 {
         public static final int NONE        = 0;
+        /** Password Authentication Protocol */
         public static final int PAP         = 1;
+        /** Microsoft Challenge Handshake Authentication Protocol */
         public static final int MSCHAP      = 2;
+        /** Microsoft Challenge Handshake Authentication Protocol v2 */
         public static final int MSCHAPV2    = 3;
+        /** Generic Token Card */
         public static final int GTC         = 4;
         private static final String PREFIX = "auth=";
         /** @hide */
@@ -249,6 +262,7 @@
      * Set the EAP authentication method.
      * @param  eapMethod is one {@link Eap#PEAP}, {@link Eap#TLS}, {@link Eap#TTLS} or
      *                   {@link Eap#PWD}
+     * @throws IllegalArgumentException on an invalid eap method
      */
     public void setEapMethod(int eapMethod) {
         switch (eapMethod) {
@@ -279,6 +293,7 @@
      * @param phase2Method is the inner authentication method and can be one of {@link Phase2#NONE},
      *                     {@link Phase2#PAP}, {@link Phase2#MSCHAP}, {@link Phase2#MSCHAPV2},
      *                     {@link Phase2#GTC}
+     * @throws IllegalArgumentException on an invalid phase2 method
      *
      */
     public void setPhase2Method(int phase2Method) {
@@ -378,7 +393,10 @@
      * Specify a X.509 certificate that identifies the server.
      *
      * <p>A default name is automatically assigned to the certificate and used
-     * with this configuration.
+     * with this configuration. The framework takes care of installing the
+     * certificate when the config is saved and removing the certificate when
+     * the config is removed.
+     *
      * @param cert X.509 CA certificate
      * @throws IllegalArgumentException if not a CA certificate
      */
@@ -425,9 +443,13 @@
      * Specify a private key and client certificate for client authorization.
      *
      * <p>A default name is automatically assigned to the key entry and used
-     * with this configuration.
+     * with this configuration.  The framework takes care of installing the
+     * key entry when the config is saved and removing the key entry when
+     * the config is removed.
+
      * @param privateKey
      * @param clientCertificate
+     * @throws IllegalArgumentException for an invalid key or certificate.
      */
     public void setClientKeyEntry(PrivateKey privateKey, X509Certificate clientCertificate) {
         if (clientCertificate != null) {