Merge "Make TimePicker/DatePicker/CalendarView render in Eclipse." into honeycomb
diff --git a/build/phone-hdpi-512-dalvik-heap.mk b/build/phone-hdpi-512-dalvik-heap.mk
index 630cf03..788b686 100644
--- a/build/phone-hdpi-512-dalvik-heap.mk
+++ b/build/phone-hdpi-512-dalvik-heap.mk
@@ -19,5 +19,5 @@
 
 PRODUCT_PROPERTY_OVERRIDES += \
     dalvik.vm.heapstartsize=5m \
-    dalvik.vm.growthlimit=32m \
+    dalvik.vm.heapgrowthlimit=32m \
     dalvik.vm.heapsize=128m
diff --git a/build/tablet-dalvik-heap.mk b/build/tablet-dalvik-heap.mk
index 37c3ec5..826a380 100644
--- a/build/tablet-dalvik-heap.mk
+++ b/build/tablet-dalvik-heap.mk
@@ -18,5 +18,5 @@
 
 PRODUCT_PROPERTY_OVERRIDES += \
     dalvik.vm.heapstartsize=5m \
-    dalvik.vm.growthlimit=48m \
+    dalvik.vm.heapgrowthlimit=48m \
     dalvik.vm.heapsize=256m
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 6c5bdb6..393412f 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -73,7 +73,6 @@
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.List;
 import java.util.WeakHashMap;
 
 /**
@@ -2375,6 +2374,7 @@
     })
     int mLayerType = LAYER_TYPE_NONE;
     Paint mLayerPaint;
+    Rect mLocalDirtyRect;
 
     /**
      * Simple constructor to use when creating a view from code.
@@ -6910,7 +6910,7 @@
      * well. This is usually true for a full invalidate, but may be set to false if the
      * View's contents or dimensions have not changed.
      */
-    private void invalidate(boolean invalidateCache) {
+    void invalidate(boolean invalidateCache) {
         if (ViewDebug.TRACE_HIERARCHY) {
             ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
         }
@@ -8173,7 +8173,9 @@
         }
 
         mLayerType = layerType;
-        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
+        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
+        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
+        mLocalDirtyRect = layerDisabled ? null : new Rect();
 
         invalidateParentCaches();
         invalidate(true);
@@ -8228,8 +8230,7 @@
             mAttachInfo.mHardwareCanvas = canvas;
             try {
                 canvas.setViewport(width, height);
-                // TODO: We should pass the dirty rect
-                canvas.onPreDraw(null);
+                canvas.onPreDraw(mLocalDirtyRect);
 
                 final int restoreCount = canvas.save();
 
@@ -8251,6 +8252,7 @@
                 canvas.onPostDraw();
                 mHardwareLayer.end(currentCanvas);
                 mAttachInfo.mHardwareCanvas = currentCanvas;
+                mLocalDirtyRect.setEmpty();
             }
         }
 
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index f0aaf3f..09e1d89 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -347,6 +347,10 @@
     // views during a transition when they otherwise would have become gone/invisible
     private ArrayList<View> mVisibilityChangingChildren;
 
+    // Indicates whether this container will use its children layers to draw
+    @ViewDebug.ExportedProperty(category = "drawing")
+    private boolean mDrawLayers = true;
+
     public ViewGroup(Context context) {
         super(context);
         initViewGroup();
@@ -2147,7 +2151,7 @@
         flags = mGroupFlags;
 
         if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
-            invalidate();
+            invalidate(true);
         }
 
         if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
@@ -2203,7 +2207,7 @@
             }
         }
 
-        invalidate();
+        invalidate(true);
     }
 
     /**
@@ -2262,7 +2266,7 @@
 
         boolean scalingRequired = false;
         boolean caching;
-        int layerType = child.getLayerType();
+        int layerType = mDrawLayers ? child.getLayerType() : LAYER_TYPE_NONE;
 
         final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
         if ((flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE ||
@@ -2539,10 +2543,10 @@
             // invalidation is the trigger to recreate display lists, so if we're using
             // display lists to render, force an invalidate to allow the animation to
             // continue drawing another frame
-            invalidate();
+            invalidate(true);
             if (a instanceof AlphaAnimation) {
                 // alpha animations should cause the child to recreate its display list
-                child.invalidate();
+                child.invalidate(true);
             }
         }
 
@@ -2552,6 +2556,17 @@
     }
 
     /**
+     * 
+     * @param enabled True if children should be drawn with layers, false otherwise.
+     * 
+     * @hide
+     */
+    public void setChildrenLayersEnabled(boolean enabled) {
+        mDrawLayers = enabled;
+        invalidate(true);
+    }
+
+    /**
      * By default, children are clipped to their bounds before drawing. This
      * allows view groups to override this behavior for animations, etc.
      *
@@ -2583,7 +2598,6 @@
         final View[] children = mChildren;
         final int count = mChildrenCount;
         for (int i = 0; i < count; i++) {
-
             children[i].setSelected(selected);
         }
     }
@@ -2596,7 +2610,6 @@
         final View[] children = mChildren;
         final int count = mChildrenCount;
         for (int i = 0; i < count; i++) {
-
             children[i].setActivated(activated);
         }
     }
@@ -2789,7 +2802,7 @@
         // therefore, we call requestLayout() on ourselves before, so that the child's request
         // will be blocked at our level
         requestLayout();
-        invalidate();
+        invalidate(true);
         addViewInner(child, index, params, false);
     }
 
@@ -3071,7 +3084,7 @@
     public void removeView(View view) {
         removeViewInternal(view);
         requestLayout();
-        invalidate();
+        invalidate(true);
     }
 
     /**
@@ -3103,7 +3116,7 @@
     public void removeViewAt(int index) {
         removeViewInternal(index, getChildAt(index));
         requestLayout();
-        invalidate();
+        invalidate(true);
     }
 
     /**
@@ -3115,7 +3128,7 @@
     public void removeViews(int start, int count) {
         removeViewsInternal(start, count);
         requestLayout();
-        invalidate();
+        invalidate(true);
     }
 
     private void removeViewInternal(View view) {
@@ -3240,7 +3253,7 @@
     public void removeAllViews() {
         removeAllViewsInLayout();
         requestLayout();
-        invalidate();
+        invalidate(true);
     }
 
     /**
@@ -3474,16 +3487,19 @@
                 if (child.mLayerType != LAYER_TYPE_NONE) {
                     mPrivateFlags |= INVALIDATED;
                     mPrivateFlags &= ~DRAWING_CACHE_VALID;
+                    child.mLocalDirtyRect.setEmpty();
                 }
                 do {
                     View view = null;
                     if (parent instanceof View) {
                         view = (View) parent;
-                        if (view.mLayerType != LAYER_TYPE_NONE &&
-                                view.getParent() instanceof View) {
-                            final View grandParent = (View) view.getParent();
-                            grandParent.mPrivateFlags |= INVALIDATED;
-                            grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
+                        if (view.mLayerType != LAYER_TYPE_NONE) {
+                            view.mLocalDirtyRect.setEmpty();
+                            if (view.getParent() instanceof View) {
+                                final View grandParent = (View) view.getParent();
+                                grandParent.mPrivateFlags |= INVALIDATED;
+                                grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
+                            }
                         }
                         if ((view.mPrivateFlags & DIRTY_MASK) != 0) {
                             // already marked dirty - we're done
@@ -3521,6 +3537,12 @@
                 // Make sure we do not set both flags at the same time
                 int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
 
+                if (child.mLayerType != LAYER_TYPE_NONE) {
+                    mPrivateFlags |= INVALIDATED;
+                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
+                    child.mLocalDirtyRect.union(dirty);
+                }
+
                 final int[] location = attachInfo.mInvalidateChildLocation;
                 location[CHILD_LEFT_INDEX] = child.mLeft;
                 location[CHILD_TOP_INDEX] = child.mTop;
@@ -3534,10 +3556,6 @@
                             (int) (boundingRect.bottom + 0.5f));
                 }
 
-                if (child.mLayerType != LAYER_TYPE_NONE) {
-                    mPrivateFlags |= INVALIDATED;
-                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
-                }                
                 do {
                     View view = null;
                     if (parent instanceof View) {
@@ -3618,6 +3636,10 @@
                     location[CHILD_LEFT_INDEX] = left;
                     location[CHILD_TOP_INDEX] = top;
 
+                    if (mLayerType != LAYER_TYPE_NONE) {
+                        mLocalDirtyRect.union(dirty);
+                    }
+
                     return mParent;
                 }
             } else {
@@ -3626,8 +3648,11 @@
                 location[CHILD_LEFT_INDEX] = mLeft;
                 location[CHILD_TOP_INDEX] = mTop;
 
-                dirty.set(0, 0, mRight - location[CHILD_LEFT_INDEX],
-                        mBottom - location[CHILD_TOP_INDEX]);
+                dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
+
+                if (mLayerType != LAYER_TYPE_NONE) {
+                    mLocalDirtyRect.union(dirty);
+                }
 
                 return mParent;
             }
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index f91ae9f..fa99eae 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -7144,6 +7144,16 @@
                     setContentScrollTo(msg.arg1, msg.arg2);
                     break;
                 case SCROLL_TO_MSG_ID:
+                    if (((Boolean) msg.obj).booleanValue()) {
+                        // This scroll is intended to bring the textfield into
+                        // view, but is only necessary if the IME is showing
+                        InputMethodManager imm = InputMethodManager.peekInstance();
+                        if (imm == null || !imm.isAcceptingText()
+                                || (!imm.isActive(WebView.this) && (!inEditingMode()
+                                || !imm.isActive(mWebTextView)))) {
+                            break;
+                        }
+                    }
                     if (setContentScrollTo(msg.arg1, msg.arg2)) {
                         // if we can't scroll to the exact position due to pin,
                         // send a message to WebCore to re-scroll when we get a
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index b949a41..5bdf408 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -2120,7 +2120,7 @@
     }
 
     // called by JNI
-    private void contentScrollTo(int x, int y) {
+    private void contentScrollTo(int x, int y, boolean onlyIfImeIsShowing) {
         if (!mBrowserFrame.firstLayoutDone()) {
             /*
              * WebKit restore state will be called before didFirstLayout(),
@@ -2133,7 +2133,8 @@
         }
         if (mWebView != null) {
             Message msg = Message.obtain(mWebView.mPrivateHandler,
-                    WebView.SCROLL_TO_MSG_ID, x, y);
+                    WebView.SCROLL_TO_MSG_ID, x, y,
+                    Boolean.valueOf(onlyIfImeIsShowing));
             if (mDrawIsScheduled) {
                 mEventHub.sendMessage(Message.obtain(null,
                         EventHub.MESSAGE_RELAY, msg));
diff --git a/core/res/res/drawable-hdpi/ic_emergency.png b/core/res/res/drawable-hdpi/ic_emergency.png
index b4465ff..89c05e3 100644
--- a/core/res/res/drawable-hdpi/ic_emergency.png
+++ b/core/res/res/drawable-hdpi/ic_emergency.png
Binary files differ
diff --git a/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml b/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
index 16bfc31..1783088 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
@@ -61,7 +61,6 @@
                 android:textSize="24sp"
                 android:textAppearance="?android:attr/textAppearanceMedium"
                 android:background="@drawable/lockscreen_password_field_dark"
-                android:hint="@string/keyguard_password_entry_touch_hint"
                 android:textColor="#ffffffff"
                 />
 
diff --git a/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml b/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
index b87b51f..63241dd 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
@@ -57,7 +57,6 @@
             android:layout_marginBottom="5dip"
             android:textAppearance="?android:attr/textAppearanceMedium"
             android:background="@drawable/lockscreen_password_field_dark"
-            android:hint="@string/keyguard_password_entry_touch_hint"
             android:textColor="#ffffffff"
             />
 
diff --git a/data/sounds/alarms/ogg/Cesium.ogg b/data/sounds/alarms/ogg/Cesium.ogg
index 76eca08..a8c379a 100644
--- a/data/sounds/alarms/ogg/Cesium.ogg
+++ b/data/sounds/alarms/ogg/Cesium.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/LowBattery.ogg b/data/sounds/effects/ogg/LowBattery.ogg
index c21218c..dfb5d88 100644
--- a/data/sounds/effects/ogg/LowBattery.ogg
+++ b/data/sounds/effects/ogg/LowBattery.ogg
Binary files differ
diff --git a/docs/html/guide/developing/building/index.jd b/docs/html/guide/developing/building/index.jd
index b001ebc..25a6e23 100644
--- a/docs/html/guide/developing/building/index.jd
+++ b/docs/html/guide/developing/building/index.jd
@@ -37,7 +37,7 @@
   
   <p>The following diagram depicts the components involved in building and running an application:</p>
 
-  <img src="/images/build-simplified.png" />
+  <img src="{@docRoot}images/build-simplified.png" />
 
   <h2 id="detailed-build">A Detailed Look at the Build Process</h2>
 
@@ -49,7 +49,7 @@
   tools and processes are masked from you. The following diagram depicts the different tools and
   processes that are involved in a build:</p>
 
-  <p><img src="/images/build.png" /></p>
+  <p><img src="{@docRoot}images/build.png" /></p>
 
   <p>The general process for a typical build is outlined below:</p>
 
diff --git a/docs/html/guide/developing/debugging/debugging-tracing.jd b/docs/html/guide/developing/debugging/debugging-tracing.jd
index dcc889d..0401966 100644
--- a/docs/html/guide/developing/debugging/debugging-tracing.jd
+++ b/docs/html/guide/developing/debugging/debugging-tracing.jd
@@ -67,7 +67,7 @@
   selected method. The method in this case is <code>LoadListener.nativeFinished()</code> and it was selected in
   the profile view.</p>
 
-  <img src="/images/traceview_timeline.png"
+  <img src="{@docRoot}images/traceview_timeline.png"
        alt="Traceview timeline panel"
        width="893"
        height="284" />
@@ -87,7 +87,7 @@
   <code>LoadListener.nativeFinished();</code> looking at the timeline panel shows that one of those calls took
   an unusually long time.</p>
 
-  <img src="/images/traceview_profile.png"
+  <img src="{@docRoot}images/traceview_profile.png"
        alt="Traceview profile panel."
        width="892"
        height="630" />
diff --git a/docs/html/guide/developing/debugging/index.jd b/docs/html/guide/developing/debugging/index.jd
index f9202ce..1f1a4ca 100644
--- a/docs/html/guide/developing/debugging/index.jd
+++ b/docs/html/guide/developing/debugging/index.jd
@@ -62,7 +62,7 @@
 
   <p>Figure 1 shows how the various debugging tools work together in a typical
   debugging environment.</p>
-  <img src="/images/debugging.png"
+  <img src="{@docRoot}images/debugging.png"
         alt="Debugging workflow" />
   <p class="img-caption><strong>Figure 1. </strong> Debugging Workflow</p>
 
diff --git a/docs/html/guide/developing/devices/emulator.jd b/docs/html/guide/developing/devices/emulator.jd
index a3cd5c5..53c1407 100644
--- a/docs/html/guide/developing/devices/emulator.jd
+++ b/docs/html/guide/developing/devices/emulator.jd
@@ -33,7 +33,7 @@
 </div>
 </div>
 
-<img src="/images/emulator-wvga800l.png" alt="Image of the Android Emulator"
+<img src="{@docRoot}images/emulator-wvga800l.png" alt="Image of the Android Emulator"
 width="367" height="349" style="margin-left:2em;float:right;"/>
 <p>The Android SDK includes a virtual mobile device emulator
 that runs on your computer. The emulator lets you prototype, develop, and test
diff --git a/docs/html/guide/developing/projects/index.jd b/docs/html/guide/developing/projects/index.jd
index 45fd5a1..609a71a 100644
--- a/docs/html/guide/developing/projects/index.jd
+++ b/docs/html/guide/developing/projects/index.jd
@@ -471,7 +471,7 @@
 <code>MyLibrary/src</code>. Eclipse shows an error on one of them because they
 are duplicate links to a single class.</p> 
  
-<img src="/images/developing/lib-migration-0.png" alt=""> 
+<img src="{@docRoot}images/developing/lib-migration-0.png" alt=""> 
 <p class="img-caption"><strong>Figure 1.</strong> Library project migration error</p>
 <p>To fix the error, remove the linked folder that <em>does not</em> contain the
 <code>_src</code> suffix. </p> 
@@ -481,14 +481,14 @@
 <code>MyLibrary</code> folder) and choose <strong>Build Path</strong> &gt;
 <strong>Remove from Build Path</strong>, as shown in figure 2.</li> 
  
-<img src="/images/developing/lib-migration-1.png" style="height:600px"
+<img src="{@docRoot}images/developing/lib-migration-1.png" style="height:600px"
 alt=""> 
 <p class="img-caption"><strong>Figure 2.</strong> Remove from Build Path menu item</p>
  
 <li>Next, when asked about unlinking the folder from the project, select
 <strong>Yes</strong>, as shown in figure 3.</li> 
  
-<img src="/images/developing/lib-migration-2.png" alt=""> 
+<img src="{@docRoot}images/developing/lib-migration-2.png" alt=""> 
 
 <p class="img-caption"><strong>Figure 3.</strong> Unlink folder confirmation window</p>
 </ol> 
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 270d153..cf0593c 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -466,34 +466,34 @@
           <li><a href="<?cs var:toroot ?>guide/developing/tools/logcat.html">logcat</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/mksdcard.html">mksdcard</a></li>
 
-          <li><a href="/guide/developing/tools/monkey.html">Monkey</a></li>
+          <li><a href="<?cs var:toroot ?>guide/developing/tools/monkey.html">Monkey</a></li>
               <li class="toggle-list">
                  <div>
-                     <a href="/guide/developing/tools/monkeyrunner_concepts.html">
+                     <a href="<?cs var:toroot ?>guide/developing/tools/monkeyrunner_concepts.html">
                      <span class="en">monkeyrunner</span>
                   </a>
                   </div>
                   <ul>
                       <li>
-                          <a href="/guide/developing/tools/MonkeyDevice.html">
+                          <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyDevice.html">
                                 <span class="en">MonkeyDevice</span>
                         </a>
                     </li>
                     <li>
-                        <a href="/guide/developing/tools/MonkeyImage.html">
+                        <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyImage.html">
                             <span class="en">MonkeyImage</span>
                         </a>
                     </li>
                     <li>
-                        <a href="/guide/developing/tools/MonkeyRunner.html">
+                        <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyRunner.html">
                             <span class="en">MonkeyRunner</span>
                         </a>
                     </li>
                   </ul>
               </li>
-              <li><a href="/guide/developing/tools/proguard.html">ProGuard</a></li>
-              <li><a href="/guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
-              <li><a href="/guide/developing/tools/traceview.html">Traceview</a></li>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/proguard.html">ProGuard</a></li>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/traceview.html">Traceview</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/zipalign.html">zipalign</a></li>
         </ul>
       </li>
diff --git a/libs/hwui/LayerRenderer.cpp b/libs/hwui/LayerRenderer.cpp
index 691f649..7379b63 100644
--- a/libs/hwui/LayerRenderer.cpp
+++ b/libs/hwui/LayerRenderer.cpp
@@ -16,8 +16,11 @@
 
 #define LOG_TAG "OpenGLRenderer"
 
+#include <ui/Rect.h>
+
 #include "LayerRenderer.h"
 #include "Properties.h"
+#include "Rect.h"
 
 namespace android {
 namespace uirenderer {
@@ -30,12 +33,25 @@
     LAYER_RENDERER_LOGD("Rendering into layer, fbo = %d", mLayer->fbo);
 
 #if RENDER_LAYERS_AS_REGIONS
-    mLayer->region.clear();
+    Rect dirty(left, top, right, bottom);
+    if (dirty.isEmpty() || (dirty.left <= 0 && dirty.top <= 0 &&
+            dirty.right >= mLayer->width && dirty.bottom >= mLayer->height)) {
+        mLayer->region.clear();
+        dirty.set(0.0f, 0.0f, mLayer->width, mLayer->height);
+    } else {
+        dirty.intersect(0.0f, 0.0f, mLayer->width, mLayer->height);
+        android::Rect r(dirty.left, dirty.top, dirty.right, dirty.bottom);
+        mLayer->region.subtractSelf(r);
+    }
 #endif
 
     glBindFramebuffer(GL_FRAMEBUFFER, mLayer->fbo);
 
+#if RENDER_LAYERS_AS_REGIONS
+    OpenGLRenderer::prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
+#else
     OpenGLRenderer::prepareDirty(0.0f, 0.0f, mLayer->width, mLayer->height, opaque);
+#endif
 }
 
 void LayerRenderer::finish() {
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 2960395..90d6ea1 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -671,25 +671,7 @@
         finishDrawTexture();
 
 #if DEBUG_LAYERS_AS_REGIONS
-        uint32_t colors[] = {
-                0x7fff0000, 0x7f00ff00,
-                0x7f0000ff, 0x7fff00ff,
-        };
-
-        int offset = 0;
-        int32_t top = rects[0].top;
-        int i = 0;
-
-        for (size_t i = 0; i < count; i++) {
-            if (top != rects[i].top) {
-                offset ^= 0x2;
-                top = rects[i].top;
-            }
-
-            Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
-            drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
-                    SkXfermode::kSrcOver_Mode);
-        }
+        drawRegionRects(layer->region);
 #endif
 
         layer->region.clear();
@@ -699,6 +681,32 @@
 #endif
 }
 
+void OpenGLRenderer::drawRegionRects(const Region& region) {
+#if DEBUG_LAYERS_AS_REGIONS
+    size_t count;
+    const android::Rect* rects = region.getArray(&count);
+
+    uint32_t colors[] = {
+            0x7fff0000, 0x7f00ff00,
+            0x7f0000ff, 0x7fff00ff,
+    };
+
+    int offset = 0;
+    int32_t top = rects[0].top;
+
+    for (size_t i = 0; i < count; i++) {
+        if (top != rects[i].top) {
+            offset ^= 0x2;
+            top = rects[i].top;
+        }
+
+        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
+        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
+                SkXfermode::kSrcOver_Mode);
+    }
+#endif
+}
+
 void OpenGLRenderer::dirtyLayer(const float left, const float top,
         const float right, const float bottom, const mat4 transform) {
 #if RENDER_LAYERS_AS_REGIONS
@@ -1626,6 +1634,10 @@
                     GL_UNSIGNED_SHORT, layer->meshIndices);
 
             finishDrawTexture();
+
+#if DEBUG_LAYERS_AS_REGIONS
+            drawRegionRects(layer->region);
+#endif
         }
     }
 #else
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index 64def03..7bbf034 100644
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -455,6 +455,8 @@
     void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords = NULL, GLuint vbo = 0);
     void finishDrawTexture();
 
+    void drawRegionRects(const Region& region);
+
     /**
      * Should be invoked every time the glScissor is modified.
      */
diff --git a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
index b8d1ca7..297c4df 100644
--- a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
+++ b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
@@ -23,6 +23,7 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
 
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
@@ -2064,6 +2065,20 @@
             effectSettings.alphaBlendingFadeInTimePercent = 100;
             effectSettings.alphaBlendingFadeOutTimePercent = 100;
             effectSettings.framingBuffer = null;
+
+            /*
+             * Set the resized RGB file dimensions
+             */
+            effectSettings.width = overlay.getResizedRGBSizeWidth();
+            if(effectSettings.width == 0) {
+                effectSettings.width = bitmap.getWidth();
+            }
+
+            effectSettings.height = overlay.getResizedRGBSizeHeight();
+            if(effectSettings.height == 0) {
+                effectSettings.height = bitmap.getHeight();
+            }
+
         }
 
         effectSettings.topLeftX = 0;
@@ -2098,6 +2113,11 @@
         return effectSettings;
     }
 
+     /* get Video Editor aspect ratio */
+    int nativeHelperGetAspectRatio() {
+        return mVideoEditor.getAspectRatio();
+    }
+
     /**
      * Sets the audio regenerate flag
      *
@@ -3039,6 +3059,8 @@
                 Log.e(TAG, "Runtime exception in nativeStartPreview");
                 throw ex;
             }
+        } else {
+            throw new IllegalStateException("generatePreview is in progress");
         }
     }
 
@@ -3066,7 +3088,10 @@
     long renderPreviewFrame(Surface surface, long time, int surfaceWidth,
             int surfaceHeight, VideoEditor.OverlayData overlayData) {
         if (mInvalidatePreviewArray) {
-            throw new RuntimeException("Call generate preview first");
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, "Call generate preview first");
+            }
+            throw new IllegalStateException("Call generate preview first");
         }
 
         long timeMs = 0;
@@ -3894,6 +3919,27 @@
     }
 
     /**
+     * Tries to grab the semaphore with a specified time out which arbitrates access to the editor
+     *
+     * @param timeoutMs time out in ms.
+     *
+     * @return true if the semaphore is acquired, false otherwise
+     * @throws InterruptedException
+     */
+    boolean lock(long timeoutMs) throws InterruptedException {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbing semaphore with timeout " + timeoutMs, new Throwable());
+        }
+
+        boolean acquireSem = mLock.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS);
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbed semaphore status " + acquireSem);
+        }
+
+        return acquireSem;
+    }
+
+    /**
      * Release the semaphore which arbitrates access to the editor
      */
     void unlock() {
diff --git a/media/java/android/media/videoeditor/MediaItem.java b/media/java/android/media/videoeditor/MediaItem.java
index e3ef599..dfe0bae 100755
--- a/media/java/android/media/videoeditor/MediaItem.java
+++ b/media/java/android/media/videoeditor/MediaItem.java
@@ -187,6 +187,10 @@
         if (mEndTransition != null) {
             mEndTransition.invalidate();
         }
+
+        for (Overlay overlay : mOverlays) {
+            ((OverlayFrame)overlay).invalidateGeneratedFiles();
+        }
     }
 
     /**
diff --git a/media/java/android/media/videoeditor/OverlayFrame.java b/media/java/android/media/videoeditor/OverlayFrame.java
index 2bb9a1c..131f5f0 100755
--- a/media/java/android/media/videoeditor/OverlayFrame.java
+++ b/media/java/android/media/videoeditor/OverlayFrame.java
@@ -21,15 +21,19 @@
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
-
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Bitmap.CompressFormat;
-
 import java.io.DataOutputStream;
 import java.nio.ByteBuffer;
 import java.nio.IntBuffer;
 
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Bitmap.CompressFormat;
+import android.util.Pair;
+
+
 /**
  * This class is used to overlay an image on top of a media item.
  * {@hide}
@@ -46,6 +50,17 @@
     private int mOFHeight;
 
     /**
+     * resized RGB Image dimensions
+     */
+    private int mResizedRGBWidth;
+    private int mResizedRGBHeight;
+
+    /**
+     *  The resize paint
+     */
+    private static final Paint sResizePaint = new Paint(Paint.FILTER_BITMAP_FLAG);
+
+    /**
      * An object of this type cannot be instantiated by using the default
      * constructor
      */
@@ -74,6 +89,8 @@
         mBitmap = bitmap;
         mFilename = null;
         mBitmapFileName = null;
+        mResizedRGBWidth = 0;
+        mResizedRGBHeight = 0;
     }
 
     /**
@@ -95,6 +112,8 @@
         mBitmapFileName = filename;
         mBitmap = BitmapFactory.decodeFile(mBitmapFileName);
         mFilename = null;
+        mResizedRGBWidth = 0;
+        mResizedRGBHeight = 0;
     }
 
     /**
@@ -182,32 +201,23 @@
         mOFHeight = mBitmap.getHeight();
 
         mFilename = path + "/" + "Overlay" + getId() + ".rgb";
-        if (!(new File(mFilename).exists())) {
-            /**
-             * Save the image to a file ; as a rgb
-             */
-            final FileOutputStream fl = new FileOutputStream(mFilename);
-            final DataOutputStream dos = new DataOutputStream(fl);
 
-            /**
-             * populate the rgb file with bitmap data
-             */
-            final int [] framingBuffer = new int[mOFWidth];
-            ByteBuffer byteBuffer = ByteBuffer.allocate(framingBuffer.length * 4);
-            IntBuffer intBuffer;
+        /* resize and save rgb as per project aspect ratio */
+        MediaArtistNativeHelper nativeHelper = (super.getMediaItem()).getNativeContext();
 
-            byte[] array = byteBuffer.array();
-            int tmp = 0;
-            while(tmp < mOFHeight) {
-                mBitmap.getPixels(framingBuffer,0,mOFWidth,0,tmp,mOFWidth,1);
-                intBuffer = byteBuffer.asIntBuffer();
-                intBuffer.put(framingBuffer,0,mOFWidth);
-                dos.write(array);
-                tmp += 1;
-            }
-            fl.flush();
-            fl.close();
-        }
+        /* get height and width for story board aspect ratio */
+        final Pair<Integer, Integer> maxResolution;
+        final Pair<Integer, Integer>[] resolutions;
+        resolutions = MediaProperties.getSupportedResolutions(nativeHelper.nativeHelperGetAspectRatio());
+
+        // Get the highest resolution
+        maxResolution = resolutions[resolutions.length - 1];
+
+        /* Generate the rgb file with rendering mode */
+        generateOverlayWithRenderingMode (super.getMediaItem(), this,
+                maxResolution.second /* max Height */ ,
+                maxResolution.first /* max Width */);
+
         return mFilename;
     }
 
@@ -238,6 +248,30 @@
      void setOverlayFrameWidth(int width) {
          mOFWidth = width;
      }
+
+    /*
+     * Set the resized RGB widht and height
+     */
+     void setResizedRGBSize(int width, int height) {
+        mResizedRGBWidth = width;
+        mResizedRGBHeight = height;
+     }
+
+    /*
+     * Get the resized RGB Height
+     */
+     int getResizedRGBSizeHeight() {
+         return mResizedRGBHeight;
+     }
+
+    /*
+     * Get the resized RGB Width
+     */
+     int getResizedRGBSizeWidth() {
+         return mResizedRGBWidth;
+     }
+
+
     /**
      * Delete the overlay files
      */
@@ -257,4 +291,174 @@
             mBitmapFileName = null;
         }
     }
+
+     /**
+     * Delete the overlay related files
+     */
+    void invalidateGeneratedFiles() {
+        if (mFilename != null) {
+            new File(mFilename).delete();
+            mFilename = null;
+        }
+
+        if (mBitmapFileName != null) {
+            new File(mBitmapFileName).delete();
+            mBitmapFileName = null;
+        }
+    }
+
+    void generateOverlayWithRenderingMode (MediaItem mediaItemsList, OverlayFrame overlay, int height , int width)
+        throws FileNotFoundException, IOException {
+
+        final MediaItem t = mediaItemsList;
+
+        /* get the rendering mode */
+        int renderMode = t.getRenderingMode();
+
+        Bitmap overlayBitmap = ((OverlayFrame)overlay).getBitmap();
+
+        /*
+         * Check if the resize of Overlay is needed with rendering mode applied
+         * because of change in export dimensions
+         */
+        int resizedRGBFileHeight = ((OverlayFrame)overlay).getResizedRGBSizeHeight();
+        int resizedRGBFileWidth = ((OverlayFrame)overlay).getResizedRGBSizeWidth();
+
+        /* Get original bitmap width if it is not resized */
+        if(resizedRGBFileWidth == 0) {
+            resizedRGBFileWidth = overlayBitmap.getWidth();
+        }
+        /* Get original bitmap height if it is not resized */
+        if(resizedRGBFileHeight == 0) {
+            resizedRGBFileHeight = overlayBitmap.getHeight();
+        }
+
+        if (resizedRGBFileWidth != width || resizedRGBFileHeight != height
+            || (!(new File(((OverlayFrame)overlay).getFilename()).exists()))) {
+            /*
+             *  Create the canvas bitmap
+             */
+            final Bitmap destBitmap = Bitmap.createBitmap((int)width,
+                                                      (int)height,
+                                                      Bitmap.Config.ARGB_8888);
+            final Canvas overlayCanvas = new Canvas(destBitmap);
+            final Rect destRect;
+            final Rect srcRect;
+
+            switch (renderMode) {
+                case MediaItem.RENDERING_MODE_STRETCH: {
+                    destRect = new Rect(0, 0, overlayCanvas.getWidth(),
+                                             overlayCanvas.getHeight());
+                    srcRect = new Rect(0, 0, overlayBitmap.getWidth(),
+                                             overlayBitmap.getHeight());
+                    break;
+                }
+
+                case MediaItem.RENDERING_MODE_BLACK_BORDER: {
+                    int left, right, top, bottom;
+                    float aROverlayImage, aRCanvas;
+                    aROverlayImage = (float)(overlayBitmap.getWidth()) /
+                                     (float)(overlayBitmap.getHeight());
+
+                    aRCanvas = (float)(overlayCanvas.getWidth()) /
+                                     (float)(overlayCanvas.getHeight());
+
+                    if (aROverlayImage > aRCanvas) {
+                        int newHeight = ((overlayCanvas.getWidth() * overlayBitmap.getHeight())
+                                         / overlayBitmap.getWidth());
+                        left = 0;
+                        top  = (overlayCanvas.getHeight() - newHeight) / 2;
+                        right = overlayCanvas.getWidth();
+                        bottom = top + newHeight;
+                    } else {
+                        int newWidth = ((overlayCanvas.getHeight() * overlayBitmap.getWidth())
+                                            / overlayBitmap.getHeight());
+                        left = (overlayCanvas.getWidth() - newWidth) / 2;
+                        top  = 0;
+                        right = left + newWidth;
+                        bottom = overlayCanvas.getHeight();
+                    }
+
+                    destRect = new Rect(left, top, right, bottom);
+                    srcRect = new Rect(0, 0, overlayBitmap.getWidth(), overlayBitmap.getHeight());
+                    break;
+                }
+
+                case MediaItem.RENDERING_MODE_CROPPING: {
+                    // Calculate the source rect
+                    int left, right, top, bottom;
+                    float aROverlayImage, aRCanvas;
+                    aROverlayImage = (float)(overlayBitmap.getWidth()) /
+                                     (float)(overlayBitmap.getHeight());
+                    aRCanvas = (float)(overlayCanvas.getWidth()) /
+                                    (float)(overlayCanvas.getHeight());
+                    if (aROverlayImage < aRCanvas) {
+                        int newHeight = ((overlayBitmap.getWidth() * overlayCanvas.getHeight())
+                                   / overlayCanvas.getWidth());
+
+                        left = 0;
+                        top  = (overlayBitmap.getHeight() - newHeight) / 2;
+                        right = overlayBitmap.getWidth();
+                        bottom = top + newHeight;
+                    } else {
+                        int newWidth = ((overlayBitmap.getHeight() * overlayCanvas.getWidth())
+                                    / overlayCanvas.getHeight());
+                        left = (overlayBitmap.getWidth() - newWidth) / 2;
+                        top  = 0;
+                        right = left + newWidth;
+                        bottom = overlayBitmap.getHeight();
+                    }
+
+                    srcRect = new Rect(left, top, right, bottom);
+                    destRect = new Rect(0, 0, overlayCanvas.getWidth(), overlayCanvas.getHeight());
+                    break;
+                }
+
+                default: {
+                    throw new IllegalStateException("Rendering mode: " + renderMode);
+                }
+            }
+
+            overlayCanvas.drawBitmap(overlayBitmap, srcRect, destRect, sResizePaint);
+
+            /*
+             * Write to the dest file
+             */
+            String outFileName = ((OverlayFrame)overlay).getFilename();
+
+            /*
+             * Save the image to same rgb file
+             */
+            if (outFileName != null) {
+                new File(outFileName).delete();
+            }
+
+            final FileOutputStream fl = new FileOutputStream(outFileName);
+            final DataOutputStream dos = new DataOutputStream(fl);
+
+            /*
+             * Populate the rgb file with bitmap data
+             */
+            final int [] framingBuffer = new int[width];
+            ByteBuffer byteBuffer = ByteBuffer.allocate(framingBuffer.length * 4);
+            IntBuffer intBuffer;
+
+            byte[] array = byteBuffer.array();
+            int tmp = 0;
+            while(tmp < height) {
+                destBitmap.getPixels(framingBuffer,0,width,0,tmp,width,1);
+                intBuffer = byteBuffer.asIntBuffer();
+                intBuffer.put(framingBuffer,0,width);
+                dos.write(array);
+                tmp += 1;
+            }
+            fl.flush();
+            fl.close();
+
+            /*
+             * Set the resized RGB width and height
+             */
+            ((OverlayFrame)overlay).setResizedRGBSize(width, height);
+        }
+    }
 }
diff --git a/media/java/android/media/videoeditor/VideoEditorImpl.java b/media/java/android/media/videoeditor/VideoEditorImpl.java
index 8bbd8e8..27ab799 100755
--- a/media/java/android/media/videoeditor/VideoEditorImpl.java
+++ b/media/java/android/media/videoeditor/VideoEditorImpl.java
@@ -109,7 +109,10 @@
     private static final String ATTR_OVERLAY_RGB_FILENAME = "overlay_rgb_filename";
     private static final String ATTR_OVERLAY_FRAME_WIDTH = "overlay_frame_width";
     private static final String ATTR_OVERLAY_FRAME_HEIGHT = "overlay_frame_height";
+    private static final String ATTR_OVERLAY_RESIZED_RGB_FRAME_WIDTH = "resized_RGBframe_width";
+    private static final String ATTR_OVERLAY_RESIZED_RGB_FRAME_HEIGHT = "resized_RGBframe_height";
 
+    private static final int ENGINE_ACCESS_MAX_TIMEOUT_MS = 500;
     /*
      *  Instance variables
      */
@@ -850,8 +853,10 @@
 
         boolean semAcquireDone = false;
         try {
-            mMANativeHelper.lock();
-            semAcquireDone = true;
+            semAcquireDone = mMANativeHelper.lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
+            if (semAcquireDone == false) {
+                throw new IllegalStateException("Timeout waiting for semaphore");
+            }
 
             if (mMediaItems.size() > 0) {
                 final Rect frame = surfaceHolder.getSurfaceFrame();
@@ -860,14 +865,14 @@
             } else {
                 result = 0;
             }
-        } catch (InterruptedException  ex) {
-            Log.e(TAG, "Sem acquire NOT successful in renderPreviewFrame");
+        } catch (InterruptedException ex) {
+            Log.w(TAG, "The thread was interrupted", new Throwable());
+            throw new IllegalStateException("The thread was interrupted");
         } finally {
             if (semAcquireDone) {
                 mMANativeHelper.unlock();
             }
         }
-Log.i("VE_IMPL","renderPreviewFrame <--");
         return result;
     }
 
@@ -1154,6 +1159,15 @@
 
             ((OverlayFrame)overlay).setOverlayFrameWidth(overlayFrameWidth);
             ((OverlayFrame)overlay).setOverlayFrameHeight(overlayFrameHeight);
+
+            final int resizedRGBFrameWidth =
+                                   Integer.parseInt(parser.getAttributeValue("",
+                                   ATTR_OVERLAY_RESIZED_RGB_FRAME_WIDTH));
+            final int resizedRGBFrameHeight =
+                                   Integer.parseInt(parser.getAttributeValue("",
+                                   ATTR_OVERLAY_RESIZED_RGB_FRAME_HEIGHT));
+
+            ((OverlayFrame)overlay).setResizedRGBSize(resizedRGBFrameWidth, resizedRGBFrameHeight);
         }
 
         return overlay;
@@ -1340,6 +1354,11 @@
                                                  Integer.toString(overlayFrame.getOverlayFrameWidth()));
                             serializer.attribute("", ATTR_OVERLAY_FRAME_HEIGHT,
                                                  Integer.toString(overlayFrame.getOverlayFrameHeight()));
+                            serializer.attribute("", ATTR_OVERLAY_RESIZED_RGB_FRAME_WIDTH,
+                                                 Integer.toString(overlayFrame.getResizedRGBSizeWidth()));
+                            serializer.attribute("", ATTR_OVERLAY_RESIZED_RGB_FRAME_HEIGHT,
+                                                 Integer.toString(overlayFrame.getResizedRGBSizeHeight()));
+
                         }
 
                     }
@@ -1524,6 +1543,17 @@
         for (Transition transition : mTransitions) {
             transition.invalidate();
         }
+
+        final Iterator<MediaItem> it = mMediaItems.iterator();
+
+        while (it.hasNext()) {
+            final MediaItem t = it.next();
+            List<Overlay> overlayList = t.getAllOverlays();
+            for (Overlay overlay : overlayList) {
+
+                ((OverlayFrame)overlay).invalidateGeneratedFiles();
+            }
+        }
     }
 
     /*
@@ -1556,8 +1586,10 @@
 
         boolean semAcquireDone = false;
         try{
-            mMANativeHelper.lock();
-            semAcquireDone = true;
+            semAcquireDone = mMANativeHelper.lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
+            if (semAcquireDone == false) {
+                throw new IllegalStateException("Timeout waiting for semaphore");
+            }
 
             if (mMediaItems.size() > 0) {
                 mMANativeHelper.previewStoryBoard(mMediaItems, mTransitions,
@@ -1569,17 +1601,9 @@
             /**
              *  release on complete by calling stopPreview
              */
-        } catch (InterruptedException  ex) {
-            Log.e(TAG, "Sem acquire NOT successful in startPreview");
-        } catch (IllegalArgumentException ex) {
-            Log.e(TAG, "Illegal Argument exception in do preview");
-            throw ex;
-        } catch (IllegalStateException ex) {
-            Log.e(TAG, "Illegal State exception in do preview");
-            throw ex;
-        } catch (RuntimeException ex) {
-            Log.e(TAG, "Runtime exception in do preview");
-            throw ex;
+        } catch (InterruptedException ex) {
+            Log.w(TAG, "The thread was interrupted", new Throwable());
+            throw new IllegalStateException("The thread was interrupted");
         } finally {
             if (semAcquireDone) {
                 mMANativeHelper.unlock();
diff --git a/media/jni/mediaeditor/VideoEditorMain.cpp b/media/jni/mediaeditor/VideoEditorMain.cpp
index 101619c..c23169a 100755
--- a/media/jni/mediaeditor/VideoEditorMain.cpp
+++ b/media/jni/mediaeditor/VideoEditorMain.cpp
@@ -454,7 +454,7 @@
         case MSG_TYPE_OVERLAY_CLEAR:
             isSendProgress = false;
             pContext->mOverlayFileName = NULL;
-            LOGI("MSG_TYPE_OVERLAY_CLEAR");
+            LOGV("MSG_TYPE_OVERLAY_CLEAR");
             //argc is not used
             pContext->mIsUpdateOverlay = true;
             break;
@@ -1102,7 +1102,7 @@
 {
     bool                            needToBeLoaded = true;
     M4OSA_ERR                       result = M4NO_ERROR;
-    M4MCS_Context                   mcsContext;
+    M4MCS_Context                   mcsContext = M4OSA_NULL;
     M4OSA_Char*                     pInputFile = M4OSA_NULL;
     M4OSA_Char*                     pOutputFile = M4OSA_NULL;
     M4OSA_Char*                     pTempPath = M4OSA_NULL;
@@ -1126,6 +1126,9 @@
     videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
         (M4OSA_NULL == pOutputParams),
         "not initialized");
+    if (needToBeLoaded == false) {
+        return M4ERR_ALLOC;
+    }
 
     pEncodingParams = (M4MCS_EncodingParams *)M4OSA_malloc(
         sizeof(M4MCS_EncodingParams),0x00,
@@ -1133,6 +1136,12 @@
     videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
         (M4OSA_NULL == pEncodingParams),
         "not initialized");
+    if (needToBeLoaded == false) {
+        M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+        pEncodingParams = M4OSA_NULL;
+        return M4ERR_ALLOC;
+    }
+
     // Initialize the MCS library.
     result = M4MCS_init(&mcsContext, pContext->initParams.pFileReadPtr,
         pContext->initParams.pFileWritePtr);
@@ -1141,6 +1150,14 @@
     videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
         (M4OSA_NULL == mcsContext),
         "not initialized");
+     if(needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+         return result;
+     }
+
     // generate the path for temp 3gp output file
     pTemp3gpFilePath = (M4OSA_Char*) M4OSA_malloc (
         (M4OSA_chrLength((M4OSA_Char*)pContext->initParams.pTempPath)
@@ -1157,6 +1174,14 @@
         M4OSA_chrNCat ( pTemp3gpFilePath , (M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH,
             M4OSA_chrLength ((M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH));
     }
+    else {
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+         return M4ERR_ALLOC;
+    }
 
     pInputFile = (M4OSA_Char *) infilePath; //pContext->mAudioSettings->pFile;
     //Delete this file later
@@ -1177,6 +1202,16 @@
         pOutputFile, pTempPath);
     videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
         (M4NO_ERROR != result), result);
+    if(needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+         pTemp3gpFilePath = M4OSA_NULL;
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+         return result;
+    }
 
     pOutputParams->OutputFileType
         = (M4VIDEOEDITING_FileType)M4VIDEOEDITING_kFileType_3GPP;
@@ -1217,7 +1252,16 @@
     result = M4MCS_setOutputParams(mcsContext, pOutputParams);
     videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
                                         (M4NO_ERROR != result), result);
-
+    if (needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+         pTemp3gpFilePath = M4OSA_NULL;
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+        return result;
+    }
     // Set the video bitrate.
     pEncodingParams->OutputVideoBitrate =
     (M4VIDEOEDITING_Bitrate)M4VIDEOEDITING_kUndefinedBitrate;
@@ -1238,12 +1282,32 @@
     result = M4MCS_setEncodingParams(mcsContext, pEncodingParams);
     videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
         (M4NO_ERROR != result), result);
+    if (needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+         pTemp3gpFilePath = M4OSA_NULL;
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+         return result;
+    }
 
     VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
                             "M4MCS_checkParamsAndStart()");
     result = M4MCS_checkParamsAndStart(mcsContext);
     videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
         (M4NO_ERROR != result), result);
+    if (needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+         pTemp3gpFilePath = M4OSA_NULL;
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+        return result;
+    }
 
     VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_step()");
 
@@ -1286,6 +1350,16 @@
 
     videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
         (M4MCS_WAR_TRANSCODING_DONE != result), result);
+    if (needToBeLoaded == false) {
+         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+         pTemp3gpFilePath = M4OSA_NULL;
+         M4MCS_abort(mcsContext);
+         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+         pOutputParams = M4OSA_NULL;
+         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+         pEncodingParams = M4OSA_NULL;
+        return result;
+    }
 
     VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_abort()");
     result = M4MCS_abort(mcsContext);
@@ -1296,9 +1370,15 @@
     M4OSA_fileExtraDelete((const M4OSA_Char *) pTemp3gpFilePath);
     VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_generateAudio() EXIT ");
 
-    M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
-    M4OSA_free((M4OSA_MemAddr32)pOutputParams);
-    M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+    if (pTemp3gpFilePath != M4OSA_NULL) {
+        M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
+    }
+    if (pOutputParams != M4OSA_NULL) {
+       M4OSA_free((M4OSA_MemAddr32)pOutputParams);
+    }
+    if(pEncodingParams != M4OSA_NULL) {
+       M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
+    }
     return result;
 }
 
@@ -1439,14 +1519,33 @@
         videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
                              (pContext->state != ManualEditState_INITIALIZED),
                              "settings already loaded");
-        // Retrieve the edit settings.
-        if (pContext->pEditSettings != M4OSA_NULL) {
-            videoEditClasses_freeEditSettings(&pContext->pEditSettings);
-            pContext->pEditSettings = M4OSA_NULL;
+        if (needToBeLoaded) {
+            // Retrieve the edit settings.
+            if (pContext->pEditSettings != M4OSA_NULL) {
+                videoEditClasses_freeEditSettings(&pContext->pEditSettings);
+                pContext->pEditSettings = M4OSA_NULL;
+            }
+            videoEditClasses_getEditSettings(&needToBeLoaded, pEnv,
+                settings, &pContext->pEditSettings,false);
         }
-        videoEditClasses_getEditSettings(&needToBeLoaded, pEnv,
-            settings, &pContext->pEditSettings,false);
     }
+
+    if (needToBeLoaded == false) {
+        j = 0;
+        while (j < pContext->pEditSettings->nbEffects)
+        {
+            if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL) {
+                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer != M4OSA_NULL) {
+                    M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
+                    Effects[j].xVSS.pFramingBuffer);
+                    pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer = M4OSA_NULL;
+                }
+            }
+          j++;
+        }
+        return;
+    }
+
     M4OSA_TRACE1_0("videoEditorC_getEditSettings done");
 
     pContext->previewFrameEditInfoId = pEnv->GetMethodID(engineClass,
@@ -1459,43 +1558,49 @@
         if(mEditClazz == M4OSA_NULL)
         {
             M4OSA_TRACE1_0("cannot find object field for mEditClazz");
-            return;
+            goto videoEditor_populateSettings_cleanup;
         }
         jclass mEffectsClazz = pEnv->FindClass(EFFECT_SETTINGS_CLASS_NAME);
         if(mEffectsClazz == M4OSA_NULL)
         {
             M4OSA_TRACE1_0("cannot find object field for mEffectsClazz");
-            return;
+            goto videoEditor_populateSettings_cleanup;
         }
         fid = pEnv->GetFieldID(mEditClazz,"effectSettingsArray", "[L"EFFECT_SETTINGS_CLASS_NAME";"  );
         if(fid == M4OSA_NULL)
         {
             M4OSA_TRACE1_0("cannot find field for effectSettingsArray Array");
-            return;
+            goto videoEditor_populateSettings_cleanup;
         }
         effectSettingsArray = (jobjectArray)pEnv->GetObjectField(settings, fid);
         if(effectSettingsArray == M4OSA_NULL)
         {
             M4OSA_TRACE1_0("cannot find object field for effectSettingsArray");
-            return;
+            goto videoEditor_populateSettings_cleanup;
         }
-        i = 0;
-        j = 0;
+
         //int overlayIndex[pContext->pEditSettings->nbEffects];
-        if ( pContext->pEditSettings->nbEffects )
+        if (pContext->pEditSettings->nbEffects > 0)
         {
             pOverlayIndex
             = (int*) M4OSA_malloc(pContext->pEditSettings->nbEffects * sizeof(int), 0,
                 (M4OSA_Char*)"pOverlayIndex");
+            if (pOverlayIndex == M4OSA_NULL) {
+                videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
+                    M4OSA_TRUE, M4ERR_ALLOC);
+                goto videoEditor_populateSettings_cleanup;
+            }
         }
 
+        i = 0;
+        j = 0;
         M4OSA_TRACE1_1("no of effects = %d",pContext->pEditSettings->nbEffects);
         while (j < pContext->pEditSettings->nbEffects)
         {
             if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL)
             {
                 pOverlayIndex[nbOverlays] = j;
-                nbOverlays++;
+
                 M4xVSS_FramingStruct *aFramingCtx = M4OSA_NULL;
                 aFramingCtx
                 = (M4xVSS_FramingStruct*)M4OSA_malloc(sizeof(M4xVSS_FramingStruct), M4VS,
@@ -1503,7 +1608,11 @@
                 if (aFramingCtx == M4OSA_NULL)
                 {
                     M4OSA_TRACE1_0("Allocation error in videoEditor_populateSettings");
+                    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
+                        M4OSA_TRUE, M4ERR_ALLOC);
+                    goto videoEditor_populateSettings_cleanup;
                 }
+
                 aFramingCtx->pCurrent = M4OSA_NULL; /* Only used by the first element of the chain */
                 aFramingCtx->previousClipTime = -1;
                 aFramingCtx->FramingYuv = M4OSA_NULL;
@@ -1524,7 +1633,6 @@
                  aFramingCtx->width = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_width;
                  aFramingCtx->height = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height;
 
-
                 result = M4xVSS_internalConvertARGB888toYUV420_FrammingEffect(pContext->engineContext,
                     &(pContext->pEditSettings->Effects[j]),aFramingCtx,
                 pContext->pEditSettings->Effects[j].xVSS.framingScaledSize);
@@ -1536,7 +1644,7 @@
                         M4OSA_free((M4OSA_MemAddr32)aFramingCtx);
                         aFramingCtx = M4OSA_NULL;
                     }
-                    return;
+                    goto videoEditor_populateSettings_cleanup;
                 }
 
                 //framing buffers are resized to fit the output video resolution.
@@ -1545,7 +1653,6 @@
                 pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height =
                     aFramingCtx->FramingRgb->u_height;
 
-
                 VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "A framing Context aFramingCtx->width = %d",
                     aFramingCtx->FramingRgb->u_width);
 
@@ -1557,7 +1664,7 @@
                 height = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height;
 
                 //RGB 565
-                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_stride = width*2;
+                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_stride = width * 2;
 
                 //for RGB565
                 pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_topleft = 0;
@@ -1565,6 +1672,13 @@
                             (M4VIFI_UInt8 *)M4OSA_malloc(width*height*2,
                             0x00,(M4OSA_Char *)"pac_data buffer");
 
+                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->pac_data == M4OSA_NULL) {
+                    M4OSA_TRACE1_0("Failed to allocate memory for framing buffer");
+                    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
+                                            M4OSA_TRUE, M4ERR_ALLOC);
+                    goto videoEditor_populateSettings_cleanup;
+                }
+
                 M4OSA_memcpy((M4OSA_Int8 *)&pContext->pEditSettings->\
                     Effects[j].xVSS.pFramingBuffer->\
                     pac_data[0],(M4OSA_Int8 *)&aFramingCtx->FramingRgb->pac_data[0],(width*height*2));
@@ -1596,6 +1710,7 @@
                     M4OSA_free((M4OSA_MemAddr32)aFramingCtx);
                     aFramingCtx = M4OSA_NULL;
                 }
+                nbOverlays++;
             }
             j++;
         }
@@ -1608,7 +1723,11 @@
             videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
                 (M4OSA_NULL == properties),
                 "not initialized");
-            getClipSetting(pEnv,properties, pContext->pEditSettings->pClipList[i]);
+            if (needToBeLoaded) {
+                getClipSetting(pEnv,properties, pContext->pEditSettings->pClipList[i]);
+            } else {
+                goto videoEditor_populateSettings_cleanup;
+            }
         }
 
         if (needToBeLoaded) {
@@ -1627,6 +1746,10 @@
                                      (M4OSA_NULL == pContext->mAudioSettings),
                                      "not initialized");
 
+        if (needToBeLoaded == false) {
+            goto videoEditor_populateSettings_cleanup;
+        }
+
         fid = pEnv->GetFieldID(audioSettingClazz,"bRemoveOriginal","Z");
         pContext->mAudioSettings->bRemoveOriginal = pEnv->GetIntField(audioSettingObject,fid);
         M4OSA_TRACE1_1("bRemoveOriginal = %d",pContext->mAudioSettings->bRemoveOriginal);
@@ -1681,37 +1804,51 @@
         M4OSA_TRACE1_1("file name = %s",pContext->mAudioSettings->pFile);
         VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "regenerateAudio() file name = %s",\
         pContext->mAudioSettings->pFile);
+
         fid = pEnv->GetFieldID(audioSettingClazz,"pcmFilePath","Ljava/lang/String;");
         str = (jstring)pEnv->GetObjectField(audioSettingObject,fid);
+
         pContext->mAudioSettings->pPCMFilePath =
         (M4OSA_Char*)pEnv->GetStringUTFChars(str, M4OSA_NULL);
+
         VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "pPCMFilePath -- %s ",\
         pContext->mAudioSettings->pPCMFilePath);
+
         fid = pEnv->GetFieldID(engineClass,"mRegenerateAudio","Z");
         bool regenerateAudio = pEnv->GetBooleanField(thiz,fid);
+
         VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "regenerateAudio -- %d ",\
         regenerateAudio);
+
         if (regenerateAudio) {
             M4OSA_TRACE1_0("Calling Generate Audio now");
             result = videoEditor_generateAudio(pEnv,
                         pContext,
                         (M4OSA_Char*)pContext->mAudioSettings->pFile,
                         (M4OSA_Char*)pContext->mAudioSettings->pPCMFilePath);
+
+            videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
+                (M4NO_ERROR != result), result);
+            if (needToBeLoaded == false) {
+                goto videoEditor_populateSettings_cleanup;
+            }
+
             regenerateAudio = false;
             pEnv->SetBooleanField(thiz,fid,regenerateAudio);
         }
-        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "regenerateAudio()");
 
         /* Audio mix and duck */
         fid = pEnv->GetFieldID(audioSettingClazz,"ducking_threshold","I");
         pContext->mAudioSettings->uiInDucking_threshold
             = pEnv->GetIntField(audioSettingObject,fid);
+
         M4OSA_TRACE1_1("ducking threshold = %d",
             pContext->mAudioSettings->uiInDucking_threshold);
 
         fid = pEnv->GetFieldID(audioSettingClazz,"ducking_lowVolume","I");
         pContext->mAudioSettings->uiInDucking_lowVolume
             = pEnv->GetIntField(audioSettingObject,fid);
+
         M4OSA_TRACE1_1("ducking lowVolume = %d",
             pContext->mAudioSettings->uiInDucking_lowVolume);
 
@@ -1720,6 +1857,7 @@
             = pEnv->GetBooleanField(audioSettingObject,fid);
         M4OSA_TRACE1_1("ducking lowVolume = %d",
             pContext->mAudioSettings->bInDucking_enable);
+
     } else {
         if (pContext->mAudioSettings != M4OSA_NULL) {
             pContext->mAudioSettings->pFile = M4OSA_NULL;
@@ -1740,22 +1878,27 @@
 
             fid = pEnv->GetFieldID(engineClass,"mRegenerateAudio","Z");
             bool regenerateAudio = pEnv->GetBooleanField(thiz,fid);
-            if(!regenerateAudio) {
+            if (!regenerateAudio) {
                 regenerateAudio = true;
                 pEnv->SetBooleanField(thiz,fid,regenerateAudio);
             }
         }
     }
-    if (pContext->pEditSettings != NULL )
+
+    if (pContext->pEditSettings != NULL)
     {
         result = pContext->mPreviewController->loadEditSettings(pContext->pEditSettings,
-        pContext->mAudioSettings);
+            pContext->mAudioSettings);
         videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
                                             (M4NO_ERROR != result), result);
 
-        pContext->mPreviewController->setJniCallback((void*)pContext,
-         (jni_progress_callback_fct)jniPreviewProgressCallback);
+        if (needToBeLoaded) {
+            pContext->mPreviewController->setJniCallback((void*)pContext,
+            (jni_progress_callback_fct)jniPreviewProgressCallback);
+        }
+    }
 
+videoEditor_populateSettings_cleanup:
         j = 0;
         while (j < nbOverlays)
         {
@@ -1766,14 +1909,22 @@
                 pContext->pEditSettings->\
                 Effects[pOverlayIndex[j]].xVSS.pFramingBuffer->pac_data = M4OSA_NULL;
             }
-            if (pContext->pEditSettings->Effects[pOverlayIndex[j]].xVSS.pFramingBuffer != M4OSA_NULL) {
-                M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
-                Effects[pOverlayIndex[j]].xVSS.pFramingBuffer);
-                pContext->pEditSettings->Effects[pOverlayIndex[j]].xVSS.pFramingBuffer = M4OSA_NULL;
-            }
             j++;
         }
-    }
+
+        j = 0;
+        while (j < pContext->pEditSettings->nbEffects)
+        {
+            if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL) {
+                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer != M4OSA_NULL) {
+                    M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
+                    Effects[j].xVSS.pFramingBuffer);
+                    pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer = M4OSA_NULL;
+                }
+            }
+          j++;
+        }
+
     if (pOverlayIndex != M4OSA_NULL)
     {
         M4OSA_free((M4OSA_MemAddr32)pOverlayIndex);
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index 7a3ef14..e1c03d4 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -5101,6 +5101,9 @@
             }
             Binder.restoreCallingIdentity(ident);
 
+            // Constrain frame to the screen size.
+            frame.intersect(0, 0, dw, dh);
+            
             if (frame.isEmpty() || maxLayer == 0) {
                 return null;
             }
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index b0f0a43..821e39f 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -23,6 +23,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemProperties;
+import android.util.Log;
 
 import com.android.internal.telephony.IPhoneSubInfo;
 import com.android.internal.telephony.ITelephony;
@@ -55,14 +56,21 @@
 public class TelephonyManager {
     private static final String TAG = "TelephonyManager";
 
-    private Context mContext;
-    private ITelephonyRegistry mRegistry;
+    private static Context sContext;
+    private static ITelephonyRegistry sRegistry;
 
     /** @hide */
     public TelephonyManager(Context context) {
-        mContext = context;
-        mRegistry = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
+        if (sContext == null) {
+            sContext = context;
+
+            sRegistry = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
                     "telephony.registry"));
+        } else {
+            Log.e(TAG, "Hidden constructor called more than once per process!");
+            Log.e(TAG, "Original: " + sContext.getPackageName() + ", new: " +
+                    context.getPackageName());
+        }
     }
 
     /** @hide */
@@ -71,7 +79,8 @@
 
     private static TelephonyManager sInstance = new TelephonyManager();
 
-    /** @hide */
+    /** @hide
+    /* @deprecated - use getSystemService as described above */
     public static TelephonyManager getDefault() {
         return sInstance;
     }
@@ -889,10 +898,10 @@
      *               LISTEN_ flags.
      */
     public void listen(PhoneStateListener listener, int events) {
-        String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>";
+        String pkgForDebug = sContext != null ? sContext.getPackageName() : "<unknown>";
         try {
             Boolean notifyNow = (getITelephony() != null);
-            mRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
+            sRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
         } catch (RemoteException ex) {
             // system process dead
         } catch (NullPointerException ex) {
@@ -967,7 +976,8 @@
      * @hide pending API review
      */
     public boolean isVoiceCapable() {
-        return mContext.getResources().getBoolean(
+        if (sContext == null) return true;
+        return sContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_voice_capable);
     }
 
@@ -983,7 +993,8 @@
      * @hide pending API review
      */
     public boolean isSmsCapable() {
-        return mContext.getResources().getBoolean(
+        if (sContext == null) return true;
+        return sContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_sms_capable);
     }
 }
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index 2db4417..fc50334 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -89,6 +89,15 @@
         </activity>
         
         <activity
+                android:name="ViewLayersActivity5"
+                android:label="_ViewLayers5">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        
+        <activity
                 android:name="AlphaLayersActivity"
                 android:label="_αLayers">
             <intent-filter>
diff --git a/tests/HwAccelerationTest/res/layout/view_layers_5.xml b/tests/HwAccelerationTest/res/layout/view_layers_5.xml
new file mode 100644
index 0000000..653f3a8
--- /dev/null
+++ b/tests/HwAccelerationTest/res/layout/view_layers_5.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="horizontal"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <LinearLayout
+        android:orientation="vertical"
+        android:layout_width="0dip"
+        android:layout_height="match_parent"
+        android:layout_weight="1">
+
+        <Button
+            android:onClick="setLayerEnabled"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Enable layer" />
+
+        <Button
+            android:onClick="setLayerDisabled"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Disable layer" />
+        
+    </LinearLayout>
+
+    <ListView
+        android:id="@+id/list1"
+        android:layout_width="0dip"
+        android:layout_height="match_parent"
+        android:layout_weight="1" />
+
+</LinearLayout>
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java
new file mode 100644
index 0000000..95a5b0d
--- /dev/null
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java
@@ -0,0 +1,121 @@
+/*
+ * 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.test.hwui;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Paint;
+import android.graphics.PorterDuff;
+import android.graphics.PorterDuffColorFilter;
+import android.os.Bundle;
+import android.util.DisplayMetrics;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+
+@SuppressWarnings({"UnusedDeclaration"})
+public class ViewLayersActivity5 extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        
+        setContentView(R.layout.view_layers_5);
+
+        setupList(R.id.list1);
+    }
+
+    public void setLayerDisabled(View v) {
+        ((ViewGroup) findViewById(R.id.list1).getParent()).setChildrenLayersEnabled(false);
+    }
+    
+    public void setLayerEnabled(View v) {
+        ((ViewGroup) findViewById(R.id.list1).getParent()).setChildrenLayersEnabled(true);
+    }
+    
+    private void setupList(int listId) {
+        final Paint p = new Paint();
+        p.setColorFilter(new PorterDuffColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY));
+
+        final ListView list = (ListView) findViewById(listId);
+        list.setAdapter(new SimpleListAdapter(this));
+        list.setLayerType(View.LAYER_TYPE_HARDWARE, p);
+    }
+
+    private static class SimpleListAdapter extends ArrayAdapter<String> {
+        public SimpleListAdapter(Context context) {
+            super(context, android.R.layout.simple_list_item_1, DATA_LIST);
+        }
+
+        @Override
+        public View getView(int position, View convertView, ViewGroup parent) {
+            TextView v = (TextView) super.getView(position, convertView, parent);
+            final Resources r = getContext().getResources();
+            final DisplayMetrics metrics = r.getDisplayMetrics();
+            v.setCompoundDrawablePadding((int) (6 * metrics.density + 0.5f));
+            v.setCompoundDrawablesWithIntrinsicBounds(r.getDrawable(R.drawable.icon),
+                    null, null, null);
+            return v;
+        }
+    }
+
+    private static final String[] DATA_LIST = {
+            "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
+            "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
+            "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
+            "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
+            "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
+            "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil",
+            "British Indian Ocean Territory", "British Virgin Islands", "Brunei", "Bulgaria",
+            "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
+            "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
+            "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
+            "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
+            "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
+            "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
+            "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
+            "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
+            "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
+            "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
+            "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
+            "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
+            "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
+            "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
+            "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
+            "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
+            "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
+            "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
+            "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
+            "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
+            "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
+            "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
+            "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
+            "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
+            "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
+            "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
+            "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
+            "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
+            "Ukraine", "United Arab Emirates", "United Kingdom",
+            "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
+            "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
+            "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
+    };
+}