Merge "Remove dead code."
diff --git a/api/current.txt b/api/current.txt
index fab07f6..9cd44ed 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -5931,6 +5931,7 @@
     field public static final java.lang.String CATEGORY_UNIT_TEST = "android.intent.category.UNIT_TEST";
     field public static final android.os.Parcelable.Creator CREATOR;
     field public static final java.lang.String EXTRA_ALARM_COUNT = "android.intent.extra.ALARM_COUNT";
+    field public static final java.lang.String EXTRA_ALLOW_MULTIPLE = "android.intent.extra.ALLOW_MULTIPLE";
     field public static final deprecated java.lang.String EXTRA_ALLOW_REPLACE = "android.intent.extra.ALLOW_REPLACE";
     field public static final java.lang.String EXTRA_ASSIST_CONTEXT = "android.intent.extra.ASSIST_CONTEXT";
     field public static final java.lang.String EXTRA_ASSIST_PACKAGE = "android.intent.extra.ASSIST_PACKAGE";
@@ -20653,21 +20654,23 @@
   public class TextToSpeech.Engine {
     ctor public TextToSpeech.Engine();
     field public static final java.lang.String ACTION_CHECK_TTS_DATA = "android.speech.tts.engine.CHECK_TTS_DATA";
+    field public static final java.lang.String ACTION_GET_SAMPLE_TEXT = "android.speech.tts.engine.GET_SAMPLE_TEXT";
     field public static final java.lang.String ACTION_INSTALL_TTS_DATA = "android.speech.tts.engine.INSTALL_TTS_DATA";
     field public static final java.lang.String ACTION_TTS_DATA_INSTALLED = "android.speech.tts.engine.TTS_DATA_INSTALLED";
-    field public static final int CHECK_VOICE_DATA_BAD_DATA = -1; // 0xffffffff
+    field public static final deprecated int CHECK_VOICE_DATA_BAD_DATA = -1; // 0xffffffff
     field public static final int CHECK_VOICE_DATA_FAIL = 0; // 0x0
-    field public static final int CHECK_VOICE_DATA_MISSING_DATA = -2; // 0xfffffffe
-    field public static final int CHECK_VOICE_DATA_MISSING_VOLUME = -3; // 0xfffffffd
+    field public static final deprecated int CHECK_VOICE_DATA_MISSING_DATA = -2; // 0xfffffffe
+    field public static final deprecated int CHECK_VOICE_DATA_MISSING_VOLUME = -3; // 0xfffffffd
     field public static final int CHECK_VOICE_DATA_PASS = 1; // 0x1
     field public static final int DEFAULT_STREAM = 3; // 0x3
     field public static final java.lang.String EXTRA_AVAILABLE_VOICES = "availableVoices";
-    field public static final java.lang.String EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor";
-    field public static final java.lang.String EXTRA_TTS_DATA_INSTALLED = "dataInstalled";
+    field public static final deprecated java.lang.String EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor";
+    field public static final java.lang.String EXTRA_SAMPLE_TEXT = "sampleText";
+    field public static final deprecated java.lang.String EXTRA_TTS_DATA_INSTALLED = "dataInstalled";
     field public static final java.lang.String EXTRA_UNAVAILABLE_VOICES = "unavailableVoices";
-    field public static final java.lang.String EXTRA_VOICE_DATA_FILES = "dataFiles";
-    field public static final java.lang.String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo";
-    field public static final java.lang.String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot";
+    field public static final deprecated java.lang.String EXTRA_VOICE_DATA_FILES = "dataFiles";
+    field public static final deprecated java.lang.String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo";
+    field public static final deprecated java.lang.String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot";
     field public static final java.lang.String INTENT_ACTION_TTS_SERVICE = "android.intent.action.TTS_SERVICE";
     field public static final java.lang.String KEY_FEATURE_EMBEDDED_SYNTHESIS = "embeddedTts";
     field public static final java.lang.String KEY_FEATURE_NETWORK_SYNTHESIS = "networkTts";
@@ -20689,7 +20692,7 @@
     method public abstract void onInit(int);
   }
 
-  public static abstract interface TextToSpeech.OnUtteranceCompletedListener {
+  public static abstract deprecated interface TextToSpeech.OnUtteranceCompletedListener {
     method public abstract void onUtteranceCompleted(java.lang.String);
   }
 
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index dc367dd..434946c 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -883,7 +883,7 @@
      * Activity Action: Allow the user to select a particular kind of data and
      * return it.  This is different than {@link #ACTION_PICK} in that here we
      * just say what kind of data is desired, not a URI of existing data from
-     * which the user can pick.  A ACTION_GET_CONTENT could allow the user to
+     * which the user can pick.  An ACTION_GET_CONTENT could allow the user to
      * create the data as it runs (for example taking a picture or recording a
      * sound), let them browse over the web and download the desired data,
      * etc.
@@ -917,12 +917,17 @@
      * from a remote server but not already on the local device (thus requiring
      * they be downloaded when opened).
      * <p>
+     * If the caller can handle multiple returned items (the user performing
+     * multiple selection), then it can specify {@link #EXTRA_ALLOW_MULTIPLE}
+     * to indicate this.
+     * <p>
      * Input: {@link #getType} is the desired MIME type to retrieve.  Note
      * that no URI is supplied in the intent, as there are no constraints on
      * where the returned data originally comes from.  You may also include the
      * {@link #CATEGORY_OPENABLE} if you can only accept data that can be
      * opened as a stream.  You may use {@link #EXTRA_LOCAL_ONLY} to limit content
-     * selection to local data.
+     * selection to local data.  You may use {@link #EXTRA_ALLOW_MULTIPLE} to
+     * allow the user to select multiple items.
      * <p>
      * Output: The URI of the item that was picked.  This must be a content:
      * URI so that any receiver can access it.
@@ -3045,6 +3050,17 @@
         "android.intent.extra.LOCAL_ONLY";
 
     /**
+     * Used to indicate that a {@link #ACTION_GET_CONTENT} intent can allow the
+     * user to select and return multiple items.  This is a boolean extra; the default
+     * is false.  If true, an implementation of ACTION_GET_CONTENT is allowed to
+     * present the user with a UI where they can pick multiple items that are all
+     * returned to the caller.  When this happens, they should be returned as
+     * the {@link #getClipData()} part of the result Intent.
+     */
+    public static final String EXTRA_ALLOW_MULTIPLE =
+        "android.intent.extra.ALLOW_MULTIPLE";
+
+    /**
      * The userHandle carried with broadcast intents related to addition, removal and switching of users
      * - {@link #ACTION_USER_ADDED}, {@link #ACTION_USER_REMOVED} and {@link #ACTION_USER_SWITCHED}.
      * @hide
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 0445b39..a368451 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -210,6 +210,8 @@
     
     List<PackageInfo> getPreferredPackages(int flags);
 
+    void resetPreferredActivities(int userId);
+
     void addPreferredActivity(in IntentFilter filter, int match,
             in ComponentName[] set, in ComponentName activity, int userId);
 
diff --git a/core/java/android/speech/tts/TextToSpeech.java b/core/java/android/speech/tts/TextToSpeech.java
index f52b5e3..c1af7a5 100644
--- a/core/java/android/speech/tts/TextToSpeech.java
+++ b/core/java/android/speech/tts/TextToSpeech.java
@@ -140,7 +140,10 @@
      * Listener that will be called when the TTS service has
      * completed synthesizing an utterance. This is only called if the utterance
      * has an utterance ID (see {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}).
+     *
+     * @deprecated Use {@link UtteranceProgressListener} instead.
      */
+    @Deprecated
     public interface OnUtteranceCompletedListener {
         /**
          * Called when an utterance has been synthesized.
@@ -236,19 +239,28 @@
         /**
          * Indicates erroneous data when checking the installation status of the resources used by
          * the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent.
+         *
+         * @deprecated Use CHECK_VOICE_DATA_FAIL instead.
          */
+        @Deprecated
         public static final int CHECK_VOICE_DATA_BAD_DATA = -1;
 
         /**
          * Indicates missing resources when checking the installation status of the resources used
          * by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent.
+         *
+         * @deprecated Use CHECK_VOICE_DATA_FAIL instead.
          */
+        @Deprecated
         public static final int CHECK_VOICE_DATA_MISSING_DATA = -2;
 
         /**
          * Indicates missing storage volume when checking the installation status of the resources
          * used by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent.
+         *
+         * @deprecated Use CHECK_VOICE_DATA_FAIL instead.
          */
+        @Deprecated
         public static final int CHECK_VOICE_DATA_MISSING_VOLUME = -3;
 
         /**
@@ -284,9 +296,8 @@
                 "android.speech.tts.engine.INSTALL_TTS_DATA";
 
         /**
-         * Broadcast Action: broadcast to signal the completion of the installation of
-         * the data files used by the synthesis engine. Success or failure is indicated in the
-         * {@link #EXTRA_TTS_DATA_INSTALLED} extra.
+         * Broadcast Action: broadcast to signal the change in the list of available
+         * languages or/and their features.
          */
         @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
         public static final String ACTION_TTS_DATA_INSTALLED =
@@ -299,20 +310,16 @@
          * return one of the following codes:
          * {@link #CHECK_VOICE_DATA_PASS},
          * {@link #CHECK_VOICE_DATA_FAIL},
-         * {@link #CHECK_VOICE_DATA_BAD_DATA},
-         * {@link #CHECK_VOICE_DATA_MISSING_DATA}, or
-         * {@link #CHECK_VOICE_DATA_MISSING_VOLUME}.
          * <p> Moreover, the data received in the activity result will contain the following
          * fields:
          * <ul>
-         *   <li>{@link #EXTRA_VOICE_DATA_ROOT_DIRECTORY} which
-         *       indicates the path to the location of the resource files,</li>
-         *   <li>{@link #EXTRA_VOICE_DATA_FILES} which contains
-         *       the list of all the resource files,</li>
-         *   <li>and {@link #EXTRA_VOICE_DATA_FILES_INFO} which
-         *       contains, for each resource file, the description of the language covered by
-         *       the file in the xxx-YYY format, where xxx is the 3-letter ISO language code,
-         *       and YYY is the 3-letter ISO country code.</li>
+         *   <li>{@link #EXTRA_AVAILABLE_VOICES} which contains an ArrayList<String> of all the
+         *   available voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and
+         *   variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").</li>
+         *   <li>{@link #EXTRA_UNAVAILABLE_VOICES} which contains an ArrayList<String> of all the
+         *   unavailable voices (ones that user can install). The format of each voice is:
+         *   lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or
+         *   "eng-USA" or "eng-USA-FEMALE").</li>
          * </ul>
          */
         @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
@@ -320,37 +327,33 @@
                 "android.speech.tts.engine.CHECK_TTS_DATA";
 
         /**
-         * Activity intent for getting some sample text to use for demonstrating TTS.
+         * Activity intent for getting some sample text to use for demonstrating TTS. Specific
+         * locale have to be requested by passing following extra parameters:
+         * <ul>
+         *   <li>language</li>
+         *   <li>country</li>
+         *   <li>variant</li>
+         * </ul>
          *
-         * @hide This intent was used by engines written against the old API.
-         * Not sure if it should be exposed.
+         * Upon completion, the activity result may contain the following fields:
+         * <ul>
+         *   <li>{@link #EXTRA_SAMPLE_TEXT} which contains an String with sample text.</li>
+         * </ul>
          */
         @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
         public static final String ACTION_GET_SAMPLE_TEXT =
                 "android.speech.tts.engine.GET_SAMPLE_TEXT";
 
+        /**
+         * Extra information received with the {@link #ACTION_GET_SAMPLE_TEXT} intent result where
+         * the TextToSpeech engine returns an String with sample text for requested voice
+         */
+        public static final String EXTRA_SAMPLE_TEXT = "sampleText";
+
+
         // extras for a TTS engine's check data activity
         /**
-         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where
-         * the TextToSpeech engine specifies the path to its resources.
-         */
-        public static final String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot";
-
-        /**
-         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where
-         * the TextToSpeech engine specifies the file names of its resources under the
-         * resource path.
-         */
-        public static final String EXTRA_VOICE_DATA_FILES = "dataFiles";
-
-        /**
-         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where
-         * the TextToSpeech engine specifies the locale associated with each resource file.
-         */
-        public static final String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo";
-
-        /**
-         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where
+         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where
          * the TextToSpeech engine returns an ArrayList<String> of all the available voices.
          * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are
          * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").
@@ -358,7 +361,7 @@
         public static final String EXTRA_AVAILABLE_VOICES = "availableVoices";
 
         /**
-         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where
+         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where
          * the TextToSpeech engine returns an ArrayList<String> of all the unavailable voices.
          * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are
          * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").
@@ -366,22 +369,63 @@
         public static final String EXTRA_UNAVAILABLE_VOICES = "unavailableVoices";
 
         /**
+         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where
+         * the TextToSpeech engine specifies the path to its resources.
+         *
+         * It may be used by language packages to find out where to put their data.
+         *
+         * @deprecated TTS engine implementation detail, this information has no use for
+         * text-to-speech API client.
+         */
+        @Deprecated
+        public static final String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot";
+
+        /**
+         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where
+         * the TextToSpeech engine specifies the file names of its resources under the
+         * resource path.
+         *
+         * @deprecated TTS engine implementation detail, this information has no use for
+         * text-to-speech API client.
+         */
+        @Deprecated
+        public static final String EXTRA_VOICE_DATA_FILES = "dataFiles";
+
+        /**
+         * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where
+         * the TextToSpeech engine specifies the locale associated with each resource file.
+         *
+         * @deprecated TTS engine implementation detail, this information has no use for
+         * text-to-speech API client.
+         */
+        @Deprecated
+        public static final String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo";
+
+        /**
          * Extra information sent with the {@link #ACTION_CHECK_TTS_DATA} intent where the
          * caller indicates to the TextToSpeech engine which specific sets of voice data to
          * check for by sending an ArrayList<String> of the voices that are of interest.
          * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are
          * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").
+         *
+         * @deprecated Redundant functionality, checking for existence of specific sets of voice
+         * data can be done on client side.
          */
+        @Deprecated
         public static final String EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor";
 
         // extras for a TTS engine's data installation
         /**
-         * Extra information received with the {@link #ACTION_TTS_DATA_INSTALLED} intent.
+         * Extra information received with the {@link #ACTION_TTS_DATA_INSTALLED} intent result.
          * It indicates whether the data files for the synthesis engine were successfully
          * installed. The installation was initiated with the  {@link #ACTION_INSTALL_TTS_DATA}
          * intent. The possible values for this extra are
          * {@link TextToSpeech#SUCCESS} and {@link TextToSpeech#ERROR}.
+         *
+         * @deprecated No longer in use. If client ise interested in information about what
+         * changed, is should send ACTION_CHECK_TTS_DATA intent to discover available voices.
          */
+        @Deprecated
         public static final String EXTRA_TTS_DATA_INSTALLED = "dataInstalled";
 
         // keys for the parameters passed with speak commands. Hidden keys are used internally
@@ -474,6 +518,10 @@
          * for a description of how feature keys work. If set and supported by the engine
          * as per {@link TextToSpeech#getFeatures(Locale)}, the engine must synthesize
          * text on-device (without making network requests).
+         *
+         * @see TextToSpeech#speak(String, int, java.util.HashMap)
+         * @see TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)
+         * @see TextToSpeech#getFeatures(java.util.Locale)
          */
         public static final String KEY_FEATURE_EMBEDDED_SYNTHESIS = "embeddedTts";
     }
diff --git a/core/java/android/view/inputmethod/InputMethodInfo.java b/core/java/android/view/inputmethod/InputMethodInfo.java
index 08e30aa..54c2ba5 100644
--- a/core/java/android/view/inputmethod/InputMethodInfo.java
+++ b/core/java/android/view/inputmethod/InputMethodInfo.java
@@ -81,6 +81,11 @@
     private boolean mIsAuxIme;
 
     /**
+     * Cavert: mForceDefault must be false for production. This flag is only for test.
+     */
+    private final boolean mForceDefault;
+
+    /**
      * Constructor.
      *
      * @param context The Context in which we are parsing the input method.
@@ -108,6 +113,7 @@
         ServiceInfo si = service.serviceInfo;
         mId = new ComponentName(si.packageName, si.name).flattenToShortString();
         mIsAuxIme = true;
+        mForceDefault = false;
 
         PackageManager pm = context.getPackageManager();
         String settingsActivityComponent = null;
@@ -215,13 +221,39 @@
         mIsAuxIme = source.readInt() == 1;
         mService = ResolveInfo.CREATOR.createFromParcel(source);
         source.readTypedList(mSubtypes, InputMethodSubtype.CREATOR);
+        mForceDefault = false;
     }
 
     /**
-     * Temporary API for creating a built-in input method.
+     * Temporary API for creating a built-in input method for test.
      */
     public InputMethodInfo(String packageName, String className,
             CharSequence label, String settingsActivity) {
+        this(buildDummyResolveInfo(packageName, className, label), false, settingsActivity, null,
+                0, false);
+    }
+
+    /**
+     * Temporary API for creating a built-in input method for test.
+     * @hide
+     */
+    public InputMethodInfo(ResolveInfo ri, boolean isAuxIme,
+            String settingsActivity, List<InputMethodSubtype> subtypes, int isDefaultResId,
+            boolean forceDefault) {
+        final ServiceInfo si = ri.serviceInfo;
+        mService = ri;
+        mId = new ComponentName(si.packageName, si.name).flattenToShortString();
+        mSettingsActivityName = settingsActivity;
+        mIsDefaultResId = isDefaultResId;
+        mIsAuxIme = isAuxIme;
+        if (subtypes != null) {
+            mSubtypes.addAll(subtypes);
+        }
+        mForceDefault = forceDefault;
+    }
+
+    private static ResolveInfo buildDummyResolveInfo(String packageName, String className,
+            CharSequence label) {
         ResolveInfo ri = new ResolveInfo();
         ServiceInfo si = new ServiceInfo();
         ApplicationInfo ai = new ApplicationInfo();
@@ -234,11 +266,7 @@
         si.exported = true;
         si.nonLocalizedLabel = label;
         ri.serviceInfo = si;
-        mService = ri;
-        mId = new ComponentName(si.packageName, si.name).flattenToShortString();
-        mSettingsActivityName = settingsActivity;
-        mIsDefaultResId = 0;
-        mIsAuxIme = false;
+        return ri;
     }
 
     /**
@@ -340,6 +368,22 @@
         return mIsDefaultResId;
     }
 
+    /**
+     * Return whether or not this ime is a default ime or not.
+     * @hide
+     */
+    public boolean isDefault(Context context) {
+        if (mForceDefault) {
+            return true;
+        }
+        try {
+            final Resources res = context.createPackageContext(getPackageName(), 0).getResources();
+            return res.getBoolean(getIsDefaultResourceId());
+        } catch (NameNotFoundException e) {
+            return false;
+        }
+    }
+
     public void dump(Printer pw, String prefix) {
         pw.println(prefix + "mId=" + mId
                 + " mSettingsActivityName=" + mSettingsActivityName);
diff --git a/core/java/com/android/internal/inputmethod/InputMethodUtils.java b/core/java/com/android/internal/inputmethod/InputMethodUtils.java
index 3d7e1ff..655d148 100644
--- a/core/java/com/android/internal/inputmethod/InputMethodUtils.java
+++ b/core/java/com/android/internal/inputmethod/InputMethodUtils.java
@@ -59,11 +59,53 @@
                 & ApplicationInfo.FLAG_SYSTEM) != 0;
     }
 
-    public static boolean isSystemImeThatHasEnglishSubtype(InputMethodInfo imi) {
+    public static boolean isSystemImeThatHasEnglishKeyboardSubtype(InputMethodInfo imi) {
         if (!isSystemIme(imi)) {
             return false;
         }
-        return containsSubtypeOf(imi, ENGLISH_LOCALE.getLanguage());
+        return containsSubtypeOf(imi, ENGLISH_LOCALE.getLanguage(), SUBTYPE_MODE_KEYBOARD);
+    }
+
+    private static boolean isSystemAuxilialyImeThatHashAutomaticSubtype(InputMethodInfo imi) {
+        if (!isSystemIme(imi)) {
+            return false;
+        }
+        if (!imi.isAuxiliaryIme()) {
+            return false;
+        }
+        final int subtypeCount = imi.getSubtypeCount();
+        for (int i = 0; i < subtypeCount; ++i) {
+            final InputMethodSubtype s = imi.getSubtypeAt(i);
+            if (s.overridesImplicitlyEnabledSubtype()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static ArrayList<InputMethodInfo> getDefaultEnabledImes(
+            Context context, boolean isSystemReady, ArrayList<InputMethodInfo> imis) {
+        final ArrayList<InputMethodInfo> retval = new ArrayList<InputMethodInfo>();
+        boolean auxilialyImeAdded = false;
+        for (int i = 0; i < imis.size(); ++i) {
+            final InputMethodInfo imi = imis.get(i);
+            if (isDefaultEnabledIme(isSystemReady, imi, context)) {
+                retval.add(imi);
+                if (imi.isAuxiliaryIme()) {
+                    auxilialyImeAdded = true;
+                }
+            }
+        }
+        if (auxilialyImeAdded) {
+            return retval;
+        }
+        for (int i = 0; i < imis.size(); ++i) {
+            final InputMethodInfo imi = imis.get(i);
+            if (isSystemAuxilialyImeThatHashAutomaticSubtype(imi)) {
+                retval.add(imi);
+            }
+        }
+        return retval;
     }
 
     // TODO: Rename isSystemDefaultImeThatHasCurrentLanguageSubtype
@@ -77,14 +119,11 @@
         }
         if (imi.getIsDefaultResourceId() != 0) {
             try {
-                Resources res = context.createPackageContext(
-                        imi.getPackageName(), 0).getResources();
-                if (res.getBoolean(imi.getIsDefaultResourceId())
-                        && containsSubtypeOf(imi, context.getResources().getConfiguration().
-                                locale.getLanguage())) {
+                if (imi.isDefault(context) && containsSubtypeOf(
+                        imi, context.getResources().getConfiguration().locale.getLanguage(),
+                        null /* mode */)) {
                     return true;
                 }
-            } catch (PackageManager.NameNotFoundException ex) {
             } catch (Resources.NotFoundException ex) {
             }
         }
@@ -97,15 +136,19 @@
     public static boolean isDefaultEnabledIme(
             boolean isSystemReady, InputMethodInfo imi, Context context) {
         return isValidSystemDefaultIme(isSystemReady, imi, context)
-                || isSystemImeThatHasEnglishSubtype(imi);
+                || isSystemImeThatHasEnglishKeyboardSubtype(imi);
     }
 
-    private static boolean containsSubtypeOf(InputMethodInfo imi, String language) {
+    private static boolean containsSubtypeOf(InputMethodInfo imi, String language, String mode) {
         final int N = imi.getSubtypeCount();
         for (int i = 0; i < N; ++i) {
-            if (imi.getSubtypeAt(i).getLocale().startsWith(language)) {
-                return true;
+            if (!imi.getSubtypeAt(i).getLocale().startsWith(language)) {
+                continue;
             }
+            if(!TextUtils.isEmpty(mode) && !imi.getSubtypeAt(i).getMode().equalsIgnoreCase(mode)) {
+                continue;
+            }
+            return true;
         }
         return false;
     }
@@ -141,7 +184,7 @@
             while (i > 0) {
                 i--;
                 final InputMethodInfo imi = enabledImes.get(i);
-                if (InputMethodUtils.isSystemImeThatHasEnglishSubtype(imi)
+                if (InputMethodUtils.isSystemImeThatHasEnglishKeyboardSubtype(imi)
                         && !imi.isAuxiliaryIme()) {
                     return imi;
                 }
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index d24513a3..fd7e3b0 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -76,18 +76,6 @@
     private final String peerSecurityContext;
 
     /**
-     * A long-lived reference to the original command socket used to launch
-     * this peer. If "peer wait" mode is specified, the process that requested
-     * the new VM instance intends to track the lifetime of the spawned instance
-     * via the command socket. In this case, the command socket is closed
-     * in the Zygote and placed here in the spawned instance so that it will
-     * not be collected and finalized. This field remains null at all times
-     * in the original Zygote process, and in all spawned processes where
-     * "peer-wait" mode was not requested.
-     */
-    private static LocalSocket sPeerWaitSocket = null;
-
-    /**
      * Constructs instance from connected socket.
      *
      * @param socket non-null; connected socket
@@ -298,11 +286,6 @@
      *   <li> --rlimit=r,c,m<i>tuple of values for setrlimit() call.
      *    <code>r</code> is the resource, <code>c</code> and <code>m</code>
      *    are the settings for current and max value.</i>
-     *   <li> --peer-wait indicates that the command socket should
-     * be inherited by (and set to close-on-exec in) the spawned process
-     * and used to track the lifetime of that process. The spawning process
-     * then exits. Without this flag, it is retained by the spawning process
-     * (and closed in the child) in expectation of a new spawn request.
      *   <li> --classpath=<i>colon-separated classpath</i> indicates
      * that the specified class (which must b first non-flag argument) should
      * be loaded from jar files in the specified classpath. Incompatible with
@@ -330,9 +313,6 @@
         /** from --setgroups */
         int[] gids;
 
-        /** from --peer-wait */
-        boolean peerWait;
-
         /**
          * From --enable-debugger, --enable-checkjni, --enable-assert,
          * --enable-safemode, and --enable-jni-logging.
@@ -437,8 +417,6 @@
                     debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
                 } else if (arg.equals("--enable-assert")) {
                     debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
-                } else if (arg.equals("--peer-wait")) {
-                    peerWait = true;
                 } else if (arg.equals("--runtime-init")) {
                     runtimeInit = true;
                 } else if (arg.startsWith("--seinfo=")) {
@@ -897,23 +875,8 @@
             FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
             throws ZygoteInit.MethodAndArgsCaller {
 
-        /*
-         * Close the socket, unless we're in "peer wait" mode, in which
-         * case it's used to track the liveness of this process.
-         */
-
-        if (parsedArgs.peerWait) {
-            try {
-                ZygoteInit.setCloseOnExec(mSocket.getFileDescriptor(), true);
-                sPeerWaitSocket = mSocket;
-            } catch (IOException ex) {
-                Log.e(TAG, "Zygote Child: error setting peer wait "
-                        + "socket to be close-on-exec", ex);
-            }
-        } else {
-            closeSocket();
-            ZygoteInit.closeServerSocket();
-        }
+        closeSocket();
+        ZygoteInit.closeServerSocket();
 
         if (descriptors != null) {
             try {
@@ -1044,18 +1007,6 @@
             return true;
         }
 
-        /*
-         * If the peer wants to use the socket to wait on the
-         * newly spawned process, then we're all done.
-         */
-        if (parsedArgs.peerWait) {
-            try {
-                mSocket.close();
-            } catch (IOException ex) {
-                Log.e(TAG, "Zygote: error closing sockets", ex);
-            }
-            return true;
-        }
         return false;
     }
 
diff --git a/core/java/com/android/internal/util/FastXmlSerializer.java b/core/java/com/android/internal/util/FastXmlSerializer.java
index 592a8fa..99eea15 100644
--- a/core/java/com/android/internal/util/FastXmlSerializer.java
+++ b/core/java/com/android/internal/util/FastXmlSerializer.java
@@ -50,6 +50,8 @@
 
     private static final int BUFFER_LEN = 8192;
 
+    private static String sSpace = "                                                              ";
+
     private final char[] mText = new char[BUFFER_LEN];
     private int mPos;
 
@@ -59,8 +61,12 @@
     private CharsetEncoder mCharset;
     private ByteBuffer mBytes = ByteBuffer.allocate(BUFFER_LEN);
 
+    private boolean mIndent = false;
     private boolean mInTag;
 
+    private int mNesting = 0;
+    private boolean mLineStart = true;
+
     private void append(char c) throws IOException {
         int pos = mPos;
         if (pos >= (BUFFER_LEN-1)) {
@@ -113,6 +119,14 @@
         append(str, 0, str.length());
     }
 
+    private void appendIndent(int indent) throws IOException {
+        indent *= 4;
+        if (indent > sSpace.length()) {
+            indent = sSpace.length();
+        }
+        append(sSpace, 0, indent);
+    }
+
     private void escapeAndAppendString(final String string) throws IOException {
         final int N = string.length();
         final char NE = (char)ESCAPE_TABLE.length;
@@ -161,6 +175,7 @@
 
         escapeAndAppendString(value);
         append('"');
+        mLineStart = false;
         return this;
     }
 
@@ -185,9 +200,13 @@
 
     public XmlSerializer endTag(String namespace, String name) throws IOException,
             IllegalArgumentException, IllegalStateException {
+        mNesting--;
         if (mInTag) {
             append(" />\n");
         } else {
+            if (mIndent && mLineStart) {
+                appendIndent(mNesting);
+            }
             append("</");
             if (namespace != null) {
                 append(namespace);
@@ -196,6 +215,7 @@
             append(name);
             append(">\n");
         }
+        mLineStart = true;
         mInTag = false;
         return this;
     }
@@ -278,6 +298,7 @@
     public void setFeature(String name, boolean state) throws IllegalArgumentException,
             IllegalStateException {
         if (name.equals("http://xmlpull.org/v1/doc/features.html#indent-output")) {
+            mIndent = true;
             return;
         }
         throw new UnsupportedOperationException();
@@ -325,6 +346,7 @@
             IllegalArgumentException, IllegalStateException {
         append("<?xml version='1.0' encoding='utf-8' standalone='"
                 + (standalone ? "yes" : "no") + "' ?>\n");
+        mLineStart = true;
     }
 
     public XmlSerializer startTag(String namespace, String name) throws IOException,
@@ -332,6 +354,10 @@
         if (mInTag) {
             append(">\n");
         }
+        if (mIndent) {
+            appendIndent(mNesting);
+        }
+        mNesting++;
         append('<');
         if (namespace != null) {
             append(namespace);
@@ -339,6 +365,7 @@
         }
         append(name);
         mInTag = true;
+        mLineStart = false;
         return this;
     }
 
@@ -349,6 +376,9 @@
             mInTag = false;
         }
         escapeAndAppendString(buf, start, len);
+        if (mIndent) {
+            mLineStart = buf[start+len-1] == '\n';
+        }
         return this;
     }
 
@@ -359,6 +389,9 @@
             mInTag = false;
         }
         escapeAndAppendString(text);
+        if (mIndent) {
+            mLineStart = text.charAt(text.length()-1) == '\n';
+        }
         return this;
     }
 
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index aafc4bf..558080c 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -690,6 +690,12 @@
         android:permissionGroup="android.permission-group.NETWORK"
         android:protectionLevel="signature|system" />
 
+    <!-- Allows access to the loop radio (Android@Home mesh network) device.
+	@hide -->
+    <permission android:name="android.permission.LOOP_RADIO"
+	android:permissionGroup="android.permission-group.NETWORK"
+	android:protectionLevel="signature|system" />
+    
     <!-- ================================== -->
     <!-- Permissions for accessing accounts -->
     <!-- ================================== -->
diff --git a/core/tests/inputmethodtests/Android.mk b/core/tests/inputmethodtests/Android.mk
new file mode 100644
index 0000000..4631e65
--- /dev/null
+++ b/core/tests/inputmethodtests/Android.mk
@@ -0,0 +1,18 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+# We only want this apk build for tests.
+LOCAL_MODULE_TAGS := tests
+
+# Include all test java files.
+LOCAL_SRC_FILES := \
+	$(call all-java-files-under, src)
+
+LOCAL_DX_FLAGS := --core-library
+LOCAL_STATIC_JAVA_LIBRARIES := core-tests android-common frameworks-core-util-lib
+LOCAL_JAVA_LIBRARIES := android.test.runner
+LOCAL_PACKAGE_NAME := FrameworksCoreInputMethodTests
+
+LOCAL_CERTIFICATE := platform
+
+include $(BUILD_PACKAGE)
diff --git a/core/tests/inputmethodtests/AndroidManifest.xml b/core/tests/inputmethodtests/AndroidManifest.xml
new file mode 100644
index 0000000..7f0b1aa
--- /dev/null
+++ b/core/tests/inputmethodtests/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          android:installLocation="internalOnly"
+          package="com.android.frameworks.coretests.inputmethod"
+          android:sharedUserId="android.uid.system">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="android.test.InstrumentationTestRunner"
+            android:targetPackage="com.android.frameworks.coretests.inputmethod"
+            android:label="Frameworks InputMethod Core Tests" />
+
+</manifest>
diff --git a/core/tests/inputmethodtests/run_core_inputmethod_test.sh b/core/tests/inputmethodtests/run_core_inputmethod_test.sh
new file mode 100755
index 0000000..5e123ec
--- /dev/null
+++ b/core/tests/inputmethodtests/run_core_inputmethod_test.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+  --rebuild ) echo Rebuild && rebuild=true;;
+  * ) com_opts+=($1);;
+  esac
+  shift
+done
+
+if [[ -z $ANDROID_PRODUCT_OUT && $rebuilld == true ]]; then
+  echo You must lunch before running this test.
+  exit 0
+fi
+
+if [[ $rebuild == true ]]; then
+  make -j4 FrameworksCoreInputMethodTests
+  TESTAPP=${ANDROID_PRODUCT_OUT}/data/app/FrameworksCoreInputMethodTests.apk
+  COMMAND="adb install -r $TESTAPP"
+  echo $COMMAND
+  $COMMAND
+fi
+
+adb shell am instrument -w -e class android.os.InputMethodTest com.android.frameworks.coretests.inputmethod/android.test.InstrumentationTestRunner
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodTest.java b/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
new file mode 100644
index 0000000..0a2b50c
--- /dev/null
+++ b/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os;
+
+import com.android.internal.inputmethod.InputMethodUtils;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
+import android.test.InstrumentationTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodSubtype;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputMethodTest extends InstrumentationTestCase {
+    private static final boolean IS_AUX = true;
+    private static final boolean IS_DEFAULT = true;
+    private static final boolean IS_AUTO = true;
+
+    @SmallTest
+    public void testDefaultEnabledImesWithDefaultVoiceIme() throws Exception {
+        final Context context = getInstrumentation().getTargetContext();
+        final ArrayList<InputMethodInfo> imis = new ArrayList<InputMethodInfo>();
+        imis.add(createDefaultAutoDummyVoiceIme());
+        imis.add(createNonDefaultAutoDummyVoiceIme0());
+        imis.add(createNonDefaultAutoDummyVoiceIme1());
+        imis.add(createNonDefaultDummyVoiceIme2());
+        imis.add(createDefaultDummyEnUSKeyboardIme());
+        imis.add(createNonDefaultDummyJaJPKeyboardIme());
+        final ArrayList<InputMethodInfo> enabledImis = InputMethodUtils.getDefaultEnabledImes(
+                context, true, imis);
+        assertEquals(2, enabledImis.size());
+        for (int i = 0; i < enabledImis.size(); ++i) {
+            final InputMethodInfo imi = enabledImis.get(0);
+            // "DummyDefaultAutoVoiceIme" and "DummyDefaultEnKeyboardIme"
+            if (imi.getPackageName().equals("DummyDefaultAutoVoiceIme")
+                    || imi.getPackageName().equals("DummyDefaultEnKeyboardIme")) {
+                continue;
+            } else {
+                fail("Invalid enabled subtype.");
+            }
+        }
+    }
+
+    @SmallTest
+    public void testDefaultEnabledImesWithOutDefaultVoiceIme() throws Exception {
+        final Context context = getInstrumentation().getTargetContext();
+        final ArrayList<InputMethodInfo> imis = new ArrayList<InputMethodInfo>();
+        imis.add(createNonDefaultAutoDummyVoiceIme0());
+        imis.add(createNonDefaultAutoDummyVoiceIme1());
+        imis.add(createNonDefaultDummyVoiceIme2());
+        imis.add(createDefaultDummyEnUSKeyboardIme());
+        imis.add(createNonDefaultDummyJaJPKeyboardIme());
+        final ArrayList<InputMethodInfo> enabledImis = InputMethodUtils.getDefaultEnabledImes(
+                context, true, imis);
+        assertEquals(3, enabledImis.size());
+        for (int i = 0; i < enabledImis.size(); ++i) {
+            final InputMethodInfo imi = enabledImis.get(0);
+            // "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1" and
+            // "DummyDefaultEnKeyboardIme"
+            if (imi.getPackageName().equals("DummyNonDefaultAutoVoiceIme0")
+                    || imi.getPackageName().equals("DummyNonDefaultAutoVoiceIme1")
+                    || imi.getPackageName().equals("DummyDefaultEnKeyboardIme")) {
+                continue;
+            } else {
+                fail("Invalid enabled subtype.");
+            }
+        }
+    }
+
+    private static InputMethodInfo createDummyInputMethodInfo(String packageName, String name,
+            CharSequence label, boolean isAuxIme, boolean isDefault,
+            List<InputMethodSubtype> subtypes) {
+        final ResolveInfo ri = new ResolveInfo();
+        final ServiceInfo si = new ServiceInfo();
+        final ApplicationInfo ai = new ApplicationInfo();
+        ai.packageName = packageName;
+        ai.enabled = true;
+        ai.flags |= ApplicationInfo.FLAG_SYSTEM;
+        si.applicationInfo = ai;
+        si.enabled = true;
+        si.packageName = packageName;
+        si.name = name;
+        si.exported = true;
+        si.nonLocalizedLabel = label;
+        ri.serviceInfo = si;
+        return new InputMethodInfo(ri, isAuxIme, "", subtypes, 1, isDefault);
+    }
+
+    private static InputMethodSubtype createDummyInputMethodSubtype(String locale, String mode,
+            boolean isAuxiliary, boolean overridesImplicitlyEnabledSubtype) {
+        return new InputMethodSubtype(0, 0, locale, mode, "", isAuxiliary,
+                overridesImplicitlyEnabledSubtype);
+    }
+
+    private static InputMethodInfo createDefaultAutoDummyVoiceIme() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO));
+        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyDefaultAutoVoiceIme", "dummy.voice0",
+                "DummyVoice0", IS_AUX, IS_DEFAULT, subtypes);
+    }
+
+    private static InputMethodInfo createNonDefaultAutoDummyVoiceIme0() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO));
+        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme0", "dummy.voice1",
+                "DummyVoice1", IS_AUX, !IS_DEFAULT, subtypes);
+    }
+
+    private static InputMethodInfo createNonDefaultAutoDummyVoiceIme1() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO));
+        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme1", "dummy.voice2",
+                "DummyVoice2", IS_AUX, !IS_DEFAULT, subtypes);
+    }
+
+    private static InputMethodInfo createNonDefaultDummyVoiceIme2() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyNonDefaultVoiceIme2", "dummy.voice3",
+                "DummyVoice3", IS_AUX, !IS_DEFAULT, subtypes);
+    }
+
+    private static InputMethodInfo createDefaultDummyEnUSKeyboardIme() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("en_US", "keyboard", !IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyDefaultEnKeyboardIme", "dummy.keyboard0",
+                "DummyKeyboard0", !IS_AUX, IS_DEFAULT, subtypes);
+    }
+
+    private static InputMethodInfo createNonDefaultDummyJaJPKeyboardIme() {
+        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        subtypes.add(createDummyInputMethodSubtype("ja_JP", "keyboard", !IS_AUX, !IS_AUTO));
+        return createDummyInputMethodInfo("DummyNonDefaultJaJPKeyboardIme", "dummy.keyboard1",
+                "DummyKeyboard1", !IS_AUX, !IS_DEFAULT, subtypes);
+    }
+}
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 83ecdd9..cf04b5c 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -106,6 +106,10 @@
         <group gid="net_bw_acct" />
     </permission>
 
+    <permission name="android.permission.LOOP_RADIO" >
+        <group gid="loop_radio" />
+    </permission>
+
     <!-- ================================================================== -->
     <!-- ================================================================== -->
     <!-- ================================================================== -->
diff --git a/graphics/java/android/renderscript/Matrix3f.java b/graphics/java/android/renderscript/Matrix3f.java
index 0bad7e0..5e9a7ca 100644
--- a/graphics/java/android/renderscript/Matrix3f.java
+++ b/graphics/java/android/renderscript/Matrix3f.java
@@ -140,7 +140,7 @@
         mMat[4] = y*y*nc +  c;
         mMat[7] =  yz*nc - xs;
         mMat[2] =  zx*nc - ys;
-        mMat[6] =  yz*nc + xs;
+        mMat[5] =  yz*nc + xs;
         mMat[8] = z*z*nc +  c;
     }
 
diff --git a/libs/hwui/Layer.h b/libs/hwui/Layer.h
index a551b3f..e8a85fd 100644
--- a/libs/hwui/Layer.h
+++ b/libs/hwui/Layer.h
@@ -277,6 +277,10 @@
      * Texture coordinates of the layer.
      */
     Rect texCoords;
+    /**
+     * Clipping rectangle.
+     */
+    Rect clipRect;
 
     /**
      * Dirty region indicating what parts of the layer
diff --git a/libs/hwui/LayerRenderer.cpp b/libs/hwui/LayerRenderer.cpp
index 61bedbb..c8a8ed4 100644
--- a/libs/hwui/LayerRenderer.cpp
+++ b/libs/hwui/LayerRenderer.cpp
@@ -62,6 +62,7 @@
         android::Rect r(dirty.left, dirty.top, dirty.right, dirty.bottom);
         mLayer->region.subtractSelf(r);
     }
+    mLayer->clipRect.set(dirty);
 
     return OpenGLRenderer::prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
 }
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index f55bc9d..1fa1b20 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -169,8 +169,8 @@
     return prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
 }
 
-status_t OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom,
-        bool opaque) {
+status_t OpenGLRenderer::prepareDirty(float left, float top,
+        float right, float bottom, bool opaque) {
     mCaches.clearGarbage();
 
     mSnapshot = new Snapshot(mFirstSnapshot,
@@ -207,7 +207,7 @@
     if (mCaches.extensions.hasDiscardFramebuffer() &&
             left <= 0.0f && top <= 0.0f && right >= mWidth && bottom >= mHeight) {
         const GLenum attachments[] = { getTargetFbo() == 0 ? (const GLenum) GL_COLOR_EXT :
-                (const GLenum) GL_COLOR_ATTACHMENT0 };
+                (const GLenum) GL_COLOR_ATTACHMENT0, GL_STENCIL_EXT };
         glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
     }
 }
@@ -237,12 +237,18 @@
 void OpenGLRenderer::startTiling(const sp<Snapshot>& s, bool opaque) {
     if (!mSuppressTiling) {
         Rect* clip = mTilingSnapshot->clipRect;
-        if (s->flags & Snapshot::kFlagIsFboLayer) {
-            clip = s->clipRect;
+        if (s->flags & Snapshot::kFlagFboTarget) {
+            clip = &s->layer->clipRect;
         }
 
-        mCaches.startTiling(clip->left, s->height - clip->bottom,
-                clip->right - clip->left, clip->bottom - clip->top, opaque);
+        startTiling(*clip, s->height, opaque);
+    }
+}
+
+void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque) {
+    if (!mSuppressTiling) {
+        mCaches.startTiling(clip.left, windowHeight - clip.bottom,
+                    clip.right - clip.left, clip.bottom - clip.top, opaque);
     }
 }
 
@@ -782,18 +788,17 @@
 }
 
 bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo) {
+    layer->clipRect.set(clip);
     layer->setFbo(mCaches.fboCache.get());
 
     mSnapshot->region = &mSnapshot->layer->region;
-    mSnapshot->flags |= Snapshot::kFlagFboTarget;
-
-    mSnapshot->flags |= Snapshot::kFlagIsFboLayer;
+    mSnapshot->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer |
+            Snapshot::kFlagDirtyOrtho;
     mSnapshot->fbo = layer->getFbo();
     mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
     mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
     mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
     mSnapshot->height = bounds.getHeight();
-    mSnapshot->flags |= Snapshot::kFlagDirtyOrtho;
     mSnapshot->orthoMatrix.load(mOrthoMatrix);
 
     endTiling();
@@ -811,7 +816,7 @@
     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
             layer->getTexture(), 0);
 
-    startTiling(mSnapshot);
+    startTiling(mSnapshot, !layer->isBlend());
 
     // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
     mCaches.enableScissor();
@@ -1245,6 +1250,11 @@
 void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
     // The layer's FBO is already bound when we reach this stage
     if (!layer->getStencilRenderBuffer()) {
+        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
+        // is attached after we initiated tiling. We must turn it off,
+        // attach the new render buffer then turn tiling back on
+        endTiling();
+
         // TODO: See Layer::removeFbo(). The stencil renderbuffer should be cached
         GLuint buffer;
         glGenRenderbuffers(1, &buffer);
@@ -1254,6 +1264,8 @@
         layer->allocateStencilRenderBuffer();
 
         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, buffer);
+
+        startTiling(layer->clipRect, layer->layer.getHeight(), !layer->isBlend());
     }
 }
 
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index d4e1eb5..594580e 100644
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -400,12 +400,21 @@
 
     /**
      * Tells the GPU what part of the screen is about to be redrawn.
+     * This method will use the clip rect that we started drawing the
+     * frame with.
      * This method needs to be invoked every time getTargetFbo() is
      * bound again.
      */
     void startTiling(const sp<Snapshot>& snapshot, bool opaque = false);
 
     /**
+     * Tells the GPU what part of the screen is about to be redrawn.
+     * This method needs to be invoked every time getTargetFbo() is
+     * bound again.
+     */
+    void startTiling(const Rect& clip, int windowHeight, bool opaque = false);
+
+    /**
      * Tells the GPU that we are done drawing the frame or that we
      * are switching to another render target.
      */
diff --git a/services/java/com/android/server/InputMethodManagerService.java b/services/java/com/android/server/InputMethodManagerService.java
index 0f14265..1a8641b 100644
--- a/services/java/com/android/server/InputMethodManagerService.java
+++ b/services/java/com/android/server/InputMethodManagerService.java
@@ -511,7 +511,8 @@
                     }
                 }
 
-                buildInputMethodListLocked(mMethodList, mMethodMap);
+                buildInputMethodListLocked(
+                        mMethodList, mMethodMap, false /* resetDefaultEnabledIme */);
 
                 boolean changed = false;
 
@@ -671,9 +672,13 @@
 
         // Just checking if defaultImiId is empty or not
         final String defaultImiId = mSettings.getSelectedInputMethod();
+        if (DEBUG) {
+            Slog.d(TAG, "Initial default ime = " + defaultImiId);
+        }
         mImeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId);
 
-        buildInputMethodListLocked(mMethodList, mMethodMap);
+        buildInputMethodListLocked(mMethodList, mMethodMap,
+                !mImeSelectedOnBoot /* resetDefaultEnabledIme */);
         mSettings.enableAllIMEsIfThereIsNoEnabledIME();
 
         if (!mImeSelectedOnBoot) {
@@ -726,7 +731,7 @@
         }
     }
 
-    private void resetAllInternalStateLocked(boolean updateOnlyWhenLocaleChanged) {
+    private void resetAllInternalStateLocked(final boolean updateOnlyWhenLocaleChanged) {
         if (!mSystemReady) {
             // not system ready
             return;
@@ -744,7 +749,8 @@
             }
             // InputMethodAndSubtypeListManager should be reset when the locale is changed.
             mImListManager = new InputMethodAndSubtypeListManager(mContext, this);
-            buildInputMethodListLocked(mMethodList, mMethodMap);
+            buildInputMethodListLocked(mMethodList, mMethodMap,
+                    updateOnlyWhenLocaleChanged /* resetDefaultEnabledIme */);
             if (!updateOnlyWhenLocaleChanged) {
                 final String selectedImiId = mSettings.getSelectedInputMethod();
                 if (TextUtils.isEmpty(selectedImiId)) {
@@ -814,7 +820,8 @@
                     mWindowManagerService.setOnHardKeyboardStatusChangeListener(
                             mHardKeyboardListener);
                 }
-                buildInputMethodListLocked(mMethodList, mMethodMap);
+                buildInputMethodListLocked(mMethodList, mMethodMap,
+                        !mImeSelectedOnBoot /* resetDefaultEnabledIme */);
                 if (!mImeSelectedOnBoot) {
                     Slog.w(TAG, "Reset the default IME as \"Resource\" is ready here.");
                     checkCurrentLocaleChangedLocked();
@@ -2147,7 +2154,8 @@
                         mFileManager.addInputMethodSubtypes(imi, subtypes);
                         final long ident = Binder.clearCallingIdentity();
                         try {
-                            buildInputMethodListLocked(mMethodList, mMethodMap);
+                            buildInputMethodListLocked(mMethodList, mMethodMap,
+                                    false /* resetDefaultEnabledIme */);
                         } finally {
                             Binder.restoreCallingIdentity(ident);
                         }
@@ -2397,9 +2405,10 @@
     }
 
     void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
-            HashMap<String, InputMethodInfo> map) {
+            HashMap<String, InputMethodInfo> map, boolean resetDefaultEnabledIme) {
         if (DEBUG) {
-            Slog.d(TAG, "--- re-buildInputMethodList " + ", \n ------ \n" + getStackTrace());
+            Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme
+                    + " \n ------ \n" + getStackTrace());
         }
         list.clear();
         map.clear();
@@ -2436,14 +2445,8 @@
                 final String id = p.getId();
                 map.put(id, p);
 
-                // Valid system default IMEs and IMEs that have English subtypes are enabled
-                // by default
-                if (InputMethodUtils.isDefaultEnabledIme(mSystemReady, p, mContext)) {
-                    setInputMethodEnabledLocked(id, true);
-                }
-
                 if (DEBUG) {
-                    Slog.d(TAG, "Found a third-party input method " + p);
+                    Slog.d(TAG, "Found an input method " + p);
                 }
 
             } catch (XmlPullParserException e) {
@@ -2453,6 +2456,18 @@
             }
         }
 
+        if (resetDefaultEnabledIme) {
+            final ArrayList<InputMethodInfo> defaultEnabledIme =
+                    InputMethodUtils.getDefaultEnabledImes(mContext, mSystemReady, list);
+            for (int i = 0; i < defaultEnabledIme.size(); ++i) {
+                final InputMethodInfo imi =  defaultEnabledIme.get(i);
+                if (DEBUG) {
+                    Slog.d(TAG, "--- enable ime = " + imi);
+                }
+                setInputMethodEnabledLocked(imi.getId(), true);
+            }
+        }
+
         final String defaultImiId = mSettings.getSelectedInputMethod();
         if (!TextUtils.isEmpty(defaultImiId)) {
             if (!map.containsKey(defaultImiId)) {
diff --git a/services/java/com/android/server/PreferredComponent.java b/services/java/com/android/server/PreferredComponent.java
index 718b05d..bb22545 100644
--- a/services/java/com/android/server/PreferredComponent.java
+++ b/services/java/com/android/server/PreferredComponent.java
@@ -164,17 +164,19 @@
         return mParseError;
     }
 
-    public void writeToXml(XmlSerializer serializer) throws IOException {
+    public void writeToXml(XmlSerializer serializer, boolean full) throws IOException {
         final int NS = mSetClasses != null ? mSetClasses.length : 0;
         serializer.attribute(null, "name", mShortComponent);
-        if (mMatch != 0) {
-            serializer.attribute(null, "match", Integer.toHexString(mMatch));
-        }
-        serializer.attribute(null, "set", Integer.toString(NS));
-        for (int s=0; s<NS; s++) {
-            serializer.startTag(null, "set");
-            serializer.attribute(null, "name", mSetComponents[s]);
-            serializer.endTag(null, "set");
+        if (full) {
+            if (mMatch != 0) {
+                serializer.attribute(null, "match", Integer.toHexString(mMatch));
+            }
+            serializer.attribute(null, "set", Integer.toString(NS));
+            for (int s=0; s<NS; s++) {
+                serializer.startTag(null, "set");
+                serializer.attribute(null, "name", mSetComponents[s]);
+                serializer.endTag(null, "set");
+            }
         }
     }
 
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index 626002d..829e67a 100644
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -173,7 +173,7 @@
 public class PackageManagerService extends IPackageManager.Stub {
     static final String TAG = "PackageManager";
     static final boolean DEBUG_SETTINGS = false;
-    private static final boolean DEBUG_PREFERRED = false;
+    static final boolean DEBUG_PREFERRED = true;
     static final boolean DEBUG_UPGRADE = false;
     private static final boolean DEBUG_INSTALL = false;
     private static final boolean DEBUG_REMOVE = false;
@@ -1021,7 +1021,7 @@
 
             readPermissions();
 
-            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false),
+            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
                     mSdkVersion, mOnlyCore);
             long startTime = SystemClock.uptimeMillis();
 
@@ -4967,7 +4967,7 @@
         ps.haveGids = true;
     }
     
-    private final class ActivityIntentResolver
+    final class ActivityIntentResolver
             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
                 boolean defaultOnly, int userId) {
@@ -8830,8 +8830,10 @@
                 }
             }
 
-            if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
-                scheduleWriteSettingsLocked();            
+            int user = UserHandle.getCallingUserId();
+            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
+                mSettings.writePackageRestrictionsLPr(user);
+                scheduleWriteSettingsLocked();
             }
         }
     }
@@ -8849,7 +8851,8 @@
             Iterator<PreferredActivity> it = pir.filterIterator();
             while (it.hasNext()) {
                 PreferredActivity pa = it.next();
-                if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
+                if (packageName == null ||
+                        pa.mPref.mComponent.getPackageName().equals(packageName)) {
                     if (removed == null) {
                         removed = new ArrayList<PreferredActivity>();
                     }
@@ -8862,12 +8865,24 @@
                     pir.removeFilter(pa);
                 }
                 changed = true;
-                mSettings.writePackageRestrictionsLPr(thisUserId);
             }
         }
         return changed;
     }
 
+    public void resetPreferredActivities(int userId) {
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
+        // writer
+        synchronized (mPackages) {
+            int user = UserHandle.getCallingUserId();
+            clearPackagePreferredActivitiesLPw(null, user);
+            mSettings.readDefaultPreferredAppsLPw(this, user);
+            mSettings.writePackageRestrictionsLPr(user);
+            scheduleWriteSettingsLocked();
+        }
+    }
+
     public int getPreferredActivities(List<IntentFilter> outFilters,
             List<ComponentName> outActivities, String packageName) {
 
@@ -9254,6 +9269,7 @@
         }
 
         DumpState dumpState = new DumpState();
+        boolean fullPreferred = false;
         
         String packageName = null;
         
@@ -9277,7 +9293,7 @@
                 pw.println("    r[esolvers]: dump intent resolvers");
                 pw.println("    perm[issions]: dump permissions");
                 pw.println("    pref[erred]: print preferred package settings");
-                pw.println("    preferred-xml: print preferred package settings as xml");
+                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
                 pw.println("    prov[iders]: dump content providers");
                 pw.println("    p[ackages]: dump installed packages");
                 pw.println("    s[hared-users]: dump shared user IDs");
@@ -9311,6 +9327,10 @@
                 dumpState.setDump(DumpState.DUMP_PREFERRED);
             } else if ("preferred-xml".equals(cmd)) {
                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
+                if (opti < args.length && "--full".equals(args[opti])) {
+                    fullPreferred = true;
+                    opti++;
+                }
             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
                 dumpState.setDump(DumpState.DUMP_PACKAGES);
             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
@@ -9405,7 +9425,7 @@
                     serializer.startDocument(null, true);
                     serializer.setFeature(
                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
-                    mSettings.writePreferredActivitiesLPr(serializer, 0);
+                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
                     serializer.endDocument();
                     serializer.flush();
                 } catch (IllegalArgumentException e) {
@@ -10158,7 +10178,7 @@
     /** Called by UserManagerService */
     void createNewUserLILPw(int userHandle, File path) {
         if (mInstaller != null) {
-            mSettings.createNewUserLILPw(mInstaller, userHandle, path);
+            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
         }
     }
 
diff --git a/services/java/com/android/server/pm/PreferredActivity.java b/services/java/com/android/server/pm/PreferredActivity.java
index dbf56ef..c655bb1 100644
--- a/services/java/com/android/server/pm/PreferredActivity.java
+++ b/services/java/com/android/server/pm/PreferredActivity.java
@@ -46,8 +46,8 @@
         mPref = new PreferredComponent(this, parser);
     }
 
-    public void writeToXml(XmlSerializer serializer) throws IOException {
-        mPref.writeToXml(serializer);
+    public void writeToXml(XmlSerializer serializer, boolean full) throws IOException {
+        mPref.writeToXml(serializer, full);
         serializer.startTag(null, "filter");
             super.writeToXml(serializer);
         serializer.endTag(null, "filter");
diff --git a/services/java/com/android/server/pm/Settings.java b/services/java/com/android/server/pm/Settings.java
index e3365244..13f514b 100644
--- a/services/java/com/android/server/pm/Settings.java
+++ b/services/java/com/android/server/pm/Settings.java
@@ -23,6 +23,12 @@
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
 
+import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.os.PatternMatcher;
+import android.util.LogPrinter;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.JournaledFile;
 import com.android.internal.util.XmlUtils;
@@ -972,14 +978,14 @@
         return components;
     }
 
-    void writePreferredActivitiesLPr(XmlSerializer serializer, int userId)
+    void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
             throws IllegalArgumentException, IllegalStateException, IOException {
         serializer.startTag(null, "preferred-activities");
         PreferredIntentResolver pir = mPreferredActivities.get(userId);
         if (pir != null) {
             for (final PreferredActivity pa : pir.filterSet()) {
                 serializer.startTag(null, TAG_ITEM);
-                pa.writeToXml(serializer);
+                pa.writeToXml(serializer, full);
                 serializer.endTag(null, TAG_ITEM);
             }
         }
@@ -1072,7 +1078,7 @@
                 }
             }
 
-            writePreferredActivitiesLPr(serializer, userId);
+            writePreferredActivitiesLPr(serializer, userId, true);
 
             serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
 
@@ -1557,7 +1563,8 @@
         }
     }
 
-    boolean readLPw(List<UserInfo> users, int sdkVersion, boolean onlyCore) {
+    boolean readLPw(PackageManagerService service, List<UserInfo> users, int sdkVersion,
+            boolean onlyCore) {
         FileInputStream str = null;
         if (mBackupSettingsFilename.exists()) {
             try {
@@ -1588,7 +1595,7 @@
                     PackageManagerService.reportSettingsProblem(Log.INFO,
                             "No settings file; creating initial state");
                     if (!onlyCore) {
-                        readDefaultPreferredAppsLPw(0);
+                        readDefaultPreferredAppsLPw(service, 0);
                     }
                     mInternalSdkPlatform = mExternalSdkPlatform = sdkVersion;
                     return false;
@@ -1771,7 +1778,7 @@
         return true;
     }
 
-    private void readDefaultPreferredAppsLPw(int userId) {
+    void readDefaultPreferredAppsLPw(PackageManagerService service, int userId) {
         // Read preferred apps from .../etc/preferred-apps directory.
         File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
         if (!preferredDir.exists() || !preferredDir.isDirectory()) {
@@ -1793,6 +1800,7 @@
                 continue;
             }
 
+            if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
             FileInputStream str = null;
             try {
                 str = new FileInputStream(f);
@@ -1814,7 +1822,7 @@
                             + " does not start with 'preferred-activities'");
                     continue;
                 }
-                readPreferredActivitiesLPw(parser, userId);
+                readDefaultPreferredActivitiesLPw(service, parser, userId);
             } catch (XmlPullParserException e) {
                 Slog.w(TAG, "Error reading apps file " + f, e);
             } catch (IOException e) {
@@ -1830,6 +1838,112 @@
         }
     }
 
+    private void readDefaultPreferredActivitiesLPw(PackageManagerService service,
+            XmlPullParser parser, int userId)
+            throws XmlPullParserException, IOException {
+        int outerDepth = parser.getDepth();
+        int type;
+        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
+                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
+            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
+                continue;
+            }
+
+            String tagName = parser.getName();
+            if (tagName.equals(TAG_ITEM)) {
+                PreferredActivity tmpPa = new PreferredActivity(parser);
+                if (tmpPa.mPref.getParseError() == null) {
+                    // The initial preferences only specify the target activity
+                    // component and intent-filter, not the set of matches.  So we
+                    // now need to query for the matches to build the correct
+                    // preferred activity entry.
+                    if (PackageManagerService.DEBUG_PREFERRED) {
+                        Log.d(TAG, "Processing preferred:");
+                        tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), "  ");
+                    }
+                    final ComponentName cn = tmpPa.mPref.mComponent;
+                    Intent intent = new Intent();
+                    int flags = 0;
+                    intent.setAction(tmpPa.getAction(0));
+                    for (int i=0; i<tmpPa.countCategories(); i++) {
+                        String cat = tmpPa.getCategory(i);
+                        if (cat.equals(Intent.CATEGORY_DEFAULT)) {
+                            flags |= PackageManager.MATCH_DEFAULT_ONLY;
+                        } else {
+                            intent.addCategory(cat);
+                        }
+                    }
+                    if (tmpPa.countDataSchemes() > 0) {
+                        Uri.Builder builder = new Uri.Builder();
+                        builder.scheme(tmpPa.getDataScheme(0));
+                        if (tmpPa.countDataAuthorities() > 0) {
+                            IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(0);
+                            if (auth.getHost() != null) {
+                                builder.authority(auth.getHost());
+                            }
+                        }
+                        if (tmpPa.countDataPaths() > 0) {
+                            PatternMatcher path = tmpPa.getDataPath(0);
+                            builder.path(path.getPath());
+                        }
+                        intent.setData(builder.build());
+                    } else if (tmpPa.countDataTypes() > 0) {
+                        intent.setType(tmpPa.getDataType(0));
+                    }
+                    List<ResolveInfo> ri = service.mActivities.queryIntent(intent,
+                            intent.getType(), flags, 0);
+                    if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Queried " + intent
+                            + " results: " + ri);
+                    int match = 0;
+                    if (ri != null && ri.size() > 1) {
+                        boolean haveAct = false;
+                        boolean haveNonSys = false;
+                        ComponentName[] set = new ComponentName[ri.size()];
+                        for (int i=0; i<ri.size(); i++) {
+                            ActivityInfo ai = ri.get(i).activityInfo;
+                            set[i] = new ComponentName(ai.packageName, ai.name);
+                            if ((ai.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
+                                // If any of the matches are not system apps, then
+                                // there is a third party app that is now an option...
+                                // so don't set a default since we don't want to hide it.
+                                if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
+                                        + ai.packageName + "/" + ai.name + ": non-system!");
+                                haveNonSys = true;
+                                break;
+                            } else if (cn.getPackageName().equals(ai.packageName)
+                                    && cn.getClassName().equals(ai.name)) {
+                                if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
+                                        + ai.packageName + "/" + ai.name + ": default!");
+                                haveAct = true;
+                                match = ri.get(i).match;
+                            } else {
+                                if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
+                                        + ai.packageName + "/" + ai.name + ": skipped");
+                            }
+                        }
+                        if (haveAct && !haveNonSys) {
+                            PreferredActivity pa = new PreferredActivity(tmpPa, match, set,
+                                    tmpPa.mPref.mComponent);
+                            editPreferredActivitiesLPw(userId).addFilter(pa);
+                        } else if (!haveNonSys) {
+                            Slog.w(TAG, "No component found for default preferred activity "
+                                    + tmpPa.mPref.mComponent);
+                        }
+                    }
+                } else {
+                    PackageManagerService.reportSettingsProblem(Log.WARN,
+                            "Error in package manager settings: <preferred-activity> "
+                                    + tmpPa.mPref.getParseError() + " at "
+                                    + parser.getPositionDescription());
+                }
+            } else {
+                PackageManagerService.reportSettingsProblem(Log.WARN,
+                        "Unknown element under <preferred-activities>: " + parser.getName());
+                XmlUtils.skipCurrentTag(parser);
+            }
+        }
+    }
+
     private int readInt(XmlPullParser parser, String ns, String name, int defValue) {
         String v = parser.getAttributeValue(ns, name);
         try {
@@ -2329,7 +2443,8 @@
         }
     }
 
-    void createNewUserLILPw(Installer installer, int userHandle, File path) {
+    void createNewUserLILPw(PackageManagerService service, Installer installer,
+            int userHandle, File path) {
         path.mkdir();
         FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
                 | FileUtils.S_IXOTH, -1, -1);
@@ -2340,7 +2455,7 @@
             installer.createUserData(ps.name,
                     UserHandle.getUid(userHandle, ps.appId), userHandle);
         }
-        readDefaultPreferredAppsLPw(userHandle);
+        readDefaultPreferredAppsLPw(service, userHandle);
         writePackageRestrictionsLPr(userHandle);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java b/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
index 0f531b7..1ab5f45 100644
--- a/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
+++ b/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
@@ -139,7 +139,7 @@
         // Write the package files and make sure they're parsed properly the first time
         writeOldFiles();
         Settings settings = new Settings(getContext(), getContext().getFilesDir());
-        assertEquals(true, settings.readLPw(null, 0, false));
+        assertEquals(true, settings.readLPw(null, null, 0, false));
         assertNotNull(settings.peekPackageLPr(PACKAGE_NAME_3));
         assertNotNull(settings.peekPackageLPr(PACKAGE_NAME_1));
 
@@ -157,11 +157,11 @@
         // Write the package files and make sure they're parsed properly the first time
         writeOldFiles();
         Settings settings = new Settings(getContext(), getContext().getFilesDir());
-        assertEquals(true, settings.readLPw(null, 0, false));
+        assertEquals(true, settings.readLPw(null, null, 0, false));
 
         // Create Settings again to make it read from the new files
         settings = new Settings(getContext(), getContext().getFilesDir());
-        assertEquals(true, settings.readLPw(null, 0, false));
+        assertEquals(true, settings.readLPw(null, null, 0, false));
 
         PackageSetting ps = settings.peekPackageLPr(PACKAGE_NAME_2);
         assertEquals(COMPONENT_ENABLED_STATE_DISABLED_USER, ps.getEnabled(0));
@@ -172,7 +172,7 @@
         // Write the package files and make sure they're parsed properly the first time
         writeOldFiles();
         Settings settings = new Settings(getContext(), getContext().getFilesDir());
-        assertEquals(true, settings.readLPw(null, 0, false));
+        assertEquals(true, settings.readLPw(null, null, 0, false));
 
         // Enable/Disable a package
         PackageSetting ps = settings.peekPackageLPr(PACKAGE_NAME_1);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ClipRegionActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ClipRegionActivity.java
index 3d3d709..774811e 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ClipRegionActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ClipRegionActivity.java
@@ -61,6 +61,7 @@
 
         public RegionView(Context c) {
             super(c);
+            setAlpha(0.5f);
         }
 
         public float getClipPosition() {