Merge "JniUtil depends on webcore native library and should not depend on others to load it"
diff --git a/Android.mk b/Android.mk
index c9a8213..d4d9a33 100644
--- a/Android.mk
+++ b/Android.mk
@@ -136,7 +136,6 @@
 	core/java/android/view/accessibility/IAccessibilityInteractionConnectionCallback.aidl\
 	core/java/android/view/accessibility/IAccessibilityManager.aidl \
 	core/java/android/view/accessibility/IAccessibilityManagerClient.aidl \
-	core/java/android/view/inputmethod/ISpellCheckerService.aidl \
 	core/java/android/view/IApplicationToken.aidl \
 	core/java/android/view/IOnKeyguardExitResult.aidl \
 	core/java/android/view/IRotationWatcher.aidl \
@@ -164,7 +163,6 @@
 	core/java/com/android/internal/view/IInputMethodClient.aidl \
 	core/java/com/android/internal/view/IInputMethodManager.aidl \
 	core/java/com/android/internal/view/IInputMethodSession.aidl \
-	core/java/com/android/internal/view/ITextServiceManager.aidl \
 	core/java/com/android/internal/widget/IRemoteViewsFactory.aidl \
 	core/java/com/android/internal/widget/IRemoteViewsAdapterConnection.aidl \
 	keystore/java/android/security/IKeyChainAliasCallback.aidl \
@@ -272,7 +270,6 @@
 	frameworks/base/core/java/com/android/internal/view/IInputMethodClient.aidl \
 	frameworks/base/core/java/com/android/internal/view/IInputMethodManager.aidl \
 	frameworks/base/core/java/com/android/internal/view/IInputMethodSession.aidl \
-	frameworks/base/core/java/com/android/internal/view/ITextServiceManager.aidl \
 	frameworks/base/graphics/java/android/graphics/Bitmap.aidl \
 	frameworks/base/graphics/java/android/graphics/Rect.aidl \
 	frameworks/base/graphics/java/android/graphics/Region.aidl \
diff --git a/api/current.txt b/api/current.txt
index a499196..721e33e 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -21,7 +21,6 @@
     field public static final java.lang.String BIND_DEVICE_ADMIN = "android.permission.BIND_DEVICE_ADMIN";
     field public static final java.lang.String BIND_INPUT_METHOD = "android.permission.BIND_INPUT_METHOD";
     field public static final java.lang.String BIND_REMOTEVIEWS = "android.permission.BIND_REMOTEVIEWS";
-    field public static final java.lang.String BIND_TEXT_SERVICE = "android.permission.BIND_TEXT_SERVICE";
     field public static final java.lang.String BIND_WALLPAPER = "android.permission.BIND_WALLPAPER";
     field public static final java.lang.String BLUETOOTH = "android.permission.BLUETOOTH";
     field public static final java.lang.String BLUETOOTH_ADMIN = "android.permission.BLUETOOTH_ADMIN";
@@ -4734,7 +4733,6 @@
     field public static final java.lang.String SENSOR_SERVICE = "sensor";
     field public static final java.lang.String STORAGE_SERVICE = "storage";
     field public static final java.lang.String TELEPHONY_SERVICE = "phone";
-    field public static final java.lang.String TEXT_SERVICE_MANAGER_SERVICE = "text_service_manager_service";
     field public static final java.lang.String UI_MODE_SERVICE = "uimode";
     field public static final java.lang.String USB_SERVICE = "usb";
     field public static final java.lang.String VIBRATOR_SERVICE = "vibrator";
@@ -23338,19 +23336,6 @@
     field public int token;
   }
 
-  public abstract interface ISpellCheckerService implements android.os.IInterface {
-    method public abstract void cancel() throws android.os.RemoteException;
-    method public abstract java.lang.CharSequence getSuggestions(java.lang.CharSequence, int, int, java.lang.String) throws android.os.RemoteException;
-    method public abstract boolean isCorrect(java.lang.CharSequence, int, int, java.lang.String) throws android.os.RemoteException;
-  }
-
-  public static abstract class ISpellCheckerService.Stub extends android.os.Binder implements android.view.inputmethod.ISpellCheckerService {
-    ctor public ISpellCheckerService.Stub();
-    method public android.os.IBinder asBinder();
-    method public static android.view.inputmethod.ISpellCheckerService asInterface(android.os.IBinder);
-    method public boolean onTransact(int, android.os.Parcel, android.os.Parcel, int) throws android.os.RemoteException;
-  }
-
   public final class InputBinding implements android.os.Parcelable {
     ctor public InputBinding(android.view.inputmethod.InputConnection, android.os.IBinder, int, int);
     ctor public InputBinding(android.view.inputmethod.InputConnection, android.view.inputmethod.InputBinding);
@@ -23535,39 +23520,6 @@
     field public static final android.os.Parcelable.Creator CREATOR;
   }
 
-  public final class SpellCheckerInfo implements android.os.Parcelable {
-    method public int describeContents();
-    method public android.content.ComponentName getComponent();
-    method public java.lang.String getId();
-    method public java.lang.String getPackageName();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator CREATOR;
-  }
-
-  public abstract class SpellCheckerService extends android.app.Service {
-    ctor public SpellCheckerService();
-    method protected void cancel();
-    method protected static java.util.Locale constructLocaleFromString(java.lang.String);
-    method protected abstract java.lang.String[] getStringSuggestions(java.lang.CharSequence, int, int, java.lang.String);
-    method protected java.lang.CharSequence getSuggestions(java.lang.CharSequence, int, int, java.lang.String);
-    method protected abstract boolean isCorrect(java.lang.CharSequence, int, int, java.lang.String);
-    method public final android.os.IBinder onBind(android.content.Intent);
-    field public static final java.lang.String SERVICE_INTERFACE;
-  }
-
-  public final class TextServiceManager {
-    method public void getSuggestions(java.lang.CharSequence, int, int, java.util.Locale, boolean, android.view.inputmethod.TextServiceManager.Callback);
-    method public void isCorrect(java.lang.CharSequence, android.view.inputmethod.TextServiceManager.Callback);
-    method public void isCorrect(java.lang.CharSequence, java.util.Locale, android.view.inputmethod.TextServiceManager.Callback);
-    method public void isCorrect(java.lang.CharSequence, int, int, java.util.Locale, android.view.inputmethod.TextServiceManager.Callback);
-    method public android.view.inputmethod.SpellCheckerInfo requestSpellCheckerConnection(java.util.Locale);
-  }
-
-  public static abstract interface TextServiceManager.Callback {
-    method public abstract void getSuggestionsResult(java.lang.CharSequence, int, int, java.util.Locale, java.lang.CharSequence);
-    method public abstract void isCorrectResult(java.lang.CharSequence, int, int, java.util.Locale, boolean);
-  }
-
 }
 
 package android.webkit {
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 09b7dd4..94a4afa 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -85,7 +85,6 @@
 import android.view.WindowManagerImpl;
 import android.view.accessibility.AccessibilityManager;
 import android.view.inputmethod.InputMethodManager;
-import android.view.inputmethod.TextServiceManager;
 import android.accounts.AccountManager;
 import android.accounts.IAccountManager;
 import android.app.admin.DevicePolicyManager;
@@ -322,11 +321,6 @@
                     return InputMethodManager.getInstance(ctx);
                 }});
 
-        registerService(TEXT_SERVICE_MANAGER_SERVICE, new ServiceFetcher() {
-                public Object createService(ContextImpl ctx) {
-                    return TextServiceManager.getInstance(ctx);
-                }});
-
         registerService(KEYGUARD_SERVICE, new ServiceFetcher() {
                 public Object getService(ContextImpl ctx) {
                     // TODO: why isn't this caching it?  It wasn't
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 7261c84..aecec66 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -1600,15 +1600,6 @@
 
     /**
      * Use with {@link #getSystemService} to retrieve a
-     * {@link android.view.inputmethod.TextServiceManager} for accessing
-     * text services.
-     *
-     * @see #getSystemService
-     */
-    public static final String TEXT_SERVICE_MANAGER_SERVICE = "text_service_manager_service";
-
-    /**
-     * Use with {@link #getSystemService} to retrieve a
      * {@link android.appwidget.AppWidgetManager} for accessing AppWidgets.
      *
      * @hide
diff --git a/core/java/android/hardware/usb/IUsbManager.aidl b/core/java/android/hardware/usb/IUsbManager.aidl
index 2b9c082..9bab797 100644
--- a/core/java/android/hardware/usb/IUsbManager.aidl
+++ b/core/java/android/hardware/usb/IUsbManager.aidl
@@ -82,11 +82,8 @@
     /* Clears default preferences and permissions for the package */
     void clearDefaults(String packageName);
 
-    /* Sets the current primary USB function. */
-    void setPrimaryFunction(String functions);
-
-    /* Sets the default primary USB function. */
-    void setDefaultFunction(String functions);
+    /* Sets the current USB function. */
+    void setCurrentFunction(String function, boolean makeDefault);
 
     /* Sets the file path for USB mass storage backing file. */
     void setMassStorageBackingFile(String path);
diff --git a/core/java/android/hardware/usb/UsbManager.java b/core/java/android/hardware/usb/UsbManager.java
index a828a23..67d200c 100644
--- a/core/java/android/hardware/usb/UsbManager.java
+++ b/core/java/android/hardware/usb/UsbManager.java
@@ -408,32 +408,18 @@
     }
 
     /**
-     * Sets the primary USB function.
+     * Sets the current USB function.
      *
      * @param function name of the USB function
+     * @param makeDefault true if this should be set as the default
      *
      * {@hide}
      */
-    public void setPrimaryFunction(String function) {
+    public void setCurrentFunction(String function, boolean makeDefault) {
         try {
-            mService.setPrimaryFunction(function);
+            mService.setCurrentFunction(function, makeDefault);
         } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in setPrimaryFunction", e);
-        }
-    }
-
-    /**
-     * Sets the default primary USB function.
-     *
-     * @param function name of the USB function
-     *
-     * {@hide}
-     */
-    public void setDefaultFunction(String function) {
-        try {
-            mService.setDefaultFunction(function);
-        } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in setDefaultFunction", e);
+            Log.e(TAG, "RemoteException in setCurrentFunction", e);
         }
     }
 
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index d456813..19e9a67 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -16,6 +16,8 @@
 
 package android.provider;
 
+
+
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
 import android.content.ComponentName;
@@ -45,6 +47,7 @@
 import java.util.HashMap;
 import java.util.HashSet;
 
+
 /**
  * The Settings provider contains global system-level device preferences.
  */
@@ -3630,15 +3633,6 @@
          */
         public static final String VOICE_RECOGNITION_SERVICE = "voice_recognition_service";
 
-
-        /**
-         * The {@link ComponentName} string of the service to be used as the spell checker
-         * service which is one of the services managed by the text service manager.
-         *
-         * @hide
-         */
-        public static final String SPELL_CHECKER_SERVICE = "spell_checker_service";
-
         /**
          * What happens when the user presses the Power button while in-call
          * and the screen is on.<br/>
diff --git a/core/java/android/view/ViewAncestor.java b/core/java/android/view/ViewAncestor.java
index afbedaf..40e99a1 100644
--- a/core/java/android/view/ViewAncestor.java
+++ b/core/java/android/view/ViewAncestor.java
@@ -1000,8 +1000,7 @@
                     + "x" + desiredWindowHeight + "...");
 
             boolean goodMeasure = false;
-            if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
-                    || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
+            if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
                 // On large screens, we don't want to allow dialogs to just
                 // stretch to fill the entire width of the screen to display
                 // one line of text.  First try doing the layout at a smaller
diff --git a/core/java/android/view/inputmethod/ISpellCheckerService.aidl b/core/java/android/view/inputmethod/ISpellCheckerService.aidl
deleted file mode 100644
index 68e406a..0000000
--- a/core/java/android/view/inputmethod/ISpellCheckerService.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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 android.view.inputmethod;
-
-/**
- * Public interface to the global input text manager, used by all client
- * applications.
- */
-interface ISpellCheckerService {
-    boolean isCorrect(CharSequence text, int start, int end, String locale);
-    CharSequence getSuggestions(CharSequence text, int start, int end, String locale);
-    void cancel();
-}
diff --git a/core/java/android/view/inputmethod/SpellCheckerInfo.aidl b/core/java/android/view/inputmethod/SpellCheckerInfo.aidl
deleted file mode 100644
index 0266038..0000000
--- a/core/java/android/view/inputmethod/SpellCheckerInfo.aidl
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * 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 android.view.inputmethod;
-
-parcelable SpellCheckerInfo;
diff --git a/core/java/android/view/inputmethod/SpellCheckerInfo.java b/core/java/android/view/inputmethod/SpellCheckerInfo.java
deleted file mode 100644
index 9754df2..0000000
--- a/core/java/android/view/inputmethod/SpellCheckerInfo.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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 android.view.inputmethod;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-public final class SpellCheckerInfo implements Parcelable {
-    private final ResolveInfo mService;
-    private final String mId;
-
-    /**
-     * Constructor.
-     * @hide
-     */
-    public SpellCheckerInfo(Context context, ResolveInfo service) {
-        mService = service;
-        ServiceInfo si = service.serviceInfo;
-        mId = new ComponentName(si.packageName, si.name).flattenToShortString();
-    }
-
-    /**
-     * Constructor.
-     * @hide
-     */
-    public SpellCheckerInfo(Parcel source) {
-        mId = source.readString();
-        mService = ResolveInfo.CREATOR.createFromParcel(source);
-    }
-
-    /**
-     * Return a unique ID for this spell checker.  The ID is generated from
-     * the package and class name implementing the method.
-     */
-    public String getId() {
-        return mId;
-    }
-
-
-    /**
-     * Return the component of the service that implements.
-     */
-    public ComponentName getComponent() {
-        return new ComponentName(
-                mService.serviceInfo.packageName, mService.serviceInfo.name);
-    }
-
-    /**
-     * Return the .apk package that implements this input method.
-     */
-    public String getPackageName() {
-        return mService.serviceInfo.packageName;
-    }
-
-    /**
-     * Used to package this object into a {@link Parcel}.
-     *
-     * @param dest The {@link Parcel} to be written.
-     * @param flags The flags used for parceling.
-     */
-    @Override
-    public void writeToParcel(Parcel dest, int flags) {
-        dest.writeString(mId);
-        mService.writeToParcel(dest, flags);
-    }
-
-
-    /**
-     * Used to make this class parcelable.
-     */
-    public static final Parcelable.Creator<SpellCheckerInfo> CREATOR
-            = new Parcelable.Creator<SpellCheckerInfo>() {
-        @Override
-        public SpellCheckerInfo createFromParcel(Parcel source) {
-            return new SpellCheckerInfo(source);
-        }
-
-        @Override
-        public SpellCheckerInfo[] newArray(int size) {
-            return new SpellCheckerInfo[size];
-        }
-    };
-
-    /**
-     * Used to make this class parcelable.
-     */
-    @Override
-    public int describeContents() {
-        return 0;
-    }
-}
diff --git a/core/java/android/view/inputmethod/SpellCheckerService.java b/core/java/android/view/inputmethod/SpellCheckerService.java
deleted file mode 100644
index ebd42e3..0000000
--- a/core/java/android/view/inputmethod/SpellCheckerService.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * 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 android.view.inputmethod;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-import android.text.Spannable;
-import android.text.SpannableString;
-import android.text.Spanned;
-import android.text.TextUtils;
-import android.text.style.SuggestionSpan;
-
-import java.util.Arrays;
-import java.util.Locale;
-
-public abstract class SpellCheckerService extends Service {
-    public static final String SERVICE_INTERFACE = SpellCheckerService.class.getName();
-
-    private final SpellCheckerServiceBinder mBinder = new SpellCheckerServiceBinder(this);
-
-    /**
-     * Check if the substring of text from start to end is a correct word or not in the specified
-     * locale.
-     * @param text the substring of text from start to end will be checked.
-     * @param start the start position of the text to be checked (inclusive)
-     * @param end the end position of the text to be checked (exclusive)
-     * @param locale the locale for checking the text
-     * @return true if the substring of text from start to end is a correct word
-     */
-    protected abstract boolean isCorrect(CharSequence text, int start, int end, String locale);
-
-    /**
-     * @param text the substring of text from start to end for getting suggestions
-     * @param start the start position of the text (inclusive)
-     * @param end the end position of the text (exclusive)
-     * @param locale the locale for getting suggestions
-     * @return text with SuggestionSpan containing suggestions
-     */
-    protected CharSequence getSuggestions(CharSequence text, int start, int end, String locale) {
-        if (TextUtils.isEmpty(text) || TextUtils.isEmpty(locale) || end <= start) {
-            return text;
-        }
-        final String[] suggestions = getStringSuggestions(text, start, end, locale);
-        if (suggestions == null || suggestions.length == 0) {
-            return text;
-        }
-        final Spannable spannable;
-        if (text instanceof Spannable) {
-            spannable = (Spannable) text;
-        } else {
-            spannable = new SpannableString(text);
-        }
-        final int N = Math.min(SuggestionSpan.SUGGESTIONS_MAX_SIZE, suggestions.length);
-        final SuggestionSpan ss = new SuggestionSpan(
-                constructLocaleFromString(locale), Arrays.copyOfRange(suggestions, 0, N), 0);
-        spannable.setSpan(ss, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-        return spannable;
-    }
-
-    /**
-     * Basic implementation for getting suggestions. This function is called from getSuggestions
-     * and the returned strings array will be set as a SuggestionSpan.
-     * If you want to set SuggestionSpan by yourself, make getStringSuggestions an empty
-     * implementation and override getSuggestions.
-     * @param text the substring of text from start to end for getting suggestions
-     * @param start the start position of the text (inclusive)
-     * @param end the end position of the text (exclusive)
-     * @param locale the locale for getting suggestions
-     * @return strings array for the substring of the specified text.
-     */
-    protected abstract String[] getStringSuggestions(
-            CharSequence text, int start, int end, String locale);
-
-    /**
-     * Request to abort all tasks executed in SpellChecker
-     */
-    protected void cancel() {}
-
-    @Override
-    public final IBinder onBind(final Intent intent) {
-        return mBinder;
-    }
-
-    @Override
-    public void onDestroy() {
-        mBinder.clearReference();
-        super.onDestroy();
-    }
-
-    protected static final Locale constructLocaleFromString(String localeStr) {
-        if (TextUtils.isEmpty(localeStr))
-            return null;
-        String[] localeParams = localeStr.split("_", 3);
-        // The length of localeParams is guaranteed to always return a 1 <= value <= 3.
-        if (localeParams.length == 1) {
-            return new Locale(localeParams[0]);
-        } else if (localeParams.length == 2) {
-            return new Locale(localeParams[0], localeParams[1]);
-        } else if (localeParams.length == 3) {
-            return new Locale(localeParams[0], localeParams[1], localeParams[2]);
-        }
-        return null;
-    }
-
-    private static class SpellCheckerServiceBinder extends ISpellCheckerService.Stub {
-        private SpellCheckerService mInternalService;
-
-        public SpellCheckerServiceBinder(SpellCheckerService service) {
-            mInternalService = service;
-        }
-
-        @Override
-        public CharSequence getSuggestions(CharSequence text, int start, int end, String locale) {
-            return mInternalService.getSuggestions(text, start, end, locale);
-        }
-
-        @Override
-        public boolean isCorrect(CharSequence text, int start, int end, String locale) {
-            return mInternalService.isCorrect(text, start, end, locale);
-        }
-
-        @Override
-        public void cancel() {}
-
-        private void clearReference() {
-            mInternalService = null;
-        }
-    }
-}
diff --git a/core/java/android/view/inputmethod/TextServiceManager.java b/core/java/android/view/inputmethod/TextServiceManager.java
deleted file mode 100644
index 9eecc9d..0000000
--- a/core/java/android/view/inputmethod/TextServiceManager.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
- * 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 android.view.inputmethod;
-
-import com.android.internal.view.ITextServiceManager;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Message;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.inputmethod.ISpellCheckerService;
-import android.view.inputmethod.SpellCheckerService;
-
-import java.lang.ref.WeakReference;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.Locale;
-import java.util.Queue;
-
-public final class TextServiceManager {
-    private static final String TAG = TextServiceManager.class.getSimpleName();
-    private static final boolean DBG = false;
-    private static final int MSG_CANCEL = 1;
-    private static final int MSG_IS_CORRECT = 2;
-    private static final int MSG_GET_SUGGESTION = 3;
-
-    private static TextServiceManager sInstance;
-    private static ITextServiceManager sService;
-
-    private final WeakReference<Context> mContextRef;
-    private static final HashMap<String, SpellCheckerConnection> sComponentMap =
-            new HashMap<String, SpellCheckerConnection>();
-
-    private TextServiceManager(Context context) {
-        mContextRef = new WeakReference<Context>(context);
-        synchronized (sComponentMap) {
-            if (sService == null) {
-                IBinder b = ServiceManager.getService(Context.TEXT_SERVICE_MANAGER_SERVICE);
-                sService = ITextServiceManager.Stub.asInterface(b);
-            }
-        }
-    }
-
-    /**
-     * Retrieve the global TextServiceManager instance, creating it if it doesn't already exist.
-     * @hide
-     */
-    public static TextServiceManager getInstance(Context context) {
-        synchronized (sComponentMap) {
-            if (sInstance != null) {
-                return sInstance;
-            }
-            sInstance = new TextServiceManager(context);
-        }
-        return sInstance;
-    }
-
-    private static class SpellCheckerConnection implements ServiceConnection {
-        private final String mLocale;
-        private ISpellCheckerService mSpellCheckerService;
-        private final Queue<Message> mPendingTasks = new LinkedList<Message>();
-        private final SpellCheckerInfo mSpellCheckerInfo;
-
-        private static class SpellCheckerParams {
-            public final CharSequence mText;
-            public final int mStart;
-            public final int mEnd;
-            public final Locale mLocale;
-            public final Callback mCallback;
-            public SpellCheckerParams(
-                    CharSequence text, int start, int end, Locale locale, Callback callback) {
-                mText = text;
-                mStart = start;
-                mEnd = end;
-                mLocale = locale;
-                mCallback = callback;
-            }
-        }
-
-        private final Handler mHandler = new Handler() {
-            @Override
-            public void handleMessage(Message msg) {
-                switch (msg.what) {
-                    case MSG_CANCEL:
-                        handleCancelMessage();
-                        break;
-                    case MSG_IS_CORRECT:
-                        handleIsCorrectMessage((SpellCheckerParams) msg.obj);
-                        break;
-                    case MSG_GET_SUGGESTION:
-                        handleGetSuggestionMessage((SpellCheckerParams) msg.obj);
-                        break;
-                }
-            }
-        };
-
-        public SpellCheckerConnection(String locale, SpellCheckerInfo sci) {
-            mLocale = locale;
-            mSpellCheckerInfo = sci;
-        }
-
-        @Override
-        public synchronized void onServiceConnected(
-                final ComponentName name, final IBinder service) {
-            mSpellCheckerService = ISpellCheckerService.Stub.asInterface(service);
-            if (DBG)
-                Log.d(TAG, "onServiceConnected - Success");
-            while (!mPendingTasks.isEmpty()) {
-                mHandler.sendMessage(mPendingTasks.poll());
-            }
-        }
-
-        @Override
-        public void onServiceDisconnected(final ComponentName name) {
-            mSpellCheckerService = null;
-            mPendingTasks.clear();
-            synchronized(sComponentMap) {
-                sComponentMap.remove(mLocale);
-            }
-            if (DBG)
-                Log.d(TAG, "onServiceDisconnected - Success");
-        }
-
-        public void isCorrect(
-                CharSequence text, int start, int end, Locale locale, Callback callback) {
-            if (callback == null) {
-                throw new IllegalArgumentException("isCorrect: Callback is null.");
-            }
-            putMessage(Message.obtain(mHandler, MSG_IS_CORRECT,
-                    new SpellCheckerParams(text, start, end, locale, callback)));
-        }
-
-        public void getSuggestions(
-                CharSequence text, int start, int end, Locale locale, Callback callback) {
-            if (callback == null) {
-                throw new IllegalArgumentException("getSuggestions: Callback is null.");
-            }
-            putMessage(Message.obtain(mHandler, MSG_GET_SUGGESTION,
-                    new SpellCheckerParams(text, start, end, locale, callback)));
-        }
-
-        public SpellCheckerInfo getSpellCheckerInfo() {
-            return mSpellCheckerInfo;
-        }
-
-        private boolean checkOpenConnection() {
-            if (mSpellCheckerService != null) {
-                return true;
-            }
-            Log.e(TAG, "not connected to the spellchecker service.");
-            return false;
-        }
-
-        private void putMessage(Message msg) {
-            if (mSpellCheckerService == null) {
-                mPendingTasks.offer(msg);
-            } else {
-                mHandler.sendMessage(msg);
-            }
-        }
-
-        private void handleCancelMessage() {
-            if (!checkOpenConnection()) {
-                return;
-            }
-            try {
-                mSpellCheckerService.cancel();
-            } catch (RemoteException e) {
-                Log.e(TAG, "Remote exception in cancel.");
-            }
-        }
-
-        private void handleIsCorrectMessage(SpellCheckerParams scp) {
-            if (!checkOpenConnection()) {
-                return;
-            }
-            try {
-                scp.mCallback.isCorrectResult(scp.mText, scp.mStart, scp.mEnd, scp.mLocale,
-                        mSpellCheckerService.isCorrect(
-                                scp.mText, scp.mStart, scp.mEnd, scp.mLocale.toString()));
-            } catch (RemoteException e) {
-                Log.e(TAG, "Remote exception in isCorrect.");
-            }
-        }
-
-        private void handleGetSuggestionMessage(SpellCheckerParams scp) {
-            if (!checkOpenConnection()) {
-                return;
-            }
-            try {
-                scp.mCallback.getSuggestionsResult(scp.mText, scp.mStart, scp.mEnd, scp.mLocale,
-                        mSpellCheckerService.getSuggestions(
-                                scp.mText, scp.mStart, scp.mEnd, scp.mLocale.toString()));
-            } catch (RemoteException e) {
-                Log.e(TAG, "Remote exception in getSuggestion.");
-            }
-        }
-    }
-
-    /**
-     * Check if the substring of text from start to end is a correct word or not in the
-     * default locale for the context.
-     * @param text text
-     * @param callback callback for getting the result from SpellChecker
-     * @return true if the substring of text from start to end is a correct word
-     */
-    public void isCorrect(CharSequence text, Callback callback) {
-        final Context context = mContextRef.get();
-        if (context == null) {
-            return;
-        }
-        isCorrect(text, mContextRef.get().getResources().getConfiguration().locale, callback);
-    }
-
-    /**
-     * Check if the substring of text from start to end is a correct word or not in the
-     * specified locale.
-     * @param text text
-     * @param locale the locale for checking the text
-     * @param callback callback for getting the result from SpellChecker
-     * @return true if the substring of text from start to end is a correct word
-     */
-    public void isCorrect(CharSequence text, Locale locale, Callback callback) {
-        isCorrect(text, 0, text.length(), locale, callback);
-    }
-
-    /**
-     * Check if the substring of text from start to end is a correct word or not in the
-     * specified locale.
-     * @param text text
-     * @param start the start position of the text to be checked
-     * @param end the end position of the text to be checked
-     * @param locale the locale for checking the text
-     * @param callback callback for getting the result from SpellChecker
-     * @return true if the substring of text from start to end is a correct word
-     */
-    public void isCorrect(CharSequence text, int start, int end, Locale locale, Callback callback) {
-        if (TextUtils.isEmpty(text) || locale == null || callback == null) {
-            throw new IllegalArgumentException(
-                    "text = " + text + ", locale = " + locale + ", callback = " + callback);
-        }
-        final int textSize = text.length();
-        if (start < 0 || textSize <= start || end < 0 || textSize <= end || start >= end) {
-            throw new IndexOutOfBoundsException(
-                    "text = " + text + ", start = " + start + ", end = " + end);
-        }
-        final SpellCheckerConnection spellCheckerConnection =
-            getCurrentSpellCheckerConnection(locale, false);
-        if (spellCheckerConnection == null) {
-            Log.e(TAG, "Could not find spellchecker for " + locale);
-            return;
-        }
-        spellCheckerConnection.isCorrect(text, start, end, locale, callback);
-    }
-
-    /**
-     * Get candidate strings for a substring of the specified text.
-     * @param text the substring of text from start to end for getting suggestions
-     * @param start the start position of the text
-     * @param end the end position of the text
-     * @param locale the locale for getting suggestions
-     * @param callback callback for getting the result from SpellChecker
-     * @return text with SuggestionSpan containing suggestions
-     */
-    public void getSuggestions(CharSequence text, int start, int end, Locale locale,
-            boolean allowMultipleWords, Callback callback) {
-        if (TextUtils.isEmpty(text) || locale == null || callback == null) {
-            throw new IllegalArgumentException(
-                    "text = " + text + ", locale = " + locale + ", callback = " + callback);
-        }
-        final int textService = text.length();
-        if (start < 0 || textService <= start || end < 0 || textService <= end || start >= end) {
-            throw new IndexOutOfBoundsException(
-                    "text = " + text + ", start = " + start + ", end = " + end);
-        }
-        final SpellCheckerConnection spellCheckerConnection = getCurrentSpellCheckerConnection(
-                locale, false);
-        if (spellCheckerConnection == null) {
-            Log.e(TAG, "Could not find spellchecker for " + locale);
-            return;
-        }
-        // TODO: Handle multiple words suggestions by using WordBreakIterator
-        spellCheckerConnection.getSuggestions(text, start, end, locale, callback);
-    }
-
-    /**
-     * Get the current spell checker service for the specified locale. It's recommended
-     * to call this method before calling other APIs in TextServiceManager.
-     * This method may update the current spell checker in use for the specified locale if the user
-     * has selected a different spell checker for the locale.
-     * @param locale locale of a spell checker
-     * @return SpellCheckerInfo for the specified locale.
-     */
-    // TODO: Add a method to get enabled spell checkers.
-    // TODO: Add a method to set a spell checker
-    public SpellCheckerInfo requestSpellCheckerConnection(Locale locale) {
-        if (locale == null) return null;
-        final SpellCheckerConnection scc = getCurrentSpellCheckerConnection(locale, true);
-        if (scc == null) return null;
-        return scc.getSpellCheckerInfo();
-    }
-
-    private SpellCheckerConnection getCurrentSpellCheckerConnection(
-            Locale locale, boolean resetIfChanged) {
-        final Context context = mContextRef.get();
-        if (locale == null) {
-            return null;
-        }
-        if (context == null) {
-            throw new RuntimeException("Context was GCed.");
-        }
-        final String localeStr = locale.toString();
-        SpellCheckerConnection connection = null;
-        synchronized (sComponentMap) {
-            if (sComponentMap.containsKey(localeStr)) {
-                connection = sComponentMap.get(localeStr);
-            }
-            if (connection != null && !resetIfChanged) {
-                return connection;
-            }
-            try {
-                final SpellCheckerInfo sci = sService.getCurrentSpellChecker(localeStr);
-                if (sci == null) {
-                    return null;
-                }
-                if (connection != null
-                        && connection.getSpellCheckerInfo().getId().equals(sci.getId())) {
-                    return connection;
-                }
-                connection = new SpellCheckerConnection(localeStr, sci);
-                final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
-
-                serviceIntent.setComponent(sci.getComponent());
-                if (!context.bindService(serviceIntent, connection,
-                        Context.BIND_AUTO_CREATE)) {
-                    Log.e(TAG, "Bind to spell checker service failed.");
-                    return null;
-                }
-                sComponentMap.put(localeStr, connection);
-                return connection;
-            } catch (RemoteException e) {
-                return null;
-            }
-        }
-    }
-
-    /**
-     * Callback for getting results from TextService
-     */
-    public interface Callback {
-        /**
-         * Callback for "isCorrect"
-         * @param text the input for isCorrect
-         * @param start the input for isCorrect
-         * @param end the input for isCorrect
-         * @param locale the input for isCorrect
-         * @param result true if the specified text is a correct word.
-         */
-        public void isCorrectResult(
-                CharSequence text, int start, int end, Locale locale, boolean result);
-        /**
-         * Callback for "getSuggestions"
-         * @param text the input for getSuggestions
-         * @param start the input for getSuggestions
-         * @param end the input for getSuggestions
-         * @param locale the input for getSuggestions
-         * @param result text with "SuggestionSpan"s attached over CharSequence
-         */
-        public void getSuggestionsResult(
-                CharSequence text, int start, int end, Locale locale, CharSequence result);
-    }
-}
diff --git a/core/java/android/widget/GridLayout.java b/core/java/android/widget/GridLayout.java
index 0e52869..e88d257 100644
--- a/core/java/android/widget/GridLayout.java
+++ b/core/java/android/widget/GridLayout.java
@@ -535,7 +535,7 @@
         return result;
     }
 
-    private int getDefaultMargin(View c, boolean leading, boolean horizontal) {
+    private int getDefaultMargin(View c, boolean horizontal, boolean leading) {
         // In the absence of any other information, calculate a default gap such
         // that, in a grid of identical components, the heights and the vertical
         // gaps are in the proportion of the golden ratio.
@@ -544,12 +544,12 @@
         return (int) (c.getMeasuredHeight() / GOLDEN_RATIO / 2);
     }
 
-    private int getDefaultMargin(View c, boolean isAtEdge, boolean leading, boolean horizontal) {
+    private int getDefaultMargin(View c, boolean isAtEdge, boolean horizontal, boolean leading) {
         // todo remove DEFAULT_CONTAINER_MARGIN. Use padding? Seek advice on Themes/Styles, etc.
-        return isAtEdge ? DEFAULT_CONTAINER_MARGIN : getDefaultMargin(c, leading, horizontal);
+        return isAtEdge ? DEFAULT_CONTAINER_MARGIN : getDefaultMargin(c, horizontal, leading);
     }
 
-    private int getDefaultMarginValue(View c, LayoutParams p, boolean leading, boolean horizontal) {
+    private int getDefaultMarginValue(View c, LayoutParams p, boolean horizontal, boolean leading) {
         if (!mUseDefaultMargins) {
             return 0;
         }
@@ -558,15 +558,19 @@
         Interval span = group.span;
         boolean isAtEdge = leading ? (span.min == 0) : (span.max == axis.getCount());
 
-        return getDefaultMargin(c, isAtEdge, leading, horizontal);
+        return getDefaultMargin(c, isAtEdge, horizontal, leading);
     }
 
-    private int getMargin(View view, boolean leading, boolean horizontal) {
+    private int getMargin(View view, boolean horizontal, boolean leading) {
         LayoutParams lp = getLayoutParams(view);
         int margin = horizontal ?
                 (leading ? lp.leftMargin : lp.rightMargin) :
                 (leading ? lp.topMargin : lp.bottomMargin);
-        return margin == UNDEFINED ? getDefaultMarginValue(view, lp, leading, horizontal) : margin;
+        return margin == UNDEFINED ? getDefaultMarginValue(view, lp, horizontal, leading) : margin;
+    }
+
+    private int getTotalMargin(View child, boolean horizontal) {
+        return getMargin(child, horizontal, true) + getMargin(child, horizontal, false);
     }
 
     private static int valueIfDefined(int value, int defaultValue) {
@@ -749,8 +753,8 @@
                 View c = getChildAt(i);
                 drawRectangle(canvas,
                         c.getLeft() - getMargin(c, true, true),
-                        c.getTop() - getMargin(c, true, false),
-                        c.getRight() + getMargin(c, false, true),
+                        c.getTop() - getMargin(c, false, true),
+                        c.getRight() + getMargin(c, true, false),
                         c.getBottom() + getMargin(c, false, false), paint);
             }
         }
@@ -794,17 +798,12 @@
         return c.getVisibility() == View.GONE;
     }
 
-    private void measureChildWithMargins(View child,
-            int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
-
+    private void measureChildWithMargins(View child, int widthMeasureSpec, int heightMeasureSpec) {
         LayoutParams lp = getLayoutParams(child);
-        int hMargins = getMargin(child, true, true) + getMargin(child, false, true);
-        int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
-                mPaddingLeft + mPaddingRight + hMargins, lp.width);
-        int vMargins = getMargin(child, true, false) + getMargin(child, false, false);
-        int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
-                mPaddingTop + mPaddingBottom + vMargins, lp.height);
-
+        int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
+                mPaddingLeft + mPaddingRight + getTotalMargin(child, true), lp.width);
+        int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
+                mPaddingTop + mPaddingBottom + getTotalMargin(child, false), lp.height);
         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
     }
 
@@ -842,9 +841,7 @@
     private int getMeasurementIncludingMargin(View c, boolean horizontal, int measurementType) {
         int result = getMeasurement(c, horizontal, measurementType);
         if (mAlignmentMode == ALIGN_MARGINS) {
-            int leadingMargin = getMargin(c, true, horizontal);
-            int trailingMargin = getMargin(c, false, horizontal);
-            return result + leadingMargin + trailingMargin;
+            return result + getTotalMargin(c, horizontal);
         }
         return result;
     }
@@ -919,8 +916,8 @@
 
             if (mAlignmentMode == ALIGN_MARGINS) {
                 int leftMargin = getMargin(c, true, true);
-                int topMargin = getMargin(c, true, false);
-                int rightMargin = getMargin(c, false, true);
+                int topMargin = getMargin(c, false, true);
+                int rightMargin = getMargin(c, true, false);
                 int bottomMargin = getMargin(c, false, false);
 
                 // Same calculation as getMeasurementIncludingMargin()
@@ -1387,7 +1384,7 @@
                 Group g = horizontal ? lp.columnGroup : lp.rowGroup;
                 Interval span = g.span;
                 int index = leading ? span.min : span.max;
-                margins[index] = max(margins[index], getMargin(c, leading, horizontal));
+                margins[index] = max(margins[index], getMargin(c, horizontal, leading));
             }
         }
 
@@ -1817,7 +1814,8 @@
         }
 
         private int getDefaultWeight(int size) {
-            return (size == MATCH_PARENT) ? DEFAULT_WEIGHT_1 : DEFAULT_WEIGHT_0;
+            //return (size == MATCH_PARENT) ? DEFAULT_WEIGHT_1 : DEFAULT_WEIGHT_0;
+            return DEFAULT_WEIGHT_0;
         }
 
         private void init(Context context, AttributeSet attrs, int defaultGravity) {
diff --git a/core/java/com/android/internal/view/ITextServiceManager.aidl b/core/java/com/android/internal/view/ITextServiceManager.aidl
deleted file mode 100644
index b288221..0000000
--- a/core/java/com/android/internal/view/ITextServiceManager.aidl
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.internal.view;
-
-import android.content.ComponentName;
-import android.view.inputmethod.SpellCheckerInfo;
-
-/**
- * Public interface to the global input text manager, used by all client
- * applications.
- */
-interface ITextServiceManager {
-    SpellCheckerInfo getCurrentSpellChecker(String locale);
-}
diff --git a/core/java/com/android/internal/widget/LockPatternView.java b/core/java/com/android/internal/widget/LockPatternView.java
index cbb110a..0c0205c 100644
--- a/core/java/com/android/internal/widget/LockPatternView.java
+++ b/core/java/com/android/internal/widget/LockPatternView.java
@@ -464,8 +464,7 @@
                 break;
             case MeasureSpec.EXACTLY:
             default:
-                // use the specified size, if non-zero
-                result = specSize != 0 ? specSize : desired;
+                result = specSize;
         }
         return result;
     }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 6cdda57..47902a8 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1112,13 +1112,6 @@
         android:description="@string/permdesc_bindInputMethod"
         android:protectionLevel="signature" />
 
-    <!-- Must be required by a TextService (e.g. SpellCheckerService)
-         to ensure that only the system can bind to it. -->
-    <permission android:name="android.permission.BIND_TEXT_SERVICE"
-        android:label="@string/permlab_bindTextService"
-        android:description="@string/permdesc_bindTextService"
-        android:protectionLevel="signature" />
-
     <!-- Must be required by a {@link android.service.wallpaper.WallpaperService},
          to ensure that only the system can bind to it. -->
     <permission android:name="android.permission.BIND_WALLPAPER"
diff --git a/core/res/res/layout/keyguard_screen_unlock_portrait.xml b/core/res/res/layout/keyguard_screen_unlock_portrait.xml
index dd68d82..03c6022 100644
--- a/core/res/res/layout/keyguard_screen_unlock_portrait.xml
+++ b/core/res/res/layout/keyguard_screen_unlock_portrait.xml
@@ -101,6 +101,10 @@
         android:visibility="gone"
         />
 
+    <!-- We need MATCH_PARENT here only to force the size of the parent to be passed to
+    the pattern view for it to compute its size. This is an unusual case, caused by
+    LockPatternView's requirement to maintain a square aspect ratio based on the width
+    of the screen. -->
     <com.android.internal.widget.LockPatternView
         android:id="@+id/lockPattern"
         android:layout_width="match_parent"
@@ -109,6 +113,8 @@
         android:layout_marginRight="8dip"
         android:layout_marginBottom="4dip"
         android:layout_marginLeft="8dip"
+        android:layout_gravity="center|bottom"
+        android:layout_rowWeight="1"
      />
 
     <TextView
@@ -123,8 +129,7 @@
     <!-- Footer: an emergency call button and an initially hidden "Forgot pattern" button -->
     <LinearLayout
         android:orientation="horizontal"
-        android:layout_width="match_parent"
-        android:layout_gravity="center">
+        android:layout_gravity="fill_horizontal">
 
         <Button android:id="@+id/emergencyCallButton"
             android:layout_width="wrap_content"
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 156f9e2..b5f4084 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -705,12 +705,6 @@
         interface of an input method. Should never be needed for normal applications.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permlab_bindTextService">bind to a text service</string>
-    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permdesc_bindTextService">Allows the holder to bind to the top-level
-        interface of a text service(e.g. SpellCheckerService). Should never be needed for normal applications.</string>
-
-    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_bindWallpaper">bind to a wallpaper</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permdesc_bindWallpaper">Allows the holder to bind to the top-level
diff --git a/media/java/android/media/videoeditor/VideoEditorImpl.java b/media/java/android/media/videoeditor/VideoEditorImpl.java
index 2105deb..649b98a 100755
--- a/media/java/android/media/videoeditor/VideoEditorImpl.java
+++ b/media/java/android/media/videoeditor/VideoEditorImpl.java
@@ -38,6 +38,7 @@
 import android.graphics.Rect;
 import android.media.videoeditor.MediaImageItem;
 import android.media.videoeditor.MediaItem;
+import android.media.MediaMetadataRetriever;
 import android.util.Log;
 import android.util.Xml;
 import android.view.Surface;
@@ -1833,12 +1834,32 @@
             }
 
             Bitmap projectBitmap = null;
-            try {
-                projectBitmap = mI.getThumbnail(width, height, 500);
-            } catch (IllegalArgumentException e) {
-                throw new IllegalArgumentException ("Illegal argument error creating project thumbnail");
-            } catch (IOException e) {
-                throw new IllegalArgumentException ("IO Error creating project thumbnail");
+            String filename = mI.getFilename();
+            if (mI instanceof MediaVideoItem) {
+                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+                retriever.setDataSource(filename);
+                Bitmap bitmap = retriever.getFrameAtTime();
+                retriever.release();
+                retriever = null;
+                if (bitmap == null) {
+                    String msg = "Thumbnail extraction from " +
+                                    filename + " failed";
+                    throw new IllegalArgumentException(msg);
+                }
+                // Resize the thumbnail to the target size
+                projectBitmap =
+                    Bitmap.createScaledBitmap(bitmap, width, height, true);
+            } else {
+                try {
+                    projectBitmap = mI.getThumbnail(width, height, 500);
+                } catch (IllegalArgumentException e) {
+                    String msg = "Project thumbnail extraction from " +
+                                    filename + " failed";
+                    throw new IllegalArgumentException(msg);
+                } catch (IOException e) {
+                    String msg = "IO Error creating project thumbnail";
+                    throw new IllegalArgumentException(msg);
+                }
             }
 
             try {
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index ea9911c..f075699d 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -205,6 +205,8 @@
     // Duration is time scale based
     void addOneSttsTableEntry(size_t sampleCount, int32_t timescaledDur);
     void addOneCttsTableEntry(size_t sampleCount, int32_t timescaledDur);
+
+    bool isTrackMalFormed() const;
     void sendTrackSummary(bool hasMultipleTracks);
 
     // Write the boxes
@@ -1975,7 +1977,6 @@
         }
 
         CHECK(timestampUs >= 0);
-
         LOGV("%s media time stamp: %lld and previous paused duration %lld",
                 mIsAudio? "Audio": "Video", timestampUs, previousPausedDurationUs);
         if (timestampUs > mTrackDurationUs) {
@@ -2082,11 +2083,10 @@
 
     }
 
-    if (mSampleSizes.empty() ||                      // no samples written
-        (!mIsAudio && mNumStssTableEntries == 0) ||  // no sync frames for video
-        (OK != checkCodecSpecificData())) {          // no codec specific data
+    if (isTrackMalFormed()) {
         err = ERROR_MALFORMED;
     }
+
     mOwner->trackProgressStatus(mTrackId, -1, err);
 
     // Last chunk
@@ -2136,6 +2136,24 @@
     return err;
 }
 
+bool MPEG4Writer::Track::isTrackMalFormed() const {
+    if (mSampleSizes.empty()) {                      // no samples written
+        LOGE("The number of recorded samples is 0");
+        return true;
+    }
+
+    if (!mIsAudio && mNumStssTableEntries == 0) {  // no sync frames for video
+        LOGE("There are no sync frames for video track");
+        return true;
+    }
+
+    if (OK != checkCodecSpecificData()) {         // no codec specific data
+        return true;
+    }
+
+    return false;
+}
+
 void MPEG4Writer::Track::sendTrackSummary(bool hasMultipleTracks) {
 
     // Send track summary only if test mode is enabled.
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbPreferenceActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbPreferenceActivity.java
index 187a486..60906a1 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbPreferenceActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbPreferenceActivity.java
@@ -1,93 +1,96 @@
-/*

- * 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.systemui.usb;

-

-import android.app.Activity;

-import android.app.AlertDialog;

-import android.content.Context;

-import android.content.DialogInterface;

-import android.hardware.usb.UsbManager;

-import android.os.Bundle;

-import android.view.LayoutInflater;

-import android.view.View;

-import android.util.Log;

-import android.widget.Button;

-

-import java.io.File;

-

-import com.android.systemui.R;

-

-public class UsbPreferenceActivity extends Activity implements View.OnClickListener  {

-

-    private static final String TAG = "UsbPreferenceActivity";

-

-    private UsbManager mUsbManager;

-    private String mCurrentFunction;

-    private String[] mFunctions;

-    private String mInstallerImagePath;

-    private Button mMtpPtpButton;

-    private Button mInstallerCdButton;

-    private boolean mPtpActive;

-

-    @Override

-    public void onCreate(Bundle icicle) {

-        super.onCreate(icicle);

-

-        mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);

-

-        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

-        dialogBuilder.setTitle(getString(R.string.usb_preference_title));

-

-        LayoutInflater inflater = (LayoutInflater)getSystemService(

-                Context.LAYOUT_INFLATER_SERVICE);

-        View buttonView = inflater.inflate(R.layout.usb_preference_buttons, null);

-        dialogBuilder.setView(buttonView);

-        mMtpPtpButton = (Button)buttonView.findViewById(R.id.mtp_ptp_button);

-        mInstallerCdButton = (Button)buttonView.findViewById(R.id.installer_cd_button);

-        mMtpPtpButton.setOnClickListener(this);

-        mInstallerCdButton.setOnClickListener(this);

-

-        mPtpActive = mUsbManager.isFunctionEnabled(UsbManager.USB_FUNCTION_PTP);

-        if (mPtpActive) {

-            mMtpPtpButton.setText(R.string.use_mtp_button_title);

-        }

-

-        mInstallerImagePath = getString(com.android.internal.R.string.config_isoImagePath);

-        if (!(new File(mInstallerImagePath)).exists()) {

-            mInstallerCdButton.setVisibility(View.GONE);

-        }

-

-        dialogBuilder.show();

-    }

-

-    public void onClick(View v) {

-        if (v.equals(mMtpPtpButton)) {

-            if (mPtpActive) {

-                mUsbManager.setPrimaryFunction(UsbManager.USB_FUNCTION_MTP);

-                mUsbManager.setDefaultFunction(UsbManager.USB_FUNCTION_MTP);

-            } else {

-                mUsbManager.setPrimaryFunction(UsbManager.USB_FUNCTION_PTP);

-                mUsbManager.setDefaultFunction(UsbManager.USB_FUNCTION_PTP);

-            }

-        } else if (v.equals(mInstallerCdButton)) {

-            mUsbManager.setPrimaryFunction(UsbManager.USB_FUNCTION_MASS_STORAGE);

-            mUsbManager.setMassStorageBackingFile(mInstallerImagePath);

-        }

-

+/*
+ * 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.systemui.usb;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.util.Log;
+import android.widget.Button;
+
+import java.io.File;
+
+import com.android.systemui.R;
+
+public class UsbPreferenceActivity extends Activity implements View.OnClickListener  {
+
+    private static final String TAG = "UsbPreferenceActivity";
+
+    private UsbManager mUsbManager;
+    private String mCurrentFunction;
+    private String[] mFunctions;
+    private String mInstallerImagePath;
+    private AlertDialog mDialog;
+    private Button mMtpPtpButton;
+    private Button mInstallerCdButton;
+    private boolean mPtpActive;
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
+
+        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+        dialogBuilder.setTitle(getString(R.string.usb_preference_title));
+
+        LayoutInflater inflater = (LayoutInflater)getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+        View buttonView = inflater.inflate(R.layout.usb_preference_buttons, null);
+        dialogBuilder.setView(buttonView);
+        mMtpPtpButton = (Button)buttonView.findViewById(R.id.mtp_ptp_button);
+        mInstallerCdButton = (Button)buttonView.findViewById(R.id.installer_cd_button);
+        mMtpPtpButton.setOnClickListener(this);
+        mInstallerCdButton.setOnClickListener(this);
+
+        mPtpActive = mUsbManager.isFunctionEnabled(UsbManager.USB_FUNCTION_PTP);
+        if (mPtpActive) {
+            mMtpPtpButton.setText(R.string.use_mtp_button_title);
+        }
+
+        mInstallerImagePath = getString(com.android.internal.R.string.config_isoImagePath);
+        if (!(new File(mInstallerImagePath)).exists()) {
+            mInstallerCdButton.setVisibility(View.GONE);
+        }
+
+        mDialog = dialogBuilder.show();
+    }
+
+    public void onClick(View v) {
+        if (v.equals(mMtpPtpButton)) {
+            if (mPtpActive) {
+                mUsbManager.setCurrentFunction(UsbManager.USB_FUNCTION_MTP, true);
+            } else {
+                mUsbManager.setCurrentFunction(UsbManager.USB_FUNCTION_PTP, true);
+            }
+        } else if (v.equals(mInstallerCdButton)) {
+            // installer CD is never default
+            mUsbManager.setCurrentFunction(UsbManager.USB_FUNCTION_MASS_STORAGE, false);
+            mUsbManager.setMassStorageBackingFile(mInstallerImagePath);
+        }
+
+        if (mDialog != null) {
+            mDialog.dismiss();
+        }
         finish();

-    }

-}

+    }
+}
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index 75f466a..baa4ec3 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -498,6 +498,7 @@
             return;
         }
 
+        int width = WRAP_CONTENT;
         if (st.decorView == null || st.refreshDecorView) {
             if (st.decorView == null) {
                 // Initialize the panel decor, this will populate st.decorView
@@ -523,6 +524,7 @@
                 // If the contents is fill parent for the width, set the
                 // corresponding background
                 backgroundResId = st.fullBackground;
+                width = MATCH_PARENT;
             } else {
                 // Otherwise, set the normal panel background
                 backgroundResId = st.background;
@@ -546,7 +548,7 @@
         st.isHandled = false;
 
         WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
-                WRAP_CONTENT, WRAP_CONTENT,
+                width, WRAP_CONTENT,
                 st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG,
                 WindowManager.LayoutParams.FLAG_DITHER
                 | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 1fc8701..a23bacf 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -228,7 +228,6 @@
         WallpaperManagerService wallpaper = null;
         LocationManagerService location = null;
         CountryDetectorService countryDetector = null;
-        TextServiceManagerService tsms = null;
 
         if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
             try {
@@ -272,14 +271,6 @@
             }
 
             try {
-                Slog.i(TAG, "Text Service Manager Service");
-                tsms = new TextServiceManagerService(context);
-                ServiceManager.addService(Context.TEXT_SERVICE_MANAGER_SERVICE, tsms);
-            } catch (Throwable e) {
-                Slog.e(TAG, "Failure starting Text Service Manager Service", e);
-            }
-
-            try {
                 Slog.i(TAG, "NetworkStats Service");
                 networkStats = new NetworkStatsService(context, networkManagement, alarm);
                 ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
@@ -543,7 +534,6 @@
         final LocationManagerService locationF = location;
         final CountryDetectorService countryDetectorF = countryDetector;
         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
-        final TextServiceManagerService textServiceManagerServiceF = tsms;
 
         // We now tell the activity manager it is okay to run third party
         // code.  It will call back into us once it has gotten to the state
@@ -576,7 +566,6 @@
                 if (countryDetectorF != null) countryDetectorF.systemReady();
                 if (throttleF != null) throttleF.systemReady();
                 if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
-                if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();
             }
         });
 
diff --git a/services/java/com/android/server/TextServiceManagerService.java b/services/java/com/android/server/TextServiceManagerService.java
deleted file mode 100644
index 05e8d53..0000000
--- a/services/java/com/android/server/TextServiceManagerService.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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.server;
-
-import com.android.internal.content.PackageMonitor;
-import com.android.internal.view.ITextServiceManager;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.view.inputmethod.InputMethodInfo;
-import android.view.inputmethod.SpellCheckerInfo;
-import android.view.inputmethod.SpellCheckerService;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Message;
-import android.provider.Settings;
-import android.text.TextUtils;
-import android.util.Slog;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-public class TextServiceManagerService extends ITextServiceManager.Stub {
-    private static final String TAG = TextServiceManagerService.class.getSimpleName();
-    private static final boolean DBG = false;
-
-    private final Context mContext;
-    private boolean mSystemReady;
-    private final TextServiceMonitor mMonitor;
-    private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap =
-            new HashMap<String, SpellCheckerInfo>();
-    private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<SpellCheckerInfo>();
-
-    public void systemReady() {
-        if (!mSystemReady) {
-            mSystemReady = true;
-        }
-    }
-
-    public TextServiceManagerService(Context context) {
-        mSystemReady = false;
-        mContext = context;
-        mMonitor = new TextServiceMonitor();
-        mMonitor.register(context, true);
-        synchronized (mSpellCheckerMap) {
-            buildSpellCheckerMapLocked(context, mSpellCheckerList, mSpellCheckerMap);
-        }
-    }
-
-    private class TextServiceMonitor extends PackageMonitor {
-        @Override
-        public void onSomePackagesChanged() {
-            synchronized (mSpellCheckerMap) {
-                buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap);
-                // TODO: Update for each locale
-                final SpellCheckerInfo sci = getCurrentSpellChecker(null);
-                final String packageName = sci.getPackageName();
-                final int change = isPackageDisappearing(packageName);
-                if (change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE) {
-                    // Package disappearing
-                    setCurSpellChecker(findAvailSpellCheckerLocked(null, packageName));
-                } else if (isPackageModified(packageName)) {
-                    // Package modified
-                    setCurSpellChecker(findAvailSpellCheckerLocked(null, packageName));
-                }
-            }
-        }
-    }
-
-    // Not used for now
-    private SpellCheckerInfo getAppearedPackageLocked(Context context, PackageMonitor monitor) {
-        final int N = mSpellCheckerList.size();
-        for (int i = 0; i < N; ++i) {
-            final SpellCheckerInfo sci = mSpellCheckerList.get(i);
-            String packageName = sci.getPackageName();
-            if (monitor.isPackageAppearing(packageName)
-                    == PackageMonitor.PACKAGE_PERMANENT_CHANGE) {
-                return sci;
-            }
-        }
-        return null;
-    }
-
-    private static void buildSpellCheckerMapLocked(Context context,
-            ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map) {
-        list.clear();
-        map.clear();
-        final PackageManager pm = context.getPackageManager();
-        List<ResolveInfo> services = pm.queryIntentServices(
-                new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
-        final int N = services.size();
-        for (int i = 0; i < N; ++i) {
-            final ResolveInfo ri = services.get(i);
-            final ServiceInfo si = ri.serviceInfo;
-            final ComponentName compName = new ComponentName(si.packageName, si.name);
-            if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
-                Slog.w(TAG, "Skipping text service " + compName
-                        + ": it does not require the permission "
-                        + android.Manifest.permission.BIND_TEXT_SERVICE);
-                continue;
-            }
-            if (DBG) Slog.d(TAG, "Add: " + compName);
-            final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
-            list.add(sci);
-            map.put(sci.getId(), sci);
-        }
-    }
-
-    // TODO: find an appropriate spell checker for specified locale
-    private SpellCheckerInfo findAvailSpellCheckerLocked(String locale, String prefPackage) {
-        final int spellCheckersCount = mSpellCheckerList.size();
-        if (spellCheckersCount == 0) {
-            Slog.w(TAG, "no available spell checker services found");
-            return null;
-        }
-        if (prefPackage != null) {
-            for (int i = 0; i < spellCheckersCount; ++i) {
-                final SpellCheckerInfo sci = mSpellCheckerList.get(i);
-                if (prefPackage.equals(sci.getPackageName())) {
-                    return sci;
-                }
-            }
-        }
-        if (spellCheckersCount > 1) {
-            Slog.w(TAG, "more than one spell checker service found, picking first");
-        }
-        return mSpellCheckerList.get(0);
-    }
-
-    // TODO: Save SpellCheckerService by supported languages. Currently only one spell
-    // checker is saved.
-    @Override
-    public SpellCheckerInfo getCurrentSpellChecker(String locale) {
-        synchronized (mSpellCheckerMap) {
-            final String curSpellCheckerId =
-                    Settings.Secure.getString(mContext.getContentResolver(),
-                            Settings.Secure.SPELL_CHECKER_SERVICE);
-            if (TextUtils.isEmpty(curSpellCheckerId)) {
-                return null;
-            }
-            return mSpellCheckerMap.get(curSpellCheckerId);
-        }
-    }
-
-    private void setCurSpellChecker(SpellCheckerInfo sci) {
-        Settings.Secure.putString(mContext.getContentResolver(),
-                Settings.Secure.SPELL_CHECKER_SERVICE, sci == null ? "" : sci.getId());
-    }
-}
diff --git a/services/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/java/com/android/server/accessibility/AccessibilityManagerService.java
index a9dfb22..f6dd43a 100644
--- a/services/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -32,6 +32,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.database.ContentObserver;
+import android.graphics.Rect;
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Handler;
@@ -814,6 +815,8 @@
 
         final AtomicInteger mInteractionIdCounter = new AtomicInteger();
 
+        final Rect mTempBounds = new Rect();
+
         // the events pending events to be dispatched to this service
         final SparseArray<AccessibilityEvent> mPendingEvents =
             new SparseArray<AccessibilityEvent>();
@@ -932,9 +935,10 @@
                 AccessibilityNodeInfo info = mCallback.getFindAccessibilityNodeInfoResultAndClear(
                         interactionId);
                 if (info != null) {
+                    applyCompatibilityScaleIfNeeded(info);
                     info.setConnection(this);
+                    info.setSealed(true);
                 }
-                info.setSealed(true);
                 return info;
             } catch (RemoteException re) {
                 if (DEBUG) {
@@ -979,6 +983,7 @@
                     final int infoCount = infos.size();
                     for (int i = 0; i < infoCount; i++) {
                         AccessibilityNodeInfo info = infos.get(i);
+                        applyCompatibilityScaleIfNeeded(info);
                         info.setConnection(this);
                         info.setSealed(true);
                     }
@@ -1019,6 +1024,7 @@
                 AccessibilityNodeInfo info =
                      mCallback.getFindAccessibilityNodeInfoResultAndClear(interactionId);
                 if (info != null) {
+                    applyCompatibilityScaleIfNeeded(info);
                     info.setConnection(this);
                     info.setSealed(true);
                 }
@@ -1093,6 +1099,24 @@
             }
             return mWindowIdToInteractionConnectionMap.get(windowId);
         }
+
+        private void applyCompatibilityScaleIfNeeded(AccessibilityNodeInfo info) {
+            IBinder windowToken = mWindowIdToWindowTokenMap.get(info.getWindowId());
+            final float scale = mWindowManagerService.getWindowCompatibilityScale(windowToken);
+
+            if (scale == 1.0f) {
+                return;
+            }
+
+            Rect bounds = mTempBounds;
+            info.getBoundsInParent(bounds);
+            bounds.scale(scale);
+            info.setBoundsInParent(bounds);
+
+            info.getBoundsInScreen(bounds);
+            bounds.scale(scale);
+            info.setBoundsInScreen(bounds);
+        }
     }
 
     final class SecurityPolicy {
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index 15e67d0..946a270 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -509,9 +509,9 @@
         }
         try {
             if (enabled) {
-                usbManager.setPrimaryFunction(UsbManager.USB_FUNCTION_RNDIS);
+                usbManager.setCurrentFunction(UsbManager.USB_FUNCTION_RNDIS, false);
             } else {
-                usbManager.setPrimaryFunction(null);
+                usbManager.setCurrentFunction(null, false);
             }
         } catch (Exception e) {
             Log.e(TAG, "Error toggling usb RNDIS", e);
diff --git a/services/java/com/android/server/usb/UsbDeviceManager.java b/services/java/com/android/server/usb/UsbDeviceManager.java
index b7f9d5c..918f1b6 100644
--- a/services/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/java/com/android/server/usb/UsbDeviceManager.java
@@ -77,9 +77,8 @@
 
     private static final int MSG_UPDATE_STATE = 0;
     private static final int MSG_ENABLE_ADB = 1;
-    private static final int MSG_SET_PRIMARY_FUNCTION = 2;
-    private static final int MSG_SET_DEFAULT_FUNCTION = 3;
-    private static final int MSG_SYSTEM_READY = 4;
+    private static final int MSG_SET_CURRENT_FUNCTION = 2;
+    private static final int MSG_SYSTEM_READY = 3;
 
     // Delay for debouncing USB disconnects.
     // We often get rapid connect/disconnect events when enabling USB functions,
@@ -227,7 +226,7 @@
                 mHandler.updateState(state);
             } else if ("START".equals(accessory)) {
                 Slog.d(TAG, "got accessory start");
-                setPrimaryFunction(UsbManager.USB_FUNCTION_ACCESSORY);
+                setCurrentFunction(UsbManager.USB_FUNCTION_ACCESSORY, false);
             }
         }
     };
@@ -371,6 +370,14 @@
             sendMessage(m);
         }
 
+        public void sendMessage(int what, Object arg0, boolean arg1) {
+            removeMessages(what);
+            Message m = Message.obtain(this, what);
+            m.obj = arg0;
+            m.arg1 = (arg1 ? 1 : 0);
+            sendMessage(m);
+        }
+
         public void updateState(String state) {
             int connected, configured;
 
@@ -395,24 +402,30 @@
             sendMessageDelayed(msg, (connected == 0) ? UPDATE_DELAY : 0);
         }
 
-        private boolean setUsbConfig(String config) {
-            // set the new configuration
-            SystemProperties.set("sys.usb.config", config);
+        private boolean waitForState(String state) {
             // wait for the transition to complete.
             // give up after 1 second.
             for (int i = 0; i < 20; i++) {
                 // State transition is done when sys.usb.conf.done is set to the new configuration
-                if (config.equals(SystemProperties.get("sys.usb.state"))) return true;
+                if (state.equals(SystemProperties.get("sys.usb.state"))) return true;
                 try {
                     // try again in 50ms
                     Thread.sleep(50);
                 } catch (InterruptedException e) {
                 }
             }
+            Log.e(TAG, "waitForState(" + state + ") FAILED");
             return false;
         }
 
-        private void setCurrentFunctions(String functions) {
+        private boolean setUsbConfig(String config) {
+            Log.d(TAG, "setUsbConfig(" + config + ")");
+            // set the new configuration
+            SystemProperties.set("sys.usb.config", config);
+            return waitForState(config);
+        }
+
+        private void doSetCurrentFunctions(String functions) {
             if (!mCurrentFunctions.equals(functions)) {
                 if (!setUsbConfig("none") || !setUsbConfig(functions)) {
                     Log.e(TAG, "Failed to switch USB configuration to " + functions);
@@ -428,17 +441,14 @@
             if (enable != mAdbEnabled) {
                 mAdbEnabled = enable;
                 String functions;
+                // Due to the persist.sys.usb.config property trigger, changing adb state requires
+                // switching to default function
                 if (enable) {
-                    functions = addFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_ADB);
-                    mDefaultFunctions = addFunction(mDefaultFunctions,
-                            UsbManager.USB_FUNCTION_ADB);
+                    functions = addFunction(mDefaultFunctions, UsbManager.USB_FUNCTION_ADB);
                 } else {
-                    functions = removeFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_ADB);
-                    mDefaultFunctions = removeFunction(mDefaultFunctions,
-                            UsbManager.USB_FUNCTION_ADB);
+                    functions = removeFunction(mDefaultFunctions, UsbManager.USB_FUNCTION_ADB);
                 }
-                SystemProperties.set("persist.sys.usb.config", mDefaultFunctions);
-                setCurrentFunctions(functions);
+                setCurrentFunction(functions, true);
                 updateAdbNotification(mAdbEnabled && mConnected);
             }
         }
@@ -449,7 +459,7 @@
             } else {
                 functionList = removeFunction(functionList, UsbManager.USB_FUNCTION_ADB);
             }
-            setCurrentFunctions(functionList);
+            doSetCurrentFunctions(functionList);
         }
 
         private void updateCurrentAccessory() {
@@ -503,8 +513,6 @@
 
         @Override
         public void handleMessage(Message msg) {
-            String function;
-
             switch (msg.what) {
                 case MSG_UPDATE_STATE:
                     mConnected = (msg.arg1 == 1);
@@ -518,7 +526,7 @@
 
                     if (!mConnected) {
                         // restore defaults when USB is disconnected
-                        setCurrentFunctions(mDefaultFunctions);
+                        doSetCurrentFunctions(mDefaultFunctions);
                     }
                     if (mSystemReady) {
                         updateUsbState();
@@ -527,20 +535,31 @@
                 case MSG_ENABLE_ADB:
                     setAdbEnabled(msg.arg1 == 1);
                     break;
-                case MSG_SET_PRIMARY_FUNCTION:
-                    function = (String)msg.obj;
-                    if (function == null) {
-                        function = mDefaultFunctions;
+                case MSG_SET_CURRENT_FUNCTION:
+                    String function = (String)msg.obj;
+                    boolean makeDefault = (msg.arg1 == 1);
+                    if (makeDefault) {
+                        if (function == null) {
+                            throw new NullPointerException();
+                        }
+                        if (mAdbEnabled) {
+                            function = addFunction(function, UsbManager.USB_FUNCTION_ADB);
+                        }
+
+                        setUsbConfig("none");
+                        // setting this property will change the current USB state
+                        // via a property trigger
+                        SystemProperties.set("persist.sys.usb.config", function);
+                        if (waitForState(function)) {
+                            mCurrentFunctions = function;
+                            mDefaultFunctions = function;
+                        }
+                    } else {
+                        if (function == null) {
+                            function = mDefaultFunctions;
+                        }
+                        setEnabledFunctions(function);
                     }
-                    setEnabledFunctions(function);
-                    break;
-                case MSG_SET_DEFAULT_FUNCTION:
-                    function = (String)msg.obj;
-                    if (mAdbEnabled) {
-                        function = addFunction(function, UsbManager.USB_FUNCTION_ADB);
-                    }
-                    SystemProperties.set("persist.sys.usb.config", function);
-                    mDefaultFunctions = function;
                     break;
                 case MSG_SYSTEM_READY:
                     updateUsbNotification(mConnected);
@@ -588,15 +607,8 @@
             return nativeOpenAccessory();
         }
 
-    public void setPrimaryFunction(String function) {
-        mHandler.sendMessage(MSG_SET_PRIMARY_FUNCTION, function);
-    }
-
-    public void setDefaultFunction(String function) {
-        if (function == null) {
-            throw new NullPointerException();
-        }
-        mHandler.sendMessage(MSG_SET_DEFAULT_FUNCTION, function);
+    public void setCurrentFunction(String function, boolean makeDefault) {
+        mHandler.sendMessage(MSG_SET_CURRENT_FUNCTION, function, makeDefault);
     }
 
     public void setMassStorageBackingFile(String path) {
diff --git a/services/java/com/android/server/usb/UsbService.java b/services/java/com/android/server/usb/UsbService.java
index 193638f..9f2c17a 100644
--- a/services/java/com/android/server/usb/UsbService.java
+++ b/services/java/com/android/server/usb/UsbService.java
@@ -146,19 +146,10 @@
         mSettingsManager.clearDefaults(packageName);
     }
 
-    public void setPrimaryFunction(String function) {
+    public void setCurrentFunction(String function, boolean makeDefault) {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
         if (mDeviceManager != null) {
-            mDeviceManager.setPrimaryFunction(function);
-        } else {
-            throw new IllegalStateException("USB device mode not supported");
-        }
-    }
-
-    public void setDefaultFunction(String function) {
-        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
-        if (mDeviceManager != null) {
-            mDeviceManager.setDefaultFunction(function);
+            mDeviceManager.setCurrentFunction(function, makeDefault);
         } else {
             throw new IllegalStateException("USB device mode not supported");
         }
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 1c87f5b..dba170a 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -2776,6 +2776,13 @@
         Binder.restoreCallingIdentity(origId);
     }
 
+    public float getWindowCompatibilityScale(IBinder windowToken) {
+        synchronized (mWindowMap) {
+            WindowState windowState = mWindowMap.get(windowToken);
+            return (windowState != null) ? windowState.mGlobalScale : 1.0f;
+        }
+    }
+
     private AttributeCache.Entry getCachedAnimations(WindowManager.LayoutParams lp) {
         if (DEBUG_ANIM) Slog.v(TAG, "Loading animations: layout params pkg="
                 + (lp != null ? lp.packageName : null)