Merge "Offload killProcessGroup to a worker thread" into nyc-dev
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index a1e2e94..8e1609c 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -116,14 +116,11 @@
      *  @param top The new top position
      *  @param right The new right position
      *  @param bottom The new bottom position
-     *  @param requestedWidth The new requested width
-     *  @param requestedHeight The new requested height
      *  @param deferTransactionUntilFrame Frame number from our parent (attached) to
      *  defer this action until.
      *  @param outFrame Rect in which is placed the new position/size on screen.
      */
     void repositionChild(IWindow childWindow, int left, int top, int right, int bottom,
-            int requestedWidth, int requestedHeight,
             long deferTransactionUntilFrame, out Rect outFrame);
 
     /*
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 477ffd9..8a8fb43 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -490,7 +490,7 @@
                               | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                               | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                               ;
-                if (!creating && !force && !mUpdateWindowNeeded) {
+                if (!creating && !force && !mUpdateWindowNeeded && !sizeChanged) {
                     mLayout.privateFlags |=
                             WindowManager.LayoutParams.PRIVATE_FLAG_PRESERVE_GEOMETRY;
                 } else {
@@ -584,18 +584,6 @@
 
                     mSurface.transferFrom(mNewSurface);
                     if (visible && mSurface.isValid()) {
-                        // We set SCALING_MODE_NO_SCALE_CROP to allow the WindowManager
-                        // to update our Surface crop without requiring a new buffer from
-                        // us. In the default mode of SCALING_MODE_FREEZE, surface geometry
-                        // state (which includes crop) is only applied when a buffer
-                        // with appropriate geometry is available. During drag resize
-                        // it is quite frequent that a matching buffer will not be available
-                        // (because we are constantly being resized and have fallen behind).
-                        // However in such situations the WindowManager still needs to be able
-                        // to update our crop to ensure we stay within the bounds of the containing
-                        // window.
-                        mSurface.setScalingMode(Surface.SCALING_MODE_NO_SCALE_CROP);
-
                         if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) {
                             mSurfaceCreated = true;
                             mIsCreating = true;
@@ -666,7 +654,6 @@
                             mLocation[0], mLocation[1]));
                     mSession.repositionChild(mWindow, mWindowSpaceLeft, mWindowSpaceTop,
                             mLocation[0], mLocation[1],
-                            mWindowSpaceWidth, mWindowSpaceHeight,
                             -1, mWinFrame);
                 } catch (RemoteException ex) {
                     Log.e(TAG, "Exception from relayout", ex);
@@ -703,7 +690,6 @@
             }
             // Just using mRTLastReportedPosition as a dummy rect here
             session.repositionChild(window, left, top, right, bottom,
-                    mWindowSpaceWidth, mWindowSpaceHeight,
                     frameNumber,
                     mRTLastReportedPosition);
             // Now overwrite mRTLastReportedPosition with our values
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index a9af654..4a68d3c 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -3411,17 +3411,10 @@
     }
 
     /**
-     * Sets whether the movement method will automatically be set to {@link LinkMovementMethod}
-     * after {@link #setText} or {@link #append} is called. The movement method is set if one of the
-     * following is true:
-     * <ul>
-     * <li>{@link #setAutoLinkMask} has been set to nonzero and links are detected in
-     * {@link #setText} or {@link #append}.
-     * <li>The input for {@link #setText} or {@link #append} contains a {@link ClickableSpan}.
-     * </ul>
-     *
-     * <p>This function does not have an immediate effect, movement method will be set only after a
-     * call to {@link #setText} or {@link #append}. The default is true.</p>
+     * Sets whether the movement method will automatically be set to
+     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
+     * set to nonzero and links are detected in {@link #setText}.
+     * The default is true.
      *
      * @attr ref android.R.styleable#TextView_linksClickable
      */
@@ -3431,14 +3424,10 @@
     }
 
     /**
-     * Returns whether the movement method will automatically be set to {@link LinkMovementMethod}
-     * after {@link #setText} or {@link #append} is called.
-     *
-     * See {@link #setLinksClickable} for details.
-     *
-     * <p>The default is true.</p>
-     *
-     * @see #setLinksClickable
+     * Returns whether the movement method will automatically be set to
+     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
+     * set to nonzero and links are detected in {@link #setText}.
+     * The default is true.
      *
      * @attr ref android.R.styleable#TextView_linksClickable
      */
@@ -4032,19 +4021,13 @@
 
         ((Editable) mText).append(text, start, end);
 
-        boolean hasClickableSpans = false;
         if (mAutoLinkMask != 0) {
-            hasClickableSpans = Linkify.addLinks((Spannable) mText, mAutoLinkMask);
-        } else if (mLinksClickable && text instanceof Spanned) {
-            ClickableSpan[] clickableSpans =
-                    ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
-            hasClickableSpans = clickableSpans != null && clickableSpans.length > 0;
-        }
-
-        // Do not change the movement method for text that supports text selection as it
-        // would prevent an arbitrary cursor displacement.
-        if (hasClickableSpans && mLinksClickable && !textCanBeSelected()) {
-            setMovementMethod(LinkMovementMethod.getInstance());
+            boolean linksWereAdded = Linkify.addLinks((Spannable) mText, mAutoLinkMask);
+            // Do not change the movement method for text that support text selection as it
+            // would prevent an arbitrary cursor displacement.
+            if (linksWereAdded && mLinksClickable && !textCanBeSelected()) {
+                setMovementMethod(LinkMovementMethod.getInstance());
+            }
         }
     }
 
@@ -4397,7 +4380,6 @@
             text = TextUtils.stringOrSpannedString(text);
         }
 
-        boolean hasClickableSpans = false;
         if (mAutoLinkMask != 0) {
             Spannable s2;
 
@@ -4407,32 +4389,22 @@
                 s2 = mSpannableFactory.newSpannable(text);
             }
 
-            hasClickableSpans = Linkify.addLinks(s2, mAutoLinkMask);
-            if (hasClickableSpans) {
+            if (Linkify.addLinks(s2, mAutoLinkMask)) {
                 text = s2;
-            }
-        } else if (mLinksClickable && text instanceof Spanned) {
-            ClickableSpan[] clickableSpans =
-                    ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
-            hasClickableSpans = clickableSpans != null && clickableSpans.length > 0;
-            if (hasClickableSpans && !(text instanceof Spannable)) {
-                text = mSpannableFactory.newSpannable(text);
-            }
-        }
+                type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
 
-        if (hasClickableSpans) {
-            type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
-            /*
-             * We must go ahead and set the text before changing the
-             * movement method, because setMovementMethod() may call
-             * setText() again to try to upgrade the buffer type.
-             */
-            mText = text;
+                /*
+                 * We must go ahead and set the text before changing the
+                 * movement method, because setMovementMethod() may call
+                 * setText() again to try to upgrade the buffer type.
+                 */
+                mText = text;
 
-            // Do not change the movement method for text that supports text selection as it
-            // would prevent an arbitrary cursor displacement.
-            if (mLinksClickable && !textCanBeSelected()) {
-                setMovementMethod(LinkMovementMethod.getInstance());
+                // Do not change the movement method for text that support text selection as it
+                // would prevent an arbitrary cursor displacement.
+                if (mLinksClickable && !textCanBeSelected()) {
+                    setMovementMethod(LinkMovementMethod.getInstance());
+                }
             }
         }
 
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index d7381ab..4429001 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -4384,8 +4384,7 @@
         <attr name="autoLink" />
         <!-- If set to false, keeps the movement method from being set
              to the link movement method even if autoLink causes links
-             to be found or the input text contains a
-             {@link android.text.style.ClickableSpan ClickableSpan}. -->
+             to be found. -->
         <attr name="linksClickable" format="boolean" />
         <!-- If set, specifies that this TextView has a numeric input method.
              The default is false.
diff --git a/graphics/java/android/graphics/FontListParser.java b/graphics/java/android/graphics/FontListParser.java
index 8f7c6a62..7871aa8 100644
--- a/graphics/java/android/graphics/FontListParser.java
+++ b/graphics/java/android/graphics/FontListParser.java
@@ -179,10 +179,10 @@
         int tag = 0;
         String tagStr = parser.getAttributeValue(null, "tag");
         if (tagStr != null && TAG_PATTERN.matcher(tagStr).matches()) {
-            tag = tagStr.charAt(0) << 24 +
-                  tagStr.charAt(1) << 16 +
-                  tagStr.charAt(2) <<  8 +
-                  tagStr.charAt(3);
+            tag = (tagStr.charAt(0) << 24) +
+                  (tagStr.charAt(1) << 16) +
+                  (tagStr.charAt(2) <<  8) +
+                  (tagStr.charAt(3)      );
         } else {
             throw new XmlPullParserException("Invalid tag attribute value.", parser, null);
         }
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
index 9ed2abf..f10af43 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
@@ -45,6 +45,8 @@
 import android.os.RemoteException;
 import android.provider.DocumentsContract;
 import android.provider.DocumentsContract.Document;
+import android.system.ErrnoException;
+import android.system.Os;
 import android.text.format.DateUtils;
 import android.util.Log;
 import android.webkit.MimeTypeMap;
@@ -451,7 +453,7 @@
         ParcelFileDescriptor srcFile = null;
         ParcelFileDescriptor dstFile = null;
         InputStream in = null;
-        OutputStream out = null;
+        ParcelFileDescriptor.AutoCloseOutputStream out = null;
         boolean success = false;
 
         try {
@@ -502,6 +504,8 @@
                     makeCopyProgress(len);
                 }
 
+                // Need to invoke IoUtils.close explicitly to avoid from ignoring errors at flush.
+                IoUtils.close(dstFile.getFileDescriptor());
                 srcFile.checkError();
             } catch (IOException e) {
                 throw new ResourceException(
diff --git a/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp b/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
index 1d4ed1d..eb96015 100644
--- a/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
+++ b/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
@@ -52,6 +52,8 @@
 static jmethodID app_fuse_get_file_size;
 static jmethodID app_fuse_read_object_bytes;
 static jmethodID app_fuse_write_object_bytes;
+static jmethodID app_fuse_flush_file_handle;
+static jmethodID app_fuse_close_file_handle;
 static jfieldID app_fuse_buffer;
 
 // NOTE:
@@ -307,7 +309,8 @@
         const uint32_t size = in->size;
         const void* const buffer = reinterpret_cast<const uint8_t*>(in) + sizeof(fuse_write_in);
         uint32_t written_size;
-        const int result = write_object_bytes(it->second, offset, size, buffer, &written_size);
+        const int result = write_object_bytes(
+                in->fh, it->second, offset, size, buffer, &written_size);
         if (result < 0) {
             return result;
         }
@@ -320,13 +323,13 @@
                             const fuse_release_in* in,
                             FuseResponse<void>* /* out */) {
         handles_.erase(in->fh);
-        return 0;
+        return env_->CallIntMethod(self_, app_fuse_close_file_handle, file_handle_to_jlong(in->fh));
     }
 
     int handle_fuse_flush(const fuse_in_header& /* header */,
-                          const void* /* in */,
+                          const fuse_flush_in* in,
                           FuseResponse<void>* /* out */) {
-        return 0;
+        return env_->CallIntMethod(self_, app_fuse_flush_file_handle, file_handle_to_jlong(in->fh));
     }
 
     template <typename T, typename S>
@@ -382,8 +385,10 @@
         return read_size;
     }
 
-    int write_object_bytes(int inode, uint64_t offset, uint32_t size, const void* buffer,
-                           uint32_t* written_size) {
+    int write_object_bytes(uint64_t handle, int inode, uint64_t offset, uint32_t size,
+                           const void* buffer, uint32_t* written_size) {
+        static_assert(sizeof(uint64_t) <= sizeof(jlong),
+                      "jlong must be able to express any uint64_t values");
         ScopedLocalRef<jbyteArray> array(
                 env_,
                 static_cast<jbyteArray>(env_->GetObjectField(self_, app_fuse_buffer)));
@@ -394,15 +399,28 @@
             }
             memcpy(bytes.get(), buffer, size);
         }
-        *written_size = env_->CallIntMethod(
-                self_, app_fuse_write_object_bytes, inode, offset, size, array.get());
-        if (env_->ExceptionCheck()) {
-            env_->ExceptionClear();
-            return -EIO;
+        const int result = env_->CallIntMethod(
+                self_,
+                app_fuse_write_object_bytes,
+                file_handle_to_jlong(handle),
+                inode,
+                offset,
+                size,
+                array.get());
+        if (result < 0) {
+            return result;
         }
+        *written_size = result;
         return 0;
     }
 
+    static jlong file_handle_to_jlong(uint64_t handle) {
+        static_assert(
+                sizeof(uint64_t) <= sizeof(jlong),
+                "jlong must be able to express any uint64_t values");
+        return static_cast<jlong>(handle);
+    }
+
     static void fuse_reply(int fd, int unique, int reply_code, void* reply_data,
                            size_t reply_size) {
         // Don't send any data for error case.
@@ -511,15 +529,21 @@
         return -1;
     }
 
-    app_fuse_buffer = env->GetFieldID(app_fuse_class, "mBuffer", "[B");
-    if (app_fuse_buffer == nullptr) {
-        ALOGE("Can't find mBuffer");
+    app_fuse_write_object_bytes = env->GetMethodID(app_fuse_class, "writeObjectBytes", "(JIJI[B)I");
+    if (app_fuse_write_object_bytes == nullptr) {
+        ALOGE("Can't find writeObjectBytes");
         return -1;
     }
 
-    app_fuse_write_object_bytes = env->GetMethodID(app_fuse_class, "writeObjectBytes", "(IJI[B)I");
-    if (app_fuse_write_object_bytes == nullptr) {
-        ALOGE("Can't find getWriteObjectBytes");
+    app_fuse_flush_file_handle = env->GetMethodID(app_fuse_class, "flushFileHandle", "(J)I");
+    if (app_fuse_flush_file_handle == nullptr) {
+        ALOGE("Can't find flushFileHandle");
+        return -1;
+    }
+
+    app_fuse_close_file_handle = env->GetMethodID(app_fuse_class, "closeFileHandle", "(J)I");
+    if (app_fuse_close_file_handle == nullptr) {
+        ALOGE("Can't find closeFileHandle");
         return -1;
     }
 
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java b/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
index 777dc60..88858a8 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
@@ -20,6 +20,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.storage.StorageManager;
+import android.system.ErrnoException;
 import android.system.OsConstants;
 import android.util.Log;
 import com.android.internal.annotations.VisibleForTesting;
@@ -34,6 +35,8 @@
         System.loadLibrary("appfuse_jni");
     }
 
+    private static final boolean DEBUG = false;
+
     /**
      * Max read amount specified at the FUSE kernel implementation.
      * The value is copied from sdcard.c.
@@ -94,7 +97,8 @@
     public ParcelFileDescriptor openFile(int i, int mode) throws FileNotFoundException {
         Preconditions.checkArgument(
                 mode == ParcelFileDescriptor.MODE_READ_ONLY ||
-                mode == ParcelFileDescriptor.MODE_WRITE_ONLY);
+                mode == (ParcelFileDescriptor.MODE_WRITE_ONLY |
+                         ParcelFileDescriptor.MODE_TRUNCATE));
         return ParcelFileDescriptor.open(new File(
                 getMountPoint(),
                 Integer.toString(i)),
@@ -127,6 +131,7 @@
 
         /**
          * Handles writing bytes for the give inode.
+         * @param fileHandle
          * @param inode
          * @param offset Offset for file bytes.
          * @param size Size for file bytes.
@@ -134,7 +139,23 @@
          * @return Number of read bytes. Must not be negative.
          * @throws IOException
          */
-        int writeObjectBytes(int inode, long offset, int size, byte[] bytes) throws IOException;
+        int writeObjectBytes(long fileHandle, int inode, long offset, int size, byte[] bytes)
+                throws IOException, ErrnoException;
+
+        /**
+         * Flushes bytes for file handle.
+         * @param fileHandle
+         * @throws IOException
+         * @throws ErrnoException
+         */
+        void flushFileHandle(long fileHandle) throws IOException, ErrnoException;
+
+        /**
+         * Closes file handle.
+         * @param fileHandle
+         * @throws IOException
+         */
+        void closeFileHandle(long fileHandle) throws IOException, ErrnoException;
     }
 
     @UsedByNative("com_android_mtp_AppFuse.cpp")
@@ -142,10 +163,8 @@
     private long getFileSize(int inode) {
         try {
             return mCallback.getFileSize(inode);
-        } catch (FileNotFoundException e) {
-            return -OsConstants.ENOENT;
-        } catch (UnsupportedOperationException e) {
-            return -OsConstants.ENOTSUP;
+        } catch (Exception error) {
+            return -getErrnoFromException(error);
         }
     }
 
@@ -159,20 +178,62 @@
             // It's OK to share the same mBuffer among requests because the requests are processed
             // by AppFuseMessageThread sequentially.
             return mCallback.readObjectBytes(inode, offset, size, mBuffer);
-        } catch (IOException e) {
-            return -OsConstants.EIO;
-        } catch (UnsupportedOperationException e) {
-            return -OsConstants.ENOTSUP;
+        } catch (Exception error) {
+            return -getErrnoFromException(error);
         }
     }
 
     @UsedByNative("com_android_mtp_AppFuse.cpp")
     @WorkerThread
-    private /* unsgined */ int writeObjectBytes(int inode,
+    private /* unsgined */ int writeObjectBytes(long fileHandler,
+                                                int inode,
                                                 /* unsigned */ long offset,
                                                 /* unsigned */ int size,
-                                                byte[] bytes) throws IOException {
-        return mCallback.writeObjectBytes(inode, offset, size, bytes);
+                                                byte[] bytes) {
+        try {
+            return mCallback.writeObjectBytes(fileHandler, inode, offset, size, bytes);
+        } catch (Exception error) {
+            return -getErrnoFromException(error);
+        }
+    }
+
+    @UsedByNative("com_android_mtp_AppFuse.cpp")
+    @WorkerThread
+    private int flushFileHandle(long fileHandle) {
+        try {
+            mCallback.flushFileHandle(fileHandle);
+            return 0;
+        } catch (Exception error) {
+            return -getErrnoFromException(error);
+        }
+    }
+
+    @UsedByNative("com_android_mtp_AppFuse.cpp")
+    @WorkerThread
+    private int closeFileHandle(long fileHandle) {
+        try {
+            mCallback.closeFileHandle(fileHandle);
+            return 0;
+        } catch (Exception error) {
+            return -getErrnoFromException(error);
+        }
+    }
+
+    private static int getErrnoFromException(Exception error) {
+        if (DEBUG) {
+            Log.e(MtpDocumentsProvider.TAG, "AppFuse callbacks", error);
+        }
+        if (error instanceof FileNotFoundException) {
+            return OsConstants.ENOENT;
+        } else if (error instanceof IOException) {
+            return OsConstants.EIO;
+        } else if (error instanceof UnsupportedOperationException) {
+            return OsConstants.ENOTSUP;
+        } else if (error instanceof IllegalArgumentException) {
+            return OsConstants.EINVAL;
+        } else {
+            return OsConstants.EIO;
+        }
     }
 
     private native boolean native_start_app_fuse_loop(int fd);
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
index 9f64046ce..50781bf 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
@@ -17,6 +17,7 @@
 package com.android.mtp;
 
 import android.content.ContentResolver;
+import android.content.Context;
 import android.content.UriPermission;
 import android.content.res.AssetFileDescriptor;
 import android.content.res.Resources;
@@ -38,11 +39,16 @@
 import android.provider.DocumentsContract;
 import android.provider.DocumentsProvider;
 import android.provider.Settings;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
 import android.util.Log;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 
+import java.io.File;
+import java.io.FileDescriptor;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.HashMap;
@@ -82,6 +88,7 @@
     private MtpDatabase mDatabase;
     private AppFuse mAppFuse;
     private ServiceIntentSender mIntentSender;
+    private Context mContext;
 
     /**
      * Provides singleton instance to MtpDocumentsService.
@@ -93,6 +100,7 @@
     @Override
     public boolean onCreate() {
         sSingleton = this;
+        mContext = getContext();
         mResources = getContext().getResources();
         mMtpManager = new MtpManager(getContext());
         mResolver = getContext().getContentResolver();
@@ -137,12 +145,14 @@
 
     @VisibleForTesting
     boolean onCreateForTesting(
+            Context context,
             Resources resources,
             MtpManager mtpManager,
             ContentResolver resolver,
             MtpDatabase database,
             StorageManager storageManager,
             ServiceIntentSender intentSender) {
+        mContext = context;
         mResources = resources;
         mMtpManager = mtpManager;
         mResolver = resolver;
@@ -232,43 +242,43 @@
         try {
             openDevice(identifier.mDeviceId);
             final MtpDeviceRecord device = getDeviceToolkit(identifier.mDeviceId).mDeviceRecord;
-            switch (mode) {
-                case "r":
-                    long fileSize;
-                    try {
-                        fileSize = getFileSize(documentId);
-                    } catch (UnsupportedOperationException exception) {
-                        fileSize = -1;
-                    }
-                    // MTP getPartialObject operation does not support files that are larger than
-                    // 4GB. Fallback to non-seekable file descriptor.
-                    if (MtpDeviceRecord.isPartialReadSupported(
-                            device.operationsSupported, fileSize)) {
-                        return mAppFuse.openFile(
-                                Integer.parseInt(documentId), ParcelFileDescriptor.MODE_READ_ONLY);
-                    } else {
-                        return getPipeManager(identifier).readDocument(mMtpManager, identifier);
-                    }
-                case "w":
-                    // TODO: Clear the parent document loader task (if exists) and call notify
-                    // when writing is completed.
-                    if (MtpDeviceRecord.isWritingSupported(device.operationsSupported)) {
-                        return getPipeManager(identifier).writeDocument(
-                                getContext(), mMtpManager, identifier, device.operationsSupported);
-                    } else {
-                        throw new UnsupportedOperationException(
-                                "The device does not support writing operation.");
-                    }
-                case "rw":
-                    // TODO: Add support for "rw" mode.
+            // Turn off MODE_CREATE because openDocument does not allow to create new files.
+            final int modeFlag =
+                    ParcelFileDescriptor.parseMode(mode) & ~ParcelFileDescriptor.MODE_CREATE;
+            if ((modeFlag & ParcelFileDescriptor.MODE_READ_ONLY) != 0) {
+                long fileSize;
+                try {
+                    fileSize = getFileSize(documentId);
+                } catch (UnsupportedOperationException exception) {
+                    fileSize = -1;
+                }
+                if (MtpDeviceRecord.isPartialReadSupported(
+                        device.operationsSupported, fileSize)) {
+                    return mAppFuse.openFile(Integer.parseInt(documentId), modeFlag);
+                } else {
+                    // If getPartialObject{|64} are not supported for the device, returns
+                    // non-seekable pipe FD instead.
+                    return getPipeManager(identifier).readDocument(mMtpManager, identifier);
+                }
+            } else if ((modeFlag & ParcelFileDescriptor.MODE_WRITE_ONLY) != 0) {
+                // TODO: Clear the parent document loader task (if exists) and call notify
+                // when writing is completed.
+                if (MtpDeviceRecord.isWritingSupported(device.operationsSupported)) {
+                    return mAppFuse.openFile(Integer.parseInt(documentId), modeFlag);
+                } else {
                     throw new UnsupportedOperationException(
-                            "The provider does not support 'rw' mode.");
-                default:
-                    throw new IllegalArgumentException("Unknown mode for openDocument: " + mode);
+                            "The device does not support writing operation.");
+                }
+            } else {
+                // TODO: Add support for "rw" mode.
+                throw new UnsupportedOperationException("The provider does not support 'rw' mode.");
             }
+        } catch (FileNotFoundException | RuntimeException error) {
+            Log.e(MtpDocumentsProvider.TAG, "openDocument", error);
+            throw error;
         } catch (IOException error) {
             Log.e(MtpDocumentsProvider.TAG, "openDocument", error);
-            throw new FileNotFoundException(error.getMessage());
+            throw new IllegalStateException(error);
         }
     }
 
@@ -595,6 +605,13 @@
     }
 
     private class AppFuseCallback implements AppFuse.Callback {
+        private final Map<Long, MtpFileWriter> mWriters = new HashMap<>();
+
+        @Override
+        public long getFileSize(int inode) throws FileNotFoundException {
+            return MtpDocumentsProvider.this.getFileSize(String.valueOf(inode));
+        }
+
         @Override
         public long readObjectBytes(
                 int inode, long offset, long size, byte[] buffer) throws IOException {
@@ -617,15 +634,43 @@
         }
 
         @Override
-        public long getFileSize(int inode) throws FileNotFoundException {
-            return MtpDocumentsProvider.this.getFileSize(String.valueOf(inode));
+        public int writeObjectBytes(
+                long fileHandle, int inode, long offset, int size, byte[] bytes)
+                throws IOException, ErrnoException {
+            final MtpFileWriter writer;
+            if (mWriters.containsKey(fileHandle)) {
+                writer = mWriters.get(fileHandle);
+            } else {
+                writer = new MtpFileWriter(mContext, String.valueOf(inode));
+                mWriters.put(fileHandle, writer);
+            }
+            return writer.write(offset, size, bytes);
         }
 
         @Override
-        public int writeObjectBytes(int inode, long offset, int size, byte[] bytes)
-                throws IOException {
-            // TODO: Implement it.
-            throw new IOException();
+        public void flushFileHandle(long fileHandle) throws IOException, ErrnoException {
+            final MtpFileWriter writer = mWriters.get(fileHandle);
+            if (writer == null) {
+                // File handle for reading.
+                return;
+            }
+            final MtpDeviceRecord device = getDeviceToolkit(
+                    mDatabase.createIdentifier(writer.getDocumentId()).mDeviceId).mDeviceRecord;
+            writer.flush(mMtpManager, mDatabase, device.operationsSupported);
+        }
+
+        @Override
+        public void closeFileHandle(long fileHandle) throws IOException, ErrnoException {
+            final MtpFileWriter writer = mWriters.get(fileHandle);
+            if (writer == null) {
+                // File handle for reading.
+                return;
+            }
+            try {
+                writer.close();
+            } finally {
+                mWriters.remove(fileHandle);
+            }
         }
     }
 }
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java
new file mode 100644
index 0000000..3e1bedc
--- /dev/null
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2016 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.mtp;
+
+import android.content.Context;
+import android.mtp.MtpObjectInfo;
+import android.os.ParcelFileDescriptor;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+
+import com.android.internal.util.Preconditions;
+
+import java.io.File;
+import java.io.IOException;
+
+class MtpFileWriter implements AutoCloseable {
+    final ParcelFileDescriptor mCacheFd;
+    final String mDocumentId;
+    boolean mDirty;
+
+    MtpFileWriter(Context context, String documentId) throws IOException {
+        mDocumentId = documentId;
+        mDirty = false;
+        final File tempFile = File.createTempFile("mtp", "tmp", context.getCacheDir());
+        mCacheFd = ParcelFileDescriptor.open(
+                tempFile,
+                ParcelFileDescriptor.MODE_READ_WRITE |
+                ParcelFileDescriptor.MODE_TRUNCATE |
+                ParcelFileDescriptor.MODE_CREATE);
+        tempFile.delete();
+    }
+
+    String getDocumentId() {
+        return mDocumentId;
+    }
+
+    int write(long offset, int size, byte[] bytes) throws IOException, ErrnoException {
+        Preconditions.checkArgumentNonnegative(offset, "offset");
+        Preconditions.checkArgumentNonnegative(size, "size");
+        Preconditions.checkArgument(size <= bytes.length);
+        if (size == 0) {
+            return 0;
+        }
+        mDirty = true;
+        Os.lseek(mCacheFd.getFileDescriptor(), offset, OsConstants.SEEK_SET);
+        return Os.write(mCacheFd.getFileDescriptor(), bytes, 0, size);
+    }
+
+    void flush(MtpManager manager, MtpDatabase database, int[] operationsSupported)
+            throws IOException, ErrnoException {
+        // Skip unnecessary flush.
+        if (!mDirty) {
+            return;
+        }
+
+        // Get the placeholder object info.
+        final Identifier identifier = database.createIdentifier(mDocumentId);
+        final MtpObjectInfo placeholderObjectInfo =
+                manager.getObjectInfo(identifier.mDeviceId, identifier.mObjectHandle);
+
+        // Delete the target object info if it already exists (as a placeholder).
+        manager.deleteDocument(identifier.mDeviceId, identifier.mObjectHandle);
+
+        // Create the target object info with a correct file size and upload the file.
+        final long size = Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_END);
+        final MtpObjectInfo targetObjectInfo = new MtpObjectInfo.Builder(placeholderObjectInfo)
+                .setCompressedSize(size)
+                .build();
+
+        Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_SET);
+        final int newObjectHandle = manager.createDocument(
+                identifier.mDeviceId, targetObjectInfo, mCacheFd);
+
+        final MtpObjectInfo newObjectInfo = manager.getObjectInfo(
+                identifier.mDeviceId, newObjectHandle);
+        final Identifier parentIdentifier =
+                database.getParentIdentifier(identifier.mDocumentId);
+        database.updateObject(
+                identifier.mDocumentId,
+                identifier.mDeviceId,
+                parentIdentifier.mDocumentId,
+                operationsSupported,
+                newObjectInfo,
+                size);
+
+        mDirty = false;
+    }
+
+    @Override
+    public void close() throws IOException {
+        mCacheFd.close();
+    }
+}
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
index 1520f3b..795bbc1 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
@@ -16,13 +16,9 @@
 
 package com.android.mtp;
 
-import android.content.Context;
-import android.mtp.MtpObjectInfo;
 import android.os.ParcelFileDescriptor;
 import android.util.Log;
 
-import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -52,15 +48,6 @@
         return task.getReadingFileDescriptor();
     }
 
-    ParcelFileDescriptor writeDocument(Context context, MtpManager model, Identifier identifier,
-                                       int[] operationsSupported)
-            throws IOException {
-        final Task task = new WriteDocumentTask(
-                context, model, identifier, operationsSupported, mDatabase);
-        mExecutor.execute(task);
-        return task.getWritingFileDescriptor();
-    }
-
     ParcelFileDescriptor readThumbnail(MtpManager model, Identifier identifier) throws IOException {
         final Task task = new GetThumbnailTask(model, identifier);
         mExecutor.execute(task);
@@ -81,10 +68,6 @@
         ParcelFileDescriptor getReadingFileDescriptor() {
             return mDescriptors[0];
         }
-
-        ParcelFileDescriptor getWritingFileDescriptor() {
-            return mDescriptors[1];
-        }
     }
 
     private static class ImportFileTask extends Task {
@@ -108,85 +91,6 @@
         }
     }
 
-    private static class WriteDocumentTask extends Task {
-        private final Context mContext;
-        private final MtpDatabase mDatabase;
-        private final int[] mOperationsSupported;
-
-        WriteDocumentTask(Context context,
-                          MtpManager model,
-                          Identifier identifier,
-                          int[] supportedOperations,
-                          MtpDatabase database)
-                throws IOException {
-            super(model, identifier);
-            mContext = context;
-            mDatabase = database;
-            mOperationsSupported = supportedOperations;
-        }
-
-        @Override
-        public void run() {
-            File tempFile = null;
-            try {
-                // Obtain a temporary file and copy the data to it.
-                tempFile = File.createTempFile("mtp", "tmp", mContext.getCacheDir());
-                try (
-                    final FileOutputStream tempOutputStream =
-                            new ParcelFileDescriptor.AutoCloseOutputStream(
-                                    ParcelFileDescriptor.open(
-                                            tempFile, ParcelFileDescriptor.MODE_WRITE_ONLY));
-                    final ParcelFileDescriptor.AutoCloseInputStream inputStream =
-                            new ParcelFileDescriptor.AutoCloseInputStream(mDescriptors[0])
-                ) {
-                    final byte[] buffer = new byte[32 * 1024];
-                    int bytes;
-                    while ((bytes = inputStream.read(buffer)) != -1) {
-                        mDescriptors[0].checkError();
-                        tempOutputStream.write(buffer, 0, bytes);
-                    }
-                    tempOutputStream.flush();
-                }
-
-                // Get the placeholder object info.
-                final MtpObjectInfo placeholderObjectInfo =
-                        mManager.getObjectInfo(mIdentifier.mDeviceId, mIdentifier.mObjectHandle);
-
-                // Delete the target object info if it already exists (as a placeholder).
-                mManager.deleteDocument(mIdentifier.mDeviceId, mIdentifier.mObjectHandle);
-
-                // Create the target object info with a correct file size and upload the file.
-                final MtpObjectInfo targetObjectInfo =
-                        new MtpObjectInfo.Builder(placeholderObjectInfo)
-                                .setCompressedSize(tempFile.length())
-                                .build();
-                final ParcelFileDescriptor tempInputDescriptor = ParcelFileDescriptor.open(
-                        tempFile, ParcelFileDescriptor.MODE_READ_ONLY);
-                final int newObjectHandle = mManager.createDocument(
-                        mIdentifier.mDeviceId, targetObjectInfo, tempInputDescriptor);
-
-                final MtpObjectInfo newObjectInfo = mManager.getObjectInfo(
-                        mIdentifier.mDeviceId, newObjectHandle);
-                final Identifier parentIdentifier =
-                        mDatabase.getParentIdentifier(mIdentifier.mDocumentId);
-                mDatabase.updateObject(
-                        mIdentifier.mDocumentId,
-                        mIdentifier.mDeviceId,
-                        parentIdentifier.mDocumentId,
-                        mOperationsSupported,
-                        newObjectInfo,
-                        tempFile.length());
-            } catch (IOException error) {
-                Log.w(MtpDocumentsProvider.TAG,
-                        "Failed to send a file because of: " + error.getMessage());
-            } finally {
-                if (tempFile != null) {
-                    tempFile.delete();
-                }
-            }
-        }
-    }
-
     private static class GetThumbnailTask extends Task {
         GetThumbnailTask(MtpManager model, Identifier identifier) throws IOException {
             super(model, identifier);
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
index 3b92506..e421de7 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
@@ -23,6 +23,8 @@
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.MediumTest;
 
+import libcore.io.IoUtils;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -143,7 +145,8 @@
                     }
 
                     @Override
-                    public int writeObjectBytes(int inode, long offset, int size, byte[] bytes) {
+                    public int writeObjectBytes(
+                            long fileHandle, int inode, long offset, int size, byte[] bytes) {
                         for (int i = 0; i < size; i++) {
                             resultBytes[(int)(offset + i)] = bytes[i];
                         }
@@ -152,7 +155,7 @@
                 });
         appFuse.mount(storageManager);
         final ParcelFileDescriptor fd = appFuse.openFile(
-                INODE, ParcelFileDescriptor.MODE_WRITE_ONLY);
+                INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
         try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
                 new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
             stream.write('a');
@@ -182,7 +185,7 @@
                 });
         appFuse.mount(storageManager);
         final ParcelFileDescriptor fd = appFuse.openFile(
-                INODE, ParcelFileDescriptor.MODE_WRITE_ONLY);
+                INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
         try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
                 new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
             stream.write('a');
@@ -192,6 +195,46 @@
         appFuse.close();
     }
 
+    public void testWriteFile_flushError() throws IOException {
+        final StorageManager storageManager = getContext().getSystemService(StorageManager.class);
+        final int INODE = 10;
+        final AppFuse appFuse = new AppFuse(
+                "test",
+                new TestCallback() {
+                    @Override
+                    public long getFileSize(int inode) throws FileNotFoundException {
+                        if (inode != INODE) {
+                            throw new FileNotFoundException();
+                        }
+                        return 5;
+                    }
+
+                    @Override
+                    public int writeObjectBytes(
+                            long fileHandle, int inode, long offset, int size, byte[] bytes) {
+                        return size;
+                    }
+
+                    @Override
+                    public void flushFileHandle(long fileHandle) throws IOException {
+                        throw new IOException();
+                    }
+                });
+        appFuse.mount(storageManager);
+        final ParcelFileDescriptor fd = appFuse.openFile(
+                INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
+        try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
+                new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
+            stream.write('a');
+            try {
+                IoUtils.close(fd.getFileDescriptor());
+                fail();
+            } catch (IOException e) {
+            }
+        }
+        appFuse.close();
+    }
+
     private static class TestCallback implements AppFuse.Callback {
         @Override
         public long getFileSize(int inode) throws FileNotFoundException {
@@ -205,9 +248,15 @@
         }
 
         @Override
-        public int writeObjectBytes(int inode, long offset, int size, byte[] bytes)
+        public int writeObjectBytes(long fileHandle, int inode, long offset, int size, byte[] bytes)
                 throws IOException {
             throw new IOException();
         }
+
+        @Override
+        public void flushFileHandle(long fileHandle) throws IOException {}
+
+        @Override
+        public void closeFileHandle(long fileHandle) {}
     }
 }
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
index 0de761c..9ed15c8 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
@@ -21,6 +21,7 @@
 import android.mtp.MtpObjectInfo;
 import android.net.Uri;
 import android.os.ParcelFileDescriptor;
+import android.os.ParcelFileDescriptor.AutoCloseOutputStream;
 import android.os.storage.StorageManager;
 import android.provider.DocumentsContract.Document;
 import android.provider.DocumentsContract.Root;
@@ -533,6 +534,30 @@
         }
     }
 
+    public void testOpenDocument_writing() throws Exception {
+        setupProvider(MtpDatabaseConstants.FLAG_DATABASE_IN_MEMORY);
+        setupRoots(0, new MtpRoot[] {
+                new MtpRoot(0, 0, "Storage", 0, 0, "")
+        });
+        final String documentId = mProvider.createDocument("2", "text/plain", "test.txt");
+        {
+            final ParcelFileDescriptor fd = mProvider.openDocument(documentId, "w", null);
+            try (ParcelFileDescriptor.AutoCloseOutputStream stream =
+                    new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
+                stream.write("Hello".getBytes());
+            }
+        }
+        {
+            final ParcelFileDescriptor fd = mProvider.openDocument(documentId, "r", null);
+            try (ParcelFileDescriptor.AutoCloseInputStream stream =
+                    new ParcelFileDescriptor.AutoCloseInputStream(fd)) {
+                final byte[] bytes = new byte[5];
+                stream.read(bytes);
+                assertTrue(Arrays.equals("Hello".getBytes(), bytes));
+            }
+        }
+    }
+
     public void testBusyDevice() throws Exception {
         mMtpManager = new TestMtpManager(getContext()) {
             @Override
@@ -740,6 +765,7 @@
         mProvider = new MtpDocumentsProvider();
         final StorageManager storageManager = getContext().getSystemService(StorageManager.class);
         assertTrue(mProvider.onCreateForTesting(
+                getContext(),
                 mResources,
                 mMtpManager,
                 mResolver,
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
index 8611797..53dc3db 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
@@ -16,10 +16,7 @@
 
 package com.android.mtp;
 
-import android.database.Cursor;
-import android.mtp.MtpObjectInfo;
 import android.os.ParcelFileDescriptor;
-import android.provider.DocumentsContract.Document;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.MediumTest;
 
@@ -66,64 +63,6 @@
         assertDescriptorError(descriptor);
     }
 
-    public void testWriteDocument_basic() throws Exception {
-        TestUtil.addTestDevice(mDatabase);
-        TestUtil.addTestStorage(mDatabase, "1");
-
-        final MtpObjectInfo info =
-                new MtpObjectInfo.Builder().setObjectHandle(1).setName("note.txt").build();
-        mDatabase.getMapper().startAddingDocuments("2");
-        mDatabase.getMapper().putChildDocuments(
-                0, "2", TestUtil.OPERATIONS_SUPPORTED,
-                new MtpObjectInfo[] { info },
-                new long[] { 0L });
-        mDatabase.getMapper().stopAddingDocuments("2");
-        // Create a placeholder file which should be replaced by a real file later.
-        mtpManager.setObjectInfo(0, info);
-
-        // Upload testing bytes.
-        final ParcelFileDescriptor descriptor = mPipeManager.writeDocument(
-                getContext(),
-                mtpManager,
-                new Identifier(0, 0, 1, "2", MtpDatabaseConstants.DOCUMENT_TYPE_OBJECT),
-                TestUtil.OPERATIONS_SUPPORTED);
-        final ParcelFileDescriptor.AutoCloseOutputStream outputStream =
-                new ParcelFileDescriptor.AutoCloseOutputStream(descriptor);
-        outputStream.write(HELLO_BYTES, 0, HELLO_BYTES.length);
-        outputStream.close();
-        mExecutor.shutdown();
-        assertTrue(mExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS));
-
-        // Check if the placeholder file is removed.
-        try {
-            mtpManager.getObjectInfo(0, 1);
-            fail();  // The placeholder file has not been deleted.
-        } catch (IOException e) {
-            // Expected error, as the file is gone.
-        }
-
-        // Confirm that the target file is created.
-        final MtpObjectInfo targetDocument = mtpManager.getObjectInfo(
-                0, TestMtpManager.CREATED_DOCUMENT_HANDLE);
-        assertTrue(targetDocument != null);
-
-        // Confirm the object handle is updated.
-        try (final Cursor cursor = mDatabase.queryDocument(
-                "2", new String[] { MtpDatabaseConstants.COLUMN_OBJECT_HANDLE })) {
-            assertEquals(1, cursor.getCount());
-            cursor.moveToNext();
-            assertEquals(TestMtpManager.CREATED_DOCUMENT_HANDLE, cursor.getInt(0));
-        }
-
-        // Verify uploaded bytes.
-        final byte[] uploadedBytes = mtpManager.getImportFileBytes(
-                0, TestMtpManager.CREATED_DOCUMENT_HANDLE);
-        assertEquals(HELLO_BYTES.length, uploadedBytes.length);
-        for (int i = 0; i < HELLO_BYTES.length; i++) {
-            assertEquals(HELLO_BYTES[i], uploadedBytes[i]);
-        }
-    }
-
     public void testReadThumbnail_basic() throws Exception {
         mtpManager.setThumbnail(0, 1, HELLO_BYTES);
         final ParcelFileDescriptor descriptor = mPipeManager.readThumbnail(
diff --git a/rs/java/android/renderscript/Allocation.java b/rs/java/android/renderscript/Allocation.java
index f2ef065..81f63ae 100644
--- a/rs/java/android/renderscript/Allocation.java
+++ b/rs/java/android/renderscript/Allocation.java
@@ -296,8 +296,13 @@
     }
 
     /**
-     * Enable/Disable AutoPadding for Vec3 elements.
-     * By default: Diabled.
+     * Enable/Disable AutoPadding for Vec3 Elements.
+     *
+     * <p> Vec3 Elements, such as {@link Element#U8_3} are treated as Vec4 Elements
+     * with the fourth vector element used as padding. Enabling the AutoPadding feature
+     * will automatically add/remove the padding when you copy to/from an Allocation
+     * with a Vec3 Element.
+     * <p> By default: Disabled.
      *
      * @param useAutoPadding True: enable AutoPadding; False: disable AutoPadding
      *
diff --git a/rs/java/android/renderscript/Script.java b/rs/java/android/renderscript/Script.java
index 2b06780..f6f93cb 100644
--- a/rs/java/android/renderscript/Script.java
+++ b/rs/java/android/renderscript/Script.java
@@ -541,21 +541,22 @@
 
     /**
      * Class for specifying the specifics about how a kernel will be
-     * launched
+     * launched.
      *
      * This class can specify a potential range of cells on which to
      * run a kernel.  If no set is called for a dimension then this
      * class will have no impact on that dimension when the kernel
      * is executed.
      *
-     * The forEach launch will operate over the intersection of the
-     * dimensions.
+     * The forEach kernel launch will operate over the intersection of
+     * the dimensions.
      *
      * Example:
      * LaunchOptions with setX(5, 15)
      * Allocation with dimension X=10, Y=10
-     * The resulting forEach run would execute over x = 5 to 10 and
-     * y = 0 to 10.
+     * The resulting forEach run would execute over:
+     * x = 5 to 9 (inclusive) and
+     * y = 0 to 9 (inclusive).
      *
      *
      */
@@ -569,11 +570,11 @@
         private int strategy;
 
         /**
-         * Set the X range.  If the end value is set to 0 the X dimension is not
-         * clipped.
+         * Set the X range. xstartArg is the lowest coordinate of the range,
+         * and xendArg-1 is the highest coordinate of the range.
          *
          * @param xstartArg Must be >= 0
-         * @param xendArg Must be >= xstartArg
+         * @param xendArg Must be > xstartArg
          *
          * @return LaunchOptions
          */
@@ -587,11 +588,11 @@
         }
 
         /**
-         * Set the Y range.  If the end value is set to 0 the Y dimension is not
-         * clipped.
+         * Set the Y range. ystartArg is the lowest coordinate of the range,
+         * and yendArg-1 is the highest coordinate of the range.
          *
          * @param ystartArg Must be >= 0
-         * @param yendArg Must be >= ystartArg
+         * @param yendArg Must be > ystartArg
          *
          * @return LaunchOptions
          */
@@ -605,11 +606,11 @@
         }
 
         /**
-         * Set the Z range.  If the end value is set to 0 the Z dimension is not
-         * clipped.
+         * Set the Z range. zstartArg is the lowest coordinate of the range,
+         * and zendArg-1 is the highest coordinate of the range.
          *
          * @param zstartArg Must be >= 0
-         * @param zendArg Must be >= zstartArg
+         * @param zendArg Must be > zstartArg
          *
          * @return LaunchOptions
          */
diff --git a/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
index 76da781..339e0e9 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
@@ -32,10 +32,9 @@
      * Supported elements types are {@link Element#U8}, {@link
      * Element#U8_2}, {@link Element#U8_3}, {@link Element#U8_4},
      * {@link Element#F32}, {@link Element#F32_2}, {@link
-     * Element#F32_3}, and {@link Element#F32_4}
+     * Element#F32_3}, and {@link Element#F32_4}.
      *
-     * The default coefficients are.
-     *
+     * <p> The default coefficients are:
      * <code>
      * <p> [ 0,  0,  0 ]
      * <p> [ 0,  1,  0 ]
@@ -67,7 +66,7 @@
     }
 
     /**
-     * Set the input of the blur.
+     * Set the input of the 3x3 convolve.
      * Must match the element type supplied during create.
      *
      * @param ain The input allocation.
@@ -80,7 +79,7 @@
     /**
      * Set the coefficients for the convolve.
      *
-     * The convolve layout is
+     * <p> The convolve layout is:
      * <code>
      * <p> [ 0,  1,  2 ]
      * <p> [ 3,  4,  5 ]
diff --git a/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
index 2d37600..a288cee 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
@@ -32,9 +32,9 @@
      * Supported elements types are {@link Element#U8}, {@link
      * Element#U8_2}, {@link Element#U8_3}, {@link Element#U8_4},
      * {@link Element#F32}, {@link Element#F32_2}, {@link
-     * Element#F32_3}, and {@link Element#F32_4}
+     * Element#F32_3}, and {@link Element#F32_4}.
      *
-     * The default coefficients are.
+     * <p> The default coefficients are:
      * <code>
      * <p> [ 0,  0,  0,  0,  0  ]
      * <p> [ 0,  0,  0,  0,  0  ]
@@ -66,7 +66,7 @@
     }
 
     /**
-     * Set the input of the blur.
+     * Set the input of the 5x5 convolve.
      * Must match the element type supplied during create.
      *
      * @param ain The input allocation.
@@ -79,7 +79,7 @@
     /**
     * Set the coefficients for the convolve.
     *
-    * The convolve layout is
+    * <p> The convolve layout is:
     * <code>
     * <p> [ 0,  1,  2,  3,  4  ]
     * <p> [ 5,  6,  7,  8,  9  ]
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index 4749417..6023d7f 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -108,7 +108,7 @@
 
     private static final boolean COMPRESS_TIME = false;
 
-    private static final int EVENT_BUFFER_SIZE = 40;
+    private static final int EVENT_BUFFER_SIZE = 100;
 
     private AlarmManager mAlarmManager;
     private IBatteryStats mBatteryStats;
@@ -192,6 +192,7 @@
     private long mNextAlarmTime;
     private long mNextIdlePendingDelay;
     private long mNextIdleDelay;
+    private long mNextLightIdleDelay;
     private long mNextLightAlarmTime;
     private long mCurIdleBudget;
     private long mMaintenanceStartTime;
@@ -353,6 +354,8 @@
         }
     };
 
+    private boolean mMaintenanceMinCheckScheduled;
+
     private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
         @Override public void onReceive(Context context, Intent intent) {
             decActiveIdleOps();
@@ -477,7 +480,11 @@
      */
     private final class Constants extends ContentObserver {
         // Key names stored in the settings value.
+        private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
+                = "light_after_inactive_to";
         private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
+        private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
+        private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
         private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
                 = "light_idle_maintenance_min_budget";
         private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
@@ -505,14 +512,35 @@
                 "sms_temp_app_whitelist_duration";
 
         /**
-         * This is the time, after becoming inactive, that we will start going
-         * in to light-weight idle mode.
+         * This is the time, after becoming inactive, that we go in to the first
+         * light-weight idle mode.
+         * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+         * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
+         */
+        public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
+
+        /**
+         * This is the initial time that we will run in idle maintenance mode.
          * @see Settings.Global#DEVICE_IDLE_CONSTANTS
          * @see #KEY_LIGHT_IDLE_TIMEOUT
          */
         public long LIGHT_IDLE_TIMEOUT;
 
         /**
+         * Scaling factor to apply to the light idle mode time each time we complete a cycle.
+         * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+         * @see #KEY_LIGHT_IDLE_FACTOR
+         */
+        public float LIGHT_IDLE_FACTOR;
+
+        /**
+         * This is the maximum time we will run in idle maintenence mode.
+         * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+         * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
+         */
+        public long LIGHT_MAX_IDLE_TIMEOUT;
+
+        /**
          * This is the minimum amount of time we want to make available for maintenance mode
          * when lightly idling.  That is, we will always have at least this amount of time
          * available maintenance before timing out and cutting off maintenance mode.
@@ -716,7 +744,14 @@
                     Slog.e(TAG, "Bad device idle settings", e);
                 }
 
+                LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
+                        KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
+                        !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
                 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
+                        !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
+                LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
+                        2f);
+                LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
                         !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
                 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
                         KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
@@ -770,10 +805,22 @@
         void dump(PrintWriter pw) {
             pw.println("  Settings:");
 
+            pw.print("    "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
+            TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
+            pw.println();
+
             pw.print("    "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
             TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
             pw.println();
 
+            pw.print("    "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
+            pw.print(LIGHT_IDLE_FACTOR);
+            pw.println();
+
+            pw.print("    "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
+            TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
+            pw.println();
+
             pw.print("    "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
             TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
             pw.println();
@@ -1640,7 +1687,10 @@
             mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
             mCurIdleBudget = 0;
             mMaintenanceStartTime = 0;
-            mAlarmManager.cancel(mMaintenanceMinCheckListener);
+            if (mMaintenanceMinCheckScheduled) {
+                mAlarmManager.cancel(mMaintenanceMinCheckListener);
+                mMaintenanceMinCheckScheduled = false;
+            }
             resetIdleManagementLocked();
             resetLightIdleManagementLocked();
             addEvent(EVENT_NORMAL);
@@ -1663,7 +1713,7 @@
                 mLightState = LIGHT_STATE_INACTIVE;
                 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
                 resetLightIdleManagementLocked();
-                scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_TIMEOUT);
+                scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
                 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
             }
         }
@@ -1672,6 +1722,7 @@
     void resetIdleManagementLocked() {
         mNextIdlePendingDelay = 0;
         mNextIdleDelay = 0;
+        mNextLightIdleDelay = 0;
         cancelAlarmLocked();
         cancelLocatingLocked();
         stopMonitoringMotionLocked();
@@ -1704,6 +1755,8 @@
         switch (mLightState) {
             case LIGHT_STATE_INACTIVE:
                 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
+                // Reset the upcoming idle delays.
+                mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
                 mMaintenanceStartTime = 0;
             case LIGHT_STATE_IDLE_MAINTENANCE:
                 if (mMaintenanceStartTime != 0) {
@@ -1717,13 +1770,21 @@
                     }
                 }
                 mMaintenanceStartTime = 0;
-                scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_TIMEOUT);
+                scheduleLightAlarmLocked(mNextLightIdleDelay);
+                mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
+                        (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
+                if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
+                    mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
+                }
                 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
                 mLightState = LIGHT_STATE_IDLE;
                 EventLogTags.writeDeviceIdleLight(mLightState, reason);
                 addEvent(EVENT_LIGHT_IDLE);
                 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
-                mAlarmManager.cancel(mMaintenanceMinCheckListener);
+                if (mMaintenanceMinCheckScheduled) {
+                    mAlarmManager.cancel(mMaintenanceMinCheckListener);
+                    mMaintenanceMinCheckScheduled = false;
+                }
                 break;
             case LIGHT_STATE_IDLE:
                 // We have been idling long enough, now it is time to do some work.
@@ -1744,6 +1805,7 @@
                 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME,
                         mMaintenanceStartTime + mConstants.MIN_LIGHT_MAINTENANCE_TIME,
                         "DeviceIdleController.maint-check", mMaintenanceMinCheckListener, mHandler);
+                mMaintenanceMinCheckScheduled = true;
                 break;
         }
     }
@@ -1820,6 +1882,7 @@
                 cancelAlarmLocked();
                 cancelLocatingLocked();
                 mAnyMotionDetector.stop();
+
             case STATE_IDLE_MAINTENANCE:
                 scheduleAlarmLocked(mNextIdleDelay, true);
                 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
@@ -1827,6 +1890,9 @@
                 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
                 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
                 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
+                if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
+                    mNextIdleDelay = mConstants.IDLE_TIMEOUT;
+                }
                 mState = STATE_IDLE;
                 if (mLightState != LIGHT_STATE_OVERRIDE) {
                     mLightState = LIGHT_STATE_OVERRIDE;
@@ -1835,7 +1901,10 @@
                 EventLogTags.writeDeviceIdle(mState, reason);
                 addEvent(EVENT_DEEP_IDLE);
                 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
-                mAlarmManager.cancel(mMaintenanceMinCheckListener);
+                if (mMaintenanceMinCheckScheduled) {
+                    mAlarmManager.cancel(mMaintenanceMinCheckListener);
+                    mMaintenanceMinCheckScheduled = false;
+                }
                 break;
             case STATE_IDLE:
                 // We have been idling long enough, now it is time to do some work.
@@ -1846,6 +1915,9 @@
                 mMaintenanceStartTime = SystemClock.elapsedRealtime();
                 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
                         (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
+                if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
+                    mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
+                }
                 mState = STATE_IDLE_MAINTENANCE;
                 EventLogTags.writeDeviceIdle(mState, reason);
                 addEvent(EVENT_DEEP_MAINTENANCE);
@@ -1853,6 +1925,7 @@
                 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME,
                         mMaintenanceStartTime + mConstants.MIN_DEEP_MAINTENANCE_TIME,
                         "DeviceIdleController.maint-check", mMaintenanceMinCheckListener, mHandler);
+                mMaintenanceMinCheckScheduled = true;
                 break;
         }
     }
@@ -2735,6 +2808,11 @@
                 TimeUtils.formatDuration(mNextIdleDelay, pw);
                 pw.println();
             }
+            if (mNextLightIdleDelay != 0) {
+                pw.print("  mNextIdleDelay=");
+                TimeUtils.formatDuration(mNextLightIdleDelay, pw);
+                pw.println();
+            }
             if (mNextLightAlarmTime != 0) {
                 pw.print("  mNextLightAlarmTime=");
                 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
@@ -2750,6 +2828,10 @@
                 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
                 pw.println();
             }
+            if (mMaintenanceMinCheckScheduled) {
+                pw.print("  mMaintenanceMinCheckScheduled=");
+                pw.println(mMaintenanceMinCheckScheduled);
+            }
             if (mJobsActive) {
                 pw.print("  mJobsActive="); pw.println(mJobsActive);
             }
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 98d44ac..b501398 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -509,34 +509,35 @@
                         continue;
                     }
 
-                    Region windowBounds = mTempRegion2;
+                    // Consider the touchable portion of the window
                     Matrix matrix = mTempMatrix;
                     populateTransformationMatrixLocked(windowState, matrix);
+                    Region touchableRegion = mTempRegion3;
+                    windowState.getTouchableRegion(touchableRegion);
+                    Rect touchableFrame = mTempRect1;
+                    touchableRegion.getBounds(touchableFrame);
                     RectF windowFrame = mTempRectF;
+                    windowFrame.set(touchableFrame);
+                    windowFrame.offset(-windowState.mFrame.left, -windowState.mFrame.top);
+                    matrix.mapRect(windowFrame);
+                    Region windowBounds = mTempRegion2;
+                    windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
+                            (int) windowFrame.right, (int) windowFrame.bottom);
+                    // Only update new regions
+                    Region portionOfWindowAlreadyAccountedFor = mTempRegion3;
+                    portionOfWindowAlreadyAccountedFor.set(mMagnifiedBounds);
+                    portionOfWindowAlreadyAccountedFor.op(nonMagnifiedBounds, Region.Op.UNION);
+                    windowBounds.op(portionOfWindowAlreadyAccountedFor, Region.Op.DIFFERENCE);
 
                     if (mWindowManagerService.mPolicy.canMagnifyWindow(windowState.mAttrs.type)) {
-                        windowFrame.set(windowState.mFrame);
-                        windowFrame.offset(-windowFrame.left, -windowFrame.top);
-                        matrix.mapRect(windowFrame);
-                        windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
-                                (int) windowFrame.right, (int) windowFrame.bottom);
                         mMagnifiedBounds.op(windowBounds, Region.Op.UNION);
                         mMagnifiedBounds.op(mAvailableBounds, Region.Op.INTERSECT);
                     } else {
-                        Region touchableRegion = mTempRegion3;
-                        windowState.getTouchableRegion(touchableRegion);
-                        Rect touchableFrame = mTempRect1;
-                        touchableRegion.getBounds(touchableFrame);
-                        windowFrame.set(touchableFrame);
-                        windowFrame.offset(-windowState.mFrame.left, -windowState.mFrame.top);
-                        matrix.mapRect(windowFrame);
-                        windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
-                                (int) windowFrame.right, (int) windowFrame.bottom);
                         nonMagnifiedBounds.op(windowBounds, Region.Op.UNION);
-                        windowBounds.op(mMagnifiedBounds, Region.Op.DIFFERENCE);
                         mAvailableBounds.op(windowBounds, Region.Op.DIFFERENCE);
                     }
 
+                    // Update accounted bounds
                     Region accountedBounds = mTempRegion2;
                     accountedBounds.set(mMagnifiedBounds);
                     accountedBounds.op(nonMagnifiedBounds, Region.Op.UNION);
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index c0c1ed8..daeb860 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -195,10 +195,8 @@
 
     @Override
     public void repositionChild(IWindow window, int left, int top, int right, int bottom,
-            int requestedWidth, int requestedHeight,
             long deferTransactionUntilFrame, Rect outFrame) {
         mService.repositionChild(this, window, left, top, right, bottom,
-                requestedWidth, requestedHeight,
                 deferTransactionUntilFrame, outFrame);
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 6d350b0..1a9e206 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2531,7 +2531,6 @@
 
     void repositionChild(Session session, IWindow client,
             int left, int top, int right, int bottom,
-            int requestedWidth, int requestedHeight,
             long deferTransactionUntilFrame, Rect outFrame) {
         Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "repositionChild");
         long origId = Binder.clearCallingIdentity();
@@ -2547,7 +2546,6 @@
                             "repositionChild called but window is not"
                             + "attached to a parent win=" + win);
                 }
-                win.setRequestedSize(requestedWidth, requestedHeight);
 
                 win.mAttrs.x = left;
                 win.mAttrs.y = top;
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
index 53adb41..5a6a00f 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
@@ -97,7 +97,6 @@
 
     @Override
     public void repositionChild(IWindow window, int left, int top, int right, int bottom,
-            int requestedWidth, int requestedHeight,
             long deferTransactionUntilFrame, Rect outFrame) {
         // pass for now.
         return;