Merge "Update the shadow strength" into lmp-dev
diff --git a/Android.mk b/Android.mk
index 35d13d7..d0c8070 100644
--- a/Android.mk
+++ b/Android.mk
@@ -156,7 +156,7 @@
 	core/java/android/hardware/hdmi/IHdmiDeviceEventListener.aidl \
 	core/java/android/hardware/hdmi/IHdmiHotplugEventListener.aidl \
 	core/java/android/hardware/hdmi/IHdmiInputChangeListener.aidl \
-	core/java/android/hardware/hdmi/IHdmiMhlScratchpadCommandListener.aidl \
+	core/java/android/hardware/hdmi/IHdmiMhlVendorCommandListener.aidl \
 	core/java/android/hardware/hdmi/IHdmiRecordListener.aidl \
 	core/java/android/hardware/hdmi/IHdmiSystemAudioModeChangeListener.aidl \
 	core/java/android/hardware/hdmi/IHdmiVendorCommandListener.aidl \
diff --git a/api/current.txt b/api/current.txt
index a7cfd0b..e9da398 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -2550,6 +2550,7 @@
     field public static final int Widget_Material_Light_CompoundButton_CheckBox = 16974504; // 0x10302a8
     field public static final int Widget_Material_Light_CompoundButton_RadioButton = 16974505; // 0x10302a9
     field public static final int Widget_Material_Light_CompoundButton_Star = 16974506; // 0x10302aa
+    field public static final int Widget_Material_Light_DatePicker = 16974578; // 0x10302f2
     field public static final int Widget_Material_Light_DropDownItem = 16974507; // 0x10302ab
     field public static final int Widget_Material_Light_DropDownItem_Spinner = 16974508; // 0x10302ac
     field public static final int Widget_Material_Light_EditText = 16974509; // 0x10302ad
@@ -2587,6 +2588,7 @@
     field public static final int Widget_Material_Light_TabWidget = 16974539; // 0x10302cb
     field public static final int Widget_Material_Light_TextView = 16974540; // 0x10302cc
     field public static final int Widget_Material_Light_TextView_SpinnerItem = 16974541; // 0x10302cd
+    field public static final int Widget_Material_Light_TimePicker = 16974577; // 0x10302f1
     field public static final int Widget_Material_Light_WebTextView = 16974542; // 0x10302ce
     field public static final int Widget_Material_Light_WebView = 16974543; // 0x10302cf
     field public static final int Widget_Material_ListPopupWindow = 16974455; // 0x1030277
@@ -2615,6 +2617,7 @@
     field public static final int Widget_Material_TabWidget = 16974476; // 0x103028c
     field public static final int Widget_Material_TextView = 16974477; // 0x103028d
     field public static final int Widget_Material_TextView_SpinnerItem = 16974478; // 0x103028e
+    field public static final int Widget_Material_TimePicker = 16974576; // 0x10302f0
     field public static final int Widget_Material_Toolbar = 16974479; // 0x103028f
     field public static final int Widget_Material_Toolbar_Button_Navigation = 16974480; // 0x1030290
     field public static final int Widget_Material_WebTextView = 16974481; // 0x1030291
@@ -4325,9 +4328,9 @@
     method public void setAllowEnterTransitionOverlap(boolean);
     method public void setAllowReturnTransitionOverlap(boolean);
     method public void setArguments(android.os.Bundle);
-    method public void setEnterSharedElementTransitionCallback(android.app.SharedElementCallback);
+    method public void setEnterSharedElementCallback(android.app.SharedElementCallback);
     method public void setEnterTransition(android.transition.Transition);
-    method public void setExitSharedElementTransitionCallback(android.app.SharedElementCallback);
+    method public void setExitSharedElementCallback(android.app.SharedElementCallback);
     method public void setExitTransition(android.transition.Transition);
     method public void setHasOptionsMenu(boolean);
     method public void setInitialSavedState(android.app.Fragment.SavedState);
@@ -5403,7 +5406,7 @@
     field public static final java.lang.String ACTION_PASSWORD_EXPIRING = "android.app.action.ACTION_PASSWORD_EXPIRING";
     field public static final java.lang.String ACTION_PASSWORD_FAILED = "android.app.action.ACTION_PASSWORD_FAILED";
     field public static final java.lang.String ACTION_PASSWORD_SUCCEEDED = "android.app.action.ACTION_PASSWORD_SUCCEEDED";
-    field public static final java.lang.String ACTION_PROFILE_PROVISIONING_COMPLETE = "android.app.action.ACTION_PROFILE_PROVISIONING_COMPLETE";
+    field public static final java.lang.String ACTION_PROFILE_PROVISIONING_COMPLETE = "android.app.action.PROFILE_PROVISIONING_COMPLETE";
     field public static final java.lang.String DEVICE_ADMIN_META_DATA = "android.app.device_admin";
     field public static final java.lang.String EXTRA_DISABLE_WARNING = "android.app.extra.DISABLE_WARNING";
     field public static final java.lang.String EXTRA_LOCK_TASK_PACKAGE = "android.app.extra.LOCK_TASK_PACKAGE";
@@ -5519,6 +5522,7 @@
     field public static final java.lang.String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
     field public static final java.lang.String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
     field public static final java.lang.String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
+    field public static final java.lang.String EXTRA_PROVISIONING_EMAIL_ADDRESS = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
     field public static final java.lang.String EXTRA_PROVISIONING_LOCALE = "android.app.extra.PROVISIONING_LOCALE";
     field public static final java.lang.String EXTRA_PROVISIONING_LOCAL_TIME = "android.app.extra.PROVISIONING_LOCAL_TIME";
     field public static final java.lang.String EXTRA_PROVISIONING_TIME_ZONE = "android.app.extra.PROVISIONING_TIME_ZONE";
@@ -5540,7 +5544,6 @@
     field public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 16; // 0x10
     field public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 8; // 0x8
     field public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1; // 0x1
-    field public static final java.lang.String KEY_PROVISIONING_EMAIL_ADDRESS = "android.app.key.PROVISIONING_EMAIL_ADDRESS";
     field public static final java.lang.String MIME_TYPE_PROVISIONING_NFC = "application/com.android.managedprovisioning";
     field public static final int PASSWORD_QUALITY_ALPHABETIC = 262144; // 0x40000
     field public static final int PASSWORD_QUALITY_ALPHANUMERIC = 327680; // 0x50000
@@ -8619,13 +8622,11 @@
   }
 
   public class LauncherApps {
-    method public void addCallback(android.content.pm.LauncherApps.Callback);
     method public java.util.List<android.content.pm.LauncherActivityInfo> getActivityList(java.lang.String, android.os.UserHandle);
     method public boolean isActivityEnabled(android.content.ComponentName, android.os.UserHandle);
     method public boolean isPackageEnabled(java.lang.String, android.os.UserHandle);
     method public void registerCallback(android.content.pm.LauncherApps.Callback);
     method public void registerCallback(android.content.pm.LauncherApps.Callback, android.os.Handler);
-    method public void removeCallback(android.content.pm.LauncherApps.Callback);
     method public android.content.pm.LauncherActivityInfo resolveActivity(android.content.Intent, android.os.UserHandle);
     method public void startAppDetailsActivity(android.content.ComponentName, android.os.UserHandle, android.graphics.Rect, android.os.Bundle);
     method public void startMainActivity(android.content.ComponentName, android.os.UserHandle, android.graphics.Rect, android.os.Bundle);
@@ -22250,9 +22251,9 @@
     field public static final int ON_AFTER_RELEASE = 536870912; // 0x20000000
     field public static final int PARTIAL_WAKE_LOCK = 1; // 0x1
     field public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32; // 0x20
+    field public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1; // 0x1
     field public static final deprecated int SCREEN_BRIGHT_WAKE_LOCK = 10; // 0xa
     field public static final deprecated int SCREEN_DIM_WAKE_LOCK = 6; // 0x6
-    field public static final int WAIT_FOR_DISTANT_PROXIMITY = 1; // 0x1
   }
 
   public final class PowerManager.WakeLock {
@@ -25736,6 +25737,8 @@
   public static final class Telephony.Mms.Intents {
     field public static final java.lang.String CONTENT_CHANGED_ACTION = "android.intent.action.CONTENT_CHANGED";
     field public static final java.lang.String DELETED_CONTENTS = "deleted_contents";
+    field public static final java.lang.String EXTRA_MMS_CONTENT_URI = "android.provider.Telephony.extra.MMS_CONTENT_URI";
+    field public static final java.lang.String EXTRA_MMS_LOCATION_URL = "android.provider.Telephony.extra.MMS_LOCATION_URL";
     field public static final java.lang.String MMS_DOWNLOAD_ACTION = "android.provider.Telephony.MMS_DOWNLOAD";
     field public static final java.lang.String MMS_SEND_ACTION = "android.provider.Telephony.MMS_SEND";
   }
@@ -28486,6 +28489,8 @@
     method public void unregisterPhoneAccount(android.telecomm.PhoneAccountHandle);
     field public static final java.lang.String ACTION_CHANGE_PHONE_ACCOUNTS = "android.telecomm.action.CHANGE_PHONE_ACCOUNTS";
     field public static final java.lang.String ACTION_CONNECTION_SERVICE_CONFIGURE = "android.telecomm.action.CONNECTION_SERVICE_CONFIGURE";
+    field public static final java.lang.String ACTION_PHONE_ACCOUNT_DISABLED = "android.telecom.action.PHONE_ACCOUNT_DISABLED";
+    field public static final java.lang.String ACTION_PHONE_ACCOUNT_ENABLED = "android.telecom.action.PHONE_ACCOUNT_ENABLED";
     field public static final java.lang.String ACTION_SHOW_CALL_SETTINGS = "android.telecomm.action.SHOW_CALL_SETTINGS";
     field public static final char DTMF_CHARACTER_PAUSE = 44; // 0x002c ','
     field public static final char DTMF_CHARACTER_WAIT = 59; // 0x003b ';'
@@ -28861,16 +28866,16 @@
 
   public final class SmsManager {
     method public java.util.ArrayList<java.lang.String> divideMessage(java.lang.String);
-    method public void downloadMultimediaMessage(java.lang.String, android.net.Uri, android.os.Bundle, android.app.PendingIntent);
+    method public void downloadMultimediaMessage(android.content.Context, java.lang.String, android.net.Uri, android.os.Bundle, android.app.PendingIntent);
     method public android.os.Bundle getCarrierConfigValues();
     method public static android.telephony.SmsManager getDefault();
     method public void injectSmsPdu(byte[], java.lang.String, android.app.PendingIntent);
     method public void sendDataMessage(java.lang.String, java.lang.String, short, byte[], android.app.PendingIntent, android.app.PendingIntent);
-    method public void sendMultimediaMessage(android.net.Uri, java.lang.String, android.os.Bundle, android.app.PendingIntent);
+    method public void sendMultimediaMessage(android.content.Context, android.net.Uri, java.lang.String, android.os.Bundle, android.app.PendingIntent);
     method public void sendMultipartTextMessage(java.lang.String, java.lang.String, java.util.ArrayList<java.lang.String>, java.util.ArrayList<android.app.PendingIntent>, java.util.ArrayList<android.app.PendingIntent>);
     method public void sendTextMessage(java.lang.String, java.lang.String, java.lang.String, android.app.PendingIntent, android.app.PendingIntent);
-    method public void updateMmsDownloadStatus(int, byte[]);
-    method public void updateMmsSendStatus(int, boolean);
+    method public void updateMmsDownloadStatus(android.content.Context, int, int, android.net.Uri);
+    method public void updateMmsSendStatus(android.content.Context, int, byte[], int, android.net.Uri);
     method public void updateSmsSendStatus(int, boolean);
     field public static final java.lang.String EXTRA_MMS_DATA = "android.telephony.extra.MMS_DATA";
     field public static final java.lang.String MMS_CONFIG_ALIAS_ENABLED = "aliasEnabled";
@@ -28905,6 +28910,7 @@
     field public static final int MMS_ERROR_HTTP_FAILURE = 4; // 0x4
     field public static final int MMS_ERROR_INVALID_APN = 2; // 0x2
     field public static final int MMS_ERROR_IO_ERROR = 5; // 0x5
+    field public static final int MMS_ERROR_RETRY = 6; // 0x6
     field public static final int MMS_ERROR_UNABLE_CONNECT_MMS = 3; // 0x3
     field public static final int MMS_ERROR_UNSPECIFIED = 1; // 0x1
     field public static final int RESULT_ERROR_GENERIC_FAILURE = 1; // 0x1
@@ -36517,7 +36523,6 @@
     method public abstract java.util.Map<java.lang.String, java.lang.String> getRequestHeaders();
     method public abstract android.net.Uri getUrl();
     method public abstract boolean hasGesture();
-    method public abstract boolean hasUserGestureInsecure();
     method public abstract boolean isForMainFrame();
   }
 
@@ -39114,9 +39119,7 @@
     method public float getShadowRadius();
     method public final boolean getShowSoftInputOnFocus();
     method public java.lang.CharSequence getText();
-    method public static int getTextColor(android.content.Context, android.content.res.TypedArray, int);
     method public final android.content.res.ColorStateList getTextColors();
-    method public static android.content.res.ColorStateList getTextColors(android.content.Context, android.content.res.TypedArray);
     method public java.util.Locale getTextLocale();
     method public float getTextScaleX();
     method public float getTextSize();
diff --git a/api/removed.txt b/api/removed.txt
index 3f2a5a5..8972679 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -35,37 +35,11 @@
 
 }
 
-package android.view.inputmethod {
+package android.widget {
 
-  public class BaseInputConnection implements android.view.inputmethod.InputConnection {
-    method public final boolean requestUpdateCursorAnchorInfo(int);
-  }
-
-  public final class CursorAnchorInfo implements android.os.Parcelable {
-    method public android.graphics.RectF getCharacterRect(int);
-    method public int getCharacterRectFlags(int);
-    method public boolean isInsertionMarkerClipped();
-    field public static final int CHARACTER_RECT_TYPE_FULLY_VISIBLE = 1; // 0x1
-    field public static final int CHARACTER_RECT_TYPE_INVISIBLE = 3; // 0x3
-    field public static final int CHARACTER_RECT_TYPE_MASK = 15; // 0xf
-    field public static final int CHARACTER_RECT_TYPE_NOT_FEASIBLE = 4; // 0x4
-    field public static final int CHARACTER_RECT_TYPE_PARTIALLY_VISIBLE = 2; // 0x2
-    field public static final int CHARACTER_RECT_TYPE_UNSPECIFIED = 0; // 0x0
-  }
-
-  public static final class CursorAnchorInfo.Builder {
-    method public android.view.inputmethod.CursorAnchorInfo.Builder addCharacterRect(int, float, float, float, float, int);
-    method public android.view.inputmethod.CursorAnchorInfo.Builder setInsertionMarkerLocation(float, float, float, float, boolean);
-  }
-
-  public abstract interface InputConnection {
-    method public abstract boolean requestUpdateCursorAnchorInfo(int);
-    field public static final int REQUEST_UPDATE_CURSOR_ANCHOR_INFO_MONITOR = 2; // 0x2
-    field public static final int REQUEST_UPDATE_CURSOR_UPDATE_IMMEDIATE = 1; // 0x1
-  }
-
-  public class InputConnectionWrapper implements android.view.inputmethod.InputConnection {
-    method public final boolean requestUpdateCursorAnchorInfo(int);
+  public class TextView extends android.view.View implements android.view.ViewTreeObserver.OnPreDrawListener {
+    method public static int getTextColor(android.content.Context, android.content.res.TypedArray, int);
+    method public static android.content.res.ColorStateList getTextColors(android.content.Context, android.content.res.TypedArray);
   }
 
 }
diff --git a/cmds/dpm/Android.mk b/cmds/dpm/Android.mk
new file mode 100644
index 0000000..9f5aee4
--- /dev/null
+++ b/cmds/dpm/Android.mk
@@ -0,0 +1,15 @@
+# Copyright 2014 The Android Open Source Project
+#
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_MODULE := dpm
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := dpm
+LOCAL_SRC_FILES := dpm
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_PREBUILT)
diff --git a/cmds/dpm/MODULE_LICENSE_APACHE2 b/cmds/dpm/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/cmds/dpm/MODULE_LICENSE_APACHE2
diff --git a/cmds/dpm/NOTICE b/cmds/dpm/NOTICE
new file mode 100644
index 0000000..316b4eb
--- /dev/null
+++ b/cmds/dpm/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2014, 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.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/cmds/dpm/dpm b/cmds/dpm/dpm
new file mode 100755
index 0000000..c2e5cbb
--- /dev/null
+++ b/cmds/dpm/dpm
@@ -0,0 +1,6 @@
+# Script to start "dpm" on the device
+#
+base=/system
+export CLASSPATH=$base/framework/dpm.jar
+exec app_process $base/bin com.android.commands.dpm.Dpm "$@"
+
diff --git a/cmds/dpm/src/com/android/commands/dpm/Dpm.java b/cmds/dpm/src/com/android/commands/dpm/Dpm.java
new file mode 100644
index 0000000..724b312
--- /dev/null
+++ b/cmds/dpm/src/com/android/commands/dpm/Dpm.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2014 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.commands.dpm;
+
+import android.app.admin.IDevicePolicyManager;
+import android.content.Context;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+
+import com.android.internal.os.BaseCommand;
+
+import java.io.PrintStream;
+
+public final class Dpm extends BaseCommand {
+
+    /**
+     * Command-line entry point.
+     *
+     * @param args The command-line arguments
+     */
+    public static void main(String[] args) {
+      (new Dpm()).run(args);
+    }
+
+    private static final String COMMAND_SET_DEVICE_OWNER = "set-device-owner";
+
+    private IDevicePolicyManager mDevicePolicyManager;
+
+    @Override
+    public void onShowUsage(PrintStream out) {
+        out.println("usage: adb shell dpm [subcommand] [options]\n" +
+                "\n" +
+                "usage: adb shell dpm set-device-owner <PACKAGE>\n" +
+                "  <PACKAGE> an Android package name.\n");
+    }
+
+    @Override
+    public void onRun() throws Exception {
+        mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
+                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
+        if (mDevicePolicyManager == null) {
+            showError("Error: Could not access the Device Policy Manager. Is the system running?");
+            return;
+        }
+
+        String command = nextArgRequired();
+        switch (command) {
+            case COMMAND_SET_DEVICE_OWNER:
+                runSetDeviceOwner(nextArgRequired());
+                break;
+            default:
+                showError("Error: unknown command '" + command + "'");
+        }
+    }
+
+    private void runSetDeviceOwner(String packageName) throws RemoteException {
+        if (mDevicePolicyManager.setDeviceOwner(packageName, null)) {
+            System.out.println("Device owner set to package " + packageName);
+        } else {
+            showError("Error: Can't set package " + packageName + " as device owner.");
+        }
+    }
+}
\ No newline at end of file
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index da34094..3863bc7 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -865,7 +865,7 @@
     }
 
     private void runInstall() {
-        int installFlags = PackageManager.INSTALL_ALL_USERS;
+        int installFlags = 0;
         int userId = UserHandle.USER_ALL;
         String installerPackageName = null;
 
@@ -912,17 +912,17 @@
                 abi = checkAbiArgument(nextOptionData());
             } else if (opt.equals("--user")) {
                 userId = Integer.parseInt(nextOptionData());
-                if (userId == UserHandle.USER_ALL) {
-                    installFlags |= PackageManager.INSTALL_ALL_USERS;
-                } else {
-                    installFlags &= ~PackageManager.INSTALL_ALL_USERS;
-                }
             } else {
                 System.err.println("Error: Unknown option: " + opt);
                 return;
             }
         }
 
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_OWNER;
+            installFlags |= PackageManager.INSTALL_ALL_USERS;
+        }
+
         final Uri verificationURI;
         final Uri originatingURI;
         final Uri referrerURI;
@@ -961,8 +961,8 @@
             VerificationParams verificationParams = new VerificationParams(verificationURI,
                     originatingURI, referrerURI, VerificationParams.NO_UID, null);
 
-            mPm.installPackageAsUser(apkFilePath, obs.getBinder(), installFlags, installerPackageName,
-                    verificationParams, abi, userId);
+            mPm.installPackageAsUser(apkFilePath, obs.getBinder(), installFlags,
+                    installerPackageName, verificationParams, abi, userId);
 
             synchronized (obs) {
                 while (!obs.finished) {
@@ -986,10 +986,10 @@
     }
 
     private void runInstallCreate() throws RemoteException {
+        int userId = UserHandle.USER_ALL;
         String installerPackageName = null;
 
         final SessionParams params = new SessionParams(SessionParams.MODE_FULL_INSTALL);
-        params.installFlags = PackageManager.INSTALL_ALL_USERS;
 
         String opt;
         while ((opt = nextOption()) != null) {
@@ -1010,6 +1010,10 @@
                 params.installFlags |= PackageManager.INSTALL_INTERNAL;
             } else if (opt.equals("-d")) {
                 params.installFlags |= PackageManager.INSTALL_ALLOW_DOWNGRADE;
+            } else if (opt.equals("--originating-uri")) {
+                params.originatingUri = Uri.parse(nextOptionData());
+            } else if (opt.equals("--referrer")) {
+                params.referrerUri = Uri.parse(nextOptionData());
             } else if (opt.equals("-p")) {
                 params.mode = SessionParams.MODE_INHERIT_EXISTING;
                 params.appPackageName = nextOptionData();
@@ -1020,13 +1024,19 @@
                 params.setSize(Long.parseLong(nextOptionData()));
             } else if (opt.equals("--abi")) {
                 params.abiOverride = checkAbiArgument(nextOptionData());
+            } else if (opt.equals("--user")) {
+                userId = Integer.parseInt(nextOptionData());
             } else {
                 throw new IllegalArgumentException("Unknown option " + opt);
             }
         }
 
-        final int sessionId = mInstaller.createSession(params, installerPackageName,
-                UserHandle.USER_OWNER);
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_OWNER;
+            params.installFlags |= PackageManager.INSTALL_ALL_USERS;
+        }
+
+        final int sessionId = mInstaller.createSession(params, installerPackageName, userId);
 
         // NOTE: adb depends on parsing this string
         System.out.println("Success: created install session [" + sessionId + "]");
@@ -1692,11 +1702,7 @@
         }
 
         public Intent getResult() {
-            try {
-                return mResult.poll(30, TimeUnit.SECONDS);
-            } catch (InterruptedException e) {
-                throw new RuntimeException(e);
-            }
+            return mResult.poll();
         }
     }
 
diff --git a/core/java/android/animation/PathKeyframes.java b/core/java/android/animation/PathKeyframes.java
index 70eed90..2a47b68 100644
--- a/core/java/android/animation/PathKeyframes.java
+++ b/core/java/android/animation/PathKeyframes.java
@@ -17,7 +17,6 @@
 
 import android.graphics.Path;
 import android.graphics.PointF;
-import android.util.MathUtils;
 
 import java.util.ArrayList;
 
@@ -64,11 +63,12 @@
 
     @Override
     public Object getValue(float fraction) {
-        fraction = MathUtils.constrain(fraction, 0, 1);
-
         int numPoints = mKeyframeData.length / 3;
-
-        if (fraction == 0) {
+        if (fraction < 0) {
+            return interpolateInRange(fraction, 0, 1);
+        } else if (fraction > 1) {
+            return interpolateInRange(fraction, numPoints - 2, numPoints - 1);
+        } else if (fraction == 0) {
             return pointForIndex(0);
         } else if (fraction == 1) {
             return pointForIndex(numPoints - 1);
@@ -91,27 +91,31 @@
             }
 
             // now high is below the fraction and low is above the fraction
-            int startBase = (high * NUM_COMPONENTS);
-            int endBase = (low * NUM_COMPONENTS);
-
-            float startFraction = mKeyframeData[startBase + FRACTION_OFFSET];
-            float endFraction = mKeyframeData[endBase + FRACTION_OFFSET];
-
-            float intervalFraction = (fraction - startFraction)/(endFraction - startFraction);
-
-            float startX = mKeyframeData[startBase + X_OFFSET];
-            float endX = mKeyframeData[endBase + X_OFFSET];
-            float startY = mKeyframeData[startBase + Y_OFFSET];
-            float endY = mKeyframeData[endBase + Y_OFFSET];
-
-            float x = interpolate(intervalFraction, startX, endX);
-            float y = interpolate(intervalFraction, startY, endY);
-
-            mTempPointF.set(x, y);
-            return mTempPointF;
+            return interpolateInRange(fraction, high, low);
         }
     }
 
+    private PointF interpolateInRange(float fraction, int startIndex, int endIndex) {
+        int startBase = (startIndex * NUM_COMPONENTS);
+        int endBase = (endIndex * NUM_COMPONENTS);
+
+        float startFraction = mKeyframeData[startBase + FRACTION_OFFSET];
+        float endFraction = mKeyframeData[endBase + FRACTION_OFFSET];
+
+        float intervalFraction = (fraction - startFraction)/(endFraction - startFraction);
+
+        float startX = mKeyframeData[startBase + X_OFFSET];
+        float endX = mKeyframeData[endBase + X_OFFSET];
+        float startY = mKeyframeData[startBase + Y_OFFSET];
+        float endY = mKeyframeData[endBase + Y_OFFSET];
+
+        float x = interpolate(intervalFraction, startX, endX);
+        float y = interpolate(intervalFraction, startY, endY);
+
+        mTempPointF.set(x, y);
+        return mTempPointF;
+    }
+
     @Override
     public void invalidateCache() {
     }
diff --git a/core/java/android/app/ActivityTransitionCoordinator.java b/core/java/android/app/ActivityTransitionCoordinator.java
index 43fa3f0..d02d17f 100644
--- a/core/java/android/app/ActivityTransitionCoordinator.java
+++ b/core/java/android/app/ActivityTransitionCoordinator.java
@@ -223,7 +223,10 @@
         mSharedElementNames.addAll(sharedElements.keySet());
         mSharedElements.addAll(sharedElements.values());
         if (getViewsTransition() != null) {
-            getDecor().captureTransitioningViews(mTransitioningViews);
+            ViewGroup decorView = getDecor();
+            if (decorView != null) {
+                decorView.captureTransitioningViews(mTransitioningViews);
+            }
             mTransitioningViews.removeAll(mSharedElements);
         }
         setEpicenter();
@@ -235,6 +238,7 @@
             View view = mTransitioningViews.get(i);
             if (!view.getGlobalVisibleRect(r)) {
                 mTransitioningViews.remove(i);
+                showView(view, true);
             }
         }
     }
@@ -350,7 +354,10 @@
                 sharedElements.put(accepted.get(i), localViews.get(i));
             }
         } else {
-            getDecor().findNamedViews(sharedElements);
+            ViewGroup decorView = getDecor();
+            if (decorView != null) {
+                decorView.findNamedViews(sharedElements);
+            }
         }
         return sharedElements;
     }
@@ -471,16 +478,18 @@
 
     protected void scheduleSetSharedElementEnd(final ArrayList<View> snapshots) {
         final View decorView = getDecor();
-        decorView.getViewTreeObserver().addOnPreDrawListener(
-                new ViewTreeObserver.OnPreDrawListener() {
-                    @Override
-                    public boolean onPreDraw() {
-                        decorView.getViewTreeObserver().removeOnPreDrawListener(this);
-                        notifySharedElementEnd(snapshots);
-                        return true;
+        if (decorView != null) {
+            decorView.getViewTreeObserver().addOnPreDrawListener(
+                    new ViewTreeObserver.OnPreDrawListener() {
+                        @Override
+                        public boolean onPreDraw() {
+                            decorView.getViewTreeObserver().removeOnPreDrawListener(this);
+                            notifySharedElementEnd(snapshots);
+                            return true;
+                        }
                     }
-                }
-        );
+            );
+        }
     }
 
     private static SharedElementOriginalState getOldSharedElementState(View view, String name,
@@ -523,7 +532,10 @@
         ArrayList<View> snapshots = new ArrayList<View>(numSharedElements);
         Context context = getWindow().getContext();
         int[] decorLoc = new int[2];
-        getDecor().getLocationOnScreen(decorLoc);
+        ViewGroup decorView = getDecor();
+        if (decorView != null) {
+            decorView.getLocationOnScreen(decorLoc);
+        }
         for (String name: names) {
             Bundle sharedElementBundle = state.getBundle(name);
             if (sharedElementBundle != null) {
@@ -605,14 +617,17 @@
     protected void showViews(ArrayList<View> views, boolean setTransitionAlpha) {
         int count = views.size();
         for (int i = 0; i < count; i++) {
-            View view = views.get(i);
-            Float alpha = mOriginalAlphas.remove(view);
-            if (alpha != null) {
-                view.setAlpha(alpha);
-            }
-            if (setTransitionAlpha) {
-                view.setTransitionAlpha(1f);
-            }
+            showView(views.get(i), setTransitionAlpha);
+        }
+    }
+
+    private void showView(View view, boolean setTransitionAlpha) {
+        Float alpha = mOriginalAlphas.remove(view);
+        if (alpha != null) {
+            view.setAlpha(alpha);
+        }
+        if (setTransitionAlpha) {
+            view.setTransitionAlpha(1f);
         }
     }
 
@@ -746,15 +761,17 @@
 
     protected void scheduleGhostVisibilityChange(final int visibility) {
         final View decorView = getDecor();
-        decorView.getViewTreeObserver()
-                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
-                    @Override
-                    public boolean onPreDraw() {
-                        decorView.getViewTreeObserver().removeOnPreDrawListener(this);
-                        setGhostVisibility(visibility);
-                        return true;
-                    }
-                });
+        if (decorView != null) {
+            decorView.getViewTreeObserver()
+                    .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
+                        @Override
+                        public boolean onPreDraw() {
+                            decorView.getViewTreeObserver().removeOnPreDrawListener(this);
+                            setGhostVisibility(visibility);
+                            return true;
+                        }
+                    });
+        }
     }
 
     protected class ContinueTransitionListener extends Transition.TransitionListenerAdapter {
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index d746745..6860683 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -66,6 +66,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.Preconditions;
+import com.android.internal.util.UserIcons;
 
 import dalvik.system.VMRuntime;
 
@@ -1660,7 +1661,11 @@
      */
     public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) {
         if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
-            return new BitmapDrawable(getUserManager().getUserIcon(itemInfo.showUserIcon));
+            Bitmap bitmap = getUserManager().getUserIcon(itemInfo.showUserIcon);
+            if (bitmap == null) {
+                return UserIcons.getDefaultUserIcon(itemInfo.showUserIcon, /* light= */ false);
+            }
+            return new BitmapDrawable(bitmap);
         }
         Drawable dr = null;
         if (itemInfo.packageName != null) {
diff --git a/core/java/android/app/EnterTransitionCoordinator.java b/core/java/android/app/EnterTransitionCoordinator.java
index 922561d..bfdb0eb 100644
--- a/core/java/android/app/EnterTransitionCoordinator.java
+++ b/core/java/android/app/EnterTransitionCoordinator.java
@@ -70,16 +70,18 @@
         resultReceiverBundle.putParcelable(KEY_REMOTE_RECEIVER, this);
         mResultReceiver.send(MSG_SET_REMOTE_RECEIVER, resultReceiverBundle);
         final View decorView = getDecor();
-        decorView.getViewTreeObserver().addOnPreDrawListener(
-                new ViewTreeObserver.OnPreDrawListener() {
-                    @Override
-                    public boolean onPreDraw() {
-                        if (mIsReadyForTransition) {
-                            decorView.getViewTreeObserver().removeOnPreDrawListener(this);
+        if (decorView != null) {
+            decorView.getViewTreeObserver().addOnPreDrawListener(
+                    new ViewTreeObserver.OnPreDrawListener() {
+                        @Override
+                        public boolean onPreDraw() {
+                            if (mIsReadyForTransition) {
+                                decorView.getViewTreeObserver().removeOnPreDrawListener(this);
+                            }
+                            return mIsReadyForTransition;
                         }
-                        return mIsReadyForTransition;
-                    }
-                });
+                    });
+        }
     }
 
     public void viewInstancesReady(ArrayList<String> accepted, ArrayList<String> localNames,
@@ -152,7 +154,10 @@
     private ArrayMap<String, View> mapNamedElements(ArrayList<String> accepted,
             ArrayList<String> localNames) {
         ArrayMap<String, View> sharedElements = new ArrayMap<String, View>();
-        getDecor().findNamedViews(sharedElements);
+        ViewGroup decorView = getDecor();
+        if (decorView != null) {
+            decorView.findNamedViews(sharedElements);
+        }
         if (accepted != null) {
             for (int i = 0; i < localNames.size(); i++) {
                 String localName = localNames.get(i);
@@ -170,10 +175,13 @@
 
     private void sendSharedElementDestination() {
         boolean allReady;
+        final View decorView = getDecor();
         if (allowOverlappingTransitions() && getEnterViewsTransition() != null) {
             allReady = false;
+        } else if (decorView == null) {
+            allReady = true;
         } else {
-            allReady = !getDecor().isLayoutRequested();
+            allReady = !decorView.isLayoutRequested();
             if (allReady) {
                 for (int i = 0; i < mSharedElements.size(); i++) {
                     if (mSharedElements.get(i).isLayoutRequested()) {
@@ -188,8 +196,7 @@
             setSharedElementMatrices();
             moveSharedElementsToOverlay();
             mResultReceiver.send(MSG_SHARED_ELEMENT_DESTINATION, state);
-        } else {
-            final View decorView = getDecor();
+        } else if (decorView != null) {
             decorView.getViewTreeObserver()
                     .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                         @Override
@@ -291,6 +298,10 @@
     }
 
     private void startSharedElementTransition(Bundle sharedElementState) {
+        ViewGroup decorView = getDecor();
+        if (decorView == null) {
+            return;
+        }
         // Remove rejected shared elements
         ArrayList<String> rejectedNames = new ArrayList<String>(mAllSharedElementNames);
         rejectedNames.removeAll(mSharedElementNames);
@@ -311,7 +322,8 @@
         boolean startSharedElementTransition = true;
         setGhostVisibility(View.INVISIBLE);
         scheduleGhostVisibilityChange(View.INVISIBLE);
-        Transition transition = beginTransition(startEnterTransition, startSharedElementTransition);
+        Transition transition = beginTransition(decorView, startEnterTransition,
+                startSharedElementTransition);
         scheduleGhostVisibilityChange(View.VISIBLE);
         setGhostVisibility(View.VISIBLE);
 
@@ -324,12 +336,16 @@
         if (mResultReceiver != null) {
             // We can't trust that the view will disappear on the same frame that the shared
             // element appears here. Assure that we get at least 2 frames for double-buffering.
-            getDecor().postOnAnimation(new Runnable() {
+            decorView.postOnAnimation(new Runnable() {
                 int mAnimations;
+
                 @Override
                 public void run() {
                     if (mAnimations++ < MIN_ANIMATION_FRAMES) {
-                        getDecor().postOnAnimation(this);
+                        View decorView = getDecor();
+                        if (decorView != null) {
+                            decorView.postOnAnimation(this);
+                        }
                     } else if (mResultReceiver != null) {
                         mResultReceiver.send(MSG_HIDE_SHARED_ELEMENTS, null);
                         mResultReceiver = null; // all done sending messages.
@@ -346,21 +362,23 @@
         final Bundle sharedElementState = mSharedElementsBundle;
         mSharedElementsBundle = null;
         final View decorView = getDecor();
-        decorView.getViewTreeObserver()
-                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
-                    @Override
-                    public boolean onPreDraw() {
-                        decorView.getViewTreeObserver().removeOnPreDrawListener(this);
-                        startTransition(new Runnable() {
-                            @Override
-                            public void run() {
-                                startSharedElementTransition(sharedElementState);
-                            }
-                        });
-                        return false;
-                    }
-                });
-        decorView.invalidate();
+        if (decorView != null) {
+            decorView.getViewTreeObserver()
+                    .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
+                        @Override
+                        public boolean onPreDraw() {
+                            decorView.getViewTreeObserver().removeOnPreDrawListener(this);
+                            startTransition(new Runnable() {
+                                @Override
+                                public void run() {
+                                    startSharedElementTransition(sharedElementState);
+                                }
+                            });
+                            return false;
+                        }
+                    });
+            decorView.invalidate();
+        }
     }
 
     private void requestLayoutForSharedElements() {
@@ -370,7 +388,7 @@
         }
     }
 
-    private Transition beginTransition(boolean startEnterTransition,
+    private Transition beginTransition(ViewGroup decorView, boolean startEnterTransition,
             boolean startSharedElementTransition) {
         Transition sharedElementTransition = null;
         if (startSharedElementTransition) {
@@ -430,7 +448,7 @@
         Transition transition = mergeTransitions(sharedElementTransition, viewsTransition);
         if (transition != null) {
             transition.addListener(new ContinueTransitionListener());
-            TransitionManager.beginDelayedTransition(getDecor(), transition);
+            TransitionManager.beginDelayedTransition(decorView, transition);
             if (startSharedElementTransition && !mSharedElementNames.isEmpty()) {
                 mSharedElements.get(0).invalidate();
             } else if (startEnterTransition && !mTransitioningViews.isEmpty()) {
@@ -464,8 +482,9 @@
     }
 
     private void startEnterTransition(Transition transition) {
-        if (!mIsReturning) {
-            Drawable background = getDecor().getBackground();
+        ViewGroup decorView = getDecor();
+        if (!mIsReturning && decorView != null) {
+            Drawable background = decorView.getBackground();
             if (background != null) {
                 background = background.mutate();
                 getWindow().setBackgroundDrawable(background);
@@ -536,25 +555,28 @@
         if (rejectedSnapshots == null || rejectedSnapshots.isEmpty()) {
             return;
         }
-        ViewGroupOverlay overlay = getDecor().getOverlay();
-        ObjectAnimator animator = null;
-        int numRejected = rejectedSnapshots.size();
-        for (int i = 0; i < numRejected; i++) {
-            View snapshot = rejectedSnapshots.get(i);
-            overlay.add(snapshot);
-            animator = ObjectAnimator.ofFloat(snapshot, View.ALPHA, 1, 0);
-            animator.start();
-        }
-        animator.addListener(new AnimatorListenerAdapter() {
-            @Override
-            public void onAnimationEnd(Animator animation) {
-                ViewGroupOverlay overlay = getDecor().getOverlay();
-                int numRejected = rejectedSnapshots.size();
-                for (int i = 0; i < numRejected; i++) {
-                    overlay.remove(rejectedSnapshots.get(i));
-                }
+        final ViewGroup decorView = getDecor();
+        if (decorView != null) {
+            ViewGroupOverlay overlay = decorView.getOverlay();
+            ObjectAnimator animator = null;
+            int numRejected = rejectedSnapshots.size();
+            for (int i = 0; i < numRejected; i++) {
+                View snapshot = rejectedSnapshots.get(i);
+                overlay.add(snapshot);
+                animator = ObjectAnimator.ofFloat(snapshot, View.ALPHA, 1, 0);
+                animator.start();
             }
-        });
+            animator.addListener(new AnimatorListenerAdapter() {
+                @Override
+                public void onAnimationEnd(Animator animation) {
+                    ViewGroupOverlay overlay = decorView.getOverlay();
+                    int numRejected = rejectedSnapshots.size();
+                    for (int i = 0; i < numRejected; i++) {
+                        overlay.remove(rejectedSnapshots.get(i));
+                    }
+                }
+            });
+        }
     }
 
     protected void onRemoteExitTransitionComplete() {
@@ -569,9 +591,12 @@
             public void run() {
                 boolean startEnterTransition = true;
                 boolean startSharedElementTransition = false;
-                Transition transition = beginTransition(startEnterTransition,
-                        startSharedElementTransition);
-                startEnterTransition(transition);
+                ViewGroup decorView = getDecor();
+                if (decorView != null) {
+                    Transition transition = beginTransition(decorView, startEnterTransition,
+                            startSharedElementTransition);
+                    startEnterTransition(transition);
+                }
             }
         });
     }
diff --git a/core/java/android/app/ExitTransitionCoordinator.java b/core/java/android/app/ExitTransitionCoordinator.java
index e85ec63..41b0db6 100644
--- a/core/java/android/app/ExitTransitionCoordinator.java
+++ b/core/java/android/app/ExitTransitionCoordinator.java
@@ -129,22 +129,25 @@
         showViews(mTransitioningViews, true);
         showViews(mSharedElements, true);
         mIsHidden = true;
-        if (!mIsReturning && getDecor() != null) {
-            getDecor().suppressLayout(false);
+        ViewGroup decorView = getDecor();
+        if (!mIsReturning && decorView != null) {
+            decorView.suppressLayout(false);
         }
         moveSharedElementsFromOverlay();
         clearState();
     }
 
     private void sharedElementExitBack() {
-        if (getDecor() != null) {
-            getDecor().suppressLayout(true);
+        final ViewGroup decorView = getDecor();
+        if (decorView != null) {
+            decorView.suppressLayout(true);
         }
-        if (mExitSharedElementBundle != null && !mExitSharedElementBundle.isEmpty() &&
+        if (decorView != null && mExitSharedElementBundle != null &&
+                !mExitSharedElementBundle.isEmpty() &&
                 !mSharedElements.isEmpty() && getSharedElementTransition() != null) {
             startTransition(new Runnable() {
                 public void run() {
-                    startSharedElementExit();
+                    startSharedElementExit(decorView);
                 }
             });
         } else {
@@ -152,7 +155,7 @@
         }
     }
 
-    private void startSharedElementExit() {
+    private void startSharedElementExit(final ViewGroup decorView) {
         Transition transition = getSharedElementExitTransition();
         transition.addListener(new Transition.TransitionListenerAdapter() {
             @Override
@@ -165,7 +168,6 @@
         });
         final ArrayList<View> sharedElementSnapshots = createSnapshots(mExitSharedElementBundle,
                 mSharedElementNames);
-        final View decorView = getDecor();
         decorView.getViewTreeObserver()
                 .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                     @Override
@@ -178,10 +180,10 @@
         setGhostVisibility(View.INVISIBLE);
         scheduleGhostVisibilityChange(View.INVISIBLE);
         mListener.onSharedElementEnd(mSharedElementNames, mSharedElements, sharedElementSnapshots);
-        TransitionManager.beginDelayedTransition(getDecor(), transition);
+        TransitionManager.beginDelayedTransition(decorView, transition);
         scheduleGhostVisibilityChange(View.VISIBLE);
         setGhostVisibility(View.VISIBLE);
-        getDecor().invalidate();
+        decorView.invalidate();
     }
 
     private void hideSharedElements() {
@@ -196,8 +198,9 @@
     public void startExit() {
         if (!mIsExitStarted) {
             mIsExitStarted = true;
-            if (getDecor() != null) {
-                getDecor().suppressLayout(true);
+            ViewGroup decorView = getDecor();
+            if (decorView != null) {
+                decorView.suppressLayout(true);
             }
             moveSharedElementsToOverlay();
             startTransition(new Runnable() {
@@ -212,8 +215,9 @@
     public void startExit(int resultCode, Intent data) {
         if (!mIsExitStarted) {
             mIsExitStarted = true;
-            if (getDecor() != null) {
-                getDecor().suppressLayout(true);
+            ViewGroup decorView = getDecor();
+            if (decorView != null) {
+                decorView.suppressLayout(true);
             }
             mHandler = new Handler() {
                 @Override
@@ -224,7 +228,7 @@
             };
             delayCancel();
             moveSharedElementsToOverlay();
-            if (getDecor().getBackground() == null) {
+            if (decorView != null && decorView.getBackground() == null) {
                 getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
             }
             ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(mActivity, this,
@@ -248,8 +252,9 @@
 
     private void startExitTransition() {
         Transition transition = getExitTransition();
-        if (transition != null) {
-            TransitionManager.beginDelayedTransition(getDecor(), transition);
+        ViewGroup decorView = getDecor();
+        if (transition != null && decorView != null) {
+            TransitionManager.beginDelayedTransition(decorView, transition);
             mTransitioningViews.get(0).invalidate();
         } else {
             transitionStarted();
@@ -337,13 +342,14 @@
         Transition viewsTransition = getExitTransition();
 
         Transition transition = mergeTransitions(sharedElementTransition, viewsTransition);
-        if (transition != null) {
+        ViewGroup decorView = getDecor();
+        if (transition != null && decorView != null) {
             setGhostVisibility(View.INVISIBLE);
             scheduleGhostVisibilityChange(View.INVISIBLE);
-            TransitionManager.beginDelayedTransition(getDecor(), transition);
+            TransitionManager.beginDelayedTransition(decorView, transition);
             scheduleGhostVisibilityChange(View.VISIBLE);
             setGhostVisibility(View.VISIBLE);
-            getDecor().invalidate();
+            decorView.invalidate();
         } else {
             transitionStarted();
         }
@@ -392,8 +398,9 @@
                 mExitNotified = true;
                 mResultReceiver.send(MSG_EXIT_TRANSITION_COMPLETE, null);
                 mResultReceiver = null; // done talking
-                if (!mIsReturning && getDecor() != null) {
-                    getDecor().suppressLayout(false);
+                ViewGroup decorView = getDecor();
+                if (!mIsReturning && decorView != null) {
+                    decorView.suppressLayout(false);
                 }
                 finishIfNecessary();
             }
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 4374622..a95abab 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -1628,7 +1628,7 @@
      * @param callback Used to manipulate the shared element transitions on this Fragment
      *                 when added not as a pop from the back stack.
      */
-    public void setEnterSharedElementTransitionCallback(SharedElementCallback callback) {
+    public void setEnterSharedElementCallback(SharedElementCallback callback) {
         if (callback == null) {
             callback = SharedElementCallback.NULL_CALLBACK;
         }
@@ -1636,13 +1636,20 @@
     }
 
     /**
+     * @hide
+     */
+    public void setEnterSharedElementTransitionCallback(SharedElementCallback callback) {
+        setEnterSharedElementCallback(callback);
+    }
+
+    /**
      * When custom transitions are used with Fragments, the exit transition callback
      * is called when this Fragment is attached or detached when popping the back stack.
      *
      * @param callback Used to manipulate the shared element transitions on this Fragment
      *                 when added as a pop from the back stack.
      */
-    public void setExitSharedElementTransitionCallback(SharedElementCallback callback) {
+    public void setExitSharedElementCallback(SharedElementCallback callback) {
         if (callback == null) {
             callback = SharedElementCallback.NULL_CALLBACK;
         }
@@ -1650,6 +1657,13 @@
     }
 
     /**
+     * @hide
+     */
+    public void setExitSharedElementTransitionCallback(SharedElementCallback callback) {
+        setExitSharedElementCallback(callback);
+    }
+
+    /**
      * Sets the Transition that will be used to move Views into the initial scene. The entering
      * Views will be those that are regular Views or ViewGroups that have
      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
diff --git a/core/java/android/app/INotificationManager.aidl b/core/java/android/app/INotificationManager.aidl
index 7d4512b..bdcff38 100644
--- a/core/java/android/app/INotificationManager.aidl
+++ b/core/java/android/app/INotificationManager.aidl
@@ -71,7 +71,6 @@
 
     ComponentName getEffectsSuppressor();
     boolean matchesCallFilter(in Bundle extras);
-    boolean matchesCallFilterAsUser(in Bundle extras, int userId);
 
     ZenModeConfig getZenModeConfig();
     boolean setZenModeConfig(in ZenModeConfig config);
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index f9e4895..31b39eb 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -2680,6 +2680,8 @@
             contentView.setViewVisibility(R.id.line3, View.GONE);
             contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
             contentView.setViewVisibility(R.id.progress, View.GONE);
+            contentView.setViewVisibility(R.id.chronometer, View.GONE);
+            contentView.setViewVisibility(R.id.time, View.GONE);
         }
 
         private RemoteViews applyStandardTemplate(int resId) {
@@ -2775,8 +2777,6 @@
                     contentView.setViewVisibility(R.id.time, View.VISIBLE);
                     contentView.setLong(R.id.time, "setTime", mWhen);
                 }
-            } else {
-                contentView.setViewVisibility(R.id.time, View.GONE);
             }
 
             // Adjust padding depending on line count and font size.
diff --git a/core/java/android/app/SharedElementCallback.java b/core/java/android/app/SharedElementCallback.java
index 82d8e5b..d772743 100644
--- a/core/java/android/app/SharedElementCallback.java
+++ b/core/java/android/app/SharedElementCallback.java
@@ -32,8 +32,8 @@
  * Listener provided in
  * {@link Activity#setEnterSharedElementCallback(SharedElementCallback)} and
  * {@link Activity#setExitSharedElementCallback(SharedElementCallback)} as well as
- * {@link Fragment#setEnterSharedElementTransitionCallback(SharedElementCallback)} and
- * {@link Fragment#setExitSharedElementTransitionCallback(SharedElementCallback)}
+ * {@link Fragment#setEnterSharedElementCallback(SharedElementCallback)} and
+ * {@link Fragment#setExitSharedElementCallback(SharedElementCallback)}
  * to monitor the Shared element transitions. The events can be used to customize Activity
  * and Fragment Transition behavior.
  */
diff --git a/core/java/android/app/admin/DeviceAdminReceiver.java b/core/java/android/app/admin/DeviceAdminReceiver.java
index e2f175c..e9cce51 100644
--- a/core/java/android/app/admin/DeviceAdminReceiver.java
+++ b/core/java/android/app/admin/DeviceAdminReceiver.java
@@ -221,7 +221,7 @@
      */
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     public static final String ACTION_PROFILE_PROVISIONING_COMPLETE =
-            "android.app.action.ACTION_PROFILE_PROVISIONING_COMPLETE";
+            "android.app.action.PROFILE_PROVISIONING_COMPLETE";
 
     /**
      * Name under which a DevicePolicy component publishes information
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 4a21913..13ed8d1 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -148,14 +148,16 @@
      * created for. Used with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}.
      *
+     * <p> This extra is part of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}.
+     *
      * <p> If the {@link #ACTION_PROVISION_MANAGED_PROFILE} intent that starts managed provisioning
      * contains this extra, it is forwarded in the
      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} intent to the mobile
      * device management application that was set as the profile owner during provisioning.
      * It is usually used to avoid that the user has to enter their email address twice.
      */
-    public static final String KEY_PROVISIONING_EMAIL_ADDRESS
-        = "android.app.key.PROVISIONING_EMAIL_ADDRESS";
+    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
+        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
 
     /**
      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 61dd747..4f20705 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -2037,6 +2037,7 @@
      * argument for use by system server and other multi-user aware code.
      * @hide
      */
+    @SystemApi
     public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) {
         throw new RuntimeException("Not implemented. Must override in a subclass.");
     }
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index d49bc50..5ee0b67 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -500,11 +500,18 @@
         }
     }
 
-    /** STOPSHIP remove when launcher 3 has been updated */
+    /**
+     * TODO Remove after 2014-09-22
+     * @hide
+     */
     public void addCallback(Callback callback) {
         registerCallback(callback);
     }
-    /** STOPSHIP remove when launcher 3 has been updated */
+
+    /**
+     * TODO Remove after 2014-09-22
+     * @hide
+     */
     public void removeCallback(Callback callback) {
         unregisterCallback(callback);
     }
diff --git a/core/java/android/hardware/camera2/params/TonemapCurve.java b/core/java/android/hardware/camera2/params/TonemapCurve.java
index 481d67a..398a7e9 100644
--- a/core/java/android/hardware/camera2/params/TonemapCurve.java
+++ b/core/java/android/hardware/camera2/params/TonemapCurve.java
@@ -81,7 +81,8 @@
      * <p>Values are stored as a contiguous array of {@code (Pin, Pout)} points.</p>
      *
      * <p>All parameters may have independent length but should have at most
-     * {@link CameraCharacteristics#TONEMAP_MAX_CURVE_POINTS} * {@value #POINT_SIZE} elements.</p>
+     * {@link CameraCharacteristics#TONEMAP_MAX_CURVE_POINTS} * {@value #POINT_SIZE} elements and
+     * at least 2 * {@value #POINT_SIZE} elements.</p>
      *
      * <p>All sub-elements must be in the inclusive range of
      * [{@value #LEVEL_BLACK}, {@value #LEVEL_WHITE}].</p>
@@ -110,6 +111,10 @@
         checkArgumentArrayLengthDivisibleBy(green, POINT_SIZE, "green");
         checkArgumentArrayLengthDivisibleBy(blue, POINT_SIZE, "blue");
 
+        checkArgumentArrayLengthNoLessThan(red, MIN_CURVE_LENGTH, "red");
+        checkArgumentArrayLengthNoLessThan(green, MIN_CURVE_LENGTH, "green");
+        checkArgumentArrayLengthNoLessThan(blue, MIN_CURVE_LENGTH, "blue");
+
         checkArrayElementsInRange(red, LEVEL_BLACK, LEVEL_WHITE, "red");
         checkArrayElementsInRange(green, LEVEL_BLACK, LEVEL_WHITE, "green");
         checkArrayElementsInRange(blue, LEVEL_BLACK, LEVEL_WHITE, "blue");
@@ -140,6 +145,14 @@
         return colorChannel;
     }
 
+    private static void checkArgumentArrayLengthNoLessThan(float[] array, int minLength,
+            String arrayName) {
+        if (array.length < minLength) {
+            throw new IllegalArgumentException(arrayName + " size must be at least "
+                    + minLength);
+        }
+    }
+
     /**
      * Get the number of points stored in this tonemap curve for the specified color channel.
      *
@@ -270,6 +283,47 @@
         return mHashCode;
     }
 
+    /**
+     * Return the TonemapCurve as a string representation.
+     *
+     * <p> {@code "TonemapCurve{R:[(%f, %f), (%f, %f) ... (%f, %f)], G:[(%f, %f), (%f, %f) ...
+     * (%f, %f)], B:[(%f, %f), (%f, %f) ... (%f, %f)]}"},
+     * where each {@code (%f, %f)} respectively represents one point of the corresponding
+     * tonemap curve. </p>
+     *
+     * @return string representation of {@link TonemapCurve}
+     */
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder("TonemapCurve{");
+        sb.append("R:");
+        sb.append(curveToString(CHANNEL_RED));
+        sb.append(", G:");
+        sb.append(curveToString(CHANNEL_GREEN));
+        sb.append(", B:");
+        sb.append(curveToString(CHANNEL_BLUE));
+        sb.append("}");
+        return sb.toString();
+    }
+
+    private String curveToString(int colorChannel) {
+        checkArgumentColorChannel(colorChannel);
+        StringBuilder sb = new StringBuilder("[");
+        float[] curve = getCurve(colorChannel);
+        int pointCount = curve.length / POINT_SIZE;
+        for (int i = 0, j = 0; i < pointCount; i++, j += 2) {
+            sb.append("(");
+            sb.append(curve[j]);
+            sb.append(", ");
+            sb.append(curve[j+1]);
+            sb.append("), ");
+        }
+        // trim extra ", " at the end. Guaranteed to work because pointCount >= 2
+        sb.setLength(sb.length() - 2);
+        sb.append("]");
+        return sb.toString();
+    }
+
     private float[] getCurve(int colorChannel) {
         switch (colorChannel) {
             case CHANNEL_RED:
@@ -285,6 +339,8 @@
 
     private final static int OFFSET_POINT_IN = 0;
     private final static int OFFSET_POINT_OUT = 1;
+    private final static int TONEMAP_MIN_CURVE_POINTS = 2;
+    private final static int MIN_CURVE_LENGTH = TONEMAP_MIN_CURVE_POINTS * POINT_SIZE;
 
     private final float[] mRed;
     private final float[] mGreen;
@@ -292,4 +348,4 @@
 
     private int mHashCode;
     private boolean mHashCalculated = false;
-};
+}
diff --git a/core/java/android/hardware/hdmi/HdmiTvClient.java b/core/java/android/hardware/hdmi/HdmiTvClient.java
index c37fb5b..9d92fd9 100644
--- a/core/java/android/hardware/hdmi/HdmiTvClient.java
+++ b/core/java/android/hardware/hdmi/HdmiTvClient.java
@@ -36,9 +36,9 @@
     private static final String TAG = "HdmiTvClient";
 
     /**
-     * Size of MHL scratchpad register.
+     * Size of MHL register for vendor command
      */
-    public static final int SCRATCHPAD_DATA_SIZE = 16;
+    public static final int VENDOR_DATA_SIZE = 16;
 
     HdmiTvClient(IHdmiControlService service) {
         super(service);
@@ -332,31 +332,31 @@
     }
 
     /**
-     * Interface used to get incoming MHL scratchpad command.
+     * Interface used to get incoming MHL vendor command.
      */
-    public interface HdmiMhlScratchpadCommandListener {
+    public interface HdmiMhlVendorCommandListener {
         void onReceived(int portId, int offset, int length, byte[] data);
     }
 
     /**
-     * Set {@link HdmiMhlScratchpadCommandListener} to get incoming MHL sSratchpad command.
+     * Set {@link HdmiMhlVendorCommandListener} to get incoming MHL vendor command.
      *
-     * @param listener to receive incoming MHL Scratchpad command
+     * @param listener to receive incoming MHL vendor command
      */
-    public void setHdmiMhlScratchpadCommandListener(HdmiMhlScratchpadCommandListener listener) {
+    public void setHdmiMhlVendorCommandListener(HdmiMhlVendorCommandListener listener) {
         if (listener == null) {
             throw new IllegalArgumentException("listener must not be null.");
         }
         try {
-            mService.addHdmiMhlScratchpadCommandListener(getListenerWrapper(listener));
+            mService.addHdmiMhlVendorCommandListener(getListenerWrapper(listener));
         } catch (RemoteException e) {
-            Log.e(TAG, "failed to set hdmi mhl scratchpad command listener: ", e);
+            Log.e(TAG, "failed to set hdmi mhl vendor command listener: ", e);
         }
     }
 
-    private IHdmiMhlScratchpadCommandListener getListenerWrapper(
-            final HdmiMhlScratchpadCommandListener listener) {
-        return new IHdmiMhlScratchpadCommandListener.Stub() {
+    private IHdmiMhlVendorCommandListener getListenerWrapper(
+            final HdmiMhlVendorCommandListener listener) {
+        return new IHdmiMhlVendorCommandListener.Stub() {
             @Override
             public void onReceived(int portId, int offset, int length, byte[] data) {
                 listener.onReceived(portId, offset, length, data);
@@ -365,29 +365,29 @@
     }
 
     /**
-     * Send MHL Scratchpad command to the device connected to a port of the given portId.
+     * Send MHL vendor command to the device connected to a port of the given portId.
      *
-     * @param portId id of port to send MHL Scratchpad command
+     * @param portId id of port to send MHL vendor command
      * @param offset offset in the in given data
      * @param length length of data. offset + length should be bound to length of data.
-     * @param data container for Scratchpad data. It should be 16 bytes.
+     * @param data container for vendor command data. It should be 16 bytes.
      * @throws IllegalArgumentException if the given parameters are invalid
      */
-    public void sendScratchpadCommand(int portId, int offset, int length, byte[] data) {
-        if (data == null || data.length != SCRATCHPAD_DATA_SIZE) {
-            throw new IllegalArgumentException("Invalid scratchpad data.");
+    public void sendMhlVendorCommand(int portId, int offset, int length, byte[] data) {
+        if (data == null || data.length != VENDOR_DATA_SIZE) {
+            throw new IllegalArgumentException("Invalid vendor command data.");
         }
-        if (offset < 0 || offset >= SCRATCHPAD_DATA_SIZE) {
+        if (offset < 0 || offset >= VENDOR_DATA_SIZE) {
             throw new IllegalArgumentException("Invalid offset:" + offset);
         }
-        if (length < 0 || offset + length > SCRATCHPAD_DATA_SIZE) {
+        if (length < 0 || offset + length > VENDOR_DATA_SIZE) {
             throw new IllegalArgumentException("Invalid length:" + length);
         }
 
         try {
-            mService.sendScratchpadCommand(portId, offset, length, data);
+            mService.sendMhlVendorCommand(portId, offset, length, data);
         } catch (RemoteException e) {
-            Log.e(TAG, "failed to send scratchpad command: ", e);
+            Log.e(TAG, "failed to send vendor command: ", e);
         }
     }
 }
diff --git a/core/java/android/hardware/hdmi/IHdmiControlService.aidl b/core/java/android/hardware/hdmi/IHdmiControlService.aidl
index 3bd45ed..4866a9a 100644
--- a/core/java/android/hardware/hdmi/IHdmiControlService.aidl
+++ b/core/java/android/hardware/hdmi/IHdmiControlService.aidl
@@ -22,7 +22,7 @@
 import android.hardware.hdmi.IHdmiDeviceEventListener;
 import android.hardware.hdmi.IHdmiHotplugEventListener;
 import android.hardware.hdmi.IHdmiInputChangeListener;
-import android.hardware.hdmi.IHdmiMhlScratchpadCommandListener;
+import android.hardware.hdmi.IHdmiMhlVendorCommandListener;
 import android.hardware.hdmi.IHdmiRecordListener;
 import android.hardware.hdmi.IHdmiSystemAudioModeChangeListener;
 import android.hardware.hdmi.IHdmiVendorCommandListener;
@@ -62,11 +62,12 @@
     void sendVendorCommand(int deviceType, int targetAddress, in byte[] params,
             boolean hasVendorId);
     void addVendorCommandListener(IHdmiVendorCommandListener listener, int deviceType);
+    void sendStandby(int deviceType, int deviceId);
     void setHdmiRecordListener(IHdmiRecordListener callback);
     void startOneTouchRecord(int recorderAddress, in byte[] recordSource);
     void stopOneTouchRecord(int recorderAddress);
     void startTimerRecording(int recorderAddress, int sourceType, in byte[] recordSource);
     void clearTimerRecording(int recorderAddress, int sourceType, in byte[] recordSource);
-    void sendScratchpadCommand(int portId, int offset, int length, in byte[] data);
-    void addHdmiMhlScratchpadCommandListener(IHdmiMhlScratchpadCommandListener listener);
+    void sendMhlVendorCommand(int portId, int offset, int length, in byte[] data);
+    void addHdmiMhlVendorCommandListener(IHdmiMhlVendorCommandListener listener);
 }
diff --git a/core/java/android/hardware/hdmi/IHdmiMhlScratchpadCommandListener.aidl b/core/java/android/hardware/hdmi/IHdmiMhlVendorCommandListener.aidl
similarity index 84%
rename from core/java/android/hardware/hdmi/IHdmiMhlScratchpadCommandListener.aidl
rename to core/java/android/hardware/hdmi/IHdmiMhlVendorCommandListener.aidl
index 4176597..4696677 100644
--- a/core/java/android/hardware/hdmi/IHdmiMhlScratchpadCommandListener.aidl
+++ b/core/java/android/hardware/hdmi/IHdmiMhlVendorCommandListener.aidl
@@ -17,11 +17,10 @@
 package android.hardware.hdmi;
 
  /**
- * Callback interface definition for MHL client to get the scratchpad
- * command.
+ * Callback interface definition for MHL client to get the vendor command.
  *
  * @hide
  */
- oneway interface IHdmiMhlScratchpadCommandListener {
+ oneway interface IHdmiMhlVendorCommandListener {
       void onReceived(int portId, int offset, int length, in byte[] data);
  }
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index d1ad0ad..5230128 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -236,6 +236,7 @@
     private static final int EX_NULL_POINTER = -4;
     private static final int EX_ILLEGAL_STATE = -5;
     private static final int EX_NETWORK_MAIN_THREAD = -6;
+    private static final int EX_UNSUPPORTED_OPERATION = -7;
     private static final int EX_HAS_REPLY_HEADER = -128;  // special; see below
 
     private static native int nativeDataSize(long nativePtr);
@@ -1427,6 +1428,8 @@
             code = EX_ILLEGAL_STATE;
         } else if (e instanceof NetworkOnMainThreadException) {
             code = EX_NETWORK_MAIN_THREAD;
+        } else if (e instanceof UnsupportedOperationException) {
+            code = EX_UNSUPPORTED_OPERATION;
         }
         writeInt(code);
         StrictMode.clearGatheredViolations();
@@ -1545,6 +1548,8 @@
                 throw new IllegalStateException(msg);
             case EX_NETWORK_MAIN_THREAD:
                 throw new NetworkOnMainThreadException();
+            case EX_UNSUPPORTED_OPERATION:
+                throw new UnsupportedOperationException(msg);
         }
         throw new RuntimeException("Unknown exception code: " + code
                 + " msg " + msg);
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 00e2e22..18b2082 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -248,7 +248,7 @@
      * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
      * indicates that an object is not in close proximity.
      */
-    public static final int WAIT_FOR_DISTANT_PROXIMITY = 1;
+    public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
 
     /**
      * Brightness value for fully on.
@@ -961,8 +961,8 @@
          * </p>
          *
          * @param flags Combination of flag values to modify the release behavior.
-         * Currently only {@link #WAIT_FOR_DISTANT_PROXIMITY} is supported. Passing 0 is
-         * equivalent to calling {@link #release()}.
+         * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
+         * Passing 0 is equivalent to calling {@link #release()}.
          */
         public void release(int flags) {
             synchronized (mToken) {
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index c76ff11..c25278f 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -998,6 +998,7 @@
      * Returns a file descriptor for the user's photo. PNG data can be read from this file.
      * @param userHandle the user whose photo we want to read.
      * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
+     * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
      * @hide
      */
     public Bitmap getUserIcon(int userHandle) {
diff --git a/core/java/android/transition/TransitionSet.java b/core/java/android/transition/TransitionSet.java
index 47ba8bd..669621eb3 100644
--- a/core/java/android/transition/TransitionSet.java
+++ b/core/java/android/transition/TransitionSet.java
@@ -432,11 +432,17 @@
      */
     @Override
     protected void runAnimators() {
+        if (mTransitions.isEmpty()) {
+            start();
+            end();
+            return;
+        }
         setupStartEndListeners();
+        int numTransitions = mTransitions.size();
         if (!mPlayTogether) {
             // Setup sequence with listeners
             // TODO: Need to add listeners in such a way that we can remove them later if canceled
-            for (int i = 1; i < mTransitions.size(); ++i) {
+            for (int i = 1; i < numTransitions; ++i) {
                 Transition previousTransition = mTransitions.get(i - 1);
                 final Transition nextTransition = mTransitions.get(i);
                 previousTransition.addListener(new TransitionListenerAdapter() {
@@ -452,8 +458,8 @@
                 firstTransition.runAnimators();
             }
         } else {
-            for (Transition childTransition : mTransitions) {
-                childTransition.runAnimators();
+            for (int i = 0; i < numTransitions; ++i) {
+                mTransitions.get(i).runAnimators();
             }
         }
     }
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index 2ed125d..fec7550 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -638,6 +638,11 @@
     public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs);
 
     /**
+     * Return the window that is hiding the keyguard, if such a thing exists.
+     */
+    public WindowState getWinShowWhenLockedLw();
+
+    /**
      * Called when the system would like to show a UI to indicate that an
      * application is starting.  You can use this to add a
      * APPLICATION_STARTING_TYPE window with the given appToken to the window
diff --git a/core/java/android/view/inputmethod/BaseInputConnection.java b/core/java/android/view/inputmethod/BaseInputConnection.java
index 20adfe4..ba5d6c2 100644
--- a/core/java/android/view/inputmethod/BaseInputConnection.java
+++ b/core/java/android/view/inputmethod/BaseInputConnection.java
@@ -436,14 +436,6 @@
     }
 
     /**
-     * The default implementation does nothing.
-     * @removed
-     */
-    public final boolean requestUpdateCursorAnchorInfo(int cursorUpdateMode) {
-        return false;
-    }
-
-    /**
      * The default implementation places the given text into the editable,
      * replacing any existing composing text.  The new text is marked as
      * in a composing state with the composing style.
diff --git a/core/java/android/view/inputmethod/CursorAnchorInfo.java b/core/java/android/view/inputmethod/CursorAnchorInfo.java
index 600fffe..fd73432 100644
--- a/core/java/android/view/inputmethod/CursorAnchorInfo.java
+++ b/core/java/android/view/inputmethod/CursorAnchorInfo.java
@@ -120,38 +120,6 @@
      */
     public static final int FLAG_IS_RTL = 0x04;
 
-    /**
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_MASK = 0x0f;
-    /**
-     * Type for {@link #CHARACTER_RECT_TYPE_MASK}: the editor did not specify any type of this
-     * character. Editor authors should not use this flag.
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_UNSPECIFIED = 0;
-    /**
-     * Type for {@link #CHARACTER_RECT_TYPE_MASK}: the character is entirely visible.
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_FULLY_VISIBLE = 1;
-    /**
-     * Type for {@link #CHARACTER_RECT_TYPE_MASK}: some area of the character is invisible.
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_PARTIALLY_VISIBLE = 2;
-    /**
-     * Type for {@link #CHARACTER_RECT_TYPE_MASK}: the character is entirely invisible.
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_INVISIBLE = 3;
-    /**
-     * Type for {@link #CHARACTER_RECT_TYPE_MASK}: the editor gave up to calculate the rectangle
-     * for this character. Input method authors should ignore the returned rectangle.
-     * @removed
-     */
-    public static final int CHARACTER_RECT_TYPE_NOT_FEASIBLE = 4;
-
     public CursorAnchorInfo(final Parcel source) {
         mSelectionStart = source.readInt();
         mSelectionEnd = source.readInt();
@@ -318,20 +286,6 @@
         }
 
         /**
-         * @removed
-         */
-        public Builder setInsertionMarkerLocation(final float horizontalPosition,
-                final float lineTop, final float lineBaseline, final float lineBottom,
-                final boolean clipped){
-            mInsertionMarkerHorizontal = horizontalPosition;
-            mInsertionMarkerTop = lineTop;
-            mInsertionMarkerBaseline = lineBaseline;
-            mInsertionMarkerBottom = lineBottom;
-            mInsertionMarkerFlags = clipped ? FLAG_HAS_INVISIBLE_REGION : 0;
-            return this;
-        }
-
-        /**
          * Sets the location of the text insertion point (zero width cursor) as a rectangle in
          * local coordinates. Calling this can be skipped when there is no text insertion point;
          * however if there is an insertion point, editors must call this method.
@@ -390,43 +344,6 @@
         }
 
         /**
-         * Adds the bounding box of the character specified with the index.
-         *
-         * @param index index of the character in Java chars units. Must be specified in
-         * ascending order across successive calls.
-         * @param leadingEdgeX x coordinate of the leading edge of the character in local
-         * coordinates, that is, left edge for LTR text and right edge for RTL text.
-         * @param leadingEdgeY y coordinate of the leading edge of the character in local
-         * coordinates.
-         * @param trailingEdgeX x coordinate of the trailing edge of the character in local
-         * coordinates, that is, right edge for LTR text and left edge for RTL text.
-         * @param trailingEdgeY y coordinate of the trailing edge of the character in local
-         * coordinates.
-         * @param flags flags for this character rect. See {@link #FLAG_HAS_VISIBLE_REGION} for
-         * example.
-         * @throws IllegalArgumentException If the index is a negative value, or not greater than
-         * all of the previously called indices.
-         * @removed
-         */
-        public Builder addCharacterRect(final int index, final float leadingEdgeX,
-                final float leadingEdgeY, final float trailingEdgeX, final float trailingEdgeY,
-                final int flags) {
-            final int newFlags;
-            final float left;
-            final float right;
-            if (leadingEdgeX <= trailingEdgeX) {
-                newFlags = flags;
-                left = leadingEdgeX;
-                right = trailingEdgeX;
-            } else {
-                newFlags = flags | FLAG_IS_RTL;
-                left = trailingEdgeX;
-                right = leadingEdgeX;
-            }
-            return addCharacterBounds(index, left, leadingEdgeY, right, trailingEdgeY, newFlags);
-        }
-
-        /**
          * Sets the matrix that transforms local coordinates into screen coordinates.
          * @param matrix transformation matrix from local coordinates into screen coordinates. null
          * is interpreted as an identity matrix.
@@ -538,15 +455,6 @@
     }
 
     /**
-     * Returns the visibility of the insertion marker.
-     * @return {@code true} if the insertion marker is partially or entirely clipped.
-     * @removed
-     */
-    public boolean isInsertionMarkerClipped() {
-        return (mInsertionMarkerFlags & FLAG_HAS_VISIBLE_REGION) != 0;
-    }
-
-    /**
      * Returns the horizontal start of the insertion marker, in the local coordinates that will
      * be transformed with {@link #getMatrix()} when rendered on the screen.
      * @return x coordinate that is compatible with {@link Layout#getPrimaryHorizontal(int)}.
@@ -602,25 +510,6 @@
     }
 
     /**
-     * Returns a new instance of {@link RectF} that indicates the location of the character
-     * specified with the index.
-     * <p>
-     * Note that coordinates are not necessarily contiguous or even monotonous, especially when
-     * RTL text and LTR text are mixed.
-     * </p>
-     * @param index index of the character in a Java chars.
-     * @return a new instance of {@link RectF} that represents the location of the character in
-     * local coordinates. null if the character is invisible or the application did not provide
-     * the location. Note that the {@code left} field can be greater than the {@code right} field
-     * if the character is in RTL text. Returns {@code null} if no location information is
-     * available.
-     * @removed
-     */
-    public RectF getCharacterRect(final int index) {
-        return getCharacterBounds(index);
-    }
-
-    /**
      * Returns the flags associated with the character bounds specified with the index.
      * @param index index of the character in a Java chars.
      * @return {@code 0} if no flag is specified.
@@ -633,16 +522,6 @@
     }
 
     /**
-     * Returns the flags associated with the character rect specified with the index.
-     * @param index index of the character in a Java chars.
-     * @return {@code 0} if no flag is specified.
-     * @removed
-     */
-    public int getCharacterRectFlags(final int index) {
-        return getCharacterBoundsFlags(index);
-    }
-
-    /**
      * Returns a new instance of {@link android.graphics.Matrix} that indicates the transformation
      * matrix that is to be applied other positional data in this class.
      * @return a new instance (copy) of the transformation matrix.
diff --git a/core/java/android/view/inputmethod/InputConnection.java b/core/java/android/view/inputmethod/InputConnection.java
index 093fb2f..c51d8a7 100644
--- a/core/java/android/view/inputmethod/InputConnection.java
+++ b/core/java/android/view/inputmethod/InputConnection.java
@@ -756,19 +756,4 @@
      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}.
      */
     public boolean requestCursorUpdates(int cursorUpdateMode);
-
-    /**
-     * @removed
-     */
-    public static final int REQUEST_UPDATE_CURSOR_UPDATE_IMMEDIATE = 1 << 0;
-
-    /**
-     * @removed
-     */
-    public static final int REQUEST_UPDATE_CURSOR_ANCHOR_INFO_MONITOR = 1 << 1;
-
-    /**
-     * @removed
-     */
-    public boolean requestUpdateCursorAnchorInfo(int cursorUpdateMode);
 }
diff --git a/core/java/android/view/inputmethod/InputConnectionWrapper.java b/core/java/android/view/inputmethod/InputConnectionWrapper.java
index 87853de..231aa07 100644
--- a/core/java/android/view/inputmethod/InputConnectionWrapper.java
+++ b/core/java/android/view/inputmethod/InputConnectionWrapper.java
@@ -129,11 +129,4 @@
     public boolean requestCursorUpdates(int cursorUpdateMode) {
         return mTarget.requestCursorUpdates(cursorUpdateMode);
     }
-
-    /**
-     * @removed
-     */
-    public final boolean requestUpdateCursorAnchorInfo(int cursorUpdateMode) {
-        return mTarget.requestCursorUpdates(cursorUpdateMode);
-    }
 }
diff --git a/core/java/android/webkit/WebResourceRequest.java b/core/java/android/webkit/WebResourceRequest.java
index b46ac9a..2185658 100644
--- a/core/java/android/webkit/WebResourceRequest.java
+++ b/core/java/android/webkit/WebResourceRequest.java
@@ -41,21 +41,12 @@
     boolean isForMainFrame();
 
     /**
-     * Gets whether a gesture (such as a link click) was associated with the request.
-     * <p>
-     * <strong>IMPORTANT:</strong>
-     * This should not be used to implement any form of security. It is possible for the content
-     * to spoof this.
+     * Gets whether a gesture (such as a click) was associated with the request.
      *
      * @return whether a gesture was associated with the request.
      */
     boolean hasGesture();
 
-    /*
-     * @removed
-     */
-    boolean hasUserGestureInsecure();
-
     /**
      * Gets the method associated with the request, for example "GET".
      *
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 94d52d5..3859e48 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -5721,14 +5721,6 @@
         public boolean requestCursorUpdates(int cursorUpdateMode) {
             return getTarget().requestCursorUpdates(cursorUpdateMode);
         }
-
-        /**
-         * @removed
-         */
-        @Override
-        public boolean requestUpdateCursorAnchorInfo(int cursorUpdateMode) {
-            return getTarget().requestCursorUpdates(cursorUpdateMode);
-        }
     }
 
     /**
diff --git a/core/java/android/widget/ActionMenuPresenter.java b/core/java/android/widget/ActionMenuPresenter.java
index ef8c006..d779124 100644
--- a/core/java/android/widget/ActionMenuPresenter.java
+++ b/core/java/android/widget/ActionMenuPresenter.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.content.res.Configuration;
 import android.content.res.Resources;
+import android.graphics.Matrix;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.os.Parcel;
@@ -582,6 +583,8 @@
     }
 
     private class OverflowMenuButton extends ImageButton implements ActionMenuView.ActionMenuChildView {
+        private final float[] mTempPts = new float[2];
+
         public OverflowMenuButton(Context context) {
             super(context, null, com.android.internal.R.attr.actionOverflowButtonStyle);
 
@@ -649,20 +652,21 @@
         }
 
         @Override
-        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
-            super.onLayout(changed, left, top, right, bottom);
+        protected boolean setFrame(int l, int t, int r, int b) {
+            final boolean changed = super.setFrame(l, t, r, b);
 
             // Set up the hotspot bounds to be centered on the image.
             final Drawable d = getDrawable();
             final Drawable bg = getBackground();
             if (d != null && bg != null) {
-                final Rect bounds = d.getBounds();
-                final int height = bottom - top;
-                final int offset = (height - bounds.width()) / 2;
-                final int hotspotLeft = bounds.left - offset;
-                final int hotspotRight = bounds.right + offset;
-                bg.setHotspotBounds(hotspotLeft, 0, hotspotRight, height);
+                final float[] pts = mTempPts;
+                pts[0] = d.getBounds().centerX();
+                getImageMatrix().mapPoints(pts);
+                final int offset =  (int) pts[0] - getWidth() / 2;
+                bg.setHotspotBounds(offset, 0, getWidth() + offset, getHeight());
             }
+
+            return changed;
         }
     }
 
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index a81ff97..1509e80 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -8178,6 +8178,8 @@
      * Returns the TextView_textColor attribute from the TypedArray, if set, or
      * the TextAppearance_textColor from the TextView_textAppearance attribute,
      * if TextView_textColor was not set directly.
+     *
+     * @removed
      */
     public static ColorStateList getTextColors(Context context, TypedArray attrs) {
         // It's not safe to use this method from apps. The parameter 'attrs'
@@ -8205,6 +8207,8 @@
      * AttributeSet, if set, or the default color from the
      * TextAppearance_textColor from the TextView_textAppearance attribute, if
      * TextView_textColor was not set directly.
+     *
+     * @removed
      */
     public static int getTextColor(Context context, TypedArray attrs, int def) {
         final ColorStateList colors = getTextColors(context, attrs);
diff --git a/core/java/android/widget/Toolbar.java b/core/java/android/widget/Toolbar.java
index ba2d5b8..1ce19ce 100644
--- a/core/java/android/widget/Toolbar.java
+++ b/core/java/android/widget/Toolbar.java
@@ -33,6 +33,7 @@
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
+import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
 
@@ -132,6 +133,8 @@
     private int mTitleTextColor;
     private int mSubtitleTextColor;
 
+    private boolean mEatingTouch;
+
     // Clear me after use.
     private final ArrayList<View> mTempViews = new ArrayList<View>();
 
@@ -1061,6 +1064,32 @@
         removeCallbacks(mShowOverflowMenuRunnable);
     }
 
+    @Override
+    public boolean onTouchEvent(MotionEvent ev) {
+        // Toolbars always eat touch events, but should still respect the touch event dispatch
+        // contract. If the normal View implementation doesn't want the events, we'll just silently
+        // eat the rest of the gesture without reporting the events to the default implementation
+        // since that's what it expects.
+
+        final int action = ev.getActionMasked();
+        if (action == MotionEvent.ACTION_DOWN) {
+            mEatingTouch = false;
+        }
+
+        if (!mEatingTouch) {
+            final boolean handled = super.onTouchEvent(ev);
+            if (action == MotionEvent.ACTION_DOWN && !handled) {
+                mEatingTouch = true;
+            }
+        }
+
+        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
+            mEatingTouch = false;
+        }
+
+        return true;
+    }
+
     /**
      * @hide
      */
diff --git a/core/java/com/android/internal/util/UserIcons.java b/core/java/com/android/internal/util/UserIcons.java
new file mode 100644
index 0000000..e1e9d5e
--- /dev/null
+++ b/core/java/com/android/internal/util/UserIcons.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2014 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.util;
+
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.PorterDuff.Mode;
+import android.graphics.drawable.Drawable;
+import android.os.UserHandle;
+
+import com.android.internal.R;
+
+/**
+ * Helper class that generates default user icons.
+ */
+public class UserIcons {
+
+    private static final int[] USER_ICON_COLORS = {
+        R.color.user_icon_1,
+        R.color.user_icon_2,
+        R.color.user_icon_3,
+        R.color.user_icon_4,
+        R.color.user_icon_5,
+        R.color.user_icon_6,
+        R.color.user_icon_7,
+        R.color.user_icon_8
+    };
+
+    /**
+     * Converts a given drawable to a bitmap.
+     */
+    public static Bitmap convertToBitmap(Drawable icon) {
+        if (icon == null) {
+            return null;
+        }
+        Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
+                Bitmap.Config.ARGB_8888);
+        icon.draw(new Canvas(bitmap));
+        return bitmap;
+    }
+
+    /**
+     * Returns a default user icon for the given user.
+     *
+     * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
+     * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
+     * @param light whether we want a light icon (suitable for a dark background)
+     */
+    public static Drawable getDefaultUserIcon(int userId, boolean light) {
+        int colorResId = light ? R.color.user_icon_default_white : R.color.user_icon_default_gray;
+        if (userId != UserHandle.USER_NULL) {
+            // Return colored icon instead
+            colorResId = USER_ICON_COLORS[userId % USER_ICON_COLORS.length];
+        }
+        Drawable icon = Resources.getSystem().getDrawable(R.drawable.ic_account_circle).mutate();
+        icon.setColorFilter(Resources.getSystem().getColor(colorResId), Mode.SRC_IN);
+        icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
+        return icon;
+    }
+}
diff --git a/core/java/com/android/internal/view/InputConnectionWrapper.java b/core/java/com/android/internal/view/InputConnectionWrapper.java
index 0c65ad1..7dc927f 100644
--- a/core/java/com/android/internal/view/InputConnectionWrapper.java
+++ b/core/java/com/android/internal/view/InputConnectionWrapper.java
@@ -445,11 +445,4 @@
         }
         return result;
     }
-
-    /**
-     * @removed
-     */
-    public boolean requestUpdateCursorAnchorInfo(int cursorUpdateMode) {
-        return requestCursorUpdates(cursorUpdateMode);
-    }
 }
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 396f3ec..4859ee6 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -2051,6 +2051,8 @@
         (void*) android_content_AssetManager_dumpTheme },
     { "applyStyle","(JIIJ[I[I[I)Z",
         (void*) android_content_AssetManager_applyStyle },
+    { "resolveAttrs","(JII[I[I[I[I)Z",
+        (void*) android_content_AssetManager_resolveAttrs },
     { "retrieveAttributes","(J[I[I[I)Z",
         (void*) android_content_AssetManager_retrieveAttributes },
     { "getArraySize","(I)I",
diff --git a/core/res/res/drawable-hdpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-hdpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index 6c36eae..0000000
--- a/core/res/res/drawable-hdpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_dialog_alert_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_dialog_alert_mtrl_alpha.png
deleted file mode 100644
index 95cfb32..0000000
--- a/core/res/res/drawable-hdpi/ic_dialog_alert_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_go_search_api_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_go_search_api_mtrl_alpha.png
deleted file mode 100644
index aa23c59..0000000
--- a/core/res/res/drawable-hdpi/ic_go_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_copy_mtrl_am_alpha.png b/core/res/res/drawable-hdpi/ic_menu_copy_mtrl_am_alpha.png
deleted file mode 100644
index d6d1f2f..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_copy_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_cut_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_menu_cut_mtrl_alpha.png
deleted file mode 100644
index ec8db6f..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_cut_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_moreoverflow_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_menu_moreoverflow_mtrl_alpha.png
deleted file mode 100644
index 1ba1295..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_moreoverflow_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_paste_mtrl_am_alpha.png b/core/res/res/drawable-hdpi/ic_menu_paste_mtrl_am_alpha.png
deleted file mode 100644
index bf44722..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_paste_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_selectall_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_menu_selectall_mtrl_alpha.png
deleted file mode 100644
index 8539741..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_selectall_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_share_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_menu_share_mtrl_alpha.png
deleted file mode 100644
index 0eacedd..0000000
--- a/core/res/res/drawable-hdpi/ic_menu_share_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_search_api_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_search_api_mtrl_alpha.png
deleted file mode 100644
index f7382d3..0000000
--- a/core/res/res/drawable-hdpi/ic_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_voice_search_api_mtrl_alpha.png b/core/res/res/drawable-hdpi/ic_voice_search_api_mtrl_alpha.png
deleted file mode 100644
index 25b8935..0000000
--- a/core/res/res/drawable-hdpi/ic_voice_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/list_divider_mtrl_alpha.9.png b/core/res/res/drawable-hdpi/list_divider_mtrl_alpha.9.png
index 77845df..2fa6d7e 100644
--- a/core/res/res/drawable-hdpi/list_divider_mtrl_alpha.9.png
+++ b/core/res/res/drawable-hdpi/list_divider_mtrl_alpha.9.png
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-ldpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index 96e86b6..0000000
--- a/core/res/res/drawable-ldpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_dialog_alert_mtrl_alpha.png b/core/res/res/drawable-ldpi/ic_dialog_alert_mtrl_alpha.png
deleted file mode 100644
index f604e8b..0000000
--- a/core/res/res/drawable-ldpi/ic_dialog_alert_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_copy_mtrl_am_alpha.png b/core/res/res/drawable-ldpi/ic_menu_copy_mtrl_am_alpha.png
deleted file mode 100644
index 565280b..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_copy_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_cut_mtrl_alpha.png b/core/res/res/drawable-ldpi/ic_menu_cut_mtrl_alpha.png
deleted file mode 100644
index dbedece..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_cut_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_moreoverflow_mtrl_alpha.png b/core/res/res/drawable-ldpi/ic_menu_moreoverflow_mtrl_alpha.png
deleted file mode 100644
index d47f81e..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_moreoverflow_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_paste_mtrl_am_alpha.png b/core/res/res/drawable-ldpi/ic_menu_paste_mtrl_am_alpha.png
deleted file mode 100644
index 430141b..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_paste_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_selectall_mtrl_alpha.png b/core/res/res/drawable-ldpi/ic_menu_selectall_mtrl_alpha.png
deleted file mode 100644
index 7b520bc..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_selectall_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/ic_menu_share_mtrl_alpha.png b/core/res/res/drawable-ldpi/ic_menu_share_mtrl_alpha.png
deleted file mode 100644
index db1e146..0000000
--- a/core/res/res/drawable-ldpi/ic_menu_share_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-ldpi/list_divider_mtrl_alpha.9.png b/core/res/res/drawable-ldpi/list_divider_mtrl_alpha.9.png
index 77845df..941d0d7 100644
--- a/core/res/res/drawable-ldpi/list_divider_mtrl_alpha.9.png
+++ b/core/res/res/drawable-ldpi/list_divider_mtrl_alpha.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-mdpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index 6674351..0000000
--- a/core/res/res/drawable-mdpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_dialog_alert_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_dialog_alert_mtrl_alpha.png
deleted file mode 100644
index 8a882f9..0000000
--- a/core/res/res/drawable-mdpi/ic_dialog_alert_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_go_search_api_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_go_search_api_mtrl_alpha.png
deleted file mode 100644
index b5f6176..0000000
--- a/core/res/res/drawable-mdpi/ic_go_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_copy_mtrl_am_alpha.png b/core/res/res/drawable-mdpi/ic_menu_copy_mtrl_am_alpha.png
deleted file mode 100644
index 3fae32d..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_copy_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_cut_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_menu_cut_mtrl_alpha.png
deleted file mode 100644
index 61ff631..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_cut_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_moreoverflow_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_menu_moreoverflow_mtrl_alpha.png
deleted file mode 100644
index 8415096..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_moreoverflow_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_paste_mtrl_am_alpha.png b/core/res/res/drawable-mdpi/ic_menu_paste_mtrl_am_alpha.png
deleted file mode 100644
index 112c268..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_paste_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_selectall_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_menu_selectall_mtrl_alpha.png
deleted file mode 100644
index 6414956..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_selectall_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_share_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_menu_share_mtrl_alpha.png
deleted file mode 100644
index e0d5ac4..0000000
--- a/core/res/res/drawable-mdpi/ic_menu_share_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_search_api_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_search_api_mtrl_alpha.png
deleted file mode 100644
index 0fb57b2..0000000
--- a/core/res/res/drawable-mdpi/ic_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_voice_search_api_mtrl_alpha.png b/core/res/res/drawable-mdpi/ic_voice_search_api_mtrl_alpha.png
deleted file mode 100644
index 3f1eee3..0000000
--- a/core/res/res/drawable-mdpi/ic_voice_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/list_divider_mtrl_alpha.9.png b/core/res/res/drawable-mdpi/list_divider_mtrl_alpha.9.png
index 77845df..070bdbf 100644
--- a/core/res/res/drawable-mdpi/list_divider_mtrl_alpha.9.png
+++ b/core/res/res/drawable-mdpi/list_divider_mtrl_alpha.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-xhdpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index 27bdcb7..0000000
--- a/core/res/res/drawable-xhdpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_dialog_alert_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_dialog_alert_mtrl_alpha.png
deleted file mode 100644
index 2229bf3..0000000
--- a/core/res/res/drawable-xhdpi/ic_dialog_alert_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_go_search_api_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_go_search_api_mtrl_alpha.png
deleted file mode 100644
index bd80981..0000000
--- a/core/res/res/drawable-xhdpi/ic_go_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_copy_mtrl_am_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_copy_mtrl_am_alpha.png
deleted file mode 100644
index b690d7c..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_copy_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_cut_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_cut_mtrl_alpha.png
deleted file mode 100644
index 10c2067..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_cut_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_moreoverflow_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_moreoverflow_mtrl_alpha.png
deleted file mode 100644
index f91b718..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_moreoverflow_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_paste_mtrl_am_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_paste_mtrl_am_alpha.png
deleted file mode 100644
index 4024627..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_paste_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_selectall_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_selectall_mtrl_alpha.png
deleted file mode 100644
index f7c0261..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_selectall_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_share_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_menu_share_mtrl_alpha.png
deleted file mode 100644
index 7accf52..0000000
--- a/core/res/res/drawable-xhdpi/ic_menu_share_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_search_api_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_search_api_mtrl_alpha.png
deleted file mode 100644
index 05cfab7..0000000
--- a/core/res/res/drawable-xhdpi/ic_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_voice_search_api_mtrl_alpha.png b/core/res/res/drawable-xhdpi/ic_voice_search_api_mtrl_alpha.png
deleted file mode 100644
index c1c23d0..0000000
--- a/core/res/res/drawable-xhdpi/ic_voice_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/list_divider_mtrl_alpha.9.png b/core/res/res/drawable-xhdpi/list_divider_mtrl_alpha.9.png
index 77845df..0d2836d 100644
--- a/core/res/res/drawable-xhdpi/list_divider_mtrl_alpha.9.png
+++ b/core/res/res/drawable-xhdpi/list_divider_mtrl_alpha.9.png
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-xxhdpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index c2d6a54..0000000
--- a/core/res/res/drawable-xxhdpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_dialog_alert_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_dialog_alert_mtrl_alpha.png
deleted file mode 100644
index 10e0756..0000000
--- a/core/res/res/drawable-xxhdpi/ic_dialog_alert_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_go_search_api_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_go_search_api_mtrl_alpha.png
deleted file mode 100644
index 8e1ab5b..0000000
--- a/core/res/res/drawable-xxhdpi/ic_go_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_copy_mtrl_am_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_copy_mtrl_am_alpha.png
deleted file mode 100644
index 7c3a58b..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_copy_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_cut_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_cut_mtrl_alpha.png
deleted file mode 100644
index 2200642..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_cut_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_moreoverflow_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_moreoverflow_mtrl_alpha.png
deleted file mode 100644
index ff1759b..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_moreoverflow_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_paste_mtrl_am_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_paste_mtrl_am_alpha.png
deleted file mode 100644
index 28c0ae0..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_paste_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_selectall_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_selectall_mtrl_alpha.png
deleted file mode 100644
index 6430d45..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_selectall_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_menu_share_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_menu_share_mtrl_alpha.png
deleted file mode 100644
index 66f7d16..0000000
--- a/core/res/res/drawable-xxhdpi/ic_menu_share_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_search_api_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_search_api_mtrl_alpha.png
deleted file mode 100644
index 6f60bd3..0000000
--- a/core/res/res/drawable-xxhdpi/ic_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_voice_search_api_mtrl_alpha.png b/core/res/res/drawable-xxhdpi/ic_voice_search_api_mtrl_alpha.png
deleted file mode 100644
index d95f1d0..0000000
--- a/core/res/res/drawable-xxhdpi/ic_voice_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/list_divider_mtrl_alpha.9.png b/core/res/res/drawable-xxhdpi/list_divider_mtrl_alpha.9.png
index 0fafd1a..b8ac46d 100644
--- a/core/res/res/drawable-xxhdpi/list_divider_mtrl_alpha.9.png
+++ b/core/res/res/drawable-xxhdpi/list_divider_mtrl_alpha.9.png
Binary files differ
diff --git a/core/res/res/drawable-xxxhdpi/ic_ab_back_mtrl_am_alpha.png b/core/res/res/drawable-xxxhdpi/ic_ab_back_mtrl_am_alpha.png
deleted file mode 100644
index 70c2040..0000000
--- a/core/res/res/drawable-xxxhdpi/ic_ab_back_mtrl_am_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xxxhdpi/ic_search_api_mtrl_alpha.png b/core/res/res/drawable-xxxhdpi/ic_search_api_mtrl_alpha.png
deleted file mode 100644
index c873e9b..0000000
--- a/core/res/res/drawable-xxxhdpi/ic_search_api_mtrl_alpha.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable/ic_ab_back_material.xml b/core/res/res/drawable/ic_ab_back_material.xml
index 37455d4..72d7981 100644
--- a/core/res/res/drawable/ic_ab_back_material.xml
+++ b/core/res/res/drawable/ic_ab_back_material.xml
@@ -1,20 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_ab_back_mtrl_am_alpha"
-    android:autoMirrored="true"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:autoMirrored="true"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M20.000000,11.000000L7.800000,11.000000l5.600000,-5.600000L12.000000,4.000000l-8.000000,8.000000l8.000000,8.000000l1.400000,-1.400000L7.800000,13.000000L20.000000,13.000000L20.000000,11.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_account_circle.xml b/core/res/res/drawable/ic_account_circle.xml
new file mode 100644
index 0000000..a8c5b8c
--- /dev/null
+++ b/core/res/res/drawable/ic_account_circle.xml
@@ -0,0 +1,24 @@
+<!--
+Copyright (C) 2014 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="48.0dp"
+        android:height="48.0dp"
+        android:viewportWidth="48.0"
+        android:viewportHeight="48.0">
+    <path
+        android:pathData="M24,0C10.8,0 0,10.8 0,24s10.8,24 24,24s24,-10.8 24,-24S37.200001,0 24,0zM24,7.2c3.96,0 7.2,3.24 7.2,7.2s-3.24,7.2 -7.2,7.2s-7.2,-3.24 -7.2,-7.2S20.040001,7.2 24,7.2zM24,41.279999c-6,0 -11.28,-3.12 -14.4,-7.68c0.12,-4.8 9.6,-7.44 14.4,-7.44s14.28,2.64 14.4,7.44C35.279999,38.16 30,41.279999 24,41.279999z"
+        android:fillColor="#FFFFFFFF"/>
+</vector>
diff --git a/core/res/res/drawable/ic_dialog_alert_material.xml b/core/res/res/drawable/ic_dialog_alert_material.xml
index 41e1ab1..3bb4d2c 100644
--- a/core/res/res/drawable/ic_dialog_alert_material.xml
+++ b/core/res/res/drawable/ic_dialog_alert_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_dialog_alert_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M1.000000,21.000000l22.000000,0.000000L12.000000,2.000000L1.000000,21.000000zM13.000000,18.000000l-2.000000,0.000000l0.000000,-2.000000l2.000000,0.000000L13.000000,18.000000zM13.000000,14.000000l-2.000000,0.000000l0.000000,-4.000000l2.000000,0.000000L13.000000,14.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_go_search_api_material.xml b/core/res/res/drawable/ic_go_search_api_material.xml
index 03f6cd5..21c7249 100644
--- a/core/res/res/drawable/ic_go_search_api_material.xml
+++ b/core/res/res/drawable/ic_go_search_api_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_go_search_api_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M10.000000,6.000000l-1.400000,1.400000 4.599999,4.600000 -4.599999,4.600000 1.400000,1.400000 6.000000,-6.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_lock_bugreport.xml b/core/res/res/drawable/ic_lock_bugreport.xml
index 8540eee..b0c32e0 100644
--- a/core/res/res/drawable/ic_lock_bugreport.xml
+++ b/core/res/res/drawable/ic_lock_bugreport.xml
@@ -17,9 +17,9 @@
         android:width="32dp"
         android:height="32dp"
         android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
     <path
-        android:fillColor="?attr/colorControlNormal"
+        android:fillColor="@color/white"
         android:pathData="M20.0,8.0l-2.8,0.0c-0.5,-0.8 -1.1,-1.5 -1.8,-2.0L17.0,4.4L15.6,3.0l-2.2,2.2C13.0,5.1 12.5,5.0 12.0,5.0s-1.0,0.1 -1.4,0.2L8.4,3.0L7.0,4.4L8.6,6.0C7.9,6.5 7.3,7.2 6.8,8.0L4.0,8.0l0.0,2.0l2.1,0.0C6.0,10.3 6.0,10.7 6.0,11.0l0.0,1.0L4.0,12.0l0.0,2.0l2.0,0.0l0.0,1.0c0.0,0.3 0.0,0.7 0.1,1.0L4.0,16.0l0.0,2.0l2.8,0.0c1.0,1.8 3.0,3.0 5.2,3.0s4.2,-1.2 5.2,-3.0L20.0,18.0l0.0,-2.0l-2.1,0.0c0.1,-0.3 0.1,-0.7 0.1,-1.0l0.0,-1.0l2.0,0.0l0.0,-2.0l-2.0,0.0l0.0,-1.0c0.0,-0.3 0.0,-0.7 -0.1,-1.0L20.0,10.0L20.0,8.0zM14.0,16.0l-4.0,0.0l0.0,-2.0l4.0,0.0L14.0,16.0zM14.0,12.0l-4.0,0.0l0.0,-2.0l4.0,0.0L14.0,12.0z"/>
 </vector>
diff --git a/core/res/res/drawable/ic_menu_copy_material.xml b/core/res/res/drawable/ic_menu_copy_material.xml
index 877b5ff..da3912b 100644
--- a/core/res/res/drawable/ic_menu_copy_material.xml
+++ b/core/res/res/drawable/ic_menu_copy_material.xml
@@ -1,20 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_copy_mtrl_am_alpha"
-    android:tint="?attr/colorControlNormal"
-    android:autoMirrored="true" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:autoMirrored="true"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M16.000000,1.000000L4.000000,1.000000C2.900000,1.000000 2.000000,1.900000 2.000000,3.000000l0.000000,14.000000l2.000000,0.000000L4.000000,3.000000l12.000000,0.000000L16.000000,1.000000zM19.000000,5.000000L8.000000,5.000000C6.900000,5.000000 6.000000,5.900000 6.000000,7.000000l0.000000,14.000000c0.000000,1.100000 0.900000,2.000000 2.000000,2.000000l11.000000,0.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000L21.000000,7.000000C21.000000,5.900000 20.100000,5.000000 19.000000,5.000000zM19.000000,21.000000L8.000000,21.000000L8.000000,7.000000l11.000000,0.000000L19.000000,21.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_menu_cut_material.xml b/core/res/res/drawable/ic_menu_cut_material.xml
index ff8d6e6..54db72a 100644
--- a/core/res/res/drawable/ic_menu_cut_material.xml
+++ b/core/res/res/drawable/ic_menu_cut_material.xml
@@ -1,19 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_cut_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:autoMirrored="true"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M10.000000,6.000000c0.000000,-2.200000 -1.800000,-4.000000 -4.000000,-4.000000S2.000000,3.800000 2.000000,6.000000c0.000000,2.200000 1.800000,4.000000 4.000000,4.000000c0.600000,0.000000 1.100000,-0.100000 1.600000,-0.400000L10.000000,12.000000l-2.400000,2.400000C7.100000,14.100000 6.600000,14.000000 6.000000,14.000000c-2.200000,0.000000 -4.000000,1.800000 -4.000000,4.000000c0.000000,2.200000 1.800000,4.000000 4.000000,4.000000s4.000000,-1.800000 4.000000,-4.000000c0.000000,-0.600000 -0.100000,-1.100000 -0.400000,-1.600000L12.000000,14.000000l7.000000,7.000000l4.000000,0.000000L9.600000,7.600000C9.900000,7.100000 10.000000,6.600000 10.000000,6.000000zM6.000000,8.000000C4.900000,8.000000 4.000000,7.100000 4.000000,6.000000s0.900000,-2.000000 2.000000,-2.000000c1.100000,0.000000 2.000000,0.900000 2.000000,2.000000S7.100000,8.000000 6.000000,8.000000zM6.000000,20.000000c-1.100000,0.000000 -2.000000,-0.900000 -2.000000,-2.000000s0.900000,-2.000000 2.000000,-2.000000c1.100000,0.000000 2.000000,0.900000 2.000000,2.000000S7.100000,20.000000 6.000000,20.000000zM12.000000,11.500000c0.300000,0.000000 0.500000,0.200000 0.500000,0.500000c0.000000,0.300000 -0.200000,0.500000 -0.500000,0.500000c-0.300000,0.000000 -0.500000,-0.200000 -0.500000,-0.500000C11.500000,11.700000 11.700000,11.500000 12.000000,11.500000zM23.000000,3.000000l-4.000000,0.000000l-6.000000,6.000000l2.000000,2.000000L23.000000,3.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_menu_moreoverflow_material.xml b/core/res/res/drawable/ic_menu_moreoverflow_material.xml
index 16d4f0c..c128570 100644
--- a/core/res/res/drawable/ic_menu_moreoverflow_material.xml
+++ b/core/res/res/drawable/ic_menu_moreoverflow_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_moreoverflow_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M12.000000,8.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000s-0.900000,-2.000000 -2.000000,-2.000000c-1.100000,0.000000 -2.000000,0.900000 -2.000000,2.000000S10.900000,8.000000 12.000000,8.000000zM12.000000,10.000000c-1.100000,0.000000 -2.000000,0.900000 -2.000000,2.000000s0.900000,2.000000 2.000000,2.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000S13.100000,10.000000 12.000000,10.000000zM12.000000,16.000000c-1.100000,0.000000 -2.000000,0.900000 -2.000000,2.000000s0.900000,2.000000 2.000000,2.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000S13.100000,16.000000 12.000000,16.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_menu_paste_material.xml b/core/res/res/drawable/ic_menu_paste_material.xml
index f7bbbf9..5f847cb 100644
--- a/core/res/res/drawable/ic_menu_paste_material.xml
+++ b/core/res/res/drawable/ic_menu_paste_material.xml
@@ -1,20 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_paste_mtrl_am_alpha"
-    android:tint="?attr/colorControlNormal"
-    android:autoMirrored="true" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:autoMirrored="true"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M19.000000,2.000000l-4.200000,0.000000c-0.400000,-1.200000 -1.500000,-2.000000 -2.800000,-2.000000c-1.300000,0.000000 -2.400000,0.800000 -2.800000,2.000000L5.000000,2.000000C3.900000,2.000000 3.000000,2.900000 3.000000,4.000000l0.000000,16.000000c0.000000,1.100000 0.900000,2.000000 2.000000,2.000000l14.000000,0.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000L21.000000,4.000000C21.000000,2.900000 20.100000,2.000000 19.000000,2.000000zM12.000000,2.000000c0.600000,0.000000 1.000000,0.400000 1.000000,1.000000s-0.400000,1.000000 -1.000000,1.000000c-0.600000,0.000000 -1.000000,-0.400000 -1.000000,-1.000000S11.400000,2.000000 12.000000,2.000000zM19.000000,20.000000L5.000000,20.000000L5.000000,4.000000l2.000000,0.000000l0.000000,3.000000l10.000000,0.000000L17.000000,4.000000l2.000000,0.000000L19.000000,20.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_menu_selectall_material.xml b/core/res/res/drawable/ic_menu_selectall_material.xml
index a431dd5..11e63fd 100644
--- a/core/res/res/drawable/ic_menu_selectall_material.xml
+++ b/core/res/res/drawable/ic_menu_selectall_material.xml
@@ -1,19 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_selectall_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:autoMirrored="true"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M3.000000,5.000000l2.000000,0.000000L5.000000,3.000000C3.900000,3.000000 3.000000,3.900000 3.000000,5.000000zM3.000000,13.000000l2.000000,0.000000l0.000000,-2.000000L3.000000,11.000000L3.000000,13.000000zM7.000000,21.000000l2.000000,0.000000l0.000000,-2.000000L7.000000,19.000000L7.000000,21.000000zM3.000000,9.000000l2.000000,0.000000L5.000000,7.000000L3.000000,7.000000L3.000000,9.000000zM13.000000,3.000000l-2.000000,0.000000l0.000000,2.000000l2.000000,0.000000L13.000000,3.000000zM19.000000,3.000000l0.000000,2.000000l2.000000,0.000000C21.000000,3.900000 20.100000,3.000000 19.000000,3.000000zM5.000000,21.000000l0.000000,-2.000000L3.000000,19.000000C3.000000,20.100000 3.900000,21.000000 5.000000,21.000000zM3.000000,17.000000l2.000000,0.000000l0.000000,-2.000000L3.000000,15.000000L3.000000,17.000000zM9.000000,3.000000L7.000000,3.000000l0.000000,2.000000l2.000000,0.000000L9.000000,3.000000zM11.000000,21.000000l2.000000,0.000000l0.000000,-2.000000l-2.000000,0.000000L11.000000,21.000000zM19.000000,13.000000l2.000000,0.000000l0.000000,-2.000000l-2.000000,0.000000L19.000000,13.000000zM19.000000,21.000000c1.100000,0.000000 2.000000,-0.900000 2.000000,-2.000000l-2.000000,0.000000L19.000000,21.000000zM19.000000,9.000000l2.000000,0.000000L21.000000,7.000000l-2.000000,0.000000L19.000000,9.000000zM19.000000,17.000000l2.000000,0.000000l0.000000,-2.000000l-2.000000,0.000000L19.000000,17.000000zM15.000000,21.000000l2.000000,0.000000l0.000000,-2.000000l-2.000000,0.000000L15.000000,21.000000zM15.000000,5.000000l2.000000,0.000000L17.000000,3.000000l-2.000000,0.000000L15.000000,5.000000zM7.000000,17.000000l10.000000,0.000000L17.000000,7.000000L7.000000,7.000000L7.000000,17.000000zM9.000000,9.000000l6.000000,0.000000l0.000000,6.000000L9.000000,15.000000L9.000000,9.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_menu_share_material.xml b/core/res/res/drawable/ic_menu_share_material.xml
index d9153af..b7c238f 100644
--- a/core/res/res/drawable/ic_menu_share_material.xml
+++ b/core/res/res/drawable/ic_menu_share_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_menu_share_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M18.000000,16.100000c-0.800000,0.000000 -1.500000,0.300000 -2.000000,0.800000l-7.100000,-4.200000C9.000000,12.500000 9.000000,12.200000 9.000000,12.000000s0.000000,-0.500000 -0.100000,-0.700000L16.000000,7.200000C16.500000,7.700000 17.200001,8.000000 18.000000,8.000000c1.700000,0.000000 3.000000,-1.300000 3.000000,-3.000000s-1.300000,-3.000000 -3.000000,-3.000000s-3.000000,1.300000 -3.000000,3.000000c0.000000,0.200000 0.000000,0.500000 0.100000,0.700000L8.000000,9.800000C7.500000,9.300000 6.800000,9.000000 6.000000,9.000000c-1.700000,0.000000 -2.900000,1.200000 -2.900000,2.900000s1.300000,3.000000 3.000000,3.000000c0.800000,0.000000 1.500000,-0.300000 2.000000,-0.800000l7.100000,4.200000c-0.100000,0.300000 -0.100000,0.500000 -0.100000,0.700000c0.000000,1.600000 1.300000,2.900000 2.900000,2.900000s2.900000,-1.300000 2.900000,-2.900000S19.600000,16.100000 18.000000,16.100000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_search_api_material.xml b/core/res/res/drawable/ic_search_api_material.xml
index bc18398..ac1aae3 100644
--- a/core/res/res/drawable/ic_search_api_material.xml
+++ b/core/res/res/drawable/ic_search_api_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_search_api_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M15.500000,14.000000l-0.800000,0.000000l-0.300000,-0.300000c1.000000,-1.100000 1.600000,-2.600000 1.600000,-4.200000C16.000000,5.900000 13.100000,3.000000 9.500000,3.000000C5.900000,3.000000 3.000000,5.900000 3.000000,9.500000S5.900000,16.000000 9.500000,16.000000c1.600000,0.000000 3.100000,-0.600000 4.200000,-1.600000l0.300000,0.300000l0.000000,0.800000l5.000000,5.000000l1.500000,-1.500000L15.500000,14.000000zM9.500000,14.000000C7.000000,14.000000 5.000000,12.000000 5.000000,9.500000S7.000000,5.000000 9.500000,5.000000C12.000000,5.000000 14.000000,7.000000 14.000000,9.500000S12.000000,14.000000 9.500000,14.000000z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/ic_voice_search_api_material.xml b/core/res/res/drawable/ic_voice_search_api_material.xml
index 05488fb..8c1e803 100644
--- a/core/res/res/drawable/ic_voice_search_api_material.xml
+++ b/core/res/res/drawable/ic_voice_search_api_material.xml
@@ -1,19 +1,25 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+Copyright (C) 2014 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
+   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
+         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.
+    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.
 -->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-    android:src="@drawable/ic_voice_search_api_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="24dp"
+        android:height="24dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0"
+        android:tint="?attr/colorControlNormal">
+    <path
+        android:pathData="M12.000000,14.000000c1.700000,0.000000 3.000000,-1.300000 3.000000,-3.000000l0.000000,-6.000000c0.000000,-1.700000 -1.300000,-3.000000 -3.000000,-3.000000c-1.700000,0.000000 -3.000000,1.300000 -3.000000,3.000000l0.000000,6.000000C9.000000,12.700000 10.300000,14.000000 12.000000,14.000000zM17.299999,11.000000c0.000000,3.000000 -2.500000,5.100000 -5.300000,5.100000c-2.800000,0.000000 -5.300000,-2.100000 -5.300000,-5.100000L5.000000,11.000000c0.000000,3.400000 2.700000,6.200000 6.000000,6.700000L11.000000,21.000000l2.000000,0.000000l0.000000,-3.300000c3.300000,-0.500000 6.000000,-3.300000 6.000000,-6.700000L17.299999,11.000001z"
+        android:fillColor="@color/white"/>
+</vector>
diff --git a/core/res/res/drawable/list_divider_material.xml b/core/res/res/drawable/list_divider_material.xml
index bf24933..7ff212a 100644
--- a/core/res/res/drawable/list_divider_material.xml
+++ b/core/res/res/drawable/list_divider_material.xml
@@ -16,4 +16,5 @@
 
 <nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
     android:src="@drawable/list_divider_mtrl_alpha"
-    android:tint="?attr/colorControlNormal" />
+    android:tint="?attr/colorForeground"
+    android:alpha="0.16" />
diff --git a/core/res/res/layout/action_mode_close_item_material.xml b/core/res/res/layout/action_mode_close_item_material.xml
index 8eb780b..89a1797 100644
--- a/core/res/res/layout/action_mode_close_item_material.xml
+++ b/core/res/res/layout/action_mode_close_item_material.xml
@@ -20,6 +20,7 @@
         android:clickable="true"
         android:paddingStart="8dip"
         android:src="?android:attr/actionModeCloseDrawable"
+        android:contentDescription="@string/action_mode_done"
         style="?android:attr/actionModeCloseButtonStyle"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
diff --git a/core/res/res/layout/alert_dialog_material.xml b/core/res/res/layout/alert_dialog_material.xml
index be89e41..e5ef629 100644
--- a/core/res/res/layout/alert_dialog_material.xml
+++ b/core/res/res/layout/alert_dialog_material.xml
@@ -56,8 +56,7 @@
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:orientation="vertical"
-        android:minHeight="64dp"
-        android:paddingTop="@dimen/alert_dialog_padding_top_material">
+        android:minHeight="64dp">
         <ScrollView android:id="@+id/scrollView"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
@@ -67,6 +66,7 @@
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:paddingStart="@dimen/alert_dialog_padding_material"
+                android:paddingTop="@dimen/alert_dialog_padding_top_material"
                 android:paddingEnd="@dimen/alert_dialog_padding_material" />
         </ScrollView>
     </LinearLayout>
diff --git a/core/res/res/values-mcc234-mnc20/config.xml b/core/res/res/values-mcc234-mnc20/config.xml
index 1ed53dc..619e517 100644
--- a/core/res/res/values-mcc234-mnc20/config.xml
+++ b/core/res/res/values-mcc234-mnc20/config.xml
@@ -21,6 +21,22 @@
      for different hardware and product builds. -->
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
 
+    <!-- Array of ConnectivityManager.TYPE_xxxx values allowable for tethering -->
+    <!-- Common options are [1, 4] for TYPE_WIFI and TYPE_MOBILE_DUN or
+    <!== [0,1,5,7] for TYPE_MOBILE, TYPE_WIFI, TYPE_MOBILE_HIPRI and TYPE_BLUETOOTH -->
+    <integer-array translatable="false" name="config_tether_upstream_types">
+        <item>1</item>
+        <item>4</item>
+        <item>7</item>
+        <item>9</item>
+    </integer-array>
+
+    <!-- String containing the apn value for tethering.  May be overriden by secure settings
+         TETHER_DUN_APN.  Value is a comma separated series of strings:
+         "name,apn,proxy,port,username,password,server,mmsc,mmsproxy,mmsport,mcc,mnc,auth,type"
+         note that empty fields can be ommitted: "name,apn,,,,,,,,,310,260,,DUN" -->
+    <string translatable="false" name="config_tether_apndata">3hotspot,3hotspot,,,,,,,,,234,20,0,DUN</string>
+
     <!-- Configure mobile network MTU. Carrier specific value is set here.
     -->
     <integer name="config_mobile_mtu">1440</integer>
diff --git a/core/res/res/values-mcc235-mnc94/config.xml b/core/res/res/values-mcc235-mnc94/config.xml
index d602c9f..723af3d 100644
--- a/core/res/res/values-mcc235-mnc94/config.xml
+++ b/core/res/res/values-mcc235-mnc94/config.xml
@@ -21,6 +21,22 @@
      for different hardware and product builds. -->
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
 
+    <!-- Array of ConnectivityManager.TYPE_xxxx values allowable for tethering -->
+    <!-- Common options are [1, 4] for TYPE_WIFI and TYPE_MOBILE_DUN or
+    <!== [0,1,5,7] for TYPE_MOBILE, TYPE_WIFI, TYPE_MOBILE_HIPRI and TYPE_BLUETOOTH -->
+    <integer-array translatable="false" name="config_tether_upstream_types">
+        <item>1</item>
+        <item>4</item>
+        <item>7</item>
+        <item>9</item>
+    </integer-array>
+
+    <!-- String containing the apn value for tethering.  May be overriden by secure settings
+         TETHER_DUN_APN.  Value is a comma separated series of strings:
+         "name,apn,proxy,port,username,password,server,mmsc,mmsproxy,mmsport,mcc,mnc,auth,type"
+         note that empty fields can be ommitted: "name,apn,,,,,,,,,310,260,,DUN" -->
+    <string translatable="false" name="config_tether_apndata">3hotspot,3hotspot,,,,,,,,,235,94,0,DUN</string>
+
     <!-- Configure mobile network MTU. Carrier specific value is set here.
     -->
     <integer name="config_mobile_mtu">1440</integer>
diff --git a/core/res/res/values-mcc425-mnc01/config.xml b/core/res/res/values-mcc425-mnc01/config.xml
deleted file mode 100644
index f4854da..0000000
--- a/core/res/res/values-mcc425-mnc01/config.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 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 my 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
-     for different hardware and product builds. -->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-
-    <!-- Array of ConnectivityManager.TYPE_xxxx values allowable for tethering -->
-    <!-- Common options are [1, 4] for TYPE_WIFI and TYPE_MOBILE_DUN or
-    <!== [0,1,5,7] for TYPE_MOBILE, TYPE_WIFI, TYPE_MOBILE_HIPRI and TYPE_BLUETOOTH -->
-    <integer-array translatable="false" name="config_tether_upstream_types">
-      <item>1</item>
-      <item>4</item>
-      <item>7</item>
-      <item>9</item>
-    </integer-array>
-
-    <!-- String containing the apn value for tethering.  May be overriden by secure settings
-         TETHER_DUN_APN.  Value is a comma separated series of strings:
-         "name,apn,proxy,port,username,password,server,mmsc,mmsproxy,mmsport,mcc,mnc,auth,type"
-         note that empty fields can be ommitted: "name,apn,,,,,,,,,310,260,,DUN" -->
-    <string translatable="false" name="config_tether_apndata">DUN,modem.orange.net.il,,,,,,,,,425,01,,DUN</string>
-
-</resources>
diff --git a/core/res/res/values-sw600dp-land/dimens_material.xml b/core/res/res/values-sw600dp/dimens_material.xml
similarity index 81%
rename from core/res/res/values-sw600dp-land/dimens_material.xml
rename to core/res/res/values-sw600dp/dimens_material.xml
index f8f16e2..e0aac38 100644
--- a/core/res/res/values-sw600dp-land/dimens_material.xml
+++ b/core/res/res/values-sw600dp/dimens_material.xml
@@ -19,5 +19,9 @@
     <dimen name="text_size_title_material_toolbar">@dimen/text_size_title_material</dimen>
     <!-- Use the default subtitle sizes on tablets. -->
     <dimen name="text_size_subtitle_material_toolbar">@dimen/text_size_subhead_material</dimen>
+    <!-- Default height of an action bar. -->
+    <dimen name="action_bar_default_height_material">64dp</dimen>
+    <!-- Default padding of an action bar. -->
+    <dimen name="action_bar_default_padding_material">4dp</dimen>
 
 </resources>
diff --git a/core/res/res/values-sw720dp/styles.xml b/core/res/res/values-sw720dp/styles.xml
index fee1c24..94ec0a6 100644
--- a/core/res/res/values-sw720dp/styles.xml
+++ b/core/res/res/values-sw720dp/styles.xml
@@ -16,10 +16,9 @@
 
 <resources>
     <style name="PreferencePanel">
-        <item name="android:layout_marginStart">@dimen/preference_screen_side_margin</item>
-        <item name="android:layout_marginEnd">@dimen/preference_screen_side_margin</item>
-        <item name="android:layout_marginTop">@dimen/preference_screen_top_margin</item>
-        <item name="android:layout_marginBottom">@dimen/preference_screen_bottom_margin</item>
-        <item name="android:background">?attr/detailsElementBackground</item>
+        <item name="layout_marginStart">@dimen/preference_screen_side_margin</item>
+        <item name="layout_marginEnd">@dimen/preference_screen_side_margin</item>
+        <item name="layout_marginTop">@dimen/preference_screen_top_margin</item>
+        <item name="layout_marginBottom">@dimen/preference_screen_bottom_margin</item>
     </style>
 </resources>
diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml
index f843d1f..a8b5d6d 100644
--- a/core/res/res/values/arrays.xml
+++ b/core/res/res/values/arrays.xml
@@ -397,30 +397,30 @@
        <item>@drawable/expander_open_mtrl_alpha</item>
        <item>@drawable/fastscroll_thumb_mtrl_alpha</item>
        <item>@drawable/fastscroll_track_mtrl_alpha</item>
-       <item>@drawable/ic_ab_back_mtrl_am_alpha</item>
+       <item>@drawable/ic_ab_back_material</item>
        <item>@drawable/ic_cab_done_mtrl_alpha</item>
        <item>@drawable/ic_clear_mtrl_alpha</item>
        <item>@drawable/ic_commit_search_api_mtrl_alpha</item>
-       <item>@drawable/ic_dialog_alert_mtrl_alpha</item>
+       <item>@drawable/ic_dialog_alert_material</item>
        <item>@drawable/ic_find_next_mtrl_alpha</item>
        <item>@drawable/ic_find_previous_mtrl_alpha</item>
-       <item>@drawable/ic_go_search_api_mtrl_alpha</item>
+       <item>@drawable/ic_go_search_api_material</item>
        <item>@drawable/ic_media_route_disabled_mtrl_alpha</item>
        <item>@drawable/ic_media_route_off_mtrl_alpha</item>
        <item>@drawable/ic_media_route_on_0_mtrl_alpha</item>
        <item>@drawable/ic_media_route_on_1_mtrl_alpha</item>
        <item>@drawable/ic_media_route_on_2_mtrl_alpha</item>
        <item>@drawable/ic_media_route_on_mtrl_alpha</item>
-       <item>@drawable/ic_menu_copy_mtrl_am_alpha</item>
-       <item>@drawable/ic_menu_cut_mtrl_alpha</item>
+       <item>@drawable/ic_menu_copy_material</item>
+       <item>@drawable/ic_menu_cut_material</item>
        <item>@drawable/ic_menu_find_mtrl_alpha</item>
-       <item>@drawable/ic_menu_moreoverflow_mtrl_alpha</item>
-       <item>@drawable/ic_menu_paste_mtrl_am_alpha</item>
+       <item>@drawable/ic_menu_moreoverflow_material</item>
+       <item>@drawable/ic_menu_paste_material</item>
        <item>@drawable/ic_menu_search_mtrl_alpha</item>
-       <item>@drawable/ic_menu_selectall_mtrl_alpha</item>
-       <item>@drawable/ic_menu_share_mtrl_alpha</item>
-       <item>@drawable/ic_search_api_mtrl_alpha</item>
-       <item>@drawable/ic_voice_search_api_mtrl_alpha</item>
+       <item>@drawable/ic_menu_selectall_material</item>
+       <item>@drawable/ic_menu_share_material</item>
+       <item>@drawable/ic_search_api_material</item>
+       <item>@drawable/ic_voice_search_api_material</item>
        <item>@drawable/list_divider_mtrl_alpha</item>
        <item>@drawable/list_section_divider_mtrl_alpha</item>
        <item>@drawable/popup_background_mtrl_mult</item>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 438d1fb..0e597d0 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -5271,11 +5271,16 @@
         <attr name="viewportWidth" format="float"/>
         <!-- The height of the canvas the drawing is on. -->
         <attr name="viewportHeight" format="float"/>
+        <!-- The name of this vector drawable -->
+        <attr name="name" />
+        <!-- The opacity of the whole vector drawable, as a value between 0
+             (completely transparent) and 1 (completely opaque). -->
+        <attr name="alpha" />
     </declare-styleable>
 
     <!-- Defines the group used in VectorDrawables. -->
     <declare-styleable name="VectorDrawableGroup">
-        <!-- The Name of this group -->
+        <!-- The name of this group -->
         <attr name="name" />
         <!-- The amount to rotate the group -->
         <attr name="rotation" />
@@ -5295,7 +5300,7 @@
 
     <!-- Defines the path used in VectorDrawables. -->
     <declare-styleable name="VectorDrawablePath">
-        <!-- The Name of this path -->
+        <!-- The name of this path -->
         <attr name="name" />
         <!-- The width a path stroke -->
         <attr name="strokeWidth" format="float" />
diff --git a/core/res/res/values/colors.xml b/core/res/res/values/colors.xml
index c42683b..5a7e168 100644
--- a/core/res/res/values/colors.xml
+++ b/core/res/res/values/colors.xml
@@ -147,5 +147,16 @@
     <color name="system_notification_accent_color">#ff607D8B</color>
     <color name="battery_saver_mode_color">#fff4511e</color><!-- deep orange 600 -->
 
+    <!-- Default user icon colors -->
+    <color name="user_icon_1">#ffe91e63</color><!-- pink 500 -->
+    <color name="user_icon_2">#ff3f51b5</color><!-- indigo 500 -->
+    <color name="user_icon_3">#ff4285f4</color><!-- blue 500 -->
+    <color name="user_icon_4">#ff00bcd4</color><!-- teal 500 -->
+    <color name="user_icon_5">#ff0f9d58</color><!-- green 500 -->
+    <color name="user_icon_6">#ff8bc34a</color><!-- light green 500 -->
+    <color name="user_icon_7">#ffff9800</color><!-- orange 500 -->
+    <color name="user_icon_8">#ffff5722</color><!-- deep orange 500 -->
+    <color name="user_icon_default_gray">#ff9e9e9e</color><!-- gray 500 -->
+    <color name="user_icon_default_white">#ffffffff</color><!-- white -->
 </resources>
 
diff --git a/core/res/res/values/dimens_material.xml b/core/res/res/values/dimens_material.xml
index 3e64f30..2b49ba2 100644
--- a/core/res/res/values/dimens_material.xml
+++ b/core/res/res/values/dimens_material.xml
@@ -31,6 +31,7 @@
     <!-- Bottom margin for action bar subtitles -->
     <dimen name="action_bar_subtitle_bottom_margin_material">5dp</dimen>
 
+    <dimen name="action_button_min_width_overflow_material">36dp</dimen>
     <dimen name="action_button_min_width_material">48dp</dimen>
     <dimen name="action_button_min_height_material">48dp</dimen>
 
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 7e3a6fa..99918a0 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2562,6 +2562,9 @@
 
   <public type="style" name="Widget.Material.SearchView" />
   <public type="style" name="Widget.Material.Light.SearchView" />
+  <public type="style" name="Widget.Material.TimePicker" />
+  <public type="style" name="Widget.Material.Light.TimePicker" />
+  <public type="style" name="Widget.Material.Light.DatePicker" />
 
   <public-padding type="string" name="l_resource_pad" end="0x01040030" />
 
diff --git a/core/res/res/values/styles_material.xml b/core/res/res/values/styles_material.xml
index 836f886..e6e5cbb 100644
--- a/core/res/res/values/styles_material.xml
+++ b/core/res/res/values/styles_material.xml
@@ -839,8 +839,8 @@
         <item name="gravity">center</item>
         <item name="scaleType">center</item>
         <item name="maxLines">2</item>
-        <item name="paddingStart">0dp</item>
-        <item name="paddingEnd">0dp</item>
+        <item name="paddingStart">12dp</item>
+        <item name="paddingEnd">12dp</item>
     </style>
 
     <style name="Widget.Material.ActionButton.CloseMode">
@@ -851,6 +851,9 @@
         <item name="src">@drawable/ic_menu_moreoverflow_material</item>
         <item name="background">?attr/actionBarItemBackground</item>
         <item name="contentDescription">@string/action_menu_overflow_description</item>
+        <item name="minWidth">@dimen/action_button_min_width_overflow_material</item>
+        <item name="minHeight">@dimen/action_button_min_height_material</item>
+        <item name="paddingStart">0dp</item>
         <item name="paddingEnd">12dp</item>
     </style>
 
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 7fc522f..117e235 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1170,6 +1170,18 @@
   <java-symbol type="drawable" name="sim_dark_orange" />
   <java-symbol type="drawable" name="sim_dark_purple" />
 
+  <java-symbol type="drawable" name="ic_account_circle" />
+  <java-symbol type="color" name="user_icon_1" />
+  <java-symbol type="color" name="user_icon_2" />
+  <java-symbol type="color" name="user_icon_3" />
+  <java-symbol type="color" name="user_icon_4" />
+  <java-symbol type="color" name="user_icon_5" />
+  <java-symbol type="color" name="user_icon_6" />
+  <java-symbol type="color" name="user_icon_7" />
+  <java-symbol type="color" name="user_icon_8" />
+  <java-symbol type="color" name="user_icon_default_gray" />
+  <java-symbol type="color" name="user_icon_default_white" />
+
   <java-symbol type="layout" name="action_bar_home" />
   <java-symbol type="layout" name="action_bar_title_item" />
   <java-symbol type="layout" name="action_menu_item_layout" />
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodTest.java b/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
index 30eb939..cb85fc5 100644
--- a/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
+++ b/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
@@ -45,177 +45,99 @@
     private static final Locale LOCALE_EN_GB = new Locale("en", "GB");
     private static final Locale LOCALE_EN_IN = new Locale("en", "IN");
     private static final Locale LOCALE_HI = new Locale("hi");
+    private static final Locale LOCALE_JA_JP = new Locale("ja", "JP");
+    private static final String SUBTYPE_MODE_KEYBOARD = "keyboard";
+    private static final String SUBTYPE_MODE_VOICE = "voice";
 
     @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(createDefaultDummyLatinKeyboardIme());
-        imis.add(createNonDefaultDummyJaJPKeyboardIme());
-        imis.add(createNonDefaultDummyJaJPKeyboardImeWithoutSubtypes());
-        imis.add(createDefaultDummyHinglishKeyboardIme());
-
-        // locale: en_US, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnUs =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_US);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
+    public void testVoiceImes() throws Exception {
+        // locale: en_US
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_EN_US, !IS_SYSTEM_READY,
                 "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnUs));
-
-        // locale: en_US, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnUs =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_US);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnUs));
-
-        // locale: en_GB, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnGB =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_GB);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
+                "DummyDefaultEnKeyboardIme", "DummyDefaultAutoVoiceIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_EN_US, !IS_SYSTEM_READY,
                 "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnGB));
-
-        // locale: en_GB, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnGB =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_GB);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnGB));
-
-        // locale: en_IN, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnIN =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_IN);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
+                "DummyDefaultEnKeyboardIme");
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_EN_US, IS_SYSTEM_READY,
+                "DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_EN_US, IS_SYSTEM_READY,
                 "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnIN));
+                "DummyDefaultEnKeyboardIme");
 
-        // locale: en_IN, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnIN =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_IN);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnIN));
-
-        // locale: hi, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleHi =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_HI);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
+        // locale: en_GB
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_EN_GB, !IS_SYSTEM_READY,
                 "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleHi));
-
-        // locale: hi, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleHi =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_HI);
-        assertEquals(toSet("DummyDefaultAutoVoiceIme", "DummyDefaultEnKeyboardIme",
+                "DummyDefaultEnKeyboardIme", "DummyDefaultAutoVoiceIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_EN_GB, !IS_SYSTEM_READY,
                 "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleHi));
+                "DummyDefaultEnKeyboardIme");
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_EN_GB, IS_SYSTEM_READY,
+                "DummyDefaultEnKeyboardIme", "DummyDefaultAutoVoiceIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_EN_GB, IS_SYSTEM_READY,
+                "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
+                "DummyDefaultEnKeyboardIme");
+
+        // locale: ja_JP
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_JA_JP, !IS_SYSTEM_READY,
+                "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
+                "DummyDefaultEnKeyboardIme", "DummyDefaultAutoVoiceIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_JA_JP, !IS_SYSTEM_READY,
+                "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
+                "DummyDefaultEnKeyboardIme");
+        assertDefaultEnabledImes(getImesWithDefaultVoiceIme(), LOCALE_JA_JP, IS_SYSTEM_READY,
+                "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
+                "DummyDefaultEnKeyboardIme", "DummyDefaultAutoVoiceIme");
+        assertDefaultEnabledImes(getImesWithoutDefaultVoiceIme(), LOCALE_JA_JP, IS_SYSTEM_READY,
+                "DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
+                "DummyDefaultEnKeyboardIme");
     }
 
     @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(createDefaultDummyLatinKeyboardIme());
-        imis.add(createNonDefaultDummyJaJPKeyboardIme());
-        imis.add(createNonDefaultDummyJaJPKeyboardImeWithoutSubtypes());
-        imis.add(createDefaultDummyHinglishKeyboardIme());
+    public void testKeyboardImes() throws Exception {
+        // locale: en_US
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_US, !IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_US, IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
 
-        // locale: en_US, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnUs =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_US);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnUs));
+        // locale: en_GB
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_GB, !IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_GB, IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
 
-        // locale: en_US, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnUs =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_US);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnUs));
+        // locale: en_IN
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_IN, !IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_EN_IN, IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
 
-        // locale: en_GB, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnGB =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_GB);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnGB));
+        // locale: hi
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_HI, !IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_HI, IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
 
-        // locale: en_GB, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnGB =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_GB);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnGB));
-
-        // locale: en_IN, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleEnIN =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_EN_IN);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleEnIN));
-
-        // locale: en_IN, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleEnIN =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_EN_IN);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleEnIN));
-
-        // locale: hi, system: not ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemNotReadyLocaleHi =
-                callGetDefaultEnabledImesUnderWithLocale(context, !IS_SYSTEM_READY, imis,
-                        LOCALE_HI);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemNotReadyLocaleHi));
-
-        // locale: hi, system: ready
-        final ArrayList<InputMethodInfo> enabledImisForSystemReadyLocaleHi =
-                callGetDefaultEnabledImesUnderWithLocale(context, IS_SYSTEM_READY, imis,
-                        LOCALE_HI);
-        assertEquals(toSet("DummyNonDefaultAutoVoiceIme0", "DummyNonDefaultAutoVoiceIme1",
-                "DummyDefaultEnKeyboardIme", "DummyDefaultHinglishKeyboardIme"),
-                getPackageNames(enabledImisForSystemReadyLocaleHi));
+        // locale: ja_JP
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_JA_JP, !IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi");
+        assertDefaultEnabledImes(getSamplePreinstalledImes(), LOCALE_JA_JP, IS_SYSTEM_READY,
+                "com.android.apps.inputmethod.voice", "com.android.apps.inputmethod.latin",
+                "com.android.apps.inputmethod.hindi", "com.android.apps.inputmethod.japanese");
     }
 
     @SmallTest
     public void testParcelable() throws Exception {
-        final ArrayList<InputMethodInfo> originalList = new ArrayList<InputMethodInfo>();
-        originalList.add(createNonDefaultAutoDummyVoiceIme0());
-        originalList.add(createNonDefaultAutoDummyVoiceIme1());
-        originalList.add(createNonDefaultDummyVoiceIme2());
-        originalList.add(createDefaultDummyLatinKeyboardIme());
-        originalList.add(createNonDefaultDummyJaJPKeyboardIme());
-        originalList.add(createNonDefaultDummyJaJPKeyboardImeWithoutSubtypes());
-
+        final ArrayList<InputMethodInfo> originalList = getSamplePreinstalledImes();
         final List<InputMethodInfo> clonedList = cloneViaParcel(originalList);
         assertNotNull(clonedList);
         final List<InputMethodInfo> clonedClonedList = cloneViaParcel(clonedList);
@@ -230,6 +152,14 @@
         }
     }
 
+    private void assertDefaultEnabledImes(final ArrayList<InputMethodInfo> preinstalledImes,
+            final Locale systemLocale, final boolean isSystemReady, String... imeNames) {
+        final Context context = getInstrumentation().getTargetContext();
+        assertEquals(new HashSet<String>(Arrays.asList(imeNames)),
+                getPackageNames(callGetDefaultEnabledImesUnderWithLocale(context,
+                        isSystemReady, preinstalledImes, systemLocale)));
+    }
+
     private static List<InputMethodInfo> cloneViaParcel(final List<InputMethodInfo> list) {
         Parcel p = null;
         try {
@@ -256,11 +186,6 @@
         }
     }
 
-    @SafeVarargs
-    private static <T> HashSet<T> toSet(final T... xs) {
-        return new HashSet<T>(Arrays.asList(xs));
-    }
-
     private HashSet<String> getPackageNames(final ArrayList<InputMethodInfo> imis) {
         final HashSet<String> packageNames = new HashSet<>();
         for (final InputMethodInfo imi : imis) {
@@ -315,83 +240,132 @@
                 .build();
     }
 
-    private static InputMethodInfo createDefaultAutoDummyVoiceIme() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyDefaultAutoVoiceIme", "dummy.voice0",
-                "DummyVoice0", IS_AUX, IS_DEFAULT, subtypes);
+    private static ArrayList<InputMethodInfo> getImesWithDefaultVoiceIme() {
+        ArrayList<InputMethodInfo> preinstalledImes = new ArrayList<>();
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("auto", SUBTYPE_MODE_VOICE, IS_AUX, IS_AUTO,
+                    !IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_VOICE, IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("DummyDefaultAutoVoiceIme",
+                    "dummy.voice0", "DummyVoice0", IS_AUX, IS_DEFAULT, subtypes));
+        }
+        preinstalledImes.addAll(getImesWithoutDefaultVoiceIme());
+        return preinstalledImes;
     }
 
-    private static InputMethodInfo createNonDefaultAutoDummyVoiceIme0() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme0", "dummy.voice1",
-                "DummyVoice1", IS_AUX, !IS_DEFAULT, subtypes);
+    private static ArrayList<InputMethodInfo> getImesWithoutDefaultVoiceIme() {
+        ArrayList<InputMethodInfo> preinstalledImes = new ArrayList<>();
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("auto", SUBTYPE_MODE_VOICE, IS_AUX, IS_AUTO,
+                    !IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_VOICE, IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme0",
+                    "dummy.voice1", "DummyVoice1", IS_AUX, !IS_DEFAULT, subtypes));
+        }
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("auto", SUBTYPE_MODE_VOICE, IS_AUX, IS_AUTO,
+                    !IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_VOICE, IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme1",
+                    "dummy.voice2", "DummyVoice2", IS_AUX, !IS_DEFAULT, subtypes));
+        }
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_VOICE, IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("DummyNonDefaultVoiceIme2",
+                    "dummy.voice3", "DummyVoice3", IS_AUX, !IS_DEFAULT, subtypes));
+        }
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("DummyDefaultEnKeyboardIme",
+                    "dummy.keyboard0", "DummyKeyboard0", !IS_AUX, IS_DEFAULT, subtypes));
+        }
+        return preinstalledImes;
     }
 
-    private static InputMethodInfo createNonDefaultAutoDummyVoiceIme1() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("auto", "voice", IS_AUX, IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyNonDefaultAutoVoiceIme1", "dummy.voice2",
-                "DummyVoice2", IS_AUX, !IS_DEFAULT, subtypes);
-    }
+    private static ArrayList<InputMethodInfo> getSamplePreinstalledImes() {
+        ArrayList<InputMethodInfo> preinstalledImes = new ArrayList<>();
 
-    private static InputMethodInfo createNonDefaultDummyVoiceIme2() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("en_US", "voice", IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyNonDefaultVoiceIme2", "dummy.voice3",
-                "DummyVoice3", IS_AUX, !IS_DEFAULT, subtypes);
-    }
+        // a dummy Voice IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("", SUBTYPE_MODE_VOICE, IS_AUX,
+                    IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("com.android.apps.inputmethod.voice",
+                    "com.android.inputmethod.voice", "DummyVoiceIme", IS_AUX, IS_DEFAULT,
+                    subtypes));
+        }
 
-    private static InputMethodInfo createDefaultDummyLatinKeyboardIme() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("en_US", "keyboard", !IS_AUX, !IS_AUTO,
-                IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("en_GB", "keyboard", !IS_AUX, !IS_AUTO,
-                IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("en_IN", "keyboard", !IS_AUX, !IS_AUTO,
-                IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("hi", "keyboard", !IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));  // not AsciiCapable!
-        subtypes.add(createDummyInputMethodSubtype("hi_ZZ", "keyboard", !IS_AUX, !IS_AUTO,
-                IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyDefaultEnKeyboardIme", "dummy.keyboard0",
-                "DummyKeyboard0", !IS_AUX, IS_DEFAULT, subtypes);
-    }
+        // a dummy Hindi IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            // TODO: This subtype should be marked as IS_ASCII_CAPABLE
+            subtypes.add(createDummyInputMethodSubtype("en_IN", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("hi", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("com.android.apps.inputmethod.hindi",
+                    "com.android.inputmethod.hindi", "DummyHindiIme", !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,
-                IS_ASCII_CAPABLE));
-        return createDummyInputMethodInfo("DummyNonDefaultJaJPKeyboardIme", "dummy.keyboard1",
-                "DummyKeyboard1", !IS_AUX, !IS_DEFAULT, subtypes);
-    }
+        // a dummy Pinyin IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("zh_CN", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("ccom.android.apps.inputmethod.pinyin",
+                    "com.android.apps.inputmethod.pinyin", "DummyPinyinIme", !IS_AUX, IS_DEFAULT,
+                    subtypes));
+        }
 
-    // Although IMEs that have no subtype are considered to be deprecated, the Android framework
-    // must still be able to handle such IMEs as well as IMEs that have at least one subtype.
-    private static InputMethodInfo createNonDefaultDummyJaJPKeyboardImeWithoutSubtypes() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        return createDummyInputMethodInfo("DummyNonDefaultJaJPKeyboardImeWithoutSubtypes",
-                "dummy.keyboard2", "DummyKeyboard2", !IS_AUX, !IS_DEFAULT, NO_SUBTYPE);
-    }
+        // a dummy Korian IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("ko", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("com.android.apps.inputmethod.korean",
+                    "com.android.apps.inputmethod.korean", "DummyKorianIme", !IS_AUX, IS_DEFAULT,
+                    subtypes));
+        }
 
-    private static InputMethodInfo createDefaultDummyHinglishKeyboardIme() {
-        final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-        subtypes.add(createDummyInputMethodSubtype("en_IN", "keyboard", !IS_AUX, !IS_AUTO,
-                IS_ASCII_CAPABLE));
-        subtypes.add(createDummyInputMethodSubtype("hi", "keyboard", !IS_AUX, !IS_AUTO,
-                !IS_ASCII_CAPABLE));  // not AsciiCapable!
-        return createDummyInputMethodInfo("DummyDefaultHinglishKeyboardIme", "dummy.keyboard2",
-                "DummyKeyboard2", !IS_AUX, IS_DEFAULT, subtypes);
+        // a dummy Latin IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("en_US", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("en_GB", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("en_IN", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("hi", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("com.android.apps.inputmethod.latin",
+                    "com.android.apps.inputmethod.latin", "DummyLatinIme", !IS_AUX, IS_DEFAULT,
+                    subtypes));
+        }
+
+        // a dummy Japanese IME
+        {
+            final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+            subtypes.add(createDummyInputMethodSubtype("ja", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            subtypes.add(createDummyInputMethodSubtype("emoji", SUBTYPE_MODE_KEYBOARD, !IS_AUX,
+                    !IS_AUTO, !IS_ASCII_CAPABLE));
+            preinstalledImes.add(createDummyInputMethodInfo("com.android.apps.inputmethod.japanese",
+                    "com.android.apps.inputmethod.japanese", "DummyJapaneseIme", !IS_AUX,
+                    IS_DEFAULT, subtypes));
+        }
+
+        return preinstalledImes;
     }
 }
diff --git a/docs/html/sdk/installing/studio.jd b/docs/html/sdk/installing/studio.jd
index ee14b19..776e312 100644
--- a/docs/html/sdk/installing/studio.jd
+++ b/docs/html/sdk/installing/studio.jd
@@ -220,7 +220,7 @@
   <li>Lint tools to catch performance, usability, version compatibility, and other problems.</li>
   <li>ProGuard and app-signing capabilities.</li>
   <li>Built-in support for <a
-  href="https://developers.google.com/cloud/devtools/android_studio_templates/"
+  href="https://developers.google.com/cloud/mobile"
   class="external-link">Google Cloud Platform</a>, making it easy to integrate Google Cloud
   Messaging and App Engine.
 </ul>
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index 0927ffd..f45c0cb 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -250,11 +250,6 @@
     public void insertInorderBarrier() {}
 
     /**
-     * @hide
-     */
-    public void initializeLight(float lightX, float lightY, float lightZ, float lightRadius) {}
-
-    /**
      * Return true if the device that the current layer draws into is opaque
      * (i.e. does not support per-pixel alpha).
      *
@@ -416,10 +411,10 @@
      * @return       value to pass to restoreToCount() to balance this save()
      */
     public int saveLayer(@Nullable RectF bounds, @Nullable Paint paint, @Saveflags int saveFlags) {
-        return native_saveLayer(mNativeCanvasWrapper,
-                bounds.left, bounds.top, bounds.right, bounds.bottom,
-                paint != null ? paint.mNativePaint : 0,
-                saveFlags);
+        if (bounds == null) {
+            bounds = new RectF(getClipBounds());
+        }
+        return saveLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, paint, saveFlags);
     }
 
     /**
@@ -462,17 +457,17 @@
      * @param saveFlags see _SAVE_FLAG constants
      * @return          value to pass to restoreToCount() to balance this call
      */
-    public int saveLayerAlpha(@NonNull RectF bounds, int alpha, @Saveflags int saveFlags) {
-        alpha = Math.min(255, Math.max(0, alpha));
-        return native_saveLayerAlpha(mNativeCanvasWrapper,
-                bounds.left, bounds.top, bounds.right, bounds.bottom,
-                alpha, saveFlags);
+    public int saveLayerAlpha(@Nullable RectF bounds, int alpha, @Saveflags int saveFlags) {
+        if (bounds == null) {
+            bounds = new RectF(getClipBounds());
+        }
+        return saveLayerAlpha(bounds.left, bounds.top, bounds.right, bounds.bottom, alpha, saveFlags);
     }
 
     /**
      * Convenience for saveLayerAlpha(bounds, alpha, {@link #ALL_SAVE_FLAG})
      */
-    public int saveLayerAlpha(@NonNull RectF bounds, int alpha) {
+    public int saveLayerAlpha(@Nullable RectF bounds, int alpha) {
         return saveLayerAlpha(bounds, alpha, ALL_SAVE_FLAG);
     }
 
@@ -481,6 +476,7 @@
      */
     public int saveLayerAlpha(float left, float top, float right, float bottom, int alpha,
             @Saveflags int saveFlags) {
+        alpha = Math.min(255, Math.max(0, alpha));
         return native_saveLayerAlpha(mNativeCanvasWrapper, left, top, right, bottom,
                                      alpha, saveFlags);
     }
diff --git a/graphics/java/android/graphics/PorterDuffColorFilter.java b/graphics/java/android/graphics/PorterDuffColorFilter.java
index 705f5e6..ff768b7 100644
--- a/graphics/java/android/graphics/PorterDuffColorFilter.java
+++ b/graphics/java/android/graphics/PorterDuffColorFilter.java
@@ -99,5 +99,25 @@
         native_instance = native_CreatePorterDuffFilter(mColor, mMode.nativeInt);
     }
 
+    @Override
+    public boolean equals(Object object) {
+        if (this == object) {
+            return true;
+        }
+        if (object == null || getClass() != object.getClass()) {
+            return false;
+        }
+        final PorterDuffColorFilter other = (PorterDuffColorFilter) object;
+        if (mColor != other.mColor || mMode != other.mMode) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return 31 *  mMode.hashCode() + mColor;
+    }
+
     private static native long native_CreatePorterDuffFilter(int srcColor, int porterDuffMode);
 }
diff --git a/graphics/java/android/graphics/drawable/BitmapDrawable.java b/graphics/java/android/graphics/drawable/BitmapDrawable.java
index 715da7e..cf6be48 100644
--- a/graphics/java/android/graphics/drawable/BitmapDrawable.java
+++ b/graphics/java/android/graphics/drawable/BitmapDrawable.java
@@ -867,7 +867,7 @@
         int[] mThemeAttrs = null;
         Bitmap mBitmap = null;
         ColorStateList mTint = null;
-        Mode mTintMode = Mode.SRC_IN;
+        Mode mTintMode = DEFAULT_TINT_MODE;
         int mGravity = Gravity.FILL;
         float mBaseAlpha = 1.0f;
         Shader.TileMode mTileModeX = null;
diff --git a/graphics/java/android/graphics/drawable/ColorDrawable.java b/graphics/java/android/graphics/drawable/ColorDrawable.java
index 9e42a89..33225ce 100644
--- a/graphics/java/android/graphics/drawable/ColorDrawable.java
+++ b/graphics/java/android/graphics/drawable/ColorDrawable.java
@@ -261,8 +261,8 @@
         @ViewDebug.ExportedProperty
         int mUseColor;  // basecolor modulated by setAlpha()
         int mChangingConfigurations;
-        ColorStateList mTint;
-        Mode mTintMode;
+        ColorStateList mTint = null;
+        Mode mTintMode = DEFAULT_TINT_MODE;
 
         ColorState() {
             // Empty constructor.
diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java
index 3cb5210..43a9eaa 100644
--- a/graphics/java/android/graphics/drawable/Drawable.java
+++ b/graphics/java/android/graphics/drawable/Drawable.java
@@ -125,6 +125,8 @@
 public abstract class Drawable {
     private static final Rect ZERO_BOUNDS_RECT = new Rect();
 
+    static final PorterDuff.Mode DEFAULT_TINT_MODE = PorterDuff.Mode.SRC_IN;
+
     private int[] mStateSet = StateSet.WILD_CARD;
     private int mLevel = 0;
     private int mChangingConfigurations = 0;
diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java
index e1c88cb..2916d6c 100644
--- a/graphics/java/android/graphics/drawable/GradientDrawable.java
+++ b/graphics/java/android/graphics/drawable/GradientDrawable.java
@@ -1638,6 +1638,11 @@
                 }
             }
 
+            // An unfilled shape is not opaque over bounds or shape
+            if (mColors == null && mColorStateList == null) {
+                return;
+            }
+
             // Colors are opaque, so opaqueOverShape=true,
             mOpaqueOverShape = true;
             // and opaqueOverBounds=true if shape fills bounds
diff --git a/graphics/java/android/graphics/drawable/NinePatchDrawable.java b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
index c185a9e..6c62ccf 100644
--- a/graphics/java/android/graphics/drawable/NinePatchDrawable.java
+++ b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
@@ -585,7 +585,7 @@
         int[] mThemeAttrs = null;
         NinePatch mNinePatch = null;
         ColorStateList mTint = null;
-        Mode mTintMode = Mode.SRC_IN;
+        Mode mTintMode = DEFAULT_TINT_MODE;
         Rect mPadding = null;
         Insets mOpticalInsets = Insets.NONE;
         float mBaseAlpha = 1.0f;
diff --git a/graphics/java/android/graphics/drawable/ShapeDrawable.java b/graphics/java/android/graphics/drawable/ShapeDrawable.java
index 6f18635..bd69d76 100644
--- a/graphics/java/android/graphics/drawable/ShapeDrawable.java
+++ b/graphics/java/android/graphics/drawable/ShapeDrawable.java
@@ -515,8 +515,8 @@
         int mChangingConfigurations;
         Paint mPaint;
         Shape mShape;
-        ColorStateList mTint;
-        Mode mTintMode = Mode.SRC_IN;
+        ColorStateList mTint = null;
+        Mode mTintMode = DEFAULT_TINT_MODE;
         Rect mPadding;
         int mIntrinsicWidth;
         int mIntrinsicHeight;
diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java
index 4407a3c..dd87699 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -216,7 +216,7 @@
         }
 
         mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
-        mVectorState.mVPathRenderer.setColorFilter(mTintFilter);
+        state.setColorFilter(mTintFilter);
     }
 
     @Override
@@ -256,21 +256,22 @@
         }
 
         if (!mAllowCaching) {
-            mVectorState.mVPathRenderer.draw(canvas, bounds.width(), bounds.height());
+            // AnimatedVectorDrawable
+            if (!mVectorState.hasTranslucentRoot()) {
+                mVectorState.mVPathRenderer.draw(canvas, bounds.width(), bounds.height());
+            } else {
+                mVectorState.createCachedBitmapIfNeeded(bounds);
+                mVectorState.updateCachedBitmap(bounds);
+                mVectorState.drawCachedBitmapWithRootAlpha(canvas);
+            }
         } else {
-            Bitmap bitmap = mVectorState.mCachedBitmap;
-            if (bitmap == null || !mVectorState.canReuseCache(bounds.width(),
-                    bounds.height())) {
-                bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(),
-                        Bitmap.Config.ARGB_8888);
-                Canvas tmpCanvas = new Canvas(bitmap);
-                mVectorState.mVPathRenderer.draw(tmpCanvas, bounds.width(), bounds.height());
-                mVectorState.mCachedBitmap = bitmap;
-
+            // Static Vector Drawable case.
+            mVectorState.createCachedBitmapIfNeeded(bounds);
+            if (!mVectorState.canReuseCache()) {
+                mVectorState.updateCachedBitmap(bounds);
                 mVectorState.updateCacheStates();
             }
-            // The bitmap's size is the same as the bounds.
-            canvas.drawBitmap(bitmap, 0, 0, null);
+            mVectorState.drawCachedBitmapWithRootAlpha(canvas);
         }
 
         canvas.restoreToCount(saveCount);
@@ -302,7 +303,7 @@
             colorFilter = mTintFilter;
         }
 
-        state.mVPathRenderer.setColorFilter(colorFilter);
+        state.setColorFilter(colorFilter);
         invalidateSelf();
     }
 
@@ -312,7 +313,7 @@
         if (state.mTint != tint) {
             state.mTint = tint;
             mTintFilter = updateTintFilter(mTintFilter, tint, state.mTintMode);
-            state.mVPathRenderer.setColorFilter(mTintFilter);
+            state.setColorFilter(mTintFilter);
             invalidateSelf();
         }
     }
@@ -323,17 +324,24 @@
         if (state.mTintMode != tintMode) {
             state.mTintMode = tintMode;
             mTintFilter = updateTintFilter(mTintFilter, state.mTint, tintMode);
-            state.mVPathRenderer.setColorFilter(mTintFilter);
+            state.setColorFilter(mTintFilter);
             invalidateSelf();
         }
     }
 
     @Override
+    public boolean isStateful() {
+        return super.isStateful() || (mVectorState != null && mVectorState.mTint != null
+                && mVectorState.mTint.isStateful());
+    }
+
+    @Override
     protected boolean onStateChange(int[] stateSet) {
         final VectorDrawableState state = mVectorState;
         if (state.mTint != null && state.mTintMode != null) {
             mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
-            mVectorState.mVPathRenderer.setColorFilter(mTintFilter);
+            state.setColorFilter(mTintFilter);
+            invalidateSelf();
             return true;
         }
         return false;
@@ -364,6 +372,21 @@
         super.applyTheme(t);
 
         final VectorDrawableState state = mVectorState;
+        if (state != null && state.mThemeAttrs != null) {
+            final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.VectorDrawable);
+            try {
+                state.mCacheDirty = true;
+                updateStateFromTypedArray(a);
+            } catch (XmlPullParserException e) {
+                throw new RuntimeException(e);
+            } finally {
+                a.recycle();
+            }
+
+            mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
+            state.setColorFilter(mTintFilter);
+        }
+
         final VPathRenderer path = state.mVPathRenderer;
         if (path != null && path.canApplyTheme()) {
             path.applyTheme(t);
@@ -433,7 +456,7 @@
         final VPathRenderer pathRenderer = new VPathRenderer();
         state.mVPathRenderer = pathRenderer;
 
-        TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawable);
+        final TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawable);
         updateStateFromTypedArray(a);
         a.recycle();
 
@@ -441,7 +464,7 @@
         inflateInternal(res, parser, attrs, theme);
 
         mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
-        state.mVPathRenderer.setColorFilter(mTintFilter);
+        state.setColorFilter(mTintFilter);
     }
 
     private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException {
@@ -492,6 +515,15 @@
             throw new XmlPullParserException(a.getPositionDescription() +
                     "<vector> tag requires height > 0");
         }
+
+        final float alphaInFloat = a.getFloat(R.styleable.VectorDrawable_alpha,
+                pathRenderer.getAlpha());
+        pathRenderer.setAlpha(alphaInFloat);
+
+        pathRenderer.mRootName = a.getString(R.styleable.VectorDrawable_name);
+        if (pathRenderer.mRootName != null) {
+            pathRenderer.mVGTargetsMap.put(pathRenderer.mRootName, pathRenderer);
+        }
     }
 
     private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs,
@@ -613,8 +645,8 @@
         int[] mThemeAttrs;
         int mChangingConfigurations;
         VPathRenderer mVPathRenderer;
-        ColorStateList mTint;
-        Mode mTintMode;
+        ColorStateList mTint = null;
+        Mode mTintMode = DEFAULT_TINT_MODE;
         boolean mAutoMirrored;
 
         Bitmap mCachedBitmap;
@@ -646,15 +678,60 @@
             }
         }
 
-        public boolean canReuseCache(int width, int height) {
+        // TODO: Support colorFilter here.
+        public void drawCachedBitmapWithRootAlpha(Canvas canvas) {
+            Paint alphaPaint = getRootAlphaPaint();
+            // The bitmap's size is the same as the bounds.
+            canvas.drawBitmap(mCachedBitmap, 0, 0, alphaPaint);
+        }
+
+        public boolean hasTranslucentRoot() {
+            return mVPathRenderer.getRootAlpha() < 255;
+        }
+
+        /**
+         * @return null when there is no need for alpha paint.
+         */
+        public Paint getRootAlphaPaint() {
+            Paint paint = null;
+            boolean needsAlphaPaint = hasTranslucentRoot();
+            if (needsAlphaPaint) {
+                paint = new Paint();
+                paint.setAlpha(mVPathRenderer.getRootAlpha());
+            }
+            return paint;
+        }
+
+        public void updateCachedBitmap(Rect bounds) {
+            mCachedBitmap.eraseColor(Color.TRANSPARENT);
+            Canvas tmpCanvas = new Canvas(mCachedBitmap);
+            mVPathRenderer.draw(tmpCanvas, bounds.width(), bounds.height());
+        }
+
+        public void createCachedBitmapIfNeeded(Rect bounds) {
+            if (mCachedBitmap == null || !canReuseBitmap(bounds.width(),
+                    bounds.height())) {
+                mCachedBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(),
+                        Bitmap.Config.ARGB_8888);
+            }
+
+        }
+
+        public boolean canReuseBitmap(int width, int height) {
+            if (width == mCachedBitmap.getWidth()
+                    && height == mCachedBitmap.getHeight()) {
+                return true;
+            }
+            return false;
+        }
+
+        public boolean canReuseCache() {
             if (!mCacheDirty
                     && mCachedThemeAttrs == mThemeAttrs
                     && mCachedTint == mTint
                     && mCachedTintMode == mTintMode
                     && mCachedAutoMirrored == mAutoMirrored
-                    && width == mCachedBitmap.getWidth()
-                    && height == mCachedBitmap.getHeight()
-                    && mCachedRootAlpha == mVPathRenderer.getRootAlpha())  {
+                    && mCachedRootAlpha == mVPathRenderer.getRootAlpha()) {
                 return true;
             }
             return false;
@@ -671,6 +748,18 @@
             mCacheDirty = false;
         }
 
+        @Override
+        public boolean canApplyTheme() {
+            return super.canApplyTheme() || mThemeAttrs != null
+                    || (mVPathRenderer != null && mVPathRenderer.canApplyTheme());
+        }
+
+        public void setColorFilter(ColorFilter colorFilter) {
+            if (mVPathRenderer != null && mVPathRenderer.setColorFilter(colorFilter)) {
+                mCacheDirty = true;
+            }
+        }
+
         public VectorDrawableState() {
             mVPathRenderer = new VPathRenderer();
         }
@@ -729,7 +818,8 @@
         float mBaseHeight = 0;
         float mViewportWidth = 0;
         float mViewportHeight = 0;
-        private int mRootAlpha = 0xFF;
+        int mRootAlpha = 0xFF;
+        String mRootName = null;
 
         final ArrayMap<String, Object> mVGTargetsMap = new ArrayMap<String, Object>();
 
@@ -747,6 +837,17 @@
             return mRootAlpha;
         }
 
+        // setAlpha() and getAlpha() are used mostly for animation purpose, since
+        // Animator like to use alpha from 0 to 1.
+        public void setAlpha(float alpha) {
+            setRootAlpha((int) (alpha * 255));
+        }
+
+        @SuppressWarnings("unused")
+        public float getAlpha() {
+            return getRootAlpha() / 255.0f;
+        }
+
         public VPathRenderer(VPathRenderer copy) {
             mRootGroup = new VGroup(copy.mRootGroup, mVGTargetsMap);
             mPath = new Path(copy.mPath);
@@ -757,6 +858,10 @@
             mViewportHeight = copy.mViewportHeight;
             mChangingConfigurations = copy.mChangingConfigurations;
             mRootAlpha = copy.mRootAlpha;
+            mRootName = copy.mRootName;
+            if (copy.mRootName != null) {
+                mVGTargetsMap.put(copy.mRootName, this);
+            }
         }
 
         public boolean canApplyTheme() {
@@ -813,17 +918,21 @@
             }
         }
 
-        public void setColorFilter(ColorFilter colorFilter) {
-            mColorFilter = colorFilter;
+        public boolean setColorFilter(ColorFilter colorFilter) {
+            if (colorFilter != mColorFilter
+                    || (colorFilter != null && !colorFilter.equals(mColorFilter))) {
+                mColorFilter = colorFilter;
 
-            if (mFillPaint != null) {
-                mFillPaint.setColorFilter(colorFilter);
+                if (mFillPaint != null) {
+                    mFillPaint.setColorFilter(colorFilter);
+                }
+
+                if (mStrokePaint != null) {
+                    mStrokePaint.setColorFilter(colorFilter);
+                }
+                return true;
             }
-
-            if (mStrokePaint != null) {
-                mStrokePaint.setColorFilter(colorFilter);
-            }
-
+            return false;
         }
 
         private void drawGroupTree(VGroup currentGroup, Matrix currentMatrix,
@@ -856,7 +965,7 @@
         }
 
         private void drawPath(VGroup vGroup, VPath vPath, Canvas canvas, int w, int h) {
-            final float scaleX =  w / mViewportWidth;
+            final float scaleX = w / mViewportWidth;
             final float scaleY = h / mViewportHeight;
             final float minScale = Math.min(scaleX, scaleY);
 
@@ -1011,10 +1120,6 @@
             return mLocalMatrix;
         }
 
-        public boolean canApplyTheme() {
-            return mThemeAttrs != null;
-        }
-
         public void inflate(Resources res, AttributeSet attrs, Theme theme) {
             final TypedArray a = obtainAttributes(res, theme, attrs,
                     R.styleable.VectorDrawableGroup);
@@ -1045,13 +1150,16 @@
             updateLocalMatrix();
         }
 
+        public boolean canApplyTheme() {
+            return mThemeAttrs != null;
+        }
+
         public void applyTheme(Theme t) {
             if (mThemeAttrs == null) {
                 return;
             }
 
-            final TypedArray a = t.resolveAttributes(mThemeAttrs,
-                    R.styleable.VectorDrawableGroup);
+            final TypedArray a = t.resolveAttributes(mThemeAttrs, R.styleable.VectorDrawableGroup);
             updateStateFromTypedArray(a);
             a.recycle();
         }
@@ -1219,7 +1327,7 @@
     /**
      * Clip path, which only has name and pathData.
      */
-    private static class VClipPath extends VPath{
+    private static class VClipPath extends VPath {
         public VClipPath() {
             // Empty constructor.
         }
@@ -1375,8 +1483,7 @@
                 return;
             }
 
-            final TypedArray a = t.resolveAttributes(mThemeAttrs,
-                    R.styleable.VectorDrawablePath);
+            final TypedArray a = t.resolveAttributes(mThemeAttrs, R.styleable.VectorDrawablePath);
             updateStateFromTypedArray(a);
             a.recycle();
         }
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 31cc1c8..0415efa 100755
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -1744,10 +1744,13 @@
         glUniform4f(mCaches.currentProgram->getUniform("roundRectInnerRectLTRB"),
                 innerRect.left, innerRect.top,
                 innerRect.right, innerRect.bottom);
-        glUniform1f(mCaches.currentProgram->getUniform("roundRectRadius"),
-                state->radius);
         glUniformMatrix4fv(mCaches.currentProgram->getUniform("roundRectInvTransform"),
                 1, GL_FALSE, &state->matrix.data[0]);
+
+        // add half pixel to round out integer rect space to cover pixel centers
+        float roundedOutRadius = state->radius + 0.5f;
+        glUniform1f(mCaches.currentProgram->getUniform("roundRectRadius"),
+                roundedOutRadius);
     }
 }
 
diff --git a/libs/hwui/RenderState.cpp b/libs/hwui/RenderState.cpp
index 54af528..86bd7dd 100644
--- a/libs/hwui/RenderState.cpp
+++ b/libs/hwui/RenderState.cpp
@@ -38,6 +38,7 @@
 }
 
 void RenderState::onGLContextDestroyed() {
+/*
     AutoMutex _lock(mLayerLock);
     size_t size = mActiveLayers.size();
     if (CC_UNLIKELY(size != 0)) {
@@ -68,6 +69,7 @@
         }
         LOG_ALWAYS_FATAL("%d layers have survived gl context destruction", size);
     }
+*/
 }
 
 void RenderState::setViewport(GLsizei width, GLsizei height) {
diff --git a/libs/hwui/RenderState.h b/libs/hwui/RenderState.h
index 74bafca..cbe7cfc 100644
--- a/libs/hwui/RenderState.h
+++ b/libs/hwui/RenderState.h
@@ -53,12 +53,16 @@
     void debugOverdraw(bool enable, bool clear);
 
     void registerLayer(const Layer* layer) {
+        /*
         AutoMutex _lock(mLayerLock);
         mActiveLayers.insert(layer);
+        */
     }
     void unregisterLayer(const Layer* layer) {
+        /*
         AutoMutex _lock(mLayerLock);
         mActiveLayers.erase(layer);
+        */
     }
 
     void registerCanvasContext(renderthread::CanvasContext* context) {
diff --git a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
index e0901d0..f0a2072 100644
--- a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
+++ b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
@@ -34,6 +34,7 @@
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.SystemProperties;
+import android.provider.Settings;
 import android.util.Log;
 
 import com.android.internal.R;
@@ -110,6 +111,9 @@
     // Set to true if the phone is having emergency call.
     private volatile boolean mIsInEmergency;
 
+    // If Location function is enabled.
+    private volatile boolean mIsLocationEnabled = false;
+
     private final INetInitiatedListener mNetInitiatedListener;
 
     // Set to true if string from HAL is encoded as Hex, e.g., "3F0039"
@@ -132,7 +136,7 @@
     };
 
     public static class GpsNiResponse {
-        /* User reponse, one of the values in GpsUserResponseType */
+        /* User response, one of the values in GpsUserResponseType */
         int userResponse;
         /* Optional extra data to pass with the user response */
         Bundle extras;
@@ -154,8 +158,11 @@
                        Emergency call back mode will be checked by reading system properties
                        when necessary: SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE)
                 */
-                mIsInEmergency |= PhoneNumberUtils.isEmergencyNumber(phoneNumber);
-                if (DEBUG) Log.v(TAG, "ACTION_NEW_OUTGOING_CALL - " + mIsInEmergency);
+                setInEmergency(PhoneNumberUtils.isEmergencyNumber(phoneNumber));
+                if (DEBUG) Log.v(TAG, "ACTION_NEW_OUTGOING_CALL - " + getInEmergency());
+            } else if (action.equals(LocationManager.MODE_CHANGED_ACTION)) {
+                updateLocationMode();
+                if (DEBUG) Log.d(TAG, "location enabled :" + getLocationEnabled());
             }
         }
     };
@@ -179,8 +186,9 @@
             mNetInitiatedListener = netInitiatedListener;
         }
 
-        mIsSuplEsEnabled = isSuplEsEnabled;
+        setSuplEsEnabled(isSuplEsEnabled);
         mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
+        updateLocationMode();
         mTelephonyManager =
             (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
 
@@ -190,7 +198,7 @@
                 if (DEBUG) Log.d(TAG, "onCallStateChanged(): state is "+ state);
                 // listening for emergency call ends
                 if (state == TelephonyManager.CALL_STATE_IDLE) {
-                    mIsInEmergency = false;
+                    setInEmergency(false);
                 }
             }
         };
@@ -198,27 +206,65 @@
 
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
+        intentFilter.addAction(LocationManager.MODE_CHANGED_ACTION);
         mContext.registerReceiver(mBroadcastReciever, intentFilter);
     }
 
-    public void setSuplEsEnablement(boolean isEnabled)
-    {
+    public void setSuplEsEnabled(boolean isEnabled) {
         mIsSuplEsEnabled = isEnabled;
     }
 
+    public boolean getSuplEsEnabled() {
+        return mIsSuplEsEnabled;
+    }
+
+    /**
+     * Updates Location enabler based on location setting.
+     */
+    public void updateLocationMode() {
+        mIsLocationEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
+    }
+
+    /**
+     * Checks if user agreed to use location.
+     */
+    public boolean getLocationEnabled() {
+        return mIsLocationEnabled;
+    }
+
+    // Note: Currently, there are two mechanisms involved to determine if a
+    // phone is in emergency mode:
+    // 1. If the user is making an emergency call, this is provided by activly
+    //    monitoring the outgoing phone number;
+    // 2. If the device is in a emergency callback state, this is provided by
+    //    system properties.
+    // If either one of above exists, the phone is considered in an emergency
+    // mode. Because of this complexity, we need to be careful about how to set
+    // and clear the emergency state.
+    public void setInEmergency(boolean isInEmergency) {
+        mIsInEmergency = isInEmergency;
+    }
+
+    public boolean getInEmergency() {
+        boolean isInEmergencyCallback = Boolean.parseBoolean(
+                SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE));
+        return mIsInEmergency || isInEmergencyCallback;
+    }
+
+
     // Handles NI events from HAL
-    public void handleNiNotification(GpsNiNotification notif)
-    {
+    public void handleNiNotification(GpsNiNotification notif) {
         if (DEBUG) Log.d(TAG, "in handleNiNotification () :"
                         + " notificationId: " + notif.notificationId
                         + " requestorId: " + notif.requestorId
                         + " text: " + notif.text
-                        + " mIsSuplEsEnabled" + mIsSuplEsEnabled);
+                        + " mIsSuplEsEnabled" + getSuplEsEnabled()
+                        + " mIsLocationEnabled" + getLocationEnabled());
 
-        if (mIsSuplEsEnabled == false) {
-            handleNi(notif);
-        } else {
+        if (getSuplEsEnabled()) {
             handleNiInEs(notif);
+        } else {
+            handleNi(notif);
         }
 
         //////////////////////////////////////////////////////////////////////////
@@ -240,9 +286,18 @@
                         + " needNotify: " + notif.needNotify
                         + " needVerify: " + notif.needVerify
                         + " privacyOverride: " + notif.privacyOverride
-                        + " mPopupImmediately: " + mPopupImmediately);
+                        + " mPopupImmediately: " + mPopupImmediately
+                        + " mInEmergency: " + getInEmergency());
 
-        // legacy behaviour
+        if (getLocationEnabled() && !getInEmergency()) {
+            // Location is currently disabled, ignore all NI requests.
+            try {
+                mNetInitiatedListener.sendNiResponse(notif.notificationId,
+                                                     GPS_NI_RESPONSE_IGNORE);
+            } catch (RemoteException e) {
+                Log.e(TAG, "RemoteException in sendNiResponse");
+            }
+        }
         if (notif.needNotify) {
         // If NI does not need verify or the dialog is not requested
         // to pop up immediately, the dialog box will not pop up.
@@ -274,9 +329,6 @@
                     + " notificationId: " + notif.notificationId);
 
         // UE is in emergency mode when in emergency call mode or in emergency call back mode
-        boolean isUEInEmergencyMode = mIsInEmergency ||
-            Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE));
-
         /*
            1. When SUPL ES bit is off and UE is not in emergency mode:
                   Call handleNi() to do legacy behaviour.
@@ -288,7 +340,7 @@
                   Ignore the emergency SUPL INIT.
         */
         boolean isNiTypeES = (notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL);
-        if (isNiTypeES != isUEInEmergencyMode) {
+        if (isNiTypeES != getInEmergency()) {
             try {
                 mNetInitiatedListener.sendNiResponse(notif.notificationId,
                                                      GPS_NI_RESPONSE_IGNORE);
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index 91a8468..6c9fb9a 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -76,6 +76,7 @@
 import android.view.KeyEvent;
 import android.view.Surface;
 import android.view.WindowManager;
+import android.view.accessibility.AccessibilityManager;
 
 import com.android.internal.telephony.ITelephony;
 import com.android.internal.util.XmlUtils;
@@ -451,11 +452,6 @@
     private Looper mSoundPoolLooper = null;
     // volume applied to sound played with playSoundEffect()
     private static int sSoundEffectVolumeDb;
-    // getActiveStreamType() will return:
-    // - STREAM_NOTIFICATION on tablets during this period after a notification stopped
-    // - STREAM_MUSIC on phones during this period after music or talkback/voice search prompt
-    // stopped
-    private static final int DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS = 5000;
     // previous volume adjustment direction received by checkForRingerModeChange()
     private int mPrevVolDirection = AudioManager.ADJUST_SAME;
     // Keyguard manager proxy
@@ -683,6 +679,8 @@
                 0,
                 null,
                 SAFE_VOLUME_CONFIGURE_TIMEOUT_MS);
+
+        StreamOverride.init(mContext);
     }
 
     private void createAudioSystemThread() {
@@ -2972,7 +2970,7 @@
                     return AudioSystem.STREAM_VOICE_CALL;
                 }
             } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
-                if (isAfMusicActiveRecently(DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS)) {
+                if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
                     if (DEBUG_VOL)
                         Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
                     return AudioSystem.STREAM_MUSIC;
@@ -3004,13 +3002,13 @@
                     return AudioSystem.STREAM_VOICE_CALL;
                 }
             } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
-                    DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS) ||
+                    StreamOverride.sDelayMs) ||
                     AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
-                            DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS)) {
+                            StreamOverride.sDelayMs)) {
                 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION");
                 return AudioSystem.STREAM_NOTIFICATION;
             } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
-                if (isAfMusicActiveRecently(DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS)) {
+                if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
                     if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: forcing STREAM_MUSIC");
                     return AudioSystem.STREAM_MUSIC;
                 } else {
@@ -5111,6 +5109,47 @@
     }
 
     //==========================================================================================
+    // Accessibility: taking touch exploration into account for selecting the default
+    //   stream override timeout when adjusting volume
+    //==========================================================================================
+    private static class StreamOverride
+            implements AccessibilityManager.TouchExplorationStateChangeListener {
+
+        // AudioService.getActiveStreamType() will return:
+        // - STREAM_NOTIFICATION on tablets during this period after a notification stopped
+        // - STREAM_MUSIC on phones during this period after music or talkback/voice search prompt
+        // stopped
+        private static final int DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS = 5000;
+        private static final int TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS = 1000;
+
+        static int sDelayMs;
+
+        static void init(Context ctxt) {
+            AccessibilityManager accessibilityManager =
+                    (AccessibilityManager) ctxt.getSystemService(Context.ACCESSIBILITY_SERVICE);
+            updateDefaultStreamOverrideDelay(
+                    accessibilityManager.isTouchExplorationEnabled());
+            accessibilityManager.addTouchExplorationStateChangeListener(
+                    new StreamOverride());
+        }
+
+        @Override
+        public void onTouchExplorationStateChanged(boolean enabled) {
+            updateDefaultStreamOverrideDelay(enabled);
+        }
+
+        private static void updateDefaultStreamOverrideDelay(boolean touchExploreEnabled) {
+            if (touchExploreEnabled) {
+                sDelayMs = TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS;
+            } else {
+                sDelayMs = DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS;
+            }
+            if (DEBUG_VOL) Log.d(TAG, "Touch exploration enabled=" + touchExploreEnabled
+                    + " stream override delay is now " + sDelayMs + " ms");
+        }
+    }
+
+    //==========================================================================================
     // Camera shutter sound policy.
     // config_camera_sound_forced configuration option in config.xml defines if the camera shutter
     // sound is forced (sound even if the device is in silent mode) or not. This option is false by
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_breadcrumb_arrow_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_breadcrumb_arrow_am_alpha.png
new file mode 100644
index 0000000..84573f6
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_breadcrumb_arrow_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_accept_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_accept_alpha.png
new file mode 100644
index 0000000..986d3fb
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_accept_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_cancel_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_cancel_alpha.png
new file mode 100644
index 0000000..ce443f9
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_cancel_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_select_item_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_select_item_alpha.png
new file mode 100644
index 0000000..a54e0ea
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_cab_select_item_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_alert_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_alert_alpha.png
new file mode 100644
index 0000000..6e65716
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_alert_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_info_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_info_alpha.png
new file mode 100644
index 0000000..35bd56e
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_dialog_info_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_album_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_album_alpha.png
new file mode 100644
index 0000000..64aa50b
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_album_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_apk_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_apk_alpha.png
new file mode 100644
index 0000000..7cbcb8b
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_apk_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_audio_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_audio_alpha.png
new file mode 100644
index 0000000..d6d79ec
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_audio_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_certificate_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_certificate_alpha.png
new file mode 100644
index 0000000..ca12928
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_certificate_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_codes_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_codes_alpha.png
new file mode 100644
index 0000000..c4afa37
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_codes_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_compressed_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_compressed_alpha.png
new file mode 100644
index 0000000..0b0aa04
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_compressed_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_contact_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_contact_am_alpha.png
new file mode 100644
index 0000000..ebd0535
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_contact_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_event_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_event_am_alpha.png
new file mode 100644
index 0000000..29cdbb7
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_event_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_excel_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_excel_alpha.png
new file mode 100644
index 0000000..ca349b6
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_excel_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_folder_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_folder_alpha.png
new file mode 100644
index 0000000..02249d2
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_folder_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_font_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_font_alpha.png
new file mode 100644
index 0000000..469b911
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_font_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_generic_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_generic_am_alpha.png
new file mode 100644
index 0000000..ef479c3
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_generic_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_image_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_image_alpha.png
new file mode 100644
index 0000000..3168d6f
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_image_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_pdf_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_pdf_alpha.png
new file mode 100644
index 0000000..9bb4d66
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_pdf_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_powerpoint_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_powerpoint_alpha.png
new file mode 100644
index 0000000..88ba9ad
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_powerpoint_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_presentation_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_presentation_alpha.png
new file mode 100644
index 0000000..5fe18da
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_presentation_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_spreadsheet_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_spreadsheet_am_alpha.png
new file mode 100644
index 0000000..1d05f6f
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_spreadsheet_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_text_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_text_am_alpha.png
new file mode 100644
index 0000000..c2308fe
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_text_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_video_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_video_am_alpha.png
new file mode 100644
index 0000000..9a173be
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_video_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_word_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_word_alpha.png
new file mode 100644
index 0000000..a564f5a
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_doc_word_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_folder_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_folder_alpha.png
new file mode 100644
index 0000000..c0c27a2
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_folder_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_grid_folder_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_grid_folder_alpha.png
new file mode 100644
index 0000000..ca6be0e
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_grid_folder_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_hamburger_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_hamburger_alpha.png
new file mode 100644
index 0000000..13b20c6
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_hamburger_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_copy_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_copy_alpha.png
new file mode 100644
index 0000000..2dcf03e
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_copy_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_delete_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_delete_alpha.png
new file mode 100644
index 0000000..07a78ed
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_delete_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_disconnect_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_disconnect_am_alpha.png
new file mode 100644
index 0000000..d7eb04f
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_disconnect_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_new_folder_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_new_folder_am_alpha.png
new file mode 100644
index 0000000..879bf45
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_new_folder_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_overflow_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_overflow_alpha.png
new file mode 100644
index 0000000..2cd4137
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_overflow_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_rename_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_rename_am_alpha.png
new file mode 100644
index 0000000..268049e
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_rename_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_search_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_search_alpha.png
new file mode 100644
index 0000000..78fc61d
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_search_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_settings_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_settings_alpha.png
new file mode 100644
index 0000000..36e8e68
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_settings_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_share_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_share_alpha.png
new file mode 100644
index 0000000..68831f3
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_share_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_sortby_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_sortby_am_alpha.png
new file mode 100644
index 0000000..827a92c
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_sortby_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_undo_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_undo_am_alpha.png
new file mode 100644
index 0000000..0f12b7d
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_undo_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_grid_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_grid_alpha.png
new file mode 100644
index 0000000..df1bac1
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_grid_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_list_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_list_alpha.png
new file mode 100644
index 0000000..9420374
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_menu_view_list_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_open_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_open_am_alpha.png
new file mode 100644
index 0000000..0394c5c
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_open_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_popout_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_popout_am_alpha.png
new file mode 100644
index 0000000..325d374
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_popout_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_download_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_download_alpha.png
new file mode 100644
index 0000000..87a5210
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_download_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_folder_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_folder_am_alpha.png
new file mode 100644
index 0000000..bb41a91
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_folder_am_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_recent_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_recent_alpha.png
new file mode 100644
index 0000000..baa723d
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_recent_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_sdcard_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_sdcard_alpha.png
new file mode 100644
index 0000000..39c737f
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_sdcard_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_usb_light_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_usb_light_alpha.png
new file mode 100644
index 0000000..88973e0
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_root_usb_light_alpha.png
Binary files differ
diff --git a/packages/DocumentsUI/res/drawable-xxxhdpi/ic_subdirectory_arrow_am_alpha.png b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_subdirectory_arrow_am_alpha.png
new file mode 100644
index 0000000..8fddb85
--- /dev/null
+++ b/packages/DocumentsUI/res/drawable-xxxhdpi/ic_subdirectory_arrow_am_alpha.png
Binary files differ
diff --git a/packages/Keyguard/res/layout/keyguard_pin_view.xml b/packages/Keyguard/res/layout/keyguard_pin_view.xml
index a33f95b..4cbddde 100644
--- a/packages/Keyguard/res/layout/keyguard_pin_view.xml
+++ b/packages/Keyguard/res/layout/keyguard_pin_view.xml
@@ -40,7 +40,7 @@
             android:layout_weight="1"
             android:layoutDirection="ltr"
             >
-        <RelativeLayout
+        <com.android.keyguard.AlphaOptimizedRelativeLayout
                 android:id="@+id/row0"
                 android:layout_width="match_parent"
                 android:layout_height="0dp"
@@ -79,7 +79,7 @@
                     android:layout_alignParentBottom="true"
                     android:background="#28FFFFFF"
                     />
-        </RelativeLayout>
+        </com.android.keyguard.AlphaOptimizedRelativeLayout>
         <LinearLayout
                 android:id="@+id/row1"
                 android:layout_width="match_parent"
@@ -196,7 +196,7 @@
                     androidprv:textView="@+id/pinEntry"
                     androidprv:digit="0"
                     />
-            <ImageButton
+            <com.android.keyguard.AlphaOptimizedImageButton
                     android:id="@+id/key_enter"
                     android:layout_width="0px"
                     android:layout_height="match_parent"
diff --git a/packages/Keyguard/res/values-h650dp/dimens.xml b/packages/Keyguard/res/values-h650dp/dimens.xml
new file mode 100644
index 0000000..4864326
--- /dev/null
+++ b/packages/Keyguard/res/values-h650dp/dimens.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2014 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
+  -->
+
+<resources>
+    <dimen name="widget_big_font_size">112dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedImageButton.java b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedImageButton.java
new file mode 100644
index 0000000..eda790f
--- /dev/null
+++ b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedImageButton.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2014 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.keyguard;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.widget.ImageButton;
+import android.widget.RelativeLayout;
+
+/**
+ * A frame layout which does not have overlapping renderings commands and therefore does not need a
+ * layer when alpha is changed.
+ */
+public class AlphaOptimizedImageButton extends ImageButton {
+
+    public AlphaOptimizedImageButton(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    @Override
+    public boolean hasOverlappingRendering() {
+        return false;
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/AlphaOptimizedLinearLayout.java b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedLinearLayout.java
similarity index 97%
rename from packages/SystemUI/src/com/android/systemui/statusbar/AlphaOptimizedLinearLayout.java
rename to packages/Keyguard/src/com/android/keyguard/AlphaOptimizedLinearLayout.java
index 9f4c3a9..36da6f1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/AlphaOptimizedLinearLayout.java
+++ b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedLinearLayout.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.systemui.statusbar;
+package com.android.keyguard;
 
 import android.content.Context;
 import android.util.AttributeSet;
diff --git a/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedRelativeLayout.java b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedRelativeLayout.java
new file mode 100644
index 0000000..200b116
--- /dev/null
+++ b/packages/Keyguard/src/com/android/keyguard/AlphaOptimizedRelativeLayout.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2014 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.keyguard;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.widget.RelativeLayout;
+
+/**
+ * A frame layout which does not have overlapping renderings commands and therefore does not need a
+ * layer when alpha is changed.
+ */
+public class AlphaOptimizedRelativeLayout extends RelativeLayout {
+
+    public AlphaOptimizedRelativeLayout(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    @Override
+    public boolean hasOverlappingRendering() {
+        return false;
+    }
+}
diff --git a/packages/Keyguard/src/com/android/keyguard/EmergencyCarrierArea.java b/packages/Keyguard/src/com/android/keyguard/EmergencyCarrierArea.java
index a592db9..0a89d9b 100644
--- a/packages/Keyguard/src/com/android/keyguard/EmergencyCarrierArea.java
+++ b/packages/Keyguard/src/com/android/keyguard/EmergencyCarrierArea.java
@@ -17,13 +17,11 @@
 package com.android.keyguard;
 
 import android.content.Context;
-import android.content.res.TypedArray;
 import android.util.AttributeSet;
 import android.view.MotionEvent;
 import android.view.View;
-import android.widget.LinearLayout;
 
-public class EmergencyCarrierArea extends LinearLayout {
+public class EmergencyCarrierArea extends AlphaOptimizedLinearLayout {
 
     private CarrierText mCarrierText;
     private EmergencyButton mEmergencyButton;
diff --git a/packages/PrintSpooler/AndroidManifest.xml b/packages/PrintSpooler/AndroidManifest.xml
index adff596..c7cf61a 100644
--- a/packages/PrintSpooler/AndroidManifest.xml
+++ b/packages/PrintSpooler/AndroidManifest.xml
@@ -55,7 +55,8 @@
 
         <service
             android:name=".renderer.PdfManipulationService"
-            android:isolatedProcess="true">
+            android:isolatedProcess="true"
+            android:process=":renderer">
         </service>
 
         <activity
diff --git a/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java b/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
index 239f006..429437d 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
@@ -135,7 +135,7 @@
     private final DeathRecipient mDeathRecipient = new DeathRecipient() {
         @Override
         public void binderDied() {
-            mAdapterDeathObserver.onDied();
+            notifyPrintingAppDied();
         }
     };
 
@@ -180,7 +180,6 @@
         } catch (RemoteException re) {
             Log.e(LOG_TAG, "Error calling start()", re);
             mState = STATE_FAILED;
-            mAdapterDeathObserver.onDied();
         }
     }
 
@@ -269,7 +268,6 @@
         } catch (RemoteException re) {
             Log.e(LOG_TAG, "Error calling finish()", re);
             mState = STATE_FAILED;
-            mAdapterDeathObserver.onDied();
         }
     }
 
@@ -1108,6 +1106,15 @@
         }
     }
 
+    private void notifyPrintingAppDied() {
+        new Handler(mLooper).post(new Runnable() {
+            @Override
+            public void run() {
+                mAdapterDeathObserver.onDied();
+            }
+        });
+    }
+
     private static final class PrintDocumentAdapterObserver
             extends IPrintDocumentAdapterObserver.Stub {
         private final WeakReference<RemotePrintDocument> mWeakDocument;
@@ -1120,12 +1127,7 @@
         public void onDestroy() {
             final RemotePrintDocument document = mWeakDocument.get();
             if (document != null) {
-                new Handler(document.mLooper).post(new Runnable() {
-                    @Override
-                    public void run() {
-                        document.mAdapterDeathObserver.onDied();
-                    }
-                });
+                document.notifyPrintingAppDied();
             }
         }
     }
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/PageAdapter.java b/packages/PrintSpooler/src/com/android/printspooler/ui/PageAdapter.java
index 22a74d6..faaf0ae 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/PageAdapter.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/PageAdapter.java
@@ -164,6 +164,7 @@
     public void onOrientationChanged() {
         mColumnCount = mContext.getResources().getInteger(
                 R.integer.preview_page_per_row_count);
+        notifyDataSetChanged();
     }
 
     public boolean isOpened() {
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/PrinterRegistry.java b/packages/PrintSpooler/src/com/android/printspooler/ui/PrinterRegistry.java
index 7f48217..cbc568a 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/PrinterRegistry.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/PrinterRegistry.java
@@ -26,7 +26,6 @@
 import android.print.PrinterId;
 import android.print.PrinterInfo;
 import com.android.internal.os.SomeArgs;
-import com.android.printspooler.model.PrintSpoolerService;
 
 import java.util.ArrayList;
 import java.util.List;
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index a3bed4f..934ed38 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -193,9 +193,12 @@
     <!-- Default for Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED, 1==on -->
     <integer name="def_heads_up_enabled">1</integer>
 
-    <!-- Default for Settings.Global.DEVICE_NAME $1=BRAND $2=MODEL-->
+    <!-- Default for Settings.Global.DEVICE_NAME $1=MANUFACTURER $2=MODEL-->
     <string name="def_device_name">%1$s %2$s</string>
 
+    <!-- Default for Settings.Global.DEVICE_NAME $1=MODEL-->
+    <string name="def_device_name_simple">%1$s</string>
+
     <!-- Default for Settings.Secure.WAKE_GESTURE_ENABLED -->
     <bool name="def_wake_gesture_enabled">true</bool>
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 6d08970..873257c 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -70,7 +70,7 @@
     // database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
     // is properly propagated through your change.  Not doing so will result in a loss of user
     // settings.
-    private static final int DATABASE_VERSION = 111;
+    private static final int DATABASE_VERSION = 112;
 
     private Context mContext;
     private int mUserHandle;
@@ -1788,6 +1788,29 @@
             upgradeVersion = 111;
         }
 
+        if (upgradeVersion < 112) {
+            if (mUserHandle == UserHandle.USER_OWNER) {
+                // When device name was added, we went with Manufacturer + Model, device name should
+                // actually be Model only.
+                // Update device name to Model if it wasn't modified by user.
+                db.beginTransaction();
+                SQLiteStatement stmt = null;
+                try {
+                    stmt = db.compileStatement("UPDATE global SET value = ? "
+                        + " WHERE name = ? AND value = ?");
+                    stmt.bindString(1, getDefaultDeviceName()); // new default device name
+                    stmt.bindString(2, Settings.Global.DEVICE_NAME);
+                    stmt.bindString(3, getOldDefaultDeviceName()); // old default device name
+                    stmt.execute();
+                    db.setTransactionSuccessful();
+                } finally {
+                    db.endTransaction();
+                    if (stmt != null) stmt.close();
+                }
+            }
+            upgradeVersion = 112;
+        }
+
         // *** Remember to update DATABASE_VERSION above!
 
         if (upgradeVersion != currentVersion) {
@@ -2585,8 +2608,12 @@
         return defaultValue;
     }
 
+    private String getOldDefaultDeviceName() {
+        return mContext.getResources().getString(R.string.def_device_name,
+                Build.MANUFACTURER, Build.MODEL);
+    }
+
     private String getDefaultDeviceName() {
-        return mContext.getResources().getString(R.string.def_device_name, Build.MANUFACTURER,
-                Build.MODEL);
+        return mContext.getResources().getString(R.string.def_device_name_simple, Build.MODEL);
     }
 }
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 4ef2189..30ccd2c 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -789,8 +789,15 @@
                             Slog.v(TAG, "putting to additional user "
                                     + mManagedProfiles.get(i).id);
                         }
-                        insertForUser(Settings.Secure.CONTENT_URI, values,
-                                mManagedProfiles.get(i).id);
+                        try {
+                            insertForUser(Settings.Secure.CONTENT_URI, values,
+                                    mManagedProfiles.get(i).id);
+                        } catch (SecurityException e) {
+                            // Temporary fix, see b/17450158
+                            Slog.w(TAG, "Cannot clone request '" + request + "' with value '"
+                                    + newValue + "' to managed profile (id "
+                                    + mManagedProfiles.get(i).id + ")", e);
+                        }
                     }
                 } finally {
                     Binder.restoreCallingIdentity(token);
diff --git a/packages/SystemUI/res/drawable/ic_account_circle.xml b/packages/SystemUI/res/drawable/ic_account_circle.xml
deleted file mode 100644
index d8649e5..0000000
--- a/packages/SystemUI/res/drawable/ic_account_circle.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24dp"
-        android:height="24dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-
-    <group
-        android:scaleX="1.2"
-        android:scaleY="1.2"
-        android:pivotX="12.0"
-        android:pivotY="12.0">
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M12.0,2.0C6.5,2.0 2.0,6.5 2.0,12.0s4.5,10.0 10.0,10.0c5.5,0.0 10.0,-4.5 10.0,-10.0S17.5,2.0 12.0,2.0zM12.0,5.0c1.7,0.0 3.0,1.3 3.0,3.0c0.0,1.7 -1.3,3.0 -3.0,3.0c-1.7,0.0 -3.0,-1.3 -3.0,-3.0C9.0,6.3 10.3,5.0 12.0,5.0zM12.0,19.2c-2.5,0.0 -4.7,-1.3 -6.0,-3.2c0.0,-2.0 4.0,-3.1 6.0,-3.1c2.0,0.0 6.0,1.1 6.0,3.1C16.7,17.9 14.5,19.2 12.0,19.2z"/>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_account_circle_qs.xml b/packages/SystemUI/res/drawable/ic_account_circle_qs.xml
deleted file mode 100644
index d10a96d..0000000
--- a/packages/SystemUI/res/drawable/ic_account_circle_qs.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<!--
-  ~ Copyright (C) 2014 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
-  -->
-
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24dp"
-        android:height="24dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-
-    <group
-            android:scaleX="1.2"
-            android:scaleY="1.2"
-            android:pivotX="12.0"
-            android:pivotY="12.0">
-        <path
-                android:fillColor="@color/qs_user_detail_icon_muted"
-                android:pathData="M12.0,2.0C6.5,2.0 2.0,6.5 2.0,12.0s4.5,10.0 10.0,10.0c5.5,0.0 10.0,-4.5 10.0,-10.0S17.5,2.0 12.0,2.0zM12.0,5.0c1.7,0.0 3.0,1.3 3.0,3.0c0.0,1.7 -1.3,3.0 -3.0,3.0c-1.7,0.0 -3.0,-1.3 -3.0,-3.0C9.0,6.3 10.3,5.0 12.0,5.0zM12.0,19.2c-2.5,0.0 -4.7,-1.3 -6.0,-3.2c0.0,-2.0 4.0,-3.1 6.0,-3.1c2.0,0.0 6.0,1.1 6.0,3.1C16.7,17.9 14.5,19.2 12.0,19.2z"/>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/layout/keyguard_user_switcher.xml b/packages/SystemUI/res/layout/keyguard_user_switcher.xml
index 7c918c2..3730bbe 100644
--- a/packages/SystemUI/res/layout/keyguard_user_switcher.xml
+++ b/packages/SystemUI/res/layout/keyguard_user_switcher.xml
@@ -14,7 +14,7 @@
   ~ See the License for the specific language governing permissions and
   ~ limitations under the License
   -->
-<com.android.systemui.statusbar.AlphaOptimizedLinearLayout
+<com.android.keyguard.AlphaOptimizedLinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/keyguard_user_switcher"
         android:orientation="vertical"
@@ -23,4 +23,4 @@
         android:gravity="end"
         android:visibility="gone"
         android:paddingTop="4dp">
-</com.android.systemui.statusbar.AlphaOptimizedLinearLayout>
+</com.android.keyguard.AlphaOptimizedLinearLayout>
diff --git a/packages/SystemUI/res/layout/status_bar.xml b/packages/SystemUI/res/layout/status_bar.xml
index 0d414f9..245c128 100644
--- a/packages/SystemUI/res/layout/status_bar.xml
+++ b/packages/SystemUI/res/layout/status_bar.xml
@@ -57,7 +57,7 @@
             >
             <!-- The alpha of this area is both controlled from PhoneStatusBarTransitions and
                  PhoneStatusBar (DISABLE_NOTIFICATION_ICONS), so we need two views here. -->
-            <com.android.systemui.statusbar.AlphaOptimizedLinearLayout
+            <com.android.keyguard.AlphaOptimizedLinearLayout
                 android:id="@+id/notification_icon_area_inner"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
@@ -74,10 +74,10 @@
                     android:layout_alignParentStart="true"
                     android:gravity="center_vertical"
                     android:orientation="horizontal"/>
-            </com.android.systemui.statusbar.AlphaOptimizedLinearLayout>
+            </com.android.keyguard.AlphaOptimizedLinearLayout>
         </com.android.systemui.statusbar.AlphaOptimizedFrameLayout>
 
-        <com.android.systemui.statusbar.AlphaOptimizedLinearLayout android:id="@+id/system_icon_area"
+        <com.android.keyguard.AlphaOptimizedLinearLayout android:id="@+id/system_icon_area"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             android:orientation="horizontal"
@@ -94,7 +94,7 @@
                 android:paddingStart="7dp"
                 android:gravity="center_vertical|start"
                 />
-        </com.android.systemui.statusbar.AlphaOptimizedLinearLayout>
+        </com.android.keyguard.AlphaOptimizedLinearLayout>
     </LinearLayout>
 
     <ViewStub
diff --git a/packages/SystemUI/res/layout/status_bar_expanded_header.xml b/packages/SystemUI/res/layout/status_bar_expanded_header.xml
index 34e062c..7ea9145 100644
--- a/packages/SystemUI/res/layout/status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/status_bar_expanded_header.xml
@@ -44,7 +44,7 @@
             android:scaleType="centerInside"/>
     </com.android.systemui.statusbar.phone.MultiUserSwitch>
 
-    <ImageButton android:id="@+id/settings_button"
+    <com.android.keyguard.AlphaOptimizedImageButton android:id="@+id/settings_button"
         style="@android:style/Widget.Material.Button.Borderless"
         android:layout_toStartOf="@id/multi_user_switch"
         android:layout_width="48dp"
diff --git a/packages/SystemUI/res/layout/system_icons.xml b/packages/SystemUI/res/layout/system_icons.xml
index 8f25d99..21386ef 100644
--- a/packages/SystemUI/res/layout/system_icons.xml
+++ b/packages/SystemUI/res/layout/system_icons.xml
@@ -20,7 +20,7 @@
     android:layout_height="match_parent"
     android:gravity="center_vertical">
 
-    <com.android.systemui.statusbar.AlphaOptimizedLinearLayout android:id="@+id/statusIcons"
+    <com.android.keyguard.AlphaOptimizedLinearLayout android:id="@+id/statusIcons"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:gravity="center_vertical"
diff --git a/packages/SystemUI/res/values-h650dp/config.xml b/packages/SystemUI/res/values-h650dp/config.xml
new file mode 100644
index 0000000..ee641b4
--- /dev/null
+++ b/packages/SystemUI/res/values-h650dp/config.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2014 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
+  -->
+
+<resources>
+    <!-- The maximum count of notifications on Keyguard. The rest will be collapsed in an overflow
+     card. -->
+    <integer name="keyguard_max_notification_count">5</integer>
+</resources>
+
diff --git a/packages/SystemUI/res/values-h650dp/dimens.xml b/packages/SystemUI/res/values-h650dp/dimens.xml
new file mode 100644
index 0000000..fbfca46
--- /dev/null
+++ b/packages/SystemUI/res/values-h650dp/dimens.xml
@@ -0,0 +1,23 @@
+<!--
+  ~ Copyright (C) 2014 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
+  -->
+
+<resources>
+    <dimen name="keyguard_clock_notifications_margin_min">32dp</dimen>
+    <dimen name="keyguard_clock_notifications_margin_max">36dp</dimen>
+
+    <fraction name="keyguard_clock_y_fraction_max">32.5%</fraction>
+    <fraction name="keyguard_clock_y_fraction_min">18.5%</fraction>
+</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index f899572..cc77aaa 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -188,9 +188,6 @@
     <!-- Doze: should the pickup sensor be used as a pulse signal? -->
     <bool name="doze_pulse_on_pick_up">false</bool>
 
-    <!-- Doze: maximum brightness to use when pulsing -->
-    <integer name="doze_pulse_brightness">40</integer>
-
     <!-- Doze: period of time between pulses (start of pulse) when following the notification light
          Format: <under_ms>:<period_ms>,...,<default_ms> -->
     <string name="doze_pulse_period_function">60000:10000,300000:30000,1800000:60000,0</string>
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
index 1183582..f411e62 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
@@ -16,9 +16,6 @@
 
 package com.android.systemui.doze;
 
-import static android.os.PowerManager.BRIGHTNESS_OFF;
-import static android.os.PowerManager.BRIGHTNESS_ON;
-
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
@@ -37,7 +34,6 @@
 import android.os.Vibrator;
 import android.service.dreams.DreamService;
 import android.util.Log;
-import android.util.MathUtils;
 import android.view.Display;
 
 import com.android.systemui.R;
@@ -68,7 +64,6 @@
     private PowerManager mPowerManager;
     private PowerManager.WakeLock mWakeLock;
     private AlarmManager mAlarmManager;
-    private int mMaxBrightness;
     private boolean mDreaming;
     private boolean mBroadcastReceiverRegistered;
     private boolean mDisplayStateSupported;
@@ -91,7 +86,6 @@
         pw.print("  mBroadcastReceiverRegistered: "); pw.println(mBroadcastReceiverRegistered);
         pw.print("  mSigMotionSensor: "); pw.println(mSigMotionSensor);
         pw.print("  mPickupSensor:"); pw.println(mPickupSensor);
-        pw.print("  mMaxBrightness: "); pw.println(mMaxBrightness);
         pw.print("  mDisplayStateSupported: "); pw.println(mDisplayStateSupported);
         pw.print("  mNotificationLightOn: "); pw.println(mNotificationLightOn);
         pw.print("  mPowerSaveActive: "); pw.println(mPowerSaveActive);
@@ -123,8 +117,6 @@
         final Resources res = mContext.getResources();
         mDisplayStateSupported = SystemProperties.getBoolean("doze.display.supported",
                 res.getBoolean(R.bool.doze_display_state_supported));
-        mMaxBrightness = MathUtils.constrain(res.getInteger(R.integer.doze_pulse_brightness),
-                BRIGHTNESS_OFF, BRIGHTNESS_ON);
         mNotificationPulseIntent = PendingIntent.getBroadcast(mContext, 0,
                 new Intent(NOTIFICATION_PULSE_ACTION).setPackage(getPackageName()),
                 PendingIntent.FLAG_UPDATE_CURRENT);
@@ -158,7 +150,6 @@
             if (DEBUG) Log.d(mTag, "stayAwake millis=" + millis);
             mWakeLock.acquire(millis);
             setDozeScreenState(mDisplayStateWhenOn);
-            setDozeScreenBrightness(mMaxBrightness);
             rescheduleOff(millis);
         }
     }
@@ -295,7 +286,6 @@
         public void run() {
             if (DEBUG) Log.d(TAG, "Display off");
             setDozeScreenState(Display.STATE_OFF);
-            setDozeScreenBrightness(PowerManager.BRIGHTNESS_DEFAULT);
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index f7e0c83..ce3739c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -92,6 +92,7 @@
 import com.android.systemui.SystemUI;
 import com.android.systemui.statusbar.NotificationData.Entry;
 import com.android.systemui.statusbar.phone.KeyguardTouchDelegate;
+import com.android.systemui.statusbar.phone.PhoneStatusBar;
 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
 import com.android.systemui.statusbar.policy.HeadsUpNotificationView;
 import com.android.systemui.statusbar.policy.PreviewInflater;
@@ -288,6 +289,10 @@
 
                         // close the shade if it was open
                         if (handled) {
+                            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                                Log.i(TAG, "Collapsing panel from mOnClickHandler after keyguard"
+                                        + "dismiss");
+                            }
                             animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
                             visibilityChanged(false);
                         }
@@ -334,6 +339,9 @@
                 Settings.Secure.putInt(mContext.getContentResolver(),
                         Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
                 if (BANNER_ACTION_SETUP.equals(action)) {
+                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                        Log.i(TAG, "Animating collapse because of BANNER_ACTION_SETUP");
+                    }
                     animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
                     mContext.startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_REDACTION)
                             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -759,6 +767,10 @@
                         }
                     }
                 });
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Collapsing panel from startNotificationGutsIntent after keyguard"
+                            + "dismiss");
+                }
                 animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
                 return true;
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index e84ca52..20eed3f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -128,6 +128,9 @@
         public boolean performAccessibilityAction(View host, int action, Bundle args) {
             if (action == ACTION_CLICK) {
                 if (host == mLockIcon) {
+                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                        Log.i(TAG, "Collapsing panel from lock icon accessibility click");
+                    }
                     mPhoneStatusBar.animateCollapsePanels(
                             CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
                     return true;
@@ -373,7 +376,8 @@
             return;
         }
         // TODO: Real icon for facelock.
-        int iconRes = mUnlockMethodCache.isFaceUnlockRunning() ? R.drawable.ic_account_circle
+        int iconRes = mUnlockMethodCache.isFaceUnlockRunning()
+                ? com.android.internal.R.drawable.ic_account_circle
                 : mUnlockMethodCache.isMethodInsecure() ? R.drawable.ic_lock_open_24dp
                 : R.drawable.ic_lock_24dp;
         mLockIcon.setImageResource(iconRes);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelBar.java
index f74d2f4..ccafbd1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelBar.java
@@ -140,6 +140,9 @@
         mPanelHolder.setSelectedPanel(mTouchingPanel);
         for (PanelView pv : mPanels) {
             if (pv != panel) {
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Collapsing because opening another panel");
+                }
                 pv.collapse(false /* delayed */);
             }
         }
@@ -191,9 +194,15 @@
         boolean waiting = false;
         for (PanelView pv : mPanels) {
             if (animate && !pv.isFullyCollapsed()) {
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Animating collapse, delayed");
+                }
                 pv.collapse(true /* delayed */);
                 waiting = true;
             } else {
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Collapsing without animation");
+                }
                 pv.resetViews();
                 pv.setExpandedFraction(0); // just in case
                 pv.setVisibility(View.GONE);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 006e480..873d528 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -86,6 +86,7 @@
     private String mViewName;
     private float mInitialTouchY;
     private float mInitialTouchX;
+    private boolean mTouchDisabled;
 
     private Interpolator mLinearOutSlowInInterpolator;
     private Interpolator mFastOutSlowInInterpolator;
@@ -134,6 +135,9 @@
     }
 
     private void runPeekAnimation() {
+        if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+            Log.i(TAG, "Starting peek animation");
+        }
         mPeekHeight = getPeekHeight();
         if (DEBUG) logf("peek to height=%.1f", mPeekHeight);
         if (mHeightAnimator != null) {
@@ -154,9 +158,15 @@
             public void onAnimationEnd(Animator animation) {
                 mPeekAnimator = null;
                 if (mCollapseAfterPeek && !mCancelled) {
+                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                        Log.i(TAG, "Peek animation finished, posting collapse");
+                    }
                     postOnAnimation(new Runnable() {
                         @Override
                         public void run() {
+                            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                                Log.i(TAG, "Peek animation finished, collapsing");
+                            }
                             collapse(false /* delayed */);
                         }
                     });
@@ -198,9 +208,13 @@
         event.offsetLocation(-deltaX, -deltaY);
     }
 
+    public void setTouchDisabled(boolean disabled) {
+        mTouchDisabled = disabled;
+    }
+
     @Override
     public boolean onTouchEvent(MotionEvent event) {
-        if (mInstantExpanding) {
+        if (mInstantExpanding || mTouchDisabled) {
             return false;
         }
 
@@ -330,6 +344,9 @@
                     }
                     boolean expand = flingExpands(vel, vectorVel);
                     onTrackingStopped(expand);
+                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                        Log.i(TAG, "Flinging: expand=" + expand);
+                    }
                     fling(vel, expand);
                     mUpdateFlingOnLayout = expand && mPanelClosedOnDown && !mHasLayoutedSinceDown;
                     if (mUpdateFlingOnLayout) {
@@ -510,6 +527,9 @@
             notifyExpandingFinished();
             return;
         }
+        if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+            Log.i(TAG, "Executing fling: expand=" + expand + " vel=" + vel);
+        }
         mOverExpandedBeforeFling = getOverExpansionAmount() > 0f;
         ValueAnimator animator = createHeightAnimator(target);
         if (expand) {
@@ -691,8 +711,14 @@
             mClosing = true;
             notifyExpandingStarted();
             if (delayed) {
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Posting collapse runnable, will be run in 120ms");
+                }
                 postDelayed(mFlingCollapseRunnable, 120);
             } else {
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Animating collapsing now");
+                }
                 fling(0, false /* expand */);
             }
         }
@@ -701,6 +727,9 @@
     private final Runnable mFlingCollapseRunnable = new Runnable() {
         @Override
         public void run() {
+            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                Log.i(TAG, "Executing collapse runnable, animating collapsing now");
+            }
             fling(0, false /* expand */);
         }
     };
@@ -729,6 +758,11 @@
     }
 
     public void instantExpand() {
+        if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+            Log.i(TAG, "Before instant expanding"
+                    + " mTracking=" + mTracking
+                    + " mExpanding=" + mExpanding);
+        }
         mInstantExpanding = true;
         mUpdateFlingOnLayout = false;
         abortAnimations();
@@ -749,6 +783,11 @@
                     public void onGlobalLayout() {
                         if (mStatusBar.getStatusBarWindow().getHeight()
                                 != mStatusBar.getStatusBarHeight()) {
+                            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                                Log.i(TAG, "Now instant expanding after layout"
+                                        + " mTracking=" + mTracking
+                                        + " mExpanding=" + mExpanding);
+                            }
                             getViewTreeObserver().removeOnGlobalLayoutListener(this);
                             setExpandedFraction(1f);
                             mInstantExpanding = false;
@@ -895,6 +934,9 @@
     private final Runnable mPostCollapseRunnable = new Runnable() {
         @Override
         public void run() {
+            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                Log.i(TAG, "Collapsing after middle clicked");
+            }
             collapse(false /* delayed */);
         }
     };
@@ -907,6 +949,9 @@
                 mStatusBar.goToKeyguard();
                 return true;
             case StatusBarState.SHADE:
+                if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Middle clicked in shade state, posting collapsing runnable");
+                }
 
                 // This gets called in the middle of the touch handling, where the state is still
                 // that we are tracking the panel. Collapse the panel after this is done.
@@ -921,7 +966,7 @@
 
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
-                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
+                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s touchDisabled=%s"
                 + "]",
                 this.getClass().getSimpleName(),
                 getExpandedHeight(),
@@ -930,7 +975,8 @@
                 mTracking?"T":"f",
                 mJustPeeked?"T":"f",
                 mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
-                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
+                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":""),
+                mTouchDisabled?"T":"f"
         ));
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 271383f..3bdae47 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -177,6 +177,7 @@
     public static final boolean DEBUG_GESTURES = false;
     public static final boolean DEBUG_MEDIA = false;
     public static final boolean DEBUG_MEDIA_FAKE_ARTWORK = false;
+    public static final boolean DEBUG_EMPTY_KEYGUARD = true;
 
     public static final boolean DEBUG_WINDOW_STATE = false;
 
@@ -403,6 +404,12 @@
     private int mNavigationBarMode;
     private Boolean mScreenOn;
 
+    // The second field is a bit different from the first one because it only listens to screen on/
+    // screen of events from Keyguard. We need this so we don't have a race condition with the
+    // broadcast. In the future, we should remove the first field altogether and rename the second
+    // field.
+    private boolean mScreenOnFromKeyguard;
+
     private ViewMediatorCallback mKeyguardViewMediatorCallback;
     private ScrimController mScrimController;
 
@@ -2238,6 +2245,11 @@
             mStatusBarWindowManager.setStatusBarFocusable(false);
 
             mStatusBarWindow.cancelExpandHelper();
+            if (DEBUG_EMPTY_KEYGUARD) {
+                Log.i(TAG, "Collapsing panel from animateCollapsePanels:"
+                        + " force=" + force
+                        + " mState=" + mState);
+            }
             mStatusBarView.collapseAllPanels(true);
         }
     }
@@ -2325,6 +2337,9 @@
     }
 
     public void animateCollapseQuickSettings() {
+        if (DEBUG_EMPTY_KEYGUARD) {
+            Log.i(TAG, "Collapsing panel from animateCollapseQuickSettings");
+        }
         mStatusBarView.collapseAllPanels(true);
     }
 
@@ -2337,6 +2352,9 @@
         }
 
         // Ensure the panel is fully collapsed (just in case; bug 6765842, 7260868)
+        if (DEBUG_EMPTY_KEYGUARD) {
+            Log.i(TAG, "Collapsing panel from makeExpandedInvisible");
+        }
         mStatusBarView.collapseAllPanels(/*animate=*/ false);
 
         // reset things to their proper state
@@ -2430,6 +2448,9 @@
             mStatusBarWindowState = state;
             if (DEBUG_WINDOW_STATE) Log.d(TAG, "Status bar " + windowStateToString(state));
             if (!showing) {
+                if (DEBUG_EMPTY_KEYGUARD) {
+                    Log.i(TAG, "Collapsing panel from setWindowState");
+                }
                 mStatusBarView.collapseAllPanels(false);
             }
         }
@@ -2987,6 +3008,10 @@
                     }
                 });
                 if (dismissShade) {
+                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                        Log.i(TAG, "Collapsing panel startActivityDismissKeyguard after keyguard"
+                                + "dismiss");
+                    }
                     animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
                 }
                 return true;
@@ -3447,6 +3472,13 @@
     public void showKeyguard() {
         setBarState(StatusBarState.KEYGUARD);
         updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
+        if (!mScreenOnFromKeyguard) {
+
+            // If the screen is off already, we need to disable touch events because these might
+            // collapse the panel after we expanded it, and thus we would end up with a blank
+            // Keyguard.
+            mNotificationPanel.setTouchDisabled(true);
+        }
         instantExpandNotificationsPanel();
         mLeaveOpenOnKeyguardHide = false;
         if (mDraggedDownRow != null) {
@@ -3654,6 +3686,9 @@
     public boolean onSpacePressed() {
         if (mScreenOn != null && mScreenOn
                 && (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED)) {
+            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
+                Log.i(TAG, "Collapsing panel from onSpacePressed");
+            }
             animateCollapsePanels(0 /* flags */, true /* force */);
             return true;
         }
@@ -3848,12 +3883,15 @@
     }
 
     public void onScreenTurnedOff() {
+        mScreenOnFromKeyguard = false;
         mStackScroller.setAnimationsEnabled(false);
     }
 
     public void onScreenTurnedOn() {
+        mScreenOnFromKeyguard = true;
         mStackScroller.setAnimationsEnabled(true);
         mNotificationPanel.onScreenTurnedOn();
+        mNotificationPanel.setTouchDisabled(false);
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserInfoController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserInfoController.java
index 8cbe272..d50e39f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserInfoController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserInfoController.java
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.policy;
 
 import android.app.ActivityManagerNative;
-import android.bluetooth.BluetoothAdapter;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
@@ -26,33 +25,21 @@
 import android.content.pm.UserInfo;
 import android.database.Cursor;
 import android.graphics.Bitmap;
-import android.graphics.BitmapShader;
-import android.graphics.Canvas;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffXfermode;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.Shader;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
-import android.hardware.display.DisplayManager;
 import android.os.AsyncTask;
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.ContactsContract;
-import android.security.KeyChain;
 import android.util.Log;
 import android.util.Pair;
 
-import com.android.internal.view.RotationPolicy;
 import com.android.systemui.BitmapHelper;
 import com.android.systemui.R;
+import com.android.internal.util.UserIcons;
 
 import java.util.ArrayList;
-import java.util.concurrent.CopyOnWriteArrayList;
 
 public final class UserInfoController {
 
@@ -142,6 +129,7 @@
             throw new RuntimeException(e);
         }
         final int userId = userInfo.id;
+        final boolean isGuest = userInfo.isGuest();
         final String userName = userInfo.name;
         final int avatarSize
                 = mContext.getResources().getDimensionPixelSize(R.dimen.max_avatar_size);
@@ -161,7 +149,8 @@
                     avatar = new BitmapDrawable(mContext.getResources(),
                             BitmapHelper.createCircularClip(rawAvatar, avatarSize, avatarSize));
                 } else {
-                    avatar = mContext.getResources().getDrawable(R.drawable.ic_account_circle);
+                    avatar = UserIcons.getDefaultUserIcon(isGuest? UserHandle.USER_NULL : userId,
+                            /* light= */ true);
                     mUseDefaultAvatar = true;
                 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index d02826f..e8f35fd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -16,13 +16,6 @@
 
 package com.android.systemui.statusbar.policy;
 
-import com.android.systemui.BitmapHelper;
-import com.android.systemui.GuestResumeSessionReceiver;
-import com.android.systemui.R;
-import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.tiles.UserDetailView;
-import com.android.systemui.statusbar.phone.SystemUIDialog;
-
 import android.app.ActivityManager;
 import android.app.ActivityManagerNative;
 import android.app.Dialog;
@@ -45,9 +38,16 @@
 import android.util.SparseArray;
 import android.view.View;
 import android.view.ViewGroup;
-import android.view.WindowManagerGlobal;
 import android.widget.BaseAdapter;
 
+import com.android.internal.util.UserIcons;
+import com.android.systemui.BitmapHelper;
+import com.android.systemui.GuestResumeSessionReceiver;
+import com.android.systemui.R;
+import com.android.systemui.qs.QSTile;
+import com.android.systemui.qs.tiles.UserDetailView;
+import com.android.systemui.statusbar.phone.SystemUIDialog;
+
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.lang.ref.WeakReference;
@@ -425,7 +425,8 @@
             if (item.isAddUser) {
                 return context.getDrawable(R.drawable.ic_add_circle_qs);
             }
-            return context.getDrawable(R.drawable.ic_account_circle_qs);
+            return UserIcons.getDefaultUserIcon(item.isGuest ? UserHandle.USER_NULL : item.info.id,
+                    /* light= */ true);
         }
     }
 
@@ -565,6 +566,9 @@
                 dismiss();
                 int id = mUserManager.createUser(
                         mContext.getString(R.string.user_new_user_name), 0 /* flags */).id;
+                Bitmap icon = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(
+                        id, /* light= */ false));
+                mUserManager.setUserIcon(id, icon);
                 switchToUserId(id);
             }
         }
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index f802e1e..92171c1 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -150,6 +150,8 @@
     // mDecor itself, or a child of mDecor where the contents go.
     private ViewGroup mContentParent;
 
+    private ViewGroup mContentRoot;
+
     SurfaceHolder.Callback2 mTakeSurfaceCallback;
 
     InputQueue.Callback mTakeInputQueueCallback;
@@ -2154,6 +2156,7 @@
 
         private int mLastTopInset = 0;
         private int mLastBottomInset = 0;
+        private int mLastRightInset = 0;
         private int mLastSystemUiVisibility = 0;
 
 
@@ -2732,7 +2735,7 @@
         @Override
         public WindowInsets onApplyWindowInsets(WindowInsets insets) {
             mFrameOffsets.set(insets.getSystemWindowInsets());
-            updateColorViews(insets);
+            insets = updateColorViews(insets);
             insets = updateStatusGuard(insets);
             updateNavigationGuard(insets);
             if (getForeground() != null) {
@@ -2749,8 +2752,12 @@
         private WindowInsets updateColorViews(WindowInsets insets) {
             if (!mIsFloating && ActivityManager.isHighEndGfx()) {
                 if (insets != null) {
-                    mLastTopInset = insets.getStableInsetTop();
-                    mLastBottomInset = insets.getStableInsetBottom();
+                    mLastTopInset = Math.min(insets.getStableInsetTop(),
+                            insets.getSystemWindowInsetTop());
+                    mLastBottomInset = Math.min(insets.getStableInsetBottom(),
+                            insets.getSystemWindowInsetBottom());
+                    mLastRightInset = Math.min(insets.getStableInsetRight(),
+                            insets.getSystemWindowInsetRight());
                 }
                 mStatusColorView = updateColorViewInt(mStatusColorView,
                         SYSTEM_UI_FLAG_FULLSCREEN, FLAG_TRANSLUCENT_STATUS,
@@ -2765,8 +2772,39 @@
                         com.android.internal.R.id.navigationBarBackground,
                         false /* hiddenByWindowFlag */);
             }
+
+            WindowManager.LayoutParams attrs = getAttributes();
+            int sysUiVisibility = attrs.systemUiVisibility | attrs.subtreeSystemUiVisibility;
+
+            // When we expand the window with FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS, we still need
+            // to ensure that the rest of the view hierarchy doesn't notice it, unless they've
+            // explicitly asked for it.
+
+            boolean consumingNavBar =
+                    (attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
+                            && (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0
+                            && (mLastSystemUiVisibility & SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
+
+            int consumedRight = consumingNavBar ? mLastRightInset : 0;
+            int consumedBottom = consumingNavBar ? mLastBottomInset : 0;
+
+            if (mContentRoot != null
+                    && mContentRoot.getLayoutParams() instanceof MarginLayoutParams) {
+                MarginLayoutParams lp = (MarginLayoutParams) mContentRoot.getLayoutParams();
+                if (lp.rightMargin != consumedRight || lp.bottomMargin != consumedBottom) {
+                    lp.rightMargin = consumedRight;
+                    lp.bottomMargin = consumedBottom;
+                    mContentRoot.setLayoutParams(lp);
+                }
+            }
+
             if (insets != null) {
-                insets = insets.consumeStableInsets();
+                insets = insets.consumeStableInsets().replaceSystemWindowInsets(
+                        insets.getSystemWindowInsetLeft(),
+                        insets.getSystemWindowInsetTop(),
+                        insets.getSystemWindowInsetRight() - consumedRight,
+                        insets.getSystemWindowInsetBottom() - consumedBottom
+                );
             }
             return insets;
         }
@@ -3381,6 +3419,7 @@
 
         View in = mLayoutInflater.inflate(layoutResource, null);
         decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
+        mContentRoot = (ViewGroup) in;
 
         ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
         if (contentParent == null) {
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 9daa190..4713a98 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -439,6 +439,7 @@
 
     WindowState mTopFullscreenOpaqueWindowState;
     HashSet<IApplicationToken> mAppsToBeHidden = new HashSet<IApplicationToken>();
+    HashSet<IApplicationToken> mAppsThatDismissKeyguard = new HashSet<IApplicationToken>();
     boolean mTopIsFullscreen;
     boolean mForceStatusBar;
     boolean mForceStatusBarFromKeyguard;
@@ -1520,8 +1521,7 @@
 
         if (ActivityManager.isHighEndGfx()
                 && (attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
-            attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE
-                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+            attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                     | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
         }
     }
@@ -1758,6 +1758,11 @@
         }
     }
 
+    @Override
+    public WindowState getWinShowWhenLockedLw() {
+        return mWinShowWhenLocked;
+    }
+
     /** {@inheritDoc} */
     @Override
     public View addStartingWindow(IBinder appToken, String packageName, int theme,
@@ -3751,6 +3756,7 @@
     public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
         mTopFullscreenOpaqueWindowState = null;
         mAppsToBeHidden.clear();
+        mAppsThatDismissKeyguard.clear();
         mForceStatusBar = false;
         mForceStatusBarFromKeyguard = false;
         mForcingShowNavBar = false;
@@ -3791,7 +3797,7 @@
                 mShowingLockscreen = true;
             }
             boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
-                    && attrs.type <= LAST_APPLICATION_WINDOW;
+                    && attrs.type < FIRST_SYSTEM_WINDOW;
             if (attrs.type == TYPE_DREAM) {
                 // If the lockscreen was showing when the dream started then wait
                 // for the dream to draw before hiding the lockscreen.
@@ -3806,38 +3812,44 @@
             final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
             final boolean secureKeyguard = isKeyguardSecure();
             if (appWindow) {
-                if (showWhenLocked || (dismissKeyguard && !secureKeyguard)) {
+                final IApplicationToken appToken = win.getAppToken();
+                if (showWhenLocked) {
                     // Remove any previous windows with the same appToken.
-                    mAppsToBeHidden.remove(win.getAppToken());
-                    if (mAppsToBeHidden.isEmpty() && showWhenLocked &&
-                            isKeyguardSecureIncludingHidden()) {
+                    mAppsToBeHidden.remove(appToken);
+                    mAppsThatDismissKeyguard.remove(appToken);
+                    if (mAppsToBeHidden.isEmpty() && isKeyguardSecureIncludingHidden()) {
                         mWinShowWhenLocked = win;
                         mHideLockScreen = true;
                         mForceStatusBarFromKeyguard = false;
                     }
+                } else if (dismissKeyguard) {
+                    if (secureKeyguard) {
+                        mAppsToBeHidden.add(appToken);
+                    } else {
+                        mAppsToBeHidden.remove(appToken);
+                    }
+                    mAppsThatDismissKeyguard.add(appToken);
                 } else {
-                    mAppsToBeHidden.add(win.getAppToken());
+                    mAppsToBeHidden.add(appToken);
                 }
                 if (attrs.x == 0 && attrs.y == 0
                         && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
                         && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
                     if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
                     mTopFullscreenOpaqueWindowState = win;
-                    if (mAppsToBeHidden.isEmpty()) {
-                        if (showWhenLocked) {
-                            if (DEBUG_LAYOUT) Slog.v(TAG,
-                                    "Setting mHideLockScreen to true by win " + win);
-                            mHideLockScreen = true;
-                            mForceStatusBarFromKeyguard = false;
-                        }
-                        if (dismissKeyguard && mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
-                            if (DEBUG_LAYOUT) Slog.v(TAG,
-                                    "Setting mDismissKeyguard true by win " + win);
-                            mDismissKeyguard = mWinDismissingKeyguard == win ?
-                                    DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
-                            mWinDismissingKeyguard = win;
-                            mForceStatusBarFromKeyguard = mShowingLockscreen && secureKeyguard;
-                        }
+                    if (!mAppsThatDismissKeyguard.isEmpty() &&
+                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
+                        if (DEBUG_LAYOUT) Slog.v(TAG,
+                                "Setting mDismissKeyguard true by win " + win);
+                        mDismissKeyguard = mWinDismissingKeyguard == win ?
+                                DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
+                        mWinDismissingKeyguard = win;
+                        mForceStatusBarFromKeyguard = mShowingLockscreen && secureKeyguard;
+                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked) {
+                        if (DEBUG_LAYOUT) Slog.v(TAG,
+                                "Setting mHideLockScreen to true by win " + win);
+                        mHideLockScreen = true;
+                        mForceStatusBarFromKeyguard = false;
                     }
                     if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
                         mAllowLockscreenWhenOn = true;
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index b04cc19..7716385 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -127,6 +127,7 @@
     long mLastAlarmDeliveryTime;
     long mStartCurrentDelayTime;
     long mNextNonWakeupDeliveryTime;
+    int mNumTimeChanged;
 
     private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
             new SparseArray<>();
@@ -821,6 +822,7 @@
                     pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
             pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
                     pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
+            pw.print("Num time change events: "); pw.println(mNumTimeChanged);
 
             if (mAlarmBatches.size() > 0) {
                 pw.println();
@@ -1619,6 +1621,9 @@
                     removeImpl(mTimeTickSender);
                     rebatchAllAlarms();
                     mClockReceiver.scheduleTimeTickEvent();
+                    synchronized (mLock) {
+                        mNumTimeChanged++;
+                    }
                     Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
                             | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
diff --git a/services/core/java/com/android/server/AppOpsService.java b/services/core/java/com/android/server/AppOpsService.java
index ef6e07c..c3465d1 100644
--- a/services/core/java/com/android/server/AppOpsService.java
+++ b/services/core/java/com/android/server/AppOpsService.java
@@ -631,7 +631,7 @@
     @Override
     public int checkPackage(int uid, String packageName) {
         synchronized (this) {
-            if (getOpsLocked(uid, packageName, true) != null) {
+            if (getOpsRawLocked(uid, packageName, true) != null) {
                 return AppOpsManager.MODE_ALLOWED;
             } else {
                 return AppOpsManager.MODE_ERRORED;
@@ -769,6 +769,15 @@
     }
 
     private Ops getOpsLocked(int uid, String packageName, boolean edit) {
+        if (uid == 0) {
+            packageName = "root";
+        } else if (uid == Process.SHELL_UID) {
+            packageName = "com.android.shell";
+        }
+        return getOpsRawLocked(uid, packageName, edit);
+    }
+
+    private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
         HashMap<String, Ops> pkgOps = mUidOps.get(uid);
         if (pkgOps == null) {
             if (!edit) {
@@ -777,11 +786,6 @@
             pkgOps = new HashMap<String, Ops>();
             mUidOps.put(uid, pkgOps);
         }
-        if (uid == 0) {
-            packageName = "root";
-        } else if (uid == Process.SHELL_UID) {
-            packageName = "com.android.shell";
-        }
         Ops ops = pkgOps.get(packageName);
         if (ops == null) {
             if (!edit) {
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 75090db..7f104c0 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -251,7 +251,7 @@
 
     private Context mContext;
     private int mNetworkPreference;
-    private int mActiveDefaultNetwork = -1;
+    private int mActiveDefaultNetwork = TYPE_NONE;
     // 0 is full bad, 100 is full good
     private int mDefaultInetConditionPublished = 0;
 
@@ -886,15 +886,6 @@
         return getNetworkInfo(mActiveDefaultNetwork, uid);
     }
 
-    // only called when the default request is satisfied
-    private void updateActiveDefaultNetwork(NetworkAgentInfo nai) {
-        if (nai != null) {
-            mActiveDefaultNetwork = nai.networkInfo.getType();
-        } else {
-            mActiveDefaultNetwork = TYPE_NONE;
-        }
-    }
-
     /**
      * Find the first Provisioning network.
      *
@@ -1936,7 +1927,9 @@
                 case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
                     NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
                     if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
-                        handleConnectionValidated(nai);
+                        if (DBG) log("Validated " + nai.name());
+                        nai.validated = true;
+                        rematchNetworkAndRequests(nai);
                     }
                     break;
                 }
@@ -2057,7 +2050,7 @@
                     if (nri.isRequest == false) continue;
                     NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
                     ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
-                            (nai != null ? nai.currentScore : 0), 0, nri.request);
+                            (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
                 }
             } else {
                 loge("Error connecting NetworkFactory");
@@ -2136,7 +2129,7 @@
                                 request.networkCapabilities.satisfiedByNetworkCapabilities(
                                 existing.networkCapabilities) &&
                                 (alternative == null ||
-                                 alternative.currentScore < existing.currentScore)) {
+                                 alternative.getCurrentScore() < existing.getCurrentScore())) {
                             alternative = existing;
                         }
                     }
@@ -2169,8 +2162,9 @@
         for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
             if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
             if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
-                if (DBG) log("apparently satisfied.  currentScore=" + network.currentScore);
-                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
+                if (DBG) log("apparently satisfied.  currentScore=" + network.getCurrentScore());
+                if ((bestNetwork == null) ||
+                        bestNetwork.getCurrentScore() < network.getCurrentScore()) {
                     if (!nri.isRequest) {
                         // Not setting bestNetwork here as a listening NetworkRequest may be
                         // satisfied by multiple Networks.  Instead the request is added to
@@ -2194,7 +2188,7 @@
             bestNetwork.addRequest(nri.request);
             mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
             notifyNetworkCallback(bestNetwork, nri);
-            score = bestNetwork.currentScore;
+            score = bestNetwork.getCurrentScore();
             if (nri.request.legacyType != TYPE_NONE) {
                 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
             }
@@ -4516,19 +4510,34 @@
         updateTcpBufferSizes(newNetwork);
     }
 
-    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
-        if (newNetwork == null) {
-            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
-            return;
-        }
-        if (newNetwork.validated) return;
-        newNetwork.validated = true;
+    // Handles a network appearing or improving its score.
+    //
+    // - Evaluates all current NetworkRequests that can be
+    //   satisfied by newNetwork, and reassigns to newNetwork
+    //   any such requests for which newNetwork is the best.
+    //
+    // - Tears down any Networks that as a result are no longer
+    //   needed. A network is needed if it is the best network for
+    //   one or more NetworkRequests, or if it is a VPN.
+    //
+    // - Tears down newNetwork if it is validated but turns out to be
+    //   unneeded. Does not tear down newNetwork if it is
+    //   unvalidated, because future validation may improve
+    //   newNetwork's score enough that it is needed.
+    //
+    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
+    // it does not remove NetworkRequests that other Networks could better satisfy.
+    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
+    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
+    // as it performs better by a factor of the number of Networks.
+    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork) {
         boolean keep = newNetwork.isVPN();
         boolean isNewDefault = false;
-        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
-        // check if any NetworkRequest wants this NetworkAgent
+        if (DBG) log("rematching " + newNetwork.name());
+        // Find and migrate to this Network any NetworkRequests for
+        // which this network is now the best.
         ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
-        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
+        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
         for (NetworkRequestInfo nri : mNetworkRequests.values()) {
             NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
             if (newNetwork == currentNetwork) {
@@ -4543,18 +4552,21 @@
             if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
                     newNetwork.networkCapabilities)) {
                 if (!nri.isRequest) {
+                    // This is not a request, it's a callback listener.
+                    // Add it to newNetwork regardless of score.
                     newNetwork.addRequest(nri.request);
                     continue;
                 }
+
                 // next check if it's better than any current network we're using for
                 // this request
                 if (VDBG) {
                     log("currentScore = " +
-                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
-                            ", newScore = " + newNetwork.currentScore);
+                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
+                            ", newScore = " + newNetwork.getCurrentScore());
                 }
                 if (currentNetwork == null ||
-                        currentNetwork.currentScore < newNetwork.currentScore) {
+                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
                     if (currentNetwork != null) {
                         if (DBG) log("   accepting network in place of " + currentNetwork.name());
                         currentNetwork.networkRequests.remove(nri.request.requestId);
@@ -4569,13 +4581,16 @@
                         mLegacyTypeTracker.add(nri.request.legacyType, newNetwork);
                     }
                     keep = true;
+                    // Tell NetworkFactories about the new score, so they can stop
+                    // trying to connect if they know they cannot match it.
                     // TODO - this could get expensive if we have alot of requests for this
                     // network.  Think about if there is a way to reduce this.  Push
                     // netid->request mapping to each factory?
-                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
+                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
                     if (mDefaultRequest.requestId == nri.request.requestId) {
                         isNewDefault = true;
-                        updateActiveDefaultNetwork(newNetwork);
+                        // TODO: Remove following line.  It's redundant with makeDefault call.
+                        mActiveDefaultNetwork = newNetwork.networkInfo.getType();
                         if (newNetwork.linkProperties != null) {
                             updateTcpBufferSizes(newNetwork);
                             setDefaultDnsSystemProperties(
@@ -4591,12 +4606,13 @@
                             mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(),
                                                       currentNetwork);
                         }
-                        mDefaultInetConditionPublished = 100;
+                        mDefaultInetConditionPublished = newNetwork.validated ? 100 : 0;
                         mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
                     }
                 }
             }
         }
+        // Linger any networks that are no longer needed.
         for (NetworkAgentInfo nai : affectedNetworks) {
             boolean teardown = !nai.isVPN();
             for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
@@ -4624,6 +4640,7 @@
         }
         if (keep) {
             if (isNewDefault) {
+                // Notify system services that this network is up.
                 makeDefault(newNetwork);
                 synchronized (ConnectivityService.this) {
                     // have a new default network, release the transition wakelock in
@@ -4640,6 +4657,7 @@
 
             // Notify battery stats service about this network, both the normal
             // interface and any stacked links.
+            // TODO: Avoid redoing this; this must only be done once when a network comes online.
             try {
                 final IBatteryStats bs = BatteryStatsService.getService();
                 final int type = newNetwork.networkInfo.getType();
@@ -4655,7 +4673,12 @@
             }
 
             notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
-        } else {
+        } else if (newNetwork.validated) {
+            // Only tear down validated networks here.  Leave unvalidated to either become
+            // validated (and get evaluated against peers, one losing here) or
+            // NetworkMonitor reports a bad network and we tear it down then.
+            // TODO: Could teardown unvalidated networks when their NetworkCapabilities
+            // satisfy no NetworkRequests.
             if (DBG && newNetwork.networkRequests.size() != 0) {
                 loge("tearing down network with live requests:");
                 for (int i=0; i < newNetwork.networkRequests.size(); i++) {
@@ -4667,6 +4690,31 @@
         }
     }
 
+    // Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
+    // being disconnected.
+    // If only one Network's score or capabilities have been modified since the last time
+    // this function was called, pass this Network in via the "changed" arugment, otherwise
+    // pass null.
+    // If only one Network has been changed but its NetworkCapabilities have not changed,
+    // pass in the Network's score (from getCurrentScore()) prior to the change via
+    // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
+    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
+        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
+        // to avoid the slowness.  It is not simply enough to process just "changed", for
+        // example in the case where "changed"'s score decreases and another network should begin
+        // satifying a NetworkRequest that "changed" currently satisfies.
+
+        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
+        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
+        // rematchNetworkAndRequests() handles.
+        if (changed != null && oldScore < changed.getCurrentScore()) {
+            rematchNetworkAndRequests(changed);
+        } else {
+            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+                rematchNetworkAndRequests(nai);
+            }
+        }
+    }
 
     private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
         NetworkInfo.State state = newInfo.getState();
@@ -4721,12 +4769,14 @@
                 }
                 // TODO: support proxy per network.
             }
-            // Make default network if we have no default.  Any network is better than no network.
+            // Consider network even though it is not yet validated.
+            // TODO: All the if-statement conditions can be removed now that validation only confers
+            // a score increase.
             if (mNetworkForRequestId.get(mDefaultRequest.requestId) == null &&
                     networkAgent.isVPN() == false &&
                     mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
                     networkAgent.networkCapabilities)) {
-                makeDefault(networkAgent);
+                rematchNetworkAndRequests(networkAgent);
             }
         } else if (state == NetworkInfo.State.DISCONNECTED ||
                 state == NetworkInfo.State.SUSPENDED) {
@@ -4752,23 +4802,11 @@
             score = 0;
         }
 
-        nai.currentScore = score;
+        final int oldScore = nai.getCurrentScore();
+        nai.setCurrentScore(score);
 
-        // TODO - This will not do the right thing if this network is lowering
-        // its score and has requests that can be served by other
-        // currently-active networks, or if the network is increasing its
-        // score and other networks have requests that can be better served
-        // by this network.
-        //
-        // Really we want to see if any of our requests migrate to other
-        // active/lingered networks and if any other requests migrate to us (depending
-        // on increasing/decreasing currentScore.  That's a bit of work and probably our
-        // score checking/network allocation code needs to be modularized so we can understand
-        // (see handleConnectionValided for an example).
-        //
-        // As a first order approx, lets just advertise the new score to factories.  If
-        // somebody can beat it they will nominate a network and our normal net replacement
-        // code will fire.
+        if (nai.created) rematchAllNetworksAndRequests(nai, oldScore);
+
         for (int i = 0; i < nai.networkRequests.size(); i++) {
             NetworkRequest nr = nai.networkRequests.valueAt(i);
             // Don't send listening requests to factories. b/17393458
diff --git a/services/core/java/com/android/server/MmsServiceBroker.java b/services/core/java/com/android/server/MmsServiceBroker.java
index b452a38..0fb80c9 100644
--- a/services/core/java/com/android/server/MmsServiceBroker.java
+++ b/services/core/java/com/android/server/MmsServiceBroker.java
@@ -219,15 +219,16 @@
         }
 
         @Override
-        public void updateMmsSendStatus(int messageRef, boolean success) throws RemoteException {
+        public void updateMmsSendStatus(int messageRef, byte[] pdu, int status)
+                throws RemoteException {
             enforceCarrierPrivilege();
-            getServiceGuarded().updateMmsSendStatus(messageRef, success);
+            getServiceGuarded().updateMmsSendStatus(messageRef, pdu, status);
         }
 
         @Override
-        public void updateMmsDownloadStatus(int messageRef, byte[] pdu) throws RemoteException {
+        public void updateMmsDownloadStatus(int messageRef, int status) throws RemoteException {
             enforceCarrierPrivilege();
-            getServiceGuarded().updateMmsDownloadStatus(messageRef, pdu);
+            getServiceGuarded().updateMmsDownloadStatus(messageRef, status);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/PersistentDataBlockService.java b/services/core/java/com/android/server/PersistentDataBlockService.java
index 2896f60..6f378fd 100644
--- a/services/core/java/com/android/server/PersistentDataBlockService.java
+++ b/services/core/java/com/android/server/PersistentDataBlockService.java
@@ -17,6 +17,7 @@
 package com.android.server;
 
 import android.Manifest;
+import android.app.ActivityManager;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.os.Binder;
@@ -26,7 +27,9 @@
 import android.os.UserHandle;
 import android.service.persistentdata.IPersistentDataBlockService;
 import android.util.Slog;
+
 import com.android.internal.R;
+
 import libcore.io.IoUtils;
 
 import java.io.DataInputStream;
@@ -241,6 +244,10 @@
 
         @Override
         public void setOemUnlockEnabled(boolean enabled) {
+            // do not allow monkey to flip the flag
+            if (ActivityManager.isUserAMonkey()) {
+                return;
+            }
             enforceOemUnlockPermission();
             FileOutputStream outputStream;
             try {
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index a490ac6..2885b83 100755
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -14645,13 +14645,10 @@
             }
         } else if ("system".equals(componentProcessName)) {
             result = true;
-        } else if (UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID)
-                && (flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
-            // Phone app is allowed to export singleuser providers.
-            result = true;
-        } else {
-            // App with pre-defined UID, check if it's a persistent app
-            result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
+        } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
+            // Phone app and persistent apps are allowed to export singleuser providers.
+            result = UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID)
+                    || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
         }
         if (DEBUG_MU) {
             Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 1287dce..80d0510 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -21,6 +21,7 @@
 import java.nio.ByteBuffer;
 
 import android.app.ActivityManager;
+import android.os.Build;
 import android.os.SystemClock;
 import com.android.internal.util.MemInfoReader;
 import com.android.server.wm.WindowManagerService;
@@ -230,21 +231,31 @@
             Slog.i("XXXXXX", "minfree_adj=" + minfree_adj + " minfree_abs=" + minfree_abs);
         }
 
+        final boolean is64bit = Build.SUPPORTED_64_BIT_ABIS.length > 0;
+
         for (int i=0; i<mOomAdj.length; i++) {
             int low = mOomMinFreeLow[i];
             int high = mOomMinFreeHigh[i];
             mOomMinFree[i] = (int)(low + ((high-low)*scale));
+            if (is64bit) {
+                // On 64 bit devices, we consume more baseline RAM, because 64 bit is cool!
+                // To avoid being all pagey and stuff, scale up the memory levels to
+                // give us some breathing room.
+                mOomMinFree[i] = (3*mOomMinFree[i])/2;
+            }
         }
 
         if (minfree_abs >= 0) {
             for (int i=0; i<mOomAdj.length; i++) {
-                mOomMinFree[i] = (int)((float)minfree_abs * mOomMinFree[i] / mOomMinFree[mOomAdj.length - 1]);
+                mOomMinFree[i] = (int)((float)minfree_abs * mOomMinFree[i]
+                        / mOomMinFree[mOomAdj.length - 1]);
             }
         }
 
         if (minfree_adj != 0) {
             for (int i=0; i<mOomAdj.length; i++) {
-                mOomMinFree[i] += (int)((float)minfree_adj * mOomMinFree[i] / mOomMinFree[mOomAdj.length - 1]);
+                mOomMinFree[i] += (int)((float)minfree_adj * mOomMinFree[i]
+                        / mOomMinFree[mOomAdj.length - 1]);
                 if (mOomMinFree[i] < 0) {
                     mOomMinFree[i] = 0;
                 }
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index bba786d..957d705 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -43,12 +43,16 @@
     public Network network;
     public LinkProperties linkProperties;
     public NetworkCapabilities networkCapabilities;
-    public int currentScore;
     public final NetworkMonitor networkMonitor;
     public final NetworkMisc networkMisc;
     public boolean created;
     public boolean validated;
 
+    // This represents the last score received from the NetworkAgent.
+    private int currentScore;
+    // Penalty applied to scores of Networks that have not been validated.
+    private static final int UNVALIDATED_SCORE_PENALTY = 40;
+
     // The list of NetworkRequests being satisfied by this Network.
     public final SparseArray<NetworkRequest> networkRequests = new SparseArray<NetworkRequest>();
     public final ArrayList<NetworkRequest> networkLingered = new ArrayList<NetworkRequest>();
@@ -80,11 +84,33 @@
         return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
     }
 
+    // Get the current score for this Network.  This may be modified from what the
+    // NetworkAgent sent, as it has modifiers applied to it.
+    public int getCurrentScore() {
+        // TODO: We may want to refactor this into a NetworkScore class that takes a base score from
+        // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the
+        // score.  The NetworkScore class would provide a nice place to centralize score constants
+        // so they are not scattered about the transports.
+
+        int score = currentScore;
+
+        if (!validated) score -= UNVALIDATED_SCORE_PENALTY;
+
+        if (score < 0) score = 0;
+
+        return score;
+    }
+
+    public void setCurrentScore(int newScore) {
+        currentScore = newScore;
+    }
+
     public String toString() {
         return "NetworkAgentInfo{ ni{" + networkInfo + "}  network{" +
                 network + "}  lp{" +
                 linkProperties + "}  nc{" +
-                networkCapabilities + "}  Score{" + currentScore + "} }";
+                networkCapabilities + "}  Score{" + getCurrentScore() + "} " +
+                "validated{" + validated + "} created{" + created + "} }";
     }
 
     public String name() {
diff --git a/services/core/java/com/android/server/hdmi/Constants.java b/services/core/java/com/android/server/hdmi/Constants.java
index 6ce235b..5823f47 100644
--- a/services/core/java/com/android/server/hdmi/Constants.java
+++ b/services/core/java/com/android/server/hdmi/Constants.java
@@ -255,37 +255,5 @@
     //     values which denotes the device type in HDMI Spec 1.4.
     static final String PROPERTY_DEVICE_TYPE = "ro.hdmi.device_type";
 
-    // --------------------------------------------------
-    // MHL sub command message types.
-    static final int MHL_MSG_MSGE  = 0x02;
-    static final int MHL_MSG_RCP   = 0x10;
-    static final int MHL_MSG_RCPK  = 0x11;
-    static final int MHL_MSG_RCPE  = 0x12;
-    static final int MHL_MSG_RAP   = 0x20;
-    static final int MHL_MSG_RAPK  = 0x21;
-
-    // MHL RAP messages.
-    static final int MHL_RAP_ACTION_POLL = 0x00;
-    static final int MHL_RAP_ACTION_CONTENT_ON = 0x10;
-    static final int MHL_RAP_ACTION_CONTENT_OFF = 0x11;
-
-    // MHL RAPK messages.
-    static final int MHL_RAPK_NO_ERROR = 0x00;
-    static final int MHL_RAPK_UNRECOGNIZED_ACTION = 0x01;
-    static final int MHL_RAPK_UNSUPPORTED_ACTION = 0x02;
-    static final int MHL_RAPK_RESPONDER_BUSY = 0x03;
-
-    static final int MHL_INVALID_ADOPTER_ID = -1;
-    static final int MHL_INVALID_DEVICE_ID = -1;
-
-    static final int MHL_CBUS_MODE_OCBUS = 1;
-    static final int MHL_CBUS_MODE_ECBUS_S = 2;
-    static final int MHL_CBUS_MODE_ECBUS_D = 3;
-
-    // MHL RCPE messages
-    static final int MHL_RCPE_NO_ERROR = 0x00;
-    static final int MHL_RCPE_INEFFECTIVE_KEYCODE = 0x01;
-    static final int MHL_RCPE_RESPONDER_BUSY = 0x02;
-
     private Constants() { /* cannot be instantiated */ }
 }
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecController.java b/services/core/java/com/android/server/hdmi/HdmiCecController.java
index c5a6dbd..0e8788a 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecController.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecController.java
@@ -32,6 +32,7 @@
 import libcore.util.EmptyArray;
 
 import java.util.ArrayList;
+import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -367,7 +368,8 @@
 
         // Extract polling candidates. No need to poll against local devices.
         List<Integer> pollingCandidates = pickPollCandidates(pickStrategy);
-        runDevicePolling(sourceAddress, pollingCandidates, retryCount, callback);
+        ArrayList<Integer> allocated = new ArrayList<>();
+        runDevicePolling(sourceAddress, pollingCandidates, retryCount, callback, allocated);
     }
 
     /**
@@ -395,7 +397,7 @@
         }
 
         int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK;
-        ArrayList<Integer> pollingCandidates = new ArrayList<>();
+        LinkedList<Integer> pollingCandidates = new LinkedList<>();
         switch (iterationStrategy) {
             case Constants.POLL_ITERATION_IN_ORDER:
                 for (int i = Constants.ADDR_TV; i <= Constants.ADDR_SPECIFIC_USE; ++i) {
@@ -430,26 +432,32 @@
     @ServiceThreadOnly
     private void runDevicePolling(final int sourceAddress,
             final List<Integer> candidates, final int retryCount,
-            final DevicePollingCallback callback) {
+            final DevicePollingCallback callback, final List<Integer> allocated) {
         assertRunOnServiceThread();
+        if (candidates.isEmpty()) {
+            if (callback != null) {
+                HdmiLogger.debug("[P]:AllocatedAddress=%s", allocated.toString());
+                callback.onPollingFinished(allocated);
+            }
+            return;
+        }
+
+        final Integer candidate = candidates.remove(0);
+        // Proceed polling action for the next address once polling action for the
+        // previous address is done.
         runOnIoThread(new Runnable() {
             @Override
             public void run() {
-                final ArrayList<Integer> allocated = new ArrayList<>();
-                for (Integer address : candidates) {
-                    if (sendPollMessage(sourceAddress, address, retryCount)) {
-                        allocated.add(address);
+                if (sendPollMessage(sourceAddress, candidate, retryCount)) {
+                    allocated.add(candidate);
+                }
+                runOnServiceThread(new Runnable() {
+                    @Override
+                    public void run() {
+                        runDevicePolling(sourceAddress, candidates, retryCount, callback,
+                                allocated);
                     }
-                }
-                HdmiLogger.debug("[P]:Allocated Address=" + allocated);
-                if (callback != null) {
-                    runOnServiceThread(new Runnable() {
-                        @Override
-                        public void run() {
-                            callback.onPollingFinished(allocated);
-                        }
-                    });
-                }
+                });
             }
         });
     }
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
index c00c5d0..41ac589 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
@@ -263,7 +263,9 @@
             case Constants.MESSAGE_GIVE_DEVICE_POWER_STATUS:
                 return handleGiveDevicePowerStatus(message);
             case Constants.MESSAGE_MENU_REQUEST:
-                return handleGiveDeviceMenuStatus(message);
+                return handleMenuRequest(message);
+            case Constants.MESSAGE_MENU_STATUS:
+                return handleMenuStatus(message);
             case Constants.MESSAGE_VENDOR_COMMAND:
                 return handleVendorCommand(message);
             case Constants.MESSAGE_VENDOR_COMMAND_WITH_ID:
@@ -503,16 +505,24 @@
         return true;
     }
 
-    protected boolean handleGiveDeviceMenuStatus(HdmiCecMessage message) {
+    protected boolean handleMenuRequest(HdmiCecMessage message) {
         // Always report menu active to receive Remote Control.
         mService.sendCecCommand(HdmiCecMessageBuilder.buildReportMenuStatus(
                 mAddress, message.getSource(), Constants.MENU_STATE_ACTIVATED));
         return true;
     }
 
+    protected boolean handleMenuStatus(HdmiCecMessage message) {
+        return false;
+    }
+
     protected boolean handleVendorCommand(HdmiCecMessage message) {
-        mService.invokeVendorCommandListeners(mDeviceType, message.getSource(),
-                message.getParams(), false);
+        if (!mService.invokeVendorCommandListeners(mDeviceType, message.getSource(),
+                message.getParams(), false)) {
+            // Vendor command listener may not have been registered yet. Respond with
+            // <Feature Abort> [NOT_IN_CORRECT_MODE] so that the sender can try again later.
+            mService.maySendFeatureAbortCommand(message, Constants.ABORT_NOT_IN_CORRECT_MODE);
+        }
         return true;
     }
 
@@ -520,7 +530,10 @@
         byte[] params = message.getParams();
         int vendorId = HdmiUtils.threeBytesToInt(params);
         if (vendorId == mService.getVendorId()) {
-            mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), params, true);
+            if (!mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), params,
+                    true)) {
+                mService.maySendFeatureAbortCommand(message, Constants.ABORT_NOT_IN_CORRECT_MODE);
+            }
         } else if (message.getDestination() != Constants.ADDR_BROADCAST &&
                 message.getSource() != Constants.ADDR_UNREGISTERED) {
             Slog.v(TAG, "Wrong direct vendor command. Replying with <Feature Abort>");
@@ -531,6 +544,10 @@
         return true;
     }
 
+    protected void sendStandby(int deviceId) {
+        // Do nothing.
+    }
+
     protected boolean handleSetOsdName(HdmiCecMessage message) {
         // The default behavior of <Set Osd Name> is doing nothing.
         return true;
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
index 58ccbdb..9033c38 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
@@ -1646,6 +1646,22 @@
     }
 
     @Override
+    protected boolean handleMenuStatus(HdmiCecMessage message) {
+        // Do nothing and just return true not to prevent from responding <Feature Abort>.
+        return true;
+    }
+
+    @Override
+    protected void sendStandby(int deviceId) {
+        HdmiDeviceInfo targetDevice = mDeviceInfos.get(deviceId);
+        if (targetDevice == null) {
+            return;
+        }
+        int targetAddress = targetDevice.getLogicalAddress();
+        mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(mAddress, targetAddress));
+    }
+
+    @Override
     protected void dump(final IndentingPrintWriter pw) {
         super.dump(pw);
         pw.println("mArcEstablished: " + mArcEstablished);
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecMessageValidator.java b/services/core/java/com/android/server/hdmi/HdmiCecMessageValidator.java
index 0b3d9fb..d703989 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecMessageValidator.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecMessageValidator.java
@@ -25,6 +25,11 @@
 public final class HdmiCecMessageValidator {
     private static final String TAG = "HdmiCecMessageValidator";
 
+    static final int OK = 0;
+    static final int ERROR_SOURCE = 1;
+    static final int ERROR_DESTINATION = 2;
+    static final int ERROR_PARAMETER = 3;
+
     private final HdmiControlService mService;
 
     interface ParameterValidator {
@@ -140,7 +145,9 @@
         addValidationInfo(Constants.MESSAGE_SET_OSD_STRING, maxLengthValidator, DEST_DIRECT);
         addValidationInfo(Constants.MESSAGE_SET_OSD_NAME, maxLengthValidator, DEST_DIRECT);
 
-        // TODO: Handle messages for the Device Menu Control.
+        // Messages for the Device Menu Control.
+        addValidationInfo(Constants.MESSAGE_MENU_REQUEST, oneByteValidator, DEST_DIRECT);
+        addValidationInfo(Constants.MESSAGE_MENU_STATUS, oneByteValidator, DEST_DIRECT);
 
         // Messages for the Remote Control Passthrough.
         // TODO: Parse the first parameter and determine if it can have the next parameter.
@@ -178,39 +185,39 @@
         mValidationInfo.append(opcode, new ValidationInfo(validator, addrType));
     }
 
-    boolean isValid(HdmiCecMessage message) {
+    int isValid(HdmiCecMessage message) {
         int opcode = message.getOpcode();
         ValidationInfo info = mValidationInfo.get(opcode);
         if (info == null) {
             HdmiLogger.warning("No validation information for the message: " + message);
-            return true;
+            return OK;
         }
 
         // Check the source field.
         if (message.getSource() == Constants.ADDR_UNREGISTERED &&
                 (info.addressType & SRC_UNREGISTERED) == 0) {
             HdmiLogger.warning("Unexpected source: " + message);
-            return false;
+            return ERROR_SOURCE;
         }
         // Check the destination field.
         if (message.getDestination() == Constants.ADDR_BROADCAST) {
             if ((info.addressType & DEST_BROADCAST) == 0) {
                 HdmiLogger.warning("Unexpected broadcast message: " + message);
-                return false;
+                return ERROR_DESTINATION;
             }
         } else {  // Direct addressing.
             if ((info.addressType & DEST_DIRECT) == 0) {
                 HdmiLogger.warning("Unexpected direct message: " + message);
-                return false;
+                return ERROR_DESTINATION;
             }
         }
 
         // Check the parameter type.
         if (!info.parameterValidator.isValid(message.getParams())) {
             HdmiLogger.warning("Unexpected parameters: " + message);
-            return false;
+            return ERROR_PARAMETER;
         }
-        return true;
+        return OK;
     }
 
     private static class FixedLengthValidator implements ParameterValidator {
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index 5cd7c01..96823e1 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -43,7 +43,7 @@
 import android.hardware.hdmi.IHdmiDeviceEventListener;
 import android.hardware.hdmi.IHdmiHotplugEventListener;
 import android.hardware.hdmi.IHdmiInputChangeListener;
-import android.hardware.hdmi.IHdmiMhlScratchpadCommandListener;
+import android.hardware.hdmi.IHdmiMhlVendorCommandListener;
 import android.hardware.hdmi.IHdmiRecordListener;
 import android.hardware.hdmi.IHdmiSystemAudioModeChangeListener;
 import android.hardware.hdmi.IHdmiVendorCommandListener;
@@ -247,10 +247,10 @@
     @GuardedBy("mLock")
     private boolean mMhlInputChangeEnabled;
 
-    // List of records for MHL Scratchpad command listener to handle the caller killed in action.
+    // List of records for MHL Vendor command listener to handle the caller killed in action.
     @GuardedBy("mLock")
-    private final ArrayList<HdmiMhlScratchpadCommandListenerRecord>
-            mScratchpadCommandListenerRecords = new ArrayList<>();
+    private final ArrayList<HdmiMhlVendorCommandListenerRecord>
+            mMhlVendorCommandListenerRecords = new ArrayList<>();
 
     @GuardedBy("mLock")
     private List<HdmiDeviceInfo> mMhlDevices;
@@ -651,7 +651,7 @@
     @ServiceThreadOnly
     void sendCecCommand(HdmiCecMessage command, @Nullable SendMessageCallback callback) {
         assertRunOnServiceThread();
-        if (mMessageValidator.isValid(command)) {
+        if (mMessageValidator.isValid(command) == HdmiCecMessageValidator.OK) {
             mCecController.sendCommand(command, callback);
         } else {
             HdmiLogger.error("Invalid message type:" + command);
@@ -682,8 +682,13 @@
     @ServiceThreadOnly
     boolean handleCecCommand(HdmiCecMessage message) {
         assertRunOnServiceThread();
-        if (!mMessageValidator.isValid(message)) {
-            return false;
+        int errorCode = mMessageValidator.isValid(message);
+        if (errorCode != HdmiCecMessageValidator.OK) {
+            // We'll not response on the messages with the invalid source or destination.
+            if (errorCode == HdmiCecMessageValidator.ERROR_PARAMETER) {
+                maySendFeatureAbortCommand(message, Constants.ABORT_INVALID_OPERAND);
+            }
+            return true;
         }
         return dispatchMessageToLocalDevice(message);
     }
@@ -814,45 +819,21 @@
     }
 
     @ServiceThreadOnly
-    void sendMhlSubcommand(int portId, HdmiMhlSubcommand command) {
-        assertRunOnServiceThread();
-        sendMhlSubcommand(portId, command, null);
-    }
-
-    @ServiceThreadOnly
-    void sendMhlSubcommand(int portId, HdmiMhlSubcommand command, SendMessageCallback callback) {
-        assertRunOnServiceThread();
-        mMhlController.sendSubcommand(portId, command, callback);
-    }
-
-    @ServiceThreadOnly
-    boolean handleMhlSubcommand(int portId, HdmiMhlSubcommand message) {
-        assertRunOnServiceThread();
-
-        HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
-        if (device != null) {
-            return device.handleSubcommand(message);
-        }
-        Slog.w(TAG, "No mhl device exists[portId:" + portId + ", message:" + message);
-        return false;
-    }
-
-    @ServiceThreadOnly
     void handleMhlHotplugEvent(int portId, boolean connected) {
         assertRunOnServiceThread();
         if (connected) {
-            HdmiMhlLocalDevice newDevice = new HdmiMhlLocalDevice(this, portId);
-            HdmiMhlLocalDevice oldDevice = mMhlController.addLocalDevice(newDevice);
+            HdmiMhlLocalDeviceStub newDevice = new HdmiMhlLocalDeviceStub(this, portId);
+            HdmiMhlLocalDeviceStub oldDevice = mMhlController.addLocalDevice(newDevice);
             if (oldDevice != null) {
                 oldDevice.onDeviceRemoved();
                 Slog.i(TAG, "Old device of port " + portId + " is removed");
             }
         } else {
-            HdmiMhlLocalDevice device = mMhlController.removeLocalDevice(portId);
+            HdmiMhlLocalDeviceStub device = mMhlController.removeLocalDevice(portId);
             if (device != null) {
                 device.onDeviceRemoved();
-                // There is no explicit event for device removal unlike capability register event
-                // used for device addition . Hence we remove the device on hotplug event.
+                // There is no explicit event for device removal.
+                // Hence we remove the device on hotplug event.
                 HdmiDeviceInfo deviceInfo = device.getInfo();
                 if (deviceInfo != null) {
                     invokeDeviceEventListeners(deviceInfo, DEVICE_EVENT_REMOVE_DEVICE);
@@ -866,40 +847,40 @@
     }
 
     @ServiceThreadOnly
-    void handleMhlCbusModeChanged(int portId, int cbusmode) {
+    void handleMhlBusModeChanged(int portId, int busmode) {
         assertRunOnServiceThread();
-        HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
+        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
         if (device != null) {
-            device.setCbusMode(cbusmode);
+            device.setBusMode(busmode);
         } else {
-            Slog.w(TAG, "No mhl device exists for cbus mode change[portId:" + portId +
-                    ", cbusmode:" + cbusmode + "]");
+            Slog.w(TAG, "No mhl device exists for bus mode change[portId:" + portId +
+                    ", busmode:" + busmode + "]");
         }
     }
 
     @ServiceThreadOnly
-    void handleMhlVbusOvercurrent(int portId, boolean on) {
+    void handleMhlBusOvercurrent(int portId, boolean on) {
         assertRunOnServiceThread();
-        HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
+        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
         if (device != null) {
-            device.onVbusOvercurrentDetected(on);
+            device.onBusOvercurrentDetected(on);
         } else {
-            Slog.w(TAG, "No mhl device exists for vbus overcurrent event[portId:" + portId + "]");
+            Slog.w(TAG, "No mhl device exists for bus overcurrent event[portId:" + portId + "]");
         }
     }
 
     @ServiceThreadOnly
-    void handleMhlCapabilityRegisterChanged(int portId, int adopterId, int deviceId) {
+    void handleMhlDeviceStatusChanged(int portId, int adopterId, int deviceId) {
         assertRunOnServiceThread();
-        HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
+        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
 
-        // Hotplug event should already have been called before capability register change event.
+        // Hotplug event should already have been called before device status change event.
         if (device != null) {
-            device.setCapabilityRegister(adopterId, deviceId);
+            device.setDeviceStatusChange(adopterId, deviceId);
             invokeDeviceEventListeners(device.getInfo(), DEVICE_EVENT_ADD_DEVICE);
             updateSafeMhlInput();
         } else {
-            Slog.w(TAG, "No mhl device exists for capability register change event[portId:"
+            Slog.w(TAG, "No mhl device exists for device status event[portId:"
                     + portId + ", adopterId:" + adopterId + ", deviceId:" + deviceId + "]");
         }
     }
@@ -908,9 +889,9 @@
     private void updateSafeMhlInput() {
         assertRunOnServiceThread();
         List<HdmiDeviceInfo> inputs = Collections.emptyList();
-        SparseArray<HdmiMhlLocalDevice> devices = mMhlController.getAllLocalDevices();
+        SparseArray<HdmiMhlLocalDeviceStub> devices = mMhlController.getAllLocalDevices();
         for (int i = 0; i < devices.size(); ++i) {
-            HdmiMhlLocalDevice device = devices.valueAt(i);
+            HdmiMhlLocalDeviceStub device = devices.valueAt(i);
             HdmiDeviceInfo info = device.getInfo();
             if (info != null) {
                 if (inputs.isEmpty()) {
@@ -928,16 +909,16 @@
         return mMhlDevices;
     }
 
-    private class HdmiMhlScratchpadCommandListenerRecord implements IBinder.DeathRecipient {
-        private final IHdmiMhlScratchpadCommandListener mListener;
+    private class HdmiMhlVendorCommandListenerRecord implements IBinder.DeathRecipient {
+        private final IHdmiMhlVendorCommandListener mListener;
 
-        public HdmiMhlScratchpadCommandListenerRecord(IHdmiMhlScratchpadCommandListener listener) {
+        public HdmiMhlVendorCommandListenerRecord(IHdmiMhlVendorCommandListener listener) {
             mListener = listener;
         }
 
         @Override
         public void binderDied() {
-            mScratchpadCommandListenerRecords.remove(this);
+            mMhlVendorCommandListenerRecords.remove(this);
         }
     }
 
@@ -1072,7 +1053,7 @@
                         invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
                         return;
                     }
-                    HdmiMhlLocalDevice device = mMhlController.getLocalDeviceById(deviceId);
+                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDeviceById(deviceId);
                     if (device != null) {
                         if (device.getPortId() == tv.getActivePortId()) {
                             invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
@@ -1117,7 +1098,7 @@
             runOnServiceThread(new Runnable() {
                 @Override
                 public void run() {
-                    HdmiMhlLocalDevice device = mMhlController.getLocalDevice(mActivePortId);
+                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(mActivePortId);
                     if (device != null) {
                         device.sendKeyEvent(keyCode, isPressed);
                         return;
@@ -1340,6 +1321,22 @@
         }
 
         @Override
+        public void sendStandby(final int deviceType, final int deviceId) {
+            enforceAccessPermission();
+            runOnServiceThread(new Runnable() {
+                @Override
+                public void run() {
+                    HdmiCecLocalDevice device = mCecController.getLocalDevice(deviceType);
+                    if (device == null) {
+                        Slog.w(TAG, "Local device not available");
+                        return;
+                    }
+                    device.sendStandby(deviceId);
+                }
+            });
+        }
+
+        @Override
         public void setHdmiRecordListener(IHdmiRecordListener listener) {
             HdmiControlService.this.setHdmiRecordListener(listener);
         }
@@ -1403,7 +1400,7 @@
         }
 
         @Override
-        public void sendScratchpadCommand(final int portId, final int offset, final int length,
+        public void sendMhlVendorCommand(final int portId, final int offset, final int length,
                 final byte[] data) {
             enforceAccessPermission();
             runOnServiceThread(new Runnable() {
@@ -1413,21 +1410,21 @@
                         Slog.w(TAG, "Hdmi control is disabled.");
                         return ;
                     }
-                    HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
+                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
                     if (device == null) {
                         Slog.w(TAG, "Invalid port id:" + portId);
                         return;
                     }
-                    mMhlController.sendScratchpadCommand(portId, offset, length, data);
+                    mMhlController.sendVendorCommand(portId, offset, length, data);
                 }
             });
         }
 
         @Override
-        public void addHdmiMhlScratchpadCommandListener(
-                IHdmiMhlScratchpadCommandListener listener) {
+        public void addHdmiMhlVendorCommandListener(
+                IHdmiMhlVendorCommandListener listener) {
             enforceAccessPermission();
-            HdmiControlService.this.addHdmiMhlScratchpadCommandListener(listener);
+            HdmiControlService.this.addHdmiMhlVendorCommandListener(listener);
         }
 
         @Override
@@ -1864,9 +1861,12 @@
         }
     }
 
-    void invokeVendorCommandListeners(int deviceType, int srcAddress, byte[] params,
+    boolean invokeVendorCommandListeners(int deviceType, int srcAddress, byte[] params,
             boolean hasVendorId) {
         synchronized (mLock) {
+            if (mVendorCommandListenerRecords.isEmpty()) {
+                return false;
+            }
             for (VendorCommandListenerRecord record : mVendorCommandListenerRecords) {
                 if (record.mDeviceType != deviceType) {
                     continue;
@@ -1877,12 +1877,13 @@
                     Slog.e(TAG, "Failed to notify vendor command reception", e);
                 }
             }
+            return true;
         }
     }
 
-    private void addHdmiMhlScratchpadCommandListener(IHdmiMhlScratchpadCommandListener listener) {
-        HdmiMhlScratchpadCommandListenerRecord record =
-                new HdmiMhlScratchpadCommandListenerRecord(listener);
+    private void addHdmiMhlVendorCommandListener(IHdmiMhlVendorCommandListener listener) {
+        HdmiMhlVendorCommandListenerRecord record =
+                new HdmiMhlVendorCommandListenerRecord(listener);
         try {
             listener.asBinder().linkToDeath(record, 0);
         } catch (RemoteException e) {
@@ -1891,18 +1892,17 @@
         }
 
         synchronized (mLock) {
-            mScratchpadCommandListenerRecords.add(record);
+            mMhlVendorCommandListenerRecords.add(record);
         }
     }
 
-    void invokeScratchpadCommandListeners(int portId, int offest, int length, byte[] data) {
+    void invokeMhlVendorCommandListeners(int portId, int offest, int length, byte[] data) {
         synchronized (mLock) {
-            for (HdmiMhlScratchpadCommandListenerRecord record :
-                    mScratchpadCommandListenerRecords) {
+            for (HdmiMhlVendorCommandListenerRecord record : mMhlVendorCommandListenerRecords) {
                 try {
                     record.mListener.onReceived(portId, offest, length, data);
                 } catch (RemoteException e) {
-                    Slog.e(TAG, "Failed to notify scratchpad command", e);
+                    Slog.e(TAG, "Failed to notify MHL vendor command", e);
                 }
             }
         }
@@ -2001,7 +2001,7 @@
         // the last port to go back to when turnoff command is received. Note that the last port
         // may not be the MHL-enabled one. In this case the device info to be passed to
         // input change listener should be the one describing the corresponding HDMI port.
-        HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
+        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
         HdmiDeviceInfo info = (device != null && device.getInfo() != null)
                 ? device.getInfo()
                 : mPortDeviceMap.get(portId);
diff --git a/services/core/java/com/android/server/hdmi/HdmiMhlControllerStub.java b/services/core/java/com/android/server/hdmi/HdmiMhlControllerStub.java
index c27cf18..708aee6 100644
--- a/services/core/java/com/android/server/hdmi/HdmiMhlControllerStub.java
+++ b/services/core/java/com/android/server/hdmi/HdmiMhlControllerStub.java
@@ -29,7 +29,7 @@
  */
 final class HdmiMhlControllerStub {
 
-    private static final SparseArray<HdmiMhlLocalDevice> mLocalDevices = new SparseArray<>();
+    private static final SparseArray<HdmiMhlLocalDeviceStub> mLocalDevices = new SparseArray<>();
     private static final HdmiPortInfo[] EMPTY_PORT_INFO = new HdmiPortInfo[0];
     private static final int INVALID_MHL_VERSION = 0;
     private static final int NO_SUPPORTED_FEATURES = 0;
@@ -53,60 +53,49 @@
     }
 
     /**
-     * Return {@link HdmiMhlLocalDevice} matched with the given port id.
+     * Return {@link HdmiMhlLocalDeviceStub} matched with the given port id.
      *
      * @return null if has no matched port id
      */
-    HdmiMhlLocalDevice getLocalDevice(int portId) {
+    HdmiMhlLocalDeviceStub getLocalDevice(int portId) {
         return null;
     }
 
     /**
-     * Return {@link HdmiMhlLocalDevice} matched with the given device id.
+     * Return {@link HdmiMhlLocalDeviceStub} matched with the given device id.
      *
      * @return null if has no matched id
      */
-    HdmiMhlLocalDevice getLocalDeviceById(int deviceId) {
+    HdmiMhlLocalDeviceStub getLocalDeviceById(int deviceId) {
         return null;
     }
 
-    SparseArray<HdmiMhlLocalDevice> getAllLocalDevices() {
+    SparseArray<HdmiMhlLocalDeviceStub> getAllLocalDevices() {
         return mLocalDevices;
     }
 
     /**
-     * Remove a {@link HdmiMhlLocalDevice} matched with the given port id.
+     * Remove a {@link HdmiMhlLocalDeviceStub} matched with the given port id.
      *
-     * @return removed {@link HdmiMhlLocalDevice}. Return null if no matched port id.
+     * @return removed {@link HdmiMhlLocalDeviceStub}. Return null if no matched port id.
      */
-    HdmiMhlLocalDevice removeLocalDevice(int portId) {
+    HdmiMhlLocalDeviceStub removeLocalDevice(int portId) {
         return null;
     }
 
     /**
-     * Add a new {@link HdmiMhlLocalDevice}.
+     * Add a new {@link HdmiMhlLocalDeviceStub}.
      *
-     * @return old {@link HdmiMhlLocalDevice} having same port id
+     * @return old {@link HdmiMhlLocalDeviceStub} having same port id
      */
-    HdmiMhlLocalDevice addLocalDevice(HdmiMhlLocalDevice device) {
+    HdmiMhlLocalDeviceStub addLocalDevice(HdmiMhlLocalDeviceStub device) {
         return null;
     }
 
     void clearAllLocalDevices() {
     }
 
-    /**
-     * Send MHL MSC-Subcommand to the device connected to the given port.
-     */
-    void sendSubcommand(int portId, HdmiMhlSubcommand command) {
-    }
-
-    void sendSubcommand(final int portId, final HdmiMhlSubcommand command,
-            SendMessageCallback callback) {
-    }
-
-
-    void sendScratchpadCommand(int portId, int offset, int length, byte[] data) {
+    void sendVendorCommand(int portId, int offset, int length, byte[] data) {
     }
 
     void setOption(int flag, int value) {
diff --git a/services/core/java/com/android/server/hdmi/HdmiMhlLocalDeviceStub.java b/services/core/java/com/android/server/hdmi/HdmiMhlLocalDeviceStub.java
new file mode 100644
index 0000000..53a7c5c
--- /dev/null
+++ b/services/core/java/com/android/server/hdmi/HdmiMhlLocalDeviceStub.java
@@ -0,0 +1,46 @@
+package com.android.server.hdmi;
+
+import android.hardware.hdmi.HdmiDeviceInfo;
+import android.hardware.hdmi.IHdmiControlCallback;
+
+/**
+ * Stub class that models a logical mhl device hosted in this system.
+ */
+final class HdmiMhlLocalDeviceStub {
+
+    private static final HdmiDeviceInfo INFO = new HdmiDeviceInfo(
+            Constants.INVALID_PHYSICAL_ADDRESS, Constants.INVALID_PORT_ID, -1, -1);
+    private final HdmiControlService mService;
+    private final int mPortId;
+
+    protected HdmiMhlLocalDeviceStub(HdmiControlService service, int portId) {
+        mService = service;
+        mPortId = portId;
+    }
+
+    void onDeviceRemoved() {
+    }
+
+    HdmiDeviceInfo getInfo() {
+        return INFO;
+    }
+
+    void setBusMode(int cbusmode) {
+    }
+
+    void onBusOvercurrentDetected(boolean on) {
+    }
+
+    void setDeviceStatusChange(int adopterId, int deviceId) {
+    }
+
+    int getPortId() {
+        return mPortId;
+    }
+
+    void turnOn(IHdmiControlCallback callback) {
+    }
+
+    void sendKeyEvent(int keycode, boolean isPressed) {
+    }
+}
diff --git a/services/core/java/com/android/server/hdmi/MhlConstants.java b/services/core/java/com/android/server/hdmi/MhlConstants.java
new file mode 100644
index 0000000..fe479f3
--- /dev/null
+++ b/services/core/java/com/android/server/hdmi/MhlConstants.java
@@ -0,0 +1,40 @@
+package com.android.server.hdmi;
+
+/**
+ * Defines constants related to MHL protocol internal implementation.
+ */
+final class MhlConstants {
+    // --------------------------------------------------
+    // MHL sub command message types.
+    static final int MSG_MSGE  = 0x02;
+    static final int MSG_RCP   = 0x10;
+    static final int MSG_RCPK  = 0x11;
+    static final int MSG_RCPE  = 0x12;
+    static final int MSG_RAP   = 0x20;
+    static final int MSG_RAPK  = 0x21;
+
+    // MHL RAP messages.
+    static final int RAP_ACTION_POLL = 0x00;
+    static final int RAP_ACTION_CONTENT_ON = 0x10;
+    static final int RAP_ACTION_CONTENT_OFF = 0x11;
+
+    // MHL RAPK messages.
+    static final int RAPK_NO_ERROR = 0x00;
+    static final int RAPK_UNRECOGNIZED_ACTION = 0x01;
+    static final int RAPK_UNSUPPORTED_ACTION = 0x02;
+    static final int RAPK_RESPONDER_BUSY = 0x03;
+
+    static final int INVALID_ADOPTER_ID = -1;
+    static final int INVALID_DEVICE_ID = -1;
+
+    static final int CBUS_MODE_OCBUS = 1;
+    static final int CBUS_MODE_ECBUS_S = 2;
+    static final int CBUS_MODE_ECBUS_D = 3;
+
+    // MHL RCPE messages
+    static final int RCPE_NO_ERROR = 0x00;
+    static final int RCPE_INEFFECTIVE_KEYCODE = 0x01;
+    static final int RCPE_RESPONDER_BUSY = 0x02;
+
+    private MhlConstants() { /* cannot be instantiated */ }
+}
diff --git a/services/core/java/com/android/server/location/GpsLocationProvider.java b/services/core/java/com/android/server/location/GpsLocationProvider.java
index 11818d8..df846a8 100644
--- a/services/core/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/core/java/com/android/server/location/GpsLocationProvider.java
@@ -494,7 +494,7 @@
                     Log.d(TAG, "SIM STATE is ready, SIM MCC/MNC is " + mccMnc);
                     synchronized (mLock) {
                         reloadGpsProperties(context, mProperties);
-                        mNIHandler.setSuplEsEnablement(mSuplEsEnabled);
+                        mNIHandler.setSuplEsEnabled(mSuplEsEnabled);
                     }
                 }
             }
@@ -590,6 +590,7 @@
                 com.android.internal.R.array.config_gpsParameters);
         for (String item : configValues) {
             Log.d(TAG, "GpsParamsResource: " + item);
+            // We need to support "KEY =", but not "=VALUE".
             String[] split = item.split("=");
             if (split.length == 2) {
                 properties.setProperty(split[0].trim().toUpperCase(), split[1]);
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index f647037..13fbf6c 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -87,6 +87,10 @@
     // Just the packages from mEnabledServicesForCurrentProfiles
     private ArraySet<String> mEnabledServicesPackageNames = new ArraySet<String>();
 
+    // Kept to de-dupe user change events (experienced after boot, when we receive a settings and a
+    // user change).
+    private int[] mLastSeenProfileIds;
+
     public ManagedServices(Context context, Handler handler, Object mutex,
             UserProfiles userProfiles) {
         mContext = context;
@@ -159,6 +163,15 @@
         }
     }
 
+    public void onUserSwitched() {
+        if (DEBUG) Slog.d(TAG, "onUserSwitched");
+        if (Arrays.equals(mLastSeenProfileIds, mUserProfiles.getCurrentProfileIds())) {
+            if (DEBUG) Slog.d(TAG, "Current profile IDs didn't change, skipping rebindServices().");
+            return;
+        }
+        rebindServices();
+    }
+
     public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
         checkNotNull(service);
         final IBinder token = service.asBinder();
@@ -321,6 +334,8 @@
                 registerService(component, userIds[i]);
             }
         }
+
+        mLastSeenProfileIds = mUserProfiles.getCurrentProfileIds();
     }
 
     /**
@@ -523,6 +538,8 @@
 
         private void update(Uri uri) {
             if (uri == null || mSecureSettingsUri.equals(uri)) {
+                if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
+                        " / uri=" + uri);
                 rebindServices();
             }
         }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index c09eff8..14587e6 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -718,6 +718,9 @@
                 // reload per-user settings
                 mSettingsObserver.update(null);
                 mUserProfiles.updateCache(context);
+                // Refresh managed services
+                mConditionProviders.onUserSwitched();
+                mListeners.onUserSwitched();
             } else if (action.equals(Intent.ACTION_USER_ADDED)) {
                 mUserProfiles.updateCache(context);
             }
@@ -1236,17 +1239,16 @@
                         final int N = keys.length;
                         for (int i = 0; i < N; i++) {
                             NotificationRecord r = mNotificationsByKey.get(keys[i]);
+                            if (r == null) continue;
                             final int userId = r.sbn.getUserId();
                             if (userId != info.userid && userId != UserHandle.USER_ALL &&
                                     !mUserProfiles.isCurrentProfile(userId)) {
                                 throw new SecurityException("Disallowed call from listener: "
                                         + info.service);
                             }
-                            if (r != null) {
-                                cancelNotificationFromListenerLocked(info, callingUid, callingPid,
-                                        r.sbn.getPackageName(), r.sbn.getTag(), r.sbn.getId(),
-                                        userId);
-                            }
+                            cancelNotificationFromListenerLocked(info, callingUid, callingPid,
+                                    r.sbn.getPackageName(), r.sbn.getTag(), r.sbn.getId(),
+                                    userId);
                         }
                     } else {
                         cancelAllLocked(callingUid, callingPid, info.userid,
@@ -1472,14 +1474,7 @@
         @Override
         public boolean matchesCallFilter(Bundle extras) {
             enforceSystemOrSystemUI("INotificationManager.matchesCallFilter");
-            return matchesCallFilterAsUser(extras, Binder.getCallingUid());
-        }
-
-        @Override
-        public boolean matchesCallFilterAsUser(Bundle extras, int userId) {
-            enforceSystemOrSystemUI("INotificationManager.matchesCallFilter");
-            UserHandle userHandle = new UserHandle(userId);
-            return mZenModeHelper.matchesCallFilter(userHandle, extras,
+            return mZenModeHelper.matchesCallFilter(UserHandle.getCallingUserHandle(), extras,
                     mRankingHelper.findExtractor(ValidateNotificationPeople.class));
         }
     };
diff --git a/services/core/java/com/android/server/notification/ValidateNotificationPeople.java b/services/core/java/com/android/server/notification/ValidateNotificationPeople.java
index f266916..1c1a034 100644
--- a/services/core/java/com/android/server/notification/ValidateNotificationPeople.java
+++ b/services/core/java/com/android/server/notification/ValidateNotificationPeople.java
@@ -19,9 +19,11 @@
 import android.app.Notification;
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.database.ContentObserver;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Bundle;
+import android.os.Handler;
 import android.os.UserHandle;
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.Contacts;
@@ -75,6 +77,9 @@
     // maps raw person handle to resolved person object
     private LruCache<String, LookupResult> mPeopleCache;
     private Map<Integer, Context> mUserToContextMap;
+    private Handler mHandler;
+    private ContentObserver mObserver;
+    private int mEvictionCount;
 
     public void initialize(Context context) {
         if (DEBUG) Slog.d(TAG, "Initializing  " + getClass().getSimpleName() + ".");
@@ -83,6 +88,22 @@
         mPeopleCache = new LruCache<String, LookupResult>(PEOPLE_CACHE_SIZE);
         mEnabled = ENABLE_PEOPLE_VALIDATOR && 1 == Settings.Global.getInt(
                 mBaseContext.getContentResolver(), SETTING_ENABLE_PEOPLE_VALIDATOR, 1);
+        if (mEnabled) {
+            mHandler = new Handler();
+            mObserver = new ContentObserver(mHandler) {
+                @Override
+                public void onChange(boolean selfChange, Uri uri, int userId) {
+                    super.onChange(selfChange, uri, userId);
+                    if (DEBUG || mEvictionCount % 100 == 0) {
+                        if (INFO) Slog.i(TAG, "mEvictionCount: " + mEvictionCount);
+                    }
+                    mPeopleCache.evictAll();
+                    mEvictionCount++;
+                }
+            };
+            mBaseContext.getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true,
+                    mObserver, UserHandle.USER_ALL);
+        }
     }
 
     public RankingReconsideration process(NotificationRecord record) {
@@ -112,6 +133,7 @@
     }
 
     public float getContactAffinity(UserHandle userHandle, Bundle extras) {
+        if (DEBUG) Slog.d(TAG, "checking affinity for " + userHandle);
         if (extras == null) return NONE;
         final String key = Long.toString(System.nanoTime());
         final float[] affinityOut = new float[1];
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index ed678d2..c106546 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -16,9 +16,6 @@
 
 package com.android.server.pm;
 
-import static android.content.pm.PackageManager.INSTALL_ALL_USERS;
-import static android.content.pm.PackageManager.INSTALL_FROM_ADB;
-import static android.content.pm.PackageManager.INSTALL_REPLACE_EXISTING;
 import static com.android.internal.util.XmlUtils.readBitmapAttribute;
 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
 import static com.android.internal.util.XmlUtils.readIntAttribute;
@@ -105,7 +102,7 @@
 
 public class PackageInstallerService extends IPackageInstaller.Stub {
     private static final String TAG = "PackageInstaller";
-    private static final boolean LOGD = true;
+    private static final boolean LOGD = false;
 
     // TODO: remove outstanding sessions when installer package goes away
     // TODO: notify listeners in other users when package has been installed there
@@ -117,6 +114,7 @@
     private static final String ATTR_SESSION_ID = "sessionId";
     private static final String ATTR_USER_ID = "userId";
     private static final String ATTR_INSTALLER_PACKAGE_NAME = "installerPackageName";
+    private static final String ATTR_INSTALLER_UID = "installerUid";
     private static final String ATTR_CREATED_MILLIS = "createdMillis";
     private static final String ATTR_SESSION_STAGE_DIR = "sessionStageDir";
     private static final String ATTR_SESSION_STAGE_CID = "sessionStageCid";
@@ -146,6 +144,7 @@
 
     private final File mStagingDir;
     private final HandlerThread mInstallThread;
+    private final Handler mInstallHandler;
 
     private final Callbacks mCallbacks;
 
@@ -190,6 +189,8 @@
         mInstallThread = new HandlerThread(TAG);
         mInstallThread.start();
 
+        mInstallHandler = new Handler(mInstallThread.getLooper());
+
         mCallbacks = new Callbacks(mInstallThread.getLooper());
 
         mSessionsFile = new AtomicFile(
@@ -336,6 +337,8 @@
         final int sessionId = readIntAttribute(in, ATTR_SESSION_ID);
         final int userId = readIntAttribute(in, ATTR_USER_ID);
         final String installerPackageName = readStringAttribute(in, ATTR_INSTALLER_PACKAGE_NAME);
+        final int installerUid = readIntAttribute(in, ATTR_INSTALLER_UID,
+                mPm.getPackageUid(installerPackageName, userId));
         final long createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
         final String stageDirRaw = readStringAttribute(in, ATTR_SESSION_STAGE_DIR);
         final File stageDir = (stageDirRaw != null) ? new File(stageDirRaw) : null;
@@ -357,8 +360,8 @@
         params.abiOverride = readStringAttribute(in, ATTR_ABI_OVERRIDE);
 
         return new PackageInstallerSession(mInternalCallback, mContext, mPm,
-                mInstallThread.getLooper(), sessionId, userId, installerPackageName, params,
-                createdMillis, stageDir, stageCid, prepared, sealed);
+                mInstallThread.getLooper(), sessionId, userId, installerPackageName, installerUid,
+                params, createdMillis, stageDir, stageCid, prepared, sealed);
     }
 
     private void writeSessionsLocked() {
@@ -398,6 +401,7 @@
         writeIntAttribute(out, ATTR_USER_ID, session.userId);
         writeStringAttribute(out, ATTR_INSTALLER_PACKAGE_NAME,
                 session.installerPackageName);
+        writeIntAttribute(out, ATTR_INSTALLER_UID, session.installerUid);
         writeLongAttribute(out, ATTR_CREATED_MILLIS, session.createdMillis);
         if (session.stageDir != null) {
             writeStringAttribute(out, ATTR_SESSION_STAGE_DIR,
@@ -446,26 +450,21 @@
     private int createSessionInternal(SessionParams params, String installerPackageName, int userId)
             throws IOException {
         final int callingUid = Binder.getCallingUid();
-        mPm.enforceCrossUserPermission(callingUid, userId, true, false, "createSession");
+        mPm.enforceCrossUserPermission(callingUid, userId, true, true, "createSession");
 
-        if (mPm.isUserRestricted(UserHandle.getUserId(callingUid),
-                UserManager.DISALLOW_INSTALL_APPS)) {
+        if (mPm.isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
             throw new SecurityException("User restriction prevents installing");
         }
 
-        // TODO: double check all possible install flags
-
         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
-            installerPackageName = "com.android.shell";
-
-            params.installFlags |= INSTALL_FROM_ADB;
+            params.installFlags |= PackageManager.INSTALL_FROM_ADB;
 
         } else {
             mAppOps.checkPackage(callingUid, installerPackageName);
 
-            params.installFlags &= ~INSTALL_FROM_ADB;
-            params.installFlags &= ~INSTALL_ALL_USERS;
-            params.installFlags |= INSTALL_REPLACE_EXISTING;
+            params.installFlags &= ~PackageManager.INSTALL_FROM_ADB;
+            params.installFlags &= ~PackageManager.INSTALL_ALL_USERS;
+            params.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
         }
 
         // Defensively resize giant app icons
@@ -532,8 +531,8 @@
             }
 
             session = new PackageInstallerSession(mInternalCallback, mContext, mPm,
-                    mInstallThread.getLooper(), sessionId, userId, installerPackageName, params,
-                    createdMillis, stageDir, stageCid, false, false);
+                    mInstallThread.getLooper(), sessionId, userId, installerPackageName, callingUid,
+                    params, createdMillis, stageDir, stageCid, false, false);
             mSessions.put(sessionId, session);
         }
 
@@ -688,7 +687,7 @@
 
     @Override
     public void uninstall(String packageName, int flags, IntentSender statusReceiver, int userId) {
-        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "uninstall");
+        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, "uninstall");
 
         final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext,
                 statusReceiver, packageName);
@@ -965,13 +964,19 @@
             mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId, progress);
         }
 
-        public void onSessionFinished(PackageInstallerSession session, boolean success) {
+        public void onSessionFinished(final PackageInstallerSession session, boolean success) {
             mCallbacks.notifySessionFinished(session.sessionId, session.userId, success);
-            synchronized (mSessions) {
-                mSessions.remove(session.sessionId);
-                mHistoricalSessions.put(session.sessionId, session);
-            }
-            writeSessionsAsync();
+
+            mInstallHandler.post(new Runnable() {
+                @Override
+                public void run() {
+                    synchronized (mSessions) {
+                        mSessions.remove(session.sessionId);
+                        mHistoricalSessions.put(session.sessionId, session);
+                        writeSessionsLocked();
+                    }
+                }
+            });
         }
 
         public void onSessionPrepared(PackageInstallerSession session) {
@@ -980,11 +985,13 @@
             writeSessionsAsync();
         }
 
-        public void onSessionSealed(PackageInstallerSession session) {
+        public void onSessionSealedBlocking(PackageInstallerSession session) {
             // It's very important that we block until we've recorded the
             // session as being sealed, since we never want to allow mutation
             // after sealing.
-            writeSessionsLocked();
+            synchronized (mSessions) {
+                writeSessionsLocked();
+            }
         }
     }
 }
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 06f550d..fb0e357 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -96,6 +96,7 @@
     final int sessionId;
     final int userId;
     final String installerPackageName;
+    final int installerUid;
     final SessionParams params;
     final long createdMillis;
 
@@ -103,9 +104,6 @@
     final File stageDir;
     final String stageCid;
 
-    /** Note that UID is not persisted; it's always derived at runtime. */
-    final int installerUid;
-
     private final AtomicInteger mActiveCount = new AtomicInteger();
 
     private final Object mLock = new Object();
@@ -186,7 +184,7 @@
 
     public PackageInstallerSession(PackageInstallerService.InternalCallback callback,
             Context context, PackageManagerService pm, Looper looper, int sessionId, int userId,
-            String installerPackageName, SessionParams params, long createdMillis,
+            String installerPackageName, int installerUid, SessionParams params, long createdMillis,
             File stageDir, String stageCid, boolean prepared, boolean sealed) {
         mCallback = callback;
         mContext = context;
@@ -196,6 +194,7 @@
         this.sessionId = sessionId;
         this.userId = userId;
         this.installerPackageName = installerPackageName;
+        this.installerUid = installerUid;
         this.params = params;
         this.createdMillis = createdMillis;
         this.stageDir = stageDir;
@@ -209,11 +208,8 @@
         mPrepared = prepared;
         mSealed = sealed;
 
-        // Always derived at runtime
-        installerUid = mPm.getPackageUid(installerPackageName, userId);
-
-        if (mPm.checkPermission(android.Manifest.permission.INSTALL_PACKAGES,
-                installerPackageName) == PackageManager.PERMISSION_GRANTED) {
+        if ((mPm.checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
+                == PackageManager.PERMISSION_GRANTED) || (installerUid == Process.ROOT_UID)) {
             mPermissionsAccepted = true;
         } else {
             mPermissionsAccepted = false;
@@ -414,7 +410,9 @@
     public void commit(IntentSender statusReceiver) {
         Preconditions.checkNotNull(statusReceiver);
 
+        final boolean wasSealed;
         synchronized (mLock) {
+            wasSealed = mSealed;
             if (!mSealed) {
                 // Verify that all writers are hands-off
                 for (FileBridge bridge : mBridges) {
@@ -422,17 +420,20 @@
                         throw new SecurityException("Files still open");
                     }
                 }
-
-                // Persist the fact that we've sealed ourselves to prevent
-                // mutations of any hard links we create.
                 mSealed = true;
-                mCallback.onSessionSealed(this);
             }
+
+            // Client staging is fully done at this point
+            mClientProgress = 1f;
+            computeProgressLocked(true);
         }
 
-        // Client staging is fully done at this point
-        mClientProgress = 1f;
-        computeProgressLocked(true);
+        if (!wasSealed) {
+            // Persist the fact that we've sealed ourselves to prevent
+            // mutations of any hard links we create. We do this without holding
+            // the session lock, since otherwise it's a lock inversion.
+            mCallback.onSessionSealedBlocking(this);
+        }
 
         // This ongoing commit should keep session active, even though client
         // will probably close their end.
@@ -537,8 +538,15 @@
             }
         };
 
-        mPm.installStage(mPackageName, stageDir, stageCid, localObserver,
-                params, installerPackageName, installerUid, new UserHandle(userId));
+        final UserHandle user;
+        if ((params.installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
+            user = UserHandle.ALL;
+        } else {
+            user = new UserHandle(userId);
+        }
+
+        mPm.installStage(mPackageName, stageDir, stageCid, localObserver, params,
+                installerPackageName, installerUid, user);
     }
 
     /**
@@ -764,8 +772,6 @@
 
     private static void extractNativeLibraries(File packageDir, String abiOverride)
             throws PackageManagerException {
-        if (LOGD) Slog.v(TAG, "extractNativeLibraries()");
-
         // Always start from a clean slate
         final File libDir = new File(packageDir, NativeLibraryHelper.LIB_DIR_NAME);
         NativeLibraryHelper.removeNativeBinariesFromDirLI(libDir, true);
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 3e5d514..0d27669 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -1793,19 +1793,17 @@
     void cleanupInstallFailedPackage(PackageSetting ps) {
         Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
         removeDataDirsLI(ps.name);
-
-        // TODO: try cleaning up codePath directory contents first, since it
-        // might be a cluster
-
         if (ps.codePath != null) {
-            if (!ps.codePath.delete()) {
-                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
+            if (ps.codePath.isDirectory()) {
+                FileUtils.deleteContents(ps.codePath);
             }
+            ps.codePath.delete();
         }
-        if (ps.resourcePath != null) {
-            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
-                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
+        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
+            if (ps.resourcePath.isDirectory()) {
+                FileUtils.deleteContents(ps.resourcePath);
             }
+            ps.resourcePath.delete();
         }
         mSettings.removePackageLPw(ps.name);
     }
@@ -4958,6 +4956,21 @@
 
     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
+        boolean success = false;
+        try {
+            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
+                    currentTime, user);
+            success = true;
+            return res;
+        } finally {
+            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
+                removeDataDirsLI(pkg.packageName);
+            }
+        }
+    }
+
+    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
+            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
         final File scanFile = new File(pkg.codePath);
         if (pkg.applicationInfo.getCodePath() == null ||
                 pkg.applicationInfo.getResourcePath() == null) {
@@ -5264,7 +5277,8 @@
         File dataPath;
         if (mPlatformPackage == pkg) {
             // The system package is special.
-            dataPath = new File (Environment.getDataDirectory(), "system");
+            dataPath = new File(Environment.getDataDirectory(), "system");
+
             pkg.applicationInfo.dataDir = dataPath.getPath();
 
         } else {
@@ -5272,7 +5286,6 @@
             dataPath = getDataPathForPackage(pkg.packageName, 0);
 
             boolean uidError = false;
-
             if (dataPath.exists()) {
                 int currentUid = 0;
                 try {
@@ -5599,13 +5612,9 @@
                     pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
         }
 
-        if ((scanFlags&SCAN_NO_DEX) == 0) {
-            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
-                    == DEX_OPT_FAILED) {
-                if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
-                    removeDataDirsLI(pkg.packageName);
-                }
-
+        if ((scanFlags & SCAN_NO_DEX) == 0) {
+            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
+                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
                 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
             }
         }
@@ -5676,16 +5685,11 @@
         // if these fail, we should abort the install since installing the library will
         // result in some apps being broken.
         if (clientLibPkgs != null) {
-            if ((scanFlags&SCAN_NO_DEX) == 0) {
-                for (int i=0; i<clientLibPkgs.size(); i++) {
+            if ((scanFlags & SCAN_NO_DEX) == 0) {
+                for (int i = 0; i < clientLibPkgs.size(); i++) {
                     PackageParser.Package clientPkg = clientLibPkgs.get(i);
-                    if (performDexOptLI(clientPkg, null /* instruction sets */,
-                            forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
-                            == DEX_OPT_FAILED) {
-                        if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
-                            removeDataDirsLI(pkg.packageName);
-                        }
-
+                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
+                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
                         throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
                                 "scanPackageLI failed to dexopt clientLibPkgs");
                     }
@@ -7668,16 +7672,11 @@
     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
             int installFlags, String installerPackageName, VerificationParams verificationParams,
             String packageAbiOverride, int userId) {
-        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
-                null);
-        if (UserHandle.getCallingUserId() != userId) {
-            mContext.enforceCallingOrSelfPermission(
-                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
-                    "installPackage " + userId);
-        }
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
 
-        final File originFile = new File(originPath);
-        final int uid = Binder.getCallingUid();
+        final int callingUid = Binder.getCallingUid();
+        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
+
         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
             try {
                 if (observer != null) {
@@ -7688,6 +7687,17 @@
             return;
         }
 
+        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
+            installFlags |= PackageManager.INSTALL_FROM_ADB;
+
+        } else {
+            // Caller holds INSTALL_PACKAGES permission, so we're less strict
+            // about installerPackageName.
+
+            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
+            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
+        }
+
         UserHandle user;
         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
             user = UserHandle.ALL;
@@ -7695,22 +7705,13 @@
             user = new UserHandle(userId);
         }
 
-        final int filteredInstallFlags;
-        if (uid == Process.SHELL_UID || uid == 0) {
-            if (DEBUG_INSTALL) {
-                Slog.v(TAG, "Install from ADB");
-            }
-            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
-        } else {
-            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
-        }
+        verificationParams.setInstallerUid(callingUid);
 
-        verificationParams.setInstallerUid(uid);
-
+        final File originFile = new File(originPath);
         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
 
         final Message msg = mHandler.obtainMessage(INIT_COPY);
-        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
+        msg.obj = new InstallParams(origin, observer, installFlags,
                 installerPackageName, verificationParams, user, packageAbiOverride);
         mHandler.sendMessage(msg);
     }
@@ -11011,45 +11012,40 @@
             Slog.w(TAG, "Attempt to delete null packageName.");
             return false;
         }
+
+        // Try finding details about the requested package
         PackageParser.Package pkg;
-        boolean dataOnly = false;
-        final int appId;
         synchronized (mPackages) {
             pkg = mPackages.get(packageName);
             if (pkg == null) {
-                dataOnly = true;
-                PackageSetting ps = mSettings.mPackages.get(packageName);
-                if ((ps == null) || (ps.pkg == null)) {
-                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
-                    return false;
+                final PackageSetting ps = mSettings.mPackages.get(packageName);
+                if (ps != null) {
+                    pkg = ps.pkg;
                 }
-                pkg = ps.pkg;
-            }
-            if (!dataOnly) {
-                // need to check this only for fully installed applications
-                if (pkg == null) {
-                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
-                    return false;
-                }
-                final ApplicationInfo applicationInfo = pkg.applicationInfo;
-                if (applicationInfo == null) {
-                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
-                    return false;
-                }
-            }
-            if (pkg != null && pkg.applicationInfo != null) {
-                appId = pkg.applicationInfo.uid;
-            } else {
-                appId = -1;
             }
         }
+
+        if (pkg == null) {
+            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
+        }
+
+        // Always delete data directories for package, even if we found no other
+        // record of app. This helps users recover from UID mismatches without
+        // resorting to a full data wipe.
         int retCode = mInstaller.clearUserData(packageName, userId);
         if (retCode < 0) {
-            Slog.w(TAG, "Couldn't remove cache files for package: "
-                    + packageName);
+            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
             return false;
         }
-        removeKeystoreDataIfNeeded(userId, appId);
+
+        if (pkg == null) {
+            return false;
+        }
+
+        if (pkg != null && pkg.applicationInfo != null) {
+            final int appId = pkg.applicationInfo.uid;
+            removeKeystoreDataIfNeeded(userId, appId);
+        }
 
         // Create a native library symlink only if we have native libraries
         // and if the native libraries are 32 bit libraries. We do not provide
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index 7808800..0a4b3bc 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -814,7 +814,7 @@
                         + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
             }
 
-            if ((flags & PowerManager.WAIT_FOR_DISTANT_PROXIMITY) != 0) {
+            if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
                 mRequestWaitForNegativeProximity = true;
             }
 
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index 50e417b..da5cfda 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -252,6 +252,10 @@
         final boolean showImeOverKeyguard = imeTarget != null && imeTarget.isVisibleNow() &&
                 (imeTarget.getAttrs().flags & FLAG_SHOW_WHEN_LOCKED) != 0;
 
+        final WindowState winShowWhenLocked = (WindowState) mPolicy.getWinShowWhenLockedLw();
+        final AppWindowToken appShowWhenLocked = winShowWhenLocked == null ?
+                null : winShowWhenLocked.mAppToken;
+
         for (int i = windows.size() - 1; i >= 0; i--) {
             WindowState win = windows.get(i);
             WindowStateAnimator winAnimator = win.mWinAnimator;
@@ -316,8 +320,8 @@
                             + " hidden=" + win.mRootToken.hidden
                             + " anim=" + win.mWinAnimator.mAnimation);
                 } else if (mPolicy.canBeForceHidden(win, win.mAttrs)) {
-                    final boolean hideWhenLocked = (flags & FLAG_SHOW_WHEN_LOCKED) == 0 &&
-                            !(win.mIsImWindow && showImeOverKeyguard);
+                    final boolean hideWhenLocked = !((win.mIsImWindow && showImeOverKeyguard) ||
+                            (appShowWhenLocked != null && appShowWhenLocked == win.mAppToken));
                     final boolean changed;
                     if (((mForceHiding == KEYGUARD_ANIMATING_IN)
                                 && (!winAnimator.isAnimating() || hideWhenLocked))
@@ -454,7 +458,10 @@
                     }
                     final int color = winAnimator.mAnimation.getBackgroundColor();
                     if (color != 0) {
-                        win.getStack().setAnimationBackground(winAnimator, color);
+                        final TaskStack stack = win.getStack();
+                        if (stack != null) {
+                            stack.setAnimationBackground(winAnimator, color);
+                        }
                     }
                 }
                 mAnimating = true;
@@ -473,7 +480,10 @@
 
                 final int color = appAnimator.animation.getBackgroundColor();
                 if (color != 0) {
-                    win.getStack().setAnimationBackground(winAnimator, color);
+                    final TaskStack stack = win.getStack();
+                    if (stack != null) {
+                        stack.setAnimationBackground(winAnimator, color);
+                    }
                 }
             }
         } // end forall windows
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index b7e56cb..9033f30 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -8556,7 +8556,8 @@
                 layerChanged = true;
                 anyLayerChanged = true;
             }
-            if (layerChanged && w.getStack().isDimming(winAnimator)) {
+            final TaskStack stack = w.getStack();
+            if (layerChanged && stack != null && stack.isDimming(winAnimator)) {
                 // Force an animation pass just to update the mDimLayer layer.
                 scheduleAnimationLocked();
             }
@@ -9380,6 +9381,9 @@
                 && !w.mExiting) {
             final WindowStateAnimator winAnimator = w.mWinAnimator;
             final TaskStack stack = w.getStack();
+            if (stack == null) {
+                return;
+            }
             stack.setDimmingTag();
             if (!stack.isDimming(winAnimator)) {
                 if (localLOGV) Slog.v(TAG, "Win " + w + " start dimming.");
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index dd611ce..da97876 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -1368,7 +1368,10 @@
                 mAnimator.setPendingLayoutChanges(w.getDisplayId(),
                         WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER);
                 if ((w.mAttrs.flags & LayoutParams.FLAG_DIM_BEHIND) != 0) {
-                    w.getStack().startDimmingIfNeeded(this);
+                    final TaskStack stack = w.getStack();
+                    if (stack != null) {
+                        stack.startDimmingIfNeeded(this);
+                    }
                 }
             } catch (RuntimeException e) {
                 // If something goes wrong with the surface (such
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 8e82e2a..95332bc 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -19,6 +19,7 @@
 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
 
 import android.accessibilityservice.AccessibilityServiceInfo;
+import android.accounts.AccountManager;
 import android.app.Activity;
 import android.app.ActivityManagerNative;
 import android.app.AlarmManager;
@@ -3579,7 +3580,7 @@
                     + " for device owner");
         }
         synchronized (this) {
-            if (isDeviceProvisioned()) {
+            if (!allowedToSetDeviceOwnerOnDevice()) {
                 throw new IllegalStateException(
                         "Trying to set device owner but device is already provisioned.");
             }
@@ -3715,7 +3716,7 @@
         synchronized (this) {
             // Only SYSTEM_UID can override the userSetupComplete
             if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID
-                    && isUserSetupComplete(userHandle)) {
+                    && hasUserSetupCompleted(userHandle)) {
                 throw new IllegalStateException(
                         "Trying to set profile owner but user is already set-up.");
             }
@@ -3772,10 +3773,14 @@
 
     @Override
     public boolean hasUserSetupCompleted() {
+        return hasUserSetupCompleted(UserHandle.getCallingUserId());
+    }
+
+    private boolean hasUserSetupCompleted(int userHandle) {
         if (!mHasFeature) {
             return true;
         }
-        DevicePolicyData policy = getUserData(UserHandle.getCallingUserId());
+        DevicePolicyData policy = getUserData(userHandle);
         // If policy is null, return true, else check if the setup has completed.
         return policy == null || policy.mUserSetupComplete;
     }
@@ -3878,14 +3883,17 @@
         return null;
     }
 
-    private boolean isDeviceProvisioned() {
-        return Settings.Global.getInt(mContext.getContentResolver(),
-                Settings.Global.DEVICE_PROVISIONED, 0) > 0;
-    }
-
-    private boolean isUserSetupComplete(int userId) {
-        return Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) > 0;
+    /**
+     * Device owner can only be set on an unprovisioned device, unless it was initiated by "adb", in
+     * which case we allow it if no account is associated with the device.
+     */
+    private boolean allowedToSetDeviceOwnerOnDevice() {
+        int callingId = Binder.getCallingUid();
+        if (callingId == Process.SHELL_UID || callingId == Process.ROOT_UID) {
+            return AccountManager.get(mContext).getAccounts().length == 0;
+        } else {
+            return !hasUserSetupCompleted(UserHandle.USER_OWNER);
+        }
     }
 
     private void enforceCrossUserPermission(int userHandle) {
diff --git a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
index 62a7ec0..972c929 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
@@ -61,7 +61,7 @@
     /**
      * Initialize any directories required and index what stats are available.
      */
-    void init() {
+    public void init(long currentTimeMillis) {
         synchronized (mLock) {
             for (File f : mIntervalDirs) {
                 f.mkdirs();
@@ -72,27 +72,53 @@
             }
 
             checkVersionLocked();
+            indexFilesLocked();
 
-            final FilenameFilter backupFileFilter = new FilenameFilter() {
-                @Override
-                public boolean accept(File dir, String name) {
-                    return !name.endsWith(".bak");
+            // Delete files that are in the future.
+            for (TimeSparseArray<AtomicFile> files : mSortedStatFiles) {
+                final int startIndex = files.closestIndexOnOrAfter(currentTimeMillis);
+                if (startIndex < 0) {
+                    continue;
                 }
-            };
 
-            // Index the available usage stat files on disk.
-            for (int i = 0; i < mSortedStatFiles.length; i++) {
+                final int fileCount = files.size();
+                for (int i = startIndex; i < fileCount; i++) {
+                    files.valueAt(i).delete();
+                }
+
+                // Remove in a separate loop because any accesses (valueAt)
+                // will cause a gc in the SparseArray and mess up the order.
+                for (int i = startIndex; i < fileCount; i++) {
+                    files.removeAt(i);
+                }
+            }
+        }
+    }
+
+    private void indexFilesLocked() {
+        final FilenameFilter backupFileFilter = new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                return !name.endsWith(".bak");
+            }
+        };
+
+        // Index the available usage stat files on disk.
+        for (int i = 0; i < mSortedStatFiles.length; i++) {
+            if (mSortedStatFiles[i] == null) {
                 mSortedStatFiles[i] = new TimeSparseArray<>();
-                File[] files = mIntervalDirs[i].listFiles(backupFileFilter);
-                if (files != null) {
-                    if (DEBUG) {
-                        Slog.d(TAG, "Found " + files.length + " stat files for interval " + i);
-                    }
+            } else {
+                mSortedStatFiles[i].clear();
+            }
+            File[] files = mIntervalDirs[i].listFiles(backupFileFilter);
+            if (files != null) {
+                if (DEBUG) {
+                    Slog.d(TAG, "Found " + files.length + " stat files for interval " + i);
+                }
 
-                    for (File f : files) {
-                        final AtomicFile af = new AtomicFile(f);
-                        mSortedStatFiles[i].put(UsageStatsXml.parseBeginTime(af), af);
-                    }
+                for (File f : files) {
+                    final AtomicFile af = new AtomicFile(f);
+                    mSortedStatFiles[i].put(UsageStatsXml.parseBeginTime(af), af);
                 }
             }
         }
@@ -135,6 +161,38 @@
         }
     }
 
+    public void onTimeChanged(long timeDiffMillis) {
+        synchronized (mLock) {
+            for (TimeSparseArray<AtomicFile> files : mSortedStatFiles) {
+                final int fileCount = files.size();
+                for (int i = 0; i < fileCount; i++) {
+                    final AtomicFile file = files.valueAt(i);
+                    final long newTime = files.keyAt(i) + timeDiffMillis;
+                    if (newTime < 0) {
+                        Slog.i(TAG, "Deleting file " + file.getBaseFile().getAbsolutePath()
+                                + " for it is in the future now.");
+                        file.delete();
+                    } else {
+                        try {
+                            file.openRead().close();
+                        } catch (IOException e) {
+                            // Ignore, this is just to make sure there are no backups.
+                        }
+                        final File newFile = new File(file.getBaseFile().getParentFile(),
+                                Long.toString(newTime));
+                        Slog.i(TAG, "Moving file " + file.getBaseFile().getAbsolutePath() + " to "
+                                + newFile.getAbsolutePath());
+                        file.getBaseFile().renameTo(newFile);
+                    }
+                }
+                files.clear();
+            }
+
+            // Now re-index the new files.
+            indexFilesLocked();
+        }
+    }
+
     /**
      * Get the latest stats that exist for this interval type.
      */
@@ -296,25 +354,24 @@
     /**
      * Remove any usage stat files that are too old.
      */
-    public void prune() {
+    public void prune(final long currentTimeMillis) {
         synchronized (mLock) {
-            long timeNow = System.currentTimeMillis();
-            mCal.setTimeInMillis(timeNow);
+            mCal.setTimeInMillis(currentTimeMillis);
             mCal.addYears(-3);
             pruneFilesOlderThan(mIntervalDirs[UsageStatsManager.INTERVAL_YEARLY],
                     mCal.getTimeInMillis());
 
-            mCal.setTimeInMillis(timeNow);
+            mCal.setTimeInMillis(currentTimeMillis);
             mCal.addMonths(-6);
             pruneFilesOlderThan(mIntervalDirs[UsageStatsManager.INTERVAL_MONTHLY],
                     mCal.getTimeInMillis());
 
-            mCal.setTimeInMillis(timeNow);
+            mCal.setTimeInMillis(currentTimeMillis);
             mCal.addWeeks(-4);
             pruneFilesOlderThan(mIntervalDirs[UsageStatsManager.INTERVAL_WEEKLY],
                     mCal.getTimeInMillis());
 
-            mCal.setTimeInMillis(timeNow);
+            mCal.setTimeInMillis(currentTimeMillis);
             mCal.addDays(-7);
             pruneFilesOlderThan(mIntervalDirs[UsageStatsManager.INTERVAL_DAILY],
                     mCal.getTimeInMillis());
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index 92117c3..2ed9745 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -65,6 +65,7 @@
     private static final long TEN_SECONDS = 10 * 1000;
     private static final long TWENTY_MINUTES = 20 * 60 * 1000;
     private static final long FLUSH_INTERVAL = DEBUG ? TEN_SECONDS : TWENTY_MINUTES;
+    private static final long TIME_CHANGE_THRESHOLD_MILLIS = 2 * 1000; // Two seconds.
 
     // Handler message types.
     static final int MSG_REPORT_EVENT = 0;
@@ -171,18 +172,47 @@
         }
     }
 
-    private UserUsageStatsService getUserDataAndInitializeIfNeededLocked(int userId) {
+    private UserUsageStatsService getUserDataAndInitializeIfNeededLocked(int userId,
+            long currentTimeMillis) {
         UserUsageStatsService service = mUserState.get(userId);
         if (service == null) {
             service = new UserUsageStatsService(userId,
                     new File(mUsageStatsDir, Integer.toString(userId)), this);
-            service.init();
+            service.init(currentTimeMillis);
             mUserState.put(userId, service);
         }
         return service;
     }
 
     /**
+     * This should be the only way to get the time from the system.
+     */
+    private long checkAndGetTimeLocked() {
+        final long actualSystemTime = System.currentTimeMillis();
+        final long actualRealtime = SystemClock.elapsedRealtime();
+        final long expectedSystemTime = (actualRealtime - mRealTimeSnapshot) + mSystemTimeSnapshot;
+        if (Math.abs(actualSystemTime - expectedSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) {
+            // The time has changed.
+            final int userCount = mUserState.size();
+            for (int i = 0; i < userCount; i++) {
+                final UserUsageStatsService service = mUserState.valueAt(i);
+                service.onTimeChanged(expectedSystemTime, actualSystemTime);
+            }
+            mRealTimeSnapshot = actualRealtime;
+            mSystemTimeSnapshot = actualSystemTime;
+        }
+        return actualSystemTime;
+    }
+
+    /**
+     * Assuming the event's timestamp is measured in milliseconds since boot,
+     * convert it to a system wall time.
+     */
+    private void convertToSystemTimeLocked(UsageEvents.Event event) {
+        event.mTimeStamp = Math.max(0, event.mTimeStamp - mRealTimeSnapshot) + mSystemTimeSnapshot;
+    }
+
+    /**
      * Called by the Binder stub
      */
     void shutdown() {
@@ -197,7 +227,11 @@
      */
     void reportEvent(UsageEvents.Event event, int userId) {
         synchronized (mLock) {
-            final UserUsageStatsService service = getUserDataAndInitializeIfNeededLocked(userId);
+            final long timeNow = checkAndGetTimeLocked();
+            convertToSystemTimeLocked(event);
+
+            final UserUsageStatsService service =
+                    getUserDataAndInitializeIfNeededLocked(userId, timeNow);
             service.reportEvent(event);
         }
     }
@@ -226,12 +260,14 @@
      * Called by the Binder stub.
      */
     List<UsageStats> queryUsageStats(int userId, int bucketType, long beginTime, long endTime) {
-        if (!validRange(beginTime, endTime)) {
-            return null;
-        }
-
         synchronized (mLock) {
-            UserUsageStatsService service = getUserDataAndInitializeIfNeededLocked(userId);
+            final long timeNow = checkAndGetTimeLocked();
+            if (!validRange(timeNow, beginTime, endTime)) {
+                return null;
+            }
+
+            final UserUsageStatsService service =
+                    getUserDataAndInitializeIfNeededLocked(userId, timeNow);
             return service.queryUsageStats(bucketType, beginTime, endTime);
         }
     }
@@ -241,12 +277,14 @@
      */
     List<ConfigurationStats> queryConfigurationStats(int userId, int bucketType, long beginTime,
             long endTime) {
-        if (!validRange(beginTime, endTime)) {
-            return null;
-        }
-
         synchronized (mLock) {
-            UserUsageStatsService service = getUserDataAndInitializeIfNeededLocked(userId);
+            final long timeNow = checkAndGetTimeLocked();
+            if (!validRange(timeNow, beginTime, endTime)) {
+                return null;
+            }
+
+            final UserUsageStatsService service =
+                    getUserDataAndInitializeIfNeededLocked(userId, timeNow);
             return service.queryConfigurationStats(bucketType, beginTime, endTime);
         }
     }
@@ -255,19 +293,20 @@
      * Called by the Binder stub.
      */
     UsageEvents queryEvents(int userId, long beginTime, long endTime) {
-        if (!validRange(beginTime, endTime)) {
-            return null;
-        }
-
         synchronized (mLock) {
-            UserUsageStatsService service = getUserDataAndInitializeIfNeededLocked(userId);
+            final long timeNow = checkAndGetTimeLocked();
+            if (!validRange(timeNow, beginTime, endTime)) {
+                return null;
+            }
+
+            final UserUsageStatsService service =
+                    getUserDataAndInitializeIfNeededLocked(userId, timeNow);
             return service.queryEvents(beginTime, endTime);
         }
     }
 
-    private static boolean validRange(long beginTime, long endTime) {
-        final long timeNow = System.currentTimeMillis();
-        return beginTime <= timeNow && beginTime < endTime;
+    private static boolean validRange(long currentTime, long beginTime, long endTime) {
+        return beginTime <= currentTime && beginTime < endTime;
     }
 
     private void flushToDiskLocked() {
@@ -387,14 +426,6 @@
      */
     private class LocalService extends UsageStatsManagerInternal {
 
-        /**
-         * The system may have its time change, so at least make sure the events
-         * are monotonic in order.
-         */
-        private long computeMonotonicSystemTime(long realTime) {
-            return (realTime - mRealTimeSnapshot) + mSystemTimeSnapshot;
-        }
-
         @Override
         public void reportEvent(ComponentName component, int userId, int eventType) {
             if (component == null) {
@@ -405,7 +436,10 @@
             UsageEvents.Event event = new UsageEvents.Event();
             event.mPackage = component.getPackageName();
             event.mClass = component.getClassName();
-            event.mTimeStamp = computeMonotonicSystemTime(SystemClock.elapsedRealtime());
+
+            // This will later be converted to system time.
+            event.mTimeStamp = SystemClock.elapsedRealtime();
+
             event.mEventType = eventType;
             mHandler.obtainMessage(MSG_REPORT_EVENT, userId, 0, event).sendToTarget();
         }
@@ -419,7 +453,10 @@
 
             UsageEvents.Event event = new UsageEvents.Event();
             event.mPackage = "android";
-            event.mTimeStamp = computeMonotonicSystemTime(SystemClock.elapsedRealtime());
+
+            // This will later be converted to system time.
+            event.mTimeStamp = SystemClock.elapsedRealtime();
+
             event.mEventType = UsageEvents.Event.CONFIGURATION_CHANGE;
             event.mConfiguration = new Configuration(config);
             mHandler.obtainMessage(MSG_REPORT_EVENT, userId, 0, event).sendToTarget();
diff --git a/services/usage/java/com/android/server/usage/UserUsageStatsService.java b/services/usage/java/com/android/server/usage/UserUsageStatsService.java
index 2769666..4916ec2 100644
--- a/services/usage/java/com/android/server/usage/UserUsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UserUsageStatsService.java
@@ -22,6 +22,7 @@
 import android.app.usage.UsageStats;
 import android.app.usage.UsageStatsManager;
 import android.content.res.Configuration;
+import android.os.SystemClock;
 import android.util.ArraySet;
 import android.util.Slog;
 
@@ -62,10 +63,9 @@
         mLogPrefix = "User[" + Integer.toString(userId) + "] ";
     }
 
-    void init() {
-        mDatabase.init();
+    void init(final long currentTimeMillis) {
+        mDatabase.init(currentTimeMillis);
 
-        final long timeNow = System.currentTimeMillis();
         int nullCount = 0;
         for (int i = 0; i < mCurrentStats.length; i++) {
             mCurrentStats[i] = mDatabase.getLatestUsageStats(i);
@@ -73,11 +73,6 @@
                 // Find out how many intervals we don't have data for.
                 // Ideally it should be all or none.
                 nullCount++;
-            } else if (mCurrentStats[i].beginTime > timeNow) {
-                Slog.e(TAG, mLogPrefix + "Interval " + i + " has stat in the future " +
-                        mCurrentStats[i].beginTime);
-                mCurrentStats[i] = null;
-                nullCount++;
             }
         }
 
@@ -92,7 +87,7 @@
 
             // By calling loadActiveStats, we will
             // generate new stats for each bucket.
-            loadActiveStats();
+            loadActiveStats(currentTimeMillis, false);
         } else {
             // Set up the expiry date to be one day from the latest daily stat.
             // This may actually be today and we will rollover on the first event
@@ -123,6 +118,12 @@
         }
     }
 
+    void onTimeChanged(long oldTime, long newTime) {
+        persistActiveStats();
+        mDatabase.onTimeChanged(newTime - oldTime);
+        loadActiveStats(newTime, true);
+    }
+
     void reportEvent(UsageEvents.Event event) {
         if (DEBUG) {
             Slog.d(TAG, mLogPrefix + "Got usage event for " + event.mPackage
@@ -132,7 +133,7 @@
 
         if (event.mTimeStamp >= mDailyExpiryDate.getTimeInMillis()) {
             // Need to rollover
-            rolloverStats();
+            rolloverStats(event.mTimeStamp);
         }
 
         final IntervalStats currentDailyStats = mCurrentStats[UsageStatsManager.INTERVAL_DAILY];
@@ -330,8 +331,8 @@
         }
     }
 
-    private void rolloverStats() {
-        final long startTime = System.currentTimeMillis();
+    private void rolloverStats(final long currentTimeMillis) {
+        final long startTime = SystemClock.elapsedRealtime();
         Slog.i(TAG, mLogPrefix + "Rolling over usage stats");
 
         // Finish any ongoing events with an END_OF_DAY event. Make a note of which components
@@ -348,7 +349,7 @@
                     continuePreviousDay.add(pkgStats.mPackageName);
                     stat.update(pkgStats.mPackageName, mDailyExpiryDate.getTimeInMillis() - 1,
                             UsageEvents.Event.END_OF_DAY);
-                    mStatsChanged = true;
+                    notifyStatsChanged();
                 }
             }
 
@@ -356,8 +357,8 @@
         }
 
         persistActiveStats();
-        mDatabase.prune();
-        loadActiveStats();
+        mDatabase.prune(currentTimeMillis);
+        loadActiveStats(currentTimeMillis, false);
 
         final int continueCount = continuePreviousDay.size();
         for (int i = 0; i < continueCount; i++) {
@@ -366,12 +367,12 @@
             for (IntervalStats stat : mCurrentStats) {
                 stat.update(name, beginTime, UsageEvents.Event.CONTINUE_PREVIOUS_DAY);
                 stat.updateConfigurationStats(previousConfig, beginTime);
-                mStatsChanged = true;
+                notifyStatsChanged();
             }
         }
         persistActiveStats();
 
-        final long totalTime = System.currentTimeMillis() - startTime;
+        final long totalTime = SystemClock.elapsedRealtime() - startTime;
         Slog.i(TAG, mLogPrefix + "Rolling over usage stats complete. Took " + totalTime
                 + " milliseconds");
     }
@@ -383,15 +384,16 @@
         }
     }
 
-    private void loadActiveStats() {
-        final long timeNow = System.currentTimeMillis();
-
+    /**
+     * @param force To force all in-memory stats to be reloaded.
+     */
+    private void loadActiveStats(final long currentTimeMillis, boolean force) {
         final UnixCalendar tempCal = mDailyExpiryDate;
         for (int intervalType = 0; intervalType < mCurrentStats.length; intervalType++) {
-            tempCal.setTimeInMillis(timeNow);
+            tempCal.setTimeInMillis(currentTimeMillis);
             UnixCalendar.truncateTo(tempCal, intervalType);
 
-            if (mCurrentStats[intervalType] != null &&
+            if (!force && mCurrentStats[intervalType] != null &&
                     mCurrentStats[intervalType].beginTime == tempCal.getTimeInMillis()) {
                 // These are the same, no need to load them (in memory stats are always newer
                 // than persisted stats).
@@ -399,11 +401,7 @@
             }
 
             final long lastBeginTime = mDatabase.getLatestUsageStatsBeginTime(intervalType);
-            if (lastBeginTime > timeNow) {
-                Slog.e(TAG, mLogPrefix + "Latest usage stats for interval " +
-                        intervalType + " begins in the future");
-                mCurrentStats[intervalType] = null;
-            } else if (lastBeginTime >= tempCal.getTimeInMillis()) {
+            if (lastBeginTime >= tempCal.getTimeInMillis()) {
                 if (DEBUG) {
                     Slog.d(TAG, mLogPrefix + "Loading existing stats @ " +
                             sDateFormat.format(lastBeginTime) + "(" + lastBeginTime +
@@ -423,11 +421,11 @@
                 }
                 mCurrentStats[intervalType] = new IntervalStats();
                 mCurrentStats[intervalType].beginTime = tempCal.getTimeInMillis();
-                mCurrentStats[intervalType].endTime = timeNow;
+                mCurrentStats[intervalType].endTime = currentTimeMillis;
             }
         }
         mStatsChanged = false;
-        mDailyExpiryDate.setTimeInMillis(timeNow);
+        mDailyExpiryDate.setTimeInMillis(currentTimeMillis);
         mDailyExpiryDate.addDays(1);
         mDailyExpiryDate.truncateToDay();
         Slog.i(TAG, mLogPrefix + "Rollover scheduled @ " +
diff --git a/telecomm/java/android/telecomm/ConnectionService.java b/telecomm/java/android/telecomm/ConnectionService.java
index 036d397..05ddc27 100644
--- a/telecomm/java/android/telecomm/ConnectionService.java
+++ b/telecomm/java/android/telecomm/ConnectionService.java
@@ -498,6 +498,13 @@
         return mBinder;
     }
 
+    /** {@inheritDoc} */
+    @Override
+    public boolean onUnbind(Intent intent) {
+        endAllConnections();
+        return super.onUnbind(intent);
+    }
+
     /**
      * This can be used by telecomm to either create a new outgoing call or attach to an existing
      * incoming call. In either case, telecomm will cycle through a set of services and call
@@ -951,4 +958,17 @@
         }
         return sNullConference;
     }
+
+    private void endAllConnections() {
+        // Unbound from telecomm.  We should end all connections and conferences.
+        for (Connection connection : mIdByConnection.keySet()) {
+            // only operate on top-level calls. Conference calls will be removed on their own.
+            if (connection.getConference() == null) {
+                connection.onDisconnect();
+            }
+        }
+        for (Conference conference : mIdByConference.keySet()) {
+            conference.onDisconnect();
+        }
+    }
 }
diff --git a/telecomm/java/android/telecomm/TelecommManager.java b/telecomm/java/android/telecomm/TelecommManager.java
index a19f51b..e2c98cd 100644
--- a/telecomm/java/android/telecomm/TelecommManager.java
+++ b/telecomm/java/android/telecomm/TelecommManager.java
@@ -70,6 +70,24 @@
             "android.telecomm.action.CHANGE_PHONE_ACCOUNTS";
 
     /**
+     * The {@link android.content.Intent} action used to inform a
+     * {@link android.telecomm.ConnectionService} that one of its {@link PhoneAccount}s has been
+     * enabled.  The {@link TelecommManager#EXTRA_PHONE_ACCOUNT_HANDLE} extra is used to indicate
+     * which {@link PhoneAccount} has been enabled.
+     */
+    public static final String ACTION_PHONE_ACCOUNT_ENABLED =
+            "android.telecom.action.PHONE_ACCOUNT_ENABLED";
+
+    /**
+     * The {@link android.content.Intent} action used to inform a
+     * {@link android.telecomm.ConnectionService} that one of its {@link PhoneAccount}s has been
+     * disabled.  The {@link TelecommManager#EXTRA_PHONE_ACCOUNT_HANDLE} extra is used to indicate
+     * which {@link PhoneAccount} has been disabled.
+     */
+    public static final String ACTION_PHONE_ACCOUNT_DISABLED =
+            "android.telecom.action.PHONE_ACCOUNT_DISABLED";
+
+    /**
      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a boolean that
      * determines whether the speakerphone should be automatically turned on for an outgoing call.
      */
diff --git a/telephony/java/com/android/internal/telephony/IMms.aidl b/telephony/java/com/android/internal/telephony/IMms.aidl
index 4337012..ebfefd1 100644
--- a/telephony/java/com/android/internal/telephony/IMms.aidl
+++ b/telephony/java/com/android/internal/telephony/IMms.aidl
@@ -62,24 +62,37 @@
 
     /**
      * Update the status of a pending (send-by-IP) MMS message handled by the carrier app.
-     * If the carrier app fails to send this message, it would be resent via carrier network.
+     * If the carrier app fails to send this message, it may be resent via carrier network
+     * depending on the status code.
+     *
+     * The caller should have carrier privileges.
+     * @see android.telephony.TelephonyManager.hasCarrierPrivileges
      *
      * @param messageRef the reference number of the MMS message.
-     * @param success True if and only if the message was sent successfully. If its value is
-     *  false, this message should be resent via carrier network
+     * @param pdu non-empty (contains the SendConf PDU) if the message was sent successfully,
+     *   otherwise, this param should be null.
+     * @param status send status. It can be Activity.RESULT_OK or one of the MMS error codes.
+     *   If status is Activity.RESULT_OK, the MMS was sent successfully.
+     *   If status is MMS_ERROR_RETRY, this message would be resent via carrier
+     *   network. The message will not be resent for other MMS error statuses.
      */
-    void updateMmsSendStatus(int messageRef, boolean success);
+    void updateMmsSendStatus(int messageRef, in byte[] pdu, in int status);
 
     /**
      * Update the status of a pending (download-by-IP) MMS message handled by the carrier app.
-     * If the carrier app fails to download this message, it would be re-downloaded via carrier
-     * network.
+     * If the carrier app fails to download this message, it may be re-downloaded via carrier
+     * network depending on the status code.
+     *
+     * The caller should have carrier privileges.
+     * @see android.telephony.TelephonyManager.hasCarrierPrivileges
      *
      * @param messageRef the reference number of the MMS message.
-     * @param pdu non-empty if downloaded successfully, otherwise, it is empty and the message
-     *  will be downloaded via carrier network
+     * @param status download status.  It can be Activity.RESULT_OK or one of the MMS error codes.
+     *   If status is Activity.RESULT_OK, the MMS was downloaded successfully.
+     *   If status is MMS_ERROR_RETRY, this message would be re-downloaded via carrier
+     *   network. The message will not be re-downloaded for other MMS error statuses.
      */
-    void updateMmsDownloadStatus(int messageRef, in byte[] pdu);
+    void updateMmsDownloadStatus(int messageRef, in int status);
 
     /**
      * Get carrier-dependent configuration values.
diff --git a/tests/StatusBar/src/com/android/statusbartest/PowerTest.java b/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
index 2ec620b..52527d9 100644
--- a/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
+++ b/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
@@ -77,9 +77,9 @@
                 mProx.release();
             }
         },
-        new Test("Disable proximity (WAIT_FOR_DISTANT_PROXIMITY") {
+        new Test("Disable proximity (RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY") {
             public void run() {
-                mProx.release(PowerManager.WAIT_FOR_DISTANT_PROXIMITY);
+                mProx.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
             }
         },
         new Test("Enable proximity, wait 5 seconds then disable") {
@@ -93,13 +93,14 @@
                 }, 5000);
             }
         },
-        new Test("Enable proximity, wait 5 seconds then disable  (WAIT_FOR_DISTANT_PROXIMITY)") {
+        new Test("Enable proximity, wait 5 seconds then disable " +
+                "(RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY)") {
             public void run() {
                 mProx.acquire();
                 mHandler.postDelayed(new Runnable() {
                     @Override
                     public void run() {
-                        mProx.release(PowerManager.WAIT_FOR_DISTANT_PROXIMITY);
+                        mProx.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
                     }
                 }, 5000);
             }
diff --git a/tests/UsageStatsTest/src/com/android/tests/usagestats/UsageLogActivity.java b/tests/UsageStatsTest/src/com/android/tests/usagestats/UsageLogActivity.java
index 31e7c38..d9a3b61 100644
--- a/tests/UsageStatsTest/src/com/android/tests/usagestats/UsageLogActivity.java
+++ b/tests/UsageStatsTest/src/com/android/tests/usagestats/UsageLogActivity.java
@@ -86,7 +86,10 @@
                 }
                 mEvents.addFirst(event);
             }
-            notifyDataSetChanged();
+
+            if (lastTimeStamp != 0) {
+                notifyDataSetChanged();
+            }
             return lastTimeStamp;
         }
 
diff --git a/core/res/res/values-sw600dp-land/dimens_material.xml b/tests/VectorDrawableTest/res/anim/trim_path_animation06.xml
similarity index 61%
copy from core/res/res/values-sw600dp-land/dimens_material.xml
copy to tests/VectorDrawableTest/res/anim/trim_path_animation06.xml
index f8f16e2..1a81866 100644
--- a/core/res/res/values-sw600dp-land/dimens_material.xml
+++ b/tests/VectorDrawableTest/res/anim/trim_path_animation06.xml
@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
+<!--
+ Copyright (C) 2014 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.
@@ -13,11 +14,12 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<resources>
 
-    <!-- Use the default title sizes on tablets. -->
-    <dimen name="text_size_title_material_toolbar">@dimen/text_size_title_material</dimen>
-    <!-- Use the default subtitle sizes on tablets. -->
-    <dimen name="text_size_subtitle_material_toolbar">@dimen/text_size_subhead_material</dimen>
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:duration="9000"
+        android:propertyName="alpha"
+        android:valueFrom="1.0"
+        android:valueTo="0.0"/>
 
-</resources>
+</set>
\ No newline at end of file
diff --git a/tests/VectorDrawableTest/res/drawable/animation_vector_drawable01.xml b/tests/VectorDrawableTest/res/drawable/animation_vector_drawable01.xml
index 19b82ad..8b0ceda 100644
--- a/tests/VectorDrawableTest/res/drawable/animation_vector_drawable01.xml
+++ b/tests/VectorDrawableTest/res/drawable/animation_vector_drawable01.xml
@@ -37,5 +37,8 @@
     <target
         android:name="rotationGroup"
         android:animation="@anim/trim_path_animation04" />
+    <target
+        android:name="rootGroup"
+        android:animation="@anim/trim_path_animation06" />
 
 </animated-vector>
\ No newline at end of file
diff --git a/tests/VectorDrawableTest/res/drawable/vector_drawable12.xml b/tests/VectorDrawableTest/res/drawable/vector_drawable12.xml
index 2c8b751..69ae62c 100644
--- a/tests/VectorDrawableTest/res/drawable/vector_drawable12.xml
+++ b/tests/VectorDrawableTest/res/drawable/vector_drawable12.xml
@@ -14,10 +14,12 @@
      limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:name="rootGroup"
         android:height="64dp"
         android:width="64dp"
         android:viewportHeight="600"
-        android:viewportWidth="600" >
+        android:viewportWidth="600"
+        android:alpha="0.5" >
 
     <group
         android:name="rotationGroup"
diff --git a/tests/VectorDrawableTest/src/com/android/test/dynamic/AnimatedVectorDrawableTest.java b/tests/VectorDrawableTest/src/com/android/test/dynamic/AnimatedVectorDrawableTest.java
index f165cde..05bf166 100644
--- a/tests/VectorDrawableTest/src/com/android/test/dynamic/AnimatedVectorDrawableTest.java
+++ b/tests/VectorDrawableTest/src/com/android/test/dynamic/AnimatedVectorDrawableTest.java
@@ -31,6 +31,8 @@
             R.drawable.animation_vector_progress_bar,
             R.drawable.animation_vector_drawable_favorite,
             R.drawable.animation_vector_drawable01,
+            // Duplicate to test constant state.
+            R.drawable.animation_vector_drawable01,
     };
 
     @Override