Merge "OverlayPlugin listener method called from main thread"
diff --git a/Android.bp b/Android.bp
index c6cf75d..ecdc082 100644
--- a/Android.bp
+++ b/Android.bp
@@ -117,7 +117,6 @@
         "core/java/android/app/timedetector/ITimeDetectorService.aidl",
         "core/java/android/app/timezone/ICallback.aidl",
         "core/java/android/app/timezone/IRulesManager.aidl",
-        "core/java/android/app/timezonedetector/ITimeZoneDetectorService.aidl",
         "core/java/android/app/usage/ICacheQuotaService.aidl",
         "core/java/android/app/usage/IStorageStatsManager.aidl",
         "core/java/android/app/usage/IUsageStatsManager.aidl",
@@ -735,6 +734,7 @@
     no_framework_libs: true,
     libs: [
         "ext",
+        "updatable_media_stubs",
     ],
 
     jarjar_rules: "jarjar_rules_hidl.txt",
@@ -1296,7 +1296,7 @@
         ":non_openjdk_javadoc_files",
         ":android_icu4j_src_files_for_docs",
         ":conscrypt_public_api_files",
-        ":media-srcs-without-aidls",
+        ":updatable-media-srcs-without-aidls",
         "test-mock/src/**/*.java",
         "test-runner/src/**/*.java",
     ],
@@ -1358,7 +1358,7 @@
         ":non_openjdk_javadoc_files",
         ":android_icu4j_src_files_for_docs",
         ":conscrypt_public_api_files",
-        ":media-srcs-without-aidls",
+        ":updatable-media-srcs-without-aidls",
     ],
     srcs_lib: "framework",
     srcs_lib_whitelist_dirs: frameworks_base_subdirs,
diff --git a/Android.mk b/Android.mk
index e405345..65d4d24 100644
--- a/Android.mk
+++ b/Android.mk
@@ -78,6 +78,7 @@
 update-api: doc-comment-check-docs
 
 # ==== hiddenapi lists =======================================
+ifneq ($(UNSAFE_DISABLE_HIDDENAPI_FLAGS),true)
 .KATI_RESTAT: $(INTERNAL_PLATFORM_HIDDENAPI_FLAGS)
 $(INTERNAL_PLATFORM_HIDDENAPI_FLAGS): \
     PRIVATE_FLAGS_INPUTS := $(PRIVATE_FLAGS_INPUTS) $(SOONG_HIDDENAPI_FLAGS)
@@ -108,6 +109,7 @@
 
 $(call dist-for-goals,droidcore,$(INTERNAL_PLATFORM_HIDDENAPI_FLAGS))
 $(call dist-for-goals,droidcore,$(INTERNAL_PLATFORM_HIDDENAPI_GREYLIST_METADATA))
+endif  # UNSAFE_DISABLE_HIDDENAPI_FLAGS
 
 # Include subdirectory makefiles
 # ============================================================
diff --git a/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java b/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
index 11c7599..9234849 100644
--- a/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
+++ b/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
@@ -39,7 +39,8 @@
     @Rule
     public final PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
 
-    private final KernelCpuThreadReader mKernelCpuThreadReader = KernelCpuThreadReader.create();
+    private final KernelCpuThreadReader mKernelCpuThreadReader =
+            KernelCpuThreadReader.create(8, uid -> 1000 <= uid && uid < 2000);
 
     @Test
     public void timeReadCurrentProcessCpuUsage() {
diff --git a/api/current.txt b/api/current.txt
index 83de0b1..64f3885 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -1511,6 +1511,7 @@
     field public static final int use32bitAbi = 16844053; // 0x1010515
     field public static final int useAppZygote = 16844184; // 0x1010598
     field public static final int useDefaultMargins = 16843641; // 0x1010379
+    field public static final int useEmbeddedDex = 16844196; // 0x10105a4
     field public static final int useIntrinsicSizeAsMinimum = 16843536; // 0x1010310
     field public static final int useLevel = 16843167; // 0x101019f
     field public static final int userVisible = 16843409; // 0x1010291
@@ -6177,6 +6178,7 @@
     method public void onTrimMemory(int);
     method public boolean onUnbind(android.content.Intent);
     method public final void startForeground(int, android.app.Notification);
+    method public final void startForeground(int, @NonNull android.app.Notification, int);
     method public final void stopForeground(boolean);
     method public final void stopForeground(int);
     method public final void stopSelf();
@@ -11322,7 +11324,7 @@
 
   public final class ModuleInfo implements android.os.Parcelable {
     method public int describeContents();
-    method @Nullable public String getName();
+    method @Nullable public CharSequence getName();
     method @Nullable public String getPackageName();
     method public boolean isHidden();
     method public void writeToParcel(android.os.Parcel, int);
@@ -11929,13 +11931,13 @@
     field public static final int FLAG_SINGLE_USER = 1073741824; // 0x40000000
     field public static final int FLAG_STOP_WITH_TASK = 1; // 0x1
     field public static final int FLAG_USE_APP_ZYGOTE = 8; // 0x8
-    field public static final int FOREGROUND_SERVICE_TYPE_DEVICE_COMPANION = 5; // 0x5
-    field public static final int FOREGROUND_SERVICE_TYPE_LOCATION = 4; // 0x4
-    field public static final int FOREGROUND_SERVICE_TYPE_MEDIA_PLAY = 2; // 0x2
-    field public static final int FOREGROUND_SERVICE_TYPE_ONGOING_PROCESS = 6; // 0x6
-    field public static final int FOREGROUND_SERVICE_TYPE_PHONE_CALL = 3; // 0x3
-    field public static final int FOREGROUND_SERVICE_TYPE_SYNC = 1; // 0x1
-    field public static final int FOREGROUND_SERVICE_TYPE_UNSPECIFIED = 0; // 0x0
+    field public static final int FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE = 16; // 0x10
+    field public static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 1; // 0x1
+    field public static final int FOREGROUND_SERVICE_TYPE_LOCATION = 8; // 0x8
+    field public static final int FOREGROUND_SERVICE_TYPE_MANIFEST = -1; // 0xffffffff
+    field public static final int FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK = 2; // 0x2
+    field public static final int FOREGROUND_SERVICE_TYPE_NONE = 0; // 0x0
+    field public static final int FOREGROUND_SERVICE_TYPE_PHONE_CALL = 4; // 0x4
     field public int flags;
     field public String permission;
   }
@@ -12386,7 +12388,7 @@
     method public String getPositionDescription();
     method @AnyRes public int getResourceId(@StyleableRes int, int);
     method public android.content.res.Resources getResources();
-    method @StyleRes public int getSourceStyleResourceId(@StyleableRes int, @StyleRes int);
+    method @StyleRes public int getSourceResourceId(@StyleableRes int, @StyleRes int);
     method @Nullable public String getString(@StyleableRes int);
     method public CharSequence getText(@StyleableRes int);
     method public CharSequence[] getTextArray(@StyleableRes int);
@@ -24743,9 +24745,9 @@
     field public static final int KEY_TYPE_OFFLINE = 2; // 0x2
     field public static final int KEY_TYPE_RELEASE = 3; // 0x3
     field public static final int KEY_TYPE_STREAMING = 1; // 0x1
-    field public static final int OFFLINE_LICENSE_INACTIVE = 2; // 0x2
+    field public static final int OFFLINE_LICENSE_STATE_RELEASED = 2; // 0x2
     field public static final int OFFLINE_LICENSE_STATE_UNKNOWN = 0; // 0x0
-    field public static final int OFFLINE_LICENSE_USABLE = 1; // 0x1
+    field public static final int OFFLINE_LICENSE_STATE_USABLE = 1; // 0x1
     field public static final String PROPERTY_ALGORITHMS = "algorithms";
     field public static final String PROPERTY_DESCRIPTION = "description";
     field public static final String PROPERTY_DEVICE_UNIQUE_ID = "deviceUniqueId";
@@ -25506,7 +25508,7 @@
     method @Nullable public android.media.MediaTimestamp getTimestamp();
     method @NonNull public java.util.List<android.media.MediaPlayer2.TrackInfo> getTrackInfo();
     method @NonNull public java.util.List<android.media.MediaPlayer2.TrackInfo> getTrackInfo(@NonNull android.media.DataSourceDesc);
-    method public android.media.VideoSize getVideoSize();
+    method public android.util.Size getVideoSize();
     method public boolean isLooping();
     method public Object loopCurrent(boolean);
     method public Object notifyWhenCommandLabelReached(@NonNull Object);
@@ -25648,7 +25650,7 @@
     method public void onMediaTimeDiscontinuity(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaTimestamp);
     method public void onSubtitleData(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.SubtitleData);
     method public void onTimedMetaDataAvailable(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.TimedMetaData);
-    method public void onVideoSizeChanged(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.VideoSize);
+    method public void onVideoSizeChanged(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.util.Size);
   }
 
   public static final class MediaPlayer2.MetricsConstants {
@@ -26553,11 +26555,6 @@
     method @NonNull public android.media.UriDataSourceDesc.Builder setDataSource(@NonNull android.content.Context, @NonNull android.net.Uri, @Nullable java.util.Map<java.lang.String,java.lang.String>, @Nullable java.util.List<java.net.HttpCookie>);
   }
 
-  public final class VideoSize {
-    method public int getHeight();
-    method public int getWidth();
-  }
-
   public interface VolumeAutomation {
     method @NonNull public android.media.VolumeShaper createVolumeShaper(@NonNull android.media.VolumeShaper.Configuration);
   }
@@ -27527,7 +27524,6 @@
     method @NonNull public java.util.List<android.media.Session2Token> getSession2Tokens();
     method public boolean isTrustedForMediaControl(@NonNull android.media.session.MediaSessionManager.RemoteUserInfo);
     method public void notifySession2Created(@NonNull android.media.Session2Token);
-    method public void notifySession2Destroyed(@NonNull android.media.Session2Token);
     method public void removeOnActiveSessionsChangedListener(@NonNull android.media.session.MediaSessionManager.OnActiveSessionsChangedListener);
     method public void removeOnSession2TokensChangedListener(@NonNull android.media.session.MediaSessionManager.OnSession2TokensChangedListener);
   }
@@ -30581,6 +30577,7 @@
     method public int getNumSuccessfulMeasurements();
     method @Nullable public android.net.wifi.aware.PeerHandle getPeerHandle();
     method public long getRangingTimestampMillis();
+    method @Nullable public android.net.wifi.rtt.ResponderLocation getResponderLocation();
     method public int getRssi();
     method public int getStatus();
     method public void writeToParcel(android.os.Parcel, int);
@@ -30598,6 +30595,64 @@
     field public static final int STATUS_CODE_FAIL_RTT_NOT_AVAILABLE = 2; // 0x2
   }
 
+  public final class ResponderLocation implements android.os.Parcelable {
+    method public int describeContents();
+    method public double getAltitude();
+    method public int getAltitudeType();
+    method public double getAltitudeUncertainty();
+    method public java.util.List<android.net.MacAddress> getColocatedBssids();
+    method public int getDatum();
+    method public int getExpectedToMove();
+    method public double getLatitude();
+    method public double getLatitudeUncertainty();
+    method public int getLciFlags();
+    method public double getLongitude();
+    method public double getLongitudeUncertainty();
+    method public int getMapImageType();
+    method @Nullable public java.net.URL getMapImageUrl();
+    method public double getStaFloorNumber();
+    method public double getStaHeightAboveFloorMeters();
+    method public double getStaHeightAboveFloorUncertaintyMeters();
+    method public boolean isLciSubelementValid();
+    method public boolean isZsubelementValid();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final int ALTITUDE_FLOORS = 2; // 0x2
+    field public static final int ALTITUDE_METERS = 1; // 0x1
+    field public static final int ALTITUDE_UNDEFINED = 0; // 0x0
+    field public static final android.os.Parcelable.Creator<android.net.wifi.rtt.ResponderLocation> CREATOR;
+    field public static final int DATUM_NAD83_MLLW = 3; // 0x3
+    field public static final int DATUM_NAD83_NAV88 = 2; // 0x2
+    field public static final int DATUM_UNDEFINED = 0; // 0x0
+    field public static final int DATUM_WGS84 = 1; // 0x1
+    field public static final int LCI_FLAGS_MASK_DEPENDENT_STA = 4; // 0x4
+    field public static final int LCI_FLAGS_MASK_REGLOC_AGREEMENT = 16; // 0x10
+    field public static final int LCI_FLAGS_MASK_REGLOC_DSE = 8; // 0x8
+    field public static final int LCI_FLAGS_MASK_VERSION = 3; // 0x3
+    field public static final int LCI_VERSION_1 = 1; // 0x1
+    field public static final int LOCATION_FIXED = 0; // 0x0
+    field public static final int LOCATION_MOVEMENT_UNKNOWN = 2; // 0x2
+    field public static final int LOCATION_RESERVED = 3; // 0x3
+    field public static final int LOCATION_VARIABLE = 1; // 0x1
+    field public static final int MAP_TYPE_BMP = 12; // 0xc
+    field public static final int MAP_TYPE_CAD = 8; // 0x8
+    field public static final int MAP_TYPE_DWF = 7; // 0x7
+    field public static final int MAP_TYPE_DWG = 6; // 0x6
+    field public static final int MAP_TYPE_DXF = 5; // 0x5
+    field public static final int MAP_TYPE_GIF = 2; // 0x2
+    field public static final int MAP_TYPE_GML = 10; // 0xa
+    field public static final int MAP_TYPE_ICO = 17; // 0x11
+    field public static final int MAP_TYPE_JPG = 3; // 0x3
+    field public static final int MAP_TYPE_KML = 11; // 0xb
+    field public static final int MAP_TYPE_PGM = 13; // 0xd
+    field public static final int MAP_TYPE_PNG = 1; // 0x1
+    field public static final int MAP_TYPE_PPM = 14; // 0xe
+    field public static final int MAP_TYPE_SVG = 4; // 0x4
+    field public static final int MAP_TYPE_TIFF = 9; // 0x9
+    field public static final int MAP_TYPE_URL_DEFINED = 0; // 0x0
+    field public static final int MAP_TYPE_XBM = 15; // 0xf
+    field public static final int MAP_TYPE_XPM = 16; // 0x10
+  }
+
   public class WifiRttManager {
     method public boolean isAvailable();
     method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.CHANGE_WIFI_STATE, android.Manifest.permission.ACCESS_WIFI_STATE}) public void startRanging(@NonNull android.net.wifi.rtt.RangingRequest, @NonNull java.util.concurrent.Executor, @NonNull android.net.wifi.rtt.RangingResultCallback);
@@ -43852,12 +43907,12 @@
 
   public class TelecomManager {
     method public void acceptHandover(android.net.Uri, int, android.telecom.PhoneAccountHandle);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ANSWER_PHONE_CALLS, android.Manifest.permission.MODIFY_PHONE_STATE}) public void acceptRingingCall();
-    method @RequiresPermission(anyOf={android.Manifest.permission.ANSWER_PHONE_CALLS, android.Manifest.permission.MODIFY_PHONE_STATE}) public void acceptRingingCall(int);
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ANSWER_PHONE_CALLS, android.Manifest.permission.MODIFY_PHONE_STATE}) public void acceptRingingCall();
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ANSWER_PHONE_CALLS, android.Manifest.permission.MODIFY_PHONE_STATE}) public void acceptRingingCall(int);
     method public void addNewIncomingCall(android.telecom.PhoneAccountHandle, android.os.Bundle);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void cancelMissedCallsNotification();
     method public android.content.Intent createManageBlockedNumbersIntent();
-    method @RequiresPermission(android.Manifest.permission.ANSWER_PHONE_CALLS) public boolean endCall();
+    method @Deprecated @RequiresPermission(android.Manifest.permission.ANSWER_PHONE_CALLS) public boolean endCall();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.net.Uri getAdnUriForPhoneAccount(android.telecom.PhoneAccountHandle);
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public java.util.List<android.telecom.PhoneAccountHandle> getCallCapablePhoneAccounts();
     method public String getDefaultDialerPackage();
@@ -48453,6 +48508,7 @@
     method public static boolean logEvent(int);
     method public static boolean logStart(int);
     method public static boolean logStop(int);
+    method public static void write(int, @NonNull java.lang.Object...);
   }
 
   public class StringBuilderPrinter implements android.util.Printer {
@@ -48538,7 +48594,7 @@
     field public int data;
     field public int density;
     field @AnyRes public int resourceId;
-    field public int sourceStyleResourceId;
+    field public int sourceResourceId;
     field public CharSequence string;
     field public int type;
   }
@@ -49814,6 +49870,7 @@
     field public static final int EDGE_RIGHT = 8; // 0x8
     field public static final int EDGE_TOP = 1; // 0x1
     field public static final int FLAG_WINDOW_IS_OBSCURED = 1; // 0x1
+    field public static final int FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 2; // 0x2
     field public static final int INVALID_POINTER_ID = -1; // 0xffffffff
     field public static final int TOOL_TYPE_ERASER = 4; // 0x4
     field public static final int TOOL_TYPE_FINGER = 1; // 0x1
@@ -50366,6 +50423,7 @@
     method public final int getScrollX();
     method public final int getScrollY();
     method @android.view.ViewDebug.ExportedProperty(category="drawing") @ColorInt public int getSolidColor();
+    method @LayoutRes public int getSourceLayoutResId();
     method public android.animation.StateListAnimator getStateListAnimator();
     method protected int getSuggestedMinimumHeight();
     method protected int getSuggestedMinimumWidth();
@@ -51030,6 +51088,7 @@
   public class ViewConfiguration {
     ctor @Deprecated public ViewConfiguration();
     method public static android.view.ViewConfiguration get(android.content.Context);
+    method @FloatRange(from=1.0) public static float getAmbiguousGestureMultiplier();
     method public static long getDefaultActionModeHideDuration();
     method public static int getDoubleTapTimeout();
     method @Deprecated public static int getEdgeSlop();
@@ -56044,8 +56103,7 @@
     method public void show(@FloatRange(from=0) float, @FloatRange(from=0) float, float, float);
     method public void update();
     field public static final int SOURCE_BOUND_MAX_IN_SURFACE = 0; // 0x0
-    field public static final int SOURCE_BOUND_MAX_IN_VIEW = 1; // 0x1
-    field public static final int SOURCE_BOUND_MAX_VISIBLE = 2; // 0x2
+    field public static final int SOURCE_BOUND_MAX_VISIBLE = 1; // 0x1
   }
 
   public static class Magnifier.Builder {
diff --git a/api/system-current.txt b/api/system-current.txt
index 43d055b..bf3c0a2 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -518,7 +518,7 @@
     method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public byte[] getStatsMetadata() throws android.app.StatsManager.StatsUnavailableException;
     method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void removeConfig(long) throws android.app.StatsManager.StatsUnavailableException;
     method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean removeConfiguration(long);
-    method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void setActiveConfigsChangedOperation(@Nullable android.app.PendingIntent) throws android.app.StatsManager.StatsUnavailableException;
+    method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public long[] setActiveConfigsChangedOperation(@Nullable android.app.PendingIntent) throws android.app.StatsManager.StatsUnavailableException;
     method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void setBroadcastSubscriber(android.app.PendingIntent, long, long) throws android.app.StatsManager.StatsUnavailableException;
     method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean setBroadcastSubscriber(long, long, android.app.PendingIntent);
     method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean setDataFetchOperation(long, android.app.PendingIntent);
@@ -1127,6 +1127,7 @@
     method public String getNotificationChannelId();
     method @Nullable public String getTaskRootClassName();
     method @Nullable public String getTaskRootPackageName();
+    method public boolean isInstantApp();
     field public static final int NOTIFICATION_INTERRUPTION = 12; // 0xc
     field public static final int NOTIFICATION_SEEN = 10; // 0xa
     field public static final int SLICE_PINNED = 14; // 0xe
@@ -1318,6 +1319,32 @@
     method public void sendOrderedBroadcast(android.content.Intent, String, android.os.Bundle, android.content.BroadcastReceiver, android.os.Handler, int, String, android.os.Bundle);
   }
 
+  public class DynamicAndroidClient {
+    ctor public DynamicAndroidClient(@NonNull android.content.Context);
+    method public void bind();
+    method public void setOnStatusChangedListener(@NonNull android.content.DynamicAndroidClient.OnStatusChangedListener, @NonNull java.util.concurrent.Executor);
+    method public void setOnStatusChangedListener(@NonNull android.content.DynamicAndroidClient.OnStatusChangedListener);
+    method public void start(String, long);
+    method public void start(String, long, long);
+    method public void unbind();
+    field public static final int CAUSE_ERROR_EXCEPTION = 6; // 0x6
+    field public static final int CAUSE_ERROR_INVALID_URL = 4; // 0x4
+    field public static final int CAUSE_ERROR_IO = 3; // 0x3
+    field public static final int CAUSE_ERROR_IPC = 5; // 0x5
+    field public static final int CAUSE_INSTALL_CANCELLED = 2; // 0x2
+    field public static final int CAUSE_INSTALL_COMPLETED = 1; // 0x1
+    field public static final int CAUSE_NOT_SPECIFIED = 0; // 0x0
+    field public static final int STATUS_IN_PROGRESS = 2; // 0x2
+    field public static final int STATUS_IN_USE = 4; // 0x4
+    field public static final int STATUS_NOT_STARTED = 1; // 0x1
+    field public static final int STATUS_READY = 3; // 0x3
+    field public static final int STATUS_UNKNOWN = 0; // 0x0
+  }
+
+  public static interface DynamicAndroidClient.OnStatusChangedListener {
+    method public void onStatusChanged(int, int, long);
+  }
+
   public class Intent implements java.lang.Cloneable android.os.Parcelable {
     field public static final String ACTION_BATTERY_LEVEL_CHANGED = "android.intent.action.BATTERY_LEVEL_CHANGED";
     field public static final String ACTION_CALL_EMERGENCY = "android.intent.action.CALL_EMERGENCY";
@@ -1639,6 +1666,7 @@
 
   public class PermissionInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
     field public static final int FLAG_REMOVED = 2; // 0x2
+    field public static final int PROTECTION_FLAG_APP_PREDICTOR = 2097152; // 0x200000
     field public static final int PROTECTION_FLAG_CONFIGURATOR = 524288; // 0x80000
     field public static final int PROTECTION_FLAG_DOCUMENTER = 262144; // 0x40000
     field public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 1048576; // 0x100000
@@ -1815,7 +1843,9 @@
     field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
     field public final float batteryLevel;
     field public final float brightness;
+    field public final long colorSampleDuration;
     field public final int colorTemperature;
+    field @Nullable public final long[] colorValueBuckets;
     field public final boolean isDefaultBrightnessConfig;
     field public final boolean isUserSetBrightness;
     field public final float lastBrightness;
@@ -3461,15 +3491,6 @@
     method public void stop();
   }
 
-  public final class Session2Token implements android.os.Parcelable {
-    ctor public Session2Token(@NonNull android.content.Context, @NonNull String, @Nullable android.os.Bundle);
-    method public void destroy();
-    method @NonNull public android.os.Bundle getExtras();
-    method public int getPid();
-    method public boolean isDestroyed();
-    field public static final String SESSION_SERVICE_INTERFACE = "android.media.MediaSession2Service";
-  }
-
   public static class SubtitleData.Builder {
     ctor public SubtitleData.Builder();
     ctor public SubtitleData.Builder(@NonNull android.media.SubtitleData);
@@ -4922,6 +4943,10 @@
     field public final boolean supports80211mc;
   }
 
+  public final class ResponderLocation implements android.os.Parcelable {
+    method public boolean getExtraInfoOnAssociationIndication();
+  }
+
   public class WifiRttManager {
     method @RequiresPermission(allOf={android.Manifest.permission.LOCATION_HARDWARE}) public void cancelRanging(@Nullable android.os.WorkSource);
     method @RequiresPermission(allOf={android.Manifest.permission.LOCATION_HARDWARE, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.CHANGE_WIFI_STATE, android.Manifest.permission.ACCESS_WIFI_STATE}) public void startRanging(@Nullable android.os.WorkSource, @NonNull android.net.wifi.rtt.RangingRequest, @NonNull java.util.concurrent.Executor, @NonNull android.net.wifi.rtt.RangingResultCallback);
@@ -5501,6 +5526,8 @@
 
   public final class PermissionControllerManager {
     method @RequiresPermission(android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) public void revokeRuntimePermissions(@NonNull java.util.Map<java.lang.String,java.util.List<java.lang.String>>, boolean, int, @NonNull java.util.concurrent.Executor, @NonNull android.permission.PermissionControllerManager.OnRevokeRuntimePermissionsCallback);
+    field public static final int COUNT_ONLY_WHEN_GRANTED = 1; // 0x1
+    field public static final int COUNT_WHEN_SYSTEM = 2; // 0x2
     field public static final int REASON_INSTALLER_POLICY_VIOLATION = 2; // 0x2
     field public static final int REASON_MALWARE = 1; // 0x1
   }
@@ -5514,7 +5541,7 @@
     ctor public PermissionControllerService();
     method public final void attachBaseContext(android.content.Context);
     method public final android.os.IBinder onBind(android.content.Intent);
-    method public abstract int onCountPermissionApps(@NonNull java.util.List<java.lang.String>, boolean, boolean);
+    method public abstract int onCountPermissionApps(@NonNull java.util.List<java.lang.String>, int);
     method @NonNull public abstract java.util.List<android.permission.RuntimePermissionPresentationInfo> onGetAppPermissions(@NonNull String);
     method @NonNull public abstract java.util.List<android.permission.RuntimePermissionUsageInfo> onGetPermissionUsages(boolean, long);
     method public abstract void onGetRuntimePermissionsBackup(@NonNull android.os.UserHandle, @NonNull java.io.OutputStream);
@@ -9185,6 +9212,21 @@
     method public int getUid();
   }
 
+  public class StatsLogAtoms {
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED = 170; // 0xaa
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_DENIED = 8; // 0x8
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_GRANTED = 5; // 0x5
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED = 1; // 0x1
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_POLICY_FIXED = 3; // 0x3
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_USER_FIXED = 2; // 0x2
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED = 6; // 0x6
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED_WITH_PREJUDICE = 7; // 0x7
+    field public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_GRANTED = 4; // 0x4
+  }
+
+  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef(prefix="PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__", value={android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_USER_FIXED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_POLICY_FIXED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_GRANTED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_GRANTED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED_WITH_PREJUDICE, android.util.StatsLogAtoms.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_DENIED}) public static @interface StatsLogAtoms.PermissionGrantRequestResultReported_Result {
+  }
+
 }
 
 package android.view {
diff --git a/api/test-current.txt b/api/test-current.txt
index 9023a85..2a9a149 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -521,6 +521,7 @@
   }
 
   public class PermissionInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
+    field public static final int PROTECTION_FLAG_APP_PREDICTOR = 2097152; // 0x200000
     field public static final int PROTECTION_FLAG_CONFIGURATOR = 524288; // 0x80000
     field public static final int PROTECTION_FLAG_DOCUMENTER = 262144; // 0x40000
     field public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 1048576; // 0x100000
@@ -659,7 +660,9 @@
     field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
     field public final float batteryLevel;
     field public final float brightness;
+    field public final long colorSampleDuration;
     field public final int colorTemperature;
+    field @Nullable public final long[] colorValueBuckets;
     field public final boolean isDefaultBrightnessConfig;
     field public final boolean isUserSetBrightness;
     field public final float lastBrightness;
@@ -1691,6 +1694,8 @@
 
   public final class PermissionControllerManager {
     method @RequiresPermission("android.permission.REVOKE_RUNTIME_PERMISSIONS") public void revokeRuntimePermissions(@NonNull java.util.Map<java.lang.String,java.util.List<java.lang.String>>, boolean, int, @NonNull java.util.concurrent.Executor, @NonNull android.permission.PermissionControllerManager.OnRevokeRuntimePermissionsCallback);
+    field public static final int COUNT_ONLY_WHEN_GRANTED = 1; // 0x1
+    field public static final int COUNT_WHEN_SYSTEM = 2; // 0x2
     field public static final int REASON_INSTALLER_POLICY_VIOLATION = 2; // 0x2
     field public static final int REASON_MALWARE = 1; // 0x1
   }
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 427662a..5f47e06 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -235,6 +235,9 @@
         BluetoothClassicPairingEventReported bluetooth_classic_pairing_event_reported = 166;
         BluetoothSmpPairingEventReported bluetooth_smp_pairing_event_reported = 167;
         ScreenTimeoutExtensionReported screen_timeout_extension_reported = 168;
+        ProcessStartTime process_start_time = 169;
+        PermissionGrantRequestResultReported permission_grant_request_result_reported = 170;
+        BluetoothSocketConnectionStateChanged bluetooth_socket_connection_state_changed = 171;
     }
 
     // Pulled events will start at field 10000.
@@ -290,6 +293,7 @@
         DebugFailingElapsedClock debug_failing_elapsed_clock = 10047;
         NumBiometricsEnrolled num_faces_enrolled = 10048;
         RoleHolder role_holder = 10049;
+        DangerousPermissionState dangerous_permission_state = 10050;
     }
 
     // DO NOT USE field numbers above 100,000 in AOSP.
@@ -2065,6 +2069,36 @@
 }
 
 /**
+ * Logs when a Bluetooth socket’s connection state changed
+ *
+ * Logged from:
+ *   system/bt
+ */
+message BluetoothSocketConnectionStateChanged {
+    // An identifier that can be used to match events for this device.
+    // Currently, this is a salted hash of the MAC address of this Bluetooth device.
+    // Salt: Randomly generated 256 bit value
+    // Hash algorithm: HMAC-SHA256
+    // Size: 32 byte
+    // Default: null or empty if the device identifier is not known
+    optional bytes obfuscated_id = 1 [(android.os.statsd.log_mode) = MODE_BYTES];
+    // Port of this socket
+    // Default 0 when unknown or don't care
+    optional int32 port = 2;
+    // Socket type as mentioned in
+    // frameworks/base/core/java/android/bluetooth/BluetoothSocket.java
+    // Default: SOCKET_TYPE_UNKNOWN
+    optional android.bluetooth.SocketTypeEnum type = 3;
+    // Socket connection state
+    // Default: SOCKET_CONNECTION_STATE_UNKNOWN
+    optional android.bluetooth.SocketConnectionstateEnum state = 4;
+    // Number of bytes sent to remote device during this connection
+    optional int64 tx_bytes = 5;
+    // Number of bytes received from remote device during this connection
+    optional int64 rx_bytes = 6;
+}
+
+/**
  * Logs when something is plugged into or removed from the USB-C connector.
  *
  * Logged from:
@@ -5096,6 +5130,48 @@
 }
 
 /**
+ * Information about a permission grant request
+ */
+message PermissionGrantRequestResultReported {
+    // unique value identifying an API call. A API call might result in multiple of these atoms
+    optional int64 request_id = 1;
+
+    // UID of package requesting the permission grant
+    optional int32 requesting_uid = 2 [(is_uid) = true];
+
+    // Name of package requesting the permission grant
+    optional string requesting_package_name = 3;
+
+    // The permission to be granted
+    optional string permission_name = 4;
+
+    // If the permission was explicitly requested via the API or added by the system
+    optional bool is_implicit = 5;
+
+    enum Result {
+        UNDEFINED = 0;
+        // permission request was ignored
+        IGNORED = 1;
+        // permission request was ignored because it was user fixed
+        IGNORED_USER_FIXED = 2;
+        // permission request was ignored because it was policy fixed
+        IGNORED_POLICY_FIXED = 3;
+        // permission was granted by user action
+        USER_GRANTED = 4;
+        // permission was automatically granted
+        AUTO_GRANTED = 5;
+        // permission was denied by user action
+        USER_DENIED = 6;
+        // permission was denied with prejudice by the user
+        USER_DENIED_WITH_PREJUDICE = 7;
+        // permission was automatically denied
+        AUTO_DENIED = 8;
+    }
+    // The result of the permission grant
+    optional Result result = 6;
+}
+
+/**
  * Logs when Omapi API used
  * Logged from:
  *     packages/apps/SecureElement/src/com/android/se/Terminal.java
@@ -5263,6 +5339,7 @@
         PERMISSION_IGNORED = 12;
         SWIPE_LEFT = 13;
         SWIPE_RIGHT = 14;
+        STACK_EXPANDED = 15;
     }
     optional Action action = 6;
 
@@ -5303,3 +5380,76 @@
     // Describes how many times in a row did the power manager reset the screen off timeout.
     optional uint32 consecutive_timeout_extended_count = 1;
 }
+
+/*
+* Logs number of milliseconds it takes to start a process.
+* The definition of app process start time is from the app launch time to
+* the time that Zygote finished forking the app process and loaded the
+* application package's java classes.
+
+* This metric is different from AppStartOccurred which is for foreground
+* activity only.
+
+* ProcessStartTime can report all processes (both foreground and background)
+* start time.
+*
+* Logged from:
+*   frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
+*/
+message ProcessStartTime {
+    // The uid of the ProcessRecord.
+    optional int32 uid = 1 [(is_uid) = true];
+
+    // The process pid.
+    optional int32 pid = 2;
+
+    // The process name.
+    // Usually package name, "system" for system server.
+    // Provided by ActivityManagerService.
+    optional string process_name = 3;
+
+    enum StartType {
+        UNKNOWN = 0;
+        WARM = 1;
+        HOT = 2;
+        COLD = 3;
+    }
+
+    // The start type.
+    optional StartType type = 4;
+
+    // The elapsed realtime at the start of the process.
+    optional int64 process_start_time_millis = 5;
+
+    // Number of milliseconds it takes to reach bind application.
+    optional int32 bind_application_delay_millis = 6;
+
+    // Number of milliseconds it takes to finish start of the process.
+    optional int32 process_start_delay_millis = 7;
+
+    // hostingType field in ProcessRecord, the component type such as "activity",
+    // "service", "content provider", "broadcast" or other strings.
+    optional string hosting_type = 8;
+
+    // hostingNameStr field in ProcessRecord. The component class name that runs
+    // in this process.
+    optional string hosting_name = 9;
+}
+
+/**
+ * State of a dangerous permission requested by a package
+ */
+message DangerousPermissionState {
+    // Name of the permission
+    optional string permission_name = 1;
+
+    // Uid of the package
+    optional int32 uid = 2 [(is_uid) = true];
+
+    // Package requesting the permission
+    optional string package_name = 3;
+
+    // If the permission is granted to the uid
+    optional bool is_granted = 4;
+}
+
diff --git a/cmds/statsd/src/external/StatsPullerManager.cpp b/cmds/statsd/src/external/StatsPullerManager.cpp
index 6f3eeaa..c69384c 100644
--- a/cmds/statsd/src/external/StatsPullerManager.cpp
+++ b/cmds/statsd/src/external/StatsPullerManager.cpp
@@ -223,6 +223,9 @@
         // RoleHolder.
         {android::util::ROLE_HOLDER,
          {.puller = new StatsCompanionServicePuller(android::util::ROLE_HOLDER)}},
+        // PermissionState.
+        {android::util::DANGEROUS_PERMISSION_STATE,
+         {.puller = new StatsCompanionServicePuller(android::util::DANGEROUS_PERMISSION_STATE)}},
 };
 
 StatsPullerManager::StatsPullerManager() : mNextPullTimeNs(NO_ALARM_UPDATE) {
diff --git a/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp b/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
index d5c358d..24a9980 100644
--- a/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
+++ b/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
@@ -31,8 +31,8 @@
 StatsdConfig CreateStatsdConfig(const GaugeMetric::SamplingType sampling_type) {
     StatsdConfig config;
     config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-    auto temperatureAtomMatcher = CreateTemperatureAtomMatcher();
-    *config.add_atom_matcher() = temperatureAtomMatcher;
+    auto atomMatcher = CreateSimpleAtomMatcher("TestMatcher", android::util::SUBSYSTEM_SLEEP_STATE);
+    *config.add_atom_matcher() = atomMatcher;
     *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
     *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
 
@@ -41,12 +41,12 @@
 
     auto gaugeMetric = config.add_gauge_metric();
     gaugeMetric->set_id(123456);
-    gaugeMetric->set_what(temperatureAtomMatcher.id());
+    gaugeMetric->set_what(atomMatcher.id());
     gaugeMetric->set_condition(screenIsOffPredicate.id());
     gaugeMetric->set_sampling_type(sampling_type);
     gaugeMetric->mutable_gauge_fields_filter()->set_include_all(true);
     *gaugeMetric->mutable_dimensions_in_what() =
-        CreateDimensions(android::util::TEMPERATURE, {2/* sensor name field */ });
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {1 /* subsystem name */});
     gaugeMetric->set_bucket(FIVE_MINUTES);
     gaugeMetric->set_max_pull_delay_sec(INT_MAX);
     config.set_hash_strings_in_metric_report(false);
@@ -139,9 +139,9 @@
     EXPECT_GT((int)gaugeMetrics.data_size(), 1);
 
     auto data = gaugeMetrics.data(0);
-    EXPECT_EQ(android::util::TEMPERATURE, data.dimensions_in_what().field());
+    EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
     EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-    EXPECT_EQ(2 /* sensor name field */,
+    EXPECT_EQ(1 /* subsystem name field */,
               data.dimensions_in_what().value_tuple().dimensions_value(0).field());
     EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
     EXPECT_EQ(6, data.bucket_info_size());
@@ -152,8 +152,8 @@
     EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
     EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(0).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(0).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(1).atom_size());
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 1,
@@ -161,8 +161,8 @@
     EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(1).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(1).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(2).atom_size());
     EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
@@ -170,8 +170,8 @@
               data.bucket_info(2).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(2).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(2).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(3).atom_size());
     EXPECT_EQ(1, data.bucket_info(3).elapsed_timestamp_nanos_size());
@@ -179,8 +179,8 @@
               data.bucket_info(3).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(3).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(3).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(3).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(3).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(3).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(3).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(4).atom_size());
     EXPECT_EQ(1, data.bucket_info(4).elapsed_timestamp_nanos_size());
@@ -188,8 +188,8 @@
               data.bucket_info(4).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(4).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(4).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(4).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(4).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(4).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(4).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(5).atom_size());
     EXPECT_EQ(1, data.bucket_info(5).elapsed_timestamp_nanos_size());
@@ -197,8 +197,8 @@
               data.bucket_info(5).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(5).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(5).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(5).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(5).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(5).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(5).atom(0).subsystem_sleep_state().time_millis(), 0);
 }
 
 TEST(GaugeMetricE2eTest, TestConditionChangeToTrueSamplePulledEvents) {
@@ -262,9 +262,9 @@
     EXPECT_GT((int)gaugeMetrics.data_size(), 1);
 
     auto data = gaugeMetrics.data(0);
-    EXPECT_EQ(android::util::TEMPERATURE, data.dimensions_in_what().field());
+    EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
     EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-    EXPECT_EQ(2 /* sensor name field */,
+    EXPECT_EQ(1 /* subsystem name field */,
               data.dimensions_in_what().value_tuple().dimensions_value(0).field());
     EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
     EXPECT_EQ(3, data.bucket_info_size());
@@ -275,8 +275,8 @@
     EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
     EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(0).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(0).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(1).atom_size());
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 100,
@@ -284,8 +284,8 @@
     EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(1).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(1).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(2, data.bucket_info(2).atom_size());
     EXPECT_EQ(2, data.bucket_info(2).elapsed_timestamp_nanos_size());
@@ -295,10 +295,10 @@
               data.bucket_info(2).elapsed_timestamp_nanos(1));
     EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(2).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(2).atom(0).temperature().temperature_deci_celsius(), 0);
-    EXPECT_TRUE(data.bucket_info(2).atom(1).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(2).atom(1).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
+    EXPECT_TRUE(data.bucket_info(2).atom(1).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(2).atom(1).subsystem_sleep_state().time_millis(), 0);
 }
 
 
@@ -366,9 +366,9 @@
     EXPECT_GT((int)gaugeMetrics.data_size(), 1);
 
     auto data = gaugeMetrics.data(0);
-    EXPECT_EQ(android::util::TEMPERATURE, data.dimensions_in_what().field());
+    EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
     EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-    EXPECT_EQ(2 /* sensor name field */,
+    EXPECT_EQ(1 /* subsystem name field */,
               data.dimensions_in_what().value_tuple().dimensions_value(0).field());
     EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
     EXPECT_EQ(3, data.bucket_info_size());
@@ -378,8 +378,8 @@
     EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(0).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(0).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(1).atom_size());
     EXPECT_EQ(configAddedTimeNs + 3 * bucketSizeNs + 11,
@@ -387,8 +387,8 @@
     EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(1).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(1).atom(0).temperature().temperature_deci_celsius(), 0);
+    EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
 
     EXPECT_EQ(1, data.bucket_info(2).atom_size());
     EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
@@ -396,9 +396,8 @@
               data.bucket_info(2).elapsed_timestamp_nanos(0));
     EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
     EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-    EXPECT_TRUE(data.bucket_info(2).atom(0).temperature().sensor_name().empty());
-    EXPECT_GT(data.bucket_info(2).atom(0).temperature().temperature_deci_celsius(), 0);
-
+    EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+    EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
 }
 
 #else
diff --git a/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp b/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
index 370c36c..aee0c1f 100644
--- a/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
@@ -70,18 +70,19 @@
     StatsdConfig config;
     config.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
 
-    auto temperatureAtomMatcher = CreateTemperatureAtomMatcher();
-    *config.add_atom_matcher() = temperatureAtomMatcher;
+    auto pulledAtomMatcher =
+            CreateSimpleAtomMatcher("TestMatcher", android::util::SUBSYSTEM_SLEEP_STATE);
+    *config.add_atom_matcher() = pulledAtomMatcher;
     *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
     *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
 
     auto valueMetric = config.add_value_metric();
     valueMetric->set_id(123456);
-    valueMetric->set_what(temperatureAtomMatcher.id());
+    valueMetric->set_what(pulledAtomMatcher.id());
     *valueMetric->mutable_value_field() =
-            CreateDimensions(android::util::TEMPERATURE, {3 /* temperature degree field */});
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {4 /* time sleeping field */});
     *valueMetric->mutable_dimensions_in_what() =
-            CreateDimensions(android::util::TEMPERATURE, {2 /* sensor name field */});
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {1 /* subsystem name */});
     valueMetric->set_bucket(FIVE_MINUTES);
     valueMetric->set_min_bucket_size_nanos(minTime);
     valueMetric->set_use_absolute_value_on_reset(true);
@@ -92,17 +93,18 @@
     StatsdConfig config;
     config.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
 
-    auto temperatureAtomMatcher = CreateTemperatureAtomMatcher();
-    *config.add_atom_matcher() = temperatureAtomMatcher;
+    auto pulledAtomMatcher =
+                CreateSimpleAtomMatcher("TestMatcher", android::util::SUBSYSTEM_SLEEP_STATE);
+    *config.add_atom_matcher() = pulledAtomMatcher;
     *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
     *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
 
     auto gaugeMetric = config.add_gauge_metric();
     gaugeMetric->set_id(123456);
-    gaugeMetric->set_what(temperatureAtomMatcher.id());
+    gaugeMetric->set_what(pulledAtomMatcher.id());
     gaugeMetric->mutable_gauge_fields_filter()->set_include_all(true);
     *gaugeMetric->mutable_dimensions_in_what() =
-            CreateDimensions(android::util::TEMPERATURE, {2 /* sensor name field */});
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {1 /* subsystem name */});
     gaugeMetric->set_bucket(FIVE_MINUTES);
     gaugeMetric->set_min_bucket_size_nanos(minTime);
     return config;
diff --git a/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp b/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
index cab6eac..f3c4e12 100644
--- a/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
@@ -31,8 +31,9 @@
 StatsdConfig CreateStatsdConfig() {
     StatsdConfig config;
     config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-    auto temperatureAtomMatcher = CreateTemperatureAtomMatcher();
-    *config.add_atom_matcher() = temperatureAtomMatcher;
+    auto pulledAtomMatcher =
+            CreateSimpleAtomMatcher("TestMatcher", android::util::SUBSYSTEM_SLEEP_STATE);
+    *config.add_atom_matcher() = pulledAtomMatcher;
     *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
     *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
 
@@ -41,12 +42,12 @@
 
     auto valueMetric = config.add_value_metric();
     valueMetric->set_id(123456);
-    valueMetric->set_what(temperatureAtomMatcher.id());
+    valueMetric->set_what(pulledAtomMatcher.id());
     valueMetric->set_condition(screenIsOffPredicate.id());
     *valueMetric->mutable_value_field() =
-        CreateDimensions(android::util::TEMPERATURE, {3/* temperature degree field */ });
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {4 /* time sleeping field */});
     *valueMetric->mutable_dimensions_in_what() =
-        CreateDimensions(android::util::TEMPERATURE, {2/* sensor name field */ });
+            CreateDimensions(android::util::SUBSYSTEM_SLEEP_STATE, {1 /* subsystem name */});
     valueMetric->set_bucket(FIVE_MINUTES);
     valueMetric->set_use_absolute_value_on_reset(true);
     valueMetric->set_skip_zero_diff_output(false);
@@ -134,9 +135,9 @@
     EXPECT_GT((int)valueMetrics.data_size(), 1);
 
     auto data = valueMetrics.data(0);
-    EXPECT_EQ(android::util::TEMPERATURE, data.dimensions_in_what().field());
+    EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
     EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-    EXPECT_EQ(2 /* sensor name field */,
+    EXPECT_EQ(1 /* subsystem name field */,
               data.dimensions_in_what().value_tuple().dimensions_value(0).field());
     EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
     EXPECT_EQ(5, data.bucket_info_size());
@@ -241,9 +242,9 @@
     EXPECT_GT((int)valueMetrics.data_size(), 1);
 
     auto data = valueMetrics.data(0);
-    EXPECT_EQ(android::util::TEMPERATURE, data.dimensions_in_what().field());
+    EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
     EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-    EXPECT_EQ(2 /* sensor name field */,
+    EXPECT_EQ(1 /* subsystem name field */,
               data.dimensions_in_what().value_tuple().dimensions_value(0).field());
     EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
     EXPECT_EQ(3, data.bucket_info_size());
diff --git a/cmds/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java b/cmds/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java
index d9aba61..fc7b778 100644
--- a/cmds/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java
+++ b/cmds/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java
@@ -32,7 +32,8 @@
 
 import java.io.File;
 import java.io.IOException;
-import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
 import java.util.logging.Level;
@@ -60,6 +61,7 @@
     };
     private static final Logger LOGGER = Logger.getLogger(TestDrive.class.getName());
 
+    private String mAdditionalAllowedPackage;
     private final Set<Long> mTrackedMetrics = new HashSet<>();
 
     public static void main(String[] args) {
@@ -69,11 +71,16 @@
         String remoteConfigPath = null;
 
         if (args.length < 1) {
-            LOGGER.log(Level.SEVERE, "Usage: ./test_drive <atomId1> <atomId2> ... <atomIdN>");
+            LOGGER.log(Level.SEVERE, "Usage: ./test_drive [-p additional_allowed_package] "
+                    + "<atomId1> <atomId2> ... <atomIdN>");
             return;
         }
 
-        for (int i = 0; i < args.length; i++) {
+        if (args.length >= 3 && args[0].equals("-p")) {
+            testDrive.mAdditionalAllowedPackage = args[1];
+        }
+
+        for (int i = testDrive.mAdditionalAllowedPackage == null ? 0 : 2; i < args.length; i++) {
             try {
                 int atomId = Integer.valueOf(args[i]);
                 if (Atom.getDescriptor().findFieldByNumber(atomId) == null) {
@@ -137,9 +144,15 @@
         long metricId = METRIC_ID_BASE;
         long atomMatcherId = ATOM_MATCHER_ID_BASE;
 
+        ArrayList<String> allowedSources = new ArrayList<>();
+        Collections.addAll(allowedSources, ALLOWED_LOG_SOURCES);
+        if (mAdditionalAllowedPackage != null) {
+            allowedSources.add(mAdditionalAllowedPackage);
+        }
+
         StatsdConfig.Builder builder = StatsdConfig.newBuilder();
         builder
-            .addAllAllowedLogSource(Arrays.asList(ALLOWED_LOG_SOURCES))
+            .addAllAllowedLogSource(allowedSources)
             .setHashStringsInMetricReport(false);
 
         for (int atomId : atomIds) {
diff --git a/config/boot-image-profile.txt b/config/boot-image-profile.txt
index c2e441b..7f4d1d0 100644
--- a/config/boot-image-profile.txt
+++ b/config/boot-image-profile.txt
@@ -19875,7 +19875,6 @@
 HSPLandroid/graphics/Bitmap;->createBitmap(Landroid/util/DisplayMetrics;IILandroid/graphics/Bitmap$Config;ZLandroid/graphics/ColorSpace;)Landroid/graphics/Bitmap;
 HSPLandroid/graphics/Bitmap;->createBitmap(Landroid/util/DisplayMetrics;[IIIIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;
 HSPLandroid/graphics/Bitmap;->createBitmap([IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;
-HSPLandroid/graphics/Bitmap;->createHardwareBitmap(Landroid/graphics/GraphicBuffer;)Landroid/graphics/Bitmap;
 HSPLandroid/graphics/Bitmap;->createScaledBitmap(Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
 HSPLandroid/graphics/Bitmap;->eraseColor(I)V
 HSPLandroid/graphics/Bitmap;->extractAlpha(Landroid/graphics/Paint;[I)Landroid/graphics/Bitmap;
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index e77e212..aac8f08 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -1768,7 +1768,7 @@
     protected void onResume() {
         if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
         dispatchActivityResumed();
-        mActivityTransitionState.onResume(this, isTopOfTask());
+        mActivityTransitionState.onResume(this);
         enableAutofillCompatibilityIfNeeded();
         if (mAutoFillResetNeeded) {
             if (!mAutoFillIgnoreFirstResumePause) {
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 75ea7bb..db3b720 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -42,6 +42,7 @@
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
+import android.graphics.ColorSpace;
 import android.graphics.GraphicBuffer;
 import android.graphics.Matrix;
 import android.graphics.Point;
@@ -1777,6 +1778,10 @@
         private final int mSystemUiVisibility;
         private final boolean mIsTranslucent;
 
+        // TODO(b/116112787) TaskSnapshot must also book keep the color space from hardware bitmap
+        // when created.
+        private final ColorSpace mColorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
+
         public TaskSnapshot(@NonNull ComponentName topActivityComponent, GraphicBuffer snapshot,
                 int orientation, Rect contentInsets, boolean reducedResolution, float scale,
                 boolean isRealSnapshot, int windowingMode, int systemUiVisibility,
@@ -1822,6 +1827,13 @@
         }
 
         /**
+         * @return The color space of graphic buffer representing the screenshot.
+         */
+        public ColorSpace getColorSpace() {
+            return mColorSpace;
+        }
+
+        /**
          * @return The screen orientation the screenshot was taken in.
          */
         @UnsupportedAppUsage
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index 86e658d..69c450c 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -23,6 +23,7 @@
 import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
+import android.content.pm.ActivityPresentationInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.UserInfo;
 import android.os.Bundle;
@@ -247,6 +248,9 @@
     /** Gets the task id for a given activity. */
     public abstract int getTaskIdForActivity(@NonNull IBinder token, boolean onlyRoot);
 
+    /** Gets the basic info for a given activity. */
+    public abstract ActivityPresentationInfo getActivityPresentationInfo(@NonNull IBinder token);
+
     public abstract void setBooting(boolean booting);
     public abstract boolean isBooting();
     public abstract void setBooted(boolean booted);
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index 94b42ff..e2d868f 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -33,6 +33,7 @@
 import android.graphics.Bitmap.Config;
 import android.graphics.GraphicBuffer;
 import android.graphics.Rect;
+import android.hardware.HardwareBuffer;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IRemoteCallback;
@@ -916,7 +917,8 @@
                 // Unpackage the GraphicBuffer from the parceled thumbnail
                 final GraphicBuffer buffer = opts.getParcelable(KEY_ANIM_THUMBNAIL);
                 if (buffer != null) {
-                    mThumbnail = Bitmap.createHardwareBitmap(buffer);
+                    mThumbnail = Bitmap.wrapHardwareBuffer(
+                            HardwareBuffer.createFromGraphicBuffer(buffer), null);
                 }
                 mStartX = opts.getInt(KEY_ANIM_START_X, 0);
                 mStartY = opts.getInt(KEY_ANIM_START_Y, 0);
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 22dcce5..21d66e5 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -129,6 +129,7 @@
 import android.util.Pair;
 import android.util.PrintWriterPrinter;
 import android.util.Slog;
+import android.util.SparseArray;
 import android.util.SparseIntArray;
 import android.util.SuperNotCalledException;
 import android.util.proto.ProtoOutputStream;
@@ -305,8 +306,14 @@
     @UnsupportedAppUsage
     final ArrayList<Application> mAllApplications
             = new ArrayList<Application>();
-    // set of instantiated backup agents, keyed by package name
-    final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
+    /**
+     * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
+     * Indexing by user id supports parallel backups across users on system packages as they run in
+     * the same process with the same package name. Indexing by package name supports multiple
+     * distinct applications running in the same process.
+     */
+    private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
+            new SparseArray<>();
     /** Reference to singleton {@link ActivityThread} */
     @UnsupportedAppUsage
     private static volatile ActivityThread sCurrentActivityThread;
@@ -659,10 +666,11 @@
         ApplicationInfo appInfo;
         CompatibilityInfo compatInfo;
         int backupMode;
+        int userId;
         public String toString() {
             return "CreateBackupAgentData{appInfo=" + appInfo
                     + " backupAgent=" + appInfo.backupAgentName
-                    + " mode=" + backupMode + "}";
+                    + " mode=" + backupMode + " userId=" + userId + "}";
         }
     }
 
@@ -877,20 +885,22 @@
         }
 
         public final void scheduleCreateBackupAgent(ApplicationInfo app,
-                CompatibilityInfo compatInfo, int backupMode) {
+                CompatibilityInfo compatInfo, int backupMode, int userId) {
             CreateBackupAgentData d = new CreateBackupAgentData();
             d.appInfo = app;
             d.compatInfo = compatInfo;
             d.backupMode = backupMode;
+            d.userId = userId;
 
             sendMessage(H.CREATE_BACKUP_AGENT, d);
         }
 
         public final void scheduleDestroyBackupAgent(ApplicationInfo app,
-                CompatibilityInfo compatInfo) {
+                CompatibilityInfo compatInfo, int userId) {
             CreateBackupAgentData d = new CreateBackupAgentData();
             d.appInfo = app;
             d.compatInfo = compatInfo;
+            d.userId = userId;
 
             sendMessage(H.DESTROY_BACKUP_AGENT, d);
         }
@@ -3616,7 +3626,8 @@
 
         try {
             IBinder binder = null;
-            BackupAgent agent = mBackupAgents.get(packageName);
+            ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
+            BackupAgent agent = backupAgents.get(packageName);
             if (agent != null) {
                 // reusing the existing instance
                 if (DEBUG_BACKUP) {
@@ -3635,9 +3646,9 @@
                     context.setOuterContext(agent);
                     agent.attach(context);
 
-                    agent.onCreate();
+                    agent.onCreate(UserHandle.of(data.userId));
                     binder = agent.onBind();
-                    mBackupAgents.put(packageName, agent);
+                    backupAgents.put(packageName, agent);
                 } catch (Exception e) {
                     // If this is during restore, fail silently; otherwise go
                     // ahead and let the user see the crash.
@@ -3653,7 +3664,7 @@
 
             // tell the OS that we're live now
             try {
-                ActivityManager.getService().backupAgentCreated(packageName, binder);
+                ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
             } catch (RemoteException e) {
                 throw e.rethrowFromSystemServer();
             }
@@ -3669,7 +3680,8 @@
 
         LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
         String packageName = packageInfo.mPackageName;
-        BackupAgent agent = mBackupAgents.get(packageName);
+        ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
+        BackupAgent agent = backupAgents.get(packageName);
         if (agent != null) {
             try {
                 agent.onDestroy();
@@ -3677,12 +3689,21 @@
                 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
                 e.printStackTrace();
             }
-            mBackupAgents.remove(packageName);
+            backupAgents.remove(packageName);
         } else {
             Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
         }
     }
 
+    private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
+        ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
+        if (backupAgents == null) {
+            backupAgents = new ArrayMap<>();
+            mBackupAgentsByUser.put(userId, backupAgents);
+        }
+        return backupAgents;
+    }
+
     @UnsupportedAppUsage
     private void handleCreateService(CreateServiceData data) {
         // If we are getting ready to gc after going to the background, well
diff --git a/core/java/android/app/ActivityTransitionState.java b/core/java/android/app/ActivityTransitionState.java
index 3201feb..3a95839 100644
--- a/core/java/android/app/ActivityTransitionState.java
+++ b/core/java/android/app/ActivityTransitionState.java
@@ -258,10 +258,10 @@
         }
     }
 
-    public void onResume(Activity activity, boolean isTopOfTask) {
+    public void onResume(Activity activity) {
         // After orientation change, the onResume can come in before the top Activity has
         // left, so if the Activity is not top, wait a second for the top Activity to exit.
-        if (isTopOfTask || mEnterTransitionCoordinator == null) {
+        if (mEnterTransitionCoordinator == null || activity.isTopOfTask()) {
             restoreExitedViews();
             restoreReenteringViews();
         } else {
diff --git a/core/java/android/app/ActivityView.java b/core/java/android/app/ActivityView.java
index eae7d6b..5814e69 100644
--- a/core/java/android/app/ActivityView.java
+++ b/core/java/android/app/ActivityView.java
@@ -363,7 +363,7 @@
         final IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
 
         mRootSurfaceControl = new SurfaceControl.Builder(surfaceSession)
-                .setContainerLayer()
+                .setContainerLayer(true)
                 .setParent(mSurfaceView.getSurfaceControl())
                 .setName(DISPLAY_NAME)
                 .build();
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index a937422..98032dc 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -3017,6 +3017,15 @@
     }
 
     @Override
+    public String getAppPredictionServicePackageName() {
+        try {
+            return mPM.getAppPredictionServicePackageName();
+        } catch (RemoteException e) {
+            throw e.rethrowAsRuntimeException();
+        }
+    }
+
+    @Override
     public String getContentCaptureServicePackageName() {
         try {
             return mPM.getContentCaptureServicePackageName();
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index 412d7f4..3aa9fa7 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -203,7 +203,7 @@
     void unbindFinished(in IBinder token, in Intent service, boolean doRebind);
     void setProcessImportant(in IBinder token, int pid, boolean isForeground, String reason);
     void setServiceForeground(in ComponentName className, in IBinder token,
-            int id, in Notification notification, int flags);
+            int id, in Notification notification, int flags, int foregroundServiceType);
     boolean moveActivityTaskToBack(in IBinder token, boolean nonRoot);
     void getMemoryInfo(out ActivityManager.MemoryInfo outInfo);
     List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState();
@@ -221,8 +221,8 @@
     boolean shutdown(int timeout);
     void stopAppSwitches();
     void resumeAppSwitches();
-    boolean bindBackupAgent(in String packageName, int backupRestoreMode, int userId);
-    void backupAgentCreated(in String packageName, in IBinder agent);
+    boolean bindBackupAgent(in String packageName, int backupRestoreMode, int targetUserId);
+    void backupAgentCreated(in String packageName, in IBinder agent, int userId);
     void unbindBackupAgent(in ApplicationInfo appInfo);
     int getUidForIntentSender(in IIntentSender sender);
     int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index c64fcf3..e7a8c0e 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -88,9 +88,9 @@
     void profilerControl(boolean start, in ProfilerInfo profilerInfo, int profileType);
     void setSchedulingGroup(int group);
     void scheduleCreateBackupAgent(in ApplicationInfo app, in CompatibilityInfo compatInfo,
-            int backupMode);
+            int backupMode, int userId);
     void scheduleDestroyBackupAgent(in ApplicationInfo app,
-            in CompatibilityInfo compatInfo);
+            in CompatibilityInfo compatInfo, int userId);
     void scheduleOnNewActivityOptions(IBinder token, in Bundle options);
     void scheduleSuicide();
     void dispatchPackageBroadcast(int cmd, in String[] packages);
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index 5fa8526..87bf5ed 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -16,7 +16,10 @@
 
 package android.app;
 
+import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
+
 import android.annotation.IntDef;
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
 import android.content.ComponentCallbacks2;
@@ -685,12 +688,10 @@
      * the permission {@link android.Manifest.permission#FOREGROUND_SERVICE} in order to use
      * this API.</p>
      *
-     * <p>To use this API, apps targeting API {@link android.os.Build.VERSION_CODES#Q} or later must
-     * specify the foreground service type using attribute
-     * {@link android.R.attr#foregroundServiceType} in service element of manifest file, otherwise
-     * a SecurityException is thrown when this API is called. Apps targeting API older than
-     * {@link android.os.Build.VERSION_CODES#Q} do not need to specify the foreground service type
-     * </p>
+     * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
+     * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
+     * service element of manifest file. The value of attribute
+     * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
      *
      * @param id The identifier for this notification as per
      * {@link NotificationManager#notify(int, Notification)
@@ -703,7 +704,42 @@
         try {
             mActivityManager.setServiceForeground(
                     new ComponentName(this, mClassName), mToken, id,
-                    notification, 0);
+                    notification, 0, FOREGROUND_SERVICE_TYPE_MANIFEST);
+        } catch (RemoteException ex) {
+        }
+    }
+
+  /**
+   * An overloaded version of {@link #startForeground(int, Notification)} with additional
+   * foregroundServiceType parameter.
+   *
+   * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
+   * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
+   * service element of manifest file. The value of attribute
+   * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
+   *
+   * <p>The foregroundServiceType parameter must be a subset flags of what is specified in manifest
+   * attribute {@link android.R.attr#foregroundServiceType}, if not, an IllegalArgumentException is
+   * thrown. Specify foregroundServiceType parameter as
+   * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST} to use all flags that
+   * is specified in manifest attribute foregroundServiceType.</p>
+   *
+   * @param id The identifier for this notification as per
+   * {@link NotificationManager#notify(int, Notification)
+   * NotificationManager.notify(int, Notification)}; must not be 0.
+   * @param notification The Notification to be displayed.
+   * @param foregroundServiceType must be a subset flags of manifest attribute
+   * {@link android.R.attr#foregroundServiceType} flags.
+   * @throws IllegalArgumentException if param foregroundServiceType is not subset of manifest
+   *     attribute {@link android.R.attr#foregroundServiceType}.
+   * @see {@link android.content.pm.ServiceInfo} for the set of FOREGROUND_SERVICE_TYPE flags.
+   */
+    public final void startForeground(int id, @NonNull Notification notification,
+            int foregroundServiceType) {
+        try {
+            mActivityManager.setServiceForeground(
+                    new ComponentName(this, mClassName), mToken, id,
+                    notification, 0, foregroundServiceType);
         } catch (RemoteException ex) {
         }
     }
@@ -731,7 +767,8 @@
     public final void stopForeground(@StopForegroundFlags int flags) {
         try {
             mActivityManager.setServiceForeground(
-                    new ComponentName(this, mClassName), mToken, 0, null, flags);
+                    new ComponentName(this, mClassName), mToken, 0, null,
+                    flags, 0);
         } catch (RemoteException ex) {
         }
     }
diff --git a/core/java/android/app/SharedElementCallback.java b/core/java/android/app/SharedElementCallback.java
index 80fb805..9fabfde 100644
--- a/core/java/android/app/SharedElementCallback.java
+++ b/core/java/android/app/SharedElementCallback.java
@@ -23,6 +23,7 @@
 import android.graphics.RectF;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
+import android.hardware.HardwareBuffer;
 import android.os.Bundle;
 import android.os.Parcelable;
 import android.transition.TransitionUtils;
@@ -234,7 +235,8 @@
                 return null;
             }
             if (bitmap == null) {
-                bitmap = Bitmap.createHardwareBitmap(buffer);
+                bitmap = Bitmap.wrapHardwareBuffer(HardwareBuffer.createFromGraphicBuffer(buffer),
+                                                   null);
             }
             ImageView imageView = new ImageView(context);
             view = imageView;
diff --git a/core/java/android/app/StatsManager.java b/core/java/android/app/StatsManager.java
index 9b66c92..3119b37 100644
--- a/core/java/android/app/StatsManager.java
+++ b/core/java/android/app/StatsManager.java
@@ -289,20 +289,23 @@
      * @param pendingIntent the PendingIntent to use when broadcasting info to the subscriber
      *                      associated with the given subscriberId. May be null, in which case
      *                      it removes any associated pending intent for this client.
+     * @return A list of configs that are currently active for this client. If the pendingIntent is
+     *         null, this will be an empty list.
      * @throws StatsUnavailableException if unsuccessful due to failing to connect to stats service
      */
     @RequiresPermission(allOf = { DUMP, PACKAGE_USAGE_STATS })
-    public void setActiveConfigsChangedOperation(@Nullable PendingIntent pendingIntent)
+    public long[] setActiveConfigsChangedOperation(@Nullable PendingIntent pendingIntent)
             throws StatsUnavailableException {
         synchronized (this) {
             try {
                 IStatsManager service = getIStatsManagerLocked();
                 if (pendingIntent == null) {
                     service.removeActiveConfigsChangedOperation(mContext.getOpPackageName());
+                    return new long[0];
                 } else {
                     // Extracts IIntentSender from the PendingIntent and turns it into an IBinder.
                     IBinder intentSender = pendingIntent.getTarget().asBinder();
-                    service.setActiveConfigsChangedOperation(intentSender,
+                    return service.setActiveConfigsChangedOperation(intentSender,
                             mContext.getOpPackageName());
                 }
 
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 31a3def..807b7f2 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -30,7 +30,6 @@
 import android.app.slice.SliceManager;
 import android.app.timedetector.TimeDetector;
 import android.app.timezone.RulesManager;
-import android.app.timezonedetector.TimeZoneDetector;
 import android.app.trust.TrustManager;
 import android.app.usage.IStorageStatsManager;
 import android.app.usage.IUsageStatsManager;
@@ -1223,13 +1222,6 @@
                             throws ServiceNotFoundException {
                         return new TimeDetector();
                     }});
-        registerService(Context.TIME_ZONE_DETECTOR_SERVICE, TimeZoneDetector.class,
-                new CachedServiceFetcher<TimeZoneDetector>() {
-                    @Override
-                    public TimeZoneDetector createService(ContextImpl ctx)
-                            throws ServiceNotFoundException {
-                        return new TimeZoneDetector();
-                    }});
 
         registerService(Context.PERMISSION_SERVICE, PermissionManager.class,
                 new CachedServiceFetcher<PermissionManager>() {
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index f0d0aad..428c9b0 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -3149,6 +3149,7 @@
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
      */
+    @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
         if (mService != null) {
             try {
@@ -10590,14 +10591,19 @@
     }
 
     /**
-     * Returns if a package is whitelisted to access cross-profile calendar APIs.
+     * Returns if a package is allowed to access cross-profile calendar APIs.
+     *
+     * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
+     * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
+     * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
+     * is turned on in the managed profile.
      *
      * <p>To query for a specific user, use
      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
      * that user, and get a {@link DevicePolicyManager} from this context.
      *
      * @param packageName the name of the package
-     * @return {@code true} if the package is whitelisted to access cross-profile calendar APIs.
+     * @return {@code true} if the package is allowed to access cross-profile calendar APIs.
      * {@code false} otherwise.
      *
      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
diff --git a/core/java/android/app/timezonedetector/ITimeZoneDetectorService.aidl b/core/java/android/app/timezonedetector/ITimeZoneDetectorService.aidl
deleted file mode 100644
index ef2cbab..0000000
--- a/core/java/android/app/timezonedetector/ITimeZoneDetectorService.aidl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app.timezonedetector;
-
-/**
- * System private API to comunicate with time zone detector service.
- *
- * <p>Used by parts of the Android system with signals associated with the device's time zone to
- * provide information to the Time Zone Detector Service.
- *
- * <p>Use the {@link android.app.timezonedetector.TimeZoneDetector} class rather than going through
- * this Binder interface directly. See {@link android.app.timezonedetector.TimeZoneDetectorService}
- * for more complete documentation.
- *
- *
- * {@hide}
- */
-interface ITimeZoneDetectorService {
-  void stubbedCall();
-}
diff --git a/core/java/android/app/timezonedetector/TimeZoneDetector.java b/core/java/android/app/timezonedetector/TimeZoneDetector.java
deleted file mode 100644
index be3c764..0000000
--- a/core/java/android/app/timezonedetector/TimeZoneDetector.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app.timezonedetector;
-
-import android.annotation.SystemService;
-import android.content.Context;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.ServiceManager.ServiceNotFoundException;
-import android.util.Log;
-
-/**
- * The interface through which system components can send signals to the TimeZoneDetectorService.
- * @hide
- */
-@SystemService(Context.TIME_ZONE_DETECTOR_SERVICE)
-public final class TimeZoneDetector {
-
-    private static final String TAG = "timezonedetector.TimeZoneDetector";
-    private static final boolean DEBUG = false;
-
-    private final ITimeZoneDetectorService mITimeZoneDetectorService;
-
-    public TimeZoneDetector() throws ServiceNotFoundException {
-        mITimeZoneDetectorService = ITimeZoneDetectorService.Stub.asInterface(
-                ServiceManager.getServiceOrThrow(Context.TIME_ZONE_DETECTOR_SERVICE));
-
-    }
-    /**
-     * Does nothing.
-     * TODO: Remove this when the service implementation is built out.
-     */
-    public void stubbedCall() {
-        if (DEBUG) {
-            Log.d(TAG, "stubbedCall called");
-        }
-        try {
-            mITimeZoneDetectorService.stubbedCall();
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-}
diff --git a/core/java/android/app/usage/UsageEvents.java b/core/java/android/app/usage/UsageEvents.java
index 451f44b..8cbe7a3 100644
--- a/core/java/android/app/usage/UsageEvents.java
+++ b/core/java/android/app/usage/UsageEvents.java
@@ -405,6 +405,16 @@
         }
 
         /**
+         * Indicates whether it is an instant app.
+         * STOPSHIP b/111407095: Add GTS tests for the newly added API method.
+         * @hide
+         */
+        @SystemApi
+        public boolean isInstantApp() {
+            return (mFlags & FLAG_IS_PACKAGE_INSTANT_APP) == FLAG_IS_PACKAGE_INSTANT_APP;
+        }
+
+        /**
          * The class name of the source of this event. This may be null for
          * certain events.
          */
@@ -530,7 +540,7 @@
 
         /** @hide */
         public Event getObfuscatedIfInstantApp() {
-            if ((mFlags & FLAG_IS_PACKAGE_INSTANT_APP) == 0) {
+            if (!isInstantApp()) {
                 return this;
             }
             final Event ret = new Event(this);
@@ -735,6 +745,7 @@
                 p.writeString(event.mNotificationChannelId);
                 break;
         }
+        p.writeInt(event.mFlags);
     }
 
     /**
@@ -802,6 +813,7 @@
                 eventOut.mNotificationChannelId = p.readString();
                 break;
         }
+        eventOut.mFlags = p.readInt();
     }
 
     @Override
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 13d12c9..f138d39 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -28,7 +28,6 @@
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
 import android.app.AppOpsManager;
-import android.app.role.RoleManager;
 import android.content.pm.PathPermission;
 import android.content.pm.ProviderInfo;
 import android.content.res.AssetFileDescriptor;
@@ -226,17 +225,6 @@
         @Override
         public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
                 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
-            if (uri.toString().startsWith("content://sms")) {
-                RoleManager rm = getContext().getSystemService(RoleManager.class);
-                if (!rm.isRoleHeld(RoleManager.ROLE_SMS)
-                        && !rm.isRoleHeld(RoleManager.ROLE_DIALER)
-                        && !rm.isRoleHeld(RoleManager.ROLE_ASSISTANT)) {
-                    // STOPSHIP: log it to westworld instead
-                    Log.wtf(TAG, "Sms access attempted by " + callingPkg
-                            + " despite not holding an appropriate role");
-                }
-            }
-
             uri = validateIncomingUri(uri);
             uri = maybeGetUriWithoutUserId(uri);
             if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 97323ca..957a484 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -3186,7 +3186,6 @@
             CROSS_PROFILE_APPS_SERVICE,
             //@hide: SYSTEM_UPDATE_SERVICE,
             //@hide: TIME_DETECTOR_SERVICE,
-            //@hide: TIME_ZONE_DETECTOR_SERVICE,
             PERMISSION_SERVICE,
     })
     @Retention(RetentionPolicy.SOURCE)
@@ -4564,15 +4563,6 @@
     public static final String TIME_DETECTOR_SERVICE = "time_detector";
 
     /**
-     * Use with {@link #getSystemService(String)} to retrieve an
-     * {@link android.app.timezonedetector.ITimeZoneDetectorService}.
-     * @hide
-     *
-     * @see #getSystemService(String)
-     */
-    public static final String TIME_ZONE_DETECTOR_SERVICE = "time_zone_detector";
-
-    /**
      * Binder service name for {@link AppBindingService}.
      * @hide
      */
diff --git a/core/java/android/content/DynamicAndroidClient.java b/core/java/android/content/DynamicAndroidClient.java
new file mode 100644
index 0000000..571cba4
--- /dev/null
+++ b/core/java/android/content/DynamicAndroidClient.java
@@ -0,0 +1,370 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.content;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
+import android.util.Slog;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.ref.WeakReference;
+import java.util.concurrent.Executor;
+
+/**
+ * This class contains methods and constants used to start DynamicAndroid
+ * installation, and a listener for progress update.
+ * @hide
+ */
+@SystemApi
+public class DynamicAndroidClient {
+    /** @hide */
+    @IntDef(prefix = { "STATUS_" }, value = {
+            STATUS_UNKNOWN,
+            STATUS_NOT_STARTED,
+            STATUS_IN_PROGRESS,
+            STATUS_READY,
+            STATUS_IN_USE,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface InstallationStatus {}
+
+    /** @hide */
+    @IntDef(prefix = { "CAUSE_" }, value = {
+            CAUSE_NOT_SPECIFIED,
+            CAUSE_INSTALL_COMPLETED,
+            CAUSE_INSTALL_CANCELLED,
+            CAUSE_ERROR_IO,
+            CAUSE_ERROR_INVALID_URL,
+            CAUSE_ERROR_IPC,
+            CAUSE_ERROR_EXCEPTION,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface StatusChangedCause {}
+
+    private static final String TAG = "DynAndroidClient";
+
+    private static final long DEFAULT_USERDATA_SIZE = (10L << 30);
+
+
+    /** Listener for installation status update. */
+    public interface OnStatusChangedListener {
+        /**
+         * This callback is called when installation status is changed, and when the
+         * client is {@link #bind} to DynamicAndroid installation service.
+         *
+         * @param status status code, also defined in {@code DynamicAndroidClient}.
+         * @param cause cause code, also defined in {@code DynamicAndroidClient}.
+         * @param progress number of bytes installed.
+         */
+        void onStatusChanged(@InstallationStatus int status, @StatusChangedCause int cause,
+                long progress);
+    }
+
+    /*
+     * Status codes
+     */
+    /** We are bound to installation service, but failed to get its status */
+    public static final int STATUS_UNKNOWN = 0;
+
+    /** Installation is not started yet. */
+    public static final int STATUS_NOT_STARTED = 1;
+
+    /** Installation is in progress. */
+    public static final int STATUS_IN_PROGRESS = 2;
+
+    /** Installation is finished but the user has not launched it. */
+    public static final int STATUS_READY = 3;
+
+    /** Device is running in Dynamic Android. */
+    public static final int STATUS_IN_USE = 4;
+
+    /*
+     * Causes
+     */
+    /** Cause is not specified. This means the status is not changed. */
+    public static final int CAUSE_NOT_SPECIFIED = 0;
+
+    /** Status changed because installation is completed. */
+    public static final int CAUSE_INSTALL_COMPLETED = 1;
+
+    /** Status changed because installation is cancelled. */
+    public static final int CAUSE_INSTALL_CANCELLED = 2;
+
+    /** Installation failed due to IOException. */
+    public static final int CAUSE_ERROR_IO = 3;
+
+    /** Installation failed because the image URL source is not supported. */
+    public static final int CAUSE_ERROR_INVALID_URL = 4;
+
+    /** Installation failed due to IPC error. */
+    public static final int CAUSE_ERROR_IPC = 5;
+
+    /** Installation failed due to unhandled exception. */
+    public static final int CAUSE_ERROR_EXCEPTION = 6;
+
+    /*
+     * IPC Messages
+     */
+    /**
+     * Message to register listener.
+     * @hide
+     */
+    public static final int MSG_REGISTER_LISTENER = 1;
+
+    /**
+     * Message to unregister listener.
+     * @hide
+     */
+    public static final int MSG_UNREGISTER_LISTENER = 2;
+
+    /**
+     * Message for status update.
+     * @hide
+     */
+    public static final int MSG_POST_STATUS = 3;
+
+    /*
+     * Messages keys
+     */
+    /**
+     * Message key, for progress update.
+     * @hide
+     */
+    public static final String KEY_INSTALLED_SIZE = "KEY_INSTALLED_SIZE";
+
+    /*
+     * Intent Actions
+     */
+    /**
+     * Intent action: start installation.
+     * @hide
+     */
+    public static final String ACTION_START_INSTALL =
+            "android.content.action.START_INSTALL";
+
+    /**
+     * Intent action: notify user if we are currently running in Dynamic Android.
+     * @hide
+     */
+    public static final String ACTION_NOTIFY_IF_IN_USE =
+            "android.content.action.NOTIFY_IF_IN_USE";
+
+    /*
+     * Intent Keys
+     */
+    /**
+     * Intent key: URL to system image.
+     * @hide
+     */
+    public static final String KEY_SYSTEM_URL = "KEY_SYSTEM_URL";
+
+    /**
+     * Intent key: Size of system image, in bytes.
+     * @hide
+     */
+    public static final String KEY_SYSTEM_SIZE = "KEY_SYSTEM_SIZE";
+
+    /**
+     * Intent key: Number of bytes to reserve for userdata.
+     * @hide
+     */
+    public static final String KEY_USERDATA_SIZE = "KEY_USERDATA_SIZE";
+
+
+    private static class IncomingHandler extends Handler {
+        private final WeakReference<DynamicAndroidClient> mWeakClient;
+
+        IncomingHandler(DynamicAndroidClient service) {
+            super(Looper.getMainLooper());
+            mWeakClient = new WeakReference<>(service);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            DynamicAndroidClient service = mWeakClient.get();
+
+            if (service != null) {
+                service.handleMessage(msg);
+            }
+        }
+    }
+
+    private class DynAndroidServiceConnection implements ServiceConnection {
+        public void onServiceConnected(ComponentName className, IBinder service) {
+            Slog.v(TAG, "DynAndroidService connected");
+
+            mService = new Messenger(service);
+
+            try {
+                Message msg = Message.obtain(null, MSG_REGISTER_LISTENER);
+                msg.replyTo = mMessenger;
+
+                mService.send(msg);
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Unable to get status from installation service");
+                mExecutor.execute(() -> {
+                    mListener.onStatusChanged(STATUS_UNKNOWN, CAUSE_ERROR_IPC, 0);
+                });
+            }
+        }
+
+        public void onServiceDisconnected(ComponentName className) {
+            Slog.v(TAG, "DynAndroidService disconnected");
+            mService = null;
+        }
+    }
+
+    private final Context mContext;
+    private final DynAndroidServiceConnection mConnection;
+    private final Messenger mMessenger;
+
+    private boolean mBound;
+    private Executor mExecutor;
+    private OnStatusChangedListener mListener;
+    private Messenger mService;
+
+    /**
+     * @hide
+     */
+    @SystemApi
+    public DynamicAndroidClient(@NonNull Context context) {
+        mContext = context;
+        mConnection = new DynAndroidServiceConnection();
+        mMessenger = new Messenger(new IncomingHandler(this));
+    }
+
+    /**
+     * This method register a listener for status change. The listener is called using
+     * the executor.
+     */
+    public void setOnStatusChangedListener(
+            @NonNull OnStatusChangedListener listener,
+            @NonNull @CallbackExecutor Executor executor) {
+        mListener = listener;
+        mExecutor = executor;
+    }
+
+    /**
+     * This method register a listener for status change. The listener is called in main
+     * thread.
+     */
+    public void setOnStatusChangedListener(
+            @NonNull OnStatusChangedListener listener) {
+        mListener = listener;
+        mExecutor = null;
+    }
+
+    /**
+     * Bind to DynamicAndroidInstallationService.
+     */
+    public void bind() {
+        Intent intent = new Intent();
+        intent.setClassName("com.android.dynandroid",
+                "com.android.dynandroid.DynamicAndroidInstallationService");
+
+        mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
+
+        mBound = true;
+    }
+
+    /**
+     * Unbind from DynamicAndroidInstallationService.
+     */
+    public void unbind() {
+        if (!mBound) {
+            return;
+        }
+
+        if (mService != null) {
+            try {
+                Message msg = Message.obtain(null, MSG_UNREGISTER_LISTENER);
+                msg.replyTo = mMessenger;
+                mService.send(msg);
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Unable to unregister from installation service");
+            }
+        }
+
+        // Detach our existing connection.
+        mContext.unbindService(mConnection);
+
+        mBound = false;
+    }
+
+    /**
+     * Start installing DynamicAndroid from URL with default userdata size.
+     *
+     * @param systemUrl A network URL or a file URL to system image.
+     * @param systemSize size of system image.
+     */
+    public void start(String systemUrl, long systemSize) {
+        start(systemUrl, systemSize, DEFAULT_USERDATA_SIZE);
+    }
+
+    /**
+     * Start installing DynamicAndroid from URL.
+     *
+     * @param systemUrl A network URL or a file URL to system image.
+     * @param systemSize size of system image.
+     * @param userdataSize bytes reserved for userdata.
+     */
+    public void start(String systemUrl, long systemSize, long userdataSize) {
+        Intent intent = new Intent();
+
+        intent.setClassName("com.android.dynandroid",
+                "com.android.dynandroid.VerificationActivity");
+
+        intent.setAction(ACTION_START_INSTALL);
+
+        intent.putExtra(KEY_SYSTEM_URL, systemUrl);
+        intent.putExtra(KEY_SYSTEM_SIZE, systemSize);
+        intent.putExtra(KEY_USERDATA_SIZE, userdataSize);
+
+        mContext.startActivity(intent);
+    }
+
+    private void handleMessage(Message msg) {
+        switch (msg.what) {
+            case MSG_POST_STATUS:
+                int status = msg.arg1;
+                int cause = msg.arg2;
+                // obj is non-null
+                long progress = ((Bundle) msg.obj).getLong(KEY_INSTALLED_SIZE);
+
+                if (mExecutor != null) {
+                    mExecutor.execute(() -> {
+                        mListener.onStatusChanged(status, cause, progress);
+                    });
+                } else {
+                    mListener.onStatusChanged(status, cause, progress);
+                }
+                break;
+            default:
+                // do nothing
+
+        }
+    }
+}
diff --git a/core/java/android/content/pm/ActivityPresentationInfo.java b/core/java/android/content/pm/ActivityPresentationInfo.java
new file mode 100644
index 0000000..ccc61dc
--- /dev/null
+++ b/core/java/android/content/pm/ActivityPresentationInfo.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.content.pm;
+
+import android.annotation.NonNull;
+import android.content.ComponentName;
+
+/**
+ * Holds basic information about an activity.
+ *
+ * @hide
+ */
+public final class ActivityPresentationInfo {
+    public final int taskId;
+    public final int displayId;
+
+    @NonNull
+    public final ComponentName componentName;
+
+    public ActivityPresentationInfo(int taskId, int displayId,
+            @NonNull ComponentName componentName) {
+        this.taskId = taskId;
+        this.displayId = displayId;
+        this.componentName = componentName;
+    }
+}
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 1358bc2..b27c5dc 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -640,19 +640,15 @@
     public static final int PRIVATE_FLAG_HAS_FRAGILE_USER_DATA = 1 << 24;
 
     /**
-     * Indicate whether this application prefers code integrity, that is, run only code that is
-     * signed. This requires android:extractNativeLibs to be "false", as well as .dex and .so (if
-     * any) stored uncompressed inside the APK, which is signed. At run time, the implications
-     * include:
-     *
-     * <ul>
-     * <li>ART will JIT the dex code directly from the APK. There may be performance characteristic
-     * changes depend on the actual workload.
-     * </ul>
+     * Indicates whether this application wants to use the embedded dex in the APK, rather than
+     * extracted or locally compiled variants. This keeps the dex code protected by the APK
+     * signature. Such apps will always run in JIT mode (same when they are first installed), and
+     * the system will never generate ahead-of-time compiled code for them. Depending on the app's
+     * workload, there may be some run time performance change, noteably the cold start time.
      *
      * @hide
      */
-    public static final int PRIVATE_FLAG_PREFER_CODE_INTEGRITY = 1 << 25;
+    public static final int PRIVATE_FLAG_USE_EMBEDDED_DEX = 1 << 25;
 
     /** @hide */
     @IntDef(flag = true, prefix = { "PRIVATE_FLAG_" }, value = {
@@ -669,7 +665,7 @@
             PRIVATE_FLAG_ISOLATED_SPLIT_LOADING,
             PRIVATE_FLAG_OEM,
             PRIVATE_FLAG_PARTIALLY_DIRECT_BOOT_AWARE,
-            PRIVATE_FLAG_PREFER_CODE_INTEGRITY,
+            PRIVATE_FLAG_USE_EMBEDDED_DEX,
             PRIVATE_FLAG_PRIVILEGED,
             PRIVATE_FLAG_PRODUCT,
             PRIVATE_FLAG_PRODUCT_SERVICES,
@@ -1962,8 +1958,8 @@
     }
 
     /** @hide */
-    public boolean isCodeIntegrityPreferred() {
-        return (privateFlags & PRIVATE_FLAG_PREFER_CODE_INTEGRITY) != 0;
+    public boolean isEmbeddedDexUsed() {
+        return (privateFlags & PRIVATE_FLAG_USE_EMBEDDED_DEX) != 0;
     }
 
     /**
diff --git a/core/java/android/content/pm/BasicActivityInfo.aidl b/core/java/android/content/pm/BasicActivityInfo.aidl
new file mode 100644
index 0000000..f04bf9a
--- /dev/null
+++ b/core/java/android/content/pm/BasicActivityInfo.aidl
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.content.pm;
+
+/** @hide */
+parcelable BasicActivityInfo;
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index a6a6f01..36ffb0e 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -686,6 +686,8 @@
 
     String getWellbeingPackageName();
 
+    String getAppPredictionServicePackageName();
+
     String getContentCaptureServicePackageName();
 
     String getIncidentReportApproverPackageName();
diff --git a/core/java/android/content/pm/ModuleInfo.java b/core/java/android/content/pm/ModuleInfo.java
index 07e640b..044e87d 100644
--- a/core/java/android/content/pm/ModuleInfo.java
+++ b/core/java/android/content/pm/ModuleInfo.java
@@ -32,7 +32,7 @@
      // constructor, and writeToParcel.
 
     /** Public name of this module. */
-    private String mName;
+    private CharSequence mName;
 
     /** The package name of this module. */
     private String mPackageName;
@@ -57,13 +57,13 @@
     }
 
     /** @hide Sets the public name of this module. */
-    public ModuleInfo setName(String name) {
+    public ModuleInfo setName(CharSequence name) {
         mName = name;
         return this;
     }
 
     /** Gets the public name of this module. */
-    public @Nullable String getName() {
+    public @Nullable CharSequence getName() {
         return mName;
     }
 
@@ -123,13 +123,13 @@
 
     /** Flattens this object into the given {@link Parcel}. */
     public void writeToParcel(Parcel dest, int parcelableFlags) {
-        dest.writeString(mName);
+        dest.writeCharSequence(mName);
         dest.writeString(mPackageName);
         dest.writeBoolean(mHidden);
     }
 
     private ModuleInfo(Parcel source) {
-        mName = source.readString();
+        mName = source.readCharSequence();
         mPackageName = source.readString();
         mHidden = source.readBoolean();
     }
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index 4f674bd..8b8f3e5 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -1290,6 +1290,28 @@
             isStaged = source.readBoolean();
         }
 
+        /** {@hide} */
+        public SessionParams copy() {
+            SessionParams ret = new SessionParams(mode);
+            ret.installFlags = installFlags;
+            ret.installLocation = installLocation;
+            ret.installReason = installReason;
+            ret.sizeBytes = sizeBytes;
+            ret.appPackageName = appPackageName;
+            ret.appIcon = appIcon;  // not a copy.
+            ret.appLabel = appLabel;
+            ret.originatingUri = originatingUri;  // not a copy, but immutable.
+            ret.originatingUid = originatingUid;
+            ret.referrerUri = referrerUri;  // not a copy, but immutable.
+            ret.abiOverride = abiOverride;
+            ret.volumeUuid = volumeUuid;
+            ret.grantedRuntimePermissions = grantedRuntimePermissions;
+            ret.installerPackageName = installerPackageName;
+            ret.isMultiPackage = isMultiPackage;
+            ret.isStaged = isStaged;
+            return ret;
+        }
+
         /**
          * Check if there are hidden options set.
          *
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index d88f36c..e2907e2 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -552,8 +552,6 @@
      * currently active, i.e. mounted and available to other processes of the OS.
      * In particular, this flag alone will not match APEX files that are staged
      * for activation at next reboot.
-     * TODO(b/119767311): include uninstalled/inactive APEX if
-     *                    MATCH_UNINSTALLED_PACKAGES is set.
      */
     public static final int MATCH_APEX = 0x40000000;
 
@@ -6727,6 +6725,16 @@
     }
 
     /**
+     * @return the system defined app predictor package name, or null if there's none.
+     *
+     * @hide
+     */
+    public String getAppPredictionServicePackageName() {
+        throw new UnsupportedOperationException(
+            "getAppPredictionServicePackageName not implemented in subclass");
+    }
+
+    /**
      * @return the system defined content capture service package name, or null if there's none.
      *
      * @hide
diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
index 738730e..4a2dbe7 100644
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ b/core/java/android/content/pm/PackageManagerInternal.java
@@ -57,6 +57,7 @@
     public static final int PACKAGE_DOCUMENTER = 8;
     public static final int PACKAGE_CONFIGURATOR = 9;
     public static final int PACKAGE_INCIDENT_REPORT_APPROVER = 10;
+    public static final int PACKAGE_APP_PREDICTOR = 11;
     @IntDef(value = {
         PACKAGE_SYSTEM,
         PACKAGE_SETUP_WIZARD,
@@ -69,6 +70,7 @@
         PACKAGE_DOCUMENTER,
         PACKAGE_CONFIGURATOR,
         PACKAGE_INCIDENT_REPORT_APPROVER,
+        PACKAGE_APP_PREDICTOR,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface KnownPackage {}
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 1fab443..2c2d6f2 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -475,7 +475,7 @@
         public final boolean extractNativeLibs;
         public final boolean isolatedSplits;
         public final boolean isSplitRequired;
-        public final boolean preferCodeIntegrity;
+        public final boolean useEmbeddedDex;
 
         public ApkLite(String codePath, String packageName, String splitName,
                 boolean isFeatureSplit,
@@ -484,7 +484,7 @@
                 int revisionCode, int installLocation, List<VerifierInfo> verifiers,
                 SigningDetails signingDetails, boolean coreApp,
                 boolean debuggable, boolean multiArch, boolean use32bitAbi,
-                boolean preferCodeIntegrity, boolean extractNativeLibs, boolean isolatedSplits) {
+                boolean useEmbeddedDex, boolean extractNativeLibs, boolean isolatedSplits) {
             this.codePath = codePath;
             this.packageName = packageName;
             this.splitName = splitName;
@@ -501,7 +501,7 @@
             this.debuggable = debuggable;
             this.multiArch = multiArch;
             this.use32bitAbi = use32bitAbi;
-            this.preferCodeIntegrity = preferCodeIntegrity;
+            this.useEmbeddedDex = useEmbeddedDex;
             this.extractNativeLibs = extractNativeLibs;
             this.isolatedSplits = isolatedSplits;
             this.isSplitRequired = isSplitRequired;
@@ -1726,7 +1726,7 @@
         boolean isolatedSplits = false;
         boolean isFeatureSplit = false;
         boolean isSplitRequired = false;
-        boolean preferCodeIntegrity = false;
+        boolean useEmbeddedDex = false;
         String configForSplit = null;
         String usesSplitName = null;
 
@@ -1790,8 +1790,8 @@
                         extractNativeLibsProvided = Boolean.valueOf(
                                 attrs.getAttributeBooleanValue(i, true));
                     }
-                    if ("preferCodeIntegrity".equals(attr)) {
-                        preferCodeIntegrity = attrs.getAttributeBooleanValue(i, false);
+                    if ("useEmbeddedDex".equals(attr)) {
+                        useEmbeddedDex = attrs.getAttributeBooleanValue(i, false);
                     }
                 }
             } else if (TAG_USES_SPLIT.equals(parser.getName())) {
@@ -1851,16 +1851,10 @@
         final boolean extractNativeLibs = (extractNativeLibsProvided != null)
                 ? extractNativeLibsProvided : extractNativeLibsDefault;
 
-        if (preferCodeIntegrity && extractNativeLibs) {
-            throw new PackageParserException(
-                    PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED,
-                    "Can't request both preferCodeIntegrity and extractNativeLibs");
-        }
-
         return new ApkLite(codePath, packageSplit.first, packageSplit.second, isFeatureSplit,
                 configForSplit, usesSplitName, isSplitRequired, versionCode, versionCodeMajor,
                 revisionCode, installLocation, verifiers, signingDetails, coreApp, debuggable,
-                multiArch, use32bitAbi, preferCodeIntegrity, extractNativeLibs, isolatedSplits);
+                multiArch, use32bitAbi, useEmbeddedDex, extractNativeLibs, isolatedSplits);
     }
 
     /**
@@ -3789,9 +3783,9 @@
         }
 
         if (sa.getBoolean(
-                R.styleable.AndroidManifestApplication_preferCodeIntegrity,
+                R.styleable.AndroidManifestApplication_useEmbeddedDex,
                 false)) {
-            ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PREFER_CODE_INTEGRITY;
+            ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_USE_EMBEDDED_DEX;
         }
 
         if (sa.getBoolean(
@@ -4429,7 +4423,7 @@
         a.owner = owner;
         a.setPackageName(owner.packageName);
 
-        a.info.theme = 0;
+        a.info.theme = android.R.style.Theme_NoDisplay;
         a.info.exported = true;
         a.info.name = AppDetailsActivity.class.getName();
         a.info.processName = owner.applicationInfo.processName;
@@ -5576,7 +5570,7 @@
 
         s.info.mForegroundServiceType = sa.getInt(
                 com.android.internal.R.styleable.AndroidManifestService_foregroundServiceType,
-                ServiceInfo.FOREGROUND_SERVICE_TYPE_UNSPECIFIED);
+                ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE);
 
         s.info.flags = 0;
         if (sa.getBoolean(
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index e776984..fb63e0d 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -224,6 +224,17 @@
     @TestApi
     public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 0x100000;
 
+    /**
+     * Additional flag for {@link #protectionLevel}, corresponding
+     * to the <code>app_predictor</code> value of
+     * {@link android.R.attr#protectionLevel}.
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int PROTECTION_FLAG_APP_PREDICTOR = 0x200000;
+
     /** @hide */
     @IntDef(flag = true, prefix = { "PROTECTION_FLAG_" }, value = {
             PROTECTION_FLAG_PRIVILEGED,
@@ -244,6 +255,7 @@
             PROTECTION_FLAG_DOCUMENTER,
             PROTECTION_FLAG_CONFIGURATOR,
             PROTECTION_FLAG_INCIDENT_REPORT_APPROVER,
+            PROTECTION_FLAG_APP_PREDICTOR,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ProtectionFlags {}
@@ -445,6 +457,9 @@
         if ((level & PermissionInfo.PROTECTION_FLAG_INCIDENT_REPORT_APPROVER) != 0) {
             protLevel += "|incidentReportApprover";
         }
+        if ((level & PermissionInfo.PROTECTION_FLAG_APP_PREDICTOR) != 0) {
+            protLevel += "|appPredictor";
+        }
         return protLevel;
     }
 
diff --git a/core/java/android/content/pm/ServiceInfo.java b/core/java/android/content/pm/ServiceInfo.java
index 8300c0c..60475de 100644
--- a/core/java/android/content/pm/ServiceInfo.java
+++ b/core/java/android/content/pm/ServiceInfo.java
@@ -101,77 +101,73 @@
     /**
      * The default foreground service type if not been set in manifest file.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_UNSPECIFIED = 0;
+    public static final int FOREGROUND_SERVICE_TYPE_NONE = 0;
 
     /**
-     * Constant corresponding to <code>sync</code> in
+     * Constant corresponding to <code>dataSync</code> in
      * the {@link android.R.attr#foregroundServiceType} attribute.
      * Data(photo, file, account) upload/download, backup/restore, import/export, fetch,
      * transfer over network between device and cloud.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_SYNC = 1;
+    public static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 1 << 0;
 
     /**
-     * Constant corresponding to <code>mediaPlay</code> in
+     * Constant corresponding to <code>mediaPlayback</code> in
      * the {@link android.R.attr#foregroundServiceType} attribute.
-     * Music, video, news or other media play.
+     * Music, video, news or other media playback.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_MEDIA_PLAY = 2;
+    public static final int FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK = 1 << 1;
 
     /**
      * Constant corresponding to <code>phoneCall</code> in
      * the {@link android.R.attr#foregroundServiceType} attribute.
      * Ongoing phone call or video conference.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_PHONE_CALL = 3;
+    public static final int FOREGROUND_SERVICE_TYPE_PHONE_CALL = 1 << 2;
 
     /**
      * Constant corresponding to <code>location</code> in
      * the {@link android.R.attr#foregroundServiceType} attribute.
      * GPS, map, navigation location update.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_LOCATION = 4;
+    public static final int FOREGROUND_SERVICE_TYPE_LOCATION = 1 << 3;
 
     /**
-     * Constant corresponding to <code>deviceCompanion</code> in
+     * Constant corresponding to <code>connectedDevice</code> in
      * the {@link android.R.attr#foregroundServiceType} attribute.
      * Auto, bluetooth, TV or other devices connection, monitoring and interaction.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_DEVICE_COMPANION = 5;
+    public static final int FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE = 1 << 4;
 
     /**
-     * Constant corresponding to <code>ongoingProcess</code> in
-     * the {@link android.R.attr#foregroundServiceType} attribute.
-     * Process that should not be interrupted, including installation, setup, photo
-     * compression etc.
+     * A special value indicates to use all types set in manifest file.
      */
-    public static final int FOREGROUND_SERVICE_TYPE_ONGOING_PROCESS = 6;
+    public static final int FOREGROUND_SERVICE_TYPE_MANIFEST = -1;
 
     /**
-     * The enumeration of values for foreground service type.
+     * The set of flags for foreground service type.
      * The foreground service type is set in {@link android.R.attr#foregroundServiceType}
      * attribute.
      * @hide
      */
-    @IntDef(flag = false, prefix = { "FOREGROUND_SERVICE_TYPE_" }, value = {
-            FOREGROUND_SERVICE_TYPE_UNSPECIFIED,
-            FOREGROUND_SERVICE_TYPE_SYNC,
-            FOREGROUND_SERVICE_TYPE_MEDIA_PLAY,
+    @IntDef(flag = true, prefix = { "FOREGROUND_SERVICE_TYPE_" }, value = {
+            FOREGROUND_SERVICE_TYPE_NONE,
+            FOREGROUND_SERVICE_TYPE_DATA_SYNC,
+            FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,
             FOREGROUND_SERVICE_TYPE_PHONE_CALL,
             FOREGROUND_SERVICE_TYPE_LOCATION,
-            FOREGROUND_SERVICE_TYPE_DEVICE_COMPANION,
-            FOREGROUND_SERVICE_TYPE_ONGOING_PROCESS
+            FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ForegroundServiceType {}
 
     /**
      * The type of foreground service, set in
-     * {@link android.R.attr#foregroundServiceType} attribute, one value in
+     * {@link android.R.attr#foregroundServiceType} attribute by ORing flags in
      * {@link ForegroundServiceType}
      * @hide
      */
-    public @ForegroundServiceType int mForegroundServiceType = FOREGROUND_SERVICE_TYPE_UNSPECIFIED;
+    public @ForegroundServiceType int mForegroundServiceType = FOREGROUND_SERVICE_TYPE_NONE;
 
     public ServiceInfo() {
     }
@@ -217,6 +213,7 @@
         super.writeToParcel(dest, parcelableFlags);
         dest.writeString(permission);
         dest.writeInt(flags);
+        dest.writeInt(mForegroundServiceType);
     }
 
     public static final Creator<ServiceInfo> CREATOR =
@@ -233,5 +230,6 @@
         super(source);
         permission = source.readString();
         flags = source.readInt();
+        mForegroundServiceType = source.readInt();
     }
 }
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index baf64ad..59db49e 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -1394,6 +1394,17 @@
         mResourcesImpl.getValue(name, outValue, resolveRefs);
     }
 
+
+    /**
+     * @param set AttributeSet for which we want to find the source.
+     * @return The resource id for the source that is backing the given AttributeSet
+     * @hide
+     */
+    @AnyRes
+    public static int getAttributeSetSourceResId(@Nullable AttributeSet set) {
+        return ResourcesImpl.getAttributeSetSourceResId(set);
+    }
+
     /**
      * This class holds the current attribute values for a particular theme.
      * In other words, a Theme is a set of values for resource attributes;
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index d8564d5..9898079 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -15,6 +15,8 @@
  */
 package android.content.res;
 
+import static android.content.res.Resources.ID_NULL;
+
 import android.animation.Animator;
 import android.animation.StateListAnimator;
 import android.annotation.AnyRes;
@@ -1222,7 +1224,7 @@
                     for (int i = 0; i < num; i++) {
                         if (cachedXmlBlockCookies[i] == assetCookie && cachedXmlBlockFiles[i] != null
                                 && cachedXmlBlockFiles[i].equals(file)) {
-                            return cachedXmlBlocks[i].newParser();
+                            return cachedXmlBlocks[i].newParser(id);
                         }
                     }
 
@@ -1239,7 +1241,7 @@
                         cachedXmlBlockCookies[pos] = assetCookie;
                         cachedXmlBlockFiles[pos] = file;
                         cachedXmlBlocks[pos] = block;
-                        return block.newParser();
+                        return block.newParser(id);
                     }
                 }
             } catch (Exception e) {
@@ -1299,6 +1301,14 @@
         }
     }
 
+    @AnyRes
+    static int getAttributeSetSourceResId(@Nullable AttributeSet set) {
+        if (set == null) {
+            return ID_NULL;
+        }
+        return ((XmlBlock.Parser) set).getSourceResId();
+    }
+
     LongSparseArray<Drawable.ConstantState> getPreloadedDrawables() {
         return sPreloadedDrawables[0];
     }
diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java
index d53834c..d36e076 100644
--- a/core/java/android/content/res/TypedArray.java
+++ b/core/java/android/content/res/TypedArray.java
@@ -72,7 +72,7 @@
     static final int STYLE_RESOURCE_ID = 3;
     static final int STYLE_CHANGING_CONFIGURATIONS = 4;
     static final int STYLE_DENSITY = 5;
-    static final int SYTLE_SOURCE_STYLE_RESOURCE_ID = 6;
+    static final int SYTLE_SOURCE_RESOURCE_ID = 6;
 
     @UnsupportedAppUsage
     private final Resources mResources;
@@ -1101,28 +1101,51 @@
     }
 
     /**
-     * Returns the resource ID of the style against which the specified attribute was resolved,
-     * otherwise returns defValue.
+     * Returns the resource ID of the style or layout against which the specified attribute was
+     * resolved, otherwise returns defValue.
+     *
+     * For example, if you we resolving two attributes {@code android:attribute1} and
+     * {@code android:attribute2} and you were inflating a {@link android.view.View} from
+     * {@code layout/my_layout.xml}:
+     * <pre>
+     *     &lt;View
+     *         style="@style/viewStyle"
+     *         android:layout_width="wrap_content"
+     *         android:layout_height="wrap_content"
+     *         android:attribute1="foo"/&gt;
+     * </pre>
+     *
+     * and {@code @style/viewStyle} is:
+     * <pre>
+     *     &lt;style android:name="viewStyle"&gt;
+     *         &lt;item name="android:attribute2"&gt;bar&lt;item/&gt;
+     *     &lt;style/&gt;
+     * </pre>
+     *
+     * then resolved {@link TypedArray} will have values that return source resource ID of
+     * {@code R.layout.my_layout} for {@code android:attribute1} and {@code R.style.viewStyle} for
+     * {@code android:attribute2}.
      *
      * @param index Index of attribute whose source style to retrieve.
-     * @param defValue Value to return if the attribute is not defined or
-     *                 not a resource.
+     * @param defaultValue Value to return if the attribute is not defined or
+     *                     not a resource.
      *
-     * @return Attribute source style resource ID or defValue if it was not resolved in any style.
+     * @return Either a style resource ID, layout resource ID, or defaultValue if it was not
+     * resolved in a style or layout.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
     @StyleRes
-    public int getSourceStyleResourceId(@StyleableRes int index, @StyleRes int defValue) {
+    public int getSourceResourceId(@StyleableRes int index, @StyleRes int defaultValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
 
         index *= STYLE_NUM_ENTRIES;
-        final int resid = mData[index + SYTLE_SOURCE_STYLE_RESOURCE_ID];
+        final int resid = mData[index + SYTLE_SOURCE_RESOURCE_ID];
         if (resid != 0) {
             return resid;
         }
-        return defValue;
+        return defaultValue;
     }
 
     /**
@@ -1337,7 +1360,7 @@
                 data[index + STYLE_CHANGING_CONFIGURATIONS]);
         outValue.density = data[index + STYLE_DENSITY];
         outValue.string = (type == TypedValue.TYPE_STRING) ? loadStringValueAt(index) : null;
-        outValue.sourceStyleResourceId = data[index + SYTLE_SOURCE_STYLE_RESOURCE_ID];
+        outValue.sourceResourceId = data[index + SYTLE_SOURCE_RESOURCE_ID];
         return true;
     }
 
diff --git a/core/java/android/content/res/XmlBlock.java b/core/java/android/content/res/XmlBlock.java
index 4e1159a..626bf77 100644
--- a/core/java/android/content/res/XmlBlock.java
+++ b/core/java/android/content/res/XmlBlock.java
@@ -16,6 +16,9 @@
 
 package android.content.res;
 
+import static android.content.res.Resources.ID_NULL;
+
+import android.annotation.AnyRes;
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
 import android.util.TypedValue;
@@ -73,9 +76,13 @@
 
     @UnsupportedAppUsage
     public XmlResourceParser newParser() {
+        return newParser(ID_NULL);
+    }
+
+    public XmlResourceParser newParser(@AnyRes int resId) {
         synchronized (this) {
             if (mNative != 0) {
-                return new Parser(nativeCreateParseState(mNative), this);
+                return new Parser(nativeCreateParseState(mNative, resId), this);
             }
             return null;
         }
@@ -88,6 +95,11 @@
             block.mOpenCount++;
         }
 
+        @AnyRes
+        public int getSourceResId() {
+            return nativeGetSourceResId(mParseState);
+        }
+
         public void setFeature(String name, boolean state) throws XmlPullParserException {
             if (FEATURE_PROCESS_NAMESPACES.equals(name) && state) {
                 return;
@@ -501,7 +513,7 @@
                                                  int offset,
                                                  int size);
     private static final native long nativeGetStringBlock(long obj);
-    private static final native long nativeCreateParseState(long obj);
+    private static final native long nativeCreateParseState(long obj, int resId);
     private static final native void nativeDestroyParseState(long state);
     private static final native void nativeDestroy(long obj);
 
@@ -539,4 +551,6 @@
     private static final native int nativeGetStyleAttribute(long state);
     @FastNative
     private static final native int nativeGetAttributeIndex(long state, String namespace, String name);
+    @FastNative
+    private static final native int nativeGetSourceResId(long state);
 }
diff --git a/core/java/android/database/sqlite/SQLiteConnection.java b/core/java/android/database/sqlite/SQLiteConnection.java
index 20505ca..3c8e236 100644
--- a/core/java/android/database/sqlite/SQLiteConnection.java
+++ b/core/java/android/database/sqlite/SQLiteConnection.java
@@ -448,6 +448,8 @@
             } finally {
                 execute(success ? "COMMIT" : "ROLLBACK", null, null);
             }
+        } catch (SQLiteException ex) {
+            throw ex;
         } catch (RuntimeException ex) {
             throw new SQLiteException("Failed to change locale for db '" + mConfiguration.label
                     + "' to '" + newLocale + "'.", ex);
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index a1b0803..ae456af 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -890,9 +890,14 @@
         try {
             try {
                 openInner();
-            } catch (SQLiteDatabaseCorruptException ex) {
-                onCorruption();
-                openInner();
+            } catch (RuntimeException ex) {
+                if (SQLiteDatabaseCorruptException.isCorruptException(ex)) {
+                    Log.e(TAG, "Database corruption detected in open()", ex);
+                    onCorruption();
+                    openInner();
+                } else {
+                    throw ex;
+                }
             }
         } catch (SQLiteException ex) {
             Log.e(TAG, "Failed to open database '" + getLabel() + "'.", ex);
diff --git a/core/java/android/database/sqlite/SQLiteDatabaseCorruptException.java b/core/java/android/database/sqlite/SQLiteDatabaseCorruptException.java
index 73b6c0c..488ef46 100644
--- a/core/java/android/database/sqlite/SQLiteDatabaseCorruptException.java
+++ b/core/java/android/database/sqlite/SQLiteDatabaseCorruptException.java
@@ -25,4 +25,20 @@
     public SQLiteDatabaseCorruptException(String error) {
         super(error);
     }
+
+    /**
+     * @return true if a given {@link Throwable} or any of its inner causes is of
+     * {@link SQLiteDatabaseCorruptException}.
+     *
+     * @hide
+     */
+    public static boolean isCorruptException(Throwable th) {
+        while (th != null) {
+            if (th instanceof SQLiteDatabaseCorruptException) {
+                return true;
+            }
+            th = th.getCause();
+        }
+        return false;
+    }
 }
diff --git a/core/java/android/hardware/HardwareBuffer.java b/core/java/android/hardware/HardwareBuffer.java
index 5d4928c..475be49 100644
--- a/core/java/android/hardware/HardwareBuffer.java
+++ b/core/java/android/hardware/HardwareBuffer.java
@@ -20,6 +20,7 @@
 import android.annotation.LongDef;
 import android.annotation.NonNull;
 import android.annotation.UnsupportedAppUsage;
+import android.graphics.GraphicBuffer;
 import android.os.Build;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -214,6 +215,19 @@
     }
 
     /**
+     * @hide
+     * Returns a <code>HardwareBuffer</code> instance from <code>GraphicBuffer</code>
+     *
+     * @param graphicBuffer A GraphicBuffer to be wrapped as HardwareBuffer
+     * @return A <code>HardwareBuffer</code> instance.
+     */
+    @NonNull
+    public static HardwareBuffer createFromGraphicBuffer(@NonNull GraphicBuffer graphicBuffer) {
+        long nativeObject = nCreateFromGraphicBuffer(graphicBuffer);
+        return new HardwareBuffer(nativeObject);
+    }
+
+    /**
      * Private use only. See {@link #create(int, int, int, int, long)}. May also be
      * called from JNI using an already allocated native <code>HardwareBuffer</code>.
      */
@@ -405,6 +419,7 @@
 
     private static native long nCreateHardwareBuffer(int width, int height, int format, int layers,
             long usage);
+    private static native long nCreateFromGraphicBuffer(GraphicBuffer graphicBuffer);
     private static native long nGetNativeFinalizer();
     private static native void nWriteHardwareBufferToParcel(long nativeObject, Parcel dest);
     private static native long nReadHardwareBufferFromParcel(Parcel in);
diff --git a/core/java/android/hardware/biometrics/BiometricFaceConstants.java b/core/java/android/hardware/biometrics/BiometricFaceConstants.java
index 125dabe..b708ef1 100644
--- a/core/java/android/hardware/biometrics/BiometricFaceConstants.java
+++ b/core/java/android/hardware/biometrics/BiometricFaceConstants.java
@@ -268,7 +268,7 @@
      * capture plane is too high.
      *
      * The tilt angle is defined as the angle swept out by the user’s face looking up
-     * and down. The pan angle would be zero if the user faced the camera directly.
+     * and down. The tilt angle would be zero if the user faced the camera directly.
      *
      * The user should be informed to look more directly at the camera.
      */
@@ -279,8 +279,8 @@
      * capture plane is too high.
      *
      * The roll angle is defined as the angle swept out by the user’s face tilting their head
-     * towards their shoulders to the left and right. The pan angle would be zero if the user
-     * faced the camera directly.
+     * towards their shoulders to the left and right. The roll angle would be zero if the user's
+     * head is vertically aligned with the camera.
      *
      * The user should be informed to look more directly at the camera.
      */
diff --git a/core/java/android/hardware/biometrics/BiometricManager.java b/core/java/android/hardware/biometrics/BiometricManager.java
index 5afe1a9..d257c03 100644
--- a/core/java/android/hardware/biometrics/BiometricManager.java
+++ b/core/java/android/hardware/biometrics/BiometricManager.java
@@ -21,6 +21,7 @@
 
 import android.annotation.IntDef;
 import android.annotation.RequiresPermission;
+import android.annotation.SystemService;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.os.RemoteException;
@@ -29,6 +30,7 @@
 /**
  * A class that contains biometric utilities. For authentication, see {@link BiometricPrompt}.
  */
+@SystemService(Context.BIOMETRIC_SERVICE)
 public class BiometricManager {
 
     private static final String TAG = "BiometricManager";
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index ec62aba..d569a78 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -202,6 +202,9 @@
          * Required: Set the text for the negative button. This would typically be used as a
          * "Cancel" button, but may be also used to show an alternative method for authentication,
          * such as screen that asks for a backup password.
+         *
+         * Note that this should not be set if {@link #setEnableFallback(boolean)} is set to true.
+         *
          * @param text
          * @return
          */
@@ -248,6 +251,10 @@
         /**
          * The user will first be prompted to authenticate with biometrics, but also given the
          * option to authenticate with their device PIN, pattern, or password.
+         *
+         * Note that {@link #setNegativeButton(CharSequence, Executor,
+         * DialogInterface.OnClickListener)} should not be set if this is set to true.
+         *
          * @param enable When true, the prompt will fall back to ask for the user's device
          *               credentials (PIN, pattern, or password).
          * @return
diff --git a/core/java/android/hardware/display/BrightnessChangeEvent.java b/core/java/android/hardware/display/BrightnessChangeEvent.java
index 02eb28c..c6186bb 100644
--- a/core/java/android/hardware/display/BrightnessChangeEvent.java
+++ b/core/java/android/hardware/display/BrightnessChangeEvent.java
@@ -16,11 +16,15 @@
 
 package android.hardware.display;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
+import java.util.Objects;
+
 /**
  * Data about a brightness settings change.
  *
@@ -72,12 +76,29 @@
     /** Whether brightness curve includes a user brightness point */
     public final boolean isUserSetBrightness;
 
+    /**
+     * Histogram counting how many times a pixel of a given value was displayed onscreen for the
+     * Value component of HSV if the device supports color sampling, if the device does not support
+     * color sampling the value will be null.
+     * The buckets of the histogram are evenly weighted, the number of buckets is device specific.
+     * For example if we had {10, 6, 4, 1} this means that 10 pixels were in the range
+     * [0x00,0x3f], 6 pixels were in the range [0x40,0x7f] etc.
+     */
+    @Nullable
+    public final long[] colorValueBuckets;
+
+    /**
+     * How many milliseconds of data are contained in the colorValueBuckets.
+     */
+    public final long colorSampleDuration;
+
 
     /** @hide */
     private BrightnessChangeEvent(float brightness, long timeStamp, String packageName,
             int userId, float[] luxValues, long[] luxTimestamps, float batteryLevel,
             float powerBrightnessFactor, boolean nightMode, int colorTemperature,
-            float lastBrightness, boolean isDefaultBrightnessConfig, boolean isUserSetBrightness) {
+            float lastBrightness, boolean isDefaultBrightnessConfig, boolean isUserSetBrightness,
+            long[] colorValueBuckets, long colorSampleDuration) {
         this.brightness = brightness;
         this.timeStamp = timeStamp;
         this.packageName = packageName;
@@ -91,6 +112,8 @@
         this.lastBrightness = lastBrightness;
         this.isDefaultBrightnessConfig = isDefaultBrightnessConfig;
         this.isUserSetBrightness = isUserSetBrightness;
+        this.colorValueBuckets = colorValueBuckets;
+        this.colorSampleDuration = colorSampleDuration;
     }
 
     /** @hide */
@@ -108,6 +131,8 @@
         this.lastBrightness = other.lastBrightness;
         this.isDefaultBrightnessConfig = other.isDefaultBrightnessConfig;
         this.isUserSetBrightness = other.isUserSetBrightness;
+        this.colorValueBuckets = other.colorValueBuckets;
+        this.colorSampleDuration = other.colorSampleDuration;
     }
 
     private BrightnessChangeEvent(Parcel source) {
@@ -124,6 +149,8 @@
         lastBrightness = source.readFloat();
         isDefaultBrightnessConfig = source.readBoolean();
         isUserSetBrightness = source.readBoolean();
+        colorValueBuckets = source.createLongArray();
+        colorSampleDuration = source.readLong();
     }
 
     public static final Creator<BrightnessChangeEvent> CREATOR =
@@ -156,6 +183,8 @@
         dest.writeFloat(lastBrightness);
         dest.writeBoolean(isDefaultBrightnessConfig);
         dest.writeBoolean(isUserSetBrightness);
+        dest.writeLongArray(colorValueBuckets);
+        dest.writeLong(colorSampleDuration);
     }
 
     /** @hide */
@@ -173,6 +202,8 @@
         private float mLastBrightness;
         private boolean mIsDefaultBrightnessConfig;
         private boolean mIsUserSetBrightness;
+        private long[] mColorValueBuckets;
+        private long mColorSampleDuration;
 
         /** {@see BrightnessChangeEvent#brightness} */
         public Builder setBrightness(float brightness) {
@@ -252,12 +283,21 @@
             return this;
         }
 
+        /** {@see BrightnessChangeEvent#valueBuckets} */
+        public Builder setColorValues(@NonNull long[] colorValueBuckets, long colorSampleDuration) {
+            Objects.requireNonNull(colorValueBuckets);
+            mColorValueBuckets = colorValueBuckets;
+            mColorSampleDuration = colorSampleDuration;
+            return this;
+        }
+
         /** Builds a BrightnessChangeEvent */
         public BrightnessChangeEvent build() {
             return new BrightnessChangeEvent(mBrightness, mTimeStamp,
                     mPackageName, mUserId, mLuxValues, mLuxTimestamps, mBatteryLevel,
                     mPowerBrightnessFactor, mNightMode, mColorTemperature, mLastBrightness,
-                    mIsDefaultBrightnessConfig, mIsUserSetBrightness);
+                    mIsDefaultBrightnessConfig, mIsUserSetBrightness, mColorValueBuckets,
+                    mColorSampleDuration);
         }
     }
 }
diff --git a/core/java/android/permission/IPermissionController.aidl b/core/java/android/permission/IPermissionController.aidl
index 5dd869f..ee6744b 100644
--- a/core/java/android/permission/IPermissionController.aidl
+++ b/core/java/android/permission/IPermissionController.aidl
@@ -32,8 +32,8 @@
     void getRuntimePermissionBackup(in UserHandle user, in ParcelFileDescriptor pipe);
     void getAppPermissions(String packageName, in RemoteCallback callback);
     void revokeRuntimePermission(String packageName, String permissionName);
-    void countPermissionApps(in List<String> permissionNames, boolean countOnlyGranted,
-            boolean countSystem, in RemoteCallback callback);
+    void countPermissionApps(in List<String> permissionNames, int flags,
+            in RemoteCallback callback);
     void getPermissionUsages(boolean countSystem, long numMillis, in RemoteCallback callback);
     void isApplicationQualifiedForRole(String roleName, String packageName,
             in RemoteCallback callback);
diff --git a/core/java/android/permission/PermissionControllerManager.java b/core/java/android/permission/PermissionControllerManager.java
index b59d0c7..c59e573 100644
--- a/core/java/android/permission/PermissionControllerManager.java
+++ b/core/java/android/permission/PermissionControllerManager.java
@@ -20,6 +20,7 @@
 
 import static com.android.internal.util.Preconditions.checkArgumentNonnegative;
 import static com.android.internal.util.Preconditions.checkCollectionElementsNotNull;
+import static com.android.internal.util.Preconditions.checkFlagsArgument;
 import static com.android.internal.util.Preconditions.checkNotNull;
 import static com.android.internal.util.Preconditions.checkStringNotEmpty;
 
@@ -113,6 +114,20 @@
      */
     public static final int REASON_INSTALLER_POLICY_VIOLATION = 2;
 
+    /** @hide */
+    @IntDef(prefix = { "COUNT_" }, value = {
+            COUNT_ONLY_WHEN_GRANTED,
+            COUNT_WHEN_SYSTEM,
+    }, flag = true)
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface CountPermissionAppsFlag {}
+
+    /** Count an app only if the permission is granted to the app. */
+    public static final int COUNT_ONLY_WHEN_GRANTED = 1;
+
+    /** Count and app even if it is a system app. */
+    public static final int COUNT_WHEN_SYSTEM = 2;
+
     /**
      * Callback for delivering the result of {@link #revokeRuntimePermissions}.
      */
@@ -162,7 +177,7 @@
      */
     public interface OnCountPermissionAppsResultCallback {
         /**
-         * The result for {@link #countPermissionApps(List, boolean, boolean,
+         * The result for {@link #countPermissionApps(List, int,
          * OnCountPermissionAppsResultCallback, Handler)}.
          *
          * @param numApps The number of apps that have one of the permissions
@@ -254,6 +269,7 @@
     public void getRuntimePermissionBackup(@NonNull UserHandle user,
             @NonNull @CallbackExecutor Executor executor,
             @NonNull OnGetRuntimePermissionBackupCallback callback) {
+        checkNotNull(user);
         checkNotNull(executor);
         checkNotNull(callback);
 
@@ -302,8 +318,8 @@
      * Count how many apps have one of a set of permissions.
      *
      * @param permissionNames The permissions the app might have
-     * @param countOnlyGranted Count an app only if the permission is granted to the app
-     * @param countSystem Also count system apps
+     * @param flags Modify which apps to count. By default all non-system apps that request a
+     *              permission are counted
      * @param callback Callback to receive the result
      * @param handler Handler on which to invoke the callback
      *
@@ -311,13 +327,14 @@
      */
     @RequiresPermission(Manifest.permission.GET_RUNTIME_PERMISSIONS)
     public void countPermissionApps(@NonNull List<String> permissionNames,
-            boolean countOnlyGranted, boolean countSystem,
+            @CountPermissionAppsFlag int flags,
             @NonNull OnCountPermissionAppsResultCallback callback, @Nullable Handler handler) {
         checkCollectionElementsNotNull(permissionNames, "permissionNames");
+        checkFlagsArgument(flags, COUNT_WHEN_SYSTEM | COUNT_ONLY_WHEN_GRANTED);
         checkNotNull(callback);
 
         sRemoteService.scheduleRequest(new PendingCountPermissionAppsRequest(sRemoteService,
-                permissionNames, countOnlyGranted, countSystem, callback,
+                permissionNames, flags, callback,
                 handler == null ? sRemoteService.getHandler() : handler));
     }
 
@@ -731,20 +748,17 @@
             AbstractRemoteService.PendingRequest<RemoteService, IPermissionController> {
         private final @NonNull List<String> mPermissionNames;
         private final @NonNull OnCountPermissionAppsResultCallback mCallback;
-        private final boolean mCountOnlyGranted;
-        private final boolean mCountSystem;
+        private final @CountPermissionAppsFlag int mFlags;
 
         private final @NonNull RemoteCallback mRemoteCallback;
 
         private PendingCountPermissionAppsRequest(@NonNull RemoteService service,
-                @NonNull List<String> permissionNames, boolean countOnlyGranted,
-                boolean countSystem, @NonNull OnCountPermissionAppsResultCallback callback,
-                @NonNull Handler handler) {
+                @NonNull List<String> permissionNames, @CountPermissionAppsFlag int flags,
+                @NonNull OnCountPermissionAppsResultCallback callback, @NonNull Handler handler) {
             super(service);
 
             mPermissionNames = permissionNames;
-            mCountOnlyGranted = countOnlyGranted;
-            mCountSystem = countSystem;
+            mFlags = flags;
             mCallback = callback;
 
             mRemoteCallback = new RemoteCallback(result -> {
@@ -770,7 +784,7 @@
         public void run() {
             try {
                 getService().getServiceInterface().countPermissionApps(mPermissionNames,
-                        mCountOnlyGranted, mCountSystem, mRemoteCallback);
+                        mFlags, mRemoteCallback);
             } catch (RemoteException e) {
                 Log.e(TAG, "Error counting permission apps", e);
             }
diff --git a/core/java/android/permission/PermissionControllerService.java b/core/java/android/permission/PermissionControllerService.java
index 9a58b97..482f4a8 100644
--- a/core/java/android/permission/PermissionControllerService.java
+++ b/core/java/android/permission/PermissionControllerService.java
@@ -16,9 +16,13 @@
 
 package android.permission;
 
+import static android.permission.PermissionControllerManager.COUNT_ONLY_WHEN_GRANTED;
+import static android.permission.PermissionControllerManager.COUNT_WHEN_SYSTEM;
+
 import static com.android.internal.util.Preconditions.checkArgument;
 import static com.android.internal.util.Preconditions.checkArgumentNonnegative;
 import static com.android.internal.util.Preconditions.checkCollectionElementsNotNull;
+import static com.android.internal.util.Preconditions.checkFlagsArgument;
 import static com.android.internal.util.Preconditions.checkNotNull;
 import static com.android.internal.util.Preconditions.checkStringNotEmpty;
 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
@@ -37,6 +41,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteCallback;
 import android.os.UserHandle;
+import android.permission.PermissionControllerManager.CountPermissionAppsFlag;
 import android.util.ArrayMap;
 import android.util.Log;
 
@@ -51,7 +56,7 @@
 /**
  * This service is meant to be implemented by the app controlling permissions.
  *
- * @see PermissionController
+ * @see PermissionControllerManager
  *
  * @hide
  */
@@ -93,10 +98,10 @@
      * Create a backup of the runtime permissions.
      *
      * @param user The user to back up
-     * @param out The stream to write the backup to
+     * @param backup The stream to write the backup to
      */
     public abstract void onGetRuntimePermissionsBackup(@NonNull UserHandle user,
-            @NonNull OutputStream out);
+            @NonNull OutputStream backup);
 
     /**
      * Gets the runtime permissions for an app.
@@ -121,13 +126,13 @@
      * Count how many apps have one of a set of permissions.
      *
      * @param permissionNames The permissions the app might have
-     * @param countOnlyGranted Count an app only if the permission is granted to the app
-     * @param countSystem Also count system apps
+     * @param flags Modify which apps to count. By default all non-system apps that request a
+     *              permission are counted
      *
      * @return the number of apps that have one of the permissions
      */
     public abstract int onCountPermissionApps(@NonNull List<String> permissionNames,
-            boolean countOnlyGranted, boolean countSystem);
+            @CountPermissionAppsFlag int flags);
 
     /**
      * Count how many apps have used permissions.
@@ -226,17 +231,18 @@
             }
 
             @Override
-            public void countPermissionApps(List<String> permissionNames, boolean countOnlyGranted,
-                    boolean countSystem, RemoteCallback callback) {
+            public void countPermissionApps(List<String> permissionNames, int flags,
+                    RemoteCallback callback) {
                 checkCollectionElementsNotNull(permissionNames, "permissionNames");
+                checkFlagsArgument(flags, COUNT_WHEN_SYSTEM | COUNT_ONLY_WHEN_GRANTED);
                 checkNotNull(callback, "callback");
 
                 enforceCallingPermission(Manifest.permission.GET_RUNTIME_PERMISSIONS, null);
 
                 mHandler.sendMessage(
                         obtainMessage(PermissionControllerService::countPermissionApps,
-                                PermissionControllerService.this, permissionNames, countOnlyGranted,
-                                countSystem, callback));
+                                PermissionControllerService.this, permissionNames, flags,
+                                callback));
             }
 
             @Override
@@ -291,11 +297,11 @@
     }
 
     private void getRuntimePermissionsBackup(@NonNull UserHandle user,
-            @NonNull ParcelFileDescriptor outFile) {
-        try (OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(outFile)) {
-            onGetRuntimePermissionsBackup(user, out);
+            @NonNull ParcelFileDescriptor backupFile) {
+        try (OutputStream backup = new ParcelFileDescriptor.AutoCloseOutputStream(backupFile)) {
+            onGetRuntimePermissionsBackup(user, backup);
         } catch (IOException e) {
-            Log.e(LOG_TAG, "Could not open pipe to write backup tp", e);
+            Log.e(LOG_TAG, "Could not open pipe to write backup to", e);
         }
     }
 
@@ -311,8 +317,8 @@
     }
 
     private void countPermissionApps(@NonNull List<String> permissionNames,
-            boolean countOnlyGranted, boolean countSystem, @NonNull RemoteCallback callback) {
-        int numApps = onCountPermissionApps(permissionNames, countOnlyGranted, countSystem);
+            @CountPermissionAppsFlag int flags, @NonNull RemoteCallback callback) {
+        int numApps = onCountPermissionApps(permissionNames, flags);
 
         Bundle result = new Bundle();
         result.putInt(PermissionControllerManager.KEY_RESULT, numApps);
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index ffa47a9..e14bb66 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -3536,6 +3536,16 @@
         private static final Validator MASTER_MONO_VALIDATOR = BOOLEAN_VALIDATOR;
 
         /**
+         * Master balance (float -1.f = 100% left, 0.f = dead center, 1.f = 100% right).
+         *
+         * @hide
+         */
+        public static final String MASTER_BALANCE = "master_balance";
+
+        private static final Validator MASTER_BALANCE_VALIDATOR =
+                new SettingsValidators.InclusiveFloatRangeValidator(-1.f, 1.f);
+
+        /**
          * Whether the notifications should use the ring volume (value of 1) or
          * a separate notification volume (value of 0). In most cases, users
          * will have this enabled so the notification and ringer volumes will be
@@ -4288,6 +4298,7 @@
             HEARING_AID,
             TTY_MODE,
             MASTER_MONO,
+            MASTER_BALANCE,
             SOUND_EFFECTS_ENABLED,
             HAPTIC_FEEDBACK_ENABLED,
             POWER_SOUNDS_ENABLED,       // moved to global
@@ -4395,6 +4406,7 @@
             PRIVATE_SETTINGS.add(VIBRATE_INPUT_DEVICES);
             PRIVATE_SETTINGS.add(VOLUME_MASTER);
             PRIVATE_SETTINGS.add(MASTER_MONO);
+            PRIVATE_SETTINGS.add(MASTER_BALANCE);
             PRIVATE_SETTINGS.add(NOTIFICATIONS_USE_RING_VOLUME);
             PRIVATE_SETTINGS.add(VIBRATE_IN_SILENT);
             PRIVATE_SETTINGS.add(MEDIA_BUTTON_RECEIVER);
@@ -4488,6 +4500,7 @@
             VALIDATORS.put(SCREEN_AUTO_BRIGHTNESS_ADJ, SCREEN_AUTO_BRIGHTNESS_ADJ_VALIDATOR);
             VALIDATORS.put(VIBRATE_INPUT_DEVICES, VIBRATE_INPUT_DEVICES_VALIDATOR);
             VALIDATORS.put(MASTER_MONO, MASTER_MONO_VALIDATOR);
+            VALIDATORS.put(MASTER_BALANCE, MASTER_BALANCE_VALIDATOR);
             VALIDATORS.put(NOTIFICATIONS_USE_RING_VOLUME, NOTIFICATIONS_USE_RING_VOLUME_VALIDATOR);
             VALIDATORS.put(VIBRATE_IN_SILENT, VIBRATE_IN_SILENT_VALIDATOR);
             VALIDATORS.put(MEDIA_BUTTON_RECEIVER, MEDIA_BUTTON_RECEIVER_VALIDATOR);
@@ -14315,6 +14328,19 @@
         public static final String LOOPER_STATS = "looper_stats";
 
         /**
+         * Settings for collecting statistics on CPU usage per thread
+         *
+         * The following strings are supported as keys:
+         * <pre>
+         *     num_buckets          (int)
+         *     collected_uids       (string)
+         * </pre>
+         *
+         * @hide
+         */
+        public static final String KERNEL_CPU_THREAD_READER = "kernel_cpu_thread_reader";
+
+        /**
          * Default user id to boot into. They map to user ids, for example, 10, 11, 12.
          *
          * @hide
diff --git a/core/java/android/service/contentsuggestions/ContentSuggestionsService.java b/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
index 0da8039..333f4be 100644
--- a/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
+++ b/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
@@ -31,6 +31,7 @@
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.GraphicBuffer;
+import android.hardware.HardwareBuffer;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
@@ -62,7 +63,8 @@
             mHandler.sendMessage(
                     obtainMessage(ContentSuggestionsService::processContextImage,
                             ContentSuggestionsService.this, taskId,
-                            Bitmap.createHardwareBitmap(contextImage),
+                            Bitmap.wrapHardwareBuffer(
+                                    HardwareBuffer.createFromGraphicBuffer(contextImage), null),
                             imageContextRequestExtras));
         }
 
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index bec654a..bff118e 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -958,13 +958,15 @@
         if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_MESSAGES,
                 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_MESSAGES, defaultPolicy))) {
             priorityCategories |= Policy.PRIORITY_CATEGORY_MESSAGES;
-            messageSenders = getNotificationPolicySenders(zenPolicy.getPriorityMessageSenders());
+            messageSenders = getNotificationPolicySenders(zenPolicy.getPriorityMessageSenders(),
+                    messageSenders);
         }
 
         if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_CALLS,
                 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_CALLS, defaultPolicy))) {
             priorityCategories |= Policy.PRIORITY_CATEGORY_CALLS;
-            callSenders = getNotificationPolicySenders(zenPolicy.getPriorityCallSenders());
+            callSenders = getNotificationPolicySenders(zenPolicy.getPriorityCallSenders(),
+                    callSenders);
         }
 
         if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_REPEAT_CALLERS,
@@ -1056,16 +1058,17 @@
         return (policy.suppressedVisualEffects & visualEffect) == 0;
     }
 
-    private int getNotificationPolicySenders(@ZenPolicy.PeopleType int senders) {
+    private int getNotificationPolicySenders(@ZenPolicy.PeopleType int senders,
+            int defaultPolicySender) {
         switch (senders) {
             case ZenPolicy.PEOPLE_TYPE_ANYONE:
                 return Policy.PRIORITY_SENDERS_ANY;
             case ZenPolicy.PEOPLE_TYPE_CONTACTS:
-
                 return Policy.PRIORITY_SENDERS_CONTACTS;
             case ZenPolicy.PEOPLE_TYPE_STARRED:
-            default:
                 return Policy.PRIORITY_SENDERS_STARRED;
+            default:
+                return defaultPolicySender;
         }
     }
 
diff --git a/core/java/android/service/voice/VoiceInteractionService.java b/core/java/android/service/voice/VoiceInteractionService.java
index e76e096..ea2a25d 100644
--- a/core/java/android/service/voice/VoiceInteractionService.java
+++ b/core/java/android/service/voice/VoiceInteractionService.java
@@ -348,7 +348,7 @@
      */
     public final void setVoiceState(int state) {
         try {
-            mSystemService.setVoiceState(state);
+            mSystemService.setVoiceState(mInterface, state);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -359,7 +359,7 @@
      */
     public final void setTranscription(@NonNull String transcription) {
         try {
-            mSystemService.setTranscription(transcription);
+            mSystemService.setTranscription(mInterface, transcription);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -372,7 +372,7 @@
      */
     public final void clearTranscription(boolean immediate) {
         try {
-            mSystemService.clearTranscription(immediate);
+            mSystemService.clearTranscription(mInterface, immediate);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/util/StatsLog.java b/core/java/android/util/StatsLog.java
index e3de307..ace4bf4 100644
--- a/core/java/android/util/StatsLog.java
+++ b/core/java/android/util/StatsLog.java
@@ -16,6 +16,7 @@
 
 package android.util;
 
+import android.annotation.NonNull;
 import android.os.IStatsManager;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -113,4 +114,18 @@
         sService = IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
         return sService;
     }
+
+    /**
+     * Add a log to the stats log.
+     *
+     * @param id The id of the atom
+     * @param params The parameters of the atom's message.
+     */
+    public static void write(int id, @NonNull Object... params) {
+        switch (id) {
+            case PERMISSION_GRANT_REQUEST_RESULT_REPORTED:
+                write(id, (long) params[0], (int) params[1], (String) params[2], (String) params[3],
+                        (boolean) params[4], (int) params[5]);
+        }
+    }
 }
diff --git a/core/java/android/util/StatsLogAtoms.java b/core/java/android/util/StatsLogAtoms.java
new file mode 100644
index 0000000..bbede53
--- /dev/null
+++ b/core/java/android/util/StatsLogAtoms.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.annotation.IntDef;
+import android.annotation.SystemApi;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Exposed stats logs atom ids.
+ *
+ * @hide
+ */
+@SystemApi
+public class StatsLogAtoms {
+    private StatsLogAtoms() {
+    }
+
+    /**
+     * Information about a permission grant request
+     *
+     * Usage: {@code StatsLog.write(PERMISSION_GRANT_REQUEST_RESULT_REPORTED, long request_id,
+     * int requesting_uid, String requesting_package_name, String permission_name,
+     * boolean is_implicit, @PermissionGrantRequestResultReported_Result int result)}
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED;
+
+    @Retention(SOURCE)
+    @IntDef(prefix = "PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__",
+            value = {PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_USER_FIXED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_POLICY_FIXED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_GRANTED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_GRANTED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED_WITH_PREJUDICE,
+                    PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_DENIED})
+    public @interface PermissionGrantRequestResultReported_Result {}
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission request was ignored
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission request was ignored because it was user fixed
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_USER_FIXED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_USER_FIXED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission request was ignored because it was policy fixed
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_POLICY_FIXED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__IGNORED_POLICY_FIXED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission was granted by user action
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_GRANTED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_GRANTED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission was automatically granted
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_GRANTED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_GRANTED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission was denied by user action
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission was denied with prejudice by the user
+     */
+    public static final int
+            PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED_WITH_PREJUDICE =
+            StatsLogInternal
+                    .PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__USER_DENIED_WITH_PREJUDICE;
+
+    /**
+     * Possible value of {@link PermissionGrantRequestResultReported_Result}:
+     * permission was automatically denied
+     */
+    public static final int PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_DENIED =
+            StatsLogInternal.PERMISSION_GRANT_REQUEST_RESULT_REPORTED__RESULT__AUTO_DENIED;
+}
diff --git a/core/java/android/util/TypedValue.java b/core/java/android/util/TypedValue.java
index 99106be..7f1ee30 100644
--- a/core/java/android/util/TypedValue.java
+++ b/core/java/android/util/TypedValue.java
@@ -217,10 +217,10 @@
     public int density;
 
     /**
-     * If the Value came from a style resource, this holds the corresponding style resource id
-     * against which the attribute was resolved.
+     * If the Value came from a style resource or a layout resource (set in an XML layout), this
+     * holds the corresponding style or layout resource id against which the attribute was resolved.
      */
-    public int sourceStyleResourceId;
+    public int sourceResourceId;
 
     /* ------------------------------------------------------------ */
 
diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java
index 7d9ec70..c794a69 100644
--- a/core/java/android/view/GestureDetector.java
+++ b/core/java/android/view/GestureDetector.java
@@ -237,16 +237,6 @@
     private static final int LONG_PRESS = 2;
     private static final int TAP = 3;
 
-    /**
-     * If a MotionEvent has CLASSIFICATION_AMBIGUOUS_GESTURE set, then certain actions, such as
-     * scrolling, will be inhibited. However, to account for the possibility of incorrect
-     * classification, the default scrolling will only be inhibited if the gesture moves beyond
-     * (default touch slop * AMBIGUOUS_GESTURE_MULTIPLIER). Likewise, the default long press
-     * timeout will be increased for some situations where the default behaviour
-     * is to cancel it.
-     */
-    private static final int AMBIGUOUS_GESTURE_MULTIPLIER = 2;
-
     private final Handler mHandler;
     @UnsupportedAppUsage
     private final OnGestureListener mListener;
@@ -636,6 +626,7 @@
                             hasPendingLongPress && ambiguousGesture;
                     if (shouldInhibitDefaultAction) {
                         // Inhibit default long press
+                        final float multiplier = ViewConfiguration.getAmbiguousGestureMultiplier();
                         if (distance > slopSquare) {
                             // The default action here is to remove long press. But if the touch
                             // slop below gets increased, and we never exceed the modified touch
@@ -643,15 +634,15 @@
                             // will happen in response to user input. To prevent this,
                             // reschedule long press with a modified timeout.
                             mHandler.removeMessages(LONG_PRESS);
-                            final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
+                            final long longPressTimeout = ViewConfiguration.getLongPressTimeout();
                             mHandler.sendEmptyMessageAtTime(LONG_PRESS, ev.getDownTime()
-                                    + longPressTimeout * AMBIGUOUS_GESTURE_MULTIPLIER);
+                                    + (long) (longPressTimeout * multiplier));
                         }
                         // Inhibit default scroll. If a gesture is ambiguous, we prevent scroll
                         // until the gesture is resolved.
                         // However, for safety, simply increase the touch slop in case the
                         // classification is erroneous. Since the value is squared, multiply twice.
-                        slopSquare *= AMBIGUOUS_GESTURE_MULTIPLIER * AMBIGUOUS_GESTURE_MULTIPLIER;
+                        slopSquare *= multiplier * multiplier;
                     }
 
                     if (distance > slopSquare) {
diff --git a/core/java/android/view/LayoutInflater.java b/core/java/android/view/LayoutInflater.java
index 6061cb2..6a290b7 100644
--- a/core/java/android/view/LayoutInflater.java
+++ b/core/java/android/view/LayoutInflater.java
@@ -414,8 +414,7 @@
 
         // Make sure the application allows code generation
         ApplicationInfo appInfo = mContext.getApplicationInfo();
-        if ((appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PREFER_CODE_INTEGRITY) != 0
-            || appInfo.isPrivilegedApp()) {
+        if (appInfo.isEmbeddedDexUsed() || appInfo.isPrivilegedApp()) {
             mUseCompiledView = false;
             return;
         }
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index 9d3552f..b6a4a09 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -431,8 +431,9 @@
 
     /**
      * This flag indicates that the window that received this motion event is partly
-     * or wholly obscured by another visible window above it.  This flag is set to true
-     * even if the event did not directly pass through the obscured area.
+     * or wholly obscured by another visible window above it. This flag is set to true
+     * if the event directly passed through the obscured area.
+     *
      * A security sensitive application can check this flag to identify situations in which
      * a malicious application may have covered up part of its content for the purpose
      * of misleading the user or hijacking touches.  An appropriate response might be
@@ -443,16 +444,17 @@
 
     /**
      * This flag indicates that the window that received this motion event is partly
-     * or wholly obscured by another visible window above it.  This flag is set to true
+     * or wholly obscured by another visible window above it. This flag is set to true
      * even if the event did not directly pass through the obscured area.
+     *
      * A security sensitive application can check this flag to identify situations in which
      * a malicious application may have covered up part of its content for the purpose
      * of misleading the user or hijacking touches.  An appropriate response might be
      * to drop the suspect touches or to take additional precautions to confirm the user's
      * actual intent.
      *
-     * Unlike FLAG_WINDOW_IS_OBSCURED, this is actually true.
-     * @hide
+     * Unlike FLAG_WINDOW_IS_OBSCURED, this is true even if the window that received this event is
+     * obstructed in areas other than the touched location.
      */
     public static final int FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 0x2;
 
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index 7fcb2af..d0194f9 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -57,7 +57,8 @@
             throws OutOfResourcesException;
 
     private static native long nativeCreateFromSurfaceControl(long surfaceControlNativeObject);
-    private static native long nativeGetFromSurfaceControl(long surfaceControlNativeObject);
+    private static native long nativeGetFromSurfaceControl(long surfaceObject,
+            long surfaceControlNativeObject);
 
     private static native long nativeLockCanvas(long nativeObject, Canvas canvas, Rect dirty)
             throws OutOfResourcesException;
@@ -519,9 +520,12 @@
             throw new NullPointerException(
                     "null SurfaceControl native object. Are you using a released SurfaceControl?");
         }
-        long newNativeObject = nativeGetFromSurfaceControl(surfaceControlPtr);
+        long newNativeObject = nativeGetFromSurfaceControl(mNativeObject, surfaceControlPtr);
 
         synchronized (mLock) {
+            if (newNativeObject == mNativeObject) {
+                return;
+            }
             if (mNativeObject != 0) {
                 nativeRelease(mNativeObject);
             }
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index 2956606..8061cc3 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -41,6 +41,7 @@
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.Region;
+import android.hardware.HardwareBuffer;
 import android.hardware.display.DisplayedContentSample;
 import android.hardware.display.DisplayedContentSamplingAttributes;
 import android.os.IBinder;
@@ -154,6 +155,8 @@
     private static native int nativeGetActiveConfig(IBinder displayToken);
     private static native boolean nativeSetActiveConfig(IBinder displayToken, int id);
     private static native int[] nativeGetDisplayColorModes(IBinder displayToken);
+    private static native SurfaceControl.DisplayPrimaries nativeGetDisplayNativePrimaries(
+            IBinder displayToken);
     private static native int[] nativeGetCompositionDataspaces();
     private static native int nativeGetActiveColorMode(IBinder displayToken);
     private static native boolean nativeSetActiveColorMode(IBinder displayToken,
@@ -501,16 +504,7 @@
             }
             mWidth = width;
             mHeight = height;
-            // set this as a buffer layer since we are specifying a buffer size.
-            return setFlags(FX_SURFACE_NORMAL, FX_SURFACE_MASK);
-        }
-
-        /**
-         * Set the initial size of the controlled surface's buffers in pixels.
-         */
-        private void unsetBufferSize() {
-            mWidth = 0;
-            mHeight = 0;
+            return this;
         }
 
         /**
@@ -628,11 +622,16 @@
          * Color layers will not have an associated BufferQueue and will instead always render a
          * solid color (that is, solid before plane alpha). Currently that color is black.
          *
+         * @param isColorLayer Whether to create a color layer.
          * @hide
          */
-        public Builder setColorLayer() {
-            unsetBufferSize();
-            return setFlags(FX_SURFACE_DIM, FX_SURFACE_MASK);
+        public Builder setColorLayer(boolean isColorLayer) {
+            if (isColorLayer) {
+                mFlags |= FX_SURFACE_DIM;
+            } else {
+                mFlags &= ~FX_SURFACE_DIM;
+            }
+            return this;
         }
 
         private boolean isColorLayerSet() {
@@ -645,11 +644,16 @@
          * Container layers will not be rendered in any fashion and instead are used
          * as a parent of renderable layers.
          *
+         * @param isContainerLayer Whether to create a container layer.
          * @hide
          */
-        public Builder setContainerLayer() {
-            unsetBufferSize();
-            return setFlags(FX_SURFACE_CONTAINER, FX_SURFACE_MASK);
+        public Builder setContainerLayer(boolean isContainerLayer) {
+            if (isContainerLayer) {
+                mFlags |= FX_SURFACE_CONTAINER;
+            } else {
+                mFlags &= ~FX_SURFACE_CONTAINER;
+            }
+            return this;
         }
 
         private boolean isContainerLayerSet() {
@@ -657,7 +661,7 @@
         }
 
         /**
-         * Set 'Surface creation flags' such as {@link #HIDDEN}, {@link #SECURE}.
+         * Set 'Surface creation flags' such as {@link HIDDEN}, {@link SECURE}.
          *
          * TODO: Finish conversion to individual builder methods?
          * @param flags The combined flags
@@ -667,11 +671,6 @@
             mFlags = flags;
             return this;
         }
-
-        private Builder setFlags(int flags, int mask) {
-            mFlags = (mFlags & ~mask) | flags;
-            return this;
-        }
     }
 
     /**
@@ -1539,6 +1538,73 @@
     }
 
     /**
+     * Color coordinates in CIE1931 XYZ color space
+     *
+     * @hide
+     */
+    public static final class CieXyz {
+        /**
+         * @hide
+         */
+        public float X;
+
+        /**
+         * @hide
+         */
+        public float Y;
+
+        /**
+         * @hide
+         */
+        public float Z;
+    }
+
+    /**
+     * Contains a display's color primaries
+     *
+     * @hide
+     */
+    public static final class DisplayPrimaries {
+        /**
+         * @hide
+         */
+        public CieXyz red;
+
+        /**
+         * @hide
+         */
+        public CieXyz green;
+
+        /**
+         * @hide
+         */
+        public CieXyz blue;
+
+        /**
+         * @hide
+         */
+        public CieXyz white;
+
+        /**
+         * @hide
+         */
+        public DisplayPrimaries() {
+        }
+    }
+
+    /**
+     * @hide
+     */
+    public static SurfaceControl.DisplayPrimaries getDisplayNativePrimaries(
+            IBinder displayToken) {
+        if (displayToken == null) {
+            throw new IllegalArgumentException("displayToken must not be null");
+        }
+
+        return nativeGetDisplayNativePrimaries(displayToken);
+    }
+
+    /**
      * @hide
      */
     public static int getActiveColorMode(IBinder displayToken) {
@@ -1738,7 +1804,10 @@
             Log.w(TAG, "Failed to take screenshot");
             return null;
         }
-        return Bitmap.createHardwareBitmap(buffer);
+        // TODO(b/116112787) Now that hardware bitmap creation can take color space, we
+        // should continue to fix screenshot.
+        return Bitmap.wrapHardwareBuffer(HardwareBuffer.createFromGraphicBuffer(buffer),
+                ColorSpace.get(ColorSpace.Named.SRGB));
     }
 
     /**
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index ecb2ac4..ecbec65 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -33,6 +33,7 @@
 import android.graphics.RenderNode;
 import android.os.Build;
 import android.os.Handler;
+import android.os.IBinder;
 import android.os.Looper;
 import android.os.SystemClock;
 import android.util.AttributeSet;
@@ -587,7 +588,7 @@
                     mBackgroundControl = new SurfaceControl.Builder(mSurfaceSession)
                         .setName("Background for -" + name)
                         .setOpaque(true)
-                        .setColorLayer()
+                        .setColorLayer(true)
                         .setParent(mSurfaceControl)
                         .build();
 
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 519181d..992b996 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -16,6 +16,7 @@
 
 package android.view;
 
+import static android.content.res.Resources.ID_NULL;
 import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
 import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED;
 
@@ -3985,15 +3986,6 @@
     public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
 
     /**
-     * If a MotionEvent has CLASSIFICATION_AMBIGUOUS_GESTURE set, then certain the default
-     * long press action will be inhibited. However, to account for the possibility of incorrect
-     * classification, the default long press timeout will instead be increased for some situations
-     * by the following factor.
-     * Likewise, the touch slop for allowing long press will be increased when gesture is uncertain.
-     */
-    private static final int AMBIGUOUS_GESTURE_MULTIPLIER = 2;
-
-    /**
      * Controls the over-scroll mode for this view.
      * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
      * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
@@ -5052,6 +5044,9 @@
     @Nullable
     private WeakReference<ContentCaptureSession> mContentCaptureSession;
 
+    @LayoutRes
+    private int mSourceLayoutId = ID_NULL;
+
     /**
      * Simple constructor to use when creating a view from code.
      *
@@ -5217,6 +5212,8 @@
     public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
         this(context);
 
+        mSourceLayoutId = Resources.getAttributeSetSourceResId(attrs);
+
         final TypedArray a = context.obtainStyledAttributes(
                 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
 
@@ -14801,18 +14798,20 @@
                             motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
                     int touchSlop = mTouchSlop;
                     if (ambiguousGesture && hasPendingLongPressCallback()) {
+                        final float ambiguousMultiplier =
+                                ViewConfiguration.getAmbiguousGestureMultiplier();
                         if (!pointInView(x, y, touchSlop)) {
                             // The default action here is to cancel long press. But instead, we
                             // just extend the timeout here, in case the classification
                             // stays ambiguous.
                             removeLongPressCallback();
-                            long delay = ViewConfiguration.getLongPressTimeout()
-                                    * AMBIGUOUS_GESTURE_MULTIPLIER;
+                            long delay = (long) (ViewConfiguration.getLongPressTimeout()
+                                    * ambiguousMultiplier);
                             // Subtract the time already spent
                             delay -= event.getEventTime() - event.getDownTime();
                             checkForLongClick(delay, x, y);
                         }
-                        touchSlop *= AMBIGUOUS_GESTURE_MULTIPLIER;
+                        touchSlop *= ambiguousMultiplier;
                     }
 
                     // Be lenient about moving outside of buttons
@@ -23253,6 +23252,18 @@
     }
 
     /**
+     * A {@link View} can be inflated from an XML layout. For such Views this method returns the
+     * resource ID of the source layout.
+     *
+     * @return The layout resource id if this view was inflated from XML, otherwise
+     * {@link Resources#ID_NULL}.
+     */
+    @LayoutRes
+    public int getSourceLayoutResId() {
+        return mSourceLayoutId;
+    }
+
+    /**
      * Returns the top padding of this view.
      *
      * @return the top padding in pixels
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
index d03d97e..94d1b6d 100644
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -16,6 +16,7 @@
 
 package android.view;
 
+import android.annotation.FloatRange;
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.app.AppGlobals;
@@ -286,6 +287,11 @@
     private static final int HAS_PERMANENT_MENU_KEY_TRUE = 1;
     private static final int HAS_PERMANENT_MENU_KEY_FALSE = 2;
 
+    /**
+     * The multiplication factor for inhibiting default gestures.
+     */
+    private static final float AMBIGUOUS_GESTURE_MULTIPLIER = 2f;
+
     private final int mEdgeSlop;
     private final int mFadingEdgeLength;
     private final int mMinimumFlingVelocity;
@@ -911,6 +917,22 @@
     }
 
     /**
+     * If a MotionEvent has CLASSIFICATION_AMBIGUOUS_GESTURE set, then certain actions, such as
+     * scrolling, will be inhibited.
+     * However, to account for the possibility of incorrect classification,
+     * the default scrolling will only be inhibited if the pointer travels less than
+     * (getScaledTouchSlop() * this factor).
+     * Likewise, the default long press timeout will be increased by this factor for some situations
+     * where the default behaviour is to cancel it.
+     *
+     * @return The multiplication factor for inhibiting default gestures.
+     */
+    @FloatRange(from = 1.0)
+    public static float getAmbiguousGestureMultiplier() {
+        return AMBIGUOUS_GESTURE_MULTIPLIER;
+    }
+
+    /**
      * Report if the device has a permanent menu key available to the user.
      *
      * <p>As of Android 3.0, devices may not have a permanent menu key available.
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 9213f32..9a317db 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -2289,6 +2289,7 @@
                 surfaceChanged |= surfaceSizeChanged;
                 final boolean alwaysConsumeNavBarChanged =
                         mPendingAlwaysConsumeNavBar != mAttachInfo.mAlwaysConsumeNavBar;
+                final boolean colorModeChanged = hasColorModeChanged(lp.getColorMode());
                 if (contentInsetsChanged) {
                     mAttachInfo.mContentInsets.set(mPendingContentInsets);
                     if (DEBUG_LAYOUT) Log.v(mTag, "Content insets changing to: "
@@ -2335,6 +2336,10 @@
                     if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
                             + mAttachInfo.mVisibleInsets);
                 }
+                if (colorModeChanged && mAttachInfo.mThreadedRenderer != null) {
+                    mAttachInfo.mThreadedRenderer.setWideGamut(
+                            lp.getColorMode() == ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT);
+                }
 
                 if (!hadSurface) {
                     if (mSurface.isValid()) {
@@ -2387,7 +2392,7 @@
                         mAttachInfo.mThreadedRenderer.destroy();
                     }
                 } else if ((surfaceGenerationId != mSurface.getGenerationId()
-                        || surfaceSizeChanged || windowRelayoutWasForced)
+                        || surfaceSizeChanged || windowRelayoutWasForced || colorModeChanged)
                         && mSurfaceHolder == null
                         && mAttachInfo.mThreadedRenderer != null) {
                     mFullRedrawNeeded = true;
@@ -4009,6 +4014,20 @@
         }
     }
 
+    private boolean hasColorModeChanged(int colorMode) {
+        if (mAttachInfo.mThreadedRenderer == null) {
+            return false;
+        }
+        final boolean isWideGamut = colorMode == ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT;
+        if (mAttachInfo.mThreadedRenderer.isWideGamut() == isWideGamut) {
+            return false;
+        }
+        if (isWideGamut && !mContext.getResources().getConfiguration().isScreenWideColorGamut()) {
+            return false;
+        }
+        return true;
+    }
+
     @Override
     public void requestChildFocus(View child, View focused) {
         if (DEBUG_INPUT_RESIZE) {
diff --git a/core/java/android/view/contentcapture/ContentCaptureContext.java b/core/java/android/view/contentcapture/ContentCaptureContext.java
index 1928613..5814759 100644
--- a/core/java/android/view/contentcapture/ContentCaptureContext.java
+++ b/core/java/android/view/contentcapture/ContentCaptureContext.java
@@ -27,6 +27,7 @@
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.view.Display;
 import android.view.View;
 
 import com.android.internal.util.Preconditions;
@@ -90,8 +91,8 @@
     // Fields below are set by server when the session starts
     private final @Nullable ComponentName mComponentName;
     private final int mTaskId;
-    private final int mDisplayId;
     private final int mFlags;
+    private final int mDisplayId;
 
     // Fields below are set by the service upon "delivery" and are not marshalled in the parcel
     private @Nullable String mParentSessionId;
@@ -123,7 +124,8 @@
         mAction = builder.mAction;
 
         mComponentName  = null;
-        mTaskId = mFlags = mDisplayId = 0;
+        mTaskId = mFlags = 0;
+        mDisplayId = Display.INVALID_DISPLAY;
     }
 
     /**
diff --git a/core/java/android/view/contentcapture/ContentCaptureManager.java b/core/java/android/view/contentcapture/ContentCaptureManager.java
index fde0ced..f31856c 100644
--- a/core/java/android/view/contentcapture/ContentCaptureManager.java
+++ b/core/java/android/view/contentcapture/ContentCaptureManager.java
@@ -67,9 +67,6 @@
 
     private final Object mLock = new Object();
 
-    @GuardedBy("mLock")
-    private boolean mDisabled;
-
     @NonNull
     private final Context mContext;
 
@@ -115,8 +112,7 @@
     public MainContentCaptureSession getMainContentCaptureSession() {
         synchronized (mLock) {
             if (mMainSession == null) {
-                mMainSession = new MainContentCaptureSession(mContext, mHandler, mService,
-                        mDisabled);
+                mMainSession = new MainContentCaptureSession(mContext, this, mHandler, mService);
                 if (VERBOSE) Log.v(TAG, "getMainContentCaptureSession(): created " + mMainSession);
             }
             return mMainSession;
@@ -180,9 +176,17 @@
      * </ul>
      */
     public boolean isContentCaptureEnabled() {
+        if (mService == null) return false;
+
+        final MainContentCaptureSession mainSession;
         synchronized (mLock) {
-            return mService != null && !mDisabled;
+            mainSession = mMainSession;
         }
+        // The main session is only set when the activity starts, so we need to return true until
+        // then.
+        if (mainSession != null && mainSession.isDisabled()) return false;
+
+        return true;
     }
 
     /**
@@ -287,7 +291,8 @@
     public void dump(String prefix, PrintWriter pw) {
         synchronized (mLock) {
             pw.print(prefix); pw.println("ContentCaptureManager");
-            pw.print(prefix); pw.print("Disabled: "); pw.println(mDisabled);
+            pw.print(prefix); pw.print("isContentCaptureEnabled(): ");
+            pw.println(isContentCaptureEnabled());
             pw.print(prefix); pw.print("Context: "); pw.println(mContext);
             pw.print(prefix); pw.print("User: "); pw.println(mContext.getUserId());
             if (mService != null) {
diff --git a/core/java/android/view/contentcapture/MainContentCaptureSession.java b/core/java/android/view/contentcapture/MainContentCaptureSession.java
index 2eca51f..034c8fa 100644
--- a/core/java/android/view/contentcapture/MainContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/MainContentCaptureSession.java
@@ -89,21 +89,23 @@
      */
     public static final String EXTRA_BINDER = "binder";
 
-    // TODO(b/111276913): make sure disabled state is in sync with manager's disabled
     @NonNull
-    private final AtomicBoolean mDisabled;
+    private final AtomicBoolean mDisabled = new AtomicBoolean(false);
 
     @NonNull
     private final Context mContext;
 
     @NonNull
+    private final ContentCaptureManager mManager;
+
+    @NonNull
     private final Handler mHandler;
 
     /**
      * Interface to the system_server binder object - it's only used to start the session (and
      * notify when the session is finished).
      */
-    @Nullable
+    @Nullable // TODO(b/122959591): shoul never be null, we should make main session null instead
     private final IContentCaptureManager mSystemServerInterface;
 
     /**
@@ -136,13 +138,13 @@
     private final LocalLog mFlushHistory = new LocalLog(10);
 
     /** @hide */
-    protected MainContentCaptureSession(@NonNull Context context, @NonNull Handler handler,
-            @Nullable IContentCaptureManager systemServerInterface,
-            @NonNull boolean disabled) {
+    protected MainContentCaptureSession(@NonNull Context context,
+            @NonNull ContentCaptureManager manager, @NonNull Handler handler,
+            @Nullable IContentCaptureManager systemServerInterface) {
         mContext = context;
+        mManager = manager;
         mHandler = handler;
         mSystemServerInterface = systemServerInterface;
-        mDisabled = new AtomicBoolean(disabled);
     }
 
     @Override
@@ -235,8 +237,8 @@
 
     /**
      * Callback from {@code system_server} after call to
-     * {@link IContentCaptureManager#startSession(int, IBinder, ComponentName, String,
-     * int, IResultReceiver)}.
+     * {@link IContentCaptureManager#startSession(IBinder, ComponentName, String, int,
+     * IResultReceiver)}
      *
      * @param resultCode session state
      * @param binder handle to {@code IContentCaptureDirectManager}
@@ -517,8 +519,12 @@
 
     @Override
     boolean isContentCaptureEnabled() {
-        return super.isContentCaptureEnabled() && mSystemServerInterface != null
-                && !mDisabled.get();
+        return super.isContentCaptureEnabled() && mManager.isContentCaptureEnabled();
+    }
+
+    // Called by ContentCaptureManager.isContentCaptureEnabled
+    boolean isDisabled() {
+        return mDisabled.get();
     }
 
     // TODO(b/122454205): refactor "notifyXXXX" methods below to a common "Buffer" object that is
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index c38566b..bb9bd52 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -4489,6 +4489,13 @@
         // when selecting text when the handles jump to the end / start of words which may be on
         // a different line.
         protected int mPreviousLineTouched = UNSET_LINE;
+        // The raw x coordinate of the motion down event which started the current dragging session.
+        // Only used and stored when magnifier is used.
+        private float mCurrentDragInitialTouchRawX = UNSET_X_VALUE;
+        // The scale transform applied by containers to the TextView. Only used and computed
+        // when magnifier is used.
+        private float mTextViewScaleX;
+        private float mTextViewScaleY;
 
         private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
             super(mTextView.getContext());
@@ -4808,25 +4815,44 @@
                             / mMagnifierAnimator.mMagnifier.getZoom());
             final Paint.FontMetrics fontMetrics = mTextView.getPaint().getFontMetrics();
             final float glyphHeight = fontMetrics.descent - fontMetrics.ascent;
-            return glyphHeight > magnifierContentHeight;
+            return glyphHeight * mTextViewScaleY > magnifierContentHeight;
         }
 
-        private boolean viewIsMatrixTransformed() {
+        /**
+         * Traverses the hierarchy above the text view, and computes the total scale applied
+         * to it. If a rotation is encountered, the method returns {@code false}, indicating
+         * that the magnifier should not be shown anyways. It would be nice to keep these two
+         * pieces of logic separate (the rotation check and the total scale calculation),
+         * but for efficiency we can do them in a single go.
+         * @return whether the text view is rotated
+         */
+        private boolean checkForTransforms() {
             if (mMagnifierAnimator.mMagnifierIsShowing) {
                 // Do not check again when the magnifier is currently showing.
-                return false;
-            }
-            if (!mTextView.hasIdentityMatrix()) {
                 return true;
             }
+
+            if (mTextView.getRotation() != 0f || mTextView.getRotationX() != 0f
+                    || mTextView.getRotationY() != 0f) {
+                return false;
+            }
+            mTextViewScaleX = mTextView.getScaleX();
+            mTextViewScaleY = mTextView.getScaleY();
+
             ViewParent viewParent = mTextView.getParent();
             while (viewParent != null) {
-                if (viewParent instanceof View && !((View) viewParent).hasIdentityMatrix()) {
-                    return true;
+                if (viewParent instanceof View) {
+                    final View view = (View) viewParent;
+                    if (view.getRotation() != 0f || view.getRotationX() != 0f
+                            || view.getRotationY() != 0f) {
+                        return false;
+                    }
+                    mTextViewScaleX *= view.getScaleX();
+                    mTextViewScaleY *= view.getScaleY();
                 }
                 viewParent = viewParent.getParent();
             }
-            return false;
+            return true;
         }
 
         /**
@@ -4864,6 +4890,12 @@
                 return false;
             }
 
+            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
+                mCurrentDragInitialTouchRawX = event.getRawX();
+            } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
+                mCurrentDragInitialTouchRawX = UNSET_X_VALUE;
+            }
+
             final Layout layout = mTextView.getLayout();
             final int lineNumber = layout.getLineForOffset(offset);
             // Compute whether the selection handles are currently on the same line, and,
@@ -4891,6 +4923,8 @@
             } else {
                 rightBound += mTextView.getLayout().getLineRight(lineNumber);
             }
+            leftBound *= mTextViewScaleX;
+            rightBound *= mTextViewScaleX;
             final float contentWidth = Math.round(mMagnifierAnimator.mMagnifier.getWidth()
                     / mMagnifierAnimator.mMagnifier.getZoom());
             if (touchXInView < leftBound - contentWidth / 2
@@ -4898,13 +4932,27 @@
                 // The touch is too far from the current line / selection, so hide the magnifier.
                 return false;
             }
-            showPosInView.x = Math.max(leftBound, Math.min(rightBound, touchXInView));
+
+            final float scaledTouchXInView;
+            if (mTextViewScaleX == 1f) {
+                // In the common case, do not use mCurrentDragInitialTouchRawX to compute this
+                // coordinate, although the formula on the else branch should be equivalent.
+                // Since the formula relies on mCurrentDragInitialTouchRawX being set on
+                // MotionEvent.ACTION_DOWN, this makes us more defensive against cases when
+                // the sequence of events might not look as expected: for example, a sequence of
+                // ACTION_MOVE not preceded by ACTION_DOWN.
+                scaledTouchXInView = touchXInView;
+            } else {
+                scaledTouchXInView = (event.getRawX() - mCurrentDragInitialTouchRawX)
+                        * mTextViewScaleX + mCurrentDragInitialTouchRawX
+                        - textViewLocationOnScreen[0];
+            }
+            showPosInView.x = Math.max(leftBound, Math.min(rightBound, scaledTouchXInView));
 
             // Vertically snap to middle of current line.
-            showPosInView.y = (mTextView.getLayout().getLineTop(lineNumber)
+            showPosInView.y = ((mTextView.getLayout().getLineTop(lineNumber)
                     + mTextView.getLayout().getLineBottom(lineNumber)) / 2.0f
-                    + mTextView.getTotalPaddingTop() - mTextView.getScrollY();
-
+                    + mTextView.getTotalPaddingTop() - mTextView.getScrollY()) * mTextViewScaleY;
             return true;
         }
 
@@ -4956,8 +5004,8 @@
             }
 
             final PointF showPosInView = new PointF();
-            final boolean shouldShow = !tooLargeTextForMagnifier()
-                    && !viewIsMatrixTransformed()
+            final boolean shouldShow = checkForTransforms() /*check not rotated and compute scale*/
+                    && !tooLargeTextForMagnifier()
                     && obtainMagnifierShowCoordinates(event, showPosInView);
             if (shouldShow) {
                 // Make the cursor visible and stop blinking.
@@ -5973,6 +6021,9 @@
                     }
 
                     updateSelection(event);
+                    if (mTextView.hasSelection() && mEndHandle != null) {
+                        mEndHandle.updateMagnifier(event);
+                    }
                     break;
 
                 case MotionEvent.ACTION_UP:
@@ -5980,6 +6031,9 @@
                         break;
                     }
                     updateSelection(event);
+                    if (mEndHandle != null) {
+                        mEndHandle.dismissMagnifier();
+                    }
 
                     // No longer dragging to select text, let the parent intercept events.
                     mTextView.getParent().requestDisallowInterceptTouchEvent(false);
diff --git a/core/java/android/widget/Magnifier.java b/core/java/android/widget/Magnifier.java
index 5147306..d5b1a3d 100644
--- a/core/java/android/widget/Magnifier.java
+++ b/core/java/android/widget/Magnifier.java
@@ -579,24 +579,11 @@
             zoomCenterY = Math.round(yPosInView + mViewCoordinatesInSurface[1]);
         }
 
-        final Rect[] bounds = new Rect[3]; // [MAX_IN_SURFACE, MAX_IN_VIEW, MAX_VISIBLE]
+        final Rect[] bounds = new Rect[2]; // [MAX_IN_SURFACE, MAX_VISIBLE]
         // Obtain the surface bounds rectangle.
         final Rect surfaceBounds = new Rect(0, 0,
                 mContentCopySurface.mWidth, mContentCopySurface.mHeight);
         bounds[0] = surfaceBounds;
-        // Obtain the view bounds rectangle.
-        final Rect viewBounds;
-        if (mView instanceof SurfaceView) {
-            viewBounds = new Rect(0, 0, mContentCopySurface.mWidth, mContentCopySurface.mHeight);
-        } else {
-            viewBounds = new Rect(
-                    mViewCoordinatesInSurface[0],
-                    mViewCoordinatesInSurface[1],
-                    mViewCoordinatesInSurface[0] + mView.getWidth(),
-                    mViewCoordinatesInSurface[1] + mView.getHeight()
-            );
-        }
-        bounds[1] = viewBounds;
         // Obtain the visible view region rectangle.
         final Rect viewVisibleRegion = new Rect();
         mView.getGlobalVisibleRect(viewVisibleRegion);
@@ -609,7 +596,7 @@
             // If we copy content from a SurfaceView, clamp coordinates relative to it.
             viewVisibleRegion.offset(-mViewCoordinatesInSurface[0], -mViewCoordinatesInSurface[1]);
         }
-        bounds[2] = viewVisibleRegion;
+        bounds[1] = viewVisibleRegion;
 
         // Aggregate the above to obtain the bounds where the content copy will be restricted.
         int resolvedLeft = Integer.MIN_VALUE;
@@ -1301,11 +1288,6 @@
          *   {@link android.view.View#getGlobalVisibleRect(Rect)}. For example, this will take into
          *   account the case when the view is contained in a scrollable container, and the
          *   magnifier will refuse to copy content outside of the visible view region</li>
-         *   <li>{@link #SOURCE_BOUND_MAX_IN_VIEW}, which extends the bound as much as possible
-         *   while remaining in the bounds of the view. Note that, although this option is
-         *   used, the magnifier will always only display content visible on the screen: if the
-         *   view lays outside the screen or is covered by a different view either partially or
-         *   totally, the magnifier will not show any view region not visible on the screen.</li>
          *   <li>{@link #SOURCE_BOUND_MAX_IN_SURFACE}, which extends the bound as much
          *   as possible while remaining inside the surface the content is copied from.</li>
          * </ul>
@@ -1349,21 +1331,14 @@
      * A source bound that will extend as much as possible, while remaining within the surface
      * the content is copied from.
      */
-
     public static final int SOURCE_BOUND_MAX_IN_SURFACE = 0;
-    /**
-     * A source bound that will extend as much as possible, while remaining within the
-     * magnified view.
-     */
-
-    public static final int SOURCE_BOUND_MAX_IN_VIEW = 1;
 
     /**
      * A source bound that will extend as much as possible, while remaining within the
      * visible region of the magnified view, as determined by
      * {@link View#getGlobalVisibleRect(Rect)}.
      */
-    public static final int SOURCE_BOUND_MAX_VISIBLE = 2;
+    public static final int SOURCE_BOUND_MAX_VISIBLE = 1;
 
 
     /**
@@ -1373,7 +1348,7 @@
      *
      * @hide
      */
-    @IntDef({SOURCE_BOUND_MAX_IN_SURFACE, SOURCE_BOUND_MAX_IN_VIEW, SOURCE_BOUND_MAX_VISIBLE})
+    @IntDef({SOURCE_BOUND_MAX_IN_SURFACE, SOURCE_BOUND_MAX_VISIBLE})
     @Retention(RetentionPolicy.SOURCE)
     public @interface SourceBound {}
 
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 46f42f7..cfe2939 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -25,6 +25,7 @@
 import android.app.prediction.AppTargetEvent;
 import android.app.prediction.AppTargetId;
 import android.content.ClipData;
+import android.content.ClipboardManager;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -80,11 +81,13 @@
 import android.view.ViewGroup.LayoutParams;
 import android.widget.AbsListView;
 import android.widget.BaseAdapter;
+import android.widget.Button;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.ListView;
 import android.widget.Space;
 import android.widget.TextView;
+import android.widget.Toast;
 
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
@@ -350,6 +353,50 @@
         super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
                 null, false);
 
+        Button copyButton = findViewById(R.id.copy_button);
+        copyButton.setOnClickListener(view -> {
+            Intent targetIntent = getTargetIntent();
+            if (targetIntent == null) {
+                finish();
+            } else {
+                final String action = targetIntent.getAction();
+
+                ClipData clipData = null;
+                if (Intent.ACTION_SEND.equals(action)) {
+                    String extraText = targetIntent.getStringExtra(Intent.EXTRA_TEXT);
+                    Uri extraStream = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
+
+                    if (extraText != null) {
+                        clipData = ClipData.newPlainText(null, extraText);
+                    } else if (extraStream != null) {
+                        clipData = ClipData.newUri(getContentResolver(), null, extraStream);
+                    } else {
+                        Log.w(TAG, "No data available to copy to clipboard");
+                        return;
+                    }
+                } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
+                    final ArrayList<Uri> streams = targetIntent.getParcelableArrayListExtra(
+                            Intent.EXTRA_STREAM);
+                    clipData = ClipData.newUri(getContentResolver(), null, streams.get(0));
+                    for (int i = 1; i < streams.size(); i++) {
+                        clipData.addItem(getContentResolver(), new ClipData.Item(streams.get(i)));
+                    }
+                } else {
+                    // expected to only be visible with ACTION_SEND or ACTION_SEND_MULTIPLE
+                    // so warn about unexpected action
+                    Log.w(TAG, "Action (" + action + ") not supported for copying to clipboard");
+                    return;
+                }
+
+                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(
+                        Context.CLIPBOARD_SERVICE);
+                clipboardManager.setPrimaryClip(clipData);
+                Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_SHORT).show();
+
+                finish();
+            }
+        });
+
         MetricsLogger.action(this, MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN);
 
         mChooserShownTime = System.currentTimeMillis();
@@ -414,39 +461,39 @@
     private void showDefaultContentPreview(final ViewGroup parentLayout,
             final Intent targetIntent) {
         CharSequence sharingText = targetIntent.getCharSequenceExtra(Intent.EXTRA_TEXT);
-        TextView previewTextView = findViewById(R.id.content_preview_text);
         if (sharingText == null) {
-            previewTextView.setVisibility(View.GONE);
+            findViewById(R.id.content_preview_text_layout).setVisibility(View.GONE);
         } else {
-            previewTextView.setText(sharingText);
+            TextView textView = findViewById(R.id.content_preview_text);
+            textView.setText(sharingText);
         }
 
         String previewTitle = targetIntent.getStringExtra(Intent.EXTRA_TITLE);
-        TextView previewTitleView = findViewById(R.id.content_preview_title);
-        if (previewTitle == null) {
-            previewTitleView.setVisibility(View.GONE);
+        if (previewTitle == null || previewTitle.trim().isEmpty()) {
+            findViewById(R.id.content_preview_title_layout).setVisibility(View.GONE);
         } else {
+            TextView previewTitleView = findViewById(R.id.content_preview_title);
             previewTitleView.setText(previewTitle);
-        }
 
-        ClipData previewData = targetIntent.getClipData();
-        Uri previewThumbnail = null;
-        if (previewData != null) {
-            if (previewData.getItemCount() > 0) {
-                ClipData.Item previewDataItem = previewData.getItemAt(0);
-                previewThumbnail = previewDataItem.getUri();
+            ClipData previewData = targetIntent.getClipData();
+            Uri previewThumbnail = null;
+            if (previewData != null) {
+                if (previewData.getItemCount() > 0) {
+                    ClipData.Item previewDataItem = previewData.getItemAt(0);
+                    previewThumbnail = previewDataItem.getUri();
+                }
             }
-        }
 
-        ImageView previewThumbnailView = findViewById(R.id.content_preview_thumbnail);
-        if (previewThumbnail == null) {
-            previewThumbnailView.setVisibility(View.GONE);
-        } else {
-            Bitmap bmp = loadThumbnail(previewThumbnail, new Size(200, 200));
-            if (bmp == null) {
+            ImageView previewThumbnailView = findViewById(R.id.content_preview_thumbnail);
+            if (previewThumbnail == null) {
                 previewThumbnailView.setVisibility(View.GONE);
             } else {
-                previewThumbnailView.setImageBitmap(bmp);
+                Bitmap bmp = loadThumbnail(previewThumbnail, new Size(100, 100));
+                if (bmp == null) {
+                    previewThumbnailView.setVisibility(View.GONE);
+                } else {
+                    previewThumbnailView.setImageBitmap(bmp);
+                }
             }
         }
     }
@@ -2020,8 +2067,8 @@
         private void updatePath(int width, int height) {
             mPath.reset();
 
-            int imageWidth = width - getPaddingLeft() - getPaddingRight();
-            int imageHeight = height - getPaddingTop() - getPaddingBottom();
+            int imageWidth = width - getPaddingRight();
+            int imageHeight = height - getPaddingBottom();
             mPath.addRoundRect(getPaddingLeft(), getPaddingTop(), imageWidth, imageHeight, mRadius,
                     mRadius, Path.Direction.CW);
         }
diff --git a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
index b85488f..8dde44e 100644
--- a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
+++ b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
@@ -155,15 +155,15 @@
     /**
      * Sets the transcribed voice to the given string.
      */
-    void setTranscription(String transcription);
+    void setTranscription(IVoiceInteractionService service, String transcription);
 
     /**
      * Indicates that the transcription session is finished.
      */
-    void clearTranscription(boolean immediate);
+    void clearTranscription(IVoiceInteractionService service, boolean immediate);
 
     /**
      * Sets the voice state indication based upon the given value.
      */
-    void setVoiceState(int state);
+    void setVoiceState(IVoiceInteractionService service, int state);
 }
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReader.java b/core/java/com/android/internal/os/KernelCpuThreadReader.java
index 2742b7c..b1328e8 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReader.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReader.java
@@ -37,9 +37,10 @@
  * frequency band.
  *
  * <p>Frequencies are bucketed together to reduce the amount of data created. This means that we
- * return {@link #NUM_BUCKETS} frequencies instead of the full number. Frequencies are reported as
- * the lowest frequency in that range. Frequencies are spread as evenly as possible across the
- * buckets. The buckets do not cross over the little/big frequencies reported.
+ * return less frequencies than provided by {@link ProcTimeInStateReader}. The number of
+ * frequencies is configurable by {@link #setNumBuckets}. Frequencies are reported as the lowest
+ * frequency in that range. Frequencies are spread as evenly as possible across the buckets. The
+ * buckets do not cross over the little/big frequencies reported.
  *
  * <p>N.B.: In order to bucket across little/big frequencies correctly, we assume that the {@code
  * time_in_state} file contains every little core frequency in ascending order, followed by every
@@ -97,22 +98,17 @@
             DEFAULT_PROC_PATH.resolve("self/time_in_state");
 
     /**
-     * Number of frequency buckets
-     */
-    private static final int NUM_BUCKETS = 8;
-
-    /**
-     * Default predicate for what UIDs to check for when getting processes. This filters to only
-     * select UID 1000 (the {@code system} user)
-     */
-    private static final Predicate<Integer> DEFAULT_UID_PREDICATE = uid -> uid == 1000;
-
-    /**
      * Value returned when there was an error getting an integer ID value (e.g. PID, UID)
      */
     private static final int ID_ERROR = -1;
 
     /**
+     * When checking whether to report data for a thread, we check the UID of the thread's owner
+     * against this predicate
+     */
+    private Predicate<Integer> mUidPredicate;
+
+    /**
      * Where the proc filesystem is mounted
      */
     private final Path mProcPath;
@@ -121,7 +117,7 @@
      * Frequencies read from the {@code time_in_state} file. Read from {@link
      * #mProcTimeInStateReader#getCpuFrequenciesKhz()} and cast to {@code int[]}
      */
-    private final int[] mFrequenciesKhz;
+    private int[] mFrequenciesKhz;
 
     /**
      * Used to read and parse {@code time_in_state} files
@@ -131,17 +127,10 @@
     /**
      * Used to sort frequencies and usage times into buckets
      */
-    private final FrequencyBucketCreator mFrequencyBucketCreator;
+    private FrequencyBucketCreator mFrequencyBucketCreator;
 
     private final Injector mInjector;
 
-    private KernelCpuThreadReader() throws IOException {
-        this(
-                DEFAULT_PROC_PATH,
-                DEFAULT_INITIAL_TIME_IN_STATE_PATH,
-                new Injector());
-    }
-
     /**
      * Create with a path where `proc` is mounted. Used primarily for testing
      *
@@ -151,17 +140,16 @@
      */
     @VisibleForTesting
     public KernelCpuThreadReader(
+            int numBuckets,
+            Predicate<Integer> uidPredicate,
             Path procPath,
             Path initialTimeInStatePath,
             Injector injector) throws IOException {
+        mUidPredicate = uidPredicate;
         mProcPath = procPath;
         mProcTimeInStateReader = new ProcTimeInStateReader(initialTimeInStatePath);
         mInjector = injector;
-
-        // Copy mProcTimeInState's frequencies and initialize bucketing
-        final long[] frequenciesKhz = mProcTimeInStateReader.getFrequenciesKhz();
-        mFrequencyBucketCreator = new FrequencyBucketCreator(frequenciesKhz, NUM_BUCKETS);
-        mFrequenciesKhz = mFrequencyBucketCreator.getBucketMinFrequencies(frequenciesKhz);
+        setNumBuckets(numBuckets);
     }
 
     /**
@@ -170,9 +158,14 @@
      * @return the reader, null if an exception was thrown during creation
      */
     @Nullable
-    public static KernelCpuThreadReader create() {
+    public static KernelCpuThreadReader create(int numBuckets, Predicate<Integer> uidPredicate) {
         try {
-            return new KernelCpuThreadReader();
+            return new KernelCpuThreadReader(
+                    numBuckets,
+                    uidPredicate,
+                    DEFAULT_PROC_PATH,
+                    DEFAULT_INITIAL_TIME_IN_STATE_PATH,
+                    new Injector());
         } catch (IOException e) {
             Slog.e(TAG, "Failed to initialize KernelCpuThreadReader", e);
             return null;
@@ -180,14 +173,6 @@
     }
 
     /**
-     * Get the per-thread CPU usage of all processes belonging to UIDs between {@code [1000, 2000)}
-     */
-    @Nullable
-    public ArrayList<ProcessCpuUsage> getProcessCpuUsageByUids() {
-        return getProcessCpuUsageByUids(DEFAULT_UID_PREDICATE);
-    }
-
-    /**
      * Get the per-thread CPU usage of all processes belonging to a set of UIDs
      *
      * <p>This function will crawl through all process {@code proc} directories found by the pattern
@@ -195,10 +180,11 @@
      * approximately 500ms on a Pixel 2. Therefore, this method can be computationally expensive,
      * and should not be called more than once an hour.
      *
-     * @param uidPredicate only get usage from processes owned by UIDs that match this predicate
+     * <p>Data is only collected for UIDs passing the predicate supplied in {@link
+     * #setUidPredicate}.
      */
     @Nullable
-    public ArrayList<ProcessCpuUsage> getProcessCpuUsageByUids(Predicate<Integer> uidPredicate) {
+    public ArrayList<ProcessCpuUsage> getProcessCpuUsageByUids() {
         if (DEBUG) {
             Slog.d(TAG, "Reading CPU thread usages for processes owned by UIDs");
         }
@@ -213,7 +199,7 @@
                 if (uid == ID_ERROR || processId == ID_ERROR) {
                     continue;
                 }
-                if (!uidPredicate.test(uid)) {
+                if (!mUidPredicate.test(uid)) {
                     continue;
                 }
 
@@ -247,10 +233,7 @@
      */
     @Nullable
     public ProcessCpuUsage getCurrentProcessCpuUsage() {
-        return getProcessCpuUsage(
-                mProcPath.resolve("self"),
-                mInjector.myPid(),
-                mInjector.myUid());
+        return getProcessCpuUsage(mProcPath.resolve("self"), mInjector.myPid(), mInjector.myUid());
     }
 
     /**
@@ -300,6 +283,31 @@
     }
 
     /**
+     * Set the number of frequency buckets to use
+     */
+    void setNumBuckets(int numBuckets) {
+        if (numBuckets < 1) {
+            Slog.w(TAG, "Number of buckets must be at least 1, but was " + numBuckets);
+            return;
+        }
+        // If `numBuckets` hasn't changed since the last set, do nothing
+        if (mFrequenciesKhz != null && mFrequenciesKhz.length == numBuckets) {
+            return;
+        }
+        mFrequencyBucketCreator = new FrequencyBucketCreator(
+                mProcTimeInStateReader.getFrequenciesKhz(), numBuckets);
+        mFrequenciesKhz = mFrequencyBucketCreator.getBucketMinFrequencies(
+                mProcTimeInStateReader.getFrequenciesKhz());
+    }
+
+    /**
+     * Set the UID predicate for {@link #getProcessCpuUsageByUids}
+     */
+    void setUidPredicate(Predicate<Integer> uidPredicate) {
+        mUidPredicate = uidPredicate;
+    }
+
+    /**
      * Get the CPU frequencies that correspond to the times reported in
      * {@link ThreadCpuUsage#usageTimesMillis}
      */
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
new file mode 100644
index 0000000..77f6a17
--- /dev/null
+++ b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2018 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.os;
+
+import android.annotation.Nullable;
+import android.content.Context;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.UserHandle;
+import android.provider.Settings;
+import android.util.KeyValueListParser;
+import android.util.Range;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Service that handles settings for {@link KernelCpuThreadReader}
+ *
+ * <p>N.B.: The `collected_uids` setting takes a string representation of what UIDs to collect data
+ * for. A string representation is used as we will want to express UID ranges, therefore an integer
+ * array could not be used. The format of the string representation is detailed here: {@link
+ * UidPredicate#fromString}.
+ *
+ * @hide Only for use within the system server
+ */
+public class KernelCpuThreadReaderSettingsObserver extends ContentObserver {
+    private static final String TAG = "KernelCpuThreadReaderSettingsObserver";
+
+    /**
+     * The number of frequency buckets to report
+     */
+    private static final String NUM_BUCKETS_SETTINGS_KEY = "num_buckets";
+    private static final int NUM_BUCKETS_DEFAULT = 8;
+
+    /**
+     * List of UIDs to report data for
+     */
+    private static final String COLLECTED_UIDS_SETTINGS_KEY = "collected_uids";
+    private static final String COLLECTED_UIDS_DEFAULT = "1000-1000";
+
+    private final Context mContext;
+
+    @Nullable
+    private final KernelCpuThreadReader mKernelCpuThreadReader;
+
+    /**
+     * @return returns a created {@link KernelCpuThreadReader} that will be modified by any
+     * change in settings, returns null if creation failed
+     */
+    @Nullable
+    public static KernelCpuThreadReader getSettingsModifiedReader(Context context) {
+        // Create the observer
+        KernelCpuThreadReaderSettingsObserver settingsObserver =
+                new KernelCpuThreadReaderSettingsObserver(context);
+        // Register the observer to listen for setting changes
+        Uri settingsUri =
+                Settings.Global.getUriFor(Settings.Global.KERNEL_CPU_THREAD_READER);
+        context.getContentResolver().registerContentObserver(
+                settingsUri, false, settingsObserver, UserHandle.USER_SYSTEM);
+        // Return the observer's reader
+        return settingsObserver.mKernelCpuThreadReader;
+    }
+
+    private KernelCpuThreadReaderSettingsObserver(Context context) {
+        super(BackgroundThread.getHandler());
+        mContext = context;
+        mKernelCpuThreadReader = KernelCpuThreadReader.create(
+                NUM_BUCKETS_DEFAULT,
+                UidPredicate.fromString(COLLECTED_UIDS_DEFAULT));
+    }
+
+    @Override
+    public void onChange(boolean selfChange, Uri uri, int userId) {
+        updateReader();
+    }
+
+    /**
+     * Update the reader with new settings
+     */
+    private void updateReader() {
+        if (mKernelCpuThreadReader == null) {
+            return;
+        }
+
+        final KeyValueListParser parser = new KeyValueListParser(',');
+        try {
+            parser.setString(Settings.Global.getString(
+                    mContext.getContentResolver(), Settings.Global.KERNEL_CPU_THREAD_READER));
+        } catch (IllegalArgumentException e) {
+            Slog.e(TAG, "Bad settings", e);
+            return;
+        }
+
+        final UidPredicate uidPredicate;
+        try {
+            uidPredicate = UidPredicate.fromString(
+                    parser.getString(COLLECTED_UIDS_SETTINGS_KEY, COLLECTED_UIDS_DEFAULT));
+        } catch (NumberFormatException e) {
+            Slog.w(TAG, "Failed to get UID predicate", e);
+            return;
+        }
+
+        mKernelCpuThreadReader.setNumBuckets(
+                parser.getInt(NUM_BUCKETS_SETTINGS_KEY, NUM_BUCKETS_DEFAULT));
+        mKernelCpuThreadReader.setUidPredicate(uidPredicate);
+    }
+
+    /**
+     * Check whether a UID belongs to a set of UIDs
+     */
+    @VisibleForTesting
+    public static class UidPredicate implements Predicate<Integer> {
+        private static final Pattern UID_RANGE_PATTERN = Pattern.compile("([0-9]+)-([0-9]+)");
+        private static final String UID_SPECIFIER_DELIMITER = ";";
+        private final List<Range<Integer>> mAcceptedUidRanges;
+
+        /**
+         * Create a UID predicate from a string representing a list of UID ranges
+         *
+         * <p>UID ranges are a pair of integers separated by a '-'. If you want to specify a single
+         * UID (e.g. UID 1000), you can use {@code 1000-1000}. Lists of ranges are separated by
+         * a single ';'. For example, this would be a valid string representation: {@code
+         * "1000-1999;2003-2003;2004-2004;2050-2060"}.
+         *
+         * <p>We do not use ',' to delimit as it is already used in separating different setting
+         * arguments.
+         *
+         * @throws NumberFormatException    if the input string is incorrectly formatted
+         * @throws IllegalArgumentException if an UID range has a lower end than start
+         */
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+        public static UidPredicate fromString(String predicateString) throws NumberFormatException {
+            final List<Range<Integer>> acceptedUidRanges = new ArrayList<>();
+            for (String uidSpecifier : predicateString.split(UID_SPECIFIER_DELIMITER)) {
+                final Matcher uidRangeMatcher = UID_RANGE_PATTERN.matcher(uidSpecifier);
+                if (!uidRangeMatcher.matches()) {
+                    throw new NumberFormatException(
+                            "Failed to recognize as number range: " + uidSpecifier);
+                }
+                acceptedUidRanges.add(Range.create(
+                        Integer.parseInt(uidRangeMatcher.group(1)),
+                        Integer.parseInt(uidRangeMatcher.group(2))));
+            }
+            return new UidPredicate(acceptedUidRanges);
+        }
+
+        private UidPredicate(List<Range<Integer>> acceptedUidRanges) {
+            mAcceptedUidRanges = acceptedUidRanges;
+        }
+
+        @Override
+        public boolean test(Integer uid) {
+            for (int i = 0; i < mAcceptedUidRanges.size(); i++) {
+                if (mAcceptedUidRanges.get(i).contains(uid)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+}
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 474d4d7..b881aef 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -94,6 +94,11 @@
      */
     public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
 
+    /**
+     * Enable profiling from shell.
+     */
+    public static final int PROFILE_FROM_SHELL = 1 << 15;
+
     /** No external storage should be mounted. */
     public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
     /** Default external storage should be mounted. */
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 51a3b48..e7a1c49 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -27,10 +27,6 @@
         "-Wno-error=deprecated-declarations",
         "-Wunused",
         "-Wunreachable-code",
-
-        // TODO: Linear blending should be enabled by default, but we are
-        // TODO: making it an opt-in while it's a work in progress
-        //"-DANDROID_ENABLE_LINEAR_BLENDING",
     ],
 
     cppflags: ["-Wno-conversion-null"],
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index d215f96..e817217 100755
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -1149,19 +1149,6 @@
     return createBitmap(env, bitmap.release(), getPremulBitmapCreateFlags(false));
 }
 
-static jobject Bitmap_createHardwareBitmap(JNIEnv* env, jobject, jobject graphicBuffer) {
-    sp<GraphicBuffer> buffer(graphicBufferForJavaObject(env, graphicBuffer));
-    // To support any color space, we need to pass an additional ColorSpace argument to
-    // java Bitmap.createHardwareBitmap.
-    SkColorType ct = uirenderer::PixelFormatToColorType(buffer->getPixelFormat());
-    sk_sp<Bitmap> bitmap = Bitmap::createFrom(buffer, ct, SkColorSpace::MakeSRGB());
-    if (!bitmap.get()) {
-        ALOGW("failed to create hardware bitmap from graphic buffer");
-        return NULL;
-    }
-    return bitmap::createBitmap(env, bitmap.release(), getPremulBitmapCreateFlags(false));
-}
-
 static jobject Bitmap_wrapHardwareBufferBitmap(JNIEnv* env, jobject, jobject hardwareBuffer,
                                                jlong colorSpacePtr) {
     AHardwareBuffer* hwBuf = android_hardware_HardwareBuffer_getNativeHardwareBuffer(env,
@@ -1257,8 +1244,6 @@
     {   "nativeGetAllocationByteCount", "(J)I", (void*)Bitmap_getAllocationByteCount },
     {   "nativeCopyPreserveInternalConfig", "(J)Landroid/graphics/Bitmap;",
         (void*)Bitmap_copyPreserveInternalConfig },
-    {   "nativeCreateHardwareBitmap", "(Landroid/graphics/GraphicBuffer;)Landroid/graphics/Bitmap;",
-        (void*) Bitmap_createHardwareBitmap },
     {   "nativeWrapHardwareBufferBitmap", "(Landroid/hardware/HardwareBuffer;J)Landroid/graphics/Bitmap;",
         (void*) Bitmap_wrapHardwareBufferBitmap },
     {   "nativeCreateGraphicBufferHandle", "(J)Landroid/graphics/GraphicBuffer;",
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 3f9ec45..79bfa17 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -15,6 +15,7 @@
 #include "Utils.h"
 #include "core_jni_helpers.h"
 
+#include <HardwareBitmapUploader.h>
 #include <nativehelper/JNIHelp.h>
 #include <androidfw/Asset.h>
 #include <androidfw/ResourceTypes.h>
@@ -278,6 +279,11 @@
 
     // Set the decode colorType
     SkColorType decodeColorType = codec->computeOutputColorType(prefColorType);
+    if (decodeColorType == kRGBA_F16_SkColorType && isHardware &&
+            !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
+        decodeColorType = kN32_SkColorType;
+    }
+
     sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(
             decodeColorType, prefColorSpace);
 
@@ -354,13 +360,7 @@
     const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(),
             decodeColorType, alphaType, decodeColorSpace);
 
-    // For wide gamut images, we will leave the color space on the SkBitmap.  Otherwise,
-    // use the default.
     SkImageInfo bitmapInfo = decodeInfo;
-    if (decodeInfo.colorSpace() && decodeInfo.colorSpace()->isSRGB()) {
-        bitmapInfo = bitmapInfo.makeColorSpace(decodeInfo.refColorSpace());
-    }
-
     if (decodeColorType == kGray_8_SkColorType) {
         // The legacy implementation of BitmapFactory used kAlpha8 for
         // grayscale images (before kGray8 existed).  While the codec
diff --git a/core/jni/android/graphics/BitmapRegionDecoder.cpp b/core/jni/android/graphics/BitmapRegionDecoder.cpp
index b4ba749..d65f324 100644
--- a/core/jni/android/graphics/BitmapRegionDecoder.cpp
+++ b/core/jni/android/graphics/BitmapRegionDecoder.cpp
@@ -33,6 +33,7 @@
 #include "android_util_Binder.h"
 #include "core_jni_helpers.h"
 
+#include <HardwareBitmapUploader.h>
 #include <nativehelper/JNIHelp.h>
 #include <androidfw/Asset.h>
 #include <binder/Parcel.h>
@@ -166,6 +167,10 @@
 
     SkBitmapRegionDecoder* brd = reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
     SkColorType decodeColorType = brd->computeOutputColorType(colorType);
+    if (decodeColorType == kRGBA_F16_SkColorType && isHardware &&
+            !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
+        decodeColorType = kN32_SkColorType;
+    }
 
     // Set up the pixel allocator
     SkBRDAllocator* allocator = nullptr;
diff --git a/core/jni/android/graphics/ImageDecoder.cpp b/core/jni/android/graphics/ImageDecoder.cpp
index 72e14e7..2d83ac3 100644
--- a/core/jni/android/graphics/ImageDecoder.cpp
+++ b/core/jni/android/graphics/ImageDecoder.cpp
@@ -24,6 +24,7 @@
 #include "core_jni_helpers.h"
 
 #include <hwui/Bitmap.h>
+#include <HardwareBitmapUploader.h>
 
 #include <SkAndroidCodec.h>
 #include <SkEncodedImageFormat.h>
@@ -256,6 +257,17 @@
         // This is currently the only way to know that we should decode to F16.
         colorType = codec->computeOutputColorType(colorType);
     }
+
+    const bool isHardware = !requireMutable
+        && (allocator == ImageDecoder::kDefault_Allocator ||
+            allocator == ImageDecoder::kHardware_Allocator)
+        && colorType != kGray_8_SkColorType;
+
+    if (colorType == kRGBA_F16_SkColorType && isHardware &&
+            !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
+        colorType = kN32_SkColorType;
+    }
+
     sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
     colorSpace = codec->computeOutputColorSpace(colorType, colorSpace);
     decodeInfo = decodeInfo.makeColorType(colorType).makeColorSpace(colorSpace);
@@ -449,10 +461,7 @@
     if (requireMutable) {
         bitmapCreateFlags |= bitmap::kBitmapCreateFlag_Mutable;
     } else {
-        if ((allocator == ImageDecoder::kDefault_Allocator ||
-             allocator == ImageDecoder::kHardware_Allocator)
-            && bm.colorType() != kAlpha_8_SkColorType)
-        {
+        if (isHardware) {
             sk_sp<Bitmap> hwBitmap = Bitmap::allocateHardwareBitmap(bm);
             if (hwBitmap) {
                 hwBitmap->setImmutable();
diff --git a/core/jni/android/graphics/Shader.cpp b/core/jni/android/graphics/Shader.cpp
index e741979..298f7f8 100644
--- a/core/jni/android/graphics/Shader.cpp
+++ b/core/jni/android/graphics/Shader.cpp
@@ -106,7 +106,7 @@
 
 static jlong LinearGradient_create(JNIEnv* env, jobject, jlong matrixPtr,
         jfloat x0, jfloat y0, jfloat x1, jfloat y1, jlongArray colorArray,
-        jfloatArray posArray, jint tileMode, long colorSpaceHandle) {
+        jfloatArray posArray, jint tileMode, jlong colorSpaceHandle) {
     SkPoint pts[2];
     pts[0].set(x0, y0);
     pts[1].set(x1, y1);
diff --git a/core/jni/android_hardware_HardwareBuffer.cpp b/core/jni/android_hardware_HardwareBuffer.cpp
index 2d1fec8..00e5ba3 100644
--- a/core/jni/android_hardware_HardwareBuffer.cpp
+++ b/core/jni/android_hardware_HardwareBuffer.cpp
@@ -21,6 +21,7 @@
 
 #include "android_os_Parcel.h"
 #include "android/graphics/GraphicsJNI.h"
+#include "android/graphics/GraphicBuffer.h"
 
 #include <android/hardware_buffer.h>
 #include <android_runtime/android_hardware_HardwareBuffer.h>
@@ -96,6 +97,12 @@
     return reinterpret_cast<jlong>(wrapper);
 }
 
+static jlong android_hardware_HardwareBuffer_createFromGraphicBuffer(JNIEnv* env, jobject clazz, jobject graphicBuffer) {
+    sp<GraphicBuffer> buffer(graphicBufferForJavaObject(env, graphicBuffer));
+    GraphicBufferWrapper* wrapper = new GraphicBufferWrapper(buffer);
+    return reinterpret_cast<jlong>(wrapper);
+}
+
 static void destroyWrapper(GraphicBufferWrapper* wrapper) {
     delete wrapper;
 }
@@ -243,6 +250,8 @@
 static const JNINativeMethod gMethods[] = {
     { "nCreateHardwareBuffer",  "(IIIIJ)J",
             (void*) android_hardware_HardwareBuffer_create },
+    { "nCreateFromGraphicBuffer", "(Landroid/graphics/GraphicBuffer;)J",
+            (void*) android_hardware_HardwareBuffer_createFromGraphicBuffer },
     { "nGetNativeFinalizer", "()J",
             (void*) android_hardware_HardwareBuffer_getNativeFinalizer },
     { "nWriteHardwareBufferToParcel",  "(JLandroid/os/Parcel;)V",
diff --git a/core/jni/android_hardware_input_InputApplicationHandle.cpp b/core/jni/android_hardware_input_InputApplicationHandle.cpp
index 1ab5843..b9301d4 100644
--- a/core/jni/android_hardware_input_InputApplicationHandle.cpp
+++ b/core/jni/android_hardware_input_InputApplicationHandle.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "InputApplicationHandle"
 
 #include <nativehelper/JNIHelp.h>
+#include "core_jni_helpers.h"
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/threads.h>
@@ -63,16 +64,7 @@
         mInfo = new InputApplicationInfo();
     }
 
-    jstring nameObj = jstring(env->GetObjectField(obj,
-            gInputApplicationHandleClassInfo.name));
-    if (nameObj) {
-        const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
-        mInfo->name = nameStr;
-        env->ReleaseStringUTFChars(nameObj, nameStr);
-        env->DeleteLocalRef(nameObj);
-    } else {
-        mInfo->name = "<null>";
-    }
+    mInfo->name = getStringField(env, obj, gInputApplicationHandleClassInfo.name, "<null>");
 
     mInfo->dispatchingTimeout = env->GetLongField(obj,
             gInputApplicationHandleClassInfo.dispatchingTimeoutNanos);
diff --git a/core/jni/android_hardware_input_InputWindowHandle.cpp b/core/jni/android_hardware_input_InputWindowHandle.cpp
index 67a7441..eb71052 100644
--- a/core/jni/android_hardware_input_InputWindowHandle.cpp
+++ b/core/jni/android_hardware_input_InputWindowHandle.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "InputWindowHandle"
 
 #include <nativehelper/JNIHelp.h>
+#include "core_jni_helpers.h"
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/threads.h>
@@ -86,24 +87,14 @@
 
     mInfo.touchableRegion.clear();
 
-    jobject tokenObj = env->GetObjectField(obj,
-            gInputWindowHandleClassInfo.token);
+    jobject tokenObj = env->GetObjectField(obj, gInputWindowHandleClassInfo.token);
     if (tokenObj) {
         mInfo.token = ibinderForJavaObject(env, tokenObj);
     } else {
         mInfo.token.clear();
     }
 
-    jstring nameObj = jstring(env->GetObjectField(obj,
-            gInputWindowHandleClassInfo.name));
-    if (nameObj) {
-        const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
-        mInfo.name = nameStr;
-        env->ReleaseStringUTFChars(nameObj, nameStr);
-        env->DeleteLocalRef(nameObj);
-    } else {
-        mInfo.name = "<null>";
-    }
+    mInfo.name = getStringField(env, obj, gInputWindowHandleClassInfo.name, "<null>");
 
     mInfo.layoutParamsFlags = env->GetIntField(obj,
             gInputWindowHandleClassInfo.layoutParamsFlags);
@@ -241,8 +232,7 @@
     GET_FIELD_ID(gInputWindowHandleClassInfo.ptr, clazz,
             "ptr", "J");
 
-    GET_FIELD_ID(gInputWindowHandleClassInfo.inputApplicationHandle,
-            clazz,
+    GET_FIELD_ID(gInputWindowHandleClassInfo.inputApplicationHandle, clazz,
             "inputApplicationHandle", "Landroid/view/InputApplicationHandle;");
 
     GET_FIELD_ID(gInputWindowHandleClassInfo.token, clazz,
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 34abcd8..a2ed7d3 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -621,6 +621,24 @@
 }
 
 static jint
+android_media_AudioSystem_setMasterBalance(JNIEnv *env, jobject thiz, jfloat balance)
+{
+    return (jint) check_AudioSystem_Command(AudioSystem::setMasterBalance(balance));
+}
+
+static jfloat
+android_media_AudioSystem_getMasterBalance(JNIEnv *env, jobject thiz)
+{
+    float balance;
+    const status_t status = AudioSystem::getMasterBalance(&balance);
+    if (status != NO_ERROR) {
+        ALOGW("%s getMasterBalance error %d, returning 0.f, audioserver down?", __func__, status);
+        balance = 0.f;
+    }
+    return balance;
+}
+
+static jint
 android_media_AudioSystem_getDevicesForStream(JNIEnv *env, jobject thiz, jint stream)
 {
     return (jint) AudioSystem::getDevicesForStream(static_cast <audio_stream_type_t>(stream));
@@ -2160,6 +2178,8 @@
     {"getMasterMute",       "()Z",      (void *)android_media_AudioSystem_getMasterMute},
     {"setMasterMono",       "(Z)I",     (void *)android_media_AudioSystem_setMasterMono},
     {"getMasterMono",       "()Z",      (void *)android_media_AudioSystem_getMasterMono},
+    {"setMasterBalance",    "(F)I",     (void *)android_media_AudioSystem_setMasterBalance},
+    {"getMasterBalance",    "()F",      (void *)android_media_AudioSystem_getMasterBalance},
     {"getDevicesForStream", "(I)I",     (void *)android_media_AudioSystem_getDevicesForStream},
     {"getPrimaryOutputSamplingRate", "()I", (void *)android_media_AudioSystem_getPrimaryOutputSamplingRate},
     {"getPrimaryOutputFrameCount",   "()I", (void *)android_media_AudioSystem_getPrimaryOutputFrameCount},
diff --git a/core/jni/android_util_XmlBlock.cpp b/core/jni/android_util_XmlBlock.cpp
index ad6bad2..1dc6834 100644
--- a/core/jni/android_util_XmlBlock.cpp
+++ b/core/jni/android_util_XmlBlock.cpp
@@ -72,7 +72,7 @@
 }
 
 static jlong android_content_XmlBlock_nativeCreateParseState(JNIEnv* env, jobject clazz,
-                                                          jlong token)
+                                                          jlong token, jint res_id)
 {
     ResXMLTree* osb = reinterpret_cast<ResXMLTree*>(token);
     if (osb == NULL) {
@@ -81,6 +81,7 @@
     }
 
     ResXMLParser* st = new ResXMLParser(*osb);
+    st->setSourceResourceId(res_id);
     if (st == NULL) {
         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
         return 0;
@@ -335,6 +336,17 @@
         ? value.data : 0;
 }
 
+static jint android_content_XmlBlock_nativeGetSourceResId(JNIEnv* env, jobject clazz,
+                                                          jlong token)
+{
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
+    if (st == NULL) {
+        return 0;
+    } else {
+        return st->getSourceResourceId();
+    }
+}
+
 static void android_content_XmlBlock_nativeDestroyParseState(JNIEnv* env, jobject clazz,
                                                           jlong token)
 {
@@ -370,7 +382,7 @@
             (void*) android_content_XmlBlock_nativeCreate },
     { "nativeGetStringBlock",       "(J)J",
             (void*) android_content_XmlBlock_nativeGetStringBlock },
-    { "nativeCreateParseState",     "(J)J",
+    { "nativeCreateParseState",     "(JI)J",
             (void*) android_content_XmlBlock_nativeCreateParseState },
     { "nativeDestroyParseState",    "(J)V",
             (void*) android_content_XmlBlock_nativeDestroyParseState },
@@ -411,6 +423,8 @@
             (void*) android_content_XmlBlock_nativeGetClassAttribute },
     { "nativeGetStyleAttribute",   "(J)I",
             (void*) android_content_XmlBlock_nativeGetStyleAttribute },
+    { "nativeGetSourceResId",      "(J)I",
+            (void*) android_content_XmlBlock_nativeGetSourceResId},
 };
 
 int register_android_content_XmlBlock(JNIEnv* env)
diff --git a/core/jni/android_view_InputChannel.cpp b/core/jni/android_view_InputChannel.cpp
index fb6be6b..9819d9a 100644
--- a/core/jni/android_view_InputChannel.cpp
+++ b/core/jni/android_view_InputChannel.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "InputChannel-JNI"
 
 #include <nativehelper/JNIHelp.h>
-
+#include "nativehelper/scoped_utf_chars.h"
 #include <android_runtime/AndroidRuntime.h>
 #include <binder/Parcel.h>
 #include <utils/Log.h>
@@ -123,9 +123,8 @@
 
 static jobjectArray android_view_InputChannel_nativeOpenInputChannelPair(JNIEnv* env,
         jclass clazz, jstring nameObj) {
-    const char* nameChars = env->GetStringUTFChars(nameObj, NULL);
-    std::string name = nameChars;
-    env->ReleaseStringUTFChars(nameObj, nameChars);
+    ScopedUtfChars nameChars(env, nameObj);
+    std::string name = nameChars.c_str();
 
     sp<InputChannel> serverChannel;
     sp<InputChannel> clientChannel;
diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp
index 0d75de9..ce5512b 100644
--- a/core/jni/android_view_RenderNode.cpp
+++ b/core/jni/android_view_RenderNode.cpp
@@ -507,15 +507,15 @@
 jmethodID gPositionListener_PositionLostMethod;
 
 static void android_view_RenderNode_requestPositionUpdates(JNIEnv* env, jobject,
-        jlong renderNodePtr, jobject surfaceview) {
-    class SurfaceViewPositionUpdater : public RenderNode::PositionListener {
+        jlong renderNodePtr, jobject listener) {
+    class PositionListenerTrampoline : public RenderNode::PositionListener {
     public:
-        SurfaceViewPositionUpdater(JNIEnv* env, jobject surfaceview) {
+        PositionListenerTrampoline(JNIEnv* env, jobject listener) {
             env->GetJavaVM(&mVm);
-            mWeakRef = env->NewWeakGlobalRef(surfaceview);
+            mWeakRef = env->NewWeakGlobalRef(listener);
         }
 
-        virtual ~SurfaceViewPositionUpdater() {
+        virtual ~PositionListenerTrampoline() {
             jnienv()->DeleteWeakGlobalRef(mWeakRef);
             mWeakRef = nullptr;
         }
@@ -539,9 +539,14 @@
                 bounds.roundOut();
             }
 
+            if (mPreviousPosition == bounds) {
+                return;
+            }
+            mPreviousPosition = bounds;
+
             incStrong(0);
             auto functor = std::bind(
-                std::mem_fn(&SurfaceViewPositionUpdater::doUpdatePositionAsync), this,
+                std::mem_fn(&PositionListenerTrampoline::doUpdatePositionAsync), this,
                 (jlong) info.canvasContext.getFrameNumber(),
                 (jint) bounds.left, (jint) bounds.top,
                 (jint) bounds.right, (jint) bounds.bottom);
@@ -552,6 +557,11 @@
         virtual void onPositionLost(RenderNode& node, const TreeInfo* info) override {
             if (CC_UNLIKELY(!mWeakRef || (info && !info->updateWindowPositions))) return;
 
+            if (mPreviousPosition.isEmpty()) {
+                return;
+            }
+            mPreviousPosition.setEmpty();
+
             ATRACE_NAME("SurfaceView position lost");
             JNIEnv* env = jnienv();
             jobject localref = env->NewLocalRef(mWeakRef);
@@ -561,6 +571,7 @@
                 return;
             }
 
+            // TODO: Remember why this is synchronous and then make a comment
             env->CallVoidMethod(localref, gPositionListener_PositionLostMethod,
                     info ? info->canvasContext.getFrameNumber() : 0);
             env->DeleteLocalRef(localref);
@@ -596,10 +607,11 @@
 
         JavaVM* mVm;
         jobject mWeakRef;
+        uirenderer::Rect mPreviousPosition;
     };
 
     RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
-    renderNode->setPositionListener(new SurfaceViewPositionUpdater(env, surfaceview));
+    renderNode->setPositionListener(new PositionListenerTrampoline(env, listener));
 }
 
 // ----------------------------------------------------------------------------
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index f9407f4..67a56ae 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -415,18 +415,23 @@
 }
 
 static jlong nativeGetFromSurfaceControl(JNIEnv* env, jclass clazz,
+        jlong nativeObject,
         jlong surfaceControlNativeObj) {
-    /*
-     * This is used by the WindowManagerService just after constructing
-     * a Surface and is necessary for returning the Surface reference to
-     * the caller. At this point, we should only have a SurfaceControl.
-     */
-
+    Surface* self(reinterpret_cast<Surface *>(nativeObject));
     sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
+
+    // If the underlying IGBP's are the same, we don't need to do anything.
+    if (self != nullptr &&
+            IInterface::asBinder(self->getIGraphicBufferProducer()) ==
+            IInterface::asBinder(ctrl->getIGraphicBufferProducer())) {
+        return nativeObject;
+    }
+
     sp<Surface> surface(ctrl->getSurface());
     if (surface != NULL) {
         surface->incStrong(&sRefBaseOwner);
     }
+
     return reinterpret_cast<jlong>(surface.get());
 }
 
@@ -614,7 +619,7 @@
             (void*)nativeAllocateBuffers },
     {"nativeCreateFromSurfaceControl", "(J)J",
             (void*)nativeCreateFromSurfaceControl },
-    {"nativeGetFromSurfaceControl", "(J)J",
+    {"nativeGetFromSurfaceControl", "(JJ)J",
             (void*)nativeGetFromSurfaceControl },
     {"nativeReadFromParcel", "(JLandroid/os/Parcel;)J",
             (void*)nativeReadFromParcel },
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index f1b259e..fad2fe0 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -36,6 +36,7 @@
 #include <memory>
 #include <stdio.h>
 #include <system/graphics.h>
+#include <ui/ConfigStoreTypes.h>
 #include <ui/DisplayInfo.h>
 #include <ui/DisplayedFrameStats.h>
 #include <ui/FrameStats.h>
@@ -108,6 +109,23 @@
     jmethodID ctor;
 } gDisplayedContentSamplingAttributesClassInfo;
 
+static struct {
+    jclass clazz;
+    jmethodID ctor;
+    jfieldID X;
+    jfieldID Y;
+    jfieldID Z;
+} gCieXyzClassInfo;
+
+static struct {
+    jclass clazz;
+    jmethodID ctor;
+    jfieldID red;
+    jfieldID green;
+    jfieldID blue;
+    jfieldID white;
+} gDisplayPrimariesClassInfo;
+
 // ----------------------------------------------------------------------------
 
 static jlong nativeCreateTransaction(JNIEnv* env, jclass clazz) {
@@ -688,6 +706,66 @@
     return colorModesArray;
 }
 
+static jobject nativeGetDisplayNativePrimaries(JNIEnv* env, jclass, jobject tokenObj) {
+    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
+    if (token == NULL) return NULL;
+
+    ui::DisplayPrimaries primaries;
+    if (SurfaceComposerClient::getDisplayNativePrimaries(token, primaries) != NO_ERROR) {
+        return NULL;
+    }
+
+    jobject jred = env->NewObject(gCieXyzClassInfo.clazz, gCieXyzClassInfo.ctor);
+    if (jred == NULL) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return NULL;
+    }
+
+    jobject jgreen = env->NewObject(gCieXyzClassInfo.clazz, gCieXyzClassInfo.ctor);
+    if (jgreen == NULL) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return NULL;
+    }
+
+    jobject jblue = env->NewObject(gCieXyzClassInfo.clazz, gCieXyzClassInfo.ctor);
+    if (jblue == NULL) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return NULL;
+    }
+
+    jobject jwhite = env->NewObject(gCieXyzClassInfo.clazz, gCieXyzClassInfo.ctor);
+    if (jwhite == NULL) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return NULL;
+    }
+
+    jobject jprimaries = env->NewObject(gDisplayPrimariesClassInfo.clazz,
+            gDisplayPrimariesClassInfo.ctor);
+    if (jprimaries == NULL) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return NULL;
+    }
+
+    env->SetFloatField(jred, gCieXyzClassInfo.X, primaries.red.X);
+    env->SetFloatField(jred, gCieXyzClassInfo.Y, primaries.red.Y);
+    env->SetFloatField(jred, gCieXyzClassInfo.Z, primaries.red.Z);
+    env->SetFloatField(jgreen, gCieXyzClassInfo.X, primaries.green.X);
+    env->SetFloatField(jgreen, gCieXyzClassInfo.Y, primaries.green.Y);
+    env->SetFloatField(jgreen, gCieXyzClassInfo.Z, primaries.green.Z);
+    env->SetFloatField(jblue, gCieXyzClassInfo.X, primaries.blue.X);
+    env->SetFloatField(jblue, gCieXyzClassInfo.Y, primaries.blue.Y);
+    env->SetFloatField(jblue, gCieXyzClassInfo.Z, primaries.blue.Z);
+    env->SetFloatField(jwhite, gCieXyzClassInfo.X, primaries.white.X);
+    env->SetFloatField(jwhite, gCieXyzClassInfo.Y, primaries.white.Y);
+    env->SetFloatField(jwhite, gCieXyzClassInfo.Z, primaries.white.Z);
+    env->SetObjectField(jprimaries, gDisplayPrimariesClassInfo.red, jred);
+    env->SetObjectField(jprimaries, gDisplayPrimariesClassInfo.green, jgreen);
+    env->SetObjectField(jprimaries, gDisplayPrimariesClassInfo.blue, jblue);
+    env->SetObjectField(jprimaries, gDisplayPrimariesClassInfo.white, jwhite);
+
+    return jprimaries;
+}
+
 static jint nativeGetActiveColorMode(JNIEnv* env, jclass, jobject tokenObj) {
     sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
     if (token == NULL) return -1;
@@ -1089,6 +1167,8 @@
             (void*)nativeSetActiveConfig },
     {"nativeGetDisplayColorModes", "(Landroid/os/IBinder;)[I",
             (void*)nativeGetDisplayColorModes},
+    {"nativeGetDisplayNativePrimaries", "(Landroid/os/IBinder;)Landroid/view/SurfaceControl$DisplayPrimaries;",
+            (void*)nativeGetDisplayNativePrimaries },
     {"nativeGetActiveColorMode", "(Landroid/os/IBinder;)I",
             (void*)nativeGetActiveColorMode},
     {"nativeSetActiveColorMode", "(Landroid/os/IBinder;I)Z",
@@ -1209,6 +1289,28 @@
             displayedContentSamplingAttributesClazz);
     gDisplayedContentSamplingAttributesClassInfo.ctor = GetMethodIDOrDie(env,
             displayedContentSamplingAttributesClazz, "<init>", "(III)V");
+
+    jclass cieXyzClazz = FindClassOrDie(env, "android/view/SurfaceControl$CieXyz");
+    gCieXyzClassInfo.clazz = MakeGlobalRefOrDie(env, cieXyzClazz);
+    gCieXyzClassInfo.ctor = GetMethodIDOrDie(env, gCieXyzClassInfo.clazz, "<init>", "()V");
+    gCieXyzClassInfo.X = GetFieldIDOrDie(env, cieXyzClazz, "X", "F");
+    gCieXyzClassInfo.Y = GetFieldIDOrDie(env, cieXyzClazz, "Y", "F");
+    gCieXyzClassInfo.Z = GetFieldIDOrDie(env, cieXyzClazz, "Z", "F");
+
+    jclass displayPrimariesClazz = FindClassOrDie(env,
+            "android/view/SurfaceControl$DisplayPrimaries");
+    gDisplayPrimariesClassInfo.clazz = MakeGlobalRefOrDie(env, displayPrimariesClazz);
+    gDisplayPrimariesClassInfo.ctor = GetMethodIDOrDie(env, gDisplayPrimariesClassInfo.clazz,
+            "<init>", "()V");
+    gDisplayPrimariesClassInfo.red = GetFieldIDOrDie(env, displayPrimariesClazz, "red",
+            "Landroid/view/SurfaceControl$CieXyz;");
+    gDisplayPrimariesClassInfo.green = GetFieldIDOrDie(env, displayPrimariesClazz, "green",
+            "Landroid/view/SurfaceControl$CieXyz;");
+    gDisplayPrimariesClassInfo.blue = GetFieldIDOrDie(env, displayPrimariesClazz, "blue",
+            "Landroid/view/SurfaceControl$CieXyz;");
+    gDisplayPrimariesClassInfo.white = GetFieldIDOrDie(env, displayPrimariesClazz, "white",
+            "Landroid/view/SurfaceControl$CieXyz;");
+
     return err;
 }
 
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index 6ee9606..b7837ef 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -276,6 +276,7 @@
 // Must match values in com.android.internal.os.Zygote.
 enum RuntimeFlags : uint32_t {
   DEBUG_ENABLE_JDWP = 1,
+  PROFILE_FROM_SHELL = 1 << 15,
 };
 
 // Forward declaration so we don't have to move the signal handler.
@@ -1224,6 +1225,13 @@
   if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
     EnableDebugger();
   }
+  if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
+    // simpleperf needs the process to be dumpable to profile it.
+    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
+      ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
+      RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
+    }
+  }
 
   if (NeedsNoRandomizeWorkaround()) {
     // Work around ARM kernel ASLR lossage (http://b/5817320).
diff --git a/core/jni/core_jni_helpers.h b/core/jni/core_jni_helpers.h
index 1325b0c..16ef753 100644
--- a/core/jni/core_jni_helpers.h
+++ b/core/jni/core_jni_helpers.h
@@ -18,6 +18,8 @@
 #define CORE_JNI_HELPERS
 
 #include <nativehelper/JNIHelp.h>
+#include <nativehelper/scoped_local_ref.h>
+#include <nativehelper/scoped_utf_chars.h>
 #include <android_runtime/AndroidRuntime.h>
 
 namespace android {
@@ -72,6 +74,20 @@
     return res;
 }
 
+/**
+ * Read the specified field from jobject, and convert to std::string.
+ * If the field cannot be obtained, return defaultValue.
+ */
+static inline std::string getStringField(JNIEnv* env, jobject obj, jfieldID fieldId,
+        const char* defaultValue) {
+    ScopedLocalRef<jstring> strObj(env, jstring(env->GetObjectField(obj, fieldId)));
+    if (strObj != nullptr) {
+        ScopedUtfChars chars(env, strObj.get());
+        return std::string(chars.c_str());
+    }
+    return std::string(defaultValue);
+}
+
 }  // namespace android
 
 #endif  // CORE_JNI_HELPERS
diff --git a/core/proto/android/app/settings_enums.proto b/core/proto/android/app/settings_enums.proto
index f2f7304..30b9b78 100644
--- a/core/proto/android/app/settings_enums.proto
+++ b/core/proto/android/app/settings_enums.proto
@@ -595,6 +595,21 @@
 
     // ACTION: Tap & Pay -> Default Application Setting -> Use Default
     ACTION_NFC_PAYMENT_ALWAYS_SETTING = 1623;
+
+    // ACTION: Settings > Search Bar > Avatar
+    // CATEGORY: SETTINGS
+    // OS: Q
+    CLICK_ACCOUNT_AVATAR = 1643;
+
+    // ACTION: Set new password (action intent android.app.action.SET_NEW_PASSWORD)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    ACTION_SET_NEW_PASSWORD = 1645;
+
+    // ACTION: Set new password (action intent android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    ACTION_SET_NEW_PARENT_PROFILE_PASSWORD = 1646;
 }
 
 /**
@@ -2194,4 +2209,9 @@
     // details for a SIM/eSIM mobile network > Click edit icon to bring up a rename dialog.
     // OS: Q
     MOBILE_NETWORK_RENAME_DIALOG = 1642;
+
+    // OPEN: Set new password (android.app.action.SET_NEW_PASSWORD action intent)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    SET_NEW_PASSWORD_ACTIVITY = 1644;
 }
diff --git a/core/proto/android/bluetooth/enums.proto b/core/proto/android/bluetooth/enums.proto
index a88a06c..5b5c9c2 100644
--- a/core/proto/android/bluetooth/enums.proto
+++ b/core/proto/android/bluetooth/enums.proto
@@ -110,3 +110,25 @@
     UNBOND_REASON_REMOTE_AUTH_CANCELED = 8;
     UNBOND_REASON_REMOVED = 9;
 }
+
+enum SocketTypeEnum {
+    SOCKET_TYPE_UNKNOWN = 0;
+    SOCKET_TYPE_RFCOMM = 1;
+    SOCKET_TYPE_SCO = 2;
+    SOCKET_TYPE_L2CAP_BREDR = 3;
+    SOCKET_TYPE_L2CAP_LE = 4;
+}
+
+enum SocketConnectionstateEnum {
+    SOCKET_CONNECTION_STATE_UNKNOWN = 0;
+    // Socket acts as a server waiting for connection
+    SOCKET_CONNECTION_STATE_LISTENING = 1;
+    // Socket acts as a client trying to connect
+    SOCKET_CONNECTION_STATE_CONNECTING = 2;
+    // Socket is connected
+    SOCKET_CONNECTION_STATE_CONNECTED = 3;
+    // Socket tries to disconnect from remote
+    SOCKET_CONNECTION_STATE_DISCONNECTING = 4;
+    // This socket is closed
+    SOCKET_CONNECTION_STATE_DISCONNECTED = 5;
+}
diff --git a/core/proto/android/providers/settings/system.proto b/core/proto/android/providers/settings/system.proto
index dfc4081..41a7498 100644
--- a/core/proto/android/providers/settings/system.proto
+++ b/core/proto/android/providers/settings/system.proto
@@ -232,6 +232,8 @@
         // Which streams are affected by mute. The stream type's bit should be set
         // to 1 if it should be muted when a mute request is received.
         optional SettingProto mute_streams_affected = 12 [ (android.privacy).dest = DEST_AUTOMATIC ];
+        // Master balance (float -1.f = 100% left, 0.f = dead center, 1.f = 100% right).
+        optional SettingProto master_balance = 13 [ (android.privacy).dest = DEST_AUTOMATIC ];
     }
     optional Volume volume = 33;
 
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index bc9dc57..840291d 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -274,6 +274,7 @@
     <protected-broadcast android:name="android.media.MASTER_VOLUME_CHANGED_ACTION" />
     <protected-broadcast android:name="android.media.MASTER_MUTE_CHANGED_ACTION" />
     <protected-broadcast android:name="android.media.MASTER_MONO_CHANGED_ACTION" />
+    <protected-broadcast android:name="android.media.MASTER_BALANCE_CHANGED_ACTION" />
     <protected-broadcast android:name="android.media.SCO_AUDIO_STATE_CHANGED" />
     <protected-broadcast android:name="android.media.ACTION_SCO_AUDIO_STATE_UPDATED" />
 
@@ -4332,7 +4333,7 @@
     <!-- @SystemApi Allows an application to manage the app predictions service.
          @hide  <p>Not for use by third-party applications.</p> -->
     <permission android:name="android.permission.MANAGE_APP_PREDICTIONS"
-         android:protectionLevel="signature" />
+         android:protectionLevel="signature|appPredictor" />
 
     <!-- Allows an app to set the theme overlay in /vendor/overlay
          being used.
diff --git a/core/res/res/anim/lock_in.xml b/core/res/res/anim/lock_in.xml
new file mode 100755
index 0000000..992bc92
--- /dev/null
+++ b/core/res/res/anim/lock_in.xml
@@ -0,0 +1,404 @@
+<!--
+     Copyright (C) 2019 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:aapt="http://schemas.android.com/aapt">
+    <aapt:attr name="android:drawable">
+        <vector
+            android:width="24dp"
+            android:height="24dp"
+            android:viewportWidth="24"
+            android:viewportHeight="24">
+            <group android:name="_R_G">
+                <group android:name="_R_G_L_2_G_N_3_T_0_M">
+                    <group
+                        android:name="_R_G_L_2_G_N_3_T_0"
+                        android:pivotX="2.25"
+                        android:pivotY="2.25"
+                        android:scaleX="0"
+                        android:scaleY="0"
+                        android:translateX="9.75"
+                        android:translateY="12.75">
+                        <group
+                            android:name="_R_G_L_2_G_T_1"
+                            android:scaleX="0.12346"
+                            android:scaleY="0.12346"
+                            android:translateX="2.25"
+                            android:translateY="2.373">
+                            <group
+                                android:name="_R_G_L_2_G"
+                                android:translateY="32">
+                                <path
+                                    android:name="_R_G_L_2_G_D_0_P_0"
+                                    android:fillAlpha="0"
+                                    android:fillColor="#ff0000"
+                                    android:fillType="nonZero"
+                                    android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                                    android:trimPathStart="0.14"
+                                    android:trimPathEnd="0.89"
+                                    android:trimPathOffset="0" />
+                                <path
+                                    android:name="_R_G_L_2_G_D_1_P_0"
+                                    android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                                    android:strokeWidth="16"
+                                    android:strokeAlpha="1"
+                                    android:strokeColor="?attr/textColor"
+                                    android:trimPathStart="0.14"
+                                    android:trimPathEnd="0.89"
+                                    android:trimPathOffset="0" />
+                            </group>
+                        </group>
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_1_G"
+                    android:pivotX="8.25"
+                    android:pivotY="7.25"
+                    android:scaleX="0"
+                    android:scaleY="0"
+                    android:translateX="3.75"
+                    android:translateY="7.75">
+                    <path
+                        android:name="_R_G_L_1_G_D_0_P_0"
+                        android:fillAlpha="1"
+                        android:fillColor="?attr/textColor"
+                        android:fillType="nonZero"
+                        android:pathData=" M14.25 0.25 C14.25,0.25 12.75,0.25 12.75,0.25 C12.75,0.25 10.75,0.25 10.75,0.25 C10.75,0.25 5.75,0.25 5.75,0.25 C5.75,0.25 3.75,0.25 3.75,0.25 C3.75,0.25 2.25,0.25 2.25,0.25 C1.15,0.25 0.25,1.15 0.25,2.25 C0.25,2.25 0.25,12.25 0.25,12.25 C0.25,13.35 1.15,14.25 2.25,14.25 C2.25,14.25 14.25,14.25 14.25,14.25 C15.35,14.25 16.25,13.35 16.25,12.25 C16.25,12.25 16.25,2.25 16.25,2.25 C16.25,1.15 15.35,0.25 14.25,0.25c  M14.25 12.25 C14.25,12.25 2.25,12.25 2.25,12.25 C2.25,12.25 2.25,2.25 2.25,2.25 C2.25,2.25 3.75,2.25 3.75,2.25 C3.75,2.25 12.75,2.25 12.75,2.25 C12.75,2.25 14.25,2.25 14.25,2.25 C14.25,2.25 14.25,12.25 14.25,12.25c " />
+                </group>
+                <group
+                    android:name="_R_G_L_0_G"
+                    android:pivotX="2.25"
+                    android:pivotY="2.25"
+                    android:scaleX="0"
+                    android:scaleY="0"
+                    android:translateX="9.75"
+                    android:translateY="12.75">
+                    <path
+                        android:name="_R_G_L_0_G_D_0_P_0"
+                        android:fillAlpha="1"
+                        android:fillColor="?attr/textColor"
+                        android:fillType="nonZero"
+                        android:pathData=" M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c " />
+                </group>
+            </group>
+            <group android:name="time_group" />
+        </vector>
+    </aapt:attr>
+    <target android:name="_R_G_L_2_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="50"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="0"
+                    android:valueFrom="0.14"
+                    android:valueTo="0.14"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="50"
+                    android:valueFrom="0.14"
+                    android:valueTo="0"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="50"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="0"
+                    android:valueFrom="0.89"
+                    android:valueTo="0.89"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="50"
+                    android:valueFrom="0.89"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="50"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="0"
+                    android:valueFrom="0.14"
+                    android:valueTo="0.14"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="50"
+                    android:valueFrom="0.14"
+                    android:valueTo="0"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="50"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="0"
+                    android:valueFrom="0.89"
+                    android:valueTo="0.89"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="50"
+                    android:valueFrom="0.89"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="150"
+                    android:pathData="M 2.25,2.373C 2.25,1.2001604776382402 2.25,-3.49116047763824 2.25,-4.664"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.001,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_N_3_T_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.0125"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.043,0.556 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.0125"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.043,0.556 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleX"
+                    android:startOffset="233"
+                    android:valueFrom="1.0125"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleY"
+                    android:startOffset="233"
+                    android:valueFrom="1.0125"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_N_3_T_0_M">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="0"
+                    android:propertyName="scaleX"
+                    android:startOffset="50"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.025"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.001,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.025"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.001,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleX"
+                    android:startOffset="233"
+                    android:valueFrom="1.025"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleY"
+                    android:startOffset="233"
+                    android:valueFrom="1.025"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.0125"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.043,0.556 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="233"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1.0125"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.043,0.556 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleX"
+                    android:startOffset="233"
+                    android:valueFrom="1.0125"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="scaleY"
+                    android:startOffset="233"
+                    android:valueFrom="1.0125"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="time_group">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="717"
+                    android:propertyName="translateX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+</animated-vector>
\ No newline at end of file
diff --git a/core/res/res/anim/lock_lock.xml b/core/res/res/anim/lock_lock.xml
new file mode 100755
index 0000000..8b7887c
--- /dev/null
+++ b/core/res/res/anim/lock_lock.xml
@@ -0,0 +1,16 @@
+<!--
+     Copyright (C) 2019 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"><aapt:attr name="android:drawable"><vector android:height="24dp" android:width="24dp" android:viewportHeight="24" android:viewportWidth="24"><group android:name="_R_G"><group android:name="_R_G_L_2_G_T_1" android:translateX="12" android:translateY="15"><group android:name="_R_G_L_2_G" android:translateX="-8.25" android:translateY="-7.25"><path android:name="_R_G_L_2_G_D_0_P_0" android:fillColor="?attr/textColor" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M14.25 0.25 C14.25,0.25 12.75,0.25 12.75,0.25 C12.75,0.25 10.75,0.25 10.75,0.25 C10.75,0.25 5.75,0.25 5.75,0.25 C5.75,0.25 3.75,0.25 3.75,0.25 C3.75,0.25 2.25,0.25 2.25,0.25 C1.15,0.25 0.25,1.15 0.25,2.25 C0.25,2.25 0.25,12.25 0.25,12.25 C0.25,13.35 1.15,14.25 2.25,14.25 C2.25,14.25 14.25,14.25 14.25,14.25 C15.35,14.25 16.25,13.35 16.25,12.25 C16.25,12.25 16.25,2.25 16.25,2.25 C16.25,1.15 15.35,0.25 14.25,0.25c  M14.25 12.25 C14.25,12.25 2.25,12.25 2.25,12.25 C2.25,12.25 2.25,2.25 2.25,2.25 C2.25,2.25 3.75,2.25 3.75,2.25 C3.75,2.25 12.75,2.25 12.75,2.25 C12.75,2.25 14.25,2.25 14.25,2.25 C14.25,2.25 14.25,12.25 14.25,12.25c "/></group></group><group android:name="_R_G_L_1_G_N_5_T_1" android:translateX="12" android:translateY="15"><group android:name="_R_G_L_1_G_N_5_T_0" android:translateX="-8.25" android:translateY="-7.25"><group android:name="_R_G_L_1_G" android:translateX="6" android:translateY="5" android:pivotX="2.25" android:pivotY="2.25" android:scaleX="1" android:scaleY="1"><path android:name="_R_G_L_1_G_D_0_P_0" android:fillColor="?attr/textColor" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c "/></group></group></group><group android:name="_R_G_L_0_G_N_5_T_1" android:translateX="12" android:translateY="15"><group android:name="_R_G_L_0_G_N_5_T_0" android:translateX="-8.25" android:translateY="-7.25"><group android:name="_R_G_L_0_G" android:translateX="-16.219" android:translateY="32.25" android:pivotX="27.965" android:pivotY="-32" android:scaleX="0.125" android:scaleY="0.125"><path android:name="_R_G_L_0_G_D_0_P_0" android:fillColor="#ff0000" android:fillAlpha="0" android:fillType="nonZero" android:pathData=" M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 "/><path android:name="_R_G_L_0_G_D_1_P_0" android:strokeColor="?attr/textColor" android:strokeLineCap="round" android:strokeLineJoin="round" android:strokeWidth="16" android:strokeAlpha="1" android:pathData=" M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 "/></group></group></group></group><group android:name="time_group"/></vector></aapt:attr><target android:name="_R_G_L_2_G_T_1"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="translateXY" android:duration="400" android:startOffset="0" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="67" android:startOffset="400" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15.594 12,15.594"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="83" android:startOffset="467" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15.594C 12,15.594 12,15.09895833581686 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="_R_G_L_1_G"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="scaleX" android:duration="450" android:startOffset="0" android:valueFrom="1" android:valueTo="1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="scaleY" android:duration="450" android:startOffset="0" android:valueFrom="1" android:valueTo="1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="scaleX" android:duration="67" android:startOffset="450" android:valueFrom="1" android:valueTo="1.1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="scaleY" android:duration="67" android:startOffset="450" android:valueFrom="1" android:valueTo="1.1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="scaleX" android:duration="183" android:startOffset="517" android:valueFrom="1.1" android:valueTo="1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="scaleY" android:duration="183" android:startOffset="517" android:valueFrom="1.1" android:valueTo="1" android:valueType="floatType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="_R_G_L_1_G_N_5_T_1"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="translateXY" android:duration="400" android:startOffset="0" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="67" android:startOffset="400" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15.594 12,15.594"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="83" android:startOffset="467" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15.594C 12,15.594 12,15.09895833581686 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="_R_G_L_0_G_D_0_P_0"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="pathData" android:duration="317" android:startOffset="0" android:valueFrom="M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 " android:valueTo="M-27.97 -55.05 C-27.97,-55.05 -28,-60.25 -27.97,-61.98 C-27.92,-64.13 -23.5,-86.37 -0.75,-86.32 C22.77,-86.26 27.75,-65.87 27.72,-64.77 C27.55,-59.38 27.97,-31.67 27.97,-31.67 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.974,0 0.458,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="pathData" android:duration="133" android:startOffset="317" android:valueFrom="M-27.97 -55.05 C-27.97,-55.05 -28,-60.25 -27.97,-61.98 C-27.92,-64.13 -23.5,-86.37 -0.75,-86.32 C22.77,-86.26 27.75,-65.87 27.72,-64.77 C27.55,-59.38 27.97,-31.67 27.97,-31.67 " android:valueTo="M-28.21 -28.42 C-28.21,-28.42 -27.85,-44.88 -27.97,-51.98 C-28,-54.13 -23.5,-76.37 -0.75,-76.32 C22.77,-76.26 27.75,-55.87 27.72,-54.77 C27.55,-49.38 27.97,-28.17 27.97,-28.17 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="pathData" android:duration="250" android:startOffset="450" android:valueFrom="M-28.21 -28.42 C-28.21,-28.42 -27.85,-44.88 -27.97,-51.98 C-28,-54.13 -23.5,-76.37 -0.75,-76.32 C22.77,-76.26 27.75,-55.87 27.72,-54.77 C27.55,-49.38 27.97,-28.17 27.97,-28.17 " android:valueTo="M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.414,0 0.647,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="_R_G_L_0_G_D_1_P_0"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="pathData" android:duration="317" android:startOffset="0" android:valueFrom="M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 " android:valueTo="M-27.97 -55.05 C-27.97,-55.05 -28,-60.25 -27.97,-61.98 C-27.92,-64.13 -23.5,-86.37 -0.75,-86.32 C22.77,-86.26 27.75,-65.87 27.72,-64.77 C27.55,-59.38 27.97,-31.67 27.97,-31.67 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.974,0 0.458,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="pathData" android:duration="133" android:startOffset="317" android:valueFrom="M-27.97 -55.05 C-27.97,-55.05 -28,-60.25 -27.97,-61.98 C-27.92,-64.13 -23.5,-86.37 -0.75,-86.32 C22.77,-86.26 27.75,-65.87 27.72,-64.77 C27.55,-59.38 27.97,-31.67 27.97,-31.67 " android:valueTo="M-28.21 -28.42 C-28.21,-28.42 -27.85,-44.88 -27.97,-51.98 C-28,-54.13 -23.5,-76.37 -0.75,-76.32 C22.77,-76.26 27.75,-55.87 27.72,-54.77 C27.55,-49.38 27.97,-28.17 27.97,-28.17 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="pathData" android:duration="250" android:startOffset="450" android:valueFrom="M-28.21 -28.42 C-28.21,-28.42 -27.85,-44.88 -27.97,-51.98 C-28,-54.13 -23.5,-76.37 -0.75,-76.32 C22.77,-76.26 27.75,-55.87 27.72,-54.77 C27.55,-49.38 27.97,-28.17 27.97,-28.17 " android:valueTo="M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 " android:valueType="pathType"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.414,0 0.647,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="_R_G_L_0_G_N_5_T_1"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="translateXY" android:duration="400" android:startOffset="0" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="67" android:startOffset="400" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15C 12,15.09895833581686 12,15.594 12,15.594"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator><objectAnimator android:propertyName="translateXY" android:duration="83" android:startOffset="467" android:propertyXName="translateX" android:propertyYName="translateY" android:pathData="M 12,15.594C 12,15.594 12,15.09895833581686 12,15"><aapt:attr name="android:interpolator"><pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0"/></aapt:attr></objectAnimator></set></aapt:attr></target><target android:name="time_group"><aapt:attr name="android:animation"><set android:ordering="together"><objectAnimator android:propertyName="translateX" android:duration="717" android:startOffset="0" android:valueFrom="0" android:valueTo="1" android:valueType="floatType"/></set></aapt:attr></target></animated-vector>
\ No newline at end of file
diff --git a/core/res/res/anim/lock_out.xml b/core/res/res/anim/lock_out.xml
new file mode 100755
index 0000000..2543d47
--- /dev/null
+++ b/core/res/res/anim/lock_out.xml
@@ -0,0 +1,277 @@
+<!--
+     Copyright (C) 2019 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:aapt="http://schemas.android.com/aapt">
+    <aapt:attr name="android:drawable">
+        <vector
+            android:width="24dp"
+            android:height="24dp"
+            android:viewportWidth="24"
+            android:viewportHeight="24">
+            <group android:name="_R_G">
+                <group android:name="_R_G_L_2_G_N_4_T_0_M">
+                    <group
+                        android:name="_R_G_L_2_G_N_4_T_0"
+                        android:pivotX="8.25"
+                        android:pivotY="7.25"
+                        android:scaleX="1"
+                        android:scaleY="1"
+                        android:translateX="3.75"
+                        android:translateY="7.75">
+                        <group
+                            android:name="_R_G_L_2_G"
+                            android:pivotY="-32"
+                            android:scaleX="0.125"
+                            android:scaleY="0.125"
+                            android:translateX="8.25"
+                            android:translateY="32.267">
+                            <path
+                                android:name="_R_G_L_2_G_D_0_P_0"
+                                android:fillAlpha="0"
+                                android:fillColor="#ff0000"
+                                android:fillType="nonZero"
+                                android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                                android:trimPathStart="0"
+                                android:trimPathEnd="1"
+                                android:trimPathOffset="0" />
+                            <path
+                                android:name="_R_G_L_2_G_D_1_P_0"
+                                android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                                android:strokeWidth="16"
+                                android:strokeAlpha="1"
+                                android:strokeColor="?attr/textColor"
+                                android:trimPathStart="0"
+                                android:trimPathEnd="1"
+                                android:trimPathOffset="0" />
+                        </group>
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_1_G"
+                    android:pivotX="8.25"
+                    android:pivotY="7.25"
+                    android:scaleX="1"
+                    android:scaleY="1"
+                    android:translateX="3.75"
+                    android:translateY="7.75">
+                    <path
+                        android:name="_R_G_L_1_G_D_0_P_0"
+                        android:fillAlpha="1"
+                        android:fillColor="?attr/textColor"
+                        android:fillType="nonZero"
+                        android:pathData=" M14.25 0.25 C14.25,0.25 12.75,0.25 12.75,0.25 C12.75,0.25 10.75,0.25 10.75,0.25 C10.75,0.25 5.75,0.25 5.75,0.25 C5.75,0.25 3.75,0.25 3.75,0.25 C3.75,0.25 2.25,0.25 2.25,0.25 C1.15,0.25 0.25,1.15 0.25,2.25 C0.25,2.25 0.25,12.25 0.25,12.25 C0.25,13.35 1.15,14.25 2.25,14.25 C2.25,14.25 14.25,14.25 14.25,14.25 C15.35,14.25 16.25,13.35 16.25,12.25 C16.25,12.25 16.25,2.25 16.25,2.25 C16.25,1.15 15.35,0.25 14.25,0.25c  M14.25 12.25 C14.25,12.25 2.25,12.25 2.25,12.25 C2.25,12.25 2.25,2.25 2.25,2.25 C2.25,2.25 3.75,2.25 3.75,2.25 C3.75,2.25 12.75,2.25 12.75,2.25 C12.75,2.25 14.25,2.25 14.25,2.25 C14.25,2.25 14.25,12.25 14.25,12.25c " />
+                </group>
+                <group android:name="_R_G_L_0_G_N_4_T_0_M">
+                    <group
+                        android:name="_R_G_L_0_G_N_4_T_0"
+                        android:pivotX="8.25"
+                        android:pivotY="7.25"
+                        android:scaleX="1"
+                        android:scaleY="1"
+                        android:translateX="3.75"
+                        android:translateY="7.75">
+                        <group
+                            android:name="_R_G_L_0_G"
+                            android:translateX="6"
+                            android:translateY="5">
+                            <path
+                                android:name="_R_G_L_0_G_D_0_P_0"
+                                android:fillAlpha="1"
+                                android:fillColor="?attr/textColor"
+                                android:fillType="nonZero"
+                                android:pathData=" M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c " />
+                        </group>
+                    </group>
+                </group>
+            </group>
+            <group android:name="time_group" />
+        </vector>
+    </aapt:attr>
+    <target android:name="_R_G_L_2_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="150"
+                    android:propertyName="strokeAlpha"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_N_4_T_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_N_4_T_0_M">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="0"
+                    android:propertyName="scaleY"
+                    android:startOffset="350"
+                    android:valueFrom="1"
+                    android:valueTo="0"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="150"
+                    android:propertyName="fillAlpha"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.02"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="83"
+                    android:propertyName="fillAlpha"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_N_4_T_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="200"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.09375"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.521,0 0.942,0.896 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_N_4_T_0_M">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="0"
+                    android:propertyName="scaleY"
+                    android:startOffset="367"
+                    android:valueFrom="1"
+                    android:valueTo="0"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="time_group">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="500"
+                    android:propertyName="translateX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+</animated-vector>
\ No newline at end of file
diff --git a/core/res/res/anim/lock_to_error.xml b/core/res/res/anim/lock_to_error.xml
new file mode 100755
index 0000000..29b4964
--- /dev/null
+++ b/core/res/res/anim/lock_to_error.xml
@@ -0,0 +1,574 @@
+<!--
+     Copyright (C) 2019 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:aapt="http://schemas.android.com/aapt">
+    <aapt:attr name="android:drawable">
+        <vector
+            android:width="24dp"
+            android:height="24dp"
+            android:viewportWidth="24"
+            android:viewportHeight="24">
+            <group android:name="_R_G">
+                <group
+                    android:name="_R_G_L_3_G"
+                    android:pivotY="-32"
+                    android:scaleX="0.12762"
+                    android:scaleY="0.12762"
+                    android:translateX="12"
+                    android:translateY="39.871">
+                    <path
+                        android:name="_R_G_L_3_G_D_0_P_0"
+                        android:fillAlpha="0"
+                        android:fillColor="#ff0000"
+                        android:fillType="nonZero"
+                        android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                        android:trimPathStart="0"
+                        android:trimPathEnd="1"
+                        android:trimPathOffset="0" />
+                    <path
+                        android:name="_R_G_L_3_G_D_1_P_0"
+                        android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                        android:strokeWidth="16"
+                        android:strokeAlpha="1"
+                        android:strokeColor="?attr/textColor"
+                        android:trimPathStart="0"
+                        android:trimPathEnd="1"
+                        android:trimPathOffset="0" />
+                </group>
+                <group
+                    android:name="_R_G_L_2_G_T_1"
+                    android:rotation="45"
+                    android:scaleX="1"
+                    android:scaleY="1"
+                    android:translateX="12"
+                    android:translateY="15">
+                    <group
+                        android:name="_R_G_L_2_G"
+                        android:translateX="-2.25"
+                        android:translateY="-2.25">
+                        <path
+                            android:name="_R_G_L_2_G_D_0_P_0"
+                            android:fillAlpha="1"
+                            android:fillColor="?attr/textColor"
+                            android:fillType="nonZero"
+                            android:pathData=" M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c " />
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_1_G_T_1"
+                    android:scaleX="0.125"
+                    android:scaleY="0.125"
+                    android:translateX="12.023"
+                    android:translateY="1.281">
+                    <group
+                        android:name="_R_G_L_1_G"
+                        android:translateX="0.317"
+                        android:translateY="45.25">
+                        <path
+                            android:name="_R_G_L_1_G_D_0_P_0"
+                            android:fillAlpha="0"
+                            android:fillColor="#EA4335"
+                            android:fillType="nonZero"
+                            android:pathData=" M4.21 -42.01 C4.21,-42.01 4.21,-32 4.21,-32 C4.21,-32 -5.25,-32 -5.25,-32 C-5.25,-32 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c " />
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_0_G"
+                    android:pivotY="21"
+                    android:scaleX="0.14286"
+                    android:scaleY="0.14286"
+                    android:translateX="12"
+                    android:translateY="-6">
+                    <path
+                        android:name="_R_G_L_0_G_D_0_P_0"
+                        android:fillAlpha="0"
+                        android:fillColor="#ffffff"
+                        android:fillType="nonZero"
+                        android:pathData=" M49.24 -12.32 C49.24,-12.32 49.24,52.91 49.24,52.91 C49.24,58.95 44.34,63.85 38.3,63.85 C38.3,63.85 -37.8,63.85 -37.8,63.85 C-43.84,63.85 -48.74,58.95 -48.74,52.91 C-48.74,52.91 -48.74,-12.32 -48.74,-12.32 C-48.74,-18.37 -43.84,-23.27 -37.8,-23.27 C-37.8,-23.27 38.3,-23.27 38.3,-23.27 C44.34,-23.27 49.24,-18.37 49.24,-12.32c " />
+                    <path
+                        android:name="_R_G_L_0_G_D_1_P_0"
+                        android:pathData=" M49.24 -12.32 C49.24,-12.32 49.24,52.91 49.24,52.91 C49.24,58.95 44.34,63.85 38.3,63.85 C38.3,63.85 -37.8,63.85 -37.8,63.85 C-43.84,63.85 -48.74,58.95 -48.74,52.91 C-48.74,52.91 -48.74,-12.32 -48.74,-12.32 C-48.74,-18.37 -43.84,-23.27 -37.8,-23.27 C-37.8,-23.27 38.3,-23.27 38.3,-23.27 C44.34,-23.27 49.24,-18.37 49.24,-12.32c "
+                        android:strokeWidth="14"
+                        android:strokeAlpha="1"
+                        android:strokeColor="?attr/textColor"
+                        android:strokeLineCap="round"
+                        android:strokeLineJoin="round" />
+                </group>
+            </group>
+            <group android:name="time_group" />
+        </vector>
+    </aapt:attr>
+    <target android:name="_R_G_L_3_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="250"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="0.5"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="250"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.5"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="strokeColor"
+                    android:startOffset="0"
+                    android:valueFrom="#fff"
+                    android:valueTo="#fff"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="strokeColor"
+                    android:startOffset="117"
+                    android:valueFrom="#fff"
+                    android:valueTo="#EA4335"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="133"
+                    android:propertyName="strokeWidth"
+                    android:startOffset="0"
+                    android:valueFrom="16"
+                    android:valueTo="8"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="250"
+                    android:propertyName="trimPathStart"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="0.5"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="250"
+                    android:propertyName="trimPathEnd"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.5"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="0"
+                    android:propertyName="scaleY"
+                    android:startOffset="183"
+                    android:valueFrom="0.12762"
+                    android:valueTo="0"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="fillColor"
+                    android:startOffset="0"
+                    android:valueFrom="#fff"
+                    android:valueTo="#fff"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="fillColor"
+                    android:startOffset="117"
+                    android:valueFrom="#fff"
+                    android:valueTo="#EA4335"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="133"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c "
+                    android:valueTo="M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0 0.833,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="133"
+                    android:propertyName="pathData"
+                    android:startOffset="133"
+                    android:valueFrom="M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c "
+                    android:valueTo="M2.25 0.25 C2.25,0.25 4.25,2.25 4.25,2.25 C4.25,2.25 2.25,4.25 2.25,4.25 C2.25,4.25 0.25,2.25 0.25,2.25 C0.25,2.25 2.25,0.25 2.25,0.25c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="17"
+                    android:pathData="M 12,15C 12,15.171875 12,14.828125 12,15"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="333"
+                    android:pathData="M 12,15C 12,15.171875 12,15.859124999999999 12,16.031"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="17">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="333"
+                    android:propertyName="scaleX"
+                    android:startOffset="17"
+                    android:valueFrom="1"
+                    android:valueTo="0.4325"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="333"
+                    android:propertyName="scaleY"
+                    android:startOffset="17"
+                    android:valueFrom="1"
+                    android:valueTo="0.4325"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="150"
+                    android:propertyName="fillAlpha"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="0"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="fillAlpha"
+                    android:startOffset="150"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="167"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M4.21 -42.01 C4.21,-42.01 4.21,-32 4.21,-32 C4.21,-32 -5.25,-32 -5.25,-32 C-5.25,-32 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueTo="M4.21 -42.01 C4.21,-42.01 4.21,-32 4.21,-32 C4.21,-32 -5.25,-32 -5.25,-32 C-5.25,-32 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="183"
+                    android:propertyName="pathData"
+                    android:startOffset="167"
+                    android:valueFrom="M4.21 -42.01 C4.21,-42.01 4.21,-32 4.21,-32 C4.21,-32 -5.25,-32 -5.25,-32 C-5.25,-32 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueTo="M4.21 -42.01 C4.21,-42.01 4.16,33 4.16,33 C4.16,33 -5.3,33 -5.3,33 C-5.3,33 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="50"
+                    android:propertyName="pathData"
+                    android:startOffset="350"
+                    android:valueFrom="M4.21 -42.01 C4.21,-42.01 4.16,33 4.16,33 C4.16,33 -5.3,33 -5.3,33 C-5.3,33 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueTo="M4.21 -42.01 C4.21,-42.01 4.19,30.81 4.19,30.81 C4.19,30.81 -5.27,30.81 -5.27,30.81 C-5.27,30.81 -5.25,-42.01 -5.25,-42.01 C-5.25,-42.01 4.21,-42.01 4.21,-42.01c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="167"
+                    android:pathData="M 12.023,1.281C 12.023,1.656 12.023,0.9059999999999999 12.023,1.281"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="183"
+                    android:pathData="M 12.023,1.281C 12.023,1.656 12.023,3.156 12.023,3.531"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="167">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="0"
+                    android:propertyName="scaleX"
+                    android:startOffset="167"
+                    android:valueFrom="0"
+                    android:valueTo="0.125"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="267"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M49.24 -12.32 C49.24,-12.32 49.24,52.91 49.24,52.91 C49.24,58.95 44.34,63.85 38.3,63.85 C38.3,63.85 -37.8,63.85 -37.8,63.85 C-43.84,63.85 -48.74,58.95 -48.74,52.91 C-48.74,52.91 -48.74,-12.32 -48.74,-12.32 C-48.74,-18.37 -43.84,-23.27 -37.8,-23.27 C-37.8,-23.27 38.3,-23.27 38.3,-23.27 C44.34,-23.27 49.24,-18.37 49.24,-12.32c "
+                    android:valueTo="M75.1 -1.1 C75.1,19.57 66.72,38.28 53.18,51.83 C39.63,65.37 20.92,73.75 0.25,73.75 C-20.42,73.75 -39.13,65.37 -52.68,51.83 C-66.22,38.28 -74.6,19.57 -74.6,-1.1 C-74.6,-21.77 -66.22,-40.48 -52.68,-54.02 C-39.13,-67.57 -20.42,-75.95 0.25,-75.95 C20.92,-75.95 39.63,-67.57 53.18,-54.02 C66.72,-40.48 75.1,-21.77 75.1,-1.1c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="117"
+                    android:propertyName="strokeColor"
+                    android:startOffset="0"
+                    android:valueFrom="#fff"
+                    android:valueTo="#fff"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="17"
+                    android:propertyName="strokeColor"
+                    android:startOffset="117"
+                    android:valueFrom="#fff"
+                    android:valueTo="#EA4335"
+                    android:valueType="colorType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="267"
+                    android:propertyName="strokeWidth"
+                    android:startOffset="0"
+                    android:valueFrom="14"
+                    android:valueTo="12"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="267"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M49.24 -12.32 C49.24,-12.32 49.24,52.91 49.24,52.91 C49.24,58.95 44.34,63.85 38.3,63.85 C38.3,63.85 -37.8,63.85 -37.8,63.85 C-43.84,63.85 -48.74,58.95 -48.74,52.91 C-48.74,52.91 -48.74,-12.32 -48.74,-12.32 C-48.74,-18.37 -43.84,-23.27 -37.8,-23.27 C-37.8,-23.27 38.3,-23.27 38.3,-23.27 C44.34,-23.27 49.24,-18.37 49.24,-12.32c "
+                    android:valueTo="M75.1 -1.1 C75.1,19.57 66.72,38.28 53.18,51.83 C39.63,65.37 20.92,73.75 0.25,73.75 C-20.42,73.75 -39.13,65.37 -52.68,51.83 C-66.22,38.28 -74.6,19.57 -74.6,-1.1 C-74.6,-21.77 -66.22,-40.48 -52.68,-54.02 C-39.13,-67.57 -20.42,-75.95 0.25,-75.95 C20.92,-75.95 39.63,-67.57 53.18,-54.02 C66.72,-40.48 75.1,-21.77 75.1,-1.1c "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="time_group">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="1017"
+                    android:propertyName="translateX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+</animated-vector>
\ No newline at end of file
diff --git a/core/res/res/anim/lock_unlock.xml b/core/res/res/anim/lock_unlock.xml
new file mode 100755
index 0000000..9cc31a0
--- /dev/null
+++ b/core/res/res/anim/lock_unlock.xml
@@ -0,0 +1,337 @@
+<!--
+     Copyright (C) 2019 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:aapt="http://schemas.android.com/aapt">
+    <aapt:attr name="android:drawable">
+        <vector
+            android:width="24dp"
+            android:height="24dp"
+            android:viewportWidth="24"
+            android:viewportHeight="24">
+            <group android:name="_R_G">
+                <group
+                    android:name="_R_G_L_2_G_T_1"
+                    android:translateX="12"
+                    android:translateY="15">
+                    <group
+                        android:name="_R_G_L_2_G"
+                        android:translateX="-8.25"
+                        android:translateY="-7.25">
+                        <path
+                            android:name="_R_G_L_2_G_D_0_P_0"
+                            android:fillAlpha="1"
+                            android:fillColor="?attr/textColor"
+                            android:fillType="nonZero"
+                            android:pathData=" M14.25 0.25 C14.25,0.25 12.75,0.25 12.75,0.25 C12.75,0.25 10.75,0.25 10.75,0.25 C10.75,0.25 5.75,0.25 5.75,0.25 C5.75,0.25 3.75,0.25 3.75,0.25 C3.75,0.25 2.25,0.25 2.25,0.25 C1.15,0.25 0.25,1.15 0.25,2.25 C0.25,2.25 0.25,12.25 0.25,12.25 C0.25,13.35 1.15,14.25 2.25,14.25 C2.25,14.25 14.25,14.25 14.25,14.25 C15.35,14.25 16.25,13.35 16.25,12.25 C16.25,12.25 16.25,2.25 16.25,2.25 C16.25,1.15 15.35,0.25 14.25,0.25c  M14.25 12.25 C14.25,12.25 2.25,12.25 2.25,12.25 C2.25,12.25 2.25,2.25 2.25,2.25 C2.25,2.25 3.75,2.25 3.75,2.25 C3.75,2.25 12.75,2.25 12.75,2.25 C12.75,2.25 14.25,2.25 14.25,2.25 C14.25,2.25 14.25,12.25 14.25,12.25c " />
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_1_G_N_5_T_1"
+                    android:translateX="12"
+                    android:translateY="15">
+                    <group
+                        android:name="_R_G_L_1_G_N_5_T_0"
+                        android:translateX="-8.25"
+                        android:translateY="-7.25">
+                        <group
+                            android:name="_R_G_L_1_G"
+                            android:pivotX="2.25"
+                            android:pivotY="2.25"
+                            android:scaleX="1"
+                            android:scaleY="1"
+                            android:translateX="6"
+                            android:translateY="5">
+                            <path
+                                android:name="_R_G_L_1_G_D_0_P_0"
+                                android:fillAlpha="1"
+                                android:fillColor="?attr/textColor"
+                                android:fillType="nonZero"
+                                android:pathData=" M2.25 0.25 C3.35,0.25 4.25,1.15 4.25,2.25 C4.25,3.35 3.35,4.25 2.25,4.25 C1.15,4.25 0.25,3.35 0.25,2.25 C0.25,1.15 1.15,0.25 2.25,0.25c " />
+                        </group>
+                    </group>
+                </group>
+                <group
+                    android:name="_R_G_L_0_G_N_5_T_1"
+                    android:translateX="12"
+                    android:translateY="15">
+                    <group
+                        android:name="_R_G_L_0_G_N_5_T_0"
+                        android:translateX="-8.25"
+                        android:translateY="-7.25">
+                        <group
+                            android:name="_R_G_L_0_G"
+                            android:pivotX="27.965"
+                            android:pivotY="-32"
+                            android:scaleX="0.125"
+                            android:scaleY="0.125"
+                            android:translateX="-16.219"
+                            android:translateY="32.25">
+                            <path
+                                android:name="_R_G_L_0_G_D_0_P_0"
+                                android:fillAlpha="0"
+                                android:fillColor="#ff0000"
+                                android:fillType="nonZero"
+                                android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 " />
+                            <path
+                                android:name="_R_G_L_0_G_D_1_P_0"
+                                android:pathData=" M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                                android:strokeWidth="16"
+                                android:strokeAlpha="1"
+                                android:strokeColor="?attr/textColor"/>
+                        </group>
+                    </group>
+                </group>
+            </group>
+            <group android:name="time_group" />
+        </vector>
+    </aapt:attr>
+    <target android:name="_R_G_L_2_G_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,15C 12,14.85416667163372 12,14.125 12,14.125"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,14.125C 12,14.125 12,15.05870145463943 12,15.324"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="133">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="100"
+                    android:pathData="M 12,15.324C 12,15.40252217555046 12,14.96669441461563 12,15"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="267">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="100"
+                    android:propertyName="scaleX"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.85"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="100"
+                    android:propertyName="scaleY"
+                    android:startOffset="0"
+                    android:valueFrom="1"
+                    android:valueTo="0.85"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="283"
+                    android:propertyName="scaleX"
+                    android:startOffset="100"
+                    android:valueFrom="0.85"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="283"
+                    android:propertyName="scaleY"
+                    android:startOffset="100"
+                    android:valueFrom="0.85"
+                    android:valueTo="1"
+                    android:valueType="floatType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.4,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_N_5_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,15C 12,14.85416667163372 12,14.125 12,14.125"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,14.125C 12,14.125 12,15.05870145463943 12,15.324"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="133">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="100"
+                    android:pathData="M 12,15.324C 12,15.40252217555046 12,14.96669441461563 12,15"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="267">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueTo="M-27.97 -48.55 C-27.97,-48.55 -28,-53.75 -27.97,-55.48 C-27.92,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.353,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="333"
+                    android:propertyName="pathData"
+                    android:startOffset="67"
+                    android:valueFrom="M-27.97 -48.55 C-27.97,-48.55 -28,-53.75 -27.97,-55.48 C-27.92,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueTo="M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.542,0 0.026,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_1_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="67"
+                    android:propertyName="pathData"
+                    android:startOffset="0"
+                    android:valueFrom="M-28.21 -31.92 C-28.21,-31.92 -27.85,-48.38 -27.97,-55.48 C-28,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueTo="M-27.97 -48.55 C-27.97,-48.55 -28,-53.75 -27.97,-55.48 C-27.92,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.353,0 0.2,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="333"
+                    android:propertyName="pathData"
+                    android:startOffset="67"
+                    android:valueFrom="M-27.97 -48.55 C-27.97,-48.55 -28,-53.75 -27.97,-55.48 C-27.92,-57.63 -23.5,-79.87 -0.75,-79.82 C22.77,-79.76 27.75,-59.37 27.72,-58.27 C27.55,-52.88 27.97,-31.67 27.97,-31.67 "
+                    android:valueTo="M79.79 -48.55 C79.79,-48.55 79.75,-53.75 79.78,-55.48 C79.83,-57.62 79.08,-78.36 53.07,-78.83 C29.5,-79.25 25.2,-59.38 25.22,-58.27 C25.25,-56.25 24.97,-31.17 24.97,-31.17 "
+                    android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.542,0 0.026,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_N_5_T_1">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,15C 12,14.85416667163372 12,14.125 12,14.125"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="0">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="133"
+                    android:pathData="M 12,14.125C 12,14.125 12,15.05870145463943 12,15.324"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="133">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+                <objectAnimator
+                    android:duration="100"
+                    android:pathData="M 12,15.324C 12,15.40252217555046 12,14.96669441461563 12,15"
+                    android:propertyName="translateXY"
+                    android:propertyXName="translateX"
+                    android:propertyYName="translateY"
+                    android:startOffset="267">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.333,0 0.667,1 1.0,1.0" />
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="time_group">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator
+                    android:duration="717"
+                    android:propertyName="translateX"
+                    android:startOffset="0"
+                    android:valueFrom="0"
+                    android:valueTo="1"
+                    android:valueType="floatType" />
+            </set>
+        </aapt:attr>
+    </target>
+</animated-vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/chooser_content_preview_rounded.xml b/core/res/res/drawable/chooser_content_preview_rounded.xml
new file mode 100644
index 0000000..7d85738
--- /dev/null
+++ b/core/res/res/drawable/chooser_content_preview_rounded.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+    android:shape="rectangle">
+
+    <stroke
+        android:width="1dp"
+        android:color="#ccc" />
+ 
+    <corners android:radius="@dimen/chooser_corner_radius" />
+
+    <padding
+        android:left="16dp"
+        android:top="12dp"
+        android:right="16dp"
+        android:bottom="12dp"/>
+</shape>
diff --git a/core/res/res/drawable/ic_auth_error.xml b/core/res/res/drawable/ic_auth_error.xml
new file mode 100644
index 0000000..ea5f572
--- /dev/null
+++ b/core/res/res/drawable/ic_auth_error.xml
@@ -0,0 +1,23 @@
+<!--
+     Copyright (C) 2019 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 android:height="24dp" android:viewportHeight="60"
+        android:viewportWidth="60" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
+    <path android:fillColor="?attr/colorError" android:pathData="M28.8,37.5l2.4,0l0,2.5l-2.4,0z"/>
+    <path android:fillColor="?attr/colorError" android:pathData="M28.8,17.5l2.4,0l0,15l-2.4,0z"/>
+    <path android:fillColor="#00000000"
+          android:pathData="M30,6.2c-13.1,0 -23.7,10.6 -23.7,23.8S16.9,53.8 30,53.8c13.1,0 23.8,-10.6 23.8,-23.8S43.1,6.2 30,6.2z"
+          android:strokeColor="?android:attr/colorError" android:strokeWidth="2.5"/>
+</vector>
diff --git a/core/res/res/drawable/ic_content_copy_gm2.xml b/core/res/res/drawable/ic_content_copy_gm2.xml
new file mode 100644
index 0000000..940da94
--- /dev/null
+++ b/core/res/res/drawable/ic_content_copy_gm2.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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"
+    android:viewportHeight="24">
+  <path
+      android:fillColor="#F999"
+      android:pathData="M18,21L4,21L4,7L2,7v14c0,1.1 0.9,2 2,2h14v-2zM21,17L21,3c0,-1.1 -0.9,-2 -2,-2L8,1c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h11c1.1,0 2,-0.9 2,-2zM19,17L8,17L8,3h11v14z"/>
+</vector>
diff --git a/core/res/res/drawable/ic_lock_24dp.xml b/core/res/res/drawable/ic_lock_24dp.xml
new file mode 100644
index 0000000..d848426
--- /dev/null
+++ b/core/res/res/drawable/ic_lock_24dp.xml
@@ -0,0 +1,30 @@
+<!--
+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="24.0dp"
+        android:height="24.0dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0">
+    <path
+        android:fillColor="?attr/textColor"
+        android:pathData="M12.0,15.0m-2.0,0.0a2.0,2.0 0.0,1.0 1.0,4.0 0.0a2.0,2.0 0.0,1.0 1.0,-4.0 0.0"/>
+    <path
+        android:pathData="M0,0h24v24H0V0z"
+        android:fillColor="#00000000"/>
+    <path
+        android:fillColor="?attr/textColor"
+        android:pathData="M18.0,8.0l-1.5,0.0L16.5,5.5C16.5,3.01 14.49,1.0 12.0,1.0S7.5,3.01 7.5,5.5L7.5,8.0L6.0,8.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,10.0c0.0,1.1 0.9,2.0 2.0,2.0l12.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L20.0,10.0C20.0,8.9 19.1,8.0 18.0,8.0zM9.5,5.5C9.5,4.12 10.62,3.0 12.0,3.0c1.38,0.0 2.5,1.12 2.5,2.5L14.5,8.0l-5.0,0.0L9.5,5.5zM18.0,20.0L6.0,20.0L6.0,10.0l1.5,0.0l9.0,0.0L18.0,10.0L18.0,20.0z"/>
+</vector>
diff --git a/core/res/res/drawable/ic_lock_open_24dp.xml b/core/res/res/drawable/ic_lock_open_24dp.xml
new file mode 100644
index 0000000..94eecad
--- /dev/null
+++ b/core/res/res/drawable/ic_lock_open_24dp.xml
@@ -0,0 +1,30 @@
+<!--
+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="24.0dp"
+        android:height="24.0dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0">
+    <path
+        android:fillColor="?attr/textColor"
+        android:pathData="M12.0,15.0m-2.0,0.0a2.0,2.0 0.0,1.0 1.0,4.0 0.0a2.0,2.0 0.0,1.0 1.0,-4.0 0.0"/>
+    <path
+        android:fillColor="?attr/textColor"
+        android:pathData="M18.5,1.0C16.01,1.0 14.0,3.01 14.0,5.5L14.0,8.0L6.0,8.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,10.0c0.0,1.1 0.9,2.0 2.0,2.0l12.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L20.0,10.0c0.0,-1.1 -0.9,-2.0 -2.0,-2.0l-2.0,0.0L16.0,5.5C16.0,4.12 17.12,3.0 18.5,3.0C19.88,3.0 21.0,4.12 21.0,5.5L21.0,6.0l2.0,0.0L23.0,5.5C23.0,3.01 20.99,1.0 18.5,1.0zM18.0,10.0l0.0,10.0L6.0,20.0L6.0,10.0L18.0,10.0z"/>
+    <path
+        android:pathData="M0,0h24v24H0V0z"
+        android:fillColor="#00000000"/>
+</vector>
diff --git a/core/res/res/layout/chooser_grid.xml b/core/res/res/layout/chooser_grid.xml
index c42f43a..a24f920 100644
--- a/core/res/res/layout/chooser_grid.xml
+++ b/core/res/res/layout/chooser_grid.xml
@@ -17,19 +17,19 @@
 */
 -->
 <com.android.internal.widget.ResolverDrawerLayout
-        xmlns:android="http://schemas.android.com/apk/res/android"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:maxWidth="@dimen/resolver_max_width"
-        android:maxCollapsedHeight="288dp"
-        android:maxCollapsedHeightSmall="56dp"
-        android:id="@id/contentPanel">
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:maxWidth="@dimen/resolver_max_width"
+    android:maxCollapsedHeight="288dp"
+    android:maxCollapsedHeightSmall="56dp"
+    android:id="@id/contentPanel">
 
     <RelativeLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_alwaysShow="true"
-            android:background="?attr/colorBackgroundFloating" >
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alwaysShow="true"
+        android:background="?attr/colorBackgroundFloating">
         <TextView android:id="@+id/profile_button"
                   android:layout_width="wrap_content"
                   android:layout_height="48dp"
@@ -51,73 +51,98 @@
                   android:textAppearance="?attr/textAppearanceMedium"
                   android:textSize="20sp"
                   android:gravity="center"
-                  android:paddingEnd="?attr/dialogPreferredPadding"
-                  android:paddingTop="12dp"
-                  android:paddingBottom="6dp"
+                  android:paddingTop="18dp"
+                  android:paddingBottom="18dp"
+                  android:paddingLeft="24dp"
+                  android:paddingRight="24dp"
                   android:layout_below="@id/profile_button"
                   android:layout_centerHorizontal="true"/>
     </RelativeLayout>
 
-    <RelativeLayout 
+    <LinearLayout
         android:id="@+id/content_preview"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
+        android:orientation="vertical"
+        android:paddingBottom="@dimen/chooser_view_spacing"
         android:background="?attr/colorBackgroundFloating">
-      
-      <view class="com.android.internal.app.ChooserActivity$RoundedRectImageView"
-            android:id="@+id/content_preview_thumbnail"
-            android:layout_alignParentTop="true"
-            android:layout_width="100dp"
+
+        <LinearLayout
+            android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:layout_alignParentStart="true"
-            android:gravity="center"
-            android:adjustViewBounds="true"
-            android:maxWidth="90dp"
-            android:maxHeight="90dp"
-            android:scaleType="fitCenter"
-            android:padding="5dp"/>
+            android:orientation="horizontal"
+            android:paddingLeft="@dimen/chooser_edge_margin_normal"
+            android:paddingRight="@dimen/chooser_edge_margin_normal"
+            android:layout_marginBottom="@dimen/chooser_view_spacing"
+            android:id="@+id/content_preview_text_layout">
+            <TextView
+                android:id="@+id/content_preview_text"
+                android:layout_width="0dp"
+                android:layout_weight="1"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center_vertical"
+                android:ellipsize="end"
+                android:gravity="start|top"
+                android:paddingRight="24dp"
+                android:maxLines="2"/>
+            <Button
+                android:id="@+id/copy_button"
+                android:layout_width="24dp"
+                android:layout_height="24dp"
+                android:gravity="center"
+                android:layout_gravity="center_vertical"
+                android:background="@drawable/ic_content_copy_gm2"/>
+        </LinearLayout>
 
-      <TextView
-          android:id="@+id/content_preview_title"
-          android:layout_alignParentTop="true"
-          android:layout_toEndOf="@id/content_preview_thumbnail"
-          android:layout_width="match_parent"
-          android:layout_height="wrap_content"
-          android:gravity="start|top"
-          android:textAppearance="?attr/textAppearanceMedium"
-          android:maxLines="2"
-          android:ellipsize="end"
-          android:paddingStart="15dp"
-          android:paddingEnd="15dp"
-          android:paddingTop="10dp" />
+        <!-- Required sub-layout so we can get the nice rounded corners-->
+        <!-- around this section -->
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal"
+            android:layout_marginLeft="@dimen/chooser_edge_margin_thin"
+            android:layout_marginRight="@dimen/chooser_edge_margin_thin"
+            android:minHeight="80dp"
+            android:background="@drawable/chooser_content_preview_rounded"
+            android:id="@+id/content_preview_title_layout">
 
-      <TextView
-          android:id="@+id/content_preview_text"
-          android:layout_width="match_parent"
-          android:layout_height="wrap_content"
-          android:layout_below="@id/content_preview_title"
-          android:layout_toEndOf="@id/content_preview_thumbnail"
-          android:gravity="start|top"
-          android:maxLines="2"
-          android:ellipsize="end"
-          android:paddingStart="15dp"
-          android:paddingEnd="15dp"
-          android:paddingTop="10dp"
-          android:paddingBottom="5dp"/>
-    </RelativeLayout>
+            <view class="com.android.internal.app.ChooserActivity$RoundedRectImageView"
+                  android:id="@+id/content_preview_thumbnail"
+                  android:layout_width="80dp"
+                  android:layout_height="80dp"
+                  android:layout_marginRight="12dp"
+                  android:adjustViewBounds="true"
+                  android:layout_gravity="center_vertical"
+                  android:gravity="center"
+                  android:maxWidth="70dp"
+                  android:maxHeight="70dp"
+                  android:padding="5dp"
+                  android:scaleType="centerCrop"/>
+
+            <TextView
+                android:id="@+id/content_preview_title"
+                android:layout_width="0dp"
+                android:layout_weight="1"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center_vertical"
+                android:ellipsize="end"
+                android:maxLines="2"
+                android:textAppearance="?attr/textAppearanceMedium"/>
+        </LinearLayout>
+    </LinearLayout>
 
     <ListView
-            android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:id="@+id/resolver_list"
-            android:clipToPadding="false"
-            android:scrollbarStyle="outsideOverlay"
-            android:background="?attr/colorBackgroundFloating"
-            android:elevation="8dp"
-            android:listSelector="@color/transparent"
-            android:divider="@null"
-            android:scrollIndicators="top"
-            android:nestedScrollingEnabled="true" />
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:id="@+id/resolver_list"
+        android:clipToPadding="false"
+        android:scrollbarStyle="outsideOverlay"
+        android:background="?attr/colorBackgroundFloating"
+        android:elevation="8dp"
+        android:listSelector="@color/transparent"
+        android:divider="@null"
+        android:scrollIndicators="top"
+        android:nestedScrollingEnabled="true"/>
 
     <TextView android:id="@+id/empty"
               android:layout_width="match_parent"
@@ -127,6 +152,6 @@
               android:text="@string/noApplications"
               android:padding="32dp"
               android:gravity="center"
-              android:visibility="gone" />
+              android:visibility="gone"/>
 
 </com.android.internal.widget.ResolverDrawerLayout>
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 1eece03..759fc12 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -280,6 +280,9 @@
         <!-- Additional flag from base permission type: this permission designates the app
             that will approve the sharing of incident reports. -->
         <flag name="incidentReportApprover" value="0x100000" />
+        <!-- Additional flag from base permission type: this permission can be automatically
+            granted to the system app predictor -->
+        <flag name="appPredictor" value="0x200000" />
     </attr>
 
     <!-- Flags indicating more context for a permission group. -->
@@ -1138,10 +1141,12 @@
          resource] to be present in order to function. Default value is false. -->
     <attr name="isSplitRequired" format="boolean" />
 
-    <!-- Flag to specify if this app prioritizes code integrity. The system may choose
-         to run with better integrity guarantee in various components if possible based on the app's
-         <code>targetSdkVersion</code>. -->
-    <attr name="preferCodeIntegrity" format="boolean" />
+    <!-- Flag to specify if this app wants to run the dex within its APK but not extracted or
+         locally compiled variants. This keeps the dex code protected by the APK signature. Such
+         apps will always run in JIT mode (same when they are first installed), and the system will
+         never generate ahead-of-time compiled code for them. Depending on the app's workload,
+         there may be some run time performance change, noteably the cold start time. -->
+    <attr name="useEmbeddedDex" format="boolean" />
 
     <!-- Extra options for an activity's UI. Applies to either the {@code <activity>} or
          {@code <application>} tag. If specified on the {@code <application>}
@@ -1445,26 +1450,20 @@
 
     <attr name="usesNonSdkApi" format="boolean" />
 
-    <!-- Specify the type of foreground service. Apps targeting API
-     {@link android.os.Build.VERSION_CODES#Q} or later must specify foreground service type,
-     otherwise a SecurityException is thrown when
-     {@link android.app.Service#startForeground(int, Notification)} on this service is called.
-    -->
+    <!-- Specify the type of foreground service. Multiple types can be specified by ORing the flags
+         together. -->
     <attr name="foregroundServiceType">
         <!-- Data (photo, file, account) upload/download, backup/restore, import/export, fetch,
         transfer over network between device and cloud.  -->
-        <enum name="sync" value="1" />
+        <flag name="dataSync" value="0x01" />
         <!-- Music, video, news or other media play. -->
-        <enum name="mediaPlay" value="2" />
+        <flag name="mediaPlayback" value="0x02" />
         <!-- Ongoing phone call or video conference. -->
-        <enum name="phoneCall" value="3" />
+        <flag name="phoneCall" value="0x04" />
         <!-- GPS, map, navigation location update. -->
-        <enum name="location" value="4" />
+        <flag name="location" value="0x08" />
         <!-- Auto, bluetooth, TV or other devices connection, monitoring and interaction. -->
-        <enum name="deviceCompanion" value="5" />
-        <!-- Process that should not be interrupted, including installation, setup, photo
-        compression etc. -->
-        <enum name="ongoingProcess" value="6" />
+        <flag name="connectedDevice" value="0x10" />
     </attr>
 
 
@@ -1611,7 +1610,7 @@
              to honor this flag as well. -->
         <attr name="usesCleartextTraffic" />
         <attr name="multiArch" />
-        <attr name="preferCodeIntegrity" />
+        <attr name="useEmbeddedDex" />
         <attr name="extractNativeLibs" />
         <attr name="defaultToDeviceProtectedStorage" format="boolean" />
         <attr name="directBootAware" />
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index eb214ba..df20f85 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -1025,7 +1025,8 @@
     <integer name="config_displayWhiteBalanceColorTemperatureDefault">6500</integer>
 
     <!-- The display primaries, in CIE1931 XYZ color space, for display
-         white balance to use in its calculations. -->
+         white balance to use in its calculations. The array must include a total of 12 float
+         values: 3 values per color (X, Y, Z) and 4 colors (R, G, B, W) -->
     <string-array name="config_displayWhiteBalanceDisplayPrimaries">
         <!-- Red X -->   <item>0.412315</item>
         <!-- Red Y -->   <item>0.212600</item>
@@ -1043,7 +1044,7 @@
 
     <!-- The nominal white coordinates, in CIE1931 XYZ color space, for Display White Balance to
          use in its calculations. AWB will adapt this white point to the target ambient white
-         point. -->
+         point. The array must include a total of 3 float values (X, Y, Z) -->
     <string-array name="config_displayWhiteBalanceDisplayNominalWhite">
         <!-- Nominal White X --> <item>0.950456</item>
         <!-- Nominal White Y --> <item>1.000000</item>
@@ -3781,4 +3782,105 @@
 
     <!-- Whether or not aware is enabled by default -->
     <bool name="config_awareSettingAvailable">false</bool>
+
+    <!-- Display White-Balance -->
+
+    <!-- See AmbientSensor.AmbientBrightnessSensor.
+         The ambient brightness sensor rate (in milliseconds). Must be positive. -->
+    <integer name="config_displayWhiteBalanceBrightnessSensorRate">250</integer>
+
+    <!-- See AmbientFilter.
+         How long ambient brightness changes are kept and taken into consideration
+         (in milliseconds). Must be positive. -->
+    <integer name="config_displayWhiteBalanceBrightnessFilterHorizon">10000</integer>
+
+    <!-- See AmbientFilter.WeightedMovingAverageAmbientFilter.
+         Recent changes are prioritised by integrating their duration over y = x + intercept
+         (the higher it is, the less prioritised recent changes are). Must be a non-negative
+         number, or NaN to avoid this implementation. -->
+    <item name="config_displayWhiteBalanceBrightnessFilterIntercept" format="float" type="dimen">10.0</item>
+
+    <!-- See AmbientSensor.AmbientColorTemperatureSensor.
+         The ambient color temperature sensor name. -->
+    <string name="config_displayWhiteBalanceColorTemperatureSensorName">com.google.sensor.color</string>
+
+    <!-- See AmbientSensor.AmbientColorTemperatureSensor.
+         The ambient color temperature sensor rate (in milliseconds). Must be positive. -->
+    <integer name="config_displayWhiteBalanceColorTemperatureSensorRate">250</integer>
+
+    <!-- See AmbientFilter.
+         How long ambient color temperature changes are kept and taken into consideration
+         (in milliseconds). Must be positive. -->
+    <integer name="config_displayWhiteBalanceColorTemperatureFilterHorizon">10000</integer>
+
+    <!-- See AmbientFilter.WeightedMovingAverageAmbientFilter.
+         Recent changes are prioritised by integrating their duration over y = x + intercept
+         (the higher it is, the less prioritised recent changes are). Must be a non-negative
+         number, or NaN to avoid this implementation. -->
+    <item name="config_displayWhiteBalanceColorTemperatureFilterIntercept" format="float"
+            type="dimen">10.0</item>
+
+    <!-- See DisplayWhiteBalanceThrottler.
+         The debounce time (in milliseconds) for increasing the screen color temperature, throttled
+         if time > lastTime + debounce. Must be non-negative. -->
+    <integer name="config_displayWhiteBalanceIncreaseDebounce">5000</integer>
+
+    <!-- See DisplayWhiteBalanceThrottler.
+         The debounce time (in milliseconds) for decreasing the screen color tempearture, throttled
+         if time < lastTime - debounce. Must be non-negative. -->
+    <integer name="config_displayWhiteBalanceDecreaseDebounce">5000</integer>
+
+    <!-- See DisplayWhiteBalanceThrottler.
+         The ambient color temperature values used to determine the threshold as the corresponding
+         value in config_displayWhiteBalance{Increase,Decrease}Threholds. Must be non-empty, the
+         same length as config_displayWhiteBalance{Increase,Decrease}Thresholds, and contain
+         non-negative, strictly increasing numbers.
+
+         For example, if:
+
+         - baseThresolds = [0, 100, 1000];
+         - increaseThresholds = [0.1, 0.15, 0.2];
+         - decreaseThresholds = [0.1, 0.05, 0.0];
+
+         Then, given the ambient color temperature INCREASED from X to Y (so X < Y):
+         - If 0 <= Y < 100, we require Y > (1 + 0.1) * X = 1.1X;
+         - If 100 <= Y < 1000, we require Y > (1 + 0.15) * X = 1.15X;
+         - If 1000 <= Y, we require Y > (1 + 0.2) * X = 1.2X.
+
+         Or, if the ambient color temperature DECREASED from X to Y (so X > Y):
+         - If 0 <= Y < 100, we require Y < (1 - 0.1) * X = 0.9X;
+         - If 100 <= Y < 1000, we require Y < (1 - 0.05) * X = 0.95X;
+         - If 1000 <= Y, we require Y < (1 - 0) * X = X.
+
+         NOTE: the numbers in this example are made up, and don't represent how actual base,
+               increase or decrease thresholds would look like. -->
+    <array name="config_displayWhiteBalanceBaseThresholds">
+        <item>0.0</item>
+    </array>
+
+    <!-- See DisplayWhiteBalanceThrottler.
+         The increase threshold values, throttled if value < value * (1 + threshold). Must be
+         non-empty, the same length as config_displayWhiteBalanceBaseThresholds, and contain
+         non-negative numbers. -->
+    <array name="config_displayWhiteBalanceIncreaseThresholds">
+        <item>0.1</item>
+    </array>
+
+    <!-- See DisplayWhiteBalanceThrottler.
+         The decrease threshold values, throttled if value > value * (1 - threshold). Must be
+         non-empty, the same length as config_displayWhiteBalanceBaseThresholds, and contain
+         non-negative numbers. -->
+    <array name="config_displayWhiteBalanceDecreaseThresholds">
+        <item>0.1</item>
+    </array>
+
+    <!-- See DisplayWhiteBalanceController.
+         The ambient brightness threshold (in lux) beneath which we fall back to a fixed ambient
+         color temperature. -->
+    <item name="config_displayWhiteBalanceLowLightAmbientBrightnessThreshold" format="float" type="dimen">10.0</item>
+
+    <!-- See DisplayWhiteBalanceController.
+         The ambient color temperature (in cct) to which we fall back when the ambient brightness
+         drops beneath a certain threshold. -->
+    <item name="config_displayWhiteBalanceLowLightAmbientColorTemperature" format="float" type="dimen">6500.0</item>
 </resources>
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index baf7587..38367fb 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -715,6 +715,9 @@
     <!-- Line spacing modifier for the message field of the harmful app dialog -->
     <item name="harmful_app_message_line_spacing_modifier" type="dimen">1.22</item>
 
-    <!-- chooser corner radius -->
-    <dimen name="chooser_corner_radius">4dp</dimen>
+    <!-- chooser (sharesheet) spacing -->
+    <dimen name="chooser_corner_radius">8dp</dimen>
+    <dimen name="chooser_view_spacing">18dp</dimen>
+    <dimen name="chooser_edge_margin_thin">16dp</dimen>
+    <dimen name="chooser_edge_margin_normal">24dp</dimen>
 </resources>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index b5266e2..e7d8102 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2937,6 +2937,7 @@
         <!-- @hide @SystemApi -->
         <public name="inheritShowWhenLocked" />
         <public name="zygotePreloadName" />
+        <public name="useEmbeddedDex" />
     </public-group>
 
     <public-group type="drawable" first-id="0x010800b4">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 04df97c..fadb28f 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -2645,6 +2645,9 @@
     <!-- Displayed to the user to confirm that they have copied text from a web page to the clipboard. -->
     <string name="text_copied">Text copied to clipboard.</string>
 
+    <!-- Displayed to the user to confirm that they have copied text/images to the clipboard [CHAR LIMIT=NONE] -->
+    <string name="copied">Copied</string>
+
     <!-- Menu item displayed at the end of a menu to allow users to see another page worth of menu items. This is shown on any app's menu as long as the app has too many items in the menu.-->
     <string name="more_item_label">More</string>
     <!-- Prepended to the shortcut for a menu item to indicate that the user should hold the MENU button together with the shortcut to invoke the item. For example, if the shortcut to open a new tab in browser is MENU and B together, then this would be prepended to the letter "B" -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 52400de..c909873 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -53,7 +53,10 @@
   <java-symbol type="id" name="content_preview" />
   <java-symbol type="id" name="content_preview_thumbnail" />
   <java-symbol type="id" name="content_preview_text" />
+  <java-symbol type="id" name="content_preview_text_layout" />
   <java-symbol type="id" name="content_preview_title" />
+  <java-symbol type="id" name="content_preview_title_layout" />
+  <java-symbol type="id" name="copy_button" />
   <java-symbol type="id" name="current_scene" />
   <java-symbol type="id" name="scene_layoutid_cache" />
   <java-symbol type="id" name="customPanel" />
@@ -545,6 +548,7 @@
   <java-symbol type="string" name="activity_resolver_work_profiles_support" />
   <java-symbol type="string" name="app_running_notification_title" />
   <java-symbol type="string" name="app_running_notification_text" />
+  <java-symbol type="string" name="copied" />
   <java-symbol type="string" name="delete" />
   <java-symbol type="string" name="deleteText" />
   <java-symbol type="string" name="grant_permissions_header_text" />
@@ -1354,6 +1358,9 @@
   <java-symbol type="drawable" name="ic_text_dot" />
   <java-symbol type="drawable" name="ic_print" />
   <java-symbol type="drawable" name="ic_print_error" />
+  <java-symbol type="drawable" name="ic_lock_24dp" />
+  <java-symbol type="drawable" name="ic_lock_open_24dp" />
+  <java-symbol type="drawable" name="ic_auth_error" />
   <java-symbol type="drawable" name="jog_dial_arrow_long_left_green" />
   <java-symbol type="drawable" name="jog_dial_arrow_long_right_red" />
   <java-symbol type="drawable" name="jog_dial_arrow_short_left_and_right" />
@@ -2215,6 +2222,10 @@
   <java-symbol type="anim" name="lock_screen_wallpaper_exit" />
   <java-symbol type="anim" name="launch_task_behind_source" />
   <java-symbol type="anim" name="wallpaper_open_exit" />
+  <java-symbol type="anim" name="lock_to_error" />
+  <java-symbol type="anim" name="lock_lock" />
+  <java-symbol type="anim" name="lock_unlock" />
+  <java-symbol type="anim" name="lock_in" />
 
   <java-symbol type="bool" name="config_alwaysUseCdmaRssi" />
   <java-symbol type="dimen" name="status_bar_icon_size" />
@@ -2711,6 +2722,9 @@
   <java-symbol type="id" name="month_view" />
   <java-symbol type="integer" name="config_zen_repeat_callers_threshold" />
   <java-symbol type="dimen" name="chooser_corner_radius" />
+  <java-symbol type="dimen" name="chooser_view_spacing" />
+  <java-symbol type="dimen" name="chooser_edge_margin_thin" />
+  <java-symbol type="dimen" name="chooser_edge_margin_normal" />
   <java-symbol type="layout" name="chooser_grid" />
   <java-symbol type="layout" name="resolve_grid_item" />
   <java-symbol type="id" name="day_picker_view_pager" />
@@ -3591,4 +3605,20 @@
   <java-symbol type="integer" name="config_attentionApiTimeout" />
 
   <java-symbol type="string" name="config_incidentReportApproverPackage" />
+
+  <!-- Display White-Balance -->
+  <java-symbol type="integer" name="config_displayWhiteBalanceBrightnessSensorRate" />
+  <java-symbol type="integer" name="config_displayWhiteBalanceBrightnessFilterHorizon" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceBrightnessFilterIntercept" />
+  <java-symbol type="string" name="config_displayWhiteBalanceColorTemperatureSensorName" />
+  <java-symbol type="integer" name="config_displayWhiteBalanceColorTemperatureSensorRate" />
+  <java-symbol type="integer" name="config_displayWhiteBalanceColorTemperatureFilterHorizon" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceColorTemperatureFilterIntercept" />
+  <java-symbol type="integer" name="config_displayWhiteBalanceIncreaseDebounce" />
+  <java-symbol type="integer" name="config_displayWhiteBalanceDecreaseDebounce" />
+  <java-symbol type="array" name="config_displayWhiteBalanceBaseThresholds" />
+  <java-symbol type="array" name="config_displayWhiteBalanceIncreaseThresholds" />
+  <java-symbol type="array" name="config_displayWhiteBalanceDecreaseThresholds" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientBrightnessThreshold" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientColorTemperature" />
 </resources>
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 268bb81..1764249 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -59,6 +59,7 @@
     <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
     <uses-permission android:name="android.permission.READ_DREAM_STATE" />
     <uses-permission android:name="android.permission.WRITE_DREAM_STATE" />
+    <uses-permission android:name="android.permission.READ_CLIPBOARD_IN_BACKGROUND" />
     <uses-permission android:name="android.permission.READ_LOGS"/>
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.READ_SMS"/>
diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
index bdf3aa2..a5ea441 100644
--- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
@@ -465,12 +465,12 @@
 
         @Override
         public void scheduleCreateBackupAgent(ApplicationInfo applicationInfo,
-                CompatibilityInfo compatibilityInfo, int i) throws RemoteException {
+                CompatibilityInfo compatibilityInfo, int i, int userId) throws RemoteException {
         }
 
         @Override
         public void scheduleDestroyBackupAgent(ApplicationInfo applicationInfo,
-                CompatibilityInfo compatibilityInfo) throws RemoteException {
+                CompatibilityInfo compatibilityInfo, int userId) throws RemoteException {
         }
 
         @Override
diff --git a/core/tests/coretests/src/android/graphics/BitmapTest.java b/core/tests/coretests/src/android/graphics/BitmapTest.java
index e79d2ae..d2a1dd9 100644
--- a/core/tests/coretests/src/android/graphics/BitmapTest.java
+++ b/core/tests/coretests/src/android/graphics/BitmapTest.java
@@ -16,6 +16,8 @@
 
 package android.graphics;
 
+import android.hardware.HardwareBuffer;
+
 import androidx.test.filters.SmallTest;
 
 import junit.framework.TestCase;
@@ -233,14 +235,31 @@
     }
 
     @SmallTest
-    public void testCreateHardwareBitmapFromGraphicBuffer() {
+    public void testWrapHardwareBufferWithSrgbColorSpace() {
         GraphicBuffer buffer = GraphicBuffer.create(10, 10, PixelFormat.RGBA_8888,
                 GraphicBuffer.USAGE_HW_TEXTURE | GraphicBuffer.USAGE_SOFTWARE_MASK);
         Canvas canvas = buffer.lockCanvas();
         canvas.drawColor(Color.YELLOW);
         buffer.unlockCanvasAndPost(canvas);
-        Bitmap hardwareBitmap = Bitmap.createHardwareBitmap(buffer);
+        Bitmap hardwareBitmap =
+                Bitmap.wrapHardwareBuffer(HardwareBuffer.createFromGraphicBuffer(buffer), null);
         assertTrue(hardwareBitmap.isPremultiplied());
         assertFalse(hardwareBitmap.isMutable());
+        assertEquals(ColorSpace.get(ColorSpace.Named.SRGB), hardwareBitmap.getColorSpace());
+    }
+
+    @SmallTest
+    public void testWrapHardwareBufferWithDisplayP3ColorSpace() {
+        GraphicBuffer buffer = GraphicBuffer.create(10, 10, PixelFormat.RGBA_8888,
+                GraphicBuffer.USAGE_HW_TEXTURE | GraphicBuffer.USAGE_SOFTWARE_MASK);
+        Canvas canvas = buffer.lockCanvas();
+        canvas.drawColor(Color.YELLOW);
+        buffer.unlockCanvasAndPost(canvas);
+        Bitmap hardwareBitmap = Bitmap.wrapHardwareBuffer(
+                HardwareBuffer.createFromGraphicBuffer(buffer),
+                ColorSpace.get(ColorSpace.Named.DISPLAY_P3));
+        assertTrue(hardwareBitmap.isPremultiplied());
+        assertFalse(hardwareBitmap.isMutable());
+        assertEquals(ColorSpace.get(ColorSpace.Named.DISPLAY_P3), hardwareBitmap.getColorSpace());
     }
 }
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index f420033..2cb925a 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -297,6 +297,7 @@
                     Settings.Global.INTENT_FIREWALL_UPDATE_METADATA_URL,
                     Settings.Global.JOB_SCHEDULER_CONSTANTS,
                     Settings.Global.KEEP_PROFILE_IN_BACKGROUND,
+                    Settings.Global.KERNEL_CPU_THREAD_READER,
                     Settings.Global.LANG_ID_UPDATE_CONTENT_URL,
                     Settings.Global.LANG_ID_UPDATE_METADATA_URL,
                     Settings.Global.LAST_ACTIVE_USER_ID,
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
index 21fcae7..6b9e69c 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
@@ -34,6 +34,9 @@
 
 import android.app.usage.UsageStatsManager;
 import android.content.ClipData;
+import android.content.ClipDescription;
+import android.content.ClipboardManager;
+import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ResolveInfo;
 import android.graphics.Bitmap;
@@ -392,6 +395,32 @@
         assertThat(chosen[0], is(toChoose));
     }
 
+    @Test
+    public void copyTextToClipboard() throws Exception {
+        Intent sendIntent = createSendTextIntent();
+        List<ResolvedComponentInfo> resolvedComponentInfos =
+                createResolvedComponentsForTestWithOtherProfile(1);
+
+        when(ChooserWrapperActivity.sOverrides.resolverListController.getResolversForIntent(
+                Mockito.anyBoolean(),
+                Mockito.anyBoolean(),
+                Mockito.isA(List.class))).thenReturn(resolvedComponentInfos);
+
+        final ChooserWrapperActivity activity = mActivityRule
+                .launchActivity(Intent.createChooser(sendIntent, null));
+        waitForIdle();
+
+        onView(withId(R.id.copy_button)).perform(click());
+
+        ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(
+                Context.CLIPBOARD_SERVICE);
+        ClipData clipData = clipboard.getPrimaryClip();
+        assertThat("testing intent sending", is(clipData.getItemAt(0).getText()));
+
+        ClipDescription clipDescription = clipData.getDescription();
+        assertThat("text/plain", is(clipDescription.getMimeType(0)));
+    }
+
     private Intent createSendTextIntent() {
         Intent sendIntent = new Intent();
         sendIntent.setAction(Intent.ACTION_SEND);
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
index c03d1f3..3ddd8aa 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
@@ -20,6 +20,7 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
+import android.os.Process;
 import android.os.SystemClock;
 import android.support.test.filters.LargeTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -121,7 +122,8 @@
         workFinishedLatch.await();
 
         // Get thread data from KernelCpuThreadReader
-        final KernelCpuThreadReader kernelCpuThreadReader = KernelCpuThreadReader.create();
+        final KernelCpuThreadReader kernelCpuThreadReader =
+                KernelCpuThreadReader.create(8, uid -> uid == Process.myUid());
         assertNotNull(kernelCpuThreadReader);
         final ProcessCpuUsage currentProcessCpuUsage =
                 kernelCpuThreadReader.getCurrentProcessCpuUsage();
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
index 0c56b8a..b9744f5 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
@@ -18,8 +18,10 @@
 
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.testng.Assert.assertThrows;
 
 import android.content.Context;
 import android.os.FileUtils;
@@ -99,6 +101,8 @@
                 THREAD_NAMES, THREAD_CPU_FREQUENCIES, THREAD_CPU_TIMES);
 
         final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
+                8,
+                uid -> 1000 <= uid && uid < 2000,
                 mProcDirectory.toPath(),
                 mProcDirectory.toPath().resolve("self/task/" + THREAD_IDS[0] + "/time_in_state"),
                 processUtils);
@@ -138,11 +142,13 @@
                     new int[][]{{uid}});
         }
         final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
+                8,
+                uidPredicate,
                 mProcDirectory.toPath(),
                 mProcDirectory.toPath().resolve(uids[0] + "/task/" + uids[0] + "/time_in_state"),
                 processUtils);
         ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsageByUids =
-                kernelCpuThreadReader.getProcessCpuUsageByUids(uidPredicate);
+                kernelCpuThreadReader.getProcessCpuUsageByUids();
         processCpuUsageByUids.sort(Comparator.comparing(usage -> usage.processId));
 
         assertEquals(expectedUids.length, processCpuUsageByUids.size());
@@ -350,4 +356,106 @@
                 4, KernelCpuThreadReader.FrequencyBucketCreator.getBigFrequenciesStartIndex(
                         new long[]{1, 2, 3, 4}));
     }
+
+    @Test
+    public void testUidPredicate_singleRange() {
+        KernelCpuThreadReaderSettingsObserver.UidPredicate uidPredicate =
+                KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("1000-1999");
+        assertTrue(uidPredicate.test(1000));
+        assertTrue(uidPredicate.test(1050));
+        assertTrue(uidPredicate.test(1999));
+        assertFalse(uidPredicate.test(2000));
+        assertFalse(uidPredicate.test(0));
+        assertFalse(uidPredicate.test(10000));
+        assertFalse(uidPredicate.test(-100));
+    }
+
+    @Test
+    public void testUidPredicate_singleUid() {
+        KernelCpuThreadReaderSettingsObserver.UidPredicate uidPredicate =
+                KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("1234-1234");
+        assertTrue(uidPredicate.test(1234));
+        assertFalse(uidPredicate.test(1235));
+        assertFalse(uidPredicate.test(1232));
+        assertFalse(uidPredicate.test(0));
+        assertFalse(uidPredicate.test(-1234));
+    }
+
+    @Test
+    public void testUidPredicate_uidAndRange() {
+        KernelCpuThreadReaderSettingsObserver.UidPredicate uidPredicate =
+                KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString(
+                        "1000-1000;1050-1060");
+        assertTrue(uidPredicate.test(1000));
+        assertTrue(uidPredicate.test(1050));
+        assertTrue(uidPredicate.test(1054));
+        assertTrue(uidPredicate.test(1060));
+        assertFalse(uidPredicate.test(1040));
+        assertFalse(uidPredicate.test(1001));
+        assertFalse(uidPredicate.test(0));
+        assertFalse(uidPredicate.test(-1000));
+    }
+
+    @Test
+    public void testUidPredicate_multiple() {
+        KernelCpuThreadReaderSettingsObserver.UidPredicate uidPredicate =
+                KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString(
+                        "1000-1000;1050-1060;1001-1001;2000-3000");
+        assertTrue(uidPredicate.test(1000));
+        assertTrue(uidPredicate.test(1001));
+        assertTrue(uidPredicate.test(1050));
+        assertTrue(uidPredicate.test(1054));
+        assertTrue(uidPredicate.test(1060));
+        assertTrue(uidPredicate.test(1001));
+        assertTrue(uidPredicate.test(2000));
+        assertTrue(uidPredicate.test(2444));
+        assertTrue(uidPredicate.test(3000));
+        assertFalse(uidPredicate.test(0));
+        assertFalse(uidPredicate.test(1040));
+        assertFalse(uidPredicate.test(3001));
+        assertFalse(uidPredicate.test(1999));
+    }
+
+    @Test
+    public void testUidPredicate_emptyRangeString() {
+        assertThrows(
+                NumberFormatException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString(""));
+    }
+
+    @Test
+    public void testUidPredicate_singleNumber() {
+        assertThrows(
+                NumberFormatException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("1000"));
+    }
+
+    @Test
+    public void testUidPredicate_lettersInRange() {
+        assertThrows(
+                NumberFormatException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString(
+                        "0-0;1-1;a;3-3"));
+    }
+
+    @Test
+    public void testUidPredicate_onlyLetters() {
+        assertThrows(
+                NumberFormatException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("abc"));
+    }
+
+    @Test
+    public void testUidPredicate_backwardsRange() {
+        assertThrows(
+                IllegalArgumentException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("20-10"));
+    }
+
+    @Test
+    public void testUidPredicate_comma() {
+        assertThrows(
+                NumberFormatException.class,
+                () -> KernelCpuThreadReaderSettingsObserver.UidPredicate.fromString("1-1,2-2,3-3"));
+    }
 }
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index f9e7dd1..080c5d5 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -712,18 +712,6 @@
     }
 
     /**
-     * Create hardware bitmap backed GraphicBuffer.
-     *
-     * @return Bitmap or null if this GraphicBuffer has unsupported PixelFormat.
-     *         currently PIXEL_FORMAT_RGBA_8888 is the only supported format
-     * @hide
-     */
-    @UnsupportedAppUsage
-    public static Bitmap createHardwareBitmap(@NonNull GraphicBuffer graphicBuffer) {
-        return nativeCreateHardwareBitmap(graphicBuffer);
-    }
-
-    /**
      * Create a hardware bitmap backed by a {@link HardwareBuffer}.
      *
      * <p>The passed HardwareBuffer's usage flags must contain
@@ -2249,7 +2237,6 @@
     private static native void nativePrepareToDraw(long nativeBitmap);
     private static native int nativeGetAllocationByteCount(long nativeBitmap);
     private static native Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap);
-    private static native Bitmap nativeCreateHardwareBitmap(GraphicBuffer buffer);
     private static native Bitmap nativeWrapHardwareBufferBitmap(HardwareBuffer buffer,
                                                                 long nativeColorSpace);
     private static native GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap);
diff --git a/graphics/java/android/graphics/BitmapShader.java b/graphics/java/android/graphics/BitmapShader.java
index bcf7229..eb0f2e1 100644
--- a/graphics/java/android/graphics/BitmapShader.java
+++ b/graphics/java/android/graphics/BitmapShader.java
@@ -65,16 +65,6 @@
         return nativeCreate(nativeMatrix, mBitmap, mTileX, mTileY);
     }
 
-    /**
-     * @hide
-     */
-    @Override
-    protected Shader copy() {
-        final BitmapShader copy = new BitmapShader(mBitmap, mTileX, mTileY);
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
     private static native long nativeCreate(long nativeMatrix, Bitmap bitmap,
             int shaderTileModeX, int shaderTileModeY);
 }
diff --git a/graphics/java/android/graphics/ComposeShader.java b/graphics/java/android/graphics/ComposeShader.java
index 70a5f53..189e174 100644
--- a/graphics/java/android/graphics/ComposeShader.java
+++ b/graphics/java/android/graphics/ComposeShader.java
@@ -87,17 +87,6 @@
         }
     }
 
-    /**
-     * @hide
-     */
-    @Override
-    protected Shader copy() {
-        final ComposeShader copy = new ComposeShader(
-                mShaderA.copy(), mShaderB.copy(), mPorterDuffMode);
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
     private static native long nativeCreate(long nativeMatrix,
             long nativeShaderA, long nativeShaderB, int porterDuffMode);
 }
diff --git a/graphics/java/android/graphics/HardwareRenderer.java b/graphics/java/android/graphics/HardwareRenderer.java
index c4ddd50..7ec76d7 100644
--- a/graphics/java/android/graphics/HardwareRenderer.java
+++ b/graphics/java/android/graphics/HardwareRenderer.java
@@ -154,6 +154,7 @@
     private boolean mOpaque = true;
     private boolean mForceDark = false;
     private FrameInfo mScratchInfo;
+    private boolean mIsWideGamut = false;
 
     /**
      * Creates a new instance of a HardwareRenderer. The HardwareRenderer will default
@@ -498,6 +499,7 @@
      * @hide
      */
     public void setWideGamut(boolean wideGamut) {
+        mIsWideGamut = wideGamut;
         nSetWideGamut(mNativeProxy, wideGamut);
     }
 
@@ -673,6 +675,11 @@
         nSetPictureCaptureCallback(mNativeProxy, callback);
     }
 
+    /** @hide */
+    public boolean isWideGamut() {
+        return mIsWideGamut;
+    }
+
     /** called by native */
     static void invokePictureCapturedCallback(long picturePtr, PictureCapturedCallback callback) {
         Picture picture = new Picture(picturePtr);
diff --git a/graphics/java/android/graphics/LinearGradient.java b/graphics/java/android/graphics/LinearGradient.java
index ad33f79..12e63c0 100644
--- a/graphics/java/android/graphics/LinearGradient.java
+++ b/graphics/java/android/graphics/LinearGradient.java
@@ -158,17 +158,6 @@
                 colorSpace().getNativeInstance());
     }
 
-    /**
-     * @hide
-     */
-    @Override
-    protected Shader copy() {
-        final LinearGradient copy = new LinearGradient(mX0, mY0, mX1, mY1, mColorLongs,
-                mPositions, mTileMode, colorSpace());
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
     private native long nativeCreate(long matrix, float x0, float y0, float x1, float y1,
             long[] colors, float[] positions, int tileMode, long colorSpaceHandle);
 }
diff --git a/graphics/java/android/graphics/PixelFormat.java b/graphics/java/android/graphics/PixelFormat.java
index 96d6eee..dde757b 100644
--- a/graphics/java/android/graphics/PixelFormat.java
+++ b/graphics/java/android/graphics/PixelFormat.java
@@ -90,6 +90,9 @@
     public static final int RGBA_F16     = 0x16;
     public static final int RGBA_1010102 = 0x2B;
 
+    /** @hide */
+    public static final int HSV_888 = 0x37;
+
     /**
      * @deprecated use {@link android.graphics.ImageFormat#JPEG
      * ImageFormat.JPEG} instead.
@@ -109,6 +112,7 @@
                 info.bytesPerPixel = 4;
                 break;
             case RGB_888:
+            case HSV_888:
                 info.bitsPerPixel = 24;
                 info.bytesPerPixel = 3;
                 break;
@@ -227,6 +231,8 @@
                 return "RGBA_F16";
             case RGBA_1010102:
                 return "RGBA_1010102";
+            case HSV_888:
+                return "HSV_888";
             case JPEG:
                 return "JPEG";
             default:
diff --git a/graphics/java/android/graphics/RadialGradient.java b/graphics/java/android/graphics/RadialGradient.java
index 5e16180..acbe3da 100644
--- a/graphics/java/android/graphics/RadialGradient.java
+++ b/graphics/java/android/graphics/RadialGradient.java
@@ -154,17 +154,6 @@
                 colorSpace().getNativeInstance());
     }
 
-    /**
-     * @hide
-     */
-    @Override
-    protected Shader copy() {
-        final RadialGradient copy = new RadialGradient(mX, mY, mRadius, mColorLongs,
-                    mPositions, mTileMode, colorSpace());
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
     private static native long nativeCreate(long matrix, float x, float y, float radius,
             @ColorLong long[] colors, float[] positions, int tileMode, long colorSpaceHandle);
 }
diff --git a/graphics/java/android/graphics/Shader.java b/graphics/java/android/graphics/Shader.java
index 7f09786..d555128 100644
--- a/graphics/java/android/graphics/Shader.java
+++ b/graphics/java/android/graphics/Shader.java
@@ -162,21 +162,6 @@
     protected void verifyNativeInstance() {
     }
 
-    /**
-     * @hide
-     */
-    protected Shader copy() {
-        final Shader copy = new Shader();
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
-    /**
-     * @hide
-     */
-    protected void copyLocalMatrix(Shader dest) {
-        dest.mLocalMatrix.set(mLocalMatrix);
-    }
 
     /**
      * @hide
diff --git a/graphics/java/android/graphics/SweepGradient.java b/graphics/java/android/graphics/SweepGradient.java
index fc386d7..667f45a 100644
--- a/graphics/java/android/graphics/SweepGradient.java
+++ b/graphics/java/android/graphics/SweepGradient.java
@@ -136,17 +136,6 @@
                 colorSpace().getNativeInstance());
     }
 
-    /**
-     * @hide
-     */
-    @Override
-    protected Shader copy() {
-        final SweepGradient copy = new SweepGradient(mCx, mCy, mColorLongs,
-                mPositions, colorSpace());
-        copyLocalMatrix(copy);
-        return copy;
-    }
-
     private static native long nativeCreate(long matrix, float x, float y,
             long[] colors, float[] positions, long colorSpaceHandle);
 }
diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java
index 09d0a58..49d3530 100644
--- a/graphics/java/android/graphics/drawable/Drawable.java
+++ b/graphics/java/android/graphics/drawable/Drawable.java
@@ -1245,6 +1245,9 @@
 
             return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
                 decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE);
+                decoder.setOnPartialImageListener((e) -> {
+                    return e.getError() == ImageDecoder.DecodeException.SOURCE_INCOMPLETE;
+                });
             });
         } catch (IOException e) {
             /*  do nothing.
diff --git a/keystore/java/android/security/OWNERS b/keystore/java/android/security/OWNERS
new file mode 100644
index 0000000..ed30587
--- /dev/null
+++ b/keystore/java/android/security/OWNERS
@@ -0,0 +1 @@
+per-file *.java,*.aidl = eranm@google.com,pgrafov@google.com,rubinxu@google.com
diff --git a/keystore/tests/OWNERS b/keystore/tests/OWNERS
new file mode 100644
index 0000000..9e65f88
--- /dev/null
+++ b/keystore/tests/OWNERS
@@ -0,0 +1,5 @@
+# Android Enterprise security team
+eranm@google.com
+irinaid@google.com
+pgrafov@google.com
+rubinxu@google.com
diff --git a/libs/androidfw/AttributeResolution.cpp b/libs/androidfw/AttributeResolution.cpp
index 18d74ef..cc177af 100644
--- a/libs/androidfw/AttributeResolution.cpp
+++ b/libs/androidfw/AttributeResolution.cpp
@@ -286,7 +286,7 @@
     value.dataType = Res_value::TYPE_NULL;
     value.data = Res_value::DATA_NULL_UNDEFINED;
     config.density = 0;
-    uint32_t source_style_resid = 0;
+    uint32_t value_source_resid = 0;
 
     // Try to find a value for this attribute...  we prioritize values
     // coming from, first XML attributes, then XML style, then default
@@ -300,6 +300,7 @@
       if (kDebugStyles) {
         ALOGI("-> From XML: type=0x%x, data=0x%08x", value.dataType, value.data);
       }
+      value_source_resid = xml_parser->getSourceResourceId();
     }
 
     if (value.dataType == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY) {
@@ -310,7 +311,7 @@
         cookie = entry->cookie;
         type_set_flags = style_flags;
         value = entry->value;
-        source_style_resid = entry->style;
+        value_source_resid = entry->style;
         if (kDebugStyles) {
           ALOGI("-> From style: type=0x%x, data=0x%08x, style=0x%08x", value.dataType, value.data,
               entry->style);
@@ -330,7 +331,7 @@
           ALOGI("-> From def style: type=0x%x, data=0x%08x, style=0x%08x", value.dataType, value.data,
               entry->style);
         }
-        source_style_resid = entry->style;
+        value_source_resid = entry->style;
       }
     }
 
@@ -349,6 +350,7 @@
     } else if (value.data != Res_value::DATA_NULL_EMPTY) {
       // If we still don't have a value for this attribute, try to find it in the theme!
       ApkAssetsCookie new_cookie = theme->GetAttribute(cur_ident, &value, &type_set_flags);
+      // TODO: set value_source_resid for the style in the theme that was used.
       if (new_cookie != kInvalidCookie) {
         if (kDebugStyles) {
           ALOGI("-> From theme: type=0x%x, data=0x%08x", value.dataType, value.data);
@@ -386,7 +388,7 @@
     out_values[STYLE_RESOURCE_ID] = resid;
     out_values[STYLE_CHANGING_CONFIGURATIONS] = type_set_flags;
     out_values[STYLE_DENSITY] = config.density;
-    out_values[SYTLE_SOURCE_STYLE] = source_style_resid;
+    out_values[SYTLE_SOURCE_RESOURCE_ID] = value_source_resid;
 
     if (value.dataType != Res_value::TYPE_NULL || value.data == Res_value::DATA_NULL_EMPTY) {
       indices_idx++;
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 63b2527..11e4cb8 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -1594,6 +1594,16 @@
     mCurExt = pos.curExt;
 }
 
+void ResXMLParser::setSourceResourceId(const uint32_t resId)
+{
+    mSourceResourceId = resId;
+}
+
+uint32_t ResXMLParser::getSourceResourceId() const
+{
+    return mSourceResourceId;
+}
+
 // --------------------------------------------------------------------
 
 static volatile int32_t gCount = 0;
diff --git a/libs/androidfw/include/androidfw/AttributeResolution.h b/libs/androidfw/include/androidfw/AttributeResolution.h
index c88004c..0cc1d3c 100644
--- a/libs/androidfw/include/androidfw/AttributeResolution.h
+++ b/libs/androidfw/include/androidfw/AttributeResolution.h
@@ -33,7 +33,7 @@
   STYLE_RESOURCE_ID = 3,
   STYLE_CHANGING_CONFIGURATIONS = 4,
   STYLE_DENSITY = 5,
-  SYTLE_SOURCE_STYLE = 6
+  SYTLE_SOURCE_RESOURCE_ID = 6
 };
 
 // These are all variations of the same method. They each perform the exact same operation,
diff --git a/libs/androidfw/include/androidfw/ResourceTypes.h b/libs/androidfw/include/androidfw/ResourceTypes.h
index 1655e89..742813e 100644
--- a/libs/androidfw/include/androidfw/ResourceTypes.h
+++ b/libs/androidfw/include/androidfw/ResourceTypes.h
@@ -782,6 +782,9 @@
     void getPosition(ResXMLPosition* pos) const;
     void setPosition(const ResXMLPosition& pos);
 
+    void setSourceResourceId(const uint32_t resId);
+    uint32_t getSourceResourceId() const;
+
 private:
     friend class ResXMLTree;
     
@@ -791,6 +794,7 @@
     event_code_t                mEventCode;
     const ResXMLTree_node*      mCurNode;
     const void*                 mCurExt;
+    uint32_t                    mSourceResourceId;
 };
 
 class DynamicRefTable;
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index 96798f9..0335a7c 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -28,10 +28,6 @@
 
         // clang's warning is broken, see: https://llvm.org/bugs/show_bug.cgi?id=21629
         "-Wno-missing-braces",
-
-        // TODO: Linear blending should be enabled by default, but we are
-        // TODO: making it an opt-in while it's a work in progress
-        //"-DANDROID_ENABLE_LINEAR_BLENDING",
     ],
 
     include_dirs: [
diff --git a/libs/hwui/HardwareBitmapUploader.cpp b/libs/hwui/HardwareBitmapUploader.cpp
index 39bfcdd..aeeb32c 100644
--- a/libs/hwui/HardwareBitmapUploader.cpp
+++ b/libs/hwui/HardwareBitmapUploader.cpp
@@ -86,7 +86,7 @@
     return sEglManager.eglDisplay();
 }
 
-static bool hasFP16Support() {
+bool HardwareBitmapUploader::hasFP16Support() {
     static std::once_flag sOnce;
     static bool hasFP16Support = false;
 
@@ -116,7 +116,6 @@
 
 static FormatInfo determineFormat(const SkBitmap& skBitmap) {
     FormatInfo formatInfo;
-    // TODO: add support for linear blending (when ANDROID_ENABLE_LINEAR_BLENDING is defined)
     switch (skBitmap.info().colorType()) {
         case kRGBA_8888_SkColorType:
             formatInfo.isSupported = true;
@@ -127,7 +126,7 @@
             formatInfo.type = GL_UNSIGNED_BYTE;
             break;
         case kRGBA_F16_SkColorType:
-            formatInfo.isSupported = hasFP16Support();
+            formatInfo.isSupported = HardwareBitmapUploader::hasFP16Support();
             if (formatInfo.isSupported) {
                 formatInfo.type = GL_HALF_FLOAT;
                 formatInfo.pixelFormat = PIXEL_FORMAT_RGBA_FP16;
diff --git a/libs/hwui/HardwareBitmapUploader.h b/libs/hwui/HardwareBitmapUploader.h
index 40f2b0c..6f41e6d 100644
--- a/libs/hwui/HardwareBitmapUploader.h
+++ b/libs/hwui/HardwareBitmapUploader.h
@@ -20,10 +20,12 @@
 
 namespace android::uirenderer {
 
-class HardwareBitmapUploader {
+class ANDROID_API HardwareBitmapUploader {
 public:
     static sk_sp<Bitmap> allocateHardwareBitmap(const SkBitmap& sourceBitmap);
     static void terminate();
+
+    static bool hasFP16Support();
 };
 
 }  // namespace android::uirenderer
diff --git a/libs/hwui/VectorDrawable.cpp b/libs/hwui/VectorDrawable.cpp
index 7265692..da905cf 100644
--- a/libs/hwui/VectorDrawable.cpp
+++ b/libs/hwui/VectorDrawable.cpp
@@ -606,12 +606,7 @@
 
 bool Tree::allocateBitmapIfNeeded(Cache& cache, int width, int height) {
     if (!canReuseBitmap(cache.bitmap.get(), width, height)) {
-#ifndef ANDROID_ENABLE_LINEAR_BLENDING
-        sk_sp<SkColorSpace> colorSpace = nullptr;
-#else
-        sk_sp<SkColorSpace> colorSpace = SkColorSpace::MakeSRGB();
-#endif
-        SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType, colorSpace);
+        SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType);
         cache.bitmap = Bitmap::allocateHeapBitmap(info);
         return true;
     }
diff --git a/libs/hwui/hwui/Canvas.cpp b/libs/hwui/hwui/Canvas.cpp
index 5231486..68aa737 100644
--- a/libs/hwui/hwui/Canvas.cpp
+++ b/libs/hwui/hwui/Canvas.cpp
@@ -25,6 +25,8 @@
 
 #include "hwui/PaintFilter.h"
 
+#include <SkFontMetrics.h>
+
 namespace android {
 
 Canvas* Canvas::create_recording_canvas(int width, int height, uirenderer::RenderNode* renderNode) {
diff --git a/libs/hwui/pipeline/skia/VectorDrawableAtlas.cpp b/libs/hwui/pipeline/skia/VectorDrawableAtlas.cpp
index 8fb621d..e783f38 100644
--- a/libs/hwui/pipeline/skia/VectorDrawableAtlas.cpp
+++ b/libs/hwui/pipeline/skia/VectorDrawableAtlas.cpp
@@ -262,12 +262,7 @@
 }
 
 sk_sp<SkSurface> VectorDrawableAtlas::createSurface(int width, int height, GrContext* context) {
-#ifndef ANDROID_ENABLE_LINEAR_BLENDING
-    sk_sp<SkColorSpace> colorSpace = nullptr;
-#else
-    sk_sp<SkColorSpace> colorSpace = SkColorSpace::MakeSRGB();
-#endif
-    SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType, colorSpace);
+    SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType);
     // This must have a top-left origin so that calls to surface->canvas->writePixels
     // performs a basic texture upload instead of a more complex drawing operation
     return SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, 0, kTopLeft_GrSurfaceOrigin,
diff --git a/libs/hwui/surfacetexture/ImageConsumer.cpp b/libs/hwui/surfacetexture/ImageConsumer.cpp
index 4a2f57e..624c290 100644
--- a/libs/hwui/surfacetexture/ImageConsumer.cpp
+++ b/libs/hwui/surfacetexture/ImageConsumer.cpp
@@ -46,8 +46,8 @@
 }
 
 void ImageConsumer::ImageSlot::createIfNeeded(sp<GraphicBuffer> graphicBuffer,
-                                              android_dataspace dataspace) {
-    if (!mImage.get() || dataspace != mDataspace) {
+                                              android_dataspace dataspace, bool forceCreate) {
+    if (!mImage.get() || dataspace != mDataspace || forceCreate) {
         mImage = graphicBuffer.get()
                          ? SkImage::MakeFromAHardwareBuffer(
                                    reinterpret_cast<AHardwareBuffer*>(graphicBuffer.get()),
@@ -71,7 +71,7 @@
             if (slot != BufferItem::INVALID_BUFFER_SLOT) {
                 *queueEmpty = true;
                 mImageSlots[slot].createIfNeeded(st.mSlots[slot].mGraphicBuffer,
-                        st.mCurrentDataSpace);
+                        st.mCurrentDataSpace, false);
                 return mImageSlots[slot].mImage;
             }
         }
@@ -150,7 +150,7 @@
     st.computeCurrentTransformMatrixLocked();
 
     *queueEmpty = false;
-    mImageSlots[slot].createIfNeeded(st.mSlots[slot].mGraphicBuffer, item.mDataSpace);
+    mImageSlots[slot].createIfNeeded(st.mSlots[slot].mGraphicBuffer, item.mDataSpace, true);
     return mImageSlots[slot].mImage;
 }
 
diff --git a/libs/hwui/surfacetexture/ImageConsumer.h b/libs/hwui/surfacetexture/ImageConsumer.h
index f0e55bb..5c41903 100644
--- a/libs/hwui/surfacetexture/ImageConsumer.h
+++ b/libs/hwui/surfacetexture/ImageConsumer.h
@@ -82,7 +82,8 @@
          */
         EGLSyncKHR mEglFence;
 
-        void createIfNeeded(sp<GraphicBuffer> graphicBuffer, android_dataspace dataspace);
+        void createIfNeeded(sp<GraphicBuffer> graphicBuffer, android_dataspace dataspace,
+                            bool forceCreate);
     };
 
     /**
diff --git a/libs/hwui/utils/Color.h b/libs/hwui/utils/Color.h
index b67d10d..79400de 100644
--- a/libs/hwui/utils/Color.h
+++ b/libs/hwui/utils/Color.h
@@ -82,17 +82,6 @@
     return linear <= 0.0031308f ? linear * 12.92f : (powf(linear, 1.0f / 2.4f) * 1.055f) - 0.055f;
 }
 
-// Opto-electronic conversion function for the sRGB color space
-// Takes a linear sRGB value and converts it to a gamma-encoded sRGB value
-// This function returns the input unmodified if linear blending is not enabled
-static constexpr float OECF(float linear) {
-#ifdef ANDROID_ENABLE_LINEAR_BLENDING
-    return OECF_sRGB(linear);
-#else
-    return linear;
-#endif
-}
-
 // Electro-optical conversion function for the sRGB color space
 // Takes a gamma-encoded sRGB value and converts it to a linear sRGB value
 static constexpr float EOCF_sRGB(float srgb) {
@@ -100,17 +89,6 @@
     return srgb <= 0.04045f ? srgb / 12.92f : powf((srgb + 0.055f) / 1.055f, 2.4f);
 }
 
-// Electro-optical conversion function for the sRGB color space
-// Takes a gamma-encoded sRGB value and converts it to a linear sRGB value
-// This function returns the input unmodified if linear blending is not enabled
-static constexpr float EOCF(float srgb) {
-#ifdef ANDROID_ENABLE_LINEAR_BLENDING
-    return EOCF_sRGB(srgb);
-#else
-    return srgb;
-#endif
-}
-
 android::PixelFormat ColorTypeToPixelFormat(SkColorType colorType);
 ANDROID_API SkColorType PixelFormatToColorType(android::PixelFormat format);
 
diff --git a/media/Android.bp b/media/Android.bp
index d7b8dd2..1aefebe 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -2,8 +2,7 @@
     name: "updatable-media",
 
     srcs: [
-        ":mediaplayer2-srcs",
-        ":mediasession2-srcs",
+        ":updatable-media-srcs",
         ":framework-media-annotation-srcs",
     ],
 
@@ -12,8 +11,12 @@
             "apex/java",
         ],
 
+        // It would be great if we don't need to add include_dirs for public
+        // parcelable classes. Find a better way.
         include_dirs: [
-            // For the usage of android.os.Bundle and android.os.ResultReceiver in aidl files
+            // To refer:
+            // android.os.Bundle
+            // android.os.ResultReceiver
             "frameworks/base/core/java",
         ],
     },
@@ -29,7 +32,15 @@
 }
 
 filegroup {
-    name: "media-srcs-without-aidls",
+    name: "updatable-media-srcs",
+    srcs: [
+        ":mediasession2-srcs",
+        ":mediaplayer2-srcs",
+    ],
+}
+
+filegroup {
+    name: "updatable-media-srcs-without-aidls",
     srcs : [
         ":mediasession2-srcs-without-aidls",
         ":mediaplayer2-srcs",
@@ -51,6 +62,7 @@
         "apex/java/android/media/Session2Command.java",
         "apex/java/android/media/Session2CommandGroup.java",
         "apex/java/android/media/Session2Link.java",
+        "apex/java/android/media/Session2Token.java",
     ],
 }
 
@@ -75,7 +87,6 @@
         "apex/java/android/media/UriDataSourceDesc.java",
         "apex/java/android/media/FileDataSourceDesc.java",
         "apex/java/android/media/CallbackDataSourceDesc.java",
-        "apex/java/android/media/VideoSize.java",
         "apex/java/android/media/Media2Utils.java",
         "apex/java/android/media/MediaPlayer2Utils.java",
         "apex/java/android/media/MediaPlayer2.java",
@@ -85,3 +96,32 @@
         "apex/java/android/media/BufferingParams.java",
     ],
 }
+
+metalava_updatable_media_args = " --error UnhiddenSystemApi " +
+    "--hide RequiresPermission " +
+    "--hide MissingPermission --hide BroadcastBehavior " +
+    "--hide HiddenSuperclass --hide DeprecationMismatch --hide UnavailableSymbol " +
+    "--hide SdkConstant --hide HiddenTypeParameter --hide Todo --hide Typo " +
+    "--hide HiddenTypedefConstant "
+
+droidstubs {
+    name: "updatable-media-stubs",
+    srcs: [
+        ":updatable-media-srcs-without-aidls",
+        ":framework-media-annotation-srcs",
+    ],
+    args: metalava_updatable_media_args + " --show-annotation android.annotation.SystemApi " +
+        " --show-annotation android.annotation.TestApi ",
+    // Ideally, sdk_version here should be "current_system", but "current - 1" is used
+    // to avoid dependency cycle with framework.
+    sdk_version: "28",
+}
+
+java_library {
+    name: "updatable_media_stubs",
+    srcs: [":updatable-media-stubs"],
+    // Ideally, sdk_version here should be "current_system", but "current - 1" is used
+    // to avoid dependency cycle with framework.
+    sdk_version: "28",
+}
+
diff --git a/media/apex/java/android/media/MediaConstants.java b/media/apex/java/android/media/MediaConstants.java
index 45ea826..65b6f55 100644
--- a/media/apex/java/android/media/MediaConstants.java
+++ b/media/apex/java/android/media/MediaConstants.java
@@ -24,8 +24,7 @@
     static final String KEY_PACKAGE_NAME = "android.media.key.PACKAGE_NAME";
 
     // Bundle key for Parcelable
-    static final String KEY_SESSION2_TOKEN = "android.media.key.SESSION2_TOKEN";
-    static final String KEY_SESSION2_LINK = "android.media.key.SESSION2_LINK";
+    static final String KEY_SESSION2LINK = "android.media.key.SESSION2LINK";
     static final String KEY_ALLOWED_COMMANDS = "android.media.key.ALLOWED_COMMANDS";
     static final String KEY_PLAYBACK_ACTIVE = "android.media.key.PLAYBACK_ACTIVE";
 
diff --git a/media/apex/java/android/media/MediaController2.java b/media/apex/java/android/media/MediaController2.java
index 41721f3..887b447 100644
--- a/media/apex/java/android/media/MediaController2.java
+++ b/media/apex/java/android/media/MediaController2.java
@@ -20,11 +20,9 @@
 import static android.media.MediaConstants.KEY_PACKAGE_NAME;
 import static android.media.MediaConstants.KEY_PID;
 import static android.media.MediaConstants.KEY_PLAYBACK_ACTIVE;
-import static android.media.MediaConstants.KEY_SESSION2_LINK;
-import static android.media.MediaConstants.KEY_SESSION2_TOKEN;
+import static android.media.MediaConstants.KEY_SESSION2LINK;
 import static android.media.Session2Command.RESULT_ERROR_UNKNOWN_ERROR;
 import static android.media.Session2Command.RESULT_INFO_SKIPPED;
-import static android.media.Session2Token.SESSION_SERVICE_INTERFACE;
 import static android.media.Session2Token.TYPE_SESSION;
 
 import android.annotation.NonNull;
@@ -262,8 +260,7 @@
 
     // Called by Controller2Link.onConnected
     void onConnected(int seq, Bundle connectionResult) {
-        Session2Token token = connectionResult.getParcelable(KEY_SESSION2_TOKEN);
-        Session2Link sessionBinder = token.getExtras().getParcelable(KEY_SESSION2_LINK);
+        Session2Link sessionBinder = connectionResult.getParcelable(KEY_SESSION2LINK);
         Session2CommandGroup allowedCommands =
                 connectionResult.getParcelable(KEY_ALLOWED_COMMANDS);
         boolean playbackActive = connectionResult.getBoolean(KEY_PLAYBACK_ACTIVE);
@@ -284,7 +281,8 @@
             // Implementation for the local binder is no-op,
             // so can be used without worrying about deadlock.
             sessionBinder.linkToDeath(mDeathRecipient, 0);
-            mConnectedToken = token;
+            mConnectedToken = new Session2Token(mSessionToken.getUid(), TYPE_SESSION,
+                    mSessionToken.getPackageName(), sessionBinder);
         }
         mCallbackExecutor.execute(() -> {
             mCallback.onConnected(MediaController2.this, allowedCommands);
@@ -355,7 +353,7 @@
     }
 
     private boolean requestConnectToSession() {
-        Session2Link sessionBinder = mSessionToken.getExtras().getParcelable(KEY_SESSION2_LINK);
+        Session2Link sessionBinder = mSessionToken.getSessionLink();
         Bundle connectionRequest = createConnectionRequest();
         try {
             sessionBinder.connect(mControllerStub, getNextSeqNumber(), connectionRequest);
@@ -368,7 +366,7 @@
 
     private boolean requestConnectToService() {
         // Service. Needs to get fresh binder whenever connection is needed.
-        final Intent intent = new Intent(SESSION_SERVICE_INTERFACE);
+        final Intent intent = new Intent(MediaSession2Service.SERVICE_INTERFACE);
         intent.setClassName(mSessionToken.getPackageName(), mSessionToken.getServiceName());
 
         // Use bindService() instead of startForegroundService() to start session service for three
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
index 0fd496b..925ca0d 100644
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ b/media/apex/java/android/media/MediaPlayer2.java
@@ -41,6 +41,7 @@
 import android.os.PowerManager;
 import android.util.Log;
 import android.util.Pair;
+import android.util.Size;
 import android.view.Surface;
 import android.view.SurfaceHolder;
 
@@ -62,7 +63,6 @@
 import java.nio.ByteOrder;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
@@ -300,7 +300,7 @@
     private final AtomicLong mSrcIdGenerator = new AtomicLong(0);
 
     private volatile float mVolume = 1.0f;
-    private VideoSize mVideoSize = new VideoSize(0, 0);
+    private Size mVideoSize = new Size(0, 0);
 
     private static ExecutorService sDrmThreadPool = Executors.newCachedThreadPool();
 
@@ -1527,7 +1527,7 @@
      * notification {@code EventCallback.onVideoSizeChanged} when the size
      * is available.
      */
-    public VideoSize getVideoSize() {
+    public Size getVideoSize() {
         return mVideoSize;
     }
 
@@ -2527,7 +2527,7 @@
                     final int width = msg.arg1;
                     final int height = msg.arg2;
 
-                    mVideoSize = new VideoSize(width, height);
+                    mVideoSize = new Size(width, height);
                     sendEvent(new EventNotifier() {
                         @Override
                         public void notify(EventCallback callback) {
@@ -2766,7 +2766,7 @@
          * @param size the size of the video
          */
         public void onVideoSizeChanged(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull VideoSize size) { }
+                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull Size size) { }
 
         /**
          * Called to indicate an avaliable timed text
diff --git a/media/apex/java/android/media/MediaSession2.java b/media/apex/java/android/media/MediaSession2.java
index 80c91cc..fdd07fd 100644
--- a/media/apex/java/android/media/MediaSession2.java
+++ b/media/apex/java/android/media/MediaSession2.java
@@ -20,10 +20,10 @@
 import static android.media.MediaConstants.KEY_PACKAGE_NAME;
 import static android.media.MediaConstants.KEY_PID;
 import static android.media.MediaConstants.KEY_PLAYBACK_ACTIVE;
-import static android.media.MediaConstants.KEY_SESSION2_LINK;
-import static android.media.MediaConstants.KEY_SESSION2_TOKEN;
+import static android.media.MediaConstants.KEY_SESSION2LINK;
 import static android.media.Session2Command.RESULT_ERROR_UNKNOWN_ERROR;
 import static android.media.Session2Command.RESULT_INFO_SKIPPED;
+import static android.media.Session2Token.TYPE_SESSION;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -34,6 +34,7 @@
 import android.media.session.MediaSessionManager.RemoteUserInfo;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.Process;
 import android.os.ResultReceiver;
 import android.util.ArrayMap;
 import android.util.ArraySet;
@@ -107,10 +108,8 @@
         mCallbackExecutor = callbackExecutor;
         mCallback = callback;
         mSessionStub = new Session2Link(this);
-
-        Bundle extras = new Bundle();
-        extras.putParcelable(KEY_SESSION2_LINK, mSessionStub);
-        mSessionToken = new Session2Token(context, id, extras);
+        mSessionToken = new Session2Token(Process.myUid(), TYPE_SESSION, context.getPackageName(),
+                mSessionStub);
         mSessionManager = (MediaSessionManager) mContext.getSystemService(
                 Context.MEDIA_SESSION_SERVICE);
         // NOTE: mResultHandler uses main looper, so this MUST NOT be blocked.
@@ -142,8 +141,6 @@
             for (ControllerInfo info : controllerInfos) {
                 info.notifyDisconnected();
             }
-            mSessionToken.destroy();
-            mSessionManager.notifySession2Destroyed(mSessionToken);
         } catch (Exception e) {
             // Should not be here.
         }
@@ -331,7 +328,7 @@
                 // It's needed because we cannot call synchronous calls between
                 // session/controller.
                 Bundle connectionResult = new Bundle();
-                connectionResult.putParcelable(KEY_SESSION2_TOKEN, mSessionToken);
+                connectionResult.putParcelable(KEY_SESSION2LINK, mSessionStub);
                 connectionResult.putParcelable(KEY_ALLOWED_COMMANDS,
                         controllerInfo.mAllowedCommands);
                 connectionResult.putBoolean(KEY_PLAYBACK_ACTIVE, isPlaybackActive());
diff --git a/media/apex/java/android/media/MediaSession2Service.java b/media/apex/java/android/media/MediaSession2Service.java
index 54d0ed2..5bb746a 100644
--- a/media/apex/java/android/media/MediaSession2Service.java
+++ b/media/apex/java/android/media/MediaSession2Service.java
@@ -48,7 +48,7 @@
     /**
      * The {@link Intent} that must be declared as handled by the service.
      */
-    public static final String SERVICE_INTERFACE = Session2Token.SESSION_SERVICE_INTERFACE;
+    public static final String SERVICE_INTERFACE = "android.media.MediaSession2Service";
 
     private static final String TAG = "MediaSession2Service";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
diff --git a/media/java/android/media/Session2Token.java b/media/apex/java/android/media/Session2Token.java
similarity index 70%
rename from media/java/android/media/Session2Token.java
rename to media/apex/java/android/media/Session2Token.java
index 80494ad..238cc2b 100644
--- a/media/java/android/media/Session2Token.java
+++ b/media/apex/java/android/media/Session2Token.java
@@ -19,17 +19,13 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.SystemApi;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
-import android.media.session.MediaSessionManager;
-import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.Process;
 import android.text.TextUtils;
 import android.util.Log;
 
@@ -39,7 +35,7 @@
 import java.util.Objects;
 
 /**
- * Represents an ongoing MediaSession2 or a MediaSession2Service.
+ * Represents an ongoing {@link MediaSession2} or a {@link MediaSession2Service}.
  * If it's representing a session service, it may not be ongoing.
  * <p>
  * This API is not generally intended for third party application developers.
@@ -48,7 +44,7 @@
  * for consistent behavior across all devices.
  * <p>
  * This may be passed to apps by the session owner to allow them to create a
- * MediaController2 to communicate with the session.
+ * {@link MediaController2} to communicate with the session.
  * <p>
  * It can be also obtained by {@link android.media.session.MediaSessionManager}.
  */
@@ -68,13 +64,6 @@
     };
 
     /**
-     * The {@link Intent} that must be declared for the session service.
-     * @hide
-     */
-    @SystemApi
-    public static final String SESSION_SERVICE_INTERFACE = "android.media.MediaSession2Service";
-
-    /**
      * @hide
      */
     @Retention(RetentionPolicy.SOURCE)
@@ -83,26 +72,22 @@
     }
 
     /**
-     * Type for MediaSession2.
+     * Type for {@link MediaSession2}.
      */
     public static final int TYPE_SESSION = 0;
 
     /**
-     * Type for MediaSession2Service.
+     * Type for {@link MediaSession2Service}.
      */
     public static final int TYPE_SESSION_SERVICE = 1;
 
-    private final String mSessionId;
-    private final int mPid;
     private final int mUid;
     @TokenType
     private final int mType;
     private final String mPackageName;
     private final String mServiceName;
+    private final Session2Link mSessionLink;
     private final ComponentName mComponentName;
-    private final Bundle mExtras;
-
-    private boolean mDestroyed = false;
 
     /**
      * Constructor for the token with type {@link #TYPE_SESSION_SERVICE}.
@@ -121,67 +106,44 @@
         final PackageManager manager = context.getPackageManager();
         final int uid = getUid(manager, serviceComponent.getPackageName());
 
-        if (!isInterfaceDeclared(manager, SESSION_SERVICE_INTERFACE, serviceComponent)) {
+        if (!isInterfaceDeclared(manager, MediaSession2Service.SERVICE_INTERFACE,
+                serviceComponent)) {
             Log.w(TAG, serviceComponent + " doesn't implement MediaSession2Service.");
         }
-        mSessionId = null;
         mComponentName = serviceComponent;
         mPackageName = serviceComponent.getPackageName();
         mServiceName = serviceComponent.getClassName();
-        mPid = -1;
         mUid = uid;
         mType = TYPE_SESSION_SERVICE;
-        mExtras = null;
+        mSessionLink = null;
     }
 
-    /**
-     * Constructor for the token with type {@link #TYPE_SESSION}.
-     *
-     * @param context The context.
-     * @param sessionId The ID of the session. Should be unique.
-     * @param extras The extras.
-     * @hide
-     */
-    @SystemApi
-    public Session2Token(@NonNull Context context, @NonNull String sessionId,
-            @Nullable Bundle extras) {
-        if (sessionId == null) {
-            throw new IllegalArgumentException("sessionId shouldn't be null");
-        }
-        if (context == null) {
-            throw new IllegalArgumentException("context shouldn't be null");
-        }
-        mSessionId = sessionId;
-        mPid = Process.myPid();
-        mUid = Process.myUid();
-        mType = TYPE_SESSION;
-        mPackageName = context.getPackageName();
-        mExtras = extras;
+    Session2Token(int uid, int type, String packageName, Session2Link sessionLink) {
+        mUid = uid;
+        mType = type;
+        mPackageName = packageName;
         mServiceName = null;
         mComponentName = null;
+        mSessionLink = sessionLink;
     }
 
     Session2Token(Parcel in) {
-        mSessionId = in.readString();
-        mPid = in.readInt();
         mUid = in.readInt();
         mType = in.readInt();
         mPackageName = in.readString();
         mServiceName = in.readString();
+        mSessionLink = in.readParcelable(null);
         mComponentName = ComponentName.unflattenFromString(in.readString());
-        mExtras = in.readParcelable(null);
     }
 
     @Override
     public void writeToParcel(Parcel dest, int flags) {
-        dest.writeString(mSessionId);
-        dest.writeInt(mPid);
         dest.writeInt(mUid);
         dest.writeInt(mType);
         dest.writeString(mPackageName);
         dest.writeString(mServiceName);
+        dest.writeParcelable(mSessionLink, flags);
         dest.writeString(mComponentName == null ? "" : mComponentName.flattenToString());
-        dest.writeParcelable(mExtras, flags);
     }
 
     @Override
@@ -191,7 +153,7 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mSessionId, mPid, mUid, mType, mPackageName, mServiceName);
+        return Objects.hash(mType, mUid, mPackageName, mServiceName, mSessionLink);
     }
 
     @Override
@@ -200,27 +162,17 @@
             return false;
         }
         Session2Token other = (Session2Token) obj;
-        return TextUtils.equals(mSessionId, other.mSessionId)
-                && mPid == other.mPid
-                && mUid == other.mUid
-                && mType == other.mType
+        return mUid == other.mUid
                 && TextUtils.equals(mPackageName, other.mPackageName)
-                && TextUtils.equals(mServiceName, other.mServiceName);
+                && TextUtils.equals(mServiceName, other.mServiceName)
+                && mType == other.mType
+                && Objects.equals(mSessionLink, other.mSessionLink);
     }
 
     @Override
     public String toString() {
         return "Session2Token {pkg=" + mPackageName + " type=" + mType
-                + " service=" + mServiceName + "}";
-    }
-
-    /**
-     * @return pid of the session
-     * @hide
-     */
-    @SystemApi
-    public int getPid() {
-        return mPid;
+                + " service=" + mServiceName + " Session2Link=" + mSessionLink + "}";
     }
 
     /**
@@ -255,36 +207,8 @@
         return mType;
     }
 
-    /**
-     * @return extras
-     * @hide
-     */
-    @SystemApi
-    @NonNull
-    public Bundle getExtras() {
-        return mExtras == null ? new Bundle() : new Bundle(mExtras);
-    }
-
-    /**
-     * Destroys this session token. After this method is called,
-     * {@link MediaSessionManager#notifySession2Created(Session2Token)} should not be called
-     * with this token.
-     *
-     * @see MediaSessionManager#notifySession2Created(Session2Token)
-     * @hide
-     */
-    @SystemApi
-    public void destroy() {
-        mDestroyed = true;
-    }
-
-    /**
-     * @return whether this token is destroyed
-     * @hide
-     */
-    @SystemApi
-    public boolean isDestroyed() {
-        return mDestroyed;
+    Session2Link getSessionLink() {
+        return mSessionLink;
     }
 
     private static boolean isInterfaceDeclared(PackageManager manager, String serviceInterface,
diff --git a/media/apex/java/android/media/VideoSize.java b/media/apex/java/android/media/VideoSize.java
deleted file mode 100644
index 19631e0..0000000
--- a/media/apex/java/android/media/VideoSize.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.media;
-
-/**
- * Immutable class for describing width and height dimensions.
- */
-public final class VideoSize {
-    /**
-     * Create a new immutable VideoSize instance.
-     *
-     * @param width The width of the video size
-     * @param height The height of the video size
-     */
-    VideoSize(int width, int height) {
-        mWidth = width;
-        mHeight = height;
-    }
-
-    /**
-     * Get the width of the video size
-     * @return width
-     */
-    public int getWidth() {
-        return mWidth;
-    }
-
-    /**
-     * Get the height of the video size
-     * @return height
-     */
-    public int getHeight() {
-        return mHeight;
-    }
-
-    /**
-     * Check if this video size is equal to another video size.
-     * <p>
-     * Two video sizes are equal if and only if both their widths and heights are
-     * equal.
-     * </p>
-     * <p>
-     * A video size object is never equal to any other type of object.
-     * </p>
-     *
-     * @return {@code true} if the objects were equal, {@code false} otherwise
-     */
-    @Override
-    public boolean equals(final Object obj) {
-        if (obj == null) {
-            return false;
-        }
-        if (this == obj) {
-            return true;
-        }
-        if (obj instanceof VideoSize) {
-            VideoSize other = (VideoSize) obj;
-            return mWidth == other.mWidth && mHeight == other.mHeight;
-        }
-        return false;
-    }
-
-    /**
-     * Return the video size represented as a string with the format {@code "WxH"}
-     *
-     * @return string representation of the video size
-     */
-    @Override
-    public String toString() {
-        return mWidth + "x" + mHeight;
-    }
-
-    private final int mWidth;
-    private final int mHeight;
-}
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index ffa3b24..9218e92 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -17,6 +17,7 @@
 package android.media;
 
 import android.annotation.NonNull;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.bluetooth.BluetoothCodecConfig;
 import android.content.Context;
@@ -933,6 +934,13 @@
     /** @hide enables or disables the master mono mode. */
     public static native int setMasterMono(boolean mono);
 
+    /** @hide returns master balance value in range -1.f -> 1.f, where 0.f is dead center. */
+    @TestApi
+    public static native float getMasterBalance();
+    /** @hide changes the audio balance of the device. */
+    @TestApi
+    public static native int setMasterBalance(float balance);
+
     // helpers for android.media.AudioManager.getProperty(), see description there for meaning
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 112561552)
     public static native int getPrimaryOutputSamplingRate();
diff --git a/media/java/android/media/MediaDrm.java b/media/java/android/media/MediaDrm.java
index 2d2c4a8..9258b85 100644
--- a/media/java/android/media/MediaDrm.java
+++ b/media/java/android/media/MediaDrm.java
@@ -1186,22 +1186,22 @@
     public static final int OFFLINE_LICENSE_STATE_UNKNOWN = 0;
 
     /**
-     * Offline license state is usable, the keys may be used for decryption.
+     * Offline license is usable, the keys may be used for decryption.
      */
-    public static final int OFFLINE_LICENSE_USABLE = 1;
+    public static final int OFFLINE_LICENSE_STATE_USABLE = 1;
 
     /**
-     * Offline license state is inactive, the keys have been marked for
-     * release using {@link #getKeyRequest} with KEY_TYPE_RELEASE but the
-     * key response has not been received.
+     * Offline license is released, the keys have been marked for
+     * release using {@link #getKeyRequest} with KEY_TYPE_RELEASE but
+     * the key response has not been received.
      */
-    public static final int OFFLINE_LICENSE_INACTIVE = 2;
+    public static final int OFFLINE_LICENSE_STATE_RELEASED = 2;
 
     /** @hide */
     @IntDef({
         OFFLINE_LICENSE_STATE_UNKNOWN,
-        OFFLINE_LICENSE_USABLE,
-        OFFLINE_LICENSE_INACTIVE,
+        OFFLINE_LICENSE_STATE_USABLE,
+        OFFLINE_LICENSE_STATE_RELEASED,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface OfflineLicenseState {}
diff --git a/media/java/android/media/session/ISessionManager.aidl b/media/java/android/media/session/ISessionManager.aidl
index edaa55d..8143bfa 100644
--- a/media/java/android/media/session/ISessionManager.aidl
+++ b/media/java/android/media/session/ISessionManager.aidl
@@ -37,7 +37,6 @@
     SessionLink createSession(String packageName, in SessionCallbackLink sessionCb, String tag,
             int userId);
     void notifySession2Created(in Session2Token sessionToken);
-    void notifySession2Destroyed(in Session2Token sessionToken);
     List<MediaSession.Token> getSessions(in ComponentName compName, int userId);
     List<Session2Token> getSession2Tokens(int userId);
     void dispatchMediaKeyEvent(String packageName, boolean asSystemService, in KeyEvent keyEvent,
diff --git a/media/java/android/media/session/MediaSessionManager.java b/media/java/android/media/session/MediaSessionManager.java
index bd8eadd..46f6c71 100644
--- a/media/java/android/media/session/MediaSessionManager.java
+++ b/media/java/android/media/session/MediaSessionManager.java
@@ -26,6 +26,7 @@
 import android.content.Context;
 import android.media.AudioManager;
 import android.media.IRemoteVolumeController;
+import android.media.MediaSession2;
 import android.media.Session2Token;
 import android.os.Handler;
 import android.os.IBinder;
@@ -114,11 +115,11 @@
     }
 
     /**
-     * Notifies that a new MediaSession2 with type {@link Session2Token#TYPE_SESSION} is
+     * Notifies that a new {@link MediaSession2} with type {@link Session2Token#TYPE_SESSION} is
      * created.
      * <p>
      * Do not use this API directly, but create a new instance through the
-     * MediaSession2.Builder instead.
+     * {@link MediaSession2.Builder} instead.
      *
      * @param token newly created session2 token
      */
@@ -129,9 +130,6 @@
         if (token.getType() != Session2Token.TYPE_SESSION) {
             throw new IllegalArgumentException("token's type should be TYPE_SESSION");
         }
-        if (token.isDestroyed()) {
-            throw new IllegalArgumentException("token is already destroyed");
-        }
         try {
             mService.notifySession2Created(token);
         } catch (RemoteException e) {
@@ -140,31 +138,6 @@
     }
 
     /**
-     * Notifies that a new MediaSession2 with type {@link Session2Token#TYPE_SESSION} is
-     * destroyed.
-     * <p>
-     * Do not use this API directly, but close a session with MediaSession2#close() instead.
-     *
-     * @param token destroyed session2 token
-     */
-    public void notifySession2Destroyed(@NonNull Session2Token token) {
-        if (token == null) {
-            throw new IllegalArgumentException("token shouldn't be null");
-        }
-        if (token.getType() != Session2Token.TYPE_SESSION) {
-            throw new IllegalArgumentException("token's type should be TYPE_SESSION");
-        }
-        if (!token.isDestroyed()) {
-            throw new IllegalArgumentException("token should have been destroyed");
-        }
-        try {
-            mService.notifySession2Destroyed(token);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
      * Get a list of controllers for all ongoing sessions. The controllers will
      * be provided in priority order with the most important controller at index
      * 0.
@@ -219,7 +192,7 @@
      * current user.
      * <p>
      * Although this API can be used without any restriction, each session owners can accept or
-     * reject your uses of MediaSession2.
+     * reject your uses of {@link MediaSession2}.
      *
      * @return A list of {@link Session2Token}.
      */
diff --git a/media/jni/android_media_MediaDrm.cpp b/media/jni/android_media_MediaDrm.cpp
index 866325c..d7ab854 100644
--- a/media/jni/android_media_MediaDrm.cpp
+++ b/media/jni/android_media_MediaDrm.cpp
@@ -175,7 +175,7 @@
 
 struct OfflineLicenseState {
     jint kOfflineLicenseStateUsable;
-    jint kOfflineLicenseStateInactive;
+    jint kOfflineLicenseStateReleased;
     jint kOfflineLicenseStateUnknown;
 } gOfflineLicenseStates;
 
@@ -797,10 +797,10 @@
     GET_STATIC_FIELD_ID(field, clazz, "SECURITY_LEVEL_HW_SECURE_ALL", "I");
     gSecurityLevels.kSecurityLevelHwSecureAll = env->GetStaticIntField(clazz, field);
 
-    GET_STATIC_FIELD_ID(field, clazz, "OFFLINE_LICENSE_USABLE", "I");
+    GET_STATIC_FIELD_ID(field, clazz, "OFFLINE_LICENSE_STATE_USABLE", "I");
     gOfflineLicenseStates.kOfflineLicenseStateUsable = env->GetStaticIntField(clazz, field);
-    GET_STATIC_FIELD_ID(field, clazz, "OFFLINE_LICENSE_INACTIVE", "I");
-    gOfflineLicenseStates.kOfflineLicenseStateInactive = env->GetStaticIntField(clazz, field);
+    GET_STATIC_FIELD_ID(field, clazz, "OFFLINE_LICENSE_STATE_RELEASED", "I");
+    gOfflineLicenseStates.kOfflineLicenseStateReleased = env->GetStaticIntField(clazz, field);
     GET_STATIC_FIELD_ID(field, clazz, "OFFLINE_LICENSE_STATE_UNKNOWN", "I");
     gOfflineLicenseStates.kOfflineLicenseStateUnknown = env->GetStaticIntField(clazz, field);
 
@@ -1581,8 +1581,8 @@
     switch(state) {
     case DrmPlugin::kOfflineLicenseStateUsable:
         return gOfflineLicenseStates.kOfflineLicenseStateUsable;
-    case DrmPlugin::kOfflineLicenseStateInactive:
-        return gOfflineLicenseStates.kOfflineLicenseStateInactive;
+    case DrmPlugin::kOfflineLicenseStateReleased:
+        return gOfflineLicenseStates.kOfflineLicenseStateReleased;
     default:
         return gOfflineLicenseStates.kOfflineLicenseStateUnknown;
     }
diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp
index f3442f4..c6b171b 100644
--- a/media/jni/android_media_MediaExtractor.cpp
+++ b/media/jni/android_media_MediaExtractor.cpp
@@ -913,13 +913,9 @@
     }
 
     // build and return the Bundle
-    MediaAnalyticsItem *item = new MediaAnalyticsItem;
+    std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
     item->readFromParcel(reply);
-    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL);
-
-    // housekeeping
-    delete item;
-    item = NULL;
+    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
 
     return mybundle;
 }
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 76bbce7..35b1081 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -682,13 +682,9 @@
         return (jobject) NULL;
     }
 
-    MediaAnalyticsItem *item = new MediaAnalyticsItem;
+    std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
     item->readFromParcel(p);
-    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL);
-
-    // housekeeping
-    delete item;
-    item = NULL;
+    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
 
     return mybundle;
 }
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index ca30f32..a7c0159 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -664,15 +664,11 @@
     }
 
     // build and return the Bundle
-    MediaAnalyticsItem *item = new MediaAnalyticsItem;
+    std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
     item->readFromParcel(reply);
-    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL);
+    jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
 
-    // housekeeping
-    delete item;
-    item = NULL;
     return mybundle;
-
 }
 
 static jboolean
diff --git a/media/native/midi/include/Doxyfile b/media/native/midi/include/Doxyfile
new file mode 100644
index 0000000..2828f48
--- /dev/null
+++ b/media/native/midi/include/Doxyfile
@@ -0,0 +1,2494 @@
+# Doxyfile 1.8.13
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = "Android Native MIDI API (AMidi)"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =" Android Native MIDI API (AMidi)"
+
+# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
+# in the documentation. The maximum height of the logo should not exceed 55
+# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
+# the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       =
+
+# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = NO
+
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES        = YES
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
+# page for each member. If set to NO, the documentation of a member will be part
+# of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 4
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. For
+# instance to make doxygen treat .inc files as Fortran files (default is PHP),
+# and .f files as C (default is Fortran), use: inc=Fortran f=C.
+#
+# Note: For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
+# to that level are automatically included in the table of contents, even if
+# they do not have an id attribute.
+# Note: This feature currently applies only to Markdown headings.
+# Minimum value: 0, maximum value: 99, default value: 0.
+# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
+
+TOC_INCLUDE_HEADINGS   = 0
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# If one adds a struct or class to a group and this option is enabled, then also
+# any nested class or struct is added to the same group. By default this option
+# is disabled and one has to add nested compounds explicitly via \ingroup.
+# The default value is: NO.
+
+GROUP_NESTED_COMPOUNDS = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO,
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. If set to YES, local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO, only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO, these classes will be included in the various overviews. This option
+# has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO, these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO, these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES, upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES, the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
+# append additional text to a page's title, such as Class Reference. If set to
+# YES the compound reference will be hidden.
+# The default value is: NO.
+
+HIDE_COMPOUND_REFERENCE= NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
+# list. This list is created by putting \todo commands in the documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
+# list. This list is created by putting \test commands in the documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES, the
+# list will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = YES
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = YES
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO, doxygen will only warn about wrong or incomplete
+# parameter documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
+# a warning is encountered.
+# The default value is: NO.
+
+WARN_AS_ERROR          = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  = "midi.h"
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# read by doxygen.
+#
+# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
+# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
+# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
+# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
+# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.idl \
+                         *.ddl \
+                         *.odl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.cs \
+                         *.d \
+                         *.php \
+                         *.php4 \
+                         *.php5 \
+                         *.phtml \
+                         *.inc \
+                         *.m \
+                         *.markdown \
+                         *.md \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.pyw \
+                         *.f90 \
+                         *.f95 \
+                         *.f03 \
+                         *.f08 \
+                         *.f \
+                         *.for \
+                         *.tcl \
+                         *.vhd \
+                         *.vhdl \
+                         *.ucf \
+                         *.qsf
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS    = NO
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = YES
+
+# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
+# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
+# cost of reduced performance. This can be particularly helpful with template
+# rich C++ code for which doxygen's built-in parser lacks the necessary type
+# information.
+# Note: The availability of this option depends on whether or not doxygen was
+# generated with the -Duse-libclang=ON option for CMake.
+# The default value is: NO.
+
+CLANG_ASSISTED_PARSING = NO
+
+# If clang assisted parsing is enabled you can provide the compiler with command
+# line options that you would normally use when invoking the compiler. Note that
+# the include paths will already be set by doxygen for the files and directories
+# specified with INPUT and INCLUDE_PATH.
+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
+
+CLANG_OPTIONS          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefore more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the style sheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to YES can help to show when doxygen was last run and thus if the
+# documentation is up to date.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = NO
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler (hhc.exe). If non-empty,
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated
+# (YES) or that it should be included in the master .chm file (NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated
+# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = NO
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. The package can be specified just
+# by its name or with the correct syntax as to be used with the LaTeX
+# \usepackage command. To get the times font for instance you can specify :
+# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
+# To use the option intlimits with the amsmath package you can specify:
+# EXTRA_PACKAGES=[intlimits]{amsmath}
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
+# string, for the replacement values of the other commands the user is referred
+# to HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# LaTeX style sheets that are included after the standard style sheets created
+# by doxygen. Using this option one can overrule certain style aspects. Doxygen
+# will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_STYLESHEET =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES, to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_TIMESTAMP        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
+# with syntax highlighting in the RTF output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_SOURCE_CODE        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
+# AutoGen Definitions (see http://autogen.sf.net) file that captures the
+# structure of the code including all documentation. Note that this feature is
+# still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO, the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
+# in the source code. If set to NO, only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES, the include files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have
+# an all uppercase name, and do not end with a semicolon. Such function macros
+# are typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have a unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
+# the class index. If set to NO, only the inherited external classes will be
+# listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: YES.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = NO
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command. Disabling a call graph can be
+# accomplished by means of the command \hidecallgraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command. Disabling a caller graph can be
+# accomplished by means of the command \hidecallergraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. For an explanation of the image formats see the section
+# output formats in the documentation of the dot tool (Graphviz (see:
+# http://www.graphviz.org/)).
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,
+# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,
+# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,
+# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
+# png:gdiplus:gdiplus.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+
+PLANTUML_JAR_PATH      =
+
+# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
+# configuration file for plantuml.
+
+PLANTUML_CFG_FILE      =
+
+# When using plantuml, the specified paths are searched for files specified by
+# the !include statement in a plantuml block.
+
+PLANTUML_INCLUDE_PATH  =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES
diff --git a/media/native/midi/include/Doxyfile.orig b/media/native/midi/include/Doxyfile.orig
new file mode 100644
index 0000000..e56fb18
--- /dev/null
+++ b/media/native/midi/include/Doxyfile.orig
@@ -0,0 +1,2494 @@
+# Doxyfile 1.8.13
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = "My Project"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
+# in the documentation. The maximum height of the logo should not exceed 55
+# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
+# the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       =
+
+# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = NO
+
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES        = YES
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
+# page for each member. If set to NO, the documentation of a member will be part
+# of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 4
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. For
+# instance to make doxygen treat .inc files as Fortran files (default is PHP),
+# and .f files as C (default is Fortran), use: inc=Fortran f=C.
+#
+# Note: For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
+# to that level are automatically included in the table of contents, even if
+# they do not have an id attribute.
+# Note: This feature currently applies only to Markdown headings.
+# Minimum value: 0, maximum value: 99, default value: 0.
+# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
+
+TOC_INCLUDE_HEADINGS   = 0
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# If one adds a struct or class to a group and this option is enabled, then also
+# any nested class or struct is added to the same group. By default this option
+# is disabled and one has to add nested compounds explicitly via \ingroup.
+# The default value is: NO.
+
+GROUP_NESTED_COMPOUNDS = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO,
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. If set to YES, local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO, only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO, these classes will be included in the various overviews. This option
+# has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO, these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO, these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES, upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES, the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
+# append additional text to a page's title, such as Class Reference. If set to
+# YES the compound reference will be hidden.
+# The default value is: NO.
+
+HIDE_COMPOUND_REFERENCE= NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
+# list. This list is created by putting \todo commands in the documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
+# list. This list is created by putting \test commands in the documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES, the
+# list will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = YES
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO, doxygen will only warn about wrong or incomplete
+# parameter documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
+# a warning is encountered.
+# The default value is: NO.
+
+WARN_AS_ERROR          = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  =
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# read by doxygen.
+#
+# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
+# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
+# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
+# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
+# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.idl \
+                         *.ddl \
+                         *.odl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.cs \
+                         *.d \
+                         *.php \
+                         *.php4 \
+                         *.php5 \
+                         *.phtml \
+                         *.inc \
+                         *.m \
+                         *.markdown \
+                         *.md \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.pyw \
+                         *.f90 \
+                         *.f95 \
+                         *.f03 \
+                         *.f08 \
+                         *.f \
+                         *.for \
+                         *.tcl \
+                         *.vhd \
+                         *.vhdl \
+                         *.ucf \
+                         *.qsf
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = YES
+
+# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
+# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
+# cost of reduced performance. This can be particularly helpful with template
+# rich C++ code for which doxygen's built-in parser lacks the necessary type
+# information.
+# Note: The availability of this option depends on whether or not doxygen was
+# generated with the -Duse-libclang=ON option for CMake.
+# The default value is: NO.
+
+CLANG_ASSISTED_PARSING = NO
+
+# If clang assisted parsing is enabled you can provide the compiler with command
+# line options that you would normally use when invoking the compiler. Note that
+# the include paths will already be set by doxygen for the files and directories
+# specified with INPUT and INCLUDE_PATH.
+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
+
+CLANG_OPTIONS          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefore more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the style sheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to YES can help to show when doxygen was last run and thus if the
+# documentation is up to date.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = NO
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler (hhc.exe). If non-empty,
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated
+# (YES) or that it should be included in the master .chm file (NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated
+# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = YES
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. The package can be specified just
+# by its name or with the correct syntax as to be used with the LaTeX
+# \usepackage command. To get the times font for instance you can specify :
+# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
+# To use the option intlimits with the amsmath package you can specify:
+# EXTRA_PACKAGES=[intlimits]{amsmath}
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
+# string, for the replacement values of the other commands the user is referred
+# to HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# LaTeX style sheets that are included after the standard style sheets created
+# by doxygen. Using this option one can overrule certain style aspects. Doxygen
+# will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_STYLESHEET =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES, to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_TIMESTAMP        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
+# with syntax highlighting in the RTF output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_SOURCE_CODE        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
+# AutoGen Definitions (see http://autogen.sf.net) file that captures the
+# structure of the code including all documentation. Note that this feature is
+# still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO, the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
+# in the source code. If set to NO, only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES, the include files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have
+# an all uppercase name, and do not end with a semicolon. Such function macros
+# are typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have a unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
+# the class index. If set to NO, only the inherited external classes will be
+# listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: YES.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command. Disabling a call graph can be
+# accomplished by means of the command \hidecallgraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command. Disabling a caller graph can be
+# accomplished by means of the command \hidecallergraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. For an explanation of the image formats see the section
+# output formats in the documentation of the dot tool (Graphviz (see:
+# http://www.graphviz.org/)).
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,
+# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,
+# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,
+# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
+# png:gdiplus:gdiplus.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+
+PLANTUML_JAR_PATH      =
+
+# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
+# configuration file for plantuml.
+
+PLANTUML_CFG_FILE      =
+
+# When using plantuml, the specified paths are searched for files specified by
+# the !include statement in a plantuml block.
+
+PLANTUML_INCLUDE_PATH  =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES
diff --git a/packages/CaptivePortalLogin/Android.bp b/packages/CaptivePortalLogin/Android.bp
index b3e4e83..7acdfa1 100644
--- a/packages/CaptivePortalLogin/Android.bp
+++ b/packages/CaptivePortalLogin/Android.bp
@@ -17,7 +17,7 @@
 android_app {
     name: "CaptivePortalLogin",
     srcs: ["src/**/*.java"],
-    platform_apis: true,
+    sdk_version: "system_current",
     certificate: "platform",
     static_libs: [
         "androidx.legacy_legacy-support-v4",
diff --git a/packages/SettingsLib/ActionBarShadow/src/com/android/settingslib/widget/ActionBarShadowController.java b/packages/SettingsLib/ActionBarShadow/src/com/android/settingslib/widget/ActionBarShadowController.java
index 68ba5fb..be3365f 100644
--- a/packages/SettingsLib/ActionBarShadow/src/com/android/settingslib/widget/ActionBarShadowController.java
+++ b/packages/SettingsLib/ActionBarShadow/src/com/android/settingslib/widget/ActionBarShadowController.java
@@ -27,7 +27,6 @@
 import androidx.lifecycle.Lifecycle;
 import androidx.lifecycle.LifecycleObserver;
 import androidx.lifecycle.OnLifecycleEvent;
-import androidx.recyclerview.widget.RecyclerView;
 
 /**
  * UI controller that adds a shadow appear/disappear animation to action bar scroll.
@@ -41,40 +40,36 @@
 
     @VisibleForTesting
     ScrollChangeWatcher mScrollChangeWatcher;
-    private RecyclerView mRecyclerView;
+    private View mScrollView;
     private boolean mIsScrollWatcherAttached;
 
     /**
      * Wire up the animation to to an {@link Activity}. Shadow will be applied to activity's
      * action bar.
      */
-    public static ActionBarShadowController attachToRecyclerView(
-            Activity activity, Lifecycle lifecycle, RecyclerView recyclerView) {
-        return new ActionBarShadowController(activity, lifecycle, recyclerView);
+    public static ActionBarShadowController attachToView(
+            Activity activity, Lifecycle lifecycle, View scrollView) {
+        return new ActionBarShadowController(activity, lifecycle, scrollView);
     }
 
     /**
      * Wire up the animation to to a {@link View}. Shadow will be applied to the view.
      */
-    public static ActionBarShadowController attachToRecyclerView(
-            View anchorView, Lifecycle lifecycle, RecyclerView recyclerView) {
-        return new ActionBarShadowController(anchorView, lifecycle, recyclerView);
+    public static ActionBarShadowController attachToView(
+            View anchorView, Lifecycle lifecycle, View scrollView) {
+        return new ActionBarShadowController(anchorView, lifecycle, scrollView);
     }
 
-    private ActionBarShadowController(Activity activity, Lifecycle lifecycle,
-            RecyclerView recyclerView) {
-        mScrollChangeWatcher =
-                new ActionBarShadowController.ScrollChangeWatcher(activity);
-        mRecyclerView = recyclerView;
+    private ActionBarShadowController(Activity activity, Lifecycle lifecycle, View scrollView) {
+        mScrollChangeWatcher = new ActionBarShadowController.ScrollChangeWatcher(activity);
+        mScrollView = scrollView;
         attachScrollWatcher();
         lifecycle.addObserver(this);
     }
 
-    private ActionBarShadowController(View anchorView, Lifecycle lifecycle,
-            RecyclerView recyclerView) {
-        mScrollChangeWatcher =
-                new ActionBarShadowController.ScrollChangeWatcher(anchorView);
-        mRecyclerView = recyclerView;
+    private ActionBarShadowController(View anchorView, Lifecycle lifecycle, View scrollView) {
+        mScrollChangeWatcher = new ActionBarShadowController.ScrollChangeWatcher(anchorView);
+        mScrollView = scrollView;
         attachScrollWatcher();
         lifecycle.addObserver(this);
     }
@@ -83,21 +78,21 @@
     private void attachScrollWatcher() {
         if (!mIsScrollWatcherAttached) {
             mIsScrollWatcherAttached = true;
-            mRecyclerView.addOnScrollListener(mScrollChangeWatcher);
-            mScrollChangeWatcher.updateDropShadow(mRecyclerView);
+            mScrollView.setOnScrollChangeListener(mScrollChangeWatcher);
+            mScrollChangeWatcher.updateDropShadow(mScrollView);
         }
     }
 
     @OnLifecycleEvent(ON_STOP)
     private void detachScrollWatcher() {
-        mRecyclerView.removeOnScrollListener(mScrollChangeWatcher);
+        mScrollView.setOnScrollChangeListener(null);
         mIsScrollWatcherAttached = false;
     }
 
     /**
      * Update the drop shadow as the scrollable entity is scrolled.
      */
-    final class ScrollChangeWatcher extends RecyclerView.OnScrollListener {
+    final class ScrollChangeWatcher implements View.OnScrollChangeListener {
 
         private final Activity mActivity;
         private final View mAnchorView;
@@ -112,9 +107,9 @@
             mActivity = null;
         }
 
-        // RecyclerView scrolled.
         @Override
-        public void onScrolled(RecyclerView view, int dx, int dy) {
+        public void onScrollChange(View view, int scrollX, int scrollY, int oldScrollX,
+                int oldScrollY) {
             updateDropShadow(view);
         }
 
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 191bd8f..3e904a3 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -101,8 +101,6 @@
     <string name="connected_via_passpoint">Connected via %1$s</string>
     <!-- Status message of Wi-Fi when it is connected by a app (via suggestion or network request). [CHAR LIMIT=NONE] -->
     <string name="connected_via_app">Connected via <xliff:g id="name" example="Wifi App">%1$s</xliff:g></string>
-    <!-- Status message of Wi-Fi when it is connected by Passpoint configuration. [CHAR LIMIT=NONE] -->
-    <string name="ssid_by_passpoint_provider"><xliff:g id="ssid" example="Cafe Wifi">%1$s</xliff:g> by <xliff:g id="passpointProvider" example="Passpoint Provider">%2$s</xliff:g></string>
     <!-- Status message of Wi-Fi when network has matching passpoint credentials. [CHAR LIMIT=NONE] -->
     <string name="available_via_passpoint">Available via %1$s</string>
     <!-- Status message of OSU Provider network when not connected. [CHAR LIMIT=NONE] -->
diff --git a/packages/SettingsLib/src/com/android/settingslib/Utils.java b/packages/SettingsLib/src/com/android/settingslib/Utils.java
index c751c39..d32e85f 100644
--- a/packages/SettingsLib/src/com/android/settingslib/Utils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/Utils.java
@@ -56,37 +56,25 @@
 
     public static void updateLocationEnabled(Context context, boolean enabled, int userId,
             int source) {
+        LocationManager locationManager = context.getSystemService(LocationManager.class);
+
         Settings.Secure.putIntForUser(
                 context.getContentResolver(), Settings.Secure.LOCATION_CHANGER, source,
                 userId);
-        Intent intent = new Intent(LocationManager.MODE_CHANGING_ACTION);
 
-        final int oldMode = Settings.Secure.getIntForUser(context.getContentResolver(),
-                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF, userId);
+        Intent intent = new Intent(LocationManager.MODE_CHANGING_ACTION);
+        final int oldMode = locationManager.isLocationEnabled()
+                ? Settings.Secure.LOCATION_MODE_ON
+                : Settings.Secure.LOCATION_MODE_OFF;
         final int newMode = enabled
-                ? Settings.Secure.LOCATION_MODE_HIGH_ACCURACY
+                ? Settings.Secure.LOCATION_MODE_ON
                 : Settings.Secure.LOCATION_MODE_OFF;
         intent.putExtra(CURRENT_MODE_KEY, oldMode);
         intent.putExtra(NEW_MODE_KEY, newMode);
         context.sendBroadcastAsUser(
                 intent, UserHandle.of(userId), android.Manifest.permission.WRITE_SECURE_SETTINGS);
-        LocationManager locationManager =
-                (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
-        locationManager.setLocationEnabledForUser(enabled, UserHandle.of(userId));
-    }
 
-    public static boolean updateLocationMode(Context context, int oldMode, int newMode, int userId,
-            int source) {
-        Settings.Secure.putIntForUser(
-                context.getContentResolver(), Settings.Secure.LOCATION_CHANGER, source,
-                userId);
-        Intent intent = new Intent(LocationManager.MODE_CHANGING_ACTION);
-        intent.putExtra(CURRENT_MODE_KEY, oldMode);
-        intent.putExtra(NEW_MODE_KEY, newMode);
-        context.sendBroadcastAsUser(
-                intent, UserHandle.of(userId), android.Manifest.permission.WRITE_SECURE_SETTINGS);
-        return Settings.Secure.putIntForUser(
-                context.getContentResolver(), Settings.Secure.LOCATION_MODE, newMode, userId);
+        locationManager.setLocationEnabledForUser(enabled, UserHandle.of(userId));
     }
 
     /**
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
index ed8b487..ac2c2c9 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
@@ -899,8 +899,9 @@
         } else if (isActive()) {
             if (isPasspoint()) {
                 // This is the active connection on passpoint
-                summary.append(getSummary(mContext, ssid, getDetailedState(),
-                        false, null, mConfig.providerFriendlyName));
+                summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
+                        /* isEphemeral */ false,
+                        /* suggestionOrSpecifierPackageName */ null));
             } else if (mConfig != null && getDetailedState() == DetailedState.CONNECTED
                     && mIsCarrierAp) {
                 // This is the active connection on a carrier AP
@@ -908,7 +909,7 @@
                         mCarrierName));
             } else {
                 // This is the active connection on non-passpoint network
-                summary.append(getSummary(mContext, getDetailedState(),
+                summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
                         mInfo != null && mInfo.isEphemeral(),
                         mInfo != null ? mInfo.getNetworkSuggestionOrSpecifierPackageName() : null));
             }
@@ -1340,14 +1341,9 @@
     }
 
     public static String getSummary(Context context, String ssid, DetailedState state,
-            boolean isEphemeral, String suggestionOrSpecifierPackageName,
-            String passpointProvider) {
+            boolean isEphemeral, String suggestionOrSpecifierPackageName) {
         if (state == DetailedState.CONNECTED) {
-            if (!TextUtils.isEmpty(passpointProvider)) {
-                // Special case for connected + passpoint networks.
-                String format = context.getString(R.string.ssid_by_passpoint_provider);
-                return String.format(format, ssid, passpointProvider);
-            } else if (isEphemeral && !TextUtils.isEmpty(suggestionOrSpecifierPackageName)) {
+            if (isEphemeral && !TextUtils.isEmpty(suggestionOrSpecifierPackageName)) {
                 CharSequence appLabel =
                         getAppLabel(suggestionOrSpecifierPackageName, context.getPackageManager());
                 return context.getString(R.string.connected_via_app, appLabel);
@@ -1401,19 +1397,6 @@
         return String.format(formats[index], ssid);
     }
 
-    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
-                                    String suggestionOrSpecifierPackageName) {
-        return getSummary(context, null, state, isEphemeral, suggestionOrSpecifierPackageName,
-                null);
-    }
-
-    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
-                                    String suggestionOrSpecifierPackageName,
-                                    String passpointProvider) {
-        return getSummary(context, null, state, false, suggestionOrSpecifierPackageName,
-                passpointProvider);
-    }
-
     public static String convertToQuotedString(String string) {
         return "\"" + string + "\"";
     }
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
index 92ebe44..4d76e44 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
@@ -38,7 +38,6 @@
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.provider.Settings;
-import android.provider.Settings.Secure;
 import android.telephony.ServiceState;
 import android.text.TextUtils;
 
@@ -86,25 +85,6 @@
     }
 
     @Test
-    public void testUpdateLocationMode_sendBroadcast() {
-        int currentUserId = ActivityManager.getCurrentUser();
-        Utils.updateLocationMode(
-                mContext,
-                Secure.LOCATION_MODE_OFF,
-                Secure.LOCATION_MODE_HIGH_ACCURACY,
-                currentUserId,
-                Settings.Secure.LOCATION_CHANGER_QUICK_SETTINGS);
-
-        verify(mContext).sendBroadcastAsUser(
-                argThat(actionMatches(LocationManager.MODE_CHANGING_ACTION)),
-                ArgumentMatchers.eq(UserHandle.of(currentUserId)),
-                ArgumentMatchers.eq(WRITE_SECURE_SETTINGS));
-        assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
-                Settings.Secure.LOCATION_CHANGER, Settings.Secure.LOCATION_CHANGER_UNKNOWN))
-                .isEqualTo(Settings.Secure.LOCATION_CHANGER_QUICK_SETTINGS);
-    }
-
-    @Test
     public void testUpdateLocationEnabled_sendBroadcast() {
         int currentUserId = ActivityManager.getCurrentUser();
         Utils.updateLocationEnabled(mContext, true, currentUserId,
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/ActionBarShadowControllerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/ActionBarShadowControllerTest.java
index a25b512..4e00ab5 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/ActionBarShadowControllerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/ActionBarShadowControllerTest.java
@@ -22,6 +22,7 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -49,6 +50,8 @@
     @Mock
     private RecyclerView mRecyclerView;
     @Mock
+    private View mScrollView;
+    @Mock
     private Activity mActivity;
     @Mock
     private ActionBar mActionBar;
@@ -66,51 +69,60 @@
     }
 
     @Test
-    public void attachToRecyclerView_shouldAddScrollWatcherAndUpdateActionBar() {
+    public void attachToView_shouldAddScrollWatcherAndUpdateActionBar() {
         when(mRecyclerView.canScrollVertically(-1)).thenReturn(false);
 
-        ActionBarShadowController.attachToRecyclerView(mActivity, mLifecycle, mRecyclerView);
+        ActionBarShadowController.attachToView(mActivity, mLifecycle, mRecyclerView);
 
         verify(mActionBar).setElevation(ActionBarShadowController.ELEVATION_LOW);
     }
 
     @Test
-    public void attachToRecyclerView_customViewAsActionBar_shouldUpdateElevationOnScroll() {
+    public void attachToView_scrollView_shouldAddScrollWatcherAndUpdateActionBar() {
+        when(mScrollView.canScrollVertically(-1)).thenReturn(false);
+
+        ActionBarShadowController.attachToView(mActivity, mLifecycle, mScrollView);
+
+        verify(mActionBar).setElevation(ActionBarShadowController.ELEVATION_LOW);
+    }
+
+    @Test
+    public void attachToView_customViewAsActionBar_shouldUpdateElevationOnScroll() {
         // Setup
         mView.setElevation(50);
         when(mRecyclerView.canScrollVertically(-1)).thenReturn(false);
         final ActionBarShadowController controller =
-                ActionBarShadowController.attachToRecyclerView(mView, mLifecycle, mRecyclerView);
+                ActionBarShadowController.attachToView(mView, mLifecycle, mRecyclerView);
         assertThat(mView.getElevation()).isEqualTo(ActionBarShadowController.ELEVATION_LOW);
 
         // Scroll
         when(mRecyclerView.canScrollVertically(-1)).thenReturn(true);
-        controller.mScrollChangeWatcher.onScrolled(mRecyclerView, 10 /* dx */, 10 /* dy */);
+        controller.mScrollChangeWatcher.onScrollChange(mRecyclerView, 10, 10, 0, 0);
         assertThat(mView.getElevation()).isEqualTo(ActionBarShadowController.ELEVATION_HIGH);
     }
 
     @Test
-    public void attachToRecyclerView_lifecycleChange_shouldAttachDetach() {
-        ActionBarShadowController.attachToRecyclerView(mActivity, mLifecycle, mRecyclerView);
+    public void attachToView_lifecycleChange_shouldAttachDetach() {
+        ActionBarShadowController.attachToView(mActivity, mLifecycle, mRecyclerView);
 
-        verify(mRecyclerView).addOnScrollListener(any());
+        verify(mRecyclerView).setOnScrollChangeListener(any());
 
         mLifecycle.handleLifecycleEvent(ON_START);
         mLifecycle.handleLifecycleEvent(ON_STOP);
-        verify(mRecyclerView).removeOnScrollListener(any());
+        verify(mRecyclerView).setOnScrollChangeListener(isNull());
 
         mLifecycle.handleLifecycleEvent(ON_START);
-        verify(mRecyclerView, times(2)).addOnScrollListener(any());
+        verify(mRecyclerView, times(3)).setOnScrollChangeListener(any());
     }
 
     @Test
     public void onScrolled_nullAnchorViewAndActivity_shouldNotCrash() {
         final Activity activity = null;
         final ActionBarShadowController controller =
-                ActionBarShadowController.attachToRecyclerView(activity, mLifecycle, mRecyclerView);
+                ActionBarShadowController.attachToView(activity, mLifecycle, mRecyclerView);
 
         // Scroll
-        controller.mScrollChangeWatcher.onScrolled(mRecyclerView, 10 /* dx */, 10 /* dy */);
+        controller.mScrollChangeWatcher.onScrollChange(mRecyclerView, 10, 10, 0, 0);
         // no crash
     }
 }
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 6ca8261..479c964 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -2712,6 +2712,9 @@
         dumpSetting(s, p,
                 Settings.System.MUTE_STREAMS_AFFECTED,
                 SystemSettingsProto.Volume.MUTE_STREAMS_AFFECTED);
+        dumpSetting(s, p,
+                Settings.System.MASTER_BALANCE,
+                SystemSettingsProto.Volume.MASTER_BALANCE);
         p.end(volumeToken);
 
         dumpSetting(s, p,
diff --git a/packages/SystemUI/res-keyguard/values/styles.xml b/packages/SystemUI/res-keyguard/values/styles.xml
index b9966cf..8bbc270 100644
--- a/packages/SystemUI/res-keyguard/values/styles.xml
+++ b/packages/SystemUI/res-keyguard/values/styles.xml
@@ -103,4 +103,10 @@
         <item name="android:textSize">@dimen/widget_label_font_size</item>
     </style>
 
+    <style name="TextAppearance.Keyguard.BottomArea">
+        <item name="android:textSize">16sp</item>
+        <item name="android:maxLines">1</item>
+        <item name="android:textColor">?attr/wallpaperTextColor</item>
+    </style>
+
 </resources>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_bottompath_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_bottompath_animation.xml
deleted file mode 100644
index 073bf6d..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_bottompath_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="283"
-        android:propertyName="pathData"
-        android:valueFrom="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-        android:valueTo="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-        android:valueType="pathType"
-        android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_0" />
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_circlepath_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_circlepath_animation.xml
deleted file mode 100644
index 990392d..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_circlepath_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="383"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="1.0"
-        android:valueTo="0.0"
-        android:valueType="floatType"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_ellipse_path_1_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_ellipse_path_1_animation.xml
deleted file mode 100644
index a00d937..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_ellipse_path_1_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="350"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,-1.988645 c 1.09829830627,0.0 1.988645,0.890346693734 1.988645,1.988645 c 0.0,1.09829830627 -0.890346693734,1.988645 -1.988645,1.988645 c -1.09829830627,0.0 -1.988645,-0.890346693734 -1.988645,-1.988645 c 0.0,-1.09829830627 0.890346693734,-1.988645 1.988645,-1.988645 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_6" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_errorcircle_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_errorcircle_animation.xml
deleted file mode 100644
index 59d6232..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_errorcircle_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="33"
-            android:propertyName="rotation"
-            android:valueFrom="5.0"
-            android:valueTo="5.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="366"
-            android:propertyName="rotation"
-            android:valueFrom="5.0"
-            android:valueTo="-180.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_errorexclamationdot_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_errorexclamationdot_animation.xml
deleted file mode 100644
index 55bfa58..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_errorexclamationdot_animation.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="283"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 12.0,12.0 c 0.0,-0.66667 0.0,-3.33333 0.0,-4.0"
-        android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_5" />
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_exclamationtop_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_exclamationtop_animation.xml
deleted file mode 100644
index 4c44c6b..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_exclamationtop_animation.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="283"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 0.0,-2.0 c 0.0,0.5 0.0,2.5 0.0,3.0"
-        android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_2" />
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_lock_top_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_lock_top_animation.xml
deleted file mode 100644
index 6f7d692..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_lock_top_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="scaleX"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="66"
-            android:propertyName="scaleX"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="scaleY"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="66"
-            android:propertyName="scaleY"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_path_1_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_path_1_animation.xml
deleted file mode 100644
index 6821e62..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_path_1_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="283"
-            android:propertyName="pathData"
-            android:valueFrom="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.0118713378906,7.9296875 0.0118713378906,7.9296875 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 -0.01123046875,-7.9296875 -0.01123046875,-7.9296875 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueTo="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.0118713378906,7.9296875 0.0118713378906,7.9296875 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 -0.01123046875,-7.9296875 -0.01123046875,-7.9296875 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="pathData"
-            android:valueFrom="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.0118713378906,7.9296875 0.0118713378906,7.9296875 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 -0.01123046875,-7.9296875 -0.01123046875,-7.9296875 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueTo="M 6.00561523438,-4.046875 c 0.0,0.0 -5.98999023438,0.0 -5.98999023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 5.98812866211,0.0 5.98812866211,0.0 c 0.0,0.0 0.00064086914062,10.0 0.00064086914062,10.0 c 0.0,0.0 -5.98840332031,0.0 -5.98840332031,0.0 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 5.99487304688,0.0 5.99487304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 0.0,-10.0 0.0,-10.0 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_3" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="0.5"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_path_2_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_path_2_animation.xml
deleted file mode 100644
index a8251dc..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_path_2_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="283"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.01123046875,7.9296875 0.01123046875,7.9296875 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 -0.0108337402344,-7.92947387695 -0.0108337402344,-7.92947387695 Z"
-            android:valueTo="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.01123046875,7.9296875 0.01123046875,7.9296875 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 -0.0108337402344,-7.92947387695 -0.0108337402344,-7.92947387695 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.01123046875,7.9296875 0.01123046875,7.9296875 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 -0.0108337402344,-7.92947387695 -0.0108337402344,-7.92947387695 Z"
-            android:valueTo="M -5.9959564209,-2.04727172852 c 0.0,0.0 6.01173400879,0.00039672851562 6.01173400879,0.00039672851562 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -6.01000976562,0.0 -6.01000976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.0,10.0 0.0,10.0 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 6.01000976562,0.0 6.01000976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 -6.01171875,0.0003662109375 -6.01171875,0.0003662109375 c 0.0,0.0 0.00038146972656,-9.99978637695 0.00038146972656,-9.99978637695 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_3" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="0.5"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_path_3_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_path_3_animation.xml
deleted file mode 100644
index c1ece08..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_path_3_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="250"
-            android:propertyName="pathData"
-            android:valueFrom="M 5.01239013672,3.390625 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueTo="M 5.01239013672,3.390625 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="pathData"
-            android:valueFrom="M 5.01239013672,3.390625 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueTo="M 5.00619506836,-6.046875 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_4" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/error_to_trustedstate_toppath_animation.xml b/packages/SystemUI/res/anim/error_to_trustedstate_toppath_animation.xml
deleted file mode 100644
index d9781df..0000000
--- a/packages/SystemUI/res/anim/error_to_trustedstate_toppath_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="66"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueTo="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueTo="M 0.0,-6.0 l 0.0,0.0 c 1.9329966243,0.0 3.5,1.5670033757 3.5,3.5 l 0.0,5.0 c 0.0,1.9329966243 -1.5670033757,3.5 -3.5,3.5 l 0.0,0.0 c -1.9329966243,0.0 -3.5,-1.5670033757 -3.5,-3.5 l 0.0,-5.0 c 0.0,-1.9329966243 1.5670033757,-3.5 3.5,-3.5 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/error_to_trustedstate_animation_interpolator_0" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="283"
-            android:propertyName="fillAlpha"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_bottompath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_bottompath_animation.xml
deleted file mode 100644
index 91829c0..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_bottompath_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="316"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="83"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_5" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_circlepath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_circlepath_animation.xml
deleted file mode 100644
index 9b08fa2..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_circlepath_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="166"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="533"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorcircle_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorcircle_animation.xml
deleted file mode 100644
index 1ea2100..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorcircle_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="rotation"
-            android:valueFrom="190.0"
-            android:valueTo="190.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="549"
-            android:propertyName="rotation"
-            android:valueFrom="190.0"
-            android:valueTo="-6.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_2" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorexclamation_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorexclamation_animation.xml
deleted file mode 100644
index 0b9cb95..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_errorexclamation_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="rotation"
-            android:valueFrom="180.0"
-            android:valueTo="180.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="499"
-            android:propertyName="rotation"
-            android:valueFrom="180.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_6" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationbottom_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationbottom_animation.xml
deleted file mode 100644
index c597b82..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationbottom_animation.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" />
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationtop_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationtop_animation.xml
deleted file mode 100644
index bde83de..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_exclamationtop_animation.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="700"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 0.0,0.0 c 0.0,-0.33333 0.0,-1.66667 0.0,-2.0"
-        android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_3" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprinterror_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprinterror_animation.xml
deleted file mode 100644
index a3afaef..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprinterror_animation.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="100"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="566"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="-305.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_2" />
-        <objectAnimator
-            android:duration="1066"
-            android:propertyName="rotation"
-            android:valueFrom="-305.0"
-            android:valueTo="-305.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-        <objectAnimator
-            android:duration="800"
-            android:propertyName="rotation"
-            android:valueFrom="-305.0"
-            android:valueTo="-720.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprintwhite_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprintwhite_animation.xml
deleted file mode 100644
index a3afaef..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_fingerprintwhite_animation.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="100"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="566"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="-305.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_2" />
-        <objectAnimator
-            android:duration="1066"
-            android:propertyName="rotation"
-            android:valueFrom="-305.0"
-            android:valueTo="-305.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-        <objectAnimator
-            android:duration="800"
-            android:propertyName="rotation"
-            android:valueFrom="-305.0"
-            android:valueTo="-720.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_0_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_0_animation.xml
deleted file mode 100644
index 1c3a766..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_0_animation.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="133"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="0.0"
-        android:valueTo="1.0"
-        android:valueType="floatType"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="100"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="100"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_animation.xml
deleted file mode 100644
index 5a9258a..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_1_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="66"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_0_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_0_animation.xml
deleted file mode 100644
index 04b8b80..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_0_animation.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="116"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="116"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_2" />
-    </set>
-    <objectAnimator
-        android:duration="166"
-        android:propertyName="trimPathStart"
-        android:valueFrom="1.0"
-        android:valueTo="0.0"
-        android:valueType="floatType"
-        android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_2" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_animation.xml
deleted file mode 100644
index c69001c..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_2_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="133"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_0_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_0_animation.xml
deleted file mode 100644
index 6fb22cd..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_0_animation.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="166"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="0.0"
-        android:valueTo="1.0"
-        android:valueType="floatType"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="166"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_animation.xml
deleted file mode 100644
index 8e9a0510..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_5_path_animation.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="150"
-        android:propertyName="trimPathStart"
-        android:valueFrom="0.0"
-        android:valueTo="1.0"
-        android:valueType="floatType"
-        android:interpolator="@android:interpolator/linear" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_0_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_0_animation.xml
deleted file mode 100644
index 3ffb8f8..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_0_animation.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="250"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="0.0"
-        android:valueTo="1.0"
-        android:valueType="floatType"
-        android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="133"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="199"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_animation.xml
deleted file mode 100644
index 3584f91..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_6_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_0_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_0_animation.xml
deleted file mode 100644
index 0d44810..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_0_animation.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="133"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="199"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_animation.xml
deleted file mode 100644
index 52a5b3e..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_ridge_7_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="33"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_toerror_toppath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_toerror_toppath_animation.xml
deleted file mode 100644
index ff7420b..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_toerror_toppath_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M -1.0,0.0 l 2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l -2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M -1.0,0.0 l 2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l -2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="499"
-            android:propertyName="pathData"
-            android:valueFrom="M -1.0,0.0 l 2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l -2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/ic_fingerprint_toerror_animation_interpolator_4" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_bottompath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_bottompath_animation.xml
deleted file mode 100644
index 4bc18f2..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_bottompath_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="250"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-            android:valueTo="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-            android:valueTo="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_circlepath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_circlepath_animation.xml
deleted file mode 100644
index 9273b9a..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_circlepath_animation.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="383"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="1.0"
-        android:valueTo="0.0"
-        android:valueType="floatType"
-        android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_4" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorcircle_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorcircle_animation.xml
deleted file mode 100644
index 062c6a0..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorcircle_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="33"
-            android:propertyName="rotation"
-            android:valueFrom="10.0"
-            android:valueTo="10.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="366"
-            android:propertyName="rotation"
-            android:valueFrom="10.0"
-            android:valueTo="-180.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_2" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorexclamation_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorexclamation_animation.xml
deleted file mode 100644
index 5d4b268..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_errorexclamation_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="33"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="416"
-            android:propertyName="rotation"
-            android:valueFrom="0.0"
-            android:valueTo="-180.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_5" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationbottom_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationbottom_animation.xml
deleted file mode 100644
index d3d7d1c..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationbottom_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="450"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 0.0,4.0 c 0.0,-0.66667 0.0,-3.33333 0.0,-4.0"
-        android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_0" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationtop_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationtop_animation.xml
deleted file mode 100644
index 04b6868..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_exclamationtop_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="450"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 0.0,-2.0 c 0.0,0.33333 0.0,1.66667 0.0,2.0"
-        android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_3" />
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_fingerprintwhite_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_fingerprintwhite_animation.xml
deleted file mode 100644
index 25f2c43..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_fingerprintwhite_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="rotation"
-            android:valueFrom="180.0"
-            android:valueTo="180.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="499"
-            android:propertyName="rotation"
-            android:valueFrom="180.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_2" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_1_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_1_path_animation.xml
deleted file mode 100644
index 4a6f39a..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_1_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="416"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="116"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_2_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_2_path_animation.xml
deleted file mode 100644
index c9a9f64..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_2_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="350"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="116"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_5_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_5_path_animation.xml
deleted file mode 100644
index 43e44cf..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_5_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="350"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="350"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_6_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_6_path_animation.xml
deleted file mode 100644
index 04a6036..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_6_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="250"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="250"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_7_path_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_7_path_animation.xml
deleted file mode 100644
index 031c5e6..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_ridge_7_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="266"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="433"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/ic_fingerprint_tofp_toppath_animation.xml b/packages/SystemUI/res/anim/ic_fingerprint_tofp_toppath_animation.xml
deleted file mode 100644
index 9b3498f..0000000
--- a/packages/SystemUI/res/anim/ic_fingerprint_tofp_toppath_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueTo="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="250"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueTo="M -1.0,0.0 l 2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l -2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/ic_fingerprint_tofp_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_1_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_1_path_animation.xml
deleted file mode 100644
index 18bc8a2..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_1_path_animation.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="60"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_off_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_2_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_2_path_animation.xml
deleted file mode 100644
index 531fac0..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_2_path_animation.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="140"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="1.0"
-        android:valueTo="0.0"
-        android:valueType="floatType"
-        android:interpolator="@interpolator/lockscreen_fingerprint_draw_off_animation_interpolator_0" />
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_5_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_5_path_animation.xml
deleted file mode 100644
index 87c7f21..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_5_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="20"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="180"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_off_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_6_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_6_path_animation.xml
deleted file mode 100644
index e0a66d9..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_6_path_animation.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="190"
-        android:propertyName="trimPathEnd"
-        android:valueFrom="1.0"
-        android:valueTo="0.0"
-        android:valueType="floatType"
-        android:interpolator="@interpolator/lockscreen_fingerprint_draw_off_animation_interpolator_1" />
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_7_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_7_path_animation.xml
deleted file mode 100644
index 9b0e17b..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_off_ridge_7_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="10"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="160"
-            android:propertyName="trimPathStart"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_off_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_1_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_1_path_animation.xml
deleted file mode 100644
index eb323f5..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_1_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="316"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="383"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_on_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_2_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_2_path_animation.xml
deleted file mode 100644
index cae4a70..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_2_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="216"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="400"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_on_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_5_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_5_path_animation.xml
deleted file mode 100644
index 0be6c9e..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_5_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="33"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="383"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_on_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_6_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_6_path_animation.xml
deleted file mode 100644
index 5d2cdb6..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_6_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="50"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="549"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_on_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_7_path_animation.xml b/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_7_path_animation.xml
deleted file mode 100644
index 6f8b559..0000000
--- a/packages/SystemUI/res/anim/lockscreen_fingerprint_draw_on_ridge_7_path_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="83"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="483"
-            android:propertyName="trimPathEnd"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/lockscreen_fingerprint_draw_on_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_bottompath_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_bottompath_animation.xml
deleted file mode 100644
index 7a01896..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_bottompath_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="149"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-            android:valueTo="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_circlepath_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_circlepath_animation.xml
deleted file mode 100644
index ac5e448..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_circlepath_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="100"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="450"
-            android:propertyName="trimPathStart"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/fast_out_slow_in" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_ellipse_path_1_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_ellipse_path_1_animation.xml
deleted file mode 100644
index 6697316..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_ellipse_path_1_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="200"
-        android:propertyName="pathData"
-        android:valueFrom="M 0.0,-1.988645 c 1.09829830627,0.0 1.988645,0.890346693734 1.988645,1.988645 c 0.0,1.09829830627 -0.890346693734,1.988645 -1.988645,1.988645 c -1.09829830627,0.0 -1.988645,-0.890346693734 -1.988645,-1.988645 c 0.0,-1.09829830627 0.890346693734,-1.988645 1.988645,-1.988645 Z"
-        android:valueTo="M 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z"
-        android:valueType="pathType"
-        android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_errorcircle_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_errorcircle_animation.xml
deleted file mode 100644
index 903d97e..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_errorcircle_animation.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="50"
-            android:propertyName="rotation"
-            android:valueFrom="184.0"
-            android:valueTo="184.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="450"
-            android:propertyName="rotation"
-            android:valueFrom="184.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_1" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_errorexclamationdot_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_errorexclamationdot_animation.xml
deleted file mode 100644
index c5339a0..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_errorexclamationdot_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="550"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 12.0,8.0 c 0.0,0.66667 0.0,3.33333 0.0,4.0"
-        android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_3" />
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_exclamationtop_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_exclamationtop_animation.xml
deleted file mode 100644
index c5b2c12..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_exclamationtop_animation.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <objectAnimator
-        android:duration="500"
-        android:propertyXName="translateX"
-        android:propertyYName="translateY"
-        android:pathData="M 0.0,2.5 c 0.0,-0.75 0.0,-3.75 0.0,-4.5"
-        android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_4" />
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_lock_top_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_lock_top_animation.xml
deleted file mode 100644
index 63a25d9..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_lock_top_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="scaleX"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="scaleX"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="scaleY"
-            android:valueFrom="1.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="scaleY"
-            android:valueFrom="1.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_path_1_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_path_1_animation.xml
deleted file mode 100644
index 547f42e..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_path_1_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M 6.00561523438,-4.046875 c 0.0,0.0 -5.98999023438,0.0 -5.98999023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 5.98812866211,0.0 5.98812866211,0.0 c 0.0,0.0 0.00064086914062,10.0 0.00064086914062,10.0 c 0.0,0.0 -5.98840332031,0.0 -5.98840332031,0.0 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 5.99487304688,0.0 5.99487304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 0.0,-10.0 0.0,-10.0 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueTo="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.00064086914062,10.625 0.00064086914062,10.625 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 0.0,-10.625 0.0,-10.625 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
-        <objectAnimator
-            android:duration="149"
-            android:propertyName="pathData"
-            android:valueFrom="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.00064086914062,10.625 0.00064086914062,10.625 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 0.0,-10.625 0.0,-10.625 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-            android:valueTo="M 0.02685546875,-4.96875 c 0.0,0.0 -0.005615234375,0.015625 -0.005615234375,0.015625 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 -0.00936889648438,3.9296875 -0.00936889648438,3.9296875 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0028076171875,0.0234375 -0.0028076171875,0.0234375 c 0.0,0.0 0.010498046875,-0.015625 0.010498046875,-0.015625 c 0.0,0.0 0.985595703125,0.0078125 0.985595703125,0.0078125 c 0.0,0.0 0.017578125,-6.015625 0.017578125,-6.015625 c 0.0,0.0 0.104400634766,0.0546875 -0.99560546875,0.0546875 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_5" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="183"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.5"
-            android:valueTo="0.5"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.5"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_path_2_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_path_2_animation.xml
deleted file mode 100644
index e5fe4d1..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_path_2_animation.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M -5.9959564209,-2.04727172852 c 0.0,0.0 6.01173400879,0.00039672851562 6.01173400879,0.00039672851562 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -6.01000976562,0.0 -6.01000976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.0,10.0 0.0,10.0 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 6.01000976562,0.0 6.01000976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 -6.01171875,0.0003662109375 -6.01171875,0.0003662109375 c 0.0,0.0 0.00038146972656,-9.99978637695 0.00038146972656,-9.99978637695 Z"
-            android:valueTo="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.0,10.625 0.0,10.625 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 0.00039672851562,-10.624786377 0.00039672851562,-10.624786377 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
-        <objectAnimator
-            android:duration="149"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.0,10.625 0.0,10.625 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 0.00039672851562,-10.624786377 0.00039672851562,-10.624786377 Z"
-            android:valueTo="M 0.0252990722656,-2.96914672852 c 0.0,0.0 -0.00390625,0.0160217285156 -0.00390625,0.0160217285156 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 0.005615234375,-0.015625 0.005615234375,-0.015625 c -1.10000610352,0.0 -1.01220703125,-0.0546875 -1.01220703125,-0.0546875 c 0.0,0.0 -0.017578125,6.015625 -0.017578125,6.015625 c 0.0,0.0 -0.0777893066406,-0.0078125 1.02221679688,-0.0078125 c 0.0,0.0 -0.005615234375,0.015625 -0.005615234375,0.015625 c 0.0,0.0 -0.002685546875,-0.0244140625 -0.002685546875,-0.0244140625 c 0.0,0.0 0.00390625,-0.0152587890625 0.00390625,-0.0152587890625 c 0.0,0.0 0.0104064941406,-3.92947387695 0.0104064941406,-3.92947387695 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_5" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="183"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.5"
-            android:valueTo="0.5"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.5"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_path_3_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_path_3_animation.xml
deleted file mode 100644
index 455d0b8..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_path_3_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="50"
-            android:propertyName="pathData"
-            android:valueFrom="M 5.00619506836,-6.046875 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueTo="M 5.00619506836,-6.046875 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="150"
-            android:propertyName="pathData"
-            android:valueFrom="M 5.00619506836,-6.046875 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueTo="M 5.01239013672,3.390625 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/anim/trusted_state_to_error_toppath_animation.xml b/packages/SystemUI/res/anim/trusted_state_to_error_toppath_animation.xml
deleted file mode 100644
index b2944e5..0000000
--- a/packages/SystemUI/res/anim/trusted_state_to_error_toppath_animation.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<set
-    xmlns:android="http://schemas.android.com/apk/res/android" >
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="200"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-7.0 l 0.0,0.0 c 1.9329966243,0.0 3.5,1.5670033757 3.5,3.5 l 0.0,7.0 c 0.0,1.9329966243 -1.5670033757,3.5 -3.5,3.5 l 0.0,0.0 c -1.9329966243,0.0 -3.5,-1.5670033757 -3.5,-3.5 l 0.0,-7.0 c 0.0,-1.9329966243 1.5670033757,-3.5 3.5,-3.5 Z"
-            android:valueTo="M 0.0,-7.0 l 0.0,0.0 c 1.9329966243,0.0 3.5,1.5670033757 3.5,3.5 l 0.0,7.0 c 0.0,1.9329966243 -1.5670033757,3.5 -3.5,3.5 l 0.0,0.0 c -1.9329966243,0.0 -3.5,-1.5670033757 -3.5,-3.5 l 0.0,-7.0 c 0.0,-1.9329966243 1.5670033757,-3.5 3.5,-3.5 Z"
-            android:valueType="pathType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="300"
-            android:propertyName="pathData"
-            android:valueFrom="M 0.0,-7.0 l 0.0,0.0 c 1.9329966243,0.0 3.5,1.5670033757 3.5,3.5 l 0.0,7.0 c 0.0,1.9329966243 -1.5670033757,3.5 -3.5,3.5 l 0.0,0.0 c -1.9329966243,0.0 -3.5,-1.5670033757 -3.5,-3.5 l 0.0,-7.0 c 0.0,-1.9329966243 1.5670033757,-3.5 3.5,-3.5 Z"
-            android:valueTo="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z"
-            android:valueType="pathType"
-            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_2" />
-    </set>
-    <set
-        android:ordering="sequentially" >
-        <objectAnimator
-            android:duration="183"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="0.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-        <objectAnimator
-            android:duration="16"
-            android:propertyName="fillAlpha"
-            android:valueFrom="0.0"
-            android:valueTo="1.0"
-            android:valueType="floatType"
-            android:interpolator="@android:interpolator/linear" />
-    </set>
-</set>
diff --git a/packages/SystemUI/res/drawable/error_to_trustedstate.xml b/packages/SystemUI/res/drawable/error_to_trustedstate.xml
deleted file mode 100755
index bc196c9..0000000
--- a/packages/SystemUI/res/drawable/error_to_trustedstate.xml
+++ /dev/null
@@ -1,105 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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:name="error_to_trustedstate"
-    android:width="24dp"
-    android:viewportWidth="24"
-    android:height="24dp"
-    android:viewportHeight="24" >
-    <group
-        android:name="lock"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="middle_ellipse"
-            android:translateY="2.9375" >
-            <path
-                android:name="ellipse_path_1"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5"
-                android:pathData="M 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z" />
-        </group>
-        <group
-            android:name="lock_right_side" >
-            <path
-                android:name="path_1"
-                android:pathData="M 1.63623046875,-4.953125 c 0.0,0.0 -1.61499023438,0.0 -1.61499023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 0.00375366210938,-0.015625 0.00375366210938,-0.015625 c 0.0,0.0 0.0118713378906,7.9296875 0.0118713378906,7.9296875 c 0.0,0.0 -0.0040283203125,0.015625 -0.0040283203125,0.015625 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 1.61987304688,0.0 1.61987304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 -0.01123046875,-7.9296875 -0.01123046875,-7.9296875 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-        <group
-            android:name="lock_left_side" >
-            <path
-                android:name="path_2"
-                android:pathData="M 0.0252990722656,-2.96975708008 c 0.0,0.0 -0.00390625,0.0166320800781 -0.00390625,0.0166320800781 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -1.63500976562,0.0 -1.63500976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.01123046875,7.9296875 0.01123046875,7.9296875 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 1.63500976562,0.0 1.63500976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 0.00390625,-0.015869140625 0.00390625,-0.015869140625 c 0.0,0.0 -0.0108337402344,-7.92947387695 -0.0108337402344,-7.92947387695 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-        <group
-            android:name="lock_top"
-            android:scaleX="0"
-            android:scaleY="0" >
-            <path
-                android:name="path_3"
-                android:pathData="M 5.01239013672,3.390625 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamationdot"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="exclamationbottom"
-            android:translateY="4" >
-            <path
-                android:name="bottompath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamation"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="exclamationtop"
-            android:translateY="-2" >
-            <path
-                android:name="toppath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorcircle"
-        android:translateX="12"
-        android:translateY="12"
-        android:rotation="5" >
-        <group
-            android:name="circle" >
-            <path
-                android:name="circlepath"
-                android:strokeColor="?android:attr/colorError"
-                android:strokeWidth="2"
-                android:strokeLineCap="round"
-                android:pathData="M 0.0,-9.0 c 4.9705627482,0.0 9.0,4.0294372518 9.0,9.0 c 0.0,4.9705627482 -4.0294372518,9.0 -9.0,9.0 c -4.9705627482,0.0 -9.0,-4.0294372518 -9.0,-9.0 c 0.0,-4.9705627482 4.0294372518,-9.0 9.0,-9.0 Z" />
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/error_to_trustedstate_animation.xml b/packages/SystemUI/res/drawable/error_to_trustedstate_animation.xml
deleted file mode 100755
index a494f1d..0000000
--- a/packages/SystemUI/res/drawable/error_to_trustedstate_animation.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/error_to_trustedstate" >
-    <target
-        android:name="ellipse_path_1"
-        android:animation="@anim/error_to_trustedstate_ellipse_path_1_animation" />
-    <target
-        android:name="path_1"
-        android:animation="@anim/error_to_trustedstate_path_1_animation" />
-    <target
-        android:name="path_2"
-        android:animation="@anim/error_to_trustedstate_path_2_animation" />
-    <target
-        android:name="lock_top"
-        android:animation="@anim/error_to_trustedstate_lock_top_animation" />
-    <target
-        android:name="path_3"
-        android:animation="@anim/error_to_trustedstate_path_3_animation" />
-    <target
-        android:name="errorexclamationdot"
-        android:animation="@anim/error_to_trustedstate_errorexclamationdot_animation" />
-    <target
-        android:name="bottompath"
-        android:animation="@anim/error_to_trustedstate_bottompath_animation" />
-    <target
-        android:name="exclamationtop"
-        android:animation="@anim/error_to_trustedstate_exclamationtop_animation" />
-    <target
-        android:name="toppath"
-        android:animation="@anim/error_to_trustedstate_toppath_animation" />
-    <target
-        android:name="errorcircle"
-        android:animation="@anim/error_to_trustedstate_errorcircle_animation" />
-    <target
-        android:name="circlepath"
-        android:animation="@anim/error_to_trustedstate_circlepath_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/drawable/ic_face_unlock.xml b/packages/SystemUI/res/drawable/ic_face_unlock.xml
deleted file mode 100644
index b302ed4..0000000
--- a/packages/SystemUI/res/drawable/ic_face_unlock.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<!--
-  ~ Copyright (C) 2018 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:viewportHeight="24.0"
-        android:viewportWidth="24.0">
-    <path android:fillColor="?attr/wallpaperTextColor"
-          android:strokeColor="?attr/wallpaperTextColor"
-          android:strokeWidth="1"
-          android:pathData="M9,11.75C8.31,11.75 7.75,12.31 7.75,13C7.75,13.69 8.31,14.25 9,14.25C9.69,14.25 10.25,13.69 10.25,13C10.25,12.31 9.69,11.75 9,11.75ZM15,11.75C14.31,11.75 13.75,12.31 13.75,13C13.75,13.69 14.31,14.25 15,14.25C15.69,14.25 16.25,13.69 16.25,13C16.25,12.31 15.69,11.75 15,11.75ZM12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2ZM12,20C7.59,20 4,16.41 4,12C4,11.71 4.02,11.42 4.05,11.14C6.41,10.09 8.28,8.16 9.26,5.77C11.07,8.33 14.05,10 17.42,10C18.2,10 18.95,9.91 19.67,9.74C19.88,10.45 20,11.21 20,12C20,16.41 16.41,20 12,20Z"
-    />
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_fingerprint_error.xml b/packages/SystemUI/res/drawable/ic_fingerprint_error.xml
deleted file mode 100644
index a7fb1a1..0000000
--- a/packages/SystemUI/res/drawable/ic_fingerprint_error.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
-Copyright (C) 2015 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="32.0dp"
-        android:height="32.0dp"
-        android:viewportWidth="32.0"
-        android:viewportHeight="32.0">
-    <path
-        android:fillColor="?android:attr/colorError"
-        android:pathData="M15.99,2.5C8.53,2.5 2.5,8.54 2.5,16.0s6.03,13.5 13.49,13.5S29.5,23.46 29.5,16.0S23.45,2.5 15.99,2.5zM16.0,26.8c-5.97,0.0 -10.8,-4.83 -10.8,-10.8S10.03,5.2 16.0,5.2S26.8,10.03 26.8,16.0S21.97,26.8 16.0,26.8z"/>
-    <path
-        android:fillColor="?android:attr/colorError"
-        android:pathData="M14.65,20.05l2.7,0.0l0.0,2.7l-2.7,0.0z"/>
-    <path
-        android:fillColor="?android:attr/colorError"
-        android:pathData="M14.65,9.25l2.7,0.0l0.0,8.1l-2.7,0.0z"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_lock.xml b/packages/SystemUI/res/drawable/ic_lock.xml
deleted file mode 100644
index 3fb8c8d..0000000
--- a/packages/SystemUI/res/drawable/ic_lock.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-  ~ Copyright (C) 2018 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="32dp"
-        android:height="32dp"
-        android:viewportWidth="32.0"
-        android:viewportHeight="32.0">
-    <path
-        android:pathData="M20.25,6.89C20.25,4.62 18.36,2.75 16,2.75C13.64,2.75 11.75,4.62 11.75,6.89V11.25H20.25V6.89ZM21.75,11.25V6.89C21.75,3.76 19.16,1.25 16,1.25C12.84,1.25 10.25,3.76 10.25,6.89V11.25H10C8.48,11.25 7.25,12.48 7.25,14V26C7.25,27.52 8.48,28.75 10,28.75H22C23.52,28.75 24.75,27.52 24.75,26V14C24.75,12.48 23.52,11.25 22,11.25H21.75ZM10,12.75C9.31,12.75 8.75,13.31 8.75,14V26C8.75,26.69 9.31,27.25 10,27.25H22C22.69,27.25 23.25,26.69 23.25,26V14C23.25,13.31 22.69,12.75 22,12.75H10ZM18,20C18,21.1 17.1,22 16,22C14.9,22 14,21.1 14,20C14,18.9 14.9,18 16,18C17.1,18 18,18.9 18,20Z"
-        android:fillType="evenOdd"
-        android:fillColor="?attr/wallpaperTextColor"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_lock_open.xml b/packages/SystemUI/res/drawable/ic_lock_open.xml
deleted file mode 100644
index 12a811c..0000000
--- a/packages/SystemUI/res/drawable/ic_lock_open.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-  ~ Copyright (C) 2018 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="32dp"
-        android:height="32dp"
-        android:viewportWidth="32.0"
-        android:viewportHeight="32.0">
-    <path
-        android:pathData="M21.75,6.89C21.75,4.62 23.64,2.75 26,2.75C28.36,2.75 30.25,4.62 30.25,6.89V12H31.75V6.89C31.75,3.76 29.16,1.25 26,1.25C22.84,1.25 20.25,3.76 20.25,6.89V11.25H10C8.48,11.25 7.25,12.48 7.25,14V26C7.25,27.52 8.48,28.75 10,28.75H22C23.52,28.75 24.75,27.52 24.75,26V14C24.75,12.48 23.52,11.25 22,11.25H21.75V6.89ZM10,12.75C9.31,12.75 8.75,13.31 8.75,14V26C8.75,26.69 9.31,27.25 10,27.25H22C22.69,27.25 23.25,26.69 23.25,26V14C23.25,13.31 22.69,12.75 22,12.75H10ZM18,20C18,21.1 17.1,22 16,22C14.9,22 14,21.1 14,20C14,18.9 14.9,18 16,18C17.1,18 18,18.9 18,20Z"
-        android:fillType="evenOdd"
-        android:fillColor="?attr/wallpaperTextColor"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_open_in_new.xml b/packages/SystemUI/res/drawable/ic_open_in_new.xml
new file mode 100644
index 0000000..3d53871
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_open_in_new.xml
@@ -0,0 +1,23 @@
+<!-- Copyright (C) 2019 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"
+        android:viewportHeight="24">
+    <path
+        android:fillColor="#FF000000"
+        android:pathData="M19,19H5V5h7V3H5c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2v-7h-2v7zM14,3v2h3.59l-9.83,9.83 1.41,1.41L19,6.41V10h2V3h-7z"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off.xml
deleted file mode 100644
index 8d382a3..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off.xml
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2017 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:name="lockscreen_fingerprint_draw_off"
-    android:width="32dp"
-    android:viewportWidth="32"
-    android:height="32dp"
-    android:viewportHeight="32" >
-    <group
-        android:name="white_fingerprint_ridges"
-        android:translateX="16.125"
-        android:translateY="19.75" >
-        <group
-            android:name="white_fingerprint_ridges_pivot"
-            android:translateX="33.2085"
-            android:translateY="30.91685" >
-            <group
-                android:name="ridge_5" >
-                <path
-                    android:name="ridge_5_path"
-                    android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_4" >
-                <path
-                    android:name="ridge_7_path"
-                    android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_3" >
-                <path
-                    android:name="ridge_6_path"
-                    android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_2" >
-                <path
-                    android:name="ridge_2_path"
-                    android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_1"
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:name="ridge_1_path"
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off_animation.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off_animation.xml
deleted file mode 100644
index 1599577..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_off_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/lockscreen_fingerprint_draw_off" >
-    <target
-        android:name="ridge_5_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_off_ridge_5_path_animation" />
-    <target
-        android:name="ridge_7_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_off_ridge_7_path_animation" />
-    <target
-        android:name="ridge_6_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_off_ridge_6_path_animation" />
-    <target
-        android:name="ridge_2_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_off_ridge_2_path_animation" />
-    <target
-        android:name="ridge_1_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_off_ridge_1_path_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on.xml
deleted file mode 100644
index 4fe160d..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on.xml
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2017 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:name="lockscreen_fingerprint_draw_on"
-    android:width="32dp"
-    android:viewportWidth="32"
-    android:height="32dp"
-    android:viewportHeight="32" >
-    <group
-        android:name="white_fingerprint_ridges"
-        android:translateX="16.125"
-        android:translateY="19.75" >
-        <group
-            android:name="white_fingerprint_ridges_pivot"
-            android:translateX="33.2085"
-            android:translateY="30.91685" >
-            <group
-                android:name="ridge_5" >
-                <path
-                    android:name="ridge_5_path"
-                    android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_4" >
-                <path
-                    android:name="ridge_7_path"
-                    android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_3" >
-                <path
-                    android:name="ridge_6_path"
-                    android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathStart="1" />
-            </group>
-            <group
-                android:name="ridge_2" >
-                <path
-                    android:name="ridge_2_path"
-                    android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathStart="1" />
-            </group>
-            <group
-                android:name="ridge_1"
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:name="ridge_1_path"
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on_animation.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on_animation.xml
deleted file mode 100644
index d1aac02..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_draw_on_animation.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/lockscreen_fingerprint_draw_on" >
-    <target
-        android:name="ridge_5_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_on_ridge_5_path_animation" />
-    <target
-        android:name="ridge_7_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_on_ridge_7_path_animation" />
-    <target
-        android:name="ridge_6_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_on_ridge_6_path_animation" />
-    <target
-        android:name="ridge_2_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_on_ridge_2_path_animation" />
-    <target
-        android:name="ridge_1_path"
-        android:animation="@anim/lockscreen_fingerprint_draw_on_ridge_1_path_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp.xml
deleted file mode 100644
index 832716a..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp.xml
+++ /dev/null
@@ -1,130 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2017 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:name="ic_fingerprint_tofp"
-    android:width="32dp"
-    android:viewportWidth="24"
-    android:height="32dp"
-    android:viewportHeight="24" >
-    <group
-        android:name="fingerprintwhite"
-        android:translateX="12"
-        android:translateY="12.4"
-        android:scaleX="0.738"
-        android:scaleY="0.738"
-        android:rotation="180" >
-        <group
-            android:name="fingerprintwhite_pivot"
-            android:translateX="33"
-            android:translateY="34" >
-            <group
-                android:name="ridge_5" >
-                <path
-                    android:name="ridge_5_path"
-                    android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_4" >
-                <path
-                    android:name="ridge_7_path"
-                    android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_3" >
-                <path
-                    android:name="ridge_6_path"
-                    android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathStart="1" />
-            </group>
-            <group
-                android:name="ridge_2" >
-                <path
-                    android:name="ridge_2_path"
-                    android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathStart="1" />
-            </group>
-            <group
-                android:name="ridge_1"
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:name="ridge_1_path"
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-        </group>
-    </group>
-    <group
-        android:name="errorcircle"
-        android:translateX="12"
-        android:translateY="12"
-        android:rotation="10" >
-        <group
-            android:name="circle" >
-            <path
-                android:name="circlepath"
-                android:strokeColor="?android:attr/colorError"
-                android:strokeWidth="2"
-                android:strokeLineCap="round"
-                android:pathData="M 0.0,-9.0 c 4.9705627482,0.0 9.0,4.0294372518 9.0,9.0 c 0.0,4.9705627482 -4.0294372518,9.0 -9.0,9.0 c -4.9705627482,0.0 -9.0,-4.0294372518 -9.0,-9.0 c 0.0,-4.9705627482 4.0294372518,-9.0 9.0,-9.0 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamation"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="exclamationbottom"
-            android:translateY="4" >
-            <path
-                android:name="bottompath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,-1.1 l 0.0,0.0 c 0.60751322478,0.0 1.1,0.49248677522 1.1,1.1 l 0.0,0.0 c 0.0,0.60751322478 -0.49248677522,1.1 -1.1,1.1 l 0.0,0.0 c -0.60751322478,0.0 -1.1,-0.49248677522 -1.1,-1.1 l 0.0,0.0 c 0.0,-0.60751322478 0.49248677522,-1.1 1.1,-1.1 Z" />
-        </group>
-        <group
-            android:name="exclamationtop"
-            android:translateY="-2" >
-            <path
-                android:name="toppath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,-3.0 l 0.0,0.0 c 0.5522847498,0.0 1.0,0.4477152502 1.0,1.0 l 0.0,4.0 c 0.0,0.5522847498 -0.4477152502,1.0 -1.0,1.0 l 0.0,0.0 c -0.5522847498,0.0 -1.0,-0.4477152502 -1.0,-1.0 l 0.0,-4.0 c 0.0,-0.5522847498 0.4477152502,-1.0 1.0,-1.0 Z" />
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp_animation.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp_animation.xml
deleted file mode 100644
index 2f33306..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_error_state_to_fp_animation.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/lockscreen_fingerprint_error_state_to_fp" >
-    <target
-        android:name="fingerprintwhite"
-        android:animation="@anim/ic_fingerprint_tofp_fingerprintwhite_animation" />
-    <target
-        android:name="ridge_5_path"
-        android:animation="@anim/ic_fingerprint_tofp_ridge_5_path_animation" />
-    <target
-        android:name="ridge_7_path"
-        android:animation="@anim/ic_fingerprint_tofp_ridge_7_path_animation" />
-    <target
-        android:name="ridge_6_path"
-        android:animation="@anim/ic_fingerprint_tofp_ridge_6_path_animation" />
-    <target
-        android:name="ridge_2_path"
-        android:animation="@anim/ic_fingerprint_tofp_ridge_2_path_animation" />
-    <target
-        android:name="ridge_1_path"
-        android:animation="@anim/ic_fingerprint_tofp_ridge_1_path_animation" />
-    <target
-        android:name="errorcircle"
-        android:animation="@anim/ic_fingerprint_tofp_errorcircle_animation" />
-    <target
-        android:name="circlepath"
-        android:animation="@anim/ic_fingerprint_tofp_circlepath_animation" />
-    <target
-        android:name="errorexclamation"
-        android:animation="@anim/ic_fingerprint_tofp_errorexclamation_animation" />
-    <target
-        android:name="exclamationbottom"
-        android:animation="@anim/ic_fingerprint_tofp_exclamationbottom_animation" />
-    <target
-        android:name="bottompath"
-        android:animation="@anim/ic_fingerprint_tofp_bottompath_animation" />
-    <target
-        android:name="exclamationtop"
-        android:animation="@anim/ic_fingerprint_tofp_exclamationtop_animation" />
-    <target
-        android:name="toppath"
-        android:animation="@anim/ic_fingerprint_tofp_toppath_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state.xml
deleted file mode 100644
index 7cc2e5c..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state.xml
+++ /dev/null
@@ -1,189 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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:name="ic_fingerprint_toerror"
-    android:width="32dp"
-    android:viewportWidth="24"
-    android:height="32dp"
-    android:viewportHeight="24" >
-    <group
-        android:name="fingerprintwhite"
-        android:translateX="12"
-        android:translateY="12.4"
-        android:scaleX="0.738"
-        android:scaleY="0.738" >
-        <group
-            android:name="fingerprintwhite_pivot"
-            android:translateX="33"
-            android:translateY="34" >
-            <group
-                android:name="ridge_5" >
-                <path
-                    android:name="ridge_5_path"
-                    android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_4" >
-                <path
-                    android:name="ridge_7_path"
-                    android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_3" >
-                <path
-                    android:name="ridge_6_path"
-                    android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_2" >
-                <path
-                    android:name="ridge_2_path"
-                    android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-            <group
-                android:name="ridge_1"
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:name="ridge_1_path"
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-        </group>
-    </group>
-    <group
-        android:name="fingerprinterror"
-        android:translateX="12"
-        android:translateY="12.4"
-        android:scaleX="0.738"
-        android:scaleY="0.738" >
-        <group
-            android:name="fingerprinterror_pivot"
-            android:translateX="33"
-            android:translateY="34" >
-            <group
-                android:name="ridge_6" >
-                <path
-                    android:name="ridge_5_path_0"
-                    android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                    android:strokeColor="?android:attr/colorError"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_7" >
-                <path
-                    android:name="ridge_7_path_0"
-                    android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                    android:strokeColor="?android:attr/colorError"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_8" >
-                <path
-                    android:name="ridge_6_path_0"
-                    android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                    android:strokeColor="?android:attr/colorError"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-            <group
-                android:name="ridge_9" >
-                <path
-                    android:name="ridge_2_path_0"
-                    android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                    android:strokeColor="?android:attr/colorError"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathStart="1" />
-            </group>
-            <group
-                android:name="ridge_10"
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:name="ridge_1_path_0"
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?android:attr/colorError"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round"
-                    android:trimPathEnd="0" />
-            </group>
-        </group>
-    </group>
-    <group
-        android:name="errorcircle"
-        android:translateX="12"
-        android:translateY="12"
-        android:rotation="190" >
-        <group
-            android:name="circle" >
-            <path
-                android:name="circlepath"
-                android:strokeColor="?android:attr/colorError"
-                android:strokeWidth="2"
-                android:strokeLineCap="round"
-                android:trimPathStart="1"
-                android:pathData="M 0.0,-9.0 c 4.9705627482,0.0 9.0,4.0294372518 9.0,9.0 c 0.0,4.9705627482 -4.0294372518,9.0 -9.0,9.0 c -4.9705627482,0.0 -9.0,-4.0294372518 -9.0,-9.0 c 0.0,-4.9705627482 4.0294372518,-9.0 9.0,-9.0 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamation"
-        android:translateX="12"
-        android:translateY="12"
-        android:rotation="180" >
-        <group
-            android:name="exclamationbottom"
-            android:translateY="4" >
-            <path
-                android:name="bottompath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z" />
-        </group>
-        <group
-            android:name="exclamationtop" >
-            <path
-                android:name="toppath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M -1.0,0.0 l 2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l -2.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z" />
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state_animation.xml b/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state_animation.xml
deleted file mode 100644
index 38096a9..0000000
--- a/packages/SystemUI/res/drawable/lockscreen_fingerprint_fp_to_error_state_animation.xml
+++ /dev/null
@@ -1,77 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/lockscreen_fingerprint_fp_to_error_state" >
-    <target
-        android:name="fingerprintwhite"
-        android:animation="@anim/ic_fingerprint_toerror_fingerprintwhite_animation" />
-    <target
-        android:name="ridge_5_path"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_5_path_animation" />
-    <target
-        android:name="ridge_7_path"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_7_path_animation" />
-    <target
-        android:name="ridge_6_path"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_6_path_animation" />
-    <target
-        android:name="ridge_2_path"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_2_path_animation" />
-    <target
-        android:name="ridge_1_path"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_1_path_animation" />
-    <target
-        android:name="fingerprinterror"
-        android:animation="@anim/ic_fingerprint_toerror_fingerprinterror_animation" />
-    <target
-        android:name="ridge_5_path_0"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_5_path_0_animation" />
-    <target
-        android:name="ridge_7_path_0"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_7_path_0_animation" />
-    <target
-        android:name="ridge_6_path_0"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_6_path_0_animation" />
-    <target
-        android:name="ridge_2_path_0"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_2_path_0_animation" />
-    <target
-        android:name="ridge_1_path_0"
-        android:animation="@anim/ic_fingerprint_toerror_ridge_1_path_0_animation" />
-    <target
-        android:name="errorcircle"
-        android:animation="@anim/ic_fingerprint_toerror_errorcircle_animation" />
-    <target
-        android:name="circlepath"
-        android:animation="@anim/ic_fingerprint_toerror_circlepath_animation" />
-    <target
-        android:name="errorexclamation"
-        android:animation="@anim/ic_fingerprint_toerror_errorexclamation_animation" />
-    <target
-        android:name="exclamationbottom"
-        android:animation="@anim/ic_fingerprint_toerror_exclamationbottom_animation" />
-    <target
-        android:name="bottompath"
-        android:animation="@anim/ic_fingerprint_toerror_bottompath_animation" />
-    <target
-        android:name="exclamationtop"
-        android:animation="@anim/ic_fingerprint_toerror_exclamationtop_animation" />
-    <target
-        android:name="toppath"
-        android:animation="@anim/ic_fingerprint_toerror_toppath_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/drawable/trusted_state_to_error.xml b/packages/SystemUI/res/drawable/trusted_state_to_error.xml
deleted file mode 100755
index 4a8e452..0000000
--- a/packages/SystemUI/res/drawable/trusted_state_to_error.xml
+++ /dev/null
@@ -1,104 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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:name="trusted_state_to_error"
-    android:width="24dp"
-    android:viewportWidth="24"
-    android:height="24dp"
-    android:viewportHeight="24" >
-    <group
-        android:name="lock"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="middle_ellipse"
-            android:translateY="2.9375" >
-            <path
-                android:name="ellipse_path_1"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5"
-                android:pathData="M 0.0,-1.988645 c 1.09829830627,0.0 1.988645,0.890346693734 1.988645,1.988645 c 0.0,1.09829830627 -0.890346693734,1.988645 -1.988645,1.988645 c -1.09829830627,0.0 -1.988645,-0.890346693734 -1.988645,-1.988645 c 0.0,-1.09829830627 0.890346693734,-1.988645 1.988645,-1.988645 Z" />
-        </group>
-        <group
-            android:name="lock_right_side" >
-            <path
-                android:name="path_1"
-                android:pathData="M 6.00561523438,-4.046875 c 0.0,0.0 -5.98999023438,0.0 -5.98999023438,0.0 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 5.98812866211,0.0 5.98812866211,0.0 c 0.0,0.0 0.00064086914062,10.0 0.00064086914062,10.0 c 0.0,0.0 -5.98840332031,0.0 -5.98840332031,0.0 c 0.0,0.0 -0.0052490234375,2.0 -0.0052490234375,2.0 c 0.0,0.0 5.99487304688,0.0 5.99487304688,0.0 c 1.10000610352,0.0 2.0,-0.900024414062 2.0,-2.0 c 0.0,0.0 0.0,-10.0 0.0,-10.0 c 0.0,-1.09997558594 -0.899993896484,-2.0 -2.0,-2.0 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-        <group
-            android:name="lock_left_side" >
-            <path
-                android:name="path_2"
-                android:pathData="M -5.9959564209,-2.04727172852 c 0.0,0.0 6.01173400879,0.00039672851562 6.01173400879,0.00039672851562 c 0.0,0.0 -0.00015258789062,-2.0 -0.00015258789062,-2.0 c 0.0,0.0 -6.01000976562,0.0 -6.01000976562,0.0 c -1.10000610352,0.0 -2.0,0.900024414062 -2.0,2.0 c 0.0,0.0 0.0,10.0 0.0,10.0 c 0.0,1.09997558594 0.899993896484,2.0 2.0,2.0 c 0.0,0.0 6.01000976562,0.0 6.01000976562,0.0 c 0.0,0.0 -0.000244140625,-2.0009765625 -0.000244140625,-2.0009765625 c 0.0,0.0 -6.01171875,0.0003662109375 -6.01171875,0.0003662109375 c 0.0,0.0 0.00038146972656,-9.99978637695 0.00038146972656,-9.99978637695 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-        <group
-            android:name="lock_top" >
-            <path
-                android:name="path_3"
-                android:pathData="M 5.00619506836,-6.046875 c 0.0,-2.76000976562 -2.23999023438,-5.0 -5.0,-5.0 c -2.76000976562,0.0 -5.0,2.23999023438 -5.0,5.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,-1.71002197266 1.38999938965,-3.09997558594 3.10000610352,-3.09997558594 c 1.71000671387,0.0 3.10000610352,1.38995361328 3.10000610352,3.09997558594 c 0.0,0.0 0.0,2.0 0.0,2.0 c 0.0,0.0 1.89999389648,0.0 1.89999389648,0.0 c 0.0,0.0 0.0,-2.0 0.0,-2.0 Z"
-                android:fillColor="?attr/wallpaperTextColor"
-                android:fillAlpha="0.5" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamationdot"
-        android:translateX="12"
-        android:translateY="8" >
-        <group
-            android:name="exclamationbottom"
-            android:translateY="4" >
-            <path
-                android:name="bottompath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 l 0.0,0.0 c 0.0,0.0 0.0,0.0 0.0,0.0 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorexclamation"
-        android:translateX="12"
-        android:translateY="12" >
-        <group
-            android:name="exclamationtop"
-            android:translateY="2.5" >
-            <path
-                android:name="toppath"
-                android:fillColor="?android:attr/colorError"
-                android:pathData="M 0.0,-7.0 l 0.0,0.0 c 1.9329966243,0.0 3.5,1.5670033757 3.5,3.5 l 0.0,7.0 c 0.0,1.9329966243 -1.5670033757,3.5 -3.5,3.5 l 0.0,0.0 c -1.9329966243,0.0 -3.5,-1.5670033757 -3.5,-3.5 l 0.0,-7.0 c 0.0,-1.9329966243 1.5670033757,-3.5 3.5,-3.5 Z" />
-        </group>
-    </group>
-    <group
-        android:name="errorcircle"
-        android:translateX="12"
-        android:translateY="12"
-        android:rotation="184" >
-        <group
-            android:name="circle" >
-            <path
-                android:name="circlepath"
-                android:strokeColor="?android:attr/colorError"
-                android:strokeWidth="2"
-                android:strokeLineCap="round"
-                android:trimPathStart="1"
-                android:pathData="M 0.0,-9.0 c 4.9705627482,0.0 9.0,4.0294372518 9.0,9.0 c 0.0,4.9705627482 -4.0294372518,9.0 -9.0,9.0 c -4.9705627482,0.0 -9.0,-4.0294372518 -9.0,-9.0 c 0.0,-4.9705627482 4.0294372518,-9.0 9.0,-9.0 Z" />
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/trusted_state_to_error_animation.xml b/packages/SystemUI/res/drawable/trusted_state_to_error_animation.xml
deleted file mode 100755
index 3457be5..0000000
--- a/packages/SystemUI/res/drawable/trusted_state_to_error_animation.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Copyright (C) 2017 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.
--->
-<animated-vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:drawable="@drawable/trusted_state_to_error" >
-    <target
-        android:name="ellipse_path_1"
-        android:animation="@anim/trusted_state_to_error_ellipse_path_1_animation" />
-    <target
-        android:name="path_1"
-        android:animation="@anim/trusted_state_to_error_path_1_animation" />
-    <target
-        android:name="path_2"
-        android:animation="@anim/trusted_state_to_error_path_2_animation" />
-    <target
-        android:name="lock_top"
-        android:animation="@anim/trusted_state_to_error_lock_top_animation" />
-    <target
-        android:name="path_3"
-        android:animation="@anim/trusted_state_to_error_path_3_animation" />
-    <target
-        android:name="errorexclamationdot"
-        android:animation="@anim/trusted_state_to_error_errorexclamationdot_animation" />
-    <target
-        android:name="bottompath"
-        android:animation="@anim/trusted_state_to_error_bottompath_animation" />
-    <target
-        android:name="exclamationtop"
-        android:animation="@anim/trusted_state_to_error_exclamationtop_animation" />
-    <target
-        android:name="toppath"
-        android:animation="@anim/trusted_state_to_error_toppath_animation" />
-    <target
-        android:name="errorcircle"
-        android:animation="@anim/trusted_state_to_error_errorcircle_animation" />
-    <target
-        android:name="circlepath"
-        android:animation="@anim/trusted_state_to_error_circlepath_animation" />
-</animated-vector>
diff --git a/packages/SystemUI/res/layout/bubble_expanded_view.xml b/packages/SystemUI/res/layout/bubble_expanded_view.xml
index 1aeb52c..f0d2b2e 100644
--- a/packages/SystemUI/res/layout/bubble_expanded_view.xml
+++ b/packages/SystemUI/res/layout/bubble_expanded_view.xml
@@ -18,6 +18,7 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
+    android:orientation="vertical"
     android:id="@+id/bubble_expanded_view">
 
     <View
@@ -26,17 +27,48 @@
         android:layout_height="@dimen/bubble_pointer_height"
     />
 
-    <TextView
-        android:id="@+id/bubble_content_header"
-        android:background="@drawable/bubble_expanded_header_bg"
-        android:textAppearance="@*android:style/TextAppearance.Material.Title"
-        android:textSize="18sp"
-        android:layout_width="match_parent"
+    <LinearLayout
+        android:id="@+id/header_layout"
         android:layout_height="@dimen/bubble_expanded_header_height"
-        android:gravity="start|center_vertical"
-        android:singleLine="true"
-        android:paddingLeft="@dimen/bubble_expanded_header_horizontal_padding"
-        android:paddingRight="@dimen/bubble_expanded_header_horizontal_padding"
-    />
+        android:layout_width="match_parent"
+        android:orientation="horizontal"
+        android:background="@drawable/bubble_expanded_header_bg">
+
+        <TextView
+            android:id="@+id/header_text"
+            android:textAppearance="@*android:style/TextAppearance.Material.Title"
+            android:textSize="18sp"
+            android:layout_weight="1"
+            android:layout_width="0dp"
+            android:layout_height="match_parent"
+            android:gravity="start|center_vertical"
+            android:singleLine="true"
+            android:paddingLeft="@dimen/bubble_expanded_header_horizontal_padding"
+            android:paddingRight="@dimen/bubble_expanded_header_horizontal_padding"
+        />
+
+        <ImageButton
+            android:id="@+id/deep_link_button"
+            android:layout_width="@dimen/bubble_header_icon_size"
+            android:layout_height="@dimen/bubble_header_icon_size"
+            android:gravity="end|center_vertical"
+            android:src="@drawable/ic_open_in_new"
+            android:scaleType="center"
+            android:tint="?android:attr/colorForeground"
+            android:background="?android:attr/selectableItemBackground"
+        />
+
+        <ImageButton
+            android:id="@id/settings_button"
+            android:layout_width="@dimen/bubble_header_icon_size"
+            android:layout_height="@dimen/bubble_header_icon_size"
+            android:src="@drawable/ic_settings"
+            android:gravity="end|center_vertical"
+            android:scaleType="center"
+            android:tint="?android:attr/colorForeground"
+            android:background="?android:attr/selectableItemBackground"
+        />
+
+    </LinearLayout>
 
 </com.android.systemui.bubbles.BubbleExpandedViewContainer>
diff --git a/packages/SystemUI/res/layout/keyguard_bottom_area.xml b/packages/SystemUI/res/layout/keyguard_bottom_area.xml
index 098c975..53b3a7e 100644
--- a/packages/SystemUI/res/layout/keyguard_bottom_area.xml
+++ b/packages/SystemUI/res/layout/keyguard_bottom_area.xml
@@ -37,22 +37,16 @@
             android:id="@+id/keyguard_indication_enterprise_disclosure"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:gravity="center_horizontal"
-            android:textStyle="italic"
-            android:textColor="?attr/wallpaperTextColorSecondary"
-            android:textSize="16sp"
-            android:textAppearance="?android:attr/textAppearanceSmall"
+            android:gravity="center"
+            android:textAppearance="@style/TextAppearance.Keyguard.BottomArea"
             android:visibility="gone" />
 
         <com.android.systemui.statusbar.phone.KeyguardIndicationTextView
             android:id="@+id/keyguard_indication_text"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:gravity="center_horizontal"
-            android:textStyle="italic"
-            android:textColor="?attr/wallpaperTextColorSecondary"
-            android:textSize="16sp"
-            android:textAppearance="?android:attr/textAppearanceSmall"
+            android:gravity="center"
+            android:textAppearance="@style/TextAppearance.Keyguard.BottomArea"
             android:accessibilityLiveRegion="polite" />
 
     </LinearLayout>
@@ -85,12 +79,13 @@
 
     <com.android.systemui.statusbar.phone.LockIcon
         android:id="@+id/lock_icon"
-        android:layout_width="@dimen/keyguard_affordance_width"
-        android:layout_height="@dimen/keyguard_affordance_height"
+        android:layout_width="@dimen/keyguard_lock_width"
+        android:layout_height="@dimen/keyguard_lock_height"
         android:layout_gravity="bottom|center_horizontal"
-        android:src="@drawable/ic_lock"
+        android:layout_marginBottom="@dimen/keyguard_lock_padding"
+        android:src="@*android:drawable/ic_lock_24dp"
         android:contentDescription="@string/accessibility_unlock_button"
-        android:scaleType="center" />
+        android:scaleType="fitCenter" />
 
     <FrameLayout
         android:id="@+id/overlay_container"
diff --git a/packages/SystemUI/res/values/attrs.xml b/packages/SystemUI/res/values/attrs.xml
index baaf9d6..0fed96e 100644
--- a/packages/SystemUI/res/values/attrs.xml
+++ b/packages/SystemUI/res/values/attrs.xml
@@ -124,6 +124,7 @@
     <attr name="darkIconTheme" format="reference" />
     <attr name="wallpaperTextColor" format="reference|color" />
     <attr name="wallpaperTextColorSecondary" format="reference|color" />
+    <attr name="backgroundProtectedStyle" format="reference" />
 
     <declare-styleable name="SmartReplyView">
         <attr name="spacing" format="dimension" />
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index d435c67..1060211 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -646,10 +646,15 @@
          + 8dp. -->
     <dimen name="assist_orb_navbar_scrim_height">56dp</dimen>
 
-    <!-- The width/height of the phone/camera/unlock icon view on keyguard. -->
+    <!-- The width/height of the phone/camera icon view on keyguard. -->
     <dimen name="keyguard_affordance_height">56dp</dimen>
     <dimen name="keyguard_affordance_width">56dp</dimen>
 
+    <!-- The width/height of the unlock icon view on keyguard. -->
+    <dimen name="keyguard_lock_height">32dp</dimen>
+    <dimen name="keyguard_lock_width">32dp</dimen>
+    <dimen name="keyguard_lock_padding">24dp</dimen>
+
     <dimen name="keyguard_indication_margin_bottom">65dp</dimen>
 
     <!-- The text size for battery level -->
@@ -1030,4 +1035,6 @@
     <dimen name="bubble_stack_offscreen">5dp</dimen>
     <!-- How far down the screen the stack starts. -->
     <dimen name="bubble_stack_starting_offset_y">100dp</dimen>
+    <!-- Size of image buttons in the bubble header -->
+    <dimen name="bubble_header_icon_size">48dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index ffa5de8..56d9bf4c 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -2309,7 +2309,7 @@
     <string name="ongoing_privacy_dialog_ok">Got it</string>
 
     <!-- Action on Ongoing Privacy Dialog to open privacy hub [CHAR LIMIT=20]-->
-    <string name="ongoing_privacy_dialog_open_settings">View details</string>
+    <string name="ongoing_privacy_dialog_open_settings">Privacy settings</string>
 
     <!-- Text for item in Ongoing Privacy Dialog title when only one app is using app ops [CHAR LIMIT=NONE] -->
     <string name="ongoing_privacy_dialog_single_app_title">App using your <xliff:g id="types_list" example="camera( and location)">%s</xliff:g></string>
@@ -2346,4 +2346,12 @@
 
     <!-- What to show on the ambient display player when song doesn't have a title. [CHAR LIMIT=20] -->
     <string name="music_controls_no_title">No title</string>
+
+    <!-- Text used for content description of deep link button in the header of expanded bubble
+         view. [CHAR_LIMIT=NONE] -->
+    <string name="bubbles_deep_link_button_description">Open <xliff:g id="app_name" example="YouTube">%1$s</xliff:g></string>
+    <!-- Text used for content description of settings button in the header of expanded bubble
+         view. [CHAR_LIMIT=NONE] -->
+    <string name="bubbles_settings_button_description">Open notification settings for <xliff:g id="app_name" example="YouTube">%1$s</xliff:g></string>
+
 </resources>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index fa675b7..96cdbd3 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -269,6 +269,8 @@
         <item name="android:colorControlHighlight">@*android:color/primary_text_material_dark</item>
         <item name="*android:lockPatternStyle">@style/LockPatternStyle</item>
         <item name="passwordStyle">@style/PasswordTheme</item>
+        <item name="backgroundProtectedStyle">@style/BackgroundProtectedStyle</item>
+        <item name="android:forceDarkAllowed">false</item>
 
         <!-- Needed for MediaRoute chooser dialog -->
         <item name="*android:isLightTheme">false</item>
@@ -285,6 +287,10 @@
         <item name="*android:isLightTheme">true</item>
     </style>
 
+    <style name="BackgroundProtectedStyle">
+        <item name="android:textColor">?attr/wallpaperTextColor</item>
+    </style>
+
     <style name="LockPatternStyle">
         <item name="*android:regularColor">?attr/wallpaperTextColor</item>
         <item name="*android:successColor">?attr/wallpaperTextColor</item>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/ThumbnailData.java b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/ThumbnailData.java
index f84c72e..1413ac1 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/ThumbnailData.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/ThumbnailData.java
@@ -17,11 +17,13 @@
 package com.android.systemui.shared.recents.model;
 
 import static android.content.res.Configuration.ORIENTATION_UNDEFINED;
+
 import static com.android.systemui.shared.system.WindowManagerWrapper.WINDOWING_MODE_UNDEFINED;
 
 import android.app.ActivityManager.TaskSnapshot;
 import android.graphics.Bitmap;
 import android.graphics.Rect;
+import android.hardware.HardwareBuffer;
 
 /**
  * Data for a single thumbnail.
@@ -51,7 +53,9 @@
     }
 
     public ThumbnailData(TaskSnapshot snapshot) {
-        thumbnail = Bitmap.createHardwareBitmap(snapshot.getSnapshot());
+        thumbnail = Bitmap.wrapHardwareBuffer(
+                HardwareBuffer.createFromGraphicBuffer(snapshot.getSnapshot()),
+                snapshot.getColorSpace());
         insets = new Rect(snapshot.getContentInsets());
         orientation = snapshot.getOrientation();
         reducedResolution = snapshot.isReducedResolution();
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index bcd41a0..0970c21 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -99,6 +99,7 @@
 import java.util.List;
 import java.util.Map.Entry;
 import java.util.TimeZone;
+import java.util.function.Consumer;
 
 /**
  * Watches for updates that may be interesting to the keyguard, and provides
@@ -218,7 +219,8 @@
     // Battery status
     private BatteryStatus mBatteryStatus;
 
-    private final StrongAuthTracker mStrongAuthTracker;
+    @VisibleForTesting
+    protected StrongAuthTracker mStrongAuthTracker;
 
     private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>>
             mCallbacks = Lists.newArrayList();
@@ -344,8 +346,7 @@
                     handleUserUnlocked();
                     break;
                 case MSG_ASSISTANT_STACK_CHANGED:
-                    mAssistantVisible = (boolean)msg.obj;
-                    updateBiometricListeningState();
+                    setAssistantVisible((boolean) msg.obj);
                     break;
                 case MSG_BIOMETRIC_AUTHENTICATION_CONTINUE:
                     updateBiometricListeningState();
@@ -354,7 +355,7 @@
                     updateLogoutEnabled();
                     break;
                 case MSG_TELEPHONY_CAPABLE:
-                    updateTelephonyCapable((boolean)msg.obj);
+                    updateTelephonyCapable((boolean) msg.obj);
                     break;
                 default:
                     super.handleMessage(msg);
@@ -538,7 +539,8 @@
         }
     }
 
-    private void onFingerprintAuthenticated(int userId) {
+    @VisibleForTesting
+    protected void onFingerprintAuthenticated(int userId) {
         Trace.beginSection("KeyGuardUpdateMonitor#onFingerPrintAuthenticated");
         mUserFingerprintAuthenticated.put(userId, true);
         // Update/refresh trust state only if user can skip bouncer
@@ -693,7 +695,8 @@
         }
     }
 
-    private void onFaceAuthenticated(int userId) {
+    @VisibleForTesting
+    protected void onFaceAuthenticated(int userId) {
         Trace.beginSection("KeyGuardUpdateMonitor#onFaceAuthenticated");
         mUserFaceAuthenticated.put(userId, true);
         // Update/refresh trust state only if user can skip bouncer
@@ -898,8 +901,9 @@
 
 
     public boolean getUserCanSkipBouncer(int userId) {
-        return getUserHasTrust(userId) || (mUserFingerprintAuthenticated.get(userId)
-                && isUnlockingWithBiometricAllowed());
+        boolean fingerprintOrFace = mUserFingerprintAuthenticated.get(userId)
+                || mUserFaceAuthenticated.get(userId);
+        return getUserHasTrust(userId) || (fingerprintOrFace && isUnlockingWithBiometricAllowed());
     }
 
     public boolean getUserHasTrust(int userId) {
@@ -950,6 +954,12 @@
         }
     }
 
+    @VisibleForTesting
+    void setAssistantVisible(boolean assistantVisible) {
+        mAssistantVisible = assistantVisible;
+        updateBiometricListeningState();
+    }
+
     static class DisplayClientState {
         public int clientGeneration;
         public boolean clearing;
@@ -1047,7 +1057,8 @@
         }
     };
 
-    private final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() {
+    @VisibleForTesting
+    protected final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() {
 
         @Override
         public void onReceive(Context context, Intent intent) {
@@ -1121,7 +1132,8 @@
         }
     };
 
-    private FaceManager.AuthenticationCallback mFaceAuthenticationCallback
+    @VisibleForTesting
+    FaceManager.AuthenticationCallback mFaceAuthenticationCallback
             = new FaceManager.AuthenticationCallback() {
 
         @Override
@@ -1298,9 +1310,13 @@
         }
     }
 
-    public class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
-        public StrongAuthTracker(Context context) {
+    public static class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
+        private final Consumer<Integer> mStrongAuthRequiredChangedCallback;
+
+        public StrongAuthTracker(Context context,
+                Consumer<Integer> strongAuthRequiredChangedCallback) {
             super(context);
+            mStrongAuthRequiredChangedCallback = strongAuthRequiredChangedCallback;
         }
 
         public boolean isUnlockingWithBiometricAllowed() {
@@ -1316,7 +1332,7 @@
 
         @Override
         public void onStrongAuthRequiredChanged(int userId) {
-            notifyStrongAuthStateChanged(userId);
+            mStrongAuthRequiredChangedCallback.accept(userId);
         }
     }
 
@@ -1423,7 +1439,7 @@
         mContext = context;
         mSubscriptionManager = SubscriptionManager.from(context);
         mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
-        mStrongAuthTracker = new StrongAuthTracker(context);
+        mStrongAuthTracker = new StrongAuthTracker(context, this::notifyStrongAuthStateChanged);
 
         // Since device can't be un-provisioned, we only need to register a content observer
         // to update mDeviceProvisioned when we are...
@@ -1548,6 +1564,14 @@
         }
     }
 
+    /**
+     * Request passive authentication, when sensors detect that a user might be present.
+     */
+    public void onAuthInterruptDetected() {
+        if (DEBUG) Log.d(TAG, "onAuthInterruptDetected()");
+        updateFaceListeningState();
+    }
+
     private void updateFaceListeningState() {
         // If this message exists, we should not authenticate again until this message is
         // consumed by the handler
@@ -1585,11 +1609,13 @@
     }
 
     private boolean shouldListenForFace() {
-        return (mKeyguardIsVisible || !mDeviceInteractive ||
-                (mBouncer && !mKeyguardGoingAway) || mGoingToSleep ||
-                shouldListenForFaceAssistant() || (mKeyguardOccluded && mIsDreaming))
-                && !mSwitchingUser && !isFaceDisabled(getCurrentUser())
-                && !mKeyguardGoingAway && !mFaceLockedOut && mFaceSettingEnabledForUser;
+        final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep;
+        final int user = getCurrentUser();
+
+        return (mBouncer || awakeKeyguard || shouldListenForFaceAssistant())
+                && !mSwitchingUser && !getUserCanSkipBouncer(user) && !isFaceDisabled(user)
+                && !mKeyguardGoingAway && !mFaceLockedOut && mFaceSettingEnabledForUser
+                && mUserManager.isUserUnlocked(user);
     }
 
 
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index e3f6add..404f2e5 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -42,6 +42,8 @@
 import android.view.WindowManager;
 import android.widget.FrameLayout;
 
+import androidx.annotation.MainThread;
+
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.Dependency;
@@ -76,11 +78,14 @@
     // Enables some subset of notifs to automatically become bubbles
     private static final boolean DEBUG_ENABLE_AUTO_BUBBLE = false;
 
-    // Secure settings
+    // Secure settings flags
+    // Feature level flag
+    private static final String ENABLE_BUBBLES = "experiment_enable_bubbles";
+    // Auto bubble flags set whether different notification types should be presented as a bubble
     private static final String ENABLE_AUTO_BUBBLE_MESSAGES = "experiment_autobubble_messaging";
     private static final String ENABLE_AUTO_BUBBLE_ONGOING = "experiment_autobubble_ongoing";
     private static final String ENABLE_AUTO_BUBBLE_ALL = "experiment_autobubble_all";
-    private static final String ENABLE_BUBBLE_ACTIVITY_VIEW = "experiment_bubble_activity_view";
+    // Use an activity view for an auto-bubbled notification if it has an appropriate content intent
     private static final String ENABLE_BUBBLE_CONTENT_INTENT = "experiment_bubble_content_intent";
 
     private final Context mContext;
@@ -262,8 +267,8 @@
                     R.layout.bubble_view, mStackView, false /* attachToRoot */);
             bubble.setNotif(notif);
             PendingIntent bubbleIntent = getValidBubbleIntent(notif);
-            if (shouldUseActivityView(mContext) || bubbleIntent != null) {
-                bubble.setBubbleIntent(getValidBubbleIntent(notif));
+            if (bubbleIntent != null) {
+                bubble.setBubbleIntent(bubbleIntent);
             }
             mBubbles.put(bubble.getKey(), bubble);
             mStackView.addBubble(bubble);
@@ -271,25 +276,12 @@
         updateVisibility();
     }
 
-    @Nullable
-    private PendingIntent getValidBubbleIntent(NotificationEntry notif) {
-        Notification notification = notif.notification.getNotification();
-        if (canLaunchInActivityView(notification.getBubbleMetadata() != null
-                ? notification.getBubbleMetadata().getIntent() : null)) {
-            return notification.getBubbleMetadata().getIntent();
-        } else if (shouldUseContentIntent(mContext)
-                && canLaunchInActivityView(notification.contentIntent)) {
-            Log.d(TAG, "[addBubble " + notif.key
-                    + "]: No appOverlayIntent, using contentIntent.");
-            return notification.contentIntent;
-        }
-        Log.d(TAG, "[addBubble " + notif.key + "]: No supported intent for ActivityView.");
-        return null;
-    }
-
     /**
      * Removes the bubble associated with the {@param uri}.
+     * <p>
+     * Must be called from the main thread.
      */
+    @MainThread
     void removeBubble(String key) {
         BubbleView bv = mBubbles.remove(key);
         if (mStackView != null && bv != null) {
@@ -309,7 +301,10 @@
     private final NotificationEntryListener mEntryListener = new NotificationEntryListener() {
         @Override
         public void onPendingEntryAdded(NotificationEntry entry) {
-            if (shouldAutoBubble(mContext, entry) || shouldBubble(entry)) {
+            if (!areBubblesEnabled(mContext)) {
+                return;
+            }
+            if (shouldAutoBubbleForFlags(mContext, entry) || shouldBubble(entry)) {
                 // TODO: handle group summaries
                 // It's a new notif, it shows in the shade and as a bubble
                 entry.setIsBubble(true);
@@ -320,6 +315,9 @@
         @Override
         public void onEntryInflated(NotificationEntry entry,
                 @NotificationInflater.InflationFlag int inflatedFlags) {
+            if (!areBubblesEnabled(mContext)) {
+                return;
+            }
             if (entry.isBubble() && mNotificationInterruptionStateProvider.shouldBubbleUp(entry)) {
                 updateBubble(entry, true /* updatePosition */);
             }
@@ -327,6 +325,9 @@
 
         @Override
         public void onPreEntryUpdated(NotificationEntry entry) {
+            if (!areBubblesEnabled(mContext)) {
+                return;
+            }
             if (mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
                     && alertAgain(entry, entry.notification.getNotification())) {
                 entry.setShowInShadeWhenBubble(true);
@@ -342,6 +343,9 @@
         public void onEntryRemoved(NotificationEntry entry,
                 @Nullable NotificationVisibility visibility,
                 boolean removedByUser) {
+            if (!areBubblesEnabled(mContext)) {
+                return;
+            }
             entry.setShowInShadeWhenBubble(false);
             if (mBubbles.containsKey(entry.key)) {
                 mBubbles.get(entry.key).updateDotVisibility();
@@ -396,6 +400,30 @@
         return mTempRect;
     }
 
+    @VisibleForTesting
+    BubbleStackView getStackView() {
+        return mStackView;
+    }
+
+    @Nullable
+    private PendingIntent getValidBubbleIntent(NotificationEntry notif) {
+        Notification notification = notif.notification.getNotification();
+        Notification.BubbleMetadata data = notif.getBubbleMetadata();
+        if (data != null && canLaunchInActivityView(data.getIntent())) {
+            return data.getIntent();
+        } else if (shouldUseContentIntent(mContext)
+                && canLaunchInActivityView(notification.contentIntent)) {
+            Log.d(TAG, "[addBubble " + notif.key
+                    + "]: No appOverlayIntent, using contentIntent.");
+            return notification.contentIntent;
+        }
+        Log.d(TAG, "[addBubble " + notif.key + "]: No supported intent for ActivityView.");
+        return null;
+    }
+
+    /**
+     * Whether an intent is properly configured to display in an {@link android.app.ActivityView}.
+     */
     private boolean canLaunchInActivityView(PendingIntent intent) {
         if (intent == null) {
             return false;
@@ -407,11 +435,6 @@
                 && (info.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) != 0;
     }
 
-    @VisibleForTesting
-    BubbleStackView getStackView() {
-        return mStackView;
-    }
-
     /**
      * Whether the notification has been developer configured to bubble and is allowed by the user.
      */
@@ -431,18 +454,14 @@
         boolean canChannelOverlay = channel != null && channel.canBubble();
         boolean hasOverlayIntent = n.getNotification().getBubbleMetadata() != null
                 && n.getNotification().getBubbleMetadata().getIntent() != null;
-        return DEBUG_ENABLE_AUTO_BUBBLE && hasOverlayIntent && canChannelOverlay && canAppOverlay;
+        return hasOverlayIntent && canChannelOverlay && canAppOverlay;
     }
 
     /**
-     * Whether the notification should bubble or not. Gated by debug flag.
-     * <p>
-     * If a notification has been set to bubble via proper bubble APIs or if it is an important
-     * message-like notification.
-     * </p>
+     * Whether the notification should automatically bubble or not. Gated by secure settings flags.
      */
     @VisibleForTesting
-    protected boolean shouldAutoBubble(Context context, NotificationEntry entry) {
+    protected boolean shouldAutoBubbleForFlags(Context context, NotificationEntry entry) {
         if (entry.isBubbleDismissed()) {
             return false;
         }
@@ -469,11 +488,9 @@
         Class<? extends Notification.Style> style = n.getNotification().getNotificationStyle();
         boolean isMessageType = Notification.CATEGORY_MESSAGE.equals(n.getNotification().category);
         boolean isMessageStyle = Notification.MessagingStyle.class.equals(style);
-        boolean shouldAutoBubble =
-                (((isMessageType && hasRemoteInput) || isMessageStyle) && autoBubbleMessages)
+        return (((isMessageType && hasRemoteInput) || isMessageStyle) && autoBubbleMessages)
                 || (isImportantOngoing && autoBubbleOngoing)
                 || autoBubbleAll;
-        return DEBUG_ENABLE_AUTO_BUBBLE && shouldAutoBubble;
     }
 
     private static boolean shouldAutoBubbleMessages(Context context) {
@@ -491,13 +508,13 @@
                 ENABLE_AUTO_BUBBLE_ALL, 0) != 0;
     }
 
-    private static boolean shouldUseActivityView(Context context) {
-        return Settings.Secure.getInt(context.getContentResolver(),
-                ENABLE_BUBBLE_ACTIVITY_VIEW, 0) != 0;
-    }
-
     private static boolean shouldUseContentIntent(Context context) {
         return Settings.Secure.getInt(context.getContentResolver(),
                 ENABLE_BUBBLE_CONTENT_INTENT, 0) != 0;
     }
+
+    private static boolean areBubblesEnabled(Context context) {
+        return Settings.Secure.getInt(context.getContentResolver(),
+                ENABLE_BUBBLES, 1) != 0;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedViewContainer.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedViewContainer.java
index 231e725..67b18fd 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedViewContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedViewContainer.java
@@ -17,32 +17,53 @@
 package com.android.systemui.bubbles;
 
 import android.annotation.Nullable;
+import android.app.Notification;
+import android.app.PendingIntent;
 import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.Color;
 import android.graphics.drawable.ShapeDrawable;
+import android.provider.Settings;
 import android.text.TextUtils;
 import android.util.AttributeSet;
+import android.util.Log;
 import android.view.View;
+import android.widget.ImageButton;
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
 import com.android.systemui.R;
 import com.android.systemui.recents.TriangleShape;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 
 /**
  * Container for the expanded bubble view, handles rendering the caret and header of the view.
  */
-public class BubbleExpandedViewContainer extends LinearLayout {
+public class BubbleExpandedViewContainer extends LinearLayout implements View.OnClickListener {
+    private static final String TAG = "BubbleExpandedView";
 
     // The triangle pointing to the expanded view
     private View mPointerView;
     // The view displayed between the pointer and the expanded view
     private TextView mHeaderView;
+    // Tappable header icon deeplinking into the app
+    private ImageButton mDeepLinkIcon;
+    // Tappable header icon deeplinking into notification settings
+    private ImageButton mSettingsIcon;
     // The view that is being displayed for the expanded state
     private View mExpandedView;
 
+    private NotificationEntry mEntry;
+    private PackageManager mPm;
+    private String mAppName;
+
+    // Need reference to let it know to collapse when new task is launched
+    private BubbleStackView mStackView;
+
     public BubbleExpandedViewContainer(Context context) {
         this(context, null);
     }
@@ -58,7 +79,7 @@
     public BubbleExpandedViewContainer(Context context, AttributeSet attrs, int defStyleAttr,
             int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
-        setOrientation(VERTICAL);
+        mPm = context.getPackageManager();
     }
 
     @Override
@@ -79,7 +100,75 @@
                 TriangleShape.create(width, height, true /* pointUp */));
         triangleDrawable.setTint(bgColor);
         mPointerView.setBackground(triangleDrawable);
-        mHeaderView = findViewById(R.id.bubble_content_header);
+
+        mHeaderView = findViewById(R.id.header_text);
+        mDeepLinkIcon = findViewById(R.id.deep_link_button);
+        mSettingsIcon = findViewById(R.id.settings_button);
+        mDeepLinkIcon.setOnClickListener(this);
+        mSettingsIcon.setOnClickListener(this);
+    }
+
+    /**
+     * Sets the notification entry used to populate this view.
+     */
+    public void setEntry(NotificationEntry entry, BubbleStackView stackView) {
+        mStackView = stackView;
+        mEntry = entry;
+
+        ApplicationInfo info;
+        try {
+            info = mPm.getApplicationInfo(
+                    entry.notification.getPackageName(),
+                    PackageManager.MATCH_UNINSTALLED_PACKAGES
+                            | PackageManager.MATCH_DISABLED_COMPONENTS
+                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
+                            | PackageManager.MATCH_DIRECT_BOOT_AWARE);
+            if (info != null) {
+                mAppName = String.valueOf(mPm.getApplicationLabel(info));
+            }
+        } catch (PackageManager.NameNotFoundException e) {
+            // Ahh... just use package name
+            mAppName = entry.notification.getPackageName();
+        }
+
+        updateHeaderView();
+    }
+
+    private void updateHeaderView() {
+        mSettingsIcon.setContentDescription(getResources().getString(
+                R.string.bubbles_settings_button_description, mAppName));
+        mDeepLinkIcon.setContentDescription(getResources().getString(
+                R.string.bubbles_deep_link_button_description, mAppName));
+        if (mEntry != null && mEntry.getBubbleMetadata() != null) {
+            setHeaderText(mEntry.getBubbleMetadata().getTitle());
+        } else {
+            // This should only happen if we're auto-bubbling notification content that isn't
+            // explicitly a bubble
+            setHeaderText(mAppName);
+        }
+    }
+
+    @Override
+    public void onClick(View view) {
+        if (mEntry == null) {
+            return;
+        }
+        Notification n = mEntry.notification.getNotification();
+        int id = view.getId();
+        if (id == R.id.deep_link_button) {
+            mStackView.collapseStack(() -> {
+                try {
+                    n.contentIntent.send();
+                } catch (PendingIntent.CanceledException e) {
+                    Log.w(TAG, "Failed to send intent for bubble with key: "
+                            + (mEntry != null ? mEntry.key : " null entry"));
+                }
+            });
+        } else if (id == R.id.settings_button) {
+            Intent intent = getSettingsIntent(mEntry.notification.getPackageName(),
+                    mEntry.notification.getUid());
+            mStackView.collapseStack(() -> mContext.startActivity(intent));
+        }
     }
 
     /**
@@ -94,7 +183,7 @@
     /**
      * Set the text displayed within the header.
      */
-    public void setHeaderText(CharSequence text) {
+    private void setHeaderText(CharSequence text) {
         mHeaderView.setText(text);
         mHeaderView.setVisibility(TextUtils.isEmpty(text) ? GONE : VISIBLE);
     }
@@ -122,4 +211,13 @@
     public View getExpandedView() {
         return mExpandedView;
     }
+
+    private Intent getSettingsIntent(String packageName, final int appUid) {
+        final Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
+        intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);
+        intent.putExtra(Settings.EXTRA_APP_UID, appUid);
+        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        return intent;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index cbca2fc..b6acd63 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -20,7 +20,6 @@
 import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
 
 import android.app.ActivityView;
-import android.app.PendingIntent;
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Outline;
@@ -28,7 +27,9 @@
 import android.graphics.PointF;
 import android.graphics.Rect;
 import android.graphics.RectF;
+import android.service.notification.StatusBarNotification;
 import android.util.Log;
+import android.util.StatsLog;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
@@ -55,6 +56,9 @@
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
 
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
 /**
  * Renders bubbles in a stack and handles animating expanded and collapsed states.
  */
@@ -241,16 +245,20 @@
             // Previously expanded, notify that this bubble is no longer expanded
             notifyExpansionChanged(mExpandedBubble, false /* expanded */);
         }
+        BubbleView prevBubble = mExpandedBubble;
         mExpandedBubble = bubbleToExpand;
         if (!mIsExpanded) {
             // If we weren't previously expanded we should animate open.
             animateExpansion(true /* expand */);
+            logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
         } else {
             // Otherwise just update the views
             // TODO: probably animate / page to expanded one
             updateExpandedBubble();
             updatePointerPosition();
             requestUpdate();
+            logBubbleEvent(prevBubble, StatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
+            logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
         }
         mExpandedBubble.getEntry().setShowInShadeWhenBubble(false);
         notifyExpansionChanged(mExpandedBubble, true /* expanded */);
@@ -279,6 +287,7 @@
                 new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
         ViewClippingUtil.setClippingDeactivated(bubbleView, true, mClippingParameters);
         requestUpdate();
+        logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__POSTED);
     }
 
     /**
@@ -287,20 +296,24 @@
     public void removeBubble(BubbleView bubbleView) {
         int removedIndex = mBubbleContainer.indexOfChild(bubbleView);
         mBubbleContainer.removeView(bubbleView);
-        boolean wasExpanded = mIsExpanded;
         int bubbleCount = mBubbleContainer.getChildCount();
-        if (mIsExpanded && bubbleView.equals(mExpandedBubble) && bubbleCount > 0) {
+        if (bubbleCount == 0) {
+            // If no bubbles remain, collapse the entire stack.
+            collapseStack();
+            return;
+        } else if (bubbleView.equals(mExpandedBubble)) {
+            // Was the current bubble just removed?
             // If we have other bubbles and are expanded go to the next one or previous
             // if the bubble removed was last
             int nextIndex = bubbleCount > removedIndex ? removedIndex : bubbleCount - 1;
             BubbleView expandedBubble = (BubbleView) mBubbleContainer.getChildAt(nextIndex);
-            setExpandedBubble(expandedBubble);
-            requestUpdate();
+            if (mIsExpanded) {
+                setExpandedBubble(expandedBubble);
+            } else {
+                mExpandedBubble = null;
+            }
         }
-        mIsExpanded = wasExpanded && mBubbleContainer.getChildCount() > 0;
-        if (wasExpanded != mIsExpanded) {
-            notifyExpansionChanged(mExpandedBubble, mIsExpanded);
-        }
+        logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__DISMISSED);
     }
 
     /**
@@ -309,6 +322,8 @@
     public void stackDismissed() {
         collapseStack();
         mBubbleContainer.removeAllViews();
+        logBubbleEvent(null /* no bubble associated with bubble stack dismiss */,
+                StatsLog.BUBBLE_UICHANGED__ACTION__STACK_DISMISSED);
     }
 
     /**
@@ -324,8 +339,7 @@
         if (updatePosition && !mIsExpanded) {
             // If alerting it gets promoted to top of the stack.
             if (mBubbleContainer.indexOfChild(bubbleView) != 0) {
-                mBubbleContainer.removeViewAndThen(bubbleView,
-                        () -> mBubbleContainer.addView(bubbleView, 0));
+                mBubbleContainer.moveViewTo(bubbleView, 0);
             }
             requestUpdate();
         }
@@ -333,6 +347,7 @@
             entry.setShowInShadeWhenBubble(false);
             requestUpdate();
         }
+        logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__UPDATED);
     }
 
     /**
@@ -368,9 +383,16 @@
             // TODO: Save opened bubble & move it to top of stack
             animateExpansion(false /* shouldExpand */);
             notifyExpansionChanged(mExpandedBubble, mIsExpanded);
+            logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
         }
     }
 
+    void collapseStack(Runnable endRunnable) {
+        collapseStack();
+        // TODO - use the runnable at end of animation
+        endRunnable.run();
+    }
+
     /**
      * Expands the stack fo bubbles.
      */
@@ -378,6 +400,7 @@
         if (!mIsExpanded) {
             mExpandedBubble = getTopBubble();
             setExpandedBubble(mExpandedBubble);
+            logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__STACK_EXPANDED);
         }
     }
 
@@ -570,6 +593,9 @@
                         .setStiffness(SpringForce.STIFFNESS_LOW)
                         .setDampingRatio(SPRING_DAMPING_RATIO),
                 /* destination */ null);
+
+        logBubbleEvent(null /* no bubble associated with bubble stack move */,
+                StatsLog.BUBBLE_UICHANGED__ACTION__STACK_MOVED);
     }
 
     /**
@@ -629,6 +655,7 @@
             return;
         }
 
+        mExpandedViewContainer.setEntry(mExpandedBubble.getEntry(), this);
         if (mExpandedBubble.hasAppOverlayIntent()) {
             // Bubble with activity view expanded state
             ActivityView expandedView = mExpandedBubble.getActivityView();
@@ -636,8 +663,6 @@
             expandedView.setLayoutParams(new LinearLayout.LayoutParams(
                     ViewGroup.LayoutParams.MATCH_PARENT, mExpandedBubbleHeight));
 
-            final PendingIntent intent = mExpandedBubble.getAppOverlayIntent();
-            mExpandedViewContainer.setHeaderText(intent.getIntent().getComponent().toShortString());
             mExpandedViewContainer.setExpandedView(expandedView);
         } else {
             // Bubble with notification view expanded state
@@ -651,8 +676,6 @@
             } else {
                 mExpandedViewContainer.setExpandedView(null);
             }
-            // Bubble with notification as expanded state doesn't need a header / title
-            mExpandedViewContainer.setHeaderText(null);
         }
     }
 
@@ -732,4 +755,72 @@
         viewState.headsUpIsVisible = false;
         viewState.applyToView(view);
     }
+
+    /**
+     * @return the number of bubbles in the stack view.
+     */
+    private int getBubbleCount() {
+        return mBubbleContainer.getChildCount();
+    }
+
+    /**
+     * Finds the bubble index within the stack.
+     *
+     * @param bubbleView the view of the bubble.
+     * @return the index of the bubble view within the bubble stack. The range of the position
+     * is between 0 and the bubble count minus 1.
+     */
+    private int getBubbleIndex(BubbleView bubbleView) {
+        return mBubbleContainer.indexOfChild(bubbleView);
+    }
+
+    /**
+     * @return the normalized x-axis position of the bubble stack rounded to 4 decimal places.
+     */
+    private float getNormalizedXPosition() {
+        return new BigDecimal(getPosition().x / mDisplaySize.x)
+                .setScale(4, RoundingMode.CEILING.HALF_UP)
+                .floatValue();
+    }
+
+    /**
+     * @return the normalized y-axis position of the bubble stack rounded to 4 decimal places.
+     */
+    private float getNormalizedYPosition() {
+        return new BigDecimal(getPosition().y / mDisplaySize.y)
+                .setScale(4, RoundingMode.CEILING.HALF_UP)
+                .floatValue();
+    }
+
+    /**
+     * Logs the bubble UI event.
+     *
+     * @param bubble the bubble that is being interacted on. Null value indicates that
+     *               the user interaction is not specific to one bubble.
+     * @param action the user interaction enum.
+     */
+    private void logBubbleEvent(@Nullable BubbleView bubble, int action) {
+        if (bubble == null) {
+            StatsLog.write(StatsLog.BUBBLE_UI_CHANGED,
+                    null /* package name */,
+                    null /* notification channel */,
+                    0 /* notification ID */,
+                    0 /* bubble position */,
+                    getBubbleCount(),
+                    action,
+                    getNormalizedXPosition(),
+                    getNormalizedYPosition());
+        } else {
+            StatusBarNotification notification = bubble.getEntry().notification;
+            StatsLog.write(StatsLog.BUBBLE_UI_CHANGED,
+                    notification.getPackageName(),
+                    notification.getNotification().getChannelId(),
+                    notification.getId(),
+                    getBubbleIndex(bubble),
+                    getBubbleCount(),
+                    action,
+                    getNormalizedXPosition(),
+                    getNormalizedYPosition());
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
index dc94832..2c23c0c 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
@@ -37,6 +37,7 @@
 import android.widget.TextView;
 
 import com.android.internal.graphics.ColorUtils;
+import com.android.systemui.Dependency;
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -59,6 +60,7 @@
 
     private NotificationEntry mEntry;
     private PendingIntent mAppOverlayIntent;
+    private BubbleController mBubbleController;
     private ActivityView mActivityView;
     private boolean mActivityViewReady;
     private boolean mActivityViewStarted;
@@ -81,6 +83,7 @@
         // XXX: can this padding just be on the view and we look it up?
         mPadding = getResources().getDimensionPixelSize(R.dimen.bubble_view_padding);
         mIconInset = getResources().getDimensionPixelSize(R.dimen.bubble_icon_inset);
+        mBubbleController = Dependency.get(BubbleController.class);
     }
 
     @Override
@@ -248,6 +251,20 @@
                 public void onActivityViewDestroyed(ActivityView view) {
                     mActivityViewReady = false;
                 }
+
+                /**
+                 * This is only called for tasks on this ActivityView, which is also set to
+                 * single-task mode -- meaning never more than one task on this display. If a task
+                 * is being removed, it's the top Activity finishing and this bubble should
+                 * be removed or collapsed.
+                 */
+                @Override
+                public void onTaskRemovalStarted(int taskId) {
+                    if (mEntry != null) {
+                        // Must post because this is called from a binder thread.
+                        post(() -> mBubbleController.removeBubble(mEntry.key));
+                    }
+                }
             });
         }
         return mActivityView;
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
index 1ced3a4..e4e6bc9 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
@@ -27,9 +27,8 @@
 
 import com.android.systemui.R;
 
-import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.List;
+import java.util.HashSet;
 import java.util.Set;
 
 /**
@@ -122,12 +121,8 @@
     protected final HashMap<DynamicAnimation.ViewProperty, DynamicAnimation.OnAnimationEndListener>
             mEndListenerForProperty = new HashMap<>();
 
-    /**
-     * List of views that were passed to removeView, but are currently being animated out. These
-     * views will be actually removed by the controller (via super.removeView) once they're done
-     * animating out.
-     */
-    private final List<View> mViewsToBeActuallyRemoved = new ArrayList<>();
+    /** Set of currently rendered transient views. */
+    private final Set<View> mTransientViews = new HashSet<>();
 
     /** The currently active animation controller. */
     private PhysicsAnimationController mController;
@@ -186,23 +181,6 @@
         mEndListenerForProperty.remove(property);
     }
 
-    /**
-     * Returns the index of the view that precedes the given index, ignoring views that were passed
-     * to removeView, but are currently being animated out before actually being removed.
-     *
-     * @return index of the preceding view, or -1 if there are none.
-     */
-    public int getPrecedingNonRemovedViewIndex(int index) {
-        for (int i = index + 1; i < getChildCount(); i++) {
-            View precedingView = getChildAt(i);
-            if (!mViewsToBeActuallyRemoved.contains(precedingView)) {
-                return i;
-            }
-        }
-
-        return -1;
-    }
-
     @Override
     public void addView(View child, int index, ViewGroup.LayoutParams params) {
         super.addView(child, index, params);
@@ -224,6 +202,24 @@
         removeViewAndThen(view, /* callback */ null);
     }
 
+    @Override
+    public void addTransientView(View view, int index) {
+        super.addTransientView(view, index);
+        mTransientViews.add(view);
+    }
+
+    @Override
+    public void removeTransientView(View view) {
+        super.removeTransientView(view);
+        mTransientViews.remove(view);
+    }
+
+    /** Immediately moves the view from wherever it currently is, to the given index. */
+    public void moveViewTo(View view, int index) {
+        super.removeView(view);
+        addView(view, index);
+    }
+
     /**
      * Let the controller know that this view should be removed, and then call the callback once the
      * controller has finished any removal animations and the view has actually been removed.
@@ -231,23 +227,31 @@
     public void removeViewAndThen(View view, Runnable callback) {
         if (mController != null) {
             final int index = indexOfChild(view);
-            // Remove the view only if it exists in this layout, and we're not already working on
-            // animating its removal.
-            if (index > -1 && !mViewsToBeActuallyRemoved.contains(view)) {
-                mViewsToBeActuallyRemoved.add(view);
-                setChildrenVisibility();
 
-                // Tell the controller to animate this view out, and call the callback when it wants
-                // to actually remove the view.
-                mController.onChildToBeRemoved(view, index, () -> {
-                    removeViewImmediateAndThen(view, callback);
-                    mViewsToBeActuallyRemoved.remove(view);
-                });
-            }
+            // Remove the view and add it back as a transient view so we can animate it out.
+            super.removeView(view);
+            addTransientView(view, index);
+
+            setChildrenVisibility();
+
+            // Tell the controller to animate this view out, and call the callback when it's
+            // finished.
+            mController.onChildToBeRemoved(view, index, () -> {
+                // Done animating, remove the transient view.
+                removeTransientView(view);
+
+                if (callback != null) {
+                    callback.run();
+                }
+            });
         } else {
             // Without a controller, nobody will animate this view out, so it gets an unceremonious
             // departure.
-            removeViewImmediateAndThen(view, callback);
+            super.removeView(view);
+
+            if (callback != null) {
+                callback.run();
+            }
         }
     }
 
@@ -278,17 +282,18 @@
     }
 
     /**
-     * Animates the property of the child at the given index to the given value, then runs the
-     * callback provided when the animation ends.
+     * Animates the property of the given child view, then runs the callback provided when the
+     * animation ends.
      */
-    protected void animateValueForChildAtIndex(
+    protected void animateValueForChild(
             DynamicAnimation.ViewProperty property,
-            int index,
+            View view,
             float value,
             float startVel,
             Runnable after) {
-        if (index < getChildCount()) {
-            final SpringAnimation animation = getAnimationAtIndex(property, index);
+        if (view != null) {
+            final SpringAnimation animation =
+                    (SpringAnimation) view.getTag(getTagIdForProperty(property));
             if (after != null) {
                 animation.addEndListener(new OneTimeEndListener() {
                     @Override
@@ -300,14 +305,38 @@
                 });
             }
 
-            if (startVel != Float.MAX_VALUE) {
-                animation.setStartVelocity(startVel);
-            }
-
             animation.animateToFinalPosition(value);
         }
     }
 
+    protected void animateValueForChild(
+            DynamicAnimation.ViewProperty property,
+            View view,
+            float value,
+            Runnable after) {
+        animateValueForChild(property, view, value, Float.MAX_VALUE, after);
+    }
+
+    protected void animateValueForChild(
+            DynamicAnimation.ViewProperty property,
+            View view,
+            float value) {
+        animateValueForChild(property, view, value, Float.MAX_VALUE, /* after */ null);
+    }
+
+    /**
+     * Animates the property of the child at the given index to the given value, then runs the
+     * callback provided when the animation ends.
+     */
+    protected void animateValueForChildAtIndex(
+            DynamicAnimation.ViewProperty property,
+            int index,
+            float value,
+            float startVel,
+            Runnable after) {
+        animateValueForChild(property, getChildAt(index), value, startVel, after);
+    }
+
     /** Shortcut to animate a value with a callback, but no start velocity. */
     protected void animateValueForChildAtIndex(
             DynamicAnimation.ViewProperty property,
@@ -366,18 +395,6 @@
         }
     }
 
-
-    /** Immediately removes the view, without notifying the controller, then runs the callback. */
-    private void removeViewImmediateAndThen(View view, Runnable callback) {
-        super.removeView(view);
-
-        if (callback != null) {
-            callback.run();
-        }
-
-        setChildrenVisibility();
-    }
-
     /**
      * Retrieves the animation of the given property from the view at the given index via the view
      * tag system.
@@ -401,7 +418,11 @@
         newAnim.addUpdateListener((animation, value, velocity) -> {
             final int nextAnimInChain =
                     mController.getNextAnimationInChain(property, indexOfChild(child));
-            if (nextAnimInChain == PhysicsAnimationController.NONE) {
+
+            // If the controller doesn't want us to chain, or if we're a transient view in the
+            // process of being removed, don't chain.
+            if (nextAnimInChain == PhysicsAnimationController.NONE
+                    || mTransientViews.contains(child)) {
                 return;
             }
 
@@ -412,9 +433,7 @@
             // If this property's animations should be chained, then check to see if there is a
             // subsequent animation within the rendering limit, and if so, tell it to animate to
             // this animation's new value (plus the offset).
-            if (nextAnimInChain < Math.min(
-                    getChildCount(),
-                    mMaxRenderedChildren + mViewsToBeActuallyRemoved.size())) {
+            if (nextAnimInChain < Math.min(getChildCount(), mMaxRenderedChildren)) {
                 getAnimationAtIndex(property, animIndex + 1)
                         .animateToFinalPosition(value + offset);
             } else if (nextAnimInChain < getChildCount()) {
@@ -442,9 +461,7 @@
                     // Ignore views that are animating out when calculating whether to hide the
                     // view. That is, if we're supposed to render 5 views, but 4 are animating out
                     // and will soon be removed, render up to 9 views temporarily.
-                    i < (mMaxRenderedChildren + mViewsToBeActuallyRemoved.size())
-                        ? View.VISIBLE
-                        : View.GONE);
+                    i < mMaxRenderedChildren ? View.VISIBLE : View.GONE);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
index 0f51376..23c6fd3 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
@@ -53,8 +53,8 @@
     /** Scale factor to use initially for new bubbles being animated in. */
     private static final float ANIMATE_IN_STARTING_SCALE = 1.15f;
 
-    /** Translation factor (multiplied by stack offset) to use for new bubbles being animated in. */
-    private static final int ANIMATE_IN_TRANSLATION_FACTOR = 4;
+    /** Translation factor (multiplied by stack offset) to use for bubbles being animated in/out. */
+    private static final int ANIMATE_TRANSLATION_FACTOR = 4;
 
     /**
      * Values to use for the default {@link SpringForce} provided to the physics animation layout.
@@ -309,7 +309,7 @@
             // animate in from this position. Since the animations are chained, when the new bubble
             // flies in from the side, it will push the other ones out of the way.
             float xOffset = getOffsetForChainedPropertyAnimation(DynamicAnimation.TRANSLATION_X);
-            child.setTranslationX(mStackPosition.x - (ANIMATE_IN_TRANSLATION_FACTOR * xOffset));
+            child.setTranslationX(mStackPosition.x - ANIMATE_TRANSLATION_FACTOR * xOffset);
             mLayout.animateValueForChildAtIndex(
                     DynamicAnimation.TRANSLATION_X, 0, mStackPosition.x);
         }
@@ -318,27 +318,19 @@
     @Override
     void onChildToBeRemoved(View child, int index, Runnable actuallyRemove) {
         // Animate the child out, actually removing it once its alpha is zero.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.ALPHA, index, 0f, () -> {
-                    actuallyRemove.run();
-                });
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.SCALE_X, index, ANIMATE_IN_STARTING_SCALE);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.SCALE_Y, index, ANIMATE_IN_STARTING_SCALE);
+        mLayout.animateValueForChild(
+                DynamicAnimation.ALPHA, child, 0f, actuallyRemove);
+        mLayout.animateValueForChild(DynamicAnimation.SCALE_X, child, ANIMATE_IN_STARTING_SCALE);
+        mLayout.animateValueForChild(DynamicAnimation.SCALE_Y, child, ANIMATE_IN_STARTING_SCALE);
 
-        final boolean hasPrecedingChild = index + 1 < mLayout.getChildCount();
-        if (hasPrecedingChild) {
-            final int precedingViewIndex = mLayout.getPrecedingNonRemovedViewIndex(index);
-            if (precedingViewIndex >= 0) {
-                final float offsetX =
-                        getOffsetForChainedPropertyAnimation(DynamicAnimation.TRANSLATION_X);
-                mLayout.animatePositionForChildAtIndex(
-                        precedingViewIndex,
-                        mStackPosition.x + (index * offsetX),
-                        mStackPosition.y);
-            }
-        }
+        // Animate the removing view in the opposite direction of the stack.
+        final float xOffset = getOffsetForChainedPropertyAnimation(DynamicAnimation.TRANSLATION_X);
+        mLayout.animateValueForChild(DynamicAnimation.TRANSLATION_X, child,
+                mStackPosition.x - (-xOffset * ANIMATE_TRANSLATION_FACTOR));
+
+        // Pull the top of the stack to the correct position, the chained animations will instruct
+        // any children that are out of place to animate to the correct position.
+        mLayout.animateValueForChildAtIndex(DynamicAnimation.TRANSLATION_X, 0, mStackPosition.x);
     }
 
     /** Moves the stack, without any animation, to the starting position. */
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
index a784773..9bca3c7 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
@@ -35,19 +35,19 @@
     private static final int SIZE = Build.IS_DEBUGGABLE ? 400 : 50;
     static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
 
-    private static final int REASONS = 10;
+    public static final int REASONS = 10;
 
     public static final int PULSE_REASON_NONE = -1;
     public static final int PULSE_REASON_INTENT = 0;
     public static final int PULSE_REASON_NOTIFICATION = 1;
     public static final int PULSE_REASON_SENSOR_SIGMOTION = 2;
-    public static final int PULSE_REASON_SENSOR_PICKUP = 3;
-    public static final int PULSE_REASON_SENSOR_DOUBLE_TAP = 4;
+    public static final int REASON_SENSOR_PICKUP = 3;
+    public static final int REASON_SENSOR_DOUBLE_TAP = 4;
     public static final int PULSE_REASON_SENSOR_LONG_PRESS = 5;
     public static final int PULSE_REASON_DOCKING = 6;
     public static final int REASON_SENSOR_WAKE_UP = 7;
     public static final int PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN = 8;
-    public static final int PULSE_REASON_SENSOR_TAP = 9;
+    public static final int REASON_SENSOR_TAP = 9;
 
     private static boolean sRegisterKeyguardCallback = true;
 
@@ -202,13 +202,13 @@
             case PULSE_REASON_INTENT: return "intent";
             case PULSE_REASON_NOTIFICATION: return "notification";
             case PULSE_REASON_SENSOR_SIGMOTION: return "sigmotion";
-            case PULSE_REASON_SENSOR_PICKUP: return "pickup";
-            case PULSE_REASON_SENSOR_DOUBLE_TAP: return "doubletap";
+            case REASON_SENSOR_PICKUP: return "pickup";
+            case REASON_SENSOR_DOUBLE_TAP: return "doubletap";
             case PULSE_REASON_SENSOR_LONG_PRESS: return "longpress";
             case PULSE_REASON_DOCKING: return "docking";
             case PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN: return "wakelockscreen";
             case REASON_SENSOR_WAKE_UP: return "wakeup";
-            case PULSE_REASON_SENSOR_TAP: return "tap";
+            case REASON_SENSOR_TAP: return "tap";
             default: throw new IllegalArgumentException("bad reason: " + pulseReason);
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index 675948e..5efdc2f 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -97,20 +97,20 @@
                         mSensorManager.getDefaultSensor(Sensor.TYPE_PICK_UP_GESTURE),
                         Settings.Secure.DOZE_PICK_UP_GESTURE,
                         config.dozePickupSensorAvailable(),
-                        DozeLog.PULSE_REASON_SENSOR_PICKUP, false /* touchCoords */,
+                        DozeLog.REASON_SENSOR_PICKUP, false /* touchCoords */,
                         false /* touchscreen */),
                 new TriggerSensor(
                         findSensorWithType(config.doubleTapSensorType()),
                         Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
                         true /* configured */,
-                        DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP,
+                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
                         dozeParameters.doubleTapReportsTouchCoordinates(),
                         true /* touchscreen */),
                 new TriggerSensor(
                         findSensorWithType(config.tapSensorType()),
                         Settings.Secure.DOZE_TAP_SCREEN_GESTURE,
                         true /* configured */,
-                        DozeLog.PULSE_REASON_SENSOR_TAP,
+                        DozeLog.REASON_SENSOR_TAP,
                         false /* reports touch coordinates */,
                         true /* touchscreen */),
                 new TriggerSensor(
@@ -530,7 +530,7 @@
 
         /**
          * Called when a sensor requests a pulse
-         * @param pulseReason Requesting sensor, e.g. {@link DozeLog#PULSE_REASON_SENSOR_PICKUP}
+         * @param pulseReason Requesting sensor, e.g. {@link DozeLog#REASON_SENSOR_PICKUP}
          * @param sensorPerformedProxCheck true if the sensor already checked for FAR proximity.
          * @param screenX the location on the screen where the sensor fired or -1
  *                if the sensor doesn't support reporting screen locations.
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index dc505b5..873fbc2 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -108,10 +108,6 @@
         DozeLog.traceNotificationPulse(mContext);
     }
 
-    private void onWhisper() {
-        requestPulse(DozeLog.PULSE_REASON_NOTIFICATION, false /* performedProxCheck */);
-    }
-
     private void proximityCheckThenCall(IntConsumer callback,
             boolean alreadyPerformedProxCheck,
             int reason) {
@@ -137,16 +133,16 @@
     @VisibleForTesting
     void onSensor(int pulseReason, boolean sensorPerformedProxCheck,
             float screenX, float screenY, float[] rawValues) {
-        boolean isDoubleTap = pulseReason == DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP;
-        boolean isTap = pulseReason == DozeLog.PULSE_REASON_SENSOR_TAP;
-        boolean isPickup = pulseReason == DozeLog.PULSE_REASON_SENSOR_PICKUP;
+        boolean isDoubleTap = pulseReason == DozeLog.REASON_SENSOR_DOUBLE_TAP;
+        boolean isTap = pulseReason == DozeLog.REASON_SENSOR_TAP;
+        boolean isPickup = pulseReason == DozeLog.REASON_SENSOR_PICKUP;
         boolean isLongPress = pulseReason == DozeLog.PULSE_REASON_SENSOR_LONG_PRESS;
         boolean isWakeDisplay = pulseReason == DozeLog.REASON_SENSOR_WAKE_UP;
         boolean isWakeLockScreen = pulseReason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN;
         boolean wakeEvent = rawValues != null && rawValues.length > 0 && rawValues[0] != 0;
 
         if (isWakeDisplay) {
-            onWakeScreen(wakeEvent);
+            onWakeScreen(wakeEvent, mMachine.getState());
         } else if (isLongPress || isWakeLockScreen) {
             requestPulse(pulseReason, sensorPerformedProxCheck);
         } else {
@@ -199,9 +195,8 @@
         }
     }
 
-    private void onWakeScreen(boolean wake) {
+    private void onWakeScreen(boolean wake, DozeMachine.State state) {
         DozeLog.traceWakeDisplay(wake);
-        DozeMachine.State state = mMachine.getState();
         boolean paused = (state == DozeMachine.State.DOZE_AOD_PAUSED);
         boolean pausing = (state == DozeMachine.State.DOZE_AOD_PAUSING);
         sWakeDisplaySensorState = wake;
@@ -212,7 +207,7 @@
                     // In pocket, drop event.
                     return;
                 }
-                if (mMachine.getState() == DozeMachine.State.DOZE) {
+                if (state == DozeMachine.State.DOZE) {
                     mMachine.requestState(DozeMachine.State.DOZE_AOD);
                 }
             }, false /* alreadyPerformedProxCheck */, DozeLog.REASON_SENSOR_WAKE_UP);
@@ -240,7 +235,7 @@
                 }
                 mDozeSensors.setListening(true);
                 if (newState == DozeMachine.State.DOZE_AOD && !sWakeDisplaySensorState) {
-                    onWakeScreen(false);
+                    onWakeScreen(false, newState);
                 }
                 break;
             case DOZE_AOD_PAUSED:
diff --git a/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
old mode 100755
new mode 100644
index ca3cdf4..5f2614e
--- a/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
@@ -42,6 +42,7 @@
 import android.os.Debug;
 import android.os.Handler;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.Pair;
@@ -247,7 +248,8 @@
         ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(Intent.ACTION_MEDIA_RESOURCE_GRANTED);
-        mContext.registerReceiver(mBroadcastReceiver, intentFilter);
+        mContext.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, intentFilter,
+                null, null);
 
         if (sSettingsPackageAndClassNamePairList == null) {
             String[] settings = mContext.getResources().getStringArray(
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
index e2688f1..fa1426e 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
@@ -22,6 +22,7 @@
 import android.content.pm.PackageManager
 import android.content.res.ColorStateList
 import android.os.UserHandle
+import android.provider.Settings
 import android.util.IconDrawableFactory
 import android.view.Gravity
 import android.view.LayoutInflater
@@ -51,6 +52,10 @@
     private val MAX_ITEMS = context.resources.getInteger(R.integer.ongoing_appops_dialog_max_apps)
     private val iconFactory = IconDrawableFactory.newInstance(context, true)
     private var dismissDialog: (() -> Unit)? = null
+    private val appsAndTypes = dialogBuilder.appsAndTypes
+            .sortedWith(compareBy({ -it.second.size }, // Sort by number of AppOps
+            { it.second.min() },
+            { it.first }))
 
     init {
         val a = context.theme.obtainStyledAttributes(
@@ -64,7 +69,7 @@
             setPositiveButton(R.string.ongoing_privacy_dialog_ok, null)
             setNeutralButton(R.string.ongoing_privacy_dialog_open_settings,
                     object : DialogInterface.OnClickListener {
-                        val intent = Intent(Intent.ACTION_REVIEW_PERMISSION_USAGE).putExtra(
+                        val intent = Intent(Settings.ACTION_ENTERPRISE_PRIVACY_SETTINGS).putExtra(
                                 Intent.EXTRA_DURATION_MILLIS, TimeUnit.MINUTES.toMillis(1))
 
                         @Suppress("DEPRECATION")
@@ -89,10 +94,10 @@
 
         title.setText(dialogBuilder.getDialogTitle())
 
-        val numItems = dialogBuilder.appsAndTypes.size
+        val numItems = appsAndTypes.size
         for (i in 0..(numItems - 1)) {
             if (i >= MAX_ITEMS) break
-            val item = dialogBuilder.appsAndTypes[i]
+            val item = appsAndTypes[i]
             addAppItem(appsList, item.first, item.second, dialogBuilder.types.size > 1)
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
index 2894621..9c1076a 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
@@ -30,8 +30,7 @@
         appsAndTypes = itemsList.groupBy({ it.application }, { it.privacyType })
                 .toList()
                 .sortedWith(compareBy({ -it.second.size }, // Sort by number of AppOps
-                        { it.second.min() }, // Sort by "smallest" AppOpp (Location is largest)
-                        { it.first })) // Sort alphabetically bt App Name
+                        { it.second.min() })) // Sort by "smallest" AppOpp (Location is largest)
         types = itemsList.map { it.privacyType }.distinct().sorted()
         val singleApp = appsAndTypes.size == 1
         app = if (singleApp) appsAndTypes[0].first else null
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
index dbe87d1..f7ca51d 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
@@ -44,17 +44,22 @@
         return applicationName.compareTo(other.applicationName)
     }
 
-    var icon: Drawable = context.getDrawable(android.R.drawable.sym_def_app_icon)
-    var applicationName: String
-
-    init {
+    private val applicationInfo: ApplicationInfo? by lazy {
         try {
-            val app: ApplicationInfo = context.packageManager
-                    .getApplicationInfo(packageName, 0)
-            icon = context.packageManager.getApplicationIcon(app)
-            applicationName = context.packageManager.getApplicationLabel(app) as String
-        } catch (e: PackageManager.NameNotFoundException) {
-            applicationName = packageName
+            context.packageManager.getApplicationInfo(packageName, 0)
+        } catch (_: PackageManager.NameNotFoundException) {
+            null
         }
     }
+    val icon: Drawable by lazy {
+        applicationInfo?.let {
+            context.packageManager.getApplicationIcon(it)
+        } ?: context.getDrawable(android.R.drawable.sym_def_app_icon)
+    }
+
+    val applicationName: String by lazy {
+        applicationInfo?.let {
+            context.packageManager.getApplicationLabel(it) as String
+        } ?: packageName
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
index a188c5a..0a39549 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
@@ -462,13 +462,6 @@
         }
     }
 
-    public void setRestingAlpha(float alpha) {
-        mRestingAlpha = alpha;
-
-        // TODO: Handle the case an animation is playing.
-        setImageAlpha(alpha, false);
-    }
-
     public float getRestingAlpha() {
         return mRestingAlpha;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index 158430f..2811505 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -486,7 +486,7 @@
             if (msg.what == MSG_HIDE_TRANSIENT) {
                 hideTransientIndication();
             } else if (msg.what == MSG_CLEAR_BIOMETRIC_MSG) {
-                mLockIcon.setTransientFpError(false);
+                mLockIcon.setTransientBiometricsError(false);
             }
         }
     };
@@ -579,7 +579,7 @@
                 mStatusBarKeyguardViewManager.showBouncerMessage(helpString,
                         errorColorState);
             } else if (updateMonitor.isScreenOn()) {
-                mLockIcon.setTransientFpError(true);
+                mLockIcon.setTransientBiometricsError(true);
                 showTransientIndication(helpString, errorColorState);
                 hideTransientIndicationDelayed(TRANSIENT_BIOMETRIC_ERROR_TIMEOUT);
                 mHandler.removeMessages(MSG_CLEAR_BIOMETRIC_MSG);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
index 0583843..be63bad 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
@@ -55,8 +55,6 @@
     private final ArrayList<NotificationSettingsListener> mSettingsListeners = new ArrayList<>();
     private final Context mContext;
 
-    protected NotificationPresenter mPresenter;
-
     public NotificationListener(Context context) {
         mContext = context;
     }
@@ -152,9 +150,7 @@
         }
     }
 
-    public void setUpWithPresenter(NotificationPresenter presenter) {
-        mPresenter = presenter;
-
+    public void registerAsSystemService() {
         try {
             registerAsSystemService(mContext,
                     new ComponentName(mContext.getPackageName(), getClass().getCanonicalName()),
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUiAdjustment.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUiAdjustment.java
index f0d804d..3db02b9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUiAdjustment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUiAdjustment.java
@@ -54,7 +54,7 @@
     public static NotificationUiAdjustment extractFromNotificationEntry(
             NotificationEntry entry) {
         return new NotificationUiAdjustment(
-                entry.key, entry.systemGeneratedSmartActions, entry.smartReplies);
+                entry.key, entry.systemGeneratedSmartActions, entry.systemGeneratedSmartReplies);
     }
 
     public static boolean needReinflate(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index ef5e936..5c62005 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -27,7 +27,6 @@
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.Dependency;
 import com.android.systemui.Dumpable;
-import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.statusbar.NotificationLifetimeExtender;
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
@@ -62,13 +61,9 @@
     private static final String TAG = "NotificationEntryMgr";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
 
-    private final Context mContext;
     @VisibleForTesting
     protected final HashMap<String, NotificationEntry> mPendingNotifications = new HashMap<>();
 
-    private final ForegroundServiceController mForegroundServiceController =
-            Dependency.get(ForegroundServiceController.class);
-
     // Lazily retrieved dependencies
     private NotificationRemoteInputManager mRemoteInputManager;
     private NotificationRowBinder mNotificationRowBinder;
@@ -97,7 +92,6 @@
     }
 
     public NotificationEntryManager(Context context) {
-        mContext = context;
         mNotificationData = new NotificationData();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index 2e93c382..db9fcc8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -102,7 +102,9 @@
     /** Smart Actions provided by the NotificationAssistantService. */
     @NonNull
     public List<Notification.Action> systemGeneratedSmartActions = Collections.emptyList();
-    public CharSequence[] smartReplies = new CharSequence[0];
+    /** Smart replies provided by the NotificationAssistantService. */
+    @NonNull
+    public CharSequence[] systemGeneratedSmartReplies = new CharSequence[0];
     @VisibleForTesting
     public int suppressedVisualEffects;
     public boolean suspended;
@@ -182,7 +184,7 @@
         userSentiment = ranking.getUserSentiment();
         systemGeneratedSmartActions = ranking.getSmartActions() == null
                 ? Collections.emptyList() : ranking.getSmartActions();
-        smartReplies = ranking.getSmartReplies() == null
+        systemGeneratedSmartReplies = ranking.getSmartReplies() == null
                 ? new CharSequence[0]
                 : ranking.getSmartReplies().toArray(new CharSequence[0]);
         suppressedVisualEffects = ranking.getSuppressedVisualEffects();
@@ -239,6 +241,13 @@
     }
 
     /**
+     * Returns the data needed for a bubble for this notification, if it exists.
+     */
+    public Notification.BubbleMetadata getBubbleMetadata() {
+        return notification.getNotification().getBubbleMetadata();
+    }
+
+    /**
      * Resets the notification entry to be re-used.
      */
     public void reset() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 0a04f4d..878d533 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -1373,13 +1373,13 @@
         }
         // Apps didn't provide any smart replies / actions, use those from NAS (if any).
         if (!appGeneratedSmartRepliesExist && !appGeneratedSmartActionsExist) {
-            boolean useGeneratedReplies = !ArrayUtils.isEmpty(entry.smartReplies)
+            boolean useGeneratedReplies = !ArrayUtils.isEmpty(entry.systemGeneratedSmartReplies)
                     && freeformRemoteInputActionPair != null
                     && freeformRemoteInputActionPair.second.getAllowGeneratedReplies()
                     && freeformRemoteInputActionPair.second.actionIntent != null;
             if (useGeneratedReplies) {
                 smartReplies = new SmartReplyView.SmartReplies(
-                        entry.smartReplies,
+                        entry.systemGeneratedSmartReplies,
                         freeformRemoteInputActionPair.first,
                         freeformRemoteInputActionPair.second.actionIntent,
                         true /* fromAssistant */);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
index 302d630..304d2ee 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
@@ -47,7 +47,7 @@
     private static final String BIOMETRIC_WAKE_LOCK_NAME = "wake-and-unlock wakelock";
 
     /**
-     * Mode in which we don't need to wake up the device when we get a fingerprint.
+     * Mode in which we don't need to wake up the device when we authenticate.
      */
     public static final int MODE_NONE = 0;
 
@@ -70,8 +70,7 @@
     public static final int MODE_SHOW_BOUNCER = 3;
 
     /**
-     * Mode in which we only wake up the device, and keyguard was not showing when we acquired a
-     * fingerprint.
+     * Mode in which we only wake up the device, and keyguard was not showing when we authenticated.
      * */
     public static final int MODE_ONLY_WAKE = 4;
 
@@ -96,22 +95,21 @@
      */
     private static final float BIOMETRIC_COLLAPSE_SPEEDUP_FACTOR = 1.1f;
 
-    private final NotificationMediaManager mMediaManager =
-            Dependency.get(NotificationMediaManager.class);
-    private PowerManager mPowerManager;
-    private Handler mHandler = new Handler();
+    private final NotificationMediaManager mMediaManager;
+    private final PowerManager mPowerManager;
+    private final Handler mHandler;
     private PowerManager.WakeLock mWakeLock;
-    private KeyguardUpdateMonitor mUpdateMonitor;
+    private final KeyguardUpdateMonitor mUpdateMonitor;
+    private final UnlockMethodCache mUnlockMethodCache;
+    private final StatusBarWindowController mStatusBarWindowController;
+    private final Context mContext;
+    private final int mWakeUpDelay;
     private int mMode;
     private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
-    private StatusBarWindowController mStatusBarWindowController;
     private DozeScrimController mDozeScrimController;
     private KeyguardViewMediator mKeyguardViewMediator;
     private ScrimController mScrimController;
     private StatusBar mStatusBar;
-    private final UnlockMethodCache mUnlockMethodCache;
-    private final Context mContext;
-    private final int mWakeUpDelay;
     private int mPendingAuthenticatedUserId = -1;
     private BiometricSourceType mPendingAuthenticatedBioSourceType = null;
     private boolean mPendingShowBouncer;
@@ -122,11 +120,14 @@
                                      KeyguardViewMediator keyguardViewMediator,
                                      ScrimController scrimController,
                                      StatusBar statusBar,
-                                     UnlockMethodCache unlockMethodCache) {
+                                     UnlockMethodCache unlockMethodCache, Handler handler,
+                                     KeyguardUpdateMonitor keyguardUpdateMonitor,
+                                     int wakeUpDelay) {
         mContext = context;
         mPowerManager = context.getSystemService(PowerManager.class);
-        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(context);
+        mUpdateMonitor = keyguardUpdateMonitor;
         mUpdateMonitor.registerCallback(this);
+        mMediaManager = Dependency.get(NotificationMediaManager.class);
         Dependency.get(WakefulnessLifecycle.class).addObserver(mWakefulnessObserver);
         Dependency.get(ScreenLifecycle.class).addObserver(mScreenObserver);
         mStatusBarWindowController = Dependency.get(StatusBarWindowController.class);
@@ -135,8 +136,8 @@
         mScrimController = scrimController;
         mStatusBar = statusBar;
         mUnlockMethodCache = unlockMethodCache;
-        mWakeUpDelay = context.getResources().getInteger(
-                com.android.internal.R.integer.config_wakeUpDelayDoze);
+        mHandler = handler;
+        mWakeUpDelay = wakeUpDelay;
     }
 
     public void setStatusBarKeyguardViewManager(
@@ -206,7 +207,7 @@
             Trace.endSection();
             return;
         }
-        startWakeAndUnlock(calculateMode());
+        startWakeAndUnlock(calculateMode(biometricSourceType));
     }
 
     public void startWakeAndUnlock(int mode) {
@@ -295,7 +296,7 @@
     }
 
     private void showBouncer() {
-        if (calculateMode() == MODE_SHOW_BOUNCER) {
+        if (mMode == MODE_SHOW_BOUNCER) {
             mStatusBarKeyguardViewManager.showBouncer(false);
         }
         mStatusBarKeyguardViewManager.animateCollapsePanels(
@@ -339,29 +340,30 @@
         return mMode;
     }
 
-    private int calculateMode() {
+    private int calculateMode(BiometricSourceType biometricSourceType) {
         boolean unlockingAllowed = mUpdateMonitor.isUnlockingWithBiometricAllowed();
         boolean deviceDreaming = mUpdateMonitor.isDreaming();
+        boolean isFace = biometricSourceType == BiometricSourceType.FACE;
 
         if (!mUpdateMonitor.isDeviceInteractive()) {
             if (!mStatusBarKeyguardViewManager.isShowing()) {
                 return MODE_ONLY_WAKE;
             } else if (mDozeScrimController.isPulsing() && unlockingAllowed) {
-                return MODE_WAKE_AND_UNLOCK_PULSING;
+                return isFace ? MODE_NONE : MODE_WAKE_AND_UNLOCK_PULSING;
             } else if (unlockingAllowed || !mUnlockMethodCache.isMethodSecure()) {
                 return MODE_WAKE_AND_UNLOCK;
             } else {
                 return MODE_SHOW_BOUNCER;
             }
         }
-        if (unlockingAllowed && deviceDreaming) {
+        if (unlockingAllowed && deviceDreaming && !isFace) {
             return MODE_WAKE_AND_UNLOCK_FROM_DREAM;
         }
         if (mStatusBarKeyguardViewManager.isShowing()) {
             if (mStatusBarKeyguardViewManager.isBouncerShowing() && unlockingAllowed) {
                 return MODE_DISMISS_BOUNCER;
             } else if (unlockingAllowed) {
-                return MODE_UNLOCK;
+                return isFace ? MODE_ONLY_WAKE : MODE_UNLOCK;
             } else if (!mStatusBarKeyguardViewManager.isBouncerShowing()) {
                 return MODE_SHOW_BOUNCER;
             }
@@ -437,7 +439,7 @@
     }
 
     /**
-     * Successful authentication with fingerprint that wakes up the device.
+     * Successful authentication with fingerprint, face, or iris that wakes up the device.
      */
     public boolean isWakeAndUnlock() {
         return mMode == MODE_WAKE_AND_UNLOCK
@@ -446,7 +448,8 @@
     }
 
     /**
-     * Successful authentication with fingerprint when the screen was either on or off.
+     * Successful authentication with fingerprint, face, or iris when the screen was either
+     * on or off.
      */
     public boolean isBiometricUnlock() {
         return isWakeAndUnlock() || mMode == MODE_UNLOCK;
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 2fa9415..6fe23fb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -251,7 +251,6 @@
         mUnlockMethodCache.addListener(this);
         KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
         mLockIcon.setScreenOn(updateMonitor.isScreenOn());
-        mLockIcon.setDeviceInteractive(updateMonitor.isDeviceInteractive());
         mLockIcon.update();
         setClipChildren(false);
         setClipToPadding(false);
@@ -337,8 +336,8 @@
         updateRightAffordanceIcon();
 
         lp = mLockIcon.getLayoutParams();
-        lp.width = getResources().getDimensionPixelSize(R.dimen.keyguard_affordance_width);
-        lp.height = getResources().getDimensionPixelSize(R.dimen.keyguard_affordance_height);
+        lp.width = getResources().getDimensionPixelSize(R.dimen.keyguard_lock_width);
+        lp.height = getResources().getDimensionPixelSize(R.dimen.keyguard_lock_height);
         mLockIcon.setLayoutParams(lp);
         mLockIcon.setContentDescription(getContext().getText(R.string.accessibility_unlock_button));
         mLockIcon.update(true /* force */);
@@ -748,16 +747,6 @@
                 }
 
                 @Override
-                public void onStartedWakingUp() {
-                    mLockIcon.setDeviceInteractive(true);
-                }
-
-                @Override
-                public void onFinishedGoingToSleep(int why) {
-                    mLockIcon.setDeviceInteractive(false);
-                }
-
-                @Override
                 public void onScreenTurnedOn() {
                     mLockIcon.setScreenOn(true);
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
index d934d95..60015ef 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
@@ -18,12 +18,13 @@
 
 import android.content.Context;
 import android.content.res.Configuration;
+import android.content.res.TypedArray;
 import android.graphics.Color;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.AnimatedVectorDrawable;
 import android.graphics.drawable.Drawable;
-import android.os.SystemProperties;
 import android.util.AttributeSet;
+import android.view.ContextThemeWrapper;
 import android.view.accessibility.AccessibilityNodeInfo;
 
 import com.android.internal.graphics.ColorUtils;
@@ -44,28 +45,33 @@
     private static final int STATE_LOCK_OPEN = 1;
     private static final int STATE_FACE_UNLOCK = 2;
     private static final int STATE_FINGERPRINT = 3;
-    private static final int STATE_FINGERPRINT_ERROR = 4;
+    private static final int STATE_BIOMETRICS_ERROR = 4;
 
     private int mLastState = 0;
-    private boolean mLastDeviceInteractive;
-    private boolean mTransientFpError;
-    private boolean mDeviceInteractive;
+    private boolean mTransientBiometricsError;
     private boolean mScreenOn;
     private boolean mLastScreenOn;
     private Drawable mUserAvatarIcon;
     private final UnlockMethodCache mUnlockMethodCache;
     private AccessibilityController mAccessibilityController;
-    private boolean mHasFingerPrintIcon;
-    private boolean mHasFaceUnlockIcon;
+    private boolean mHasFingerPrintState;
+    private boolean mIsFaceUnlockState;
     private int mDensity;
     private boolean mPulsing;
     private boolean mDozing;
+    private boolean mLastDozing;
+    private boolean mLastPulsing;
 
     private final Runnable mDrawOffTimeout = () -> update(true /* forceUpdate */);
     private float mDarkAmount;
 
     public LockIcon(Context context, AttributeSet attrs) {
         super(context, attrs);
+        TypedArray typedArray = context.getTheme().obtainStyledAttributes(
+                attrs, new int[]{ R.attr.backgroundProtectedStyle }, 0, 0);
+        mContext = new ContextThemeWrapper(context,
+                typedArray.getResourceId(0, R.style.BackgroundProtectedStyle));
+        typedArray.recycle();
         mUnlockMethodCache = UnlockMethodCache.getInstance(context);
     }
 
@@ -75,13 +81,11 @@
         update();
     }
 
-    public void setTransientFpError(boolean transientFpError) {
-        mTransientFpError = transientFpError;
-        update();
-    }
-
-    public void setDeviceInteractive(boolean deviceInteractive) {
-        mDeviceInteractive = deviceInteractive;
+    /**
+     * If we're currently presenting an authentication error message.
+     */
+    public void setTransientBiometricsError(boolean transientBiometricsError) {
+        mTransientBiometricsError = transientBiometricsError;
         update();
     }
 
@@ -106,21 +110,14 @@
 
     public void update(boolean force) {
         int state = getState();
-        boolean anyFingerprintIcon = state == STATE_FINGERPRINT || state == STATE_FINGERPRINT_ERROR;
-        mHasFaceUnlockIcon = state == STATE_FACE_UNLOCK;
-        if (state != mLastState || mDeviceInteractive != mLastDeviceInteractive
-                || mScreenOn != mLastScreenOn || force) {
-            int iconAnimRes =
-                getAnimationResForTransition(mLastState, state, mLastDeviceInteractive,
-                    mDeviceInteractive, mLastScreenOn, mScreenOn);
+        boolean anyFingerprintState = state == STATE_FINGERPRINT
+                || state == STATE_BIOMETRICS_ERROR;
+        mIsFaceUnlockState = state == STATE_FACE_UNLOCK;
+        if (state != mLastState || mLastDozing == mDozing || mLastPulsing == mPulsing
+                || mLastScreenOn != mScreenOn || force) {
+            int iconAnimRes = getAnimationResForTransition(mLastState, state, mLastPulsing,
+                    mPulsing, mLastDozing, mDozing);
             boolean isAnim = iconAnimRes != -1;
-            if (iconAnimRes == R.drawable.lockscreen_fingerprint_draw_off_animation) {
-                anyFingerprintIcon = true;
-            } else if (iconAnimRes == R.drawable.trusted_state_to_error_animation) {
-                anyFingerprintIcon = true;
-            } else if (iconAnimRes == R.drawable.error_to_trustedstate_animation) {
-                anyFingerprintIcon = true;
-            }
 
             Drawable icon;
             if (isAnim) {
@@ -128,7 +125,7 @@
                 icon = mContext.getDrawable(iconAnimRes);
             } else {
                 // Load the static icon resource based on the current state.
-                icon = getIconForState(state, mScreenOn, mDeviceInteractive);
+                icon = getIconForState(state);
             }
 
             final AnimatedVectorDrawable animation = icon instanceof AnimatedVectorDrawable
@@ -136,18 +133,18 @@
                     : null;
             setImageDrawable(icon, false);
             updateDarkTint();
-            if (mHasFaceUnlockIcon) {
+            if (mIsFaceUnlockState) {
                 announceForAccessibility(getContext().getString(
                     R.string.accessibility_scanning_face));
             }
 
-            mHasFingerPrintIcon = anyFingerprintIcon;
+            mHasFingerPrintState = anyFingerprintState;
             if (animation != null && isAnim) {
                 animation.forceAnimationOnUI();
                 animation.start();
             }
 
-            if (iconAnimRes == R.drawable.lockscreen_fingerprint_draw_off_animation) {
+            if (isAnim && !mLastScreenOn) {
                 removeCallbacks(mDrawOffTimeout);
                 postDelayed(mDrawOffTimeout, FP_DRAW_OFF_TIMEOUT);
             } else {
@@ -155,8 +152,9 @@
             }
 
             mLastState = state;
-            mLastDeviceInteractive = mDeviceInteractive;
             mLastScreenOn = mScreenOn;
+            mLastDozing = mDozing;
+            mLastPulsing = mPulsing;
         }
 
         setVisibility(mDozing && !mPulsing ? GONE : VISIBLE);
@@ -167,11 +165,11 @@
         if (mAccessibilityController == null) {
             return;
         }
+        boolean canLock = mUnlockMethodCache.isMethodSecure()
+                && mUnlockMethodCache.canSkipBouncer();
         boolean clickToUnlock = mAccessibilityController.isAccessibilityEnabled();
-        boolean clickToForceLock = mUnlockMethodCache.isTrustManaged()
-                && !clickToUnlock;
-        boolean longClickToForceLock = mUnlockMethodCache.isTrustManaged()
-                && !clickToForceLock;
+        boolean clickToForceLock = canLock && !clickToUnlock;
+        boolean longClickToForceLock = canLock && !clickToForceLock;
         setClickable(clickToForceLock || clickToUnlock);
         setLongClickable(longClickToForceLock);
         setFocusable(mAccessibilityController.isAccessibilityEnabled());
@@ -180,7 +178,7 @@
     @Override
     public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
         super.onInitializeAccessibilityNodeInfo(info);
-        if (mHasFingerPrintIcon) {
+        if (mHasFingerPrintState) {
             AccessibilityNodeInfo.AccessibilityAction unlock
                     = new AccessibilityNodeInfo.AccessibilityAction(
                     AccessibilityNodeInfo.ACTION_CLICK,
@@ -188,7 +186,7 @@
             info.addAction(unlock);
             info.setHintText(getContext().getString(
                     R.string.accessibility_waiting_for_fingerprint));
-        } else if (mHasFaceUnlockIcon){
+        } else if (mIsFaceUnlockState) {
             //Avoid 'button' to be spoken for scanning face
             info.setClassName(LockIcon.class.getName());
             info.setContentDescription(getContext().getString(
@@ -200,26 +198,24 @@
         mAccessibilityController = accessibilityController;
     }
 
-    private Drawable getIconForState(int state, boolean screenOn, boolean deviceInteractive) {
+    private Drawable getIconForState(int state) {
         int iconRes;
         switch (state) {
             case STATE_FINGERPRINT:
             case STATE_LOCKED:
-                iconRes = R.drawable.ic_lock;
+            case STATE_FACE_UNLOCK:
+                iconRes = com.android.internal.R.drawable.ic_lock_24dp;
                 break;
             case STATE_LOCK_OPEN:
                 if (mUnlockMethodCache.isTrustManaged() && mUnlockMethodCache.isTrusted()
                     && mUserAvatarIcon != null) {
                     return mUserAvatarIcon;
                 } else {
-                    iconRes = R.drawable.ic_lock_open;
+                    iconRes = com.android.internal.R.drawable.ic_lock_open_24dp;
                 }
                 break;
-            case STATE_FACE_UNLOCK:
-                iconRes = R.drawable.ic_face_unlock;
-                break;
-            case STATE_FINGERPRINT_ERROR:
-                iconRes = R.drawable.ic_fingerprint_error;
+            case STATE_BIOMETRICS_ERROR:
+                iconRes = com.android.internal.R.drawable.ic_auth_error;
                 break;
             default:
                 throw new IllegalArgumentException();
@@ -229,36 +225,36 @@
     }
 
     private int getAnimationResForTransition(int oldState, int newState,
-            boolean oldDeviceInteractive, boolean deviceInteractive,
-            boolean oldScreenOn, boolean screenOn) {
-        if (oldState == STATE_FINGERPRINT && newState == STATE_FINGERPRINT_ERROR) {
-            return R.drawable.lockscreen_fingerprint_fp_to_error_state_animation;
-        } else if (oldState == STATE_LOCK_OPEN && newState == STATE_FINGERPRINT_ERROR) {
-            return R.drawable.trusted_state_to_error_animation;
-        } else if (oldState == STATE_FINGERPRINT_ERROR && newState == STATE_LOCK_OPEN) {
-            return R.drawable.error_to_trustedstate_animation;
-        } else if (oldState == STATE_FINGERPRINT_ERROR && newState == STATE_FINGERPRINT) {
-            return R.drawable.lockscreen_fingerprint_error_state_to_fp_animation;
-        } else if (oldState == STATE_FINGERPRINT && newState == STATE_LOCK_OPEN
-                && !mUnlockMethodCache.isTrusted()) {
-            return R.drawable.lockscreen_fingerprint_draw_off_animation;
-        } else if (newState == STATE_FINGERPRINT && (!oldScreenOn && screenOn && deviceInteractive
-                || screenOn && !oldDeviceInteractive && deviceInteractive)) {
-            return R.drawable.lockscreen_fingerprint_draw_on_animation;
-        } else {
-            return -1;
+            boolean wasPulsing, boolean pulsing,
+            boolean wasDozing, boolean dozing) {
+
+        boolean isError = newState == STATE_BIOMETRICS_ERROR;
+        boolean isUnlocked = newState == STATE_LOCK_OPEN;
+        boolean isLocked = !isUnlocked;
+        boolean wasUnlocked = oldState == STATE_LOCK_OPEN;
+
+        if (isError) {
+            return com.android.internal.R.anim.lock_to_error;
+        } else if (isUnlocked) {
+            return com.android.internal.R.anim.lock_unlock;
+        } else if (wasUnlocked && isLocked && mScreenOn) {
+            return com.android.internal.R.anim.lock_lock;
+        } else if (isLocked && (!wasPulsing && pulsing || wasDozing && !dozing)) {
+            return com.android.internal.R.anim.lock_in;
         }
+        return -1;
     }
 
     private int getState() {
         KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
         boolean fingerprintRunning = updateMonitor.isFingerprintDetectionRunning();
         boolean unlockingAllowed = updateMonitor.isUnlockingWithBiometricAllowed();
-        if (mTransientFpError) {
-            return STATE_FINGERPRINT_ERROR;
+        if (mTransientBiometricsError) {
+            return STATE_BIOMETRICS_ERROR;
         } else if (mUnlockMethodCache.canSkipBouncer()) {
             return STATE_LOCK_OPEN;
-        } else if (mUnlockMethodCache.isFaceUnlockRunning()) {
+        } else if (mUnlockMethodCache.isFaceUnlockRunning()
+                || updateMonitor.isFaceDetectionRunning()) {
             return STATE_FACE_UNLOCK;
         } else if (fingerprintRunning && unlockingAllowed) {
             return STATE_FINGERPRINT;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationGestureAction.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationGestureAction.java
index 39fbbb1..eca14eb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationGestureAction.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationGestureAction.java
@@ -20,12 +20,10 @@
 import static android.view.WindowManagerPolicyConstants.NAV_BAR_RIGHT;
 
 import static com.android.systemui.shared.system.NavigationBarCompat.HIT_TARGET_NONE;
-import static com.android.systemui.statusbar.phone.NavigationPrototypeController.PROTOTYPE_ENABLED;
 
 import android.annotation.NonNull;
 import android.content.Context;
 import android.graphics.Canvas;
-import android.provider.Settings;
 import android.view.MotionEvent;
 
 import com.android.systemui.recents.OverviewProxyService;
@@ -34,10 +32,6 @@
  * A gesture action that would be triggered and reassigned by {@link QuickStepController}
  */
 public abstract class NavigationGestureAction {
-    private static final String ENABLE_TASK_STABILIZER_FLAG = "ENABLE_TASK_STABILIZER";
-
-    static private boolean sLastTaskStabilizationFlag;
-
     protected final NavigationBarView mNavigationBarView;
     protected final OverviewProxyService mProxySender;
 
@@ -50,9 +44,6 @@
             @NonNull OverviewProxyService service) {
         mNavigationBarView = navigationBarView;
         mProxySender = service;
-        sLastTaskStabilizationFlag = Settings.Global.getInt(
-                mNavigationBarView.getContext().getContentResolver(),
-                ENABLE_TASK_STABILIZER_FLAG, 0) != 0;
     }
 
     /**
@@ -82,15 +73,6 @@
      */
     public void startGesture(MotionEvent event) {
         mIsActive = true;
-
-        // Tell launcher that this action requires a stable task list or not
-        boolean flag = requiresStableTaskList();
-        if (getGlobalBoolean(PROTOTYPE_ENABLED) && flag != sLastTaskStabilizationFlag) {
-            Settings.Global.putInt(mNavigationBarView.getContext().getContentResolver(),
-                    ENABLE_TASK_STABILIZER_FLAG, flag ? 1 : 0);
-            sLastTaskStabilizationFlag = flag;
-        }
-
         onGestureStart(event);
     }
 
@@ -163,13 +145,6 @@
      */
     public abstract boolean isEnabled();
 
-    /**
-     * @return action requires a stable task list from launcher
-     */
-    protected boolean requiresStableTaskList() {
-        return false;
-    }
-
     protected void onDarkIntensityChange(float intensity) {
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java
index f4f86eb..b4feb25 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java
@@ -37,7 +37,6 @@
 
     private final String GESTURE_MATCH_SETTING = "quickstepcontroller_gesture_match_map";
     public static final String NAV_COLOR_ADAPT_ENABLE_SETTING = "navbar_color_adapt_enable";
-    public static final String PROTOTYPE_ENABLED = "prototype_enabled";
 
     @Retention(RetentionPolicy.SOURCE)
     @IntDef({ACTION_DEFAULT, ACTION_QUICKSTEP, ACTION_QUICKSCRUB, ACTION_BACK,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 711b08e..a9727c9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -1800,11 +1800,9 @@
                 || mBarState == StatusBarState.SHADE_LOCKED) {
             boolean active = getMaxPanelHeight() - getExpandedHeight() > mUnlockMoveDistance;
             KeyguardAffordanceView lockIcon = mKeyguardBottomArea.getLockIcon();
-            if (active && !mUnlockIconActive && mTracking) {
-                lockIcon.setImageAlpha(1.0f, true, 150, Interpolators.FAST_OUT_LINEAR_IN, null);
-            } else if (!active && mUnlockIconActive && mTracking) {
-                lockIcon.setImageAlpha(lockIcon.getRestingAlpha(), true /* animate */,
-                        150, Interpolators.FAST_OUT_LINEAR_IN, null);
+            if (active != mUnlockIconActive && mTracking) {
+                lockIcon.setImageAlpha(lockIcon.getRestingAlpha(), true, 150,
+                        Interpolators.FAST_OUT_LINEAR_IN, null);
             }
             mUnlockIconActive = active;
         }
@@ -2015,7 +2013,6 @@
                 || mBarState == StatusBarState.SHADE_LOCKED)) {
             KeyguardAffordanceView lockIcon = mKeyguardBottomArea.getLockIcon();
             lockIcon.setImageAlpha(0.0f, true, 100, Interpolators.FAST_OUT_LINEAR_IN, null);
-            lockIcon.setImageScale(2.0f, true, 100, Interpolators.FAST_OUT_LINEAR_IN);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepAction.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepAction.java
index 1999f9a..b18b79e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepAction.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepAction.java
@@ -47,10 +47,6 @@
         return mNavigationBarView.isQuickStepSwipeUpEnabled();
     }
 
-    protected boolean requiresStableTaskList() {
-        return true;
-    }
-
     @Override
     public void onGestureStart(MotionEvent event) {
         try {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 2413268..c129143 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -354,6 +354,8 @@
     protected StatusBarWindowController mStatusBarWindowController;
     protected UnlockMethodCache mUnlockMethodCache;
     @VisibleForTesting
+    KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    @VisibleForTesting
     DozeServiceHost mDozeServiceHost = new DozeServiceHost();
     private boolean mWakeUpComingFromTouch;
     private PointF mWakeUpTouchLocation;
@@ -612,6 +614,7 @@
         mNotificationLogger = Dependency.get(NotificationLogger.class);
         mRemoteInputManager = Dependency.get(NotificationRemoteInputManager.class);
         mNotificationListener =  Dependency.get(NotificationListener.class);
+        mNotificationListener.registerAsSystemService();
         mNetworkController = Dependency.get(NetworkController.class);
         mUserSwitcherController = Dependency.get(UserSwitcherController.class);
         mScreenLifecycle = Dependency.get(ScreenLifecycle.class);
@@ -673,7 +676,7 @@
                 mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
 
         mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
-
+        mKeyguardUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
         mBarService = IStatusBarService.Stub.asInterface(
                 ServiceManager.getService(Context.STATUS_BAR_SERVICE));
 
@@ -760,7 +763,7 @@
         mUnlockMethodCache.addListener(this);
         startKeyguard();
 
-        KeyguardUpdateMonitor.getInstance(mContext).registerCallback(mUpdateCallback);
+        mKeyguardUpdateMonitor.registerCallback(mUpdateCallback);
         putComponent(DozeHost.class, mDozeServiceHost);
 
         mScreenPinningRequest = new ScreenPinningRequest(mContext);
@@ -1054,7 +1057,6 @@
                         mDeviceProvisionedController);
 
         mAppOpsController.addCallback(APP_OPS, this);
-        mNotificationListener.setUpWithPresenter(mPresenter);
         mNotificationShelf.setOnActivatedListener(mPresenter);
         mRemoteInputManager.getController().addCallback(mStatusBarWindowController);
 
@@ -1206,7 +1208,9 @@
         KeyguardViewMediator keyguardViewMediator = getComponent(KeyguardViewMediator.class);
         mBiometricUnlockController = new BiometricUnlockController(mContext,
                 mDozeScrimController, keyguardViewMediator,
-                mScrimController, this, UnlockMethodCache.getInstance(mContext));
+                mScrimController, this, UnlockMethodCache.getInstance(mContext),
+                new Handler(), mKeyguardUpdateMonitor, mContext.getResources().getInteger(
+                com.android.internal.R.integer.config_wakeUpDelayDoze));
         mStatusBarKeyguardViewManager = keyguardViewMediator.registerStatusBar(this,
                 getBouncerContainer(), mNotificationPanel, mBiometricUnlockController);
         mKeyguardIndicationController
@@ -2357,8 +2361,8 @@
             mLightBarController.dump(fd, pw, args);
         }
 
-        if (KeyguardUpdateMonitor.getInstance(mContext) != null) {
-            KeyguardUpdateMonitor.getInstance(mContext).dump(fd, pw, args);
+        if (mKeyguardUpdateMonitor != null) {
+            mKeyguardUpdateMonitor.dump(fd, pw, args);
         }
 
         FalsingManager.getInstance(mContext).dump(pw);
@@ -3891,6 +3895,11 @@
                 return;
             }
 
+            if (mKeyguardUpdateMonitor != null
+                    && reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
+                mKeyguardUpdateMonitor.onAuthInterruptDetected();
+            }
+
             // Set the state to pulsing, so ScrimController will know what to do once we ask it to
             // execute the transition. The pulse callback will then be invoked when the scrims
             // are black, indicating that StatusBar is ready to present the rest of the UI.
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index 2055519..d5a275e 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -18,15 +18,33 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import com.google.common.truth.Truth.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
+import android.app.admin.DevicePolicyManager;
+import android.app.trust.TrustManager;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricSourceType;
+import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
 import android.os.Bundle;
+import android.os.UserManager;
 import android.telephony.ServiceState;
 import android.telephony.SubscriptionManager;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
+import android.testing.TestableContext;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
@@ -39,6 +57,8 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -52,37 +72,71 @@
 @RunWithLooper(setAsMainLooper = true)
 public class KeyguardUpdateMonitorTest extends SysuiTestCase {
 
+    @Mock
+    private KeyguardUpdateMonitor.StrongAuthTracker mStrongAuthTracker;
+    @Mock
+    private TrustManager mTrustManager;
+    @Mock
+    private FingerprintManager mFingerprintManager;
+    @Mock
+    private FaceManager mFaceManager;
+    @Mock
+    private BiometricManager mBiometricManager;
+    @Mock
+    private PackageManager mPackageManager;
+    @Mock
+    private UserManager mUserManager;
+    @Mock
+    private DevicePolicyManager mDevicePolicyManager;
     private TestableLooper mTestableLooper;
+    private TestableKeyguardUpdateMonitor mKeyguardUpdateMonitor;
 
     @Before
     public void setup() {
+        MockitoAnnotations.initMocks(this);
+        TestableContext context = spy(mContext);
+        when(mPackageManager.hasSystemFeature(anyString())).thenReturn(true);
+        when(context.getPackageManager()).thenReturn(mPackageManager);
+        doAnswer(invocation -> {
+            IBiometricEnabledOnKeyguardCallback callback = invocation.getArgument(0);
+            callback.onChanged(BiometricSourceType.FACE, true /* enabled */);
+            return null;
+        }).when(mBiometricManager).registerEnabledOnKeyguardCallback(any());
+        when(mFaceManager.isHardwareDetected()).thenReturn(true);
+        when(mFaceManager.hasEnrolledTemplates()).thenReturn(true);
+        when(mFaceManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+        when(mUserManager.isUserUnlocked(anyInt())).thenReturn(true);
+        when(mStrongAuthTracker.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        context.addMockSystemService(TrustManager.class, mTrustManager);
+        context.addMockSystemService(FingerprintManager.class, mFingerprintManager);
+        context.addMockSystemService(BiometricManager.class, mBiometricManager);
+        context.addMockSystemService(FaceManager.class, mFaceManager);
+        context.addMockSystemService(UserManager.class, mUserManager);
+        context.addMockSystemService(DevicePolicyManager.class, mDevicePolicyManager);
+
         mTestableLooper = TestableLooper.get(this);
+        mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(context);
     }
 
     @Test
     public void testIgnoresSimStateCallback_rebroadcast() {
         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
 
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
-
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
         mTestableLooper.processAllMessages();
         Assert.assertTrue("onSimStateChanged not called",
-                keyguardUpdateMonitor.hasSimStateJustChanged());
+                mKeyguardUpdateMonitor.hasSimStateJustChanged());
 
         intent.putExtra(TelephonyIntents.EXTRA_REBROADCAST_ON_UNLOCK, true);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext(), intent);
         mTestableLooper.processAllMessages();
         Assert.assertFalse("onSimStateChanged should have been skipped",
-                keyguardUpdateMonitor.hasSimStateJustChanged());
+                mKeyguardUpdateMonitor.hasSimStateJustChanged());
     }
 
     @Test
     public void testTelephonyCapable_BootInitState() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
@@ -90,36 +144,30 @@
         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         intent.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_ABSENT);
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent,null, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isTrue();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
     }
 
     @Test
     public void testTelephonyCapable_SimInvalid_ServiceState_InService() {
         // SERVICE_STATE - IN_SERVICE, but SIM_STATE is invalid TelephonyCapable should be False
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_IN_SERVICE);
         state.fillInNotifierBundle(data);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
     public void testTelephonyCapable_SimValid_ServiceState_PowerOff() {
         // Simulate AirplaneMode case, SERVICE_STATE - POWER_OFF, check TelephonyCapable False
         // Only receive ServiceState callback IN_SERVICE -> OUT_OF_SERVICE -> POWER_OFF
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         intent.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_LOADED);
@@ -127,10 +175,10 @@
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_POWER_OFF);
         state.fillInNotifierBundle(data);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, true));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isTrue();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
     }
 
     /* Normal SIM inserted flow
@@ -142,24 +190,20 @@
      */
     @Test
     public void testTelephonyCapable_BootInitState_ServiceState_OutOfService() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
         state.fillInNotifierBundle(data);
         intent.putExtras(data);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
     public void testTelephonyCapable_BootInitState_SimState_NotReady() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
@@ -167,16 +211,14 @@
         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         intent.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_NOT_READY);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
     public void testTelephonyCapable_BootInitState_SimState_Ready() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_OUT_OF_SERVICE);
@@ -184,46 +226,40 @@
         Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         intent.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_READY);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
     public void testTelephonyCapable_BootInitState_ServiceState_PowerOff() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_POWER_OFF);
         state.fillInNotifierBundle(data);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, false));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
     }
 
     @Test
     public void testTelephonyCapable_SimValid_ServiceState_InService() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_IN_SERVICE);
         state.fillInNotifierBundle(data);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intent, data, true));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isTrue();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
     }
 
     @Test
     public void testTelephonyCapable_SimValid_SimState_Loaded() {
-        TestableKeyguardUpdateMonitor keyguardUpdateMonitor =
-                new TestableKeyguardUpdateMonitor(getContext());
         Bundle data = new Bundle();
         ServiceState state = new ServiceState();
         state.setState(ServiceState.STATE_IN_SERVICE);
@@ -231,19 +267,96 @@
         Intent intentSimState = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         intentSimState.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_LOADED);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intentSimState, data, true));
         mTestableLooper.processAllMessages();
         // Even SimState Loaded, still need ACTION_SERVICE_STATE_CHANGED turn on mTelephonyCapable
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isFalse();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isFalse();
 
         Intent intentServiceState =  new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         intentSimState.putExtra(IccCardConstants.INTENT_KEY_ICC_STATE
                 , IccCardConstants.INTENT_VALUE_ICC_LOADED);
-        keyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
+        mKeyguardUpdateMonitor.mBroadcastReceiver.onReceive(getContext()
                 , putPhoneInfo(intentServiceState, data, true));
         mTestableLooper.processAllMessages();
-        assertThat(keyguardUpdateMonitor.mTelephonyCapable).isTrue();
+        assertThat(mKeyguardUpdateMonitor.mTelephonyCapable).isTrue();
+    }
+
+    @Test
+    public void testTriesToAuthenticate_whenBouncer() {
+        mKeyguardUpdateMonitor.sendKeyguardBouncerChanged(true);
+        mTestableLooper.processAllMessages();
+
+        verify(mFaceManager).authenticate(any(), any(), anyInt(), any(), any());
+        verify(mFaceManager).isHardwareDetected();
+        verify(mFaceManager).hasEnrolledTemplates(anyInt());
+    }
+
+    @Test
+    public void testTriesToAuthenticate_whenKeyguard() {
+        mKeyguardUpdateMonitor.dispatchStartedWakingUp();
+        mTestableLooper.processAllMessages();
+        mKeyguardUpdateMonitor.onKeyguardVisibilityChanged(true);
+        verify(mFaceManager).authenticate(any(), any(), anyInt(), any(), any());
+    }
+
+    @Test
+    public void skipsAuthentication_whenEncryptedKeyguard() {
+        reset(mUserManager);
+        when(mUserManager.isUserUnlocked(anyInt())).thenReturn(false);
+
+        mKeyguardUpdateMonitor.dispatchStartedWakingUp();
+        mTestableLooper.processAllMessages();
+        mKeyguardUpdateMonitor.onKeyguardVisibilityChanged(true);
+        verify(mFaceManager, never()).authenticate(any(), any(), anyInt(), any(), any());
+    }
+
+    @Test
+    public void testTriesToAuthenticate_whenAssistant() {
+        mKeyguardUpdateMonitor.setKeyguardOccluded(true);
+        mKeyguardUpdateMonitor.setAssistantVisible(true);
+
+        verify(mFaceManager).authenticate(any(), any(), anyInt(), any(), any());
+    }
+
+    @Test
+    public void testNeverAuthenticates_whenFaceLockout() {
+        mKeyguardUpdateMonitor.mFaceAuthenticationCallback
+                .onAuthenticationError(FaceManager.FACE_ERROR_LOCKOUT, "lockout");
+        mKeyguardUpdateMonitor.sendKeyguardBouncerChanged(true);
+        mTestableLooper.processAllMessages();
+
+        verify(mFaceManager, never()).authenticate(any(), any(), anyInt(), any(), any());
+    }
+
+    @Test
+    public void testOnFaceAuthenticated_skipsFaceWhenAuthenticated() {
+        mKeyguardUpdateMonitor.onFaceAuthenticated(KeyguardUpdateMonitor.getCurrentUser());
+        mKeyguardUpdateMonitor.sendKeyguardBouncerChanged(true);
+        mTestableLooper.processAllMessages();
+
+        verify(mFaceManager, never()).authenticate(any(), any(), anyInt(), any(), any());
+    }
+
+    @Test
+    public void testGetUserCanSkipBouncer_whenFace() {
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        mKeyguardUpdateMonitor.onFaceAuthenticated(user);
+        assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
+    }
+
+    @Test
+    public void testGetUserCanSkipBouncer_whenFingerprint() {
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        mKeyguardUpdateMonitor.onFingerprintAuthenticated(user);
+        assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
+    }
+
+    @Test
+    public void testGetUserCanSkipBouncer_whenTrust() {
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        mKeyguardUpdateMonitor.onTrustChanged(true /* enabled */, user, 0 /* flags */);
+        assertThat(mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)).isTrue();
     }
 
     private Intent putPhoneInfo(Intent intent, Bundle data, Boolean simInited) {
@@ -261,8 +374,9 @@
 
         protected TestableKeyguardUpdateMonitor(Context context) {
             super(context);
-            // Avoid race condition when unexpected broadcast could be received.
             context.unregisterReceiver(mBroadcastReceiver);
+            context.unregisterReceiver(mBroadcastAllReceiver);
+            mStrongAuthTracker = KeyguardUpdateMonitorTest.this.mStrongAuthTracker;
         }
 
         public boolean hasSimStateJustChanged() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 5be8826..e32d48d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -304,7 +304,7 @@
         }
 
         @Override
-        public boolean shouldAutoBubble(Context c, NotificationEntry entry) {
+        public boolean shouldAutoBubbleForFlags(Context c, NotificationEntry entry) {
             return entry.notification.getNotification().getBubbleMetadata() != null;
         }
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
index bfc02d9..5be991f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
@@ -75,7 +75,7 @@
     }
 
     @Test
-    public void testRenderVisibility() {
+    public void testRenderVisibility() throws InterruptedException {
         mLayout.setController(mTestableController);
         addOneMoreThanRenderLimitBubbles();
 
@@ -87,7 +87,7 @@
     }
 
     @Test
-    public void testHierarchyChanges() {
+    public void testHierarchyChanges() throws InterruptedException {
         mLayout.setController(mTestableController);
         addOneMoreThanRenderLimitBubbles();
 
@@ -242,26 +242,6 @@
     }
 
     @Test
-    public void testPrecedingNonRemovedIndex() {
-        mLayout.setController(mTestableController);
-        addOneMoreThanRenderLimitBubbles();
-
-        // Call removeView at index 4, but don't actually remove it yet (as if we're animating it
-        // out). The preceding, non-removed view index to 3 should initially be 4, but then 5 since
-        // 4 is on its way out.
-        assertEquals(4, mLayout.getPrecedingNonRemovedViewIndex(3));
-        mLayout.removeView(mViews.get(4));
-        assertEquals(5, mLayout.getPrecedingNonRemovedViewIndex(3));
-
-        // Call removeView at index 1, and actually remove it immediately. With the old view at 1
-        // instantly gone, the preceding view to 0 should be 1 in both cases.
-        assertEquals(1, mLayout.getPrecedingNonRemovedViewIndex(0));
-        mTestableController.setRemoveImmediately(true);
-        mLayout.removeView(mViews.get(1));
-        assertEquals(1, mLayout.getPrecedingNonRemovedViewIndex(0));
-    }
-
-    @Test
     public void testSetController() throws InterruptedException {
         // Add the bubbles, then set the controller, to make sure that a controller added to an
         // already-initialized view works correctly.
@@ -360,8 +340,6 @@
 
         mLayout.cancelAllAnimations();
 
-        waitForLayoutMessageQueue();
-
         // Animations should be somewhere before their end point.
         assertTrue(mViews.get(0).getTranslationX() < 1000);
         assertTrue(mViews.get(0).getTranslationY() < 1000);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
index 186a762..31e44d7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
@@ -23,6 +23,7 @@
 import android.os.Looper;
 import android.view.DisplayCutout;
 import android.view.View;
+import android.view.ViewGroup;
 import android.view.WindowInsets;
 import android.widget.FrameLayout;
 
@@ -93,7 +94,7 @@
     }
 
     /** Add one extra bubble over the limit, so we can make sure it's gone/chains appropriately. */
-    void addOneMoreThanRenderLimitBubbles() {
+    void addOneMoreThanRenderLimitBubbles() throws InterruptedException {
         for (int i = 0; i < mMaxRenderedBubbles + 1; i++) {
             final View newView = new FrameLayout(mContext);
             mLayout.addView(newView, 0);
@@ -129,7 +130,7 @@
     void waitForLayoutMessageQueue() throws InterruptedException {
         // Wait for layout, then the view should be actually removed.
         CountDownLatch layoutLatch = new CountDownLatch(1);
-        mLayout.post(layoutLatch::countDown);
+        mMainThreadHandler.post(layoutLatch::countDown);
         layoutLatch.await(1, TimeUnit.SECONDS);
     }
 
@@ -145,11 +146,7 @@
         @Override
         public void setController(PhysicsAnimationController controller) {
             mMainThreadHandler.post(() -> super.setController(controller));
-            try {
-                waitForLayoutMessageQueue();
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-            }
+            waitForMessageQueueAndIgnoreIfInterrupted();
         }
 
         @Override
@@ -169,6 +166,32 @@
             return mWindowInsets;
         }
 
+        @Override
+        public void removeView(View view) {
+            mMainThreadHandler.post(() ->
+                    super.removeView(view));
+            waitForMessageQueueAndIgnoreIfInterrupted();
+        }
+
+        @Override
+        public void addView(View child, int index, ViewGroup.LayoutParams params) {
+            mMainThreadHandler.post(() ->
+                    super.addView(child, index, params));
+            waitForMessageQueueAndIgnoreIfInterrupted();
+        }
+
+        /**
+         * Wait for the queue but just catch and print the exception if interrupted, since we can't
+         * just add the exception to the overridden methods' signatures.
+         */
+        private void waitForMessageQueueAndIgnoreIfInterrupted() {
+            try {
+                waitForLayoutMessageQueue();
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+
         /**
          * Sets an end listener that will be called after the 'real' end listener that was already
          * set.
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
index db819d5..97935ed 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
@@ -178,17 +178,20 @@
 
     @Test
     public void testChildRemoved() throws InterruptedException {
+        assertEquals(0, mLayout.getTransientViewCount());
+
         final View firstView = mLayout.getChildAt(0);
         mLayout.removeView(firstView);
 
-        // The view should still be there, since the controller is animating it out and hasn't yet
-        // actually removed it from the parent view.
-        assertEquals(0, mLayout.indexOfChild(firstView));
+        // The view should now be transient, and missing from the view's normal hierarchy.
+        assertEquals(1, mLayout.getTransientViewCount());
+        assertEquals(-1, mLayout.indexOfChild(firstView));
 
         waitForPropertyAnimations(DynamicAnimation.ALPHA);
         waitForLayoutMessageQueue();
 
-        assertEquals(-1, mLayout.indexOfChild(firstView));
+        // The view should now be gone entirely, no transient views left.
+        assertEquals(0, mLayout.getTransientViewCount());
 
         // The subsequent view should have been translated over to 0, not stacked off to the left.
         assertEquals(0, mLayout.getChildAt(0).getTranslationX(), .1f);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
index e1c481e..5a6200f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
@@ -230,9 +230,9 @@
     public void testPulseReason_getMatchesRequest() {
         mMachine.requestState(INITIALIZED);
         mMachine.requestState(DOZE);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP);
+        mMachine.requestPulse(DozeLog.REASON_SENSOR_DOUBLE_TAP);
 
-        assertEquals(DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP, mMachine.getPulseReason());
+        assertEquals(DozeLog.REASON_SENSOR_DOUBLE_TAP, mMachine.getPulseReason());
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
index 7b358b9..cdac7c97 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
@@ -125,7 +125,7 @@
     public void testOnSensor_whenUndockedWithNearAndDoubleTapScreen_shouldNotWakeUp() {
         mSensors.getMockProximitySensor().sendProximityResult(false /* far */);
 
-        mTriggers.onSensor(DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP,
+        mTriggers.onSensor(DozeLog.REASON_SENSOR_DOUBLE_TAP,
                 false /* sensorPerformedProxCheck */, 50 /* screenX */, 50 /* screenY */,
                 null /* rawValues */);
 
@@ -137,7 +137,7 @@
         doReturn(true).when(mDockManagerFake).isDocked();
         mSensors.getMockProximitySensor().sendProximityResult(false /* far */);
 
-        mTriggers.onSensor(DozeLog.PULSE_REASON_SENSOR_DOUBLE_TAP,
+        mTriggers.onSensor(DozeLog.REASON_SENSOR_DOUBLE_TAP,
                 false /* sensorPerformedProxCheck */, 50 /* screenX */, 50 /* screenY */,
                 null /* rawValues */);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
index f163b88..b6e0d90 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
@@ -37,7 +37,7 @@
                 "Bar", TEST_UID, context))
         val bar3 = PrivacyItem(Privacy.TYPE_LOCATION, PrivacyApplication(
                 "Bar", TEST_UID, context))
-        val foo0 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+        val foo0 = PrivacyItem(Privacy.TYPE_MICROPHONE, PrivacyApplication(
                 "Foo", TEST_UID, context))
         val baz1 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
                 "Baz", TEST_UID, context))
@@ -50,10 +50,11 @@
         assertEquals(3, list.size)
         val appsList = list.map { it.first }
         val typesList = list.map { it.second }
+        // List is sorted by number of types and then by types
         assertEquals(listOf("Bar", "Baz", "Foo"), appsList.map { it.packageName })
         assertEquals(listOf(Privacy.TYPE_CAMERA, Privacy.TYPE_LOCATION), typesList[0])
         assertEquals(listOf(Privacy.TYPE_CAMERA), typesList[1])
-        assertEquals(listOf(Privacy.TYPE_CAMERA), typesList[2])
+        assertEquals(listOf(Privacy.TYPE_MICROPHONE), typesList[2])
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
index 425ca58..8e926848 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
@@ -97,7 +97,6 @@
                 mDelegate);
         lockscreenUserManager.setUpWithPresenter(mPresenter);
         viewHierarchyManager.setUpWithPresenter(mPresenter, mListContainer);
-        notificationListener.setUpWithPresenter(mPresenter);
 
         TestableLooper.get(this).processAllMessages();
         assertFalse(mDependency.hasInstantiatedDependency(StatusBarWindowController.class));
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
index bcf5964..cffa9c7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
@@ -77,8 +77,6 @@
         mListener = new NotificationListener(mContext);
         mSbn = new StatusBarNotification(TEST_PACKAGE_NAME, TEST_PACKAGE_NAME, 0, null, TEST_UID, 0,
                 new Notification(), UserHandle.CURRENT, null, 0);
-
-        mListener.setUpWithPresenter(mPresenter);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
index c36fec2..c80396d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
@@ -209,7 +209,8 @@
 
     @Test
     public void chooseSmartRepliesAndActions_smartRepliesOff_noSystemGeneratedSmartSuggestions() {
-        mEntry.smartReplies = new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
         mEntry.systemGeneratedSmartActions =
                 createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
         when(mSmartReplyConstants.isEnabled()).thenReturn(false);
@@ -256,11 +257,13 @@
         // replies.
         setupAppGeneratedReplies(null /* smartReplies */);
 
-        mEntry.smartReplies = new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
         NotificationContentView.SmartRepliesAndActions repliesAndActions =
                 NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
 
-        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(mEntry.smartReplies);
+        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(
+                mEntry.systemGeneratedSmartReplies);
         assertThat(repliesAndActions.smartReplies.fromAssistant).isTrue();
         assertThat(repliesAndActions.smartActions).isNull();
     }
@@ -271,7 +274,7 @@
         // replies.
         setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
 
-        mEntry.smartReplies =
+        mEntry.systemGeneratedSmartReplies =
                 new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
         NotificationContentView.SmartRepliesAndActions repliesAndActions =
                 NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
@@ -306,7 +309,8 @@
                 createActions(new String[] {"Test Action 1", "Test Action 2"});
         setupAppGeneratedSuggestions(appGenSmartReplies, appGenSmartActions);
 
-        mEntry.smartReplies = new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
         mEntry.systemGeneratedSmartActions =
                 createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
 
@@ -325,7 +329,8 @@
         // actions.
         setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
         when(mNotification.getAllowSystemGeneratedContextualActions()).thenReturn(false);
-        mEntry.smartReplies = new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
         mEntry.systemGeneratedSmartActions =
                 createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
new file mode 100644
index 0000000..7be4756
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.phone;
+
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.hardware.biometrics.BiometricSourceType;
+import android.os.Handler;
+import android.os.PowerManager;
+import android.os.UserHandle;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper.RunWithLooper;
+
+import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.statusbar.NotificationMediaManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+public class BiometricsUnlockControllerTest extends SysuiTestCase {
+
+    @Mock
+    private NotificationMediaManager mMediaManager;
+    @Mock
+    private PowerManager mPowerManager;
+    @Mock
+    private KeyguardUpdateMonitor mUpdateMonitor;
+    @Mock
+    private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
+    @Mock
+    private StatusBarWindowController mStatusBarWindowController;
+    @Mock
+    private DozeScrimController mDozeScrimController;
+    @Mock
+    private KeyguardViewMediator mKeyguardViewMediator;
+    @Mock
+    private ScrimController mScrimController;
+    @Mock
+    private StatusBar mStatusBar;
+    @Mock
+    private UnlockMethodCache mUnlockMethodCache;
+    private BiometricUnlockController mBiometricUnlockController;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
+        when(mUpdateMonitor.isDeviceInteractive()).thenReturn(true);
+        mContext.addMockSystemService(PowerManager.class, mPowerManager);
+        mDependency.injectTestDependency(NotificationMediaManager.class, mMediaManager);
+        mDependency.injectTestDependency(StatusBarWindowController.class,
+                mStatusBarWindowController);
+        mBiometricUnlockController = new BiometricUnlockController(mContext, mDozeScrimController,
+                mKeyguardViewMediator, mScrimController, mStatusBar, mUnlockMethodCache,
+                new Handler(), mUpdateMonitor, 0 /* wakeUpDelay */);
+        mBiometricUnlockController.setStatusBarKeyguardViewManager(mStatusBarKeyguardViewManager);
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFingerprintAndBiometricsDisallowed_showBouncer() {
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FINGERPRINT);
+        verify(mStatusBarKeyguardViewManager).showBouncer(eq(false));
+        verify(mStatusBarKeyguardViewManager).animateCollapsePanels(anyFloat());
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFingerprintAndNotInteractive_wakeAndUnlock() {
+        reset(mUpdateMonitor);
+        reset(mStatusBarKeyguardViewManager);
+        when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        when(mDozeScrimController.isPulsing()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FINGERPRINT);
+
+        verify(mKeyguardViewMediator).onWakeAndUnlocking();
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFingerprint_dismissKeyguard() {
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FINGERPRINT);
+
+        verify(mStatusBarKeyguardViewManager, never()).showBouncer(anyBoolean());
+        verify(mStatusBarKeyguardViewManager).animateCollapsePanels(anyFloat());
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFingerprintOnBouncer_dismissBouncer() {
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FINGERPRINT);
+
+        verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(eq(false));
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFace_dontDismissKeyguard() {
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FACE);
+
+        verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFaceOnBouncer_dismissBouncer() {
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FACE);
+
+        verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(eq(false));
+    }
+
+    @Test
+    public void onBiometricAuthenticated_whenFaceAndPulsing_dontDismissKeyguard() {
+        reset(mUpdateMonitor);
+        reset(mStatusBarKeyguardViewManager);
+        when(mUpdateMonitor.isUnlockingWithBiometricAllowed()).thenReturn(true);
+        when(mDozeScrimController.isPulsing()).thenReturn(true);
+        mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
+                BiometricSourceType.FACE);
+
+        verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index 17611ff..49fcafd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -64,6 +64,7 @@
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.logging.testing.FakeMetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
+import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.Dependency;
 import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.InitController;
@@ -120,6 +121,9 @@
 import java.io.ByteArrayOutputStream;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
@@ -161,6 +165,8 @@
     private NotificationAlertingManager mNotificationAlertingManager;
     @Mock
     private NotificationLogger.ExpansionStateLogger mExpansionStateLogger;
+    @Mock
+    private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
 
     private TestableStatusBar mStatusBar;
     private FakeMetricsLogger mMetricsLogger;
@@ -252,7 +258,7 @@
                 mDozeScrimController, mock(NotificationShelf.class),
                 mLockscreenUserManager, mCommandQueue, mNotificationPresenter,
                 mock(BubbleController.class), mock(NavigationBarController.class),
-                mock(AutoHideController.class));
+                mock(AutoHideController.class), mKeyguardUpdateMonitor);
         mStatusBar.mContext = mContext;
         mStatusBar.mComponents = mContext.getComponents();
         SystemUIFactory.getInstance().getRootComponent()
@@ -631,6 +637,39 @@
     }
 
     @Test
+    public void testPulseWhileDozing_notifyAuthInterrupt() {
+        HashSet<Integer> reasonsWantingAuth = new HashSet<>(
+                Collections.singletonList(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN));
+        HashSet<Integer> reasonsSkippingAuth = new HashSet<>(
+                Arrays.asList(DozeLog.PULSE_REASON_INTENT,
+                        DozeLog.PULSE_REASON_NOTIFICATION,
+                        DozeLog.PULSE_REASON_SENSOR_SIGMOTION,
+                        DozeLog.REASON_SENSOR_PICKUP,
+                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
+                        DozeLog.PULSE_REASON_SENSOR_LONG_PRESS,
+                        DozeLog.PULSE_REASON_DOCKING,
+                        DozeLog.REASON_SENSOR_WAKE_UP,
+                        DozeLog.REASON_SENSOR_TAP));
+        HashSet<Integer> reasonsThatDontPulse = new HashSet<>(
+                Arrays.asList(DozeLog.REASON_SENSOR_PICKUP,
+                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
+                        DozeLog.REASON_SENSOR_TAP));
+
+        for (int i = 0; i < DozeLog.REASONS; i++) {
+            reset(mKeyguardUpdateMonitor);
+            mStatusBar.mDozeServiceHost.pulseWhileDozing(mock(DozeHost.PulseCallback.class), i);
+            if (reasonsWantingAuth.contains(i)) {
+                verify(mKeyguardUpdateMonitor).onAuthInterruptDetected();
+            } else if (reasonsSkippingAuth.contains(i) || reasonsThatDontPulse.contains(i)) {
+                verify(mKeyguardUpdateMonitor, never()).onAuthInterruptDetected();
+            } else {
+                throw new AssertionError("Reason " + i + " isn't specified as wanting or skipping"
+                        + " passive auth. Please consider how this pulse reason should behave.");
+            }
+        }
+    }
+
+    @Test
     public void testSetState_changesIsFullScreenUserSwitcherState() {
         mStatusBar.setBarStateForTest(StatusBarState.KEYGUARD);
         assertFalse(mStatusBar.isFullScreenUserSwitcherState());
@@ -705,7 +744,8 @@
                 NotificationPresenter notificationPresenter,
                 BubbleController bubbleController,
                 NavigationBarController navBarController,
-                AutoHideController autoHideController) {
+                AutoHideController autoHideController,
+                KeyguardUpdateMonitor keyguardUpdateMonitor) {
             mStatusBarKeyguardViewManager = man;
             mUnlockMethodCache = unlock;
             mKeyguardIndicationController = key;
@@ -738,6 +778,7 @@
             mBubbleController = bubbleController;
             mNavigationBarController = navBarController;
             mAutoHideController = autoHideController;
+            mKeyguardUpdateMonitor = keyguardUpdateMonitor;
         }
 
         private WakefulnessLifecycle createAwakeWakefulnessLifecycle() {
diff --git a/proto/src/metrics_constants/metrics_constants.proto b/proto/src/metrics_constants/metrics_constants.proto
index aeb4261..76bb24d 100644
--- a/proto/src/metrics_constants/metrics_constants.proto
+++ b/proto/src/metrics_constants/metrics_constants.proto
@@ -6915,6 +6915,27 @@
     // OS: Q
     MOBILE_NETWORK_RENAME_DIALOG = 1642;
 
+    // ACTION: Settings > Search Bar > Avatar
+    // CATEGORY: SETTINGS
+    // OS: Q
+    ACTION_CLICK_ACCOUNT_AVATAR = 1643;
+
+    // OPEN: Set new password (action intents android.app.action.SET_NEW_PASSWORD or
+    // android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    SET_NEW_PASSWORD_ACTIVITY = 1644;
+
+    // ACTION: Set new password (action intent android.app.action.SET_NEW_PASSWORD)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    ACTION_SET_NEW_PASSWORD = 1645;
+
+    // ACTION: Set new password (action intent android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD)
+    // CATEGORY: SETTINGS
+    // OS: Q
+    ACTION_SET_NEW_PARENT_PROFILE_PASSWORD = 1646;
+
     // ---- End Q Constants, all Q constants go above this line ----
     // Add new aosp constants above this line.
     // END OF AOSP CONSTANTS
diff --git a/proto/src/wifi.proto b/proto/src/wifi.proto
index b84736b..2b45b49 100644
--- a/proto/src/wifi.proto
+++ b/proto/src/wifi.proto
@@ -1888,11 +1888,31 @@
     LABEL_BAD = 2;
   }
 
+  enum UsabilityStatsTriggerType {
+    // Default/Invalid event
+    TYPE_UNKNOWN = 0;
+
+    // There is a data stall from tx failures
+    TYPE_DATA_STALL_BAD_TX = 1;
+
+    // There is a data stall from rx failures
+    TYPE_DATA_STALL_TX_WITHOUT_RX = 2;
+
+    // There is a data stall from both tx and rx failures
+    TYPE_DATA_STALL_BOTH = 3;
+
+    // Firmware generated an alert
+    TYPE_FIRMWARE_ALERT = 4;
+  }
+
   // The current wifi usability state
   optional Label label = 1;
 
   // The list of timestamped wifi usability stats
   repeated WifiUsabilityStatsEntry stats = 2;
+
+  // What event triggered WifiUsabilityStats.
+  optional UsabilityStatsTriggerType trigger_type = 3;
 }
 
 message DeviceMobilityStatePnoScanStats {
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index 75ee99f..9249c9c 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -26,6 +26,7 @@
 import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.pm.ActivityPresentationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.UserInfo;
@@ -346,21 +347,16 @@
                 @NonNull ComponentName componentName, @NonNull String sessionId, int flags,
                 @NonNull IResultReceiver result) {
             Preconditions.checkNotNull(activityToken);
-            Preconditions.checkNotNull(componentName);
             Preconditions.checkNotNull(sessionId);
             final int userId = UserHandle.getCallingUserId();
 
-            // TODO(b/111276913): refactor getTaskIdForActivity() to also return ComponentName,
-            // so we don't pass it on startSession (same for Autofill)
-            final int taskId = getAmInternal().getTaskIdForActivity(activityToken, false);
-
-            // TODO(b/121260224): get from AM as well
-            final int displayId = 0;
+            final ActivityPresentationInfo activityPresentationInfo = getAmInternal()
+                    .getActivityPresentationInfo(activityToken);
 
             synchronized (mLock) {
                 final ContentCapturePerUserService service = getServiceForUserLocked(userId);
-                service.startSessionLocked(activityToken, componentName, taskId, displayId,
-                        sessionId, Binder.getCallingUid(), flags, result);
+                service.startSessionLocked(activityToken, activityPresentationInfo, sessionId,
+                        Binder.getCallingUid(), flags, result);
             }
         }
 
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
index bc0e19a..c8a27f1 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
@@ -19,6 +19,7 @@
 import static android.service.contentcapture.ContentCaptureService.setClientState;
 import static android.view.contentcapture.ContentCaptureSession.STATE_DISABLED;
 import static android.view.contentcapture.ContentCaptureSession.STATE_DUPLICATED_ID;
+import static android.view.contentcapture.ContentCaptureSession.STATE_INTERNAL_ERROR;
 import static android.view.contentcapture.ContentCaptureSession.STATE_NO_SERVICE;
 
 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
@@ -33,6 +34,7 @@
 import android.app.assist.AssistContent;
 import android.app.assist.AssistStructure;
 import android.content.ComponentName;
+import android.content.pm.ActivityPresentationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ServiceInfo;
@@ -171,10 +173,18 @@
     // TODO(b/119613670): log metrics
     @GuardedBy("mLock")
     public void startSessionLocked(@NonNull IBinder activityToken,
-            @NonNull ComponentName componentName, int taskId, int displayId,
+            @NonNull ActivityPresentationInfo activityPresentationInfo,
             @NonNull String sessionId, int uid, int flags,
             @NonNull IResultReceiver clientReceiver) {
-
+        if (activityPresentationInfo == null) {
+            Slog.w(TAG, "basic activity info is null");
+            setClientState(clientReceiver, STATE_DISABLED | STATE_INTERNAL_ERROR,
+                    /* binder= */ null);
+            return;
+        }
+        final int taskId = activityPresentationInfo.taskId;
+        final int displayId = activityPresentationInfo.displayId;
+        final ComponentName componentName = activityPresentationInfo.componentName;
         final ComponentName serviceComponentName = getServiceComponentName();
         final boolean enabled = isEnabledLocked();
         final String historyItem =
diff --git a/services/core/Android.bp b/services/core/Android.bp
index bf08f3e..f9de554 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -50,7 +50,7 @@
         "android.hardware.vibrator-V1.0-java",
         "android.hardware.configstore-V1.0-java",
         "android.hardware.contexthub-V1.0-java",
-        "android.hidl.manager-V1.0-java",
+        "android.hidl.manager-V1.2-java",
         "netd_aidl_interface-java",
         "netd_event_listener_interface-java",
     ],
diff --git a/services/core/java/com/android/server/PackageWatchdog.java b/services/core/java/com/android/server/PackageWatchdog.java
index 4507193..ec40971 100644
--- a/services/core/java/com/android/server/PackageWatchdog.java
+++ b/services/core/java/com/android/server/PackageWatchdog.java
@@ -247,9 +247,8 @@
                 }
 
                 for (int pIndex = 0; pIndex < packages.size(); pIndex++) {
-                    String packageToReport = packages.get(pIndex).getPackageName();
-                    long packageVersionCode = packages.get(pIndex).getVersionCode();
-                    // Observer that will receive failure for packageToReport
+                    VersionedPackage versionedPackage = packages.get(pIndex);
+                    // Observer that will receive failure for versionedPackage
                     PackageHealthObserver currentObserverToNotify = null;
                     int currentObserverImpact = Integer.MAX_VALUE;
 
@@ -258,9 +257,8 @@
                         ObserverInternal observer = mAllObservers.valueAt(oIndex);
                         PackageHealthObserver registeredObserver = observer.mRegisteredObserver;
                         if (registeredObserver != null
-                                && observer.onPackageFailure(packageToReport)) {
-                            int impact = registeredObserver.onHealthCheckFailed(packageToReport,
-                                    packageVersionCode);
+                                && observer.onPackageFailure(versionedPackage.getPackageName())) {
+                            int impact = registeredObserver.onHealthCheckFailed(versionedPackage);
                             if (impact != PackageHealthObserverImpact.USER_IMPACT_NONE
                                     && impact < currentObserverImpact) {
                                 currentObserverToNotify = registeredObserver;
@@ -271,7 +269,7 @@
 
                     // Execute action with least user impact
                     if (currentObserverToNotify != null) {
-                        currentObserverToNotify.execute(packageToReport, packageVersionCode);
+                        currentObserverToNotify.execute(versionedPackage);
                     }
                 }
             }
@@ -310,19 +308,19 @@
     /** Register instances of this interface to receive notifications on package failure. */
     public interface PackageHealthObserver {
         /**
-         * Called when health check fails for the {@code packageName}.
+         * Called when health check fails for the {@code versionedPackage}.
          *
          * @return any one of {@link PackageHealthObserverImpact} to express the impact
          * to the user on {@link #execute}
          */
-        @PackageHealthObserverImpact int onHealthCheckFailed(String packageName, long versionCdoe);
+        @PackageHealthObserverImpact int onHealthCheckFailed(VersionedPackage versionedPackage);
 
         /**
          * Executes mitigation for {@link #onHealthCheckFailed}.
          *
          * @return {@code true} if action was executed successfully, {@code false} otherwise
          */
-        boolean execute(String packageName, long versionCode);
+        boolean execute(VersionedPackage versionedPackage);
 
         // TODO(zezeozue): Ensure uniqueness?
         /**
diff --git a/services/core/java/com/android/server/VibratorService.java b/services/core/java/com/android/server/VibratorService.java
index 9b9911a..545baa0 100644
--- a/services/core/java/com/android/server/VibratorService.java
+++ b/services/core/java/com/android/server/VibratorService.java
@@ -1454,6 +1454,17 @@
 
         private final IBinder mToken;
 
+        private final class CommonOptions {
+            public boolean force = false;
+            public void check(String opt) {
+                switch (opt) {
+                    case "-f":
+                        force = true;
+                        break;
+                }
+            }
+        }
+
         private VibratorShellCommand(IBinder token) {
             mToken = token;
         }
@@ -1473,11 +1484,11 @@
             return handleDefaultCommands(cmd);
         }
 
-        private boolean checkDoNotDisturb() {
+        private boolean checkDoNotDisturb(CommonOptions opts) {
             try {
                 final int zenMode = Settings.Global.getInt(mContext.getContentResolver(),
                         Settings.Global.ZEN_MODE);
-                if (zenMode != Settings.Global.ZEN_MODE_OFF) {
+                if (zenMode != Settings.Global.ZEN_MODE_OFF && !opts.force) {
                     try (PrintWriter pw = getOutPrintWriter();) {
                         pw.print("Ignoring because device is on DND mode ");
                         pw.println(DebugUtils.flagsToString(Settings.Global.class, "ZEN_MODE_",
@@ -1495,7 +1506,14 @@
         private int runVibrate() {
             Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "runVibrate");
             try {
-                if (checkDoNotDisturb()) {
+                CommonOptions commonOptions = new CommonOptions();
+
+                String opt;
+                while ((opt = getNextOption()) != null) {
+                    commonOptions.check(opt);
+                }
+
+                if (checkDoNotDisturb(commonOptions)) {
                     return 0;
                 }
 
@@ -1518,13 +1536,10 @@
         private int runWaveform() {
             Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "runWaveform");
             try {
-                if (checkDoNotDisturb()) {
-                    return 0;
-                }
-
                 String description = "Shell command";
                 int repeat = -1;
                 ArrayList<Integer> amplitudesList = null;
+                CommonOptions commonOptions = new CommonOptions();
 
                 String opt;
                 while ((opt = getNextOption()) != null) {
@@ -1540,9 +1555,16 @@
                                 amplitudesList = new ArrayList<Integer>();
                             }
                             break;
+                        default:
+                            commonOptions.check(opt);
+                            break;
                     }
                 }
 
+                if (checkDoNotDisturb(commonOptions)) {
+                    return 0;
+                }
+
                 ArrayList<Long> timingsList = new ArrayList<Long>();
 
                 String arg;
@@ -1574,7 +1596,14 @@
         private int runPrebaked() {
             Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "runPrebaked");
             try {
-                if (checkDoNotDisturb()) {
+                CommonOptions commonOptions = new CommonOptions();
+
+                String opt;
+                while ((opt = getNextOption()) != null) {
+                    commonOptions.check(opt);
+                }
+
+                if (checkDoNotDisturb(commonOptions)) {
                     return 0;
                 }
 
@@ -1618,6 +1647,8 @@
                 pw.println("    (Do Not Disturb) mode.");
                 pw.println("  cancel");
                 pw.println("    Cancels any active vibration");
+                pw.println("Common Options:");
+                pw.println("  -f - Force. Ignore Do Not Disturb setting.");
                 pw.println("");
             }
         }
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index d95604e..2f1f91e 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -17,6 +17,7 @@
 package com.android.server.am;
 
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
+import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
 
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
@@ -218,7 +219,7 @@
                     if (DEBUG_FOREGROUND_SERVICE) {
                         Slog.i(TAG, "  Stopping fg for service " + r);
                     }
-                    setServiceForegroundInnerLocked(r, 0, null, 0);
+                    setServiceForegroundInnerLocked(r, 0, null, 0, 0);
                 }
             }
         }
@@ -914,13 +915,13 @@
     }
 
     public void setServiceForegroundLocked(ComponentName className, IBinder token,
-            int id, Notification notification, int flags) {
+            int id, Notification notification, int flags, int foregroundServiceType) {
         final int userId = UserHandle.getCallingUserId();
         final long origId = Binder.clearCallingIdentity();
         try {
             ServiceRecord r = findServiceLocked(className, token, userId);
             if (r != null) {
-                setServiceForegroundInnerLocked(r, id, notification, flags);
+                setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
             }
         } finally {
             Binder.restoreCallingIdentity(origId);
@@ -1211,7 +1212,7 @@
      * @param id Notification ID.  Zero === exit foreground state for the given service.
      */
     private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
-            Notification notification, int flags) {
+            Notification notification, int flags, int foregroundServiceType) {
         if (id != 0) {
             if (notification == null) {
                 throw new IllegalArgumentException("null notification");
@@ -1244,13 +1245,20 @@
                             android.Manifest.permission.FOREGROUND_SERVICE,
                             r.app.pid, r.appInfo.uid, "startForeground");
                 }
-                if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q) {
-                    if (r.serviceInfo.getForegroundServiceType()
-                            == ServiceInfo.FOREGROUND_SERVICE_TYPE_UNSPECIFIED) {
-                        // STOPSHIP(b/120611119): replace log message with SecurityException.
-                        Slog.w(TAG, "missing foregroundServiceType attribute in "
-                                + "service element of manifest file");
-                    }
+
+                int manifestType = r.serviceInfo.getForegroundServiceType();
+                // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
+                // consider it is the same as manifest foreground service type.
+                if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
+                    foregroundServiceType = manifestType;
+                }
+                // Check the passed in foreground service type flags is a subset of manifest
+                // foreground service type flags.
+                if ((foregroundServiceType & manifestType) != foregroundServiceType) {
+                    // STOPSHIP(b/120611119): replace log message with IllegalArgumentException.
+                    Slog.w(TAG, "foregroundServiceType must be a subset of "
+                            + "foregroundServiceType attribute in "
+                            + "service element of manifest file");
                 }
             }
             boolean alreadyStartedOp = false;
@@ -1307,6 +1315,7 @@
                     }
                     notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
                     r.foregroundNoti = notification;
+                    r.foregroundServiceType = foregroundServiceType;
                     if (!r.isForeground) {
                         final ServiceMap smap = getServiceMapLocked(r.userId);
                         if (smap != null) {
@@ -1443,7 +1452,7 @@
             ServiceRecord sr = proc.services.valueAt(i);
             if (sr.isForeground || sr.fgRequired) {
                 anyForeground = true;
-                fgServiceTypes |= sr.serviceInfo.mForegroundServiceType;
+                fgServiceTypes |= sr.foregroundServiceType;
                 break;
             }
         }
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 66e9eb3a..5538e49 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -121,6 +121,7 @@
 import static com.android.server.am.MemoryStatUtil.hasMemcg;
 import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
 import static com.android.server.am.MemoryStatUtil.readRssHighWaterMarkFromProcfs;
+import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
@@ -198,6 +199,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.ActivityInfo;
+import android.content.pm.ActivityPresentationInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
 import android.content.pm.IPackageDataObserver;
@@ -284,6 +286,7 @@
 import android.util.TimingsTraceLog;
 import android.util.proto.ProtoOutputStream;
 import android.util.proto.ProtoUtils;
+import android.view.Display;
 import android.view.Gravity;
 import android.view.IRecentsAnimationRunner;
 import android.view.LayoutInflater;
@@ -549,6 +552,11 @@
     // Whether we should use SCHED_FIFO for UI and RenderThreads.
     boolean mUseFifoUiScheduling = false;
 
+    // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
+    // For simplicity, since we statically declare the size of the array of BroadcastQueues,
+    // we still create this new offload queue, but never ever put anything on it.
+    boolean mEnableOffloadQueue;
+
     BroadcastQueue mFgBroadcastQueue;
     BroadcastQueue mBgBroadcastQueue;
     BroadcastQueue mOffloadBroadcastQueue;
@@ -2283,6 +2291,9 @@
         // by default, no "slow" policy in this queue
         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
 
+        mEnableOffloadQueue = SystemProperties.getBoolean(
+                "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
+
         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                 "foreground", foreConstants, false);
         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
@@ -3577,6 +3588,9 @@
         if (tracesFile == null) {
             return null;
         }
+        if (DEBUG_ANR) {
+            Slog.d(TAG, "Dumping to " + tracesFile.getAbsolutePath());
+        }
 
         dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
         return tracesFile;
@@ -4496,6 +4510,7 @@
         // next app record if we are emulating process with anonymous threads.
         ProcessRecord app;
         long startTime = SystemClock.uptimeMillis();
+        long bindApplicationTimeMillis;
         if (pid != MY_PID && pid >= 0) {
             synchronized (mPidsSelfLocked) {
                 app = mPidsSelfLocked.get(pid);
@@ -4733,6 +4748,7 @@
             }
 
             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
+            bindApplicationTimeMillis = SystemClock.elapsedRealtime();
             mAtmInternal.preBindApplication(app.getWindowProcessController());
             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
             if (app.isolatedEntryPoint != null) {
@@ -4836,7 +4852,7 @@
             try {
                 thread.scheduleCreateBackupAgent(backupTarget.appInfo,
                         compatibilityInfoForPackage(backupTarget.appInfo),
-                        backupTarget.backupMode);
+                        backupTarget.backupMode, backupTarget.userId);
             } catch (Exception e) {
                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
                 badApp = true;
@@ -4854,6 +4870,17 @@
             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
         }
 
+        StatsLog.write(
+                StatsLog.PROCESS_START_TIME,
+                app.info.uid,
+                app.pid,
+                app.info.packageName,
+                StatsLog.PROCESS_START_TIME__TYPE__COLD,
+                app.startTime,
+                (int) (bindApplicationTimeMillis - app.startTime),
+                (int) (SystemClock.elapsedRealtime() - app.startTime),
+                app.hostingType,
+                (app.hostingNameStr != null ? app.hostingNameStr : ""));
         return true;
     }
 
@@ -13530,9 +13557,10 @@
 
     @Override
     public void setServiceForeground(ComponentName className, IBinder token,
-            int id, Notification notification, int flags) {
+            int id, Notification notification, int flags, int foregroundServiceType) {
         synchronized(this) {
-            mServices.setServiceForegroundLocked(className, token, id, notification, flags);
+            mServices.setServiceForegroundLocked(className, token, id, notification, flags,
+                    foregroundServiceType);
         }
     }
 
@@ -13671,18 +13699,26 @@
     // Cause the target app to be launched if necessary and its backup agent
     // instantiated.  The backup agent will invoke backupAgentCreated() on the
     // activity manager to announce its creation.
-    public boolean bindBackupAgent(String packageName, int backupMode, int userId) {
+    public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId) {
         if (DEBUG_BACKUP) {
-            Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode="
-                    + backupMode + " userId=" + userId + " callingUid = " + Binder.getCallingUid()
+            Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
+                    + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
                     + " uid = " + Process.myUid());
         }
         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
 
+        // The instantiatedUserId is the user of the process the backup agent is started in. This is
+        // different from the targetUserId which is the user whose data is to be backed up or
+        // restored. This distinction is important for system-process packages that live in the
+        // system user's process but backup/restore data for non-system users.
+        // TODO (b/123688746): Handle all system-process packages with singleton check.
+        final int instantiatedUserId =
+                PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId;
+
         IPackageManager pm = AppGlobals.getPackageManager();
         ApplicationInfo app = null;
         try {
-            app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, userId);
+            app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
         } catch (RemoteException e) {
             // can't happen; package manager is process-local
         }
@@ -13706,7 +13742,7 @@
                         + app.packageName + ": " + e);
             }
 
-            BackupRecord r = new BackupRecord(app, backupMode);
+            BackupRecord r = new BackupRecord(app, backupMode, targetUserId);
             ComponentName hostingName =
                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL)
                             ? new ComponentName(app.packageName, app.backupAgentName)
@@ -13728,10 +13764,10 @@
                 proc.inFullBackup = true;
             }
             r.app = proc;
-            final BackupRecord backupTarget = mBackupTargets.get(userId);
+            final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
             newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1;
-            mBackupTargets.put(userId, r);
+            mBackupTargets.put(targetUserId, r);
 
             // Try not to kill the process during backup
             updateOomAdjLocked(proc, true);
@@ -13742,7 +13778,7 @@
                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
                 try {
                     proc.thread.scheduleCreateBackupAgent(app,
-                            compatibilityInfoForPackage(app), backupMode);
+                            compatibilityInfoForPackage(app), backupMode, targetUserId);
                 } catch (RemoteException e) {
                     // Will time out on the backup manager side
                 }
@@ -13782,16 +13818,18 @@
 
     // A backup agent has just come up
     @Override
-    public void backupAgentCreated(String agentPackageName, IBinder agent) {
-        final int callingUserId = UserHandle.getCallingUserId();
+    public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
+        // Resolve the target user id and enforce permissions.
+        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
+                userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
         if (DEBUG_BACKUP) {
             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
-                    + " callingUserId = " + callingUserId + " callingUid = "
-                    + Binder.getCallingUid() + " uid = " + Process.myUid());
+                    + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
+                    + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
         }
 
         synchronized(this) {
-            final BackupRecord backupTarget = mBackupTargets.get(callingUserId);
+            final BackupRecord backupTarget = mBackupTargets.get(userId);
             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
             if (!agentPackageName.equals(backupAppName)) {
                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
@@ -13803,7 +13841,7 @@
         try {
             IBackupManager bm = IBackupManager.Stub.asInterface(
                     ServiceManager.getService(Context.BACKUP_SERVICE));
-            bm.agentConnectedForUser(callingUserId, agentPackageName, agent);
+            bm.agentConnectedForUser(userId, agentPackageName, agent);
         } catch (RemoteException e) {
             // can't happen; the backup manager service is local
         } catch (Exception e) {
@@ -13856,7 +13894,7 @@
                 if (proc.thread != null) {
                     try {
                         proc.thread.scheduleDestroyBackupAgent(appInfo,
-                                compatibilityInfoForPackage(appInfo));
+                                compatibilityInfoForPackage(appInfo), userId);
                     } catch (Exception e) {
                         Slog.e(TAG, "Exception when unbinding backup agent:");
                         e.printStackTrace();
@@ -14090,7 +14128,8 @@
                     BroadcastQueue queue = broadcastQueueForIntent(intent);
                     BroadcastRecord r = new BroadcastRecord(queue, intent, null,
                             null, -1, -1, false, null, null, OP_NONE, null, receivers,
-                            null, 0, null, null, false, true, true, -1, false);
+                            null, 0, null, null, false, true, true, -1, false,
+                            false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
                     queue.enqueueParallelBroadcastLocked(r);
                     queue.scheduleBroadcastsLocked();
                 }
@@ -14475,6 +14514,8 @@
             }
         }
 
+        boolean timeoutExempt = false;
+
         if (action != null) {
             if (getBackgroundLaunchBroadcasts().contains(action)) {
                 if (DEBUG_BACKGROUND_CHECK) {
@@ -14700,6 +14741,9 @@
                     Log.w(TAG, "Broadcast " + action
                             + " no longer supported. It will not be delivered.");
                     return ActivityManager.BROADCAST_SUCCESS;
+                case Intent.ACTION_PRE_BOOT_COMPLETED:
+                    timeoutExempt = true;
+                    break;
             }
 
             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
@@ -14842,7 +14886,7 @@
                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
                     requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
                     resultCode, resultData, resultExtras, ordered, sticky, false, userId,
-                    allowBackgroundActivityStarts);
+                    allowBackgroundActivityStarts, timeoutExempt);
             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
             final boolean replaced = replacePending
                     && (queue.replaceParallelBroadcastLocked(r) != null);
@@ -14939,7 +14983,7 @@
                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
                     requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
                     resultData, resultExtras, ordered, sticky, false, userId,
-                    allowBackgroundActivityStarts);
+                    allowBackgroundActivityStarts, timeoutExempt);
 
             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
 
@@ -17628,6 +17672,19 @@
         }
 
         @Override
+        public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
+            int displayId = Display.INVALID_DISPLAY;
+            try {
+                displayId = mActivityTaskManager.getActivityDisplayId(token);
+            } catch (RemoteException e) {
+            }
+
+            return new ActivityPresentationInfo(mActivityTaskManager.getTaskForActivity(token,
+                    /*onlyRoot=*/ false), displayId,
+                    mActivityTaskManager.getActivityClassForToken(token));
+        }
+
+        @Override
         public void setBooting(boolean booting) {
             mBooting = booting;
         }
@@ -18389,6 +18446,6 @@
     }
 
     private boolean isOnOffloadQueue(int flags) {
-        return ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0);
+        return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
     }
 }
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 740c0da..4f6f9fd 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -1815,7 +1815,7 @@
 
     int runTrackAssociations(PrintWriter pw) {
         mInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
-                "registerUidObserver()");
+                "runTrackAssociations()");
         synchronized (mInternal) {
             if (!mInternal.mTrackingAssociations) {
                 mInternal.mTrackingAssociations = true;
@@ -1829,7 +1829,7 @@
 
     int runUntrackAssociations(PrintWriter pw) {
         mInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
-                "registerUidObserver()");
+                "runUntrackAssociations()");
         synchronized (mInternal) {
             if (mInternal.mTrackingAssociations) {
                 mInternal.mTrackingAssociations = false;
diff --git a/services/core/java/com/android/server/am/BackupRecord.java b/services/core/java/com/android/server/am/BackupRecord.java
index 40ad383..37b4be4 100644
--- a/services/core/java/com/android/server/am/BackupRecord.java
+++ b/services/core/java/com/android/server/am/BackupRecord.java
@@ -28,14 +28,16 @@
     
     String stringName;                     // cached toString() output
     final ApplicationInfo appInfo;         // information about BackupAgent's app
+    final int userId;                      // user for which backup is performed
     final int backupMode;                  // full backup / incremental / restore
     ProcessRecord app;                     // where this agent is running or null
 
     // ----- Implementation -----
 
-    BackupRecord(ApplicationInfo _appInfo, int _backupMode) {
+    BackupRecord(ApplicationInfo _appInfo, int _backupMode, int _userId) {
         appInfo = _appInfo;
         backupMode = _backupMode;
+        userId = _userId;
     }
 
     public String toString() {
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index 1fb11ba..a11ebfd 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -461,14 +461,21 @@
 
         // if this receiver was slow, impose deferral policy on the app.  This will kick in
         // when processNextBroadcastLocked() next finds this uid as a receiver identity.
-        if (mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
-            if (DEBUG_BROADCAST_DEFERRAL) {
-                Slog.i(TAG, "Broadcast receiver was slow: " + receiver + " br=" + r);
+        if (!r.timeoutExempt) {
+            if (mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
+                if (DEBUG_BROADCAST_DEFERRAL) {
+                    Slog.i(TAG, "Broadcast receiver was slow: " + receiver + " br=" + r);
+                }
+                if (r.curApp != null) {
+                    mDispatcher.startDeferring(r.curApp.uid);
+                } else {
+                    Slog.d(TAG, "finish receiver curApp is null? " + r);
+                }
             }
-            if (r.curApp != null) {
-                mDispatcher.startDeferring(r.curApp.uid);
-            } else {
-                Slog.d(TAG, "finish receiver curApp is null? " + r);
+        } else {
+            if (DEBUG_BROADCAST_DEFERRAL) {
+                Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
+                        + " is exempt from deferral policy");
             }
         }
 
@@ -1008,12 +1015,11 @@
             // detection, we catch "hung" broadcasts here, discard them,
             // and continue to make progress.
             //
-            // This is only done if the system is ready so that PRE_BOOT_COMPLETED
-            // receivers don't get executed with timeouts. They're intended for
-            // one time heavy lifting after system upgrades and can take
-            // significant amounts of time.
+            // This is only done if the system is ready so that early-stage receivers
+            // don't get executed with timeouts; and of course other timeout-
+            // exempt broadcasts are ignored.
             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
-            if (mService.mProcessesReady && r.dispatchTime > 0) {
+            if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
                 if ((numReceivers > 0) &&
                         (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
                     Slog.w(TAG, "Hung broadcast ["
@@ -1619,9 +1625,17 @@
         BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
         if (fromMsg) {
             if (!mService.mProcessesReady) {
-                // Only process broadcast timeouts if the system is ready. That way
-                // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
-                // to do heavy lifting for system up.
+                // Only process broadcast timeouts if the system is ready; some early
+                // broadcasts do heavy work setting up system facilities
+                return;
+            }
+
+            // If the broadcast is generally exempt from timeout tracking, we're done
+            if (r.timeoutExempt) {
+                if (DEBUG_BROADCAST) {
+                    Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
+                            + r.intent.getAction());
+                }
                 return;
             }
 
diff --git a/services/core/java/com/android/server/am/BroadcastRecord.java b/services/core/java/com/android/server/am/BroadcastRecord.java
index d9e03f8..fa9b79d 100644
--- a/services/core/java/com/android/server/am/BroadcastRecord.java
+++ b/services/core/java/com/android/server/am/BroadcastRecord.java
@@ -74,6 +74,7 @@
     long dispatchClockTime; // the clock time the dispatch started
     long receiverTime;      // when current receiver started for timeouts.
     long finishTime;        // when we finished the broadcast.
+    boolean timeoutExempt;  // true if this broadcast is not subject to receiver timeouts
     int resultCode;         // current result code value.
     String resultData;      // current result data value.
     Bundle resultExtras;    // current result extra data values.
@@ -236,7 +237,7 @@
             String[] _requiredPermissions, int _appOp, BroadcastOptions _options, List _receivers,
             IIntentReceiver _resultTo, int _resultCode, String _resultData, Bundle _resultExtras,
             boolean _serialized, boolean _sticky, boolean _initialSticky, int _userId,
-            boolean _allowBackgroundActivityStarts) {
+            boolean _allowBackgroundActivityStarts, boolean _timeoutExempt) {
         if (_intent == null) {
             throw new NullPointerException("Can't construct with a null intent");
         }
@@ -266,6 +267,7 @@
         nextReceiver = 0;
         state = IDLE;
         allowBackgroundActivityStarts = _allowBackgroundActivityStarts;
+        timeoutExempt = _timeoutExempt;
     }
 
     /**
@@ -310,6 +312,7 @@
         manifestSkipCount = from.manifestSkipCount;
         queue = from.queue;
         allowBackgroundActivityStarts = from.allowBackgroundActivityStarts;
+        timeoutExempt = from.timeoutExempt;
     }
 
     /**
@@ -345,7 +348,7 @@
                 callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
                 requiredPermissions, appOp, options, splitReceivers, resultTo, resultCode,
                 resultData, resultExtras, ordered, sticky, initialSticky, userId,
-                allowBackgroundActivityStarts);
+                allowBackgroundActivityStarts, timeoutExempt);
 
         return split;
     }
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 49c4bc4..f90c0ca 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -58,7 +58,6 @@
 import android.graphics.Point;
 import android.net.LocalSocket;
 import android.net.LocalSocketAddress;
-import android.net.Uri;
 import android.os.AppZygote;
 import android.os.Binder;
 import android.os.Build;
@@ -1481,6 +1480,9 @@
                     mService.mSafeMode == true) {
                 runtimeFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
             }
+            if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_PROFILEABLE_BY_SHELL) != 0) {
+                runtimeFlags |= Zygote.PROFILE_FROM_SHELL;
+            }
             if ("1".equals(SystemProperties.get("debug.checkjni"))) {
                 runtimeFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
             }
@@ -1507,7 +1509,7 @@
                 mService.mNativeDebuggingApp = null;
             }
 
-            if (app.info.isCodeIntegrityPreferred()
+            if (app.info.isEmbeddedDexUsed()
                     || (app.info.isPrivilegedApp()
                         && DexManager.isPackageSelectedToRunOob(app.pkgList.mPkgList.keySet()))) {
                 runtimeFlags |= Zygote.ONLY_USE_SYSTEM_OAT_FILES;
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 6161f7d..5dccaf1 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -1172,9 +1172,9 @@
 
     void setActiveInstrumentation(ActiveInstrumentation instr) {
         mInstr = instr;
-        mWindowProcessController.setInstrumenting(instr != null);
-        mWindowProcessController.setInstrumentingWithBackgroundActivityStartPrivileges(instr != null
-                && instr.mHasBackgroundActivityStartsPermission);
+        boolean isInstrumenting = instr != null;
+        mWindowProcessController.setInstrumenting(isInstrumenting,
+                isInstrumenting && instr.mHasBackgroundActivityStartsPermission);
     }
 
     ActiveInstrumentation getActiveInstrumentation() {
diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java
index da5ce1c..abc1066a 100644
--- a/services/core/java/com/android/server/am/ServiceRecord.java
+++ b/services/core/java/com/android/server/am/ServiceRecord.java
@@ -16,10 +16,8 @@
 
 package com.android.server.am;
 
-import com.android.internal.app.procstats.ServiceState;
-import com.android.internal.os.BatteryStatsImpl;
-import com.android.server.LocalServices;
-import com.android.server.notification.NotificationManagerInternal;
+import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
+import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.app.INotificationManager;
 import android.app.Notification;
@@ -44,6 +42,11 @@
 import android.util.TimeUtils;
 import android.util.proto.ProtoOutputStream;
 import android.util.proto.ProtoUtils;
+
+import com.android.internal.app.procstats.ServiceState;
+import com.android.internal.os.BatteryStatsImpl;
+import com.android.server.LocalServices;
+import com.android.server.notification.NotificationManagerInternal;
 import com.android.server.uri.NeededUriGrants;
 import com.android.server.uri.UriPermissionOwner;
 
@@ -52,9 +55,6 @@
 import java.util.List;
 import java.util.Objects;
 
-import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
-import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
-
 /**
  * A running application service.
  */
@@ -103,6 +103,7 @@
     boolean isForeground;   // is service currently in foreground mode?
     int foregroundId;       // Notification ID of last foreground req.
     Notification foregroundNoti; // Notification record of foreground state.
+    int foregroundServiceType; // foreground service types.
     long lastActivity;      // last time there was some activity on the service.
     long startingBgTimeout;  // time at which we scheduled this for a delayed start.
     boolean startRequested; // someone explicitly called start?
@@ -722,7 +723,7 @@
                         // If it gave us a garbage notification, it doesn't
                         // get to be foreground.
                         ams.setServiceForeground(instanceName, ServiceRecord.this,
-                                0, null, 0);
+                                0, null, 0, 0);
                         ams.crashApplication(appUid, appPid, localPackageName, -1,
                                 "Bad notification for startForeground: " + e);
                     }
diff --git a/services/core/java/com/android/server/attention/AttentionManagerService.java b/services/core/java/com/android/server/attention/AttentionManagerService.java
index 2061b26..9a1d7bf 100644
--- a/services/core/java/com/android/server/attention/AttentionManagerService.java
+++ b/services/core/java/com/android/server/attention/AttentionManagerService.java
@@ -108,24 +108,23 @@
                 AttentionService.ATTENTION_FAILURE_UNKNOWN);
     }
 
-    @Override
-    public void onBootPhase(int phase) {
-        super.onBootPhase(phase);
-        if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
+    /** Resolves and sets up the attention service if it had not been done yet. */
+    private boolean isServiceAvailable() {
+        if (mComponentName == null) {
             mComponentName = resolveAttentionService(mContext);
-            if (isAttentionServiceSupported()) {
-                // If the service is supported we want to keep receiving the screen off events.
+            if (mComponentName != null) {
                 mContext.registerReceiver(new ScreenStateReceiver(),
                         new IntentFilter(Intent.ACTION_SCREEN_OFF));
             }
         }
+        return mComponentName != null;
     }
 
     /**
      * Returns {@code true} if attention service is supported on this device.
      */
     public boolean isAttentionServiceSupported() {
-        return mComponentName != null && isServiceEnabled();
+        return isServiceEnabled() && isServiceAvailable();
     }
 
     private boolean isServiceEnabled() {
@@ -258,7 +257,7 @@
     private UserState getOrCreateUserStateLocked(int userId) {
         UserState result = mUserStates.get(userId);
         if (result == null) {
-            result = new UserState(userId, mContext, mLock);
+            result = new UserState(userId, mContext, mLock, mComponentName);
             mUserStates.put(userId, result);
         }
         return result;
@@ -397,6 +396,7 @@
     }
 
     private static final class UserState {
+        final ComponentName mComponentName;
         final AttentionServiceConnection mConnection = new AttentionServiceConnection();
 
         @GuardedBy("mLock")
@@ -416,10 +416,11 @@
         final Context mContext;
         final Object mLock;
 
-        private UserState(int userId, Context context, Object lock) {
+        private UserState(int userId, Context context, Object lock, ComponentName componentName) {
             mUserId = userId;
             mContext = Preconditions.checkNotNull(context);
             mLock = Preconditions.checkNotNull(lock);
+            mComponentName = Preconditions.checkNotNull(componentName);
         }
 
 
@@ -443,15 +444,9 @@
             final long identity = Binder.clearCallingIdentity();
 
             try {
-                final ComponentName componentName =
-                        resolveAttentionService(mContext);
-                if (componentName == null) {
-                    // Might happen if the storage is encrypted and the user is not unlocked
-                    return false;
-                }
                 final Intent mServiceIntent = new Intent(
                         AttentionService.SERVICE_INTERFACE).setComponent(
-                        componentName);
+                        mComponentName);
                 willBind = mContext.bindServiceAsUser(mServiceIntent, mConnection,
                         Context.BIND_AUTO_CREATE, UserHandle.CURRENT);
                 mBinding = willBind;
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 1723163..9457fe3 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -908,6 +908,9 @@
         // Restore mono mode
         updateMasterMono(mContentResolver);
 
+        // Restore audio balance
+        updateMasterBalance(mContentResolver);
+
         // Restore ringer mode
         setRingerModeInt(getRingerModeInternal(), false);
 
@@ -1196,6 +1199,17 @@
         AudioSystem.setMasterMono(masterMono);
     }
 
+    private void updateMasterBalance(ContentResolver cr) {
+        final float masterBalance = System.getFloatForUser(
+                cr, System.MASTER_BALANCE, 0.f /* default */, UserHandle.USER_CURRENT);
+        if (DEBUG_VOL) {
+            Log.d(TAG, String.format("Master balance %f", masterBalance));
+        }
+        if (AudioSystem.setMasterBalance(masterBalance) != 0) {
+            Log.e(TAG, String.format("setMasterBalance failed for %f", masterBalance));
+        }
+    }
+
     private void sendEncodedSurroundMode(ContentResolver cr, String eventSource)
     {
         final int encodedSurroundMode = Settings.Global.getInt(
@@ -1372,6 +1386,8 @@
 
         updateMasterMono(cr);
 
+        updateMasterBalance(cr);
+
         // Each stream will read its own persisted settings
 
         // Broadcast the sticky intents
@@ -4948,6 +4964,8 @@
                 Settings.Global.DOCK_AUDIO_MEDIA_ENABLED), false, this);
             mContentResolver.registerContentObserver(Settings.System.getUriFor(
                     Settings.System.MASTER_MONO), false, this);
+            mContentResolver.registerContentObserver(Settings.System.getUriFor(
+                    Settings.System.MASTER_BALANCE), false, this);
 
             mEncodedSurroundMode = Settings.Global.getInt(
                     mContentResolver, Settings.Global.ENCODED_SURROUND_OUTPUT,
@@ -4981,6 +4999,7 @@
                 }
                 readDockAudioSettings(mContentResolver);
                 updateMasterMono(mContentResolver);
+                updateMasterBalance(mContentResolver);
                 updateEncodedSurroundOutput();
                 sendEnabledSurroundFormats(mContentResolver, mSurroundModeChanged);
                 updateAssistantUId(false);
diff --git a/services/core/java/com/android/server/biometrics/AuthenticationClient.java b/services/core/java/com/android/server/biometrics/AuthenticationClient.java
index eaa7a83..bd4acdb 100644
--- a/services/core/java/com/android/server/biometrics/AuthenticationClient.java
+++ b/services/core/java/com/android/server/biometrics/AuthenticationClient.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.security.KeyStore;
@@ -71,6 +72,11 @@
         stop(false /* initiatedByClient */);
     }
 
+    @Override
+    protected int statsAction() {
+        return BiometricsProtoEnums.ACTION_AUTHENTICATE;
+    }
+
     public boolean isBiometricPrompt() {
         return getCookie() != 0;
     }
@@ -80,8 +86,16 @@
     }
 
     @Override
+    protected boolean isCryptoOperation() {
+        return mOpId != 0;
+    }
+
+    @Override
     public boolean onAuthenticated(BiometricAuthenticator.Identifier identifier,
             boolean authenticated, ArrayList<Byte> token) {
+        super.logOnAuthenticated(authenticated, mRequireConfirmation, getTargetUserId(),
+                isBiometricPrompt());
+
         final BiometricServiceBase.ServiceListener listener = getListener();
 
         mMetricsLogger.action(mMetrics.actionBiometricAuth(), authenticated);
@@ -142,10 +156,7 @@
                     final int errorCode = lockoutMode == LOCKOUT_TIMED
                             ? BiometricConstants.BIOMETRIC_ERROR_LOCKOUT
                             : BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
-                    if (listener != null) {
-                        listener.onError(getHalDeviceId(), errorCode, 0 /* vendorCode */,
-                                getCookie());
-                    }
+                    onError(getHalDeviceId(), errorCode, 0 /* vendorCode */);
                 } else {
                     // Don't send onAuthenticationFailed if we're in lockout, it causes a
                     // janky UI on Keyguard/BiometricPrompt since "authentication failed"
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 15d66e6..b50b800 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -41,6 +41,7 @@
 import android.hardware.biometrics.BiometricConstants;
 import android.hardware.biometrics.BiometricPrompt;
 import android.hardware.biometrics.BiometricSourceType;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
 import android.hardware.biometrics.IBiometricService;
 import android.hardware.biometrics.IBiometricServiceReceiver;
@@ -64,6 +65,7 @@
 import android.text.TextUtils;
 import android.util.Pair;
 import android.util.Slog;
+import android.util.StatsLog;
 
 import com.android.internal.R;
 import com.android.internal.statusbar.IStatusBarService;
@@ -309,6 +311,7 @@
             // Continue authentication with the same modality/modalities after "try again" is
             // pressed
             final int mModality;
+            final boolean mRequireConfirmation;
 
             // The current state, which can be either idle, called, or started
             private int mState = STATE_AUTH_IDLE;
@@ -316,10 +319,13 @@
             // the authentication.
             byte[] mTokenEscrow;
 
+            // Timestamp when hardware authentication occurred
+            private long mAuthenticatedTimeMs;
+
             AuthSession(HashMap<Integer, Integer> modalities, IBinder token, long sessionId,
                     int userId, IBiometricServiceReceiver receiver, String opPackageName,
                     Bundle bundle, int callingUid, int callingPid, int callingUserId,
-                    int modality) {
+                    int modality, boolean requireConfirmation) {
                 mModalitiesWaiting = modalities;
                 mToken = token;
                 mSessionId = sessionId;
@@ -331,6 +337,11 @@
                 mCallingPid = callingPid;
                 mCallingUserId = callingUserId;
                 mModality = modality;
+                mRequireConfirmation = requireConfirmation;
+            }
+
+            boolean isCrypto() {
+                return mSessionId != 0;
             }
 
             boolean containsCookie(int cookie) {
@@ -412,6 +423,7 @@
                         mCurrentAuthSession.mState = STATE_AUTH_IDLE;
                         mCurrentAuthSession = null;
                     } else {
+                        mCurrentAuthSession.mAuthenticatedTimeMs = System.currentTimeMillis();
                         // Store the auth token and submit it to keystore after the confirmation
                         // button has been pressed.
                         mCurrentAuthSession.mTokenEscrow = token;
@@ -557,6 +569,8 @@
                     return;
                 }
 
+                logDialogDismissed(reason);
+
                 if (reason != BiometricPrompt.DISMISSED_REASON_POSITIVE) {
                     // Positive button is used by passive modalities as a "confirm" button,
                     // do not send to client
@@ -599,6 +613,77 @@
                             mCurrentAuthSession.mModality);
                 });
             }
+
+            private void logDialogDismissed(int reason) {
+                if (reason == BiometricPrompt.DISMISSED_REASON_POSITIVE) {
+                    // Explicit auth, authentication confirmed.
+                    // Latency in this case is authenticated -> confirmed. <Biometric>Service
+                    // should have the first half (first acquired -> authenticated).
+                    final long latency = System.currentTimeMillis()
+                            - mCurrentAuthSession.mAuthenticatedTimeMs;
+
+                    if (LoggableMonitor.DEBUG) {
+                        Slog.v(LoggableMonitor.TAG, "Confirmed! Modality: " + statsModality()
+                                + ", User: " + mCurrentAuthSession.mUserId
+                                + ", IsCrypto: " + mCurrentAuthSession.isCrypto()
+                                + ", Client: " + BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT
+                                + ", RequireConfirmation: "
+                                    + mCurrentAuthSession.mRequireConfirmation
+                                + ", State: " + StatsLog.BIOMETRIC_AUTHENTICATED__STATE__CONFIRMED
+                                + ", Latency: " + latency);
+                    }
+
+                    StatsLog.write(StatsLog.BIOMETRIC_AUTHENTICATED,
+                            statsModality(),
+                            mCurrentAuthSession.mUserId,
+                            mCurrentAuthSession.isCrypto(),
+                            BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT,
+                            mCurrentAuthSession.mRequireConfirmation,
+                            StatsLog.BIOMETRIC_AUTHENTICATED__STATE__CONFIRMED,
+                            latency);
+                } else {
+                    int error = reason == BiometricPrompt.DISMISSED_REASON_NEGATIVE
+                            ? BiometricConstants.BIOMETRIC_ERROR_NEGATIVE_BUTTON
+                            : reason == BiometricPrompt.DISMISSED_REASON_USER_CANCEL
+                                    ? BiometricConstants.BIOMETRIC_ERROR_USER_CANCELED
+                                    : 0;
+                    if (LoggableMonitor.DEBUG) {
+                        Slog.v(LoggableMonitor.TAG, "Dismissed! Modality: " + statsModality()
+                                + ", User: " + mCurrentAuthSession.mUserId
+                                + ", IsCrypto: " + mCurrentAuthSession.isCrypto()
+                                + ", Action: " + BiometricsProtoEnums.ACTION_AUTHENTICATE
+                                + ", Client: " + BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT
+                                + ", Error: " + error);
+                    }
+                    // Auth canceled
+                    StatsLog.write(StatsLog.BIOMETRIC_ERROR_OCCURRED,
+                            statsModality(),
+                            mCurrentAuthSession.mUserId,
+                            mCurrentAuthSession.isCrypto(),
+                            BiometricsProtoEnums.ACTION_AUTHENTICATE,
+                            BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT,
+                            error,
+                            0 /* vendorCode */);
+                }
+            }
+
+            private int statsModality() {
+                int modality = 0;
+                if (mCurrentAuthSession == null) {
+                    return BiometricsProtoEnums.MODALITY_UNKNOWN;
+                }
+                if ((mCurrentAuthSession.mModality & BiometricAuthenticator.TYPE_FINGERPRINT)
+                        != 0) {
+                    modality |= BiometricsProtoEnums.MODALITY_FINGERPRINT;
+                }
+                if ((mCurrentAuthSession.mModality & BiometricAuthenticator.TYPE_IRIS) != 0) {
+                    modality |= BiometricsProtoEnums.MODALITY_IRIS;
+                }
+                if ((mCurrentAuthSession.mModality & BiometricAuthenticator.TYPE_FACE) != 0) {
+                    modality |= BiometricsProtoEnums.MODALITY_FACE;
+                }
+                return modality;
+            }
         };
 
         @Override // Binder call
@@ -719,14 +804,17 @@
             // result back to the client.
             // TODO(b/123378871): Remove when moved.
             if (bundle.getBoolean(BiometricPrompt.KEY_ENABLE_FALLBACK)) {
-                mConfirmDeviceCredentialReceiver = receiver;
-                final KeyguardManager kgm = getContext().getSystemService(KeyguardManager.class);
-                // Use this so we don't need to duplicate logic..
-                final Intent intent = kgm.createConfirmDeviceCredentialIntent(null /* title */,
-                        null /* description */);
-                // Then give it the bundle to do magic behavior..
-                intent.putExtra(KeyguardManager.EXTRA_BIOMETRIC_PROMPT_BUNDLE, bundle);
-                getContext().startActivityAsUser(intent, UserHandle.CURRENT);
+                mHandler.post(() -> {
+                    mConfirmDeviceCredentialReceiver = receiver;
+                    final KeyguardManager kgm = getContext().getSystemService(
+                            KeyguardManager.class);
+                    // Use this so we don't need to duplicate logic..
+                    final Intent intent = kgm.createConfirmDeviceCredentialIntent(null /* title */,
+                            null /* description */);
+                    // Then give it the bundle to do magic behavior..
+                    intent.putExtra(KeyguardManager.EXTRA_BIOMETRIC_PROMPT_BUNDLE, bundle);
+                    getContext().startActivityAsUser(intent, UserHandle.CURRENT);
+                });
                 return;
             }
 
@@ -815,7 +903,11 @@
             try {
                 boolean requireConfirmation = bundle.getBoolean(
                         BiometricPrompt.KEY_REQUIRE_CONFIRMATION, true /* default */);
-
+                if ((modality & TYPE_FACE) != 0) {
+                    // Check if the user has forced confirmation to be required in Settings.
+                    requireConfirmation = requireConfirmation
+                            || mSettingObserver.getFaceAlwaysRequireConfirmation();
+                }
                 // Generate random cookies to pass to the services that should prepare to start
                 // authenticating. Store the cookie here and wait for all services to "ack"
                 // with the cookie. Once all cookies are received, we can show the prompt
@@ -827,7 +919,7 @@
                 authenticators.put(modality, cookie);
                 mPendingAuthSession = new AuthSession(authenticators, token, sessionId, userId,
                         receiver, opPackageName, bundle, callingUid, callingPid, callingUserId,
-                        modality);
+                        modality, requireConfirmation);
                 mPendingAuthSession.mState = STATE_AUTH_CALLED;
                 // No polymorphism :(
                 if ((modality & TYPE_FINGERPRINT) != 0) {
@@ -839,9 +931,6 @@
                     Slog.w(TAG, "Iris unsupported");
                 }
                 if ((modality & TYPE_FACE) != 0) {
-                    // Check if the user has forced confirmation to be required in Settings.
-                    requireConfirmation = requireConfirmation
-                            || mSettingObserver.getFaceAlwaysRequireConfirmation();
                     mFaceService.prepareForAuthentication(requireConfirmation,
                             token, sessionId, userId, mInternalReceiver, opPackageName,
                             cookie, callingUid, callingPid, callingUserId);
diff --git a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
index 2791165..b65535a 100644
--- a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
+++ b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
@@ -35,6 +35,7 @@
 import android.content.pm.UserInfo;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.hardware.biometrics.IBiometricService;
 import android.hardware.biometrics.IBiometricServiceLockoutResetCallback;
 import android.hardware.biometrics.IBiometricServiceReceiverInternal;
@@ -55,6 +56,7 @@
 import android.util.Slog;
 import android.util.SparseBooleanArray;
 import android.util.SparseIntArray;
+import android.util.StatsLog;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
@@ -220,8 +222,16 @@
      */
     protected void notifyClientActiveCallbacks(boolean isActive) {}
 
+    protected abstract int statsModality();
+
     protected abstract class AuthenticationClientImpl extends AuthenticationClient {
 
+        // Used to check if the public API that was invoked was from FingerprintManager. Only
+        // to be overridden by FingerprintService.
+        protected boolean isFingerprint() {
+            return false;
+        }
+
         public AuthenticationClientImpl(Context context, DaemonWrapper daemon, long halDeviceId,
                 IBinder token, ServiceListener listener, int targetUserId, int groupId, long opId,
                 boolean restricted, String owner, int cookie, boolean requireConfirmation) {
@@ -230,6 +240,19 @@
         }
 
         @Override
+        protected int statsClient() {
+            if (isKeyguard(getOwnerString())) {
+                return BiometricsProtoEnums.CLIENT_KEYGUARD;
+            } else if (isBiometricPrompt()) {
+                return BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT;
+            } else if (isFingerprint()) {
+                return BiometricsProtoEnums.CLIENT_FINGERPRINT_MANAGER;
+            } else {
+                return BiometricsProtoEnums.CLIENT_UNKNOWN;
+            }
+        }
+
+        @Override
         public void onStart() {
             try {
                 mActivityTaskManager.registerTaskStackListener(mTaskStackListener);
@@ -296,7 +319,7 @@
         }
     }
 
-    protected class RemovalClientImpl extends RemovalClient {
+    protected abstract class RemovalClientImpl extends RemovalClient {
         private boolean mShouldNotify;
 
         public RemovalClientImpl(Context context, DaemonWrapper daemon, long halDeviceId,
@@ -318,7 +341,7 @@
         }
     }
 
-    protected class EnumerateClientImpl extends EnumerateClient {
+    protected abstract class EnumerateClientImpl extends EnumerateClient {
 
         public EnumerateClientImpl(Context context, DaemonWrapper daemon, long halDeviceId,
                 IBinder token, ServiceListener listener, int groupId, int userId,
@@ -600,6 +623,8 @@
         mHALDeathCount++;
         handleError(getHalDeviceId(), BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE,
                 0 /*vendorCode */);
+
+        StatsLog.write(StatsLog.BIOMETRIC_HAL_DEATH_REPORTED, statsModality());
     }
 
     protected ClientMonitor getCurrentClient() {
@@ -653,7 +678,6 @@
             } else {
                 updateActiveGroup(mCurrentUserId, null);
             }
-
         }
     }
 
diff --git a/services/core/java/com/android/server/biometrics/ClientMonitor.java b/services/core/java/com/android/server/biometrics/ClientMonitor.java
index d19aff6..e80b39b 100644
--- a/services/core/java/com/android/server/biometrics/ClientMonitor.java
+++ b/services/core/java/com/android/server/biometrics/ClientMonitor.java
@@ -36,7 +36,7 @@
  * the current client.  Subclasses are responsible for coordinating the interaction with
  * the biometric's HAL for the specific action (e.g. authenticate, enroll, enumerate, etc.).
  */
-public abstract class ClientMonitor implements IBinder.DeathRecipient {
+public abstract class ClientMonitor extends LoggableMonitor implements IBinder.DeathRecipient {
     protected static final int ERROR_ESRCH = 3; // Likely HAL is dead. See errno.h.
     protected static final boolean DEBUG = BiometricServiceBase.DEBUG;
     private static final AudioAttributes FINGERPRINT_SONFICATION_ATTRIBUTES =
@@ -157,6 +157,7 @@
      * @return true if client should be removed
      */
     public boolean onAcquired(int acquiredInfo, int vendorCode) {
+        super.logOnAcquired(acquiredInfo, vendorCode, getTargetUserId());
         try {
             if (mListener != null) {
                 mListener.onAcquired(getHalDeviceId(), acquiredInfo, vendorCode);
@@ -180,6 +181,7 @@
      * @return true if client should be removed
      */
     public boolean onError(long deviceId, int error, int vendorCode) {
+        super.logOnError(error, vendorCode, getTargetUserId());
         try {
             if (mListener != null) {
                 mListener.onError(deviceId, error, vendorCode, getCookie());
diff --git a/services/core/java/com/android/server/biometrics/EnrollClient.java b/services/core/java/com/android/server/biometrics/EnrollClient.java
index 3ff94bc..882a929 100644
--- a/services/core/java/com/android/server/biometrics/EnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/EnrollClient.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.util.Slog;
@@ -51,11 +52,17 @@
     }
 
     @Override
+    protected int statsAction() {
+        return BiometricsProtoEnums.ACTION_ENROLL;
+    }
+
+    @Override
     public boolean onEnrollResult(BiometricAuthenticator.Identifier identifier,
             int remaining) {
         if (remaining == 0) {
             mBiometricUtils.addBiometricForUser(getContext(), getTargetUserId(), identifier);
         }
+        notifyUserActivity();
         return sendEnrollResult(identifier, remaining);
     }
 
diff --git a/services/core/java/com/android/server/biometrics/EnumerateClient.java b/services/core/java/com/android/server/biometrics/EnumerateClient.java
index df6220c..0f57f48 100644
--- a/services/core/java/com/android/server/biometrics/EnumerateClient.java
+++ b/services/core/java/com/android/server/biometrics/EnumerateClient.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.util.Slog;
@@ -38,6 +39,11 @@
     }
 
     @Override
+    protected int statsAction() {
+        return BiometricsProtoEnums.ACTION_ENUMERATE;
+    }
+
+    @Override
     public int start() {
         // The biometric template ids will be removed when we get confirmation from the HAL
         try {
diff --git a/services/core/java/com/android/server/biometrics/LoggableMonitor.java b/services/core/java/com/android/server/biometrics/LoggableMonitor.java
new file mode 100644
index 0000000..91c924d
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/LoggableMonitor.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.biometrics;
+
+import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
+import android.hardware.face.FaceManager;
+import android.util.Slog;
+import android.util.StatsLog;
+
+/**
+ * Abstract class that adds logging functionality to the ClientMonitor classes.
+ */
+public abstract class LoggableMonitor {
+
+    public static final String TAG = "BiometricStats";
+    public static final boolean DEBUG = true;
+
+    private long mFirstAcquireTimeMs;
+
+    /**
+     * Only valid for AuthenticationClient.
+     * @return true if the client is authenticating for a crypto operation.
+     */
+    protected boolean isCryptoOperation() {
+        return false;
+    }
+
+    /**
+     * @return One of {@link BiometricsProtoEnums} MODALITY_* constants.
+     */
+    protected abstract int statsModality();
+
+    /**
+     * Action == enroll, authenticate, remove, enumerate.
+     * @return One of {@link BiometricsProtoEnums} ACTION_* constants.
+     */
+    protected abstract int statsAction();
+
+    /**
+     * Only matters for AuthenticationClient. Should only be overridden in
+     * {@link BiometricServiceBase}, which determines if a client is for BiometricPrompt, Keyguard,
+     * etc.
+     * @return one of {@link BiometricsProtoEnums} CLIENT_* constants.
+     */
+    protected int statsClient() {
+        return BiometricsProtoEnums.CLIENT_UNKNOWN;
+    }
+
+    protected final void logOnAcquired(int acquiredInfo, int vendorCode, int targetUserId) {
+        if (statsModality() == BiometricsProtoEnums.MODALITY_FACE) {
+            if (acquiredInfo == FaceManager.FACE_ACQUIRED_START) {
+                mFirstAcquireTimeMs = System.currentTimeMillis();
+            }
+        } else if (acquiredInfo == BiometricConstants.BIOMETRIC_ACQUIRED_GOOD) {
+            if (mFirstAcquireTimeMs == 0) {
+                mFirstAcquireTimeMs = System.currentTimeMillis();
+            }
+        }
+        if (DEBUG) {
+            Slog.v(TAG, "Acquired! Modality: " + statsModality()
+                    + ", User: " + targetUserId
+                    + ", IsCrypto: " + isCryptoOperation()
+                    + ", Action: " + statsAction()
+                    + ", Client: " + statsClient()
+                    + ", AcquiredInfo: " + acquiredInfo
+                    + ", VendorCode: " + vendorCode);
+        }
+        StatsLog.write(StatsLog.BIOMETRIC_ACQUIRED,
+                statsModality(),
+                targetUserId,
+                isCryptoOperation(),
+                statsAction(),
+                statsClient(),
+                acquiredInfo,
+                0 /* vendorCode */); // Don't log vendorCode for now
+    }
+
+    protected final void logOnError(int error, int vendorCode, int targetUserId) {
+        if (DEBUG) {
+            Slog.v(TAG, "Error! Modality: " + statsModality()
+                    + ", User: " + targetUserId
+                    + ", IsCrypto: " + isCryptoOperation()
+                    + ", Action: " + statsAction()
+                    + ", Client: " + statsClient()
+                    + ", Error: " + error
+                    + ", VendorCode: " + vendorCode);
+        }
+        StatsLog.write(StatsLog.BIOMETRIC_ERROR_OCCURRED,
+                statsModality(),
+                targetUserId,
+                isCryptoOperation(),
+                statsAction(),
+                statsClient(),
+                error,
+                vendorCode);
+    }
+
+    protected final void logOnAuthenticated(boolean authenticated, boolean requireConfirmation,
+            int targetUserId, boolean isBiometricPrompt) {
+        int authState = StatsLog.BIOMETRIC_AUTHENTICATED__STATE__UNKNOWN;
+        if (!authenticated) {
+            authState = StatsLog.BIOMETRIC_AUTHENTICATED__STATE__REJECTED;
+        } else {
+            // Authenticated
+            if (isBiometricPrompt && requireConfirmation) {
+                authState = StatsLog.BIOMETRIC_AUTHENTICATED__STATE__PENDING_CONFIRMATION;
+            } else {
+                authState = StatsLog.BIOMETRIC_AUTHENTICATED__STATE__CONFIRMED;
+            }
+        }
+
+        // Only valid if we have a first acquired time, otherwise set to -1
+        final long latency = mFirstAcquireTimeMs != 0
+                ? (System.currentTimeMillis() - mFirstAcquireTimeMs)
+                : -1;
+
+        if (DEBUG) {
+            Slog.v(TAG, "Authenticated! Modality: " + statsModality()
+                    + ", User: " + targetUserId
+                    + ", IsCrypto: " + isCryptoOperation()
+                    + ", Client: " + statsClient()
+                    + ", RequireConfirmation: " + requireConfirmation
+                    + ", State: " + authState
+                    + ", Latency: " + latency);
+        }
+
+        StatsLog.write(StatsLog.BIOMETRIC_AUTHENTICATED,
+                statsModality(),
+                targetUserId,
+                isCryptoOperation(),
+                statsClient(),
+                requireConfirmation,
+                authState,
+                latency);
+    }
+}
diff --git a/services/core/java/com/android/server/biometrics/RemovalClient.java b/services/core/java/com/android/server/biometrics/RemovalClient.java
index be233ec..0509067 100644
--- a/services/core/java/com/android/server/biometrics/RemovalClient.java
+++ b/services/core/java/com/android/server/biometrics/RemovalClient.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.util.Slog;
@@ -43,6 +44,11 @@
     }
 
     @Override
+    protected int statsAction() {
+        return BiometricsProtoEnums.ACTION_REMOVE;
+    }
+
+    @Override
     public int start() {
         // The biometric template ids will be removed when we get confirmation from the HAL
         try {
diff --git a/services/core/java/com/android/server/biometrics/face/FaceService.java b/services/core/java/com/android/server/biometrics/face/FaceService.java
index d4be539..90342ee 100644
--- a/services/core/java/com/android/server/biometrics/face/FaceService.java
+++ b/services/core/java/com/android/server/biometrics/face/FaceService.java
@@ -27,6 +27,7 @@
 import android.content.pm.UserInfo;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.hardware.biometrics.IBiometricServiceLockoutResetCallback;
 import android.hardware.biometrics.IBiometricServiceReceiverInternal;
 import android.hardware.biometrics.face.V1_0.IBiometricsFace;
@@ -90,6 +91,11 @@
             super(context, daemon, halDeviceId, token, listener, targetUserId, groupId, opId,
                     restricted, owner, cookie, requireConfirmation);
         }
+
+        @Override
+        protected int statsModality() {
+            return FaceService.this.statsModality();
+        }
     }
 
     /**
@@ -126,6 +132,11 @@
                 public boolean shouldVibrate() {
                     return false;
                 }
+
+                @Override
+                protected int statsModality() {
+                    return FaceService.this.statsModality();
+                }
             };
 
             enrollInternal(client, UserHandle.getCallingUserId());
@@ -206,7 +217,12 @@
             final boolean restricted = isRestricted();
             final RemovalClientImpl client = new RemovalClientImpl(getContext(), mDaemonWrapper,
                     mHalDeviceId, token, new ServiceListenerImpl(receiver), faceId, 0 /* groupId */,
-                    userId, restricted, token.toString());
+                    userId, restricted, token.toString()) {
+                @Override
+                protected int statsModality() {
+                    return FaceService.this.statsModality();
+                }
+            };
             client.setShouldNotifyUserActivity(true);
             removeInternal(client);
         }
@@ -219,7 +235,12 @@
             final boolean restricted = isRestricted();
             final EnumerateClientImpl client = new EnumerateClientImpl(getContext(), mDaemonWrapper,
                     mHalDeviceId, token, new ServiceListenerImpl(receiver), userId, userId,
-                    restricted, getContext().getOpPackageName());
+                    restricted, getContext().getOpPackageName()) {
+                @Override
+                protected int statsModality() {
+                    return FaceService.this.statsModality();
+                }
+            };
             enumerateInternal(client);
         }
 
@@ -770,6 +791,11 @@
         // noop for Face.
     }
 
+    @Override
+    protected int statsModality() {
+        return BiometricsProtoEnums.MODALITY_FACE;
+    }
+
     /** Gets the face daemon */
     private synchronized IBiometricsFace getFaceDaemon() {
         if (mDaemon == null) {
diff --git a/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java b/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java
index f84cda03..62947c7 100644
--- a/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java
@@ -30,6 +30,7 @@
 import android.content.pm.UserInfo;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricsProtoEnums;
 import android.hardware.biometrics.IBiometricServiceLockoutResetCallback;
 import android.hardware.biometrics.IBiometricServiceReceiverInternal;
 import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint;
@@ -101,6 +102,11 @@
     }
 
     private final class FingerprintAuthClient extends AuthenticationClientImpl {
+        @Override
+        protected boolean isFingerprint() {
+            return true;
+        }
+
         public FingerprintAuthClient(Context context,
                 DaemonWrapper daemon, long halDeviceId, IBinder token,
                 ServiceListener listener, int targetUserId, int groupId, long opId,
@@ -109,6 +115,11 @@
             super(context, daemon, halDeviceId, token, listener, targetUserId, groupId, opId,
                     restricted, owner, cookie, requireConfirmation);
         }
+
+        @Override
+        protected int statsModality() {
+            return FingerprintService.this.statsModality();
+        }
     }
 
     /**
@@ -147,6 +158,11 @@
                 public boolean shouldVibrate() {
                     return true;
                 }
+
+                @Override
+                protected int statsModality() {
+                    return FingerprintService.this.statsModality();
+                }
             };
 
             enrollInternal(client, userId);
@@ -225,7 +241,12 @@
             final boolean restricted = isRestricted();
             final RemovalClientImpl client = new RemovalClientImpl(getContext(), mDaemonWrapper,
                     mHalDeviceId, token, new ServiceListenerImpl(receiver), fingerId, groupId,
-                    userId, restricted, token.toString());
+                    userId, restricted, token.toString()) {
+                @Override
+                protected int statsModality() {
+                    return FingerprintService.this.statsModality();
+                }
+            };
             client.setShouldNotifyUserActivity(true);
             removeInternal(client);
         }
@@ -238,7 +259,12 @@
             final boolean restricted = isRestricted();
             final EnumerateClientImpl client = new EnumerateClientImpl(getContext(), mDaemonWrapper,
                     mHalDeviceId, token, new ServiceListenerImpl(receiver), userId, userId,
-                    restricted, getContext().getOpPackageName());
+                    restricted, getContext().getOpPackageName()) {
+                @Override
+                protected int statsModality() {
+                    return FingerprintService.this.statsModality();
+                }
+            };
             enumerateInternal(client);
         }
 
@@ -544,6 +570,11 @@
             }
             return remaining == 0;
         }
+
+        @Override
+        protected int statsModality() {
+            return FingerprintService.this.statsModality();
+        }
     }
 
     /**
@@ -558,6 +589,11 @@
                     restricted,
                     owner);
         }
+
+        @Override
+        protected int statsModality() {
+            return FingerprintService.this.statsModality();
+        }
     }
 
     private final FingerprintMetrics mFingerprintMetrics = new FingerprintMetrics();
@@ -885,6 +921,11 @@
         }
     }
 
+    @Override
+    protected int statsModality() {
+        return BiometricsProtoEnums.MODALITY_FINGERPRINT;
+    }
+
     /** Gets the fingerprint daemon */
     private synchronized IBiometricsFingerprint getFingerprintDaemon() {
         if (mDaemon == null) {
diff --git a/services/core/java/com/android/server/biometrics/iris/IrisService.java b/services/core/java/com/android/server/biometrics/iris/IrisService.java
index 37cdc2a..eb457b6 100644
--- a/services/core/java/com/android/server/biometrics/iris/IrisService.java
+++ b/services/core/java/com/android/server/biometrics/iris/IrisService.java
@@ -17,6 +17,7 @@
 package com.android.server.biometrics.iris;
 
 import android.content.Context;
+import android.hardware.biometrics.BiometricsProtoEnums;
 
 import com.android.server.biometrics.BiometricServiceBase;
 import com.android.server.biometrics.BiometricUtils;
@@ -128,4 +129,9 @@
     protected boolean checkAppOps(int uid, String opPackageName) {
         return false;
     }
+
+    @Override
+    protected int statsModality() {
+        return BiometricsProtoEnums.MODALITY_IRIS;
+    }
 }
diff --git a/services/core/java/com/android/server/display/BrightnessTracker.java b/services/core/java/com/android/server/display/BrightnessTracker.java
index 019d726..727cf0e 100644
--- a/services/core/java/com/android/server/display/BrightnessTracker.java
+++ b/services/core/java/com/android/server/display/BrightnessTracker.java
@@ -27,12 +27,17 @@
 import android.content.IntentFilter;
 import android.content.pm.ParceledListSlice;
 import android.database.ContentObserver;
+import android.graphics.PixelFormat;
 import android.hardware.Sensor;
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.hardware.display.AmbientBrightnessDayStats;
 import android.hardware.display.BrightnessChangeEvent;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.DisplayManagerInternal;
+import android.hardware.display.DisplayedContentSample;
+import android.hardware.display.DisplayedContentSamplingAttributes;
 import android.net.Uri;
 import android.os.BatteryManager;
 import android.os.Environment;
@@ -48,6 +53,7 @@
 import android.util.AtomicFile;
 import android.util.Slog;
 import android.util.Xml;
+import android.view.Display;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -55,6 +61,7 @@
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.RingBuffer;
+import com.android.server.LocalServices;
 
 import libcore.io.IoUtils;
 
@@ -111,6 +118,8 @@
     private static final String ATTR_DEFAULT_CONFIG = "defaultConfig";
     private static final String ATTR_POWER_SAVE = "powerSaveFactor";
     private static final String ATTR_USER_POINT = "userPoint";
+    private static final String ATTR_COLOR_SAMPLE_DURATION = "colorSampleDuration";
+    private static final String ATTR_COLOR_VALUE_BUCKETS = "colorValueBuckets";
 
     private static final int MSG_BACKGROUND_START = 0;
     private static final int MSG_BRIGHTNESS_CHANGED = 1;
@@ -119,6 +128,10 @@
 
     private static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
 
+    private static final long COLOR_SAMPLE_DURATION = TimeUnit.SECONDS.toSeconds(10);
+    // Sample chanel 2 of HSV which is the Value component.
+    private static final int COLOR_SAMPLE_COMPONENT_MASK = 0x1 << 2;
+
     // Lock held while accessing mEvents, is held while writing events to flash.
     private final Object mEventsLock = new Object();
     @GuardedBy("mEventsLock")
@@ -136,12 +149,16 @@
     private final ContentResolver mContentResolver;
     private final Handler mBgHandler;
 
-    // mBroadcastReceiver,  mSensorListener, mSettingsObserver and mSensorRegistered
-    // should only be used on the mBgHandler thread.
+    // These members should only be accessed on the mBgHandler thread.
     private BroadcastReceiver mBroadcastReceiver;
     private SensorListener mSensorListener;
     private SettingsObserver mSettingsObserver;
+    private DisplayListener mDisplayListener;
     private boolean mSensorRegistered;
+    private boolean mColorSamplingEnabled;
+    private int mNoFramesToSample;
+    private float mFrameRate;
+    // End of block of members that should only be accessed on the mBgHandler thread.
 
     private @UserIdInt int mCurrentUserId = UserHandle.USER_NULL;
 
@@ -208,6 +225,7 @@
             mLastBrightness = initialBrightness;
             mStarted = true;
         }
+        enableColorSampling();
     }
 
     /** Stop listening for events */
@@ -226,6 +244,7 @@
         synchronized (mDataCollectionLock) {
             mStarted = false;
         }
+        disableColorSampling();
     }
 
     public void onSwitchUser(@UserIdInt int newUserId) {
@@ -367,6 +386,17 @@
         builder.setColorTemperature(mInjector.getColorTemperature(mContext,
                 UserHandle.USER_CURRENT));
 
+        if (mColorSamplingEnabled) {
+            DisplayedContentSample sample = mInjector.sampleColor(mNoFramesToSample);
+            if (sample != null && sample.getSampleComponent(
+                    DisplayedContentSample.ColorComponent.CHANNEL2) != null) {
+                float numMillis = (sample.getNumFrames() / mFrameRate) * 1000.0f;
+                builder.setColorValues(
+                        sample.getSampleComponent(DisplayedContentSample.ColorComponent.CHANNEL2),
+                        Math.round(numMillis));
+            }
+        }
+
         BrightnessChangeEvent event = builder.build();
         if (DEBUG) {
             Slog.d(TAG, "Event " + event.brightness + " " + event.packageName);
@@ -541,6 +571,19 @@
                 }
                 out.attribute(null, ATTR_LUX, luxValues.toString());
                 out.attribute(null, ATTR_LUX_TIMESTAMPS, luxTimestamps.toString());
+                if (toWrite[i].colorValueBuckets != null
+                        && toWrite[i].colorValueBuckets.length > 0) {
+                    out.attribute(null, ATTR_COLOR_SAMPLE_DURATION,
+                            Long.toString(toWrite[i].colorSampleDuration));
+                    StringBuilder buckets = new StringBuilder();
+                    for (int j = 0; j < toWrite[i].colorValueBuckets.length; ++j) {
+                        if (j > 0) {
+                            buckets.append(',');
+                        }
+                        buckets.append(Long.toString(toWrite[i].colorValueBuckets[j]));
+                    }
+                    out.attribute(null, ATTR_COLOR_VALUE_BUCKETS, buckets.toString());
+                }
                 out.endTag(null, TAG_EVENT);
             }
         }
@@ -628,6 +671,20 @@
                         builder.setUserBrightnessPoint(Boolean.parseBoolean(userPoint));
                     }
 
+                    String colorSampleDurationString =
+                            parser.getAttributeValue(null, ATTR_COLOR_SAMPLE_DURATION);
+                    String colorValueBucketsString =
+                            parser.getAttributeValue(null, ATTR_COLOR_VALUE_BUCKETS);
+                    if (colorSampleDurationString != null && colorValueBucketsString != null) {
+                        long colorSampleDuration = Long.parseLong(colorSampleDurationString);
+                        String[] buckets = colorValueBucketsString.split(",");
+                        long[] bucketValues = new long[buckets.length];
+                        for (int i = 0; i < bucketValues.length; ++i) {
+                            bucketValues[i] = Long.parseLong(buckets[i]);
+                        }
+                        builder.setColorValues(bucketValues, colorSampleDuration);
+                    }
+
                     BrightnessChangeEvent event = builder.build();
                     if (DEBUG) {
                         Slog.i(TAG, "Read event " + event.brightness
@@ -695,6 +752,73 @@
 
     private void dumpLocal(PrintWriter pw) {
         pw.println("  mSensorRegistered=" + mSensorRegistered);
+        pw.println("  mColorSamplingEnabled=" + mColorSamplingEnabled);
+        pw.println("  mNoFramesToSample=" + mNoFramesToSample);
+        pw.println("  mFrameRate=" + mFrameRate);
+    }
+
+    private void enableColorSampling() {
+        if (!mInjector.isBrightnessModeAutomatic(mContentResolver)
+                || !mInjector.isInteractive(mContext)
+                || mColorSamplingEnabled) {
+            return;
+        }
+
+        mFrameRate = mInjector.getFrameRate(mContext);
+        if (mFrameRate <= 0) {
+            Slog.wtf(TAG, "Default display has a zero or negative framerate.");
+            return;
+        }
+        mNoFramesToSample = (int) (mFrameRate * COLOR_SAMPLE_DURATION);
+
+        DisplayedContentSamplingAttributes attributes = mInjector.getSamplingAttributes();
+        if (DEBUG && attributes != null) {
+            Slog.d(TAG, "Color sampling"
+                    + " mask=0x" + Integer.toHexString(attributes.getComponentMask())
+                    + " dataSpace=0x" + Integer.toHexString(attributes.getDataspace())
+                    + " pixelFormat=0x" + Integer.toHexString(attributes.getPixelFormat()));
+        }
+        // Do we support sampling the Value component of HSV
+        if (attributes != null && attributes.getPixelFormat() == PixelFormat.HSV_888
+                && (attributes.getComponentMask() & COLOR_SAMPLE_COMPONENT_MASK) != 0) {
+
+            mColorSamplingEnabled = mInjector.enableColorSampling(/* enable= */true,
+                    mNoFramesToSample);
+            if (DEBUG) {
+                Slog.i(TAG, "turning on color sampling for "
+                        + mNoFramesToSample + " frames, success=" + mColorSamplingEnabled);
+            }
+        }
+        if (mColorSamplingEnabled && mDisplayListener == null) {
+            mDisplayListener = new DisplayListener();
+            mInjector.registerDisplayListener(mContext, mDisplayListener, mBgHandler);
+        }
+    }
+
+    private void disableColorSampling() {
+        if (!mColorSamplingEnabled) {
+            return;
+        }
+        mInjector.enableColorSampling(/* enable= */ false, /* noFrames= */ 0);
+        mColorSamplingEnabled = false;
+        if (mDisplayListener != null) {
+            mInjector.unRegisterDisplayListener(mContext, mDisplayListener);
+            mDisplayListener = null;
+        }
+        if (DEBUG) {
+            Slog.i(TAG, "turning off color sampling");
+        }
+    }
+
+    private void updateColorSampling() {
+        if (!mColorSamplingEnabled) {
+            return;
+        }
+        float frameRate = mInjector.getFrameRate(mContext);
+        if (frameRate != mFrameRate) {
+            disableColorSampling();
+            enableColorSampling();
+        }
     }
 
     public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(int userId) {
@@ -768,6 +892,26 @@
         }
     }
 
+    private final class DisplayListener implements DisplayManager.DisplayListener {
+
+        @Override
+        public void onDisplayAdded(int displayId) {
+            // Ignore
+        }
+
+        @Override
+        public void onDisplayRemoved(int displayId) {
+            // Ignore
+        }
+
+        @Override
+        public void onDisplayChanged(int displayId) {
+            if (displayId == Display.DEFAULT_DISPLAY) {
+                updateColorSampling();
+            }
+        }
+    }
+
     private final class SettingsObserver extends ContentObserver {
         public SettingsObserver(Handler handler) {
             super(handler);
@@ -828,9 +972,11 @@
                     break;
                 case MSG_START_SENSOR_LISTENER:
                     startSensorListener();
+                    enableColorSampling();
                     break;
                 case MSG_STOP_SENSOR_LISTENER:
                     stopSensorListener();
+                    disableColorSampling();
                     break;
             }
         }
@@ -957,5 +1103,44 @@
         public boolean isNightModeActive(Context context, int userId) {
             return new ColorDisplayController(context, userId).isActivated();
         }
+
+        public DisplayedContentSample sampleColor(int noFramesToSample) {
+            final DisplayManagerInternal displayManagerInternal =
+                    LocalServices.getService(DisplayManagerInternal.class);
+            return displayManagerInternal.getDisplayedContentSample(
+                   Display.DEFAULT_DISPLAY, noFramesToSample, 0);
+        }
+
+        public float getFrameRate(Context context) {
+            final DisplayManager displayManager = context.getSystemService(DisplayManager.class);
+            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
+            return display.getRefreshRate();
+        }
+
+        public DisplayedContentSamplingAttributes getSamplingAttributes() {
+            final DisplayManagerInternal displayManagerInternal =
+                    LocalServices.getService(DisplayManagerInternal.class);
+            return displayManagerInternal.getDisplayedContentSamplingAttributes(
+                    Display.DEFAULT_DISPLAY);
+        }
+
+        public boolean enableColorSampling(boolean enable, int noFrames) {
+            final DisplayManagerInternal displayManagerInternal =
+                    LocalServices.getService(DisplayManagerInternal.class);
+            return displayManagerInternal.setDisplayedContentSamplingEnabled(
+                    Display.DEFAULT_DISPLAY, enable, COLOR_SAMPLE_COMPONENT_MASK, noFrames);
+        }
+
+        public void registerDisplayListener(Context context,
+                DisplayManager.DisplayListener listener, Handler handler) {
+            final DisplayManager displayManager = context.getSystemService(DisplayManager.class);
+            displayManager.registerDisplayListener(listener, handler);
+        }
+
+        public void unRegisterDisplayListener(Context context,
+                DisplayManager.DisplayListener listener) {
+            final DisplayManager displayManager = context.getSystemService(DisplayManager.class);
+            displayManager.unregisterDisplayListener(listener);
+        }
     }
 }
diff --git a/services/core/java/com/android/server/display/ColorDisplayService.java b/services/core/java/com/android/server/display/ColorDisplayService.java
index eb0ed0a..591ce8d 100644
--- a/services/core/java/com/android/server/display/ColorDisplayService.java
+++ b/services/core/java/com/android/server/display/ColorDisplayService.java
@@ -55,6 +55,7 @@
 import android.opengl.Matrix;
 import android.os.Binder;
 import android.os.Handler;
+import android.os.IBinder;
 import android.os.Looper;
 import android.os.Message;
 import android.os.SystemProperties;
@@ -66,6 +67,9 @@
 import android.view.SurfaceControl;
 import android.view.accessibility.AccessibilityManager;
 import android.view.animation.AnimationUtils;
+import android.view.SurfaceControl;
+import android.view.SurfaceControl.DisplayPrimaries;
+
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.ColorDisplayController;
@@ -145,43 +149,20 @@
         @Override
         public void setUp(Context context, boolean needsLinear) {
             mSetUp = false;
+            final Resources res = context.getResources();
 
-            final Resources res = getContext().getResources();
-            final String[] displayPrimariesValues = res.getStringArray(
-                    R.array.config_displayWhiteBalanceDisplayPrimaries);
+            ColorSpace.Rgb displayColorSpaceRGB = getDisplayColorSpaceFromSurfaceControl();
+            if (displayColorSpaceRGB == null) {
+                Slog.w(TAG, "Failed to get display color space from SurfaceControl, trying res");
+                displayColorSpaceRGB = getDisplayColorSpaceFromResources(res);
+                if (displayColorSpaceRGB == null) {
+                    Slog.e(TAG, "Failed to get display color space from resources");
+                    return;
+                }
+            }
+
             final String[] nominalWhiteValues = res.getStringArray(
                     R.array.config_displayWhiteBalanceDisplayNominalWhite);
-
-            if (displayPrimariesValues.length != NUM_DISPLAY_PRIMARIES_VALS) {
-                Slog.e(TAG, "Unexpected display white balance primaries resource length " +
-                        displayPrimariesValues.length);
-                return;
-            }
-
-            if (nominalWhiteValues.length != NUM_VALUES_PER_PRIMARY) {
-                Slog.e(TAG, "Unexpected display white balance nominal white resource length " +
-                        nominalWhiteValues.length);
-                return;
-            }
-
-            float[] displayRedGreenBlueXYZ =
-                    new float[NUM_DISPLAY_PRIMARIES_VALS - NUM_VALUES_PER_PRIMARY];
-            float[] displayWhiteXYZ = new float[NUM_VALUES_PER_PRIMARY];
-            for (int i = 0; i < displayRedGreenBlueXYZ.length; i++) {
-                displayRedGreenBlueXYZ[i] = Float.parseFloat(displayPrimariesValues[i]);
-            }
-            for (int i = 0; i < displayWhiteXYZ.length; i++) {
-                displayWhiteXYZ[i] = Float.parseFloat(
-                        displayPrimariesValues[displayRedGreenBlueXYZ.length + i]);
-            }
-
-            final ColorSpace.Rgb displayColorSpaceRGB = new ColorSpace.Rgb(
-                    "Display Color Space",
-                    displayRedGreenBlueXYZ,
-                    displayWhiteXYZ,
-                    2.2f // gamma, unused for display white balance
-            );
-
             float[] displayNominalWhiteXYZ = new float[NUM_VALUES_PER_PRIMARY];
             for (int i = 0; i < nominalWhiteValues.length; i++) {
                 displayNominalWhiteXYZ[i] = Float.parseFloat(nominalWhiteValues[i]);
@@ -190,14 +171,14 @@
             final int colorTemperatureMin = res.getInteger(
                     R.integer.config_displayWhiteBalanceColorTemperatureMin);
             if (colorTemperatureMin <= 0) {
-                Slog.e(TAG, "display white balance minimum temperature must be greater than 0");
+                Slog.e(TAG, "Display white balance minimum temperature must be greater than 0");
                 return;
             }
 
             final int colorTemperatureMax = res.getInteger(
                     R.integer.config_displayWhiteBalanceColorTemperatureMax);
             if (colorTemperatureMax < colorTemperatureMin) {
-                Slog.e(TAG, "display white balance max temp must be greater or equal to min");
+                Slog.e(TAG, "Display white balance max temp must be greater or equal to min");
                 return;
             }
 
@@ -323,6 +304,57 @@
                         matrixToString(mMatrixDisplayWhiteBalance, 4));
             }
         }
+
+        private ColorSpace.Rgb makeRgbColorSpaceFromXYZ(float[] redGreenBlueXYZ, float[] whiteXYZ) {
+            return new ColorSpace.Rgb(
+                "Display Color Space",
+                redGreenBlueXYZ,
+                whiteXYZ,
+                2.2f // gamma, unused for display white balance
+            );
+        }
+
+        private ColorSpace.Rgb getDisplayColorSpaceFromSurfaceControl() {
+            IBinder displayToken = SurfaceControl.getBuiltInDisplay(
+                    SurfaceControl.BUILT_IN_DISPLAY_ID_MAIN);
+            if (displayToken == null) {
+                return null;
+            }
+
+            DisplayPrimaries primaries = SurfaceControl.getDisplayNativePrimaries(displayToken);
+            if (primaries == null || primaries.red == null || primaries.green == null ||
+                primaries.blue == null || primaries.white == null) {
+                return null;
+            }
+
+            return makeRgbColorSpaceFromXYZ(
+                    new float[] {
+                        primaries.red.X, primaries.red.Y, primaries.red.Z,
+                        primaries.green.X, primaries.green.Y, primaries.green.Z,
+                        primaries.blue.X, primaries.blue.Y, primaries.blue.Z,
+                    },
+                    new float[] { primaries.white.X, primaries.white.Y, primaries.white.Z }
+                    );
+        }
+
+        private ColorSpace.Rgb getDisplayColorSpaceFromResources(Resources res) {
+            final String[] displayPrimariesValues = res.getStringArray(
+                    R.array.config_displayWhiteBalanceDisplayPrimaries);
+            float[] displayRedGreenBlueXYZ =
+                    new float[NUM_DISPLAY_PRIMARIES_VALS - NUM_VALUES_PER_PRIMARY];
+            float[] displayWhiteXYZ = new float[NUM_VALUES_PER_PRIMARY];
+
+            for (int i = 0; i < displayRedGreenBlueXYZ.length; i++) {
+                displayRedGreenBlueXYZ[i] = Float.parseFloat(displayPrimariesValues[i]);
+            }
+
+            for (int i = 0; i < displayWhiteXYZ.length; i++) {
+                displayWhiteXYZ[i] = Float.parseFloat(
+                        displayPrimariesValues[displayRedGreenBlueXYZ.length + i]);
+            }
+
+            return makeRgbColorSpaceFromXYZ(displayRedGreenBlueXYZ, displayWhiteXYZ);
+        }
     };
 
     private final TintController mGlobalSaturationTintController = new TintController() {
diff --git a/services/core/java/com/android/server/display/ColorFade.java b/services/core/java/com/android/server/display/ColorFade.java
index 0400b56..f2c539c 100644
--- a/services/core/java/com/android/server/display/ColorFade.java
+++ b/services/core/java/com/android/server/display/ColorFade.java
@@ -575,7 +575,7 @@
                 final SurfaceControl.Builder builder =
                         new SurfaceControl.Builder(mSurfaceSession).setName("ColorFade");
                 if (mMode == MODE_FADE) {
-                    builder.setColorLayer();
+                    builder.setColorLayer(true);
                 } else {
                     builder.setBufferSize(mDisplayWidth, mDisplayHeight);
                 }
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index c9df86e..80ea1da 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -2196,6 +2196,22 @@
             }
         }
 
+        void setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
+            if (mDisplayPowerController != null) {
+                synchronized (mSyncRoot) {
+                    mDisplayPowerController.setDisplayWhiteBalanceLoggingEnabled(enabled);
+                }
+            }
+        }
+
+        void setAmbientColorTemperatureOverride(float cct) {
+            if (mDisplayPowerController != null) {
+                synchronized (mSyncRoot) {
+                    mDisplayPowerController.setAmbientColorTemperatureOverride(cct);
+                }
+            }
+        }
+
         private boolean validatePackageName(int uid, String packageName) {
             if (packageName != null) {
                 String[] packageNames = mContext.getPackageManager().getPackagesForUid(uid);
diff --git a/services/core/java/com/android/server/display/DisplayManagerShellCommand.java b/services/core/java/com/android/server/display/DisplayManagerShellCommand.java
index abbfc7b..04d28ea 100644
--- a/services/core/java/com/android/server/display/DisplayManagerShellCommand.java
+++ b/services/core/java/com/android/server/display/DisplayManagerShellCommand.java
@@ -45,6 +45,12 @@
                 return setAutoBrightnessLoggingEnabled(true);
             case "ab-logging-disable":
                 return setAutoBrightnessLoggingEnabled(false);
+            case "dwb-logging-enable":
+                return setDisplayWhiteBalanceLoggingEnabled(true);
+            case "dwb-logging-disable":
+                return setDisplayWhiteBalanceLoggingEnabled(false);
+            case "dwb-set-cct":
+                return setAmbientColorTemperatureOverride();
             default:
                 return handleDefaultCommands(cmd);
         }
@@ -65,6 +71,12 @@
         pw.println("    Enable auto-brightness logging.");
         pw.println("  ab-logging-disable");
         pw.println("    Disable auto-brightness logging.");
+        pw.println("  dwb-logging-enable");
+        pw.println("    Enable display white-balance logging.");
+        pw.println("  dwb-logging-disable");
+        pw.println("    Disable display white-balance logging.");
+        pw.println("  dwb-set-cct CCT");
+        pw.println("    Sets the ambient color temperature override to CCT (use -1 to disable).");
         pw.println();
         Intent.printIntentArgsHelp(pw , "");
     }
@@ -75,7 +87,7 @@
             getErrPrintWriter().println("Error: no brightness specified");
             return 1;
         }
-        float brightness = -1;
+        float brightness = -1.0f;
         try {
             brightness = Float.parseFloat(brightnessText);
         } catch (NumberFormatException e) {
@@ -84,7 +96,7 @@
             getErrPrintWriter().println("Error: brightness should be a number between 0 and 1");
             return 1;
         }
-        mService.setBrightness((int) brightness * 255);
+        mService.setBrightness((int) (brightness * 255));
         return 0;
     }
 
@@ -97,4 +109,26 @@
         mService.setAutoBrightnessLoggingEnabled(enabled);
         return 0;
     }
+
+    private int setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
+        mService.setDisplayWhiteBalanceLoggingEnabled(enabled);
+        return 0;
+    }
+
+    private int setAmbientColorTemperatureOverride() {
+        String cctText = getNextArg();
+        if (cctText == null) {
+            getErrPrintWriter().println("Error: no cct specified");
+            return 1;
+        }
+        float cct;
+        try {
+            cct = Float.parseFloat(cctText);
+        } catch (NumberFormatException e) {
+            getErrPrintWriter().println("Error: cct should be a number");
+            return 1;
+        }
+        mService.setAmbientColorTemperatureOverride(cct);
+        return 0;
+    }
 }
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index 2a8462b..dc5be6a 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -52,6 +52,9 @@
 import com.android.internal.app.IBatteryStats;
 import com.android.server.LocalServices;
 import com.android.server.am.BatteryStatsService;
+import com.android.server.display.whitebalance.DisplayWhiteBalanceController;
+import com.android.server.display.whitebalance.DisplayWhiteBalanceFactory;
+import com.android.server.display.whitebalance.DisplayWhiteBalanceSettings;
 import com.android.server.policy.WindowManagerPolicy;
 
 import java.io.PrintWriter;
@@ -78,7 +81,8 @@
  * For debugging, you can make the color fade and brightness animations run
  * slower by changing the "animator duration scale" option in Development Settings.
  */
-final class DisplayPowerController implements AutomaticBrightnessController.Callbacks {
+final class DisplayPowerController implements AutomaticBrightnessController.Callbacks,
+        DisplayWhiteBalanceController.Callbacks {
     private static final String TAG = "DisplayPowerController";
     private static final String SCREEN_ON_BLOCKED_TRACE_NAME = "Screen on blocked";
     private static final String SCREEN_OFF_BLOCKED_TRACE_NAME = "Screen off blocked";
@@ -307,6 +311,12 @@
     // Whether or not to skip the initial brightness ramps into STATE_ON.
     private final boolean mSkipScreenOnBrightnessRamp;
 
+    // Display white balance components.
+    @Nullable
+    private final DisplayWhiteBalanceSettings mDisplayWhiteBalanceSettings;
+    @Nullable
+    private final DisplayWhiteBalanceController mDisplayWhiteBalanceController;
+
     // A record of state for skipping brightness ramps.
     private int mSkipRampState = RAMP_STATE_SKIP_NONE;
 
@@ -504,6 +514,20 @@
         mPendingScreenBrightnessSetting = -1;
         mTemporaryAutoBrightnessAdjustment = Float.NaN;
         mPendingAutoBrightnessAdjustment = Float.NaN;
+
+        DisplayWhiteBalanceSettings displayWhiteBalanceSettings = null;
+        DisplayWhiteBalanceController displayWhiteBalanceController = null;
+        try {
+            displayWhiteBalanceSettings = new DisplayWhiteBalanceSettings(mContext, mHandler);
+            displayWhiteBalanceController = DisplayWhiteBalanceFactory.create(mHandler,
+                    mSensorManager, resources);
+            displayWhiteBalanceSettings.setCallbacks(this);
+            displayWhiteBalanceController.setCallbacks(this);
+        } catch (Exception e) {
+            Slog.e(TAG, "failed to set up display white-balance: " + e);
+        }
+        mDisplayWhiteBalanceSettings = displayWhiteBalanceSettings;
+        mDisplayWhiteBalanceController = displayWhiteBalanceController;
     }
 
     /**
@@ -526,6 +550,9 @@
     public void onSwitchUser(@UserIdInt int newUserId) {
         handleSettingsChange(true /* userSwitch */);
         mBrightnessTracker.onSwitchUser(newUserId);
+        if (mDisplayWhiteBalanceSettings != null) {
+            mDisplayWhiteBalanceSettings.onSwitchUser();
+        }
     }
 
     public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(
@@ -988,6 +1015,16 @@
 
         }
 
+        // Update display white-balance.
+        if (mDisplayWhiteBalanceController != null) {
+            if (state == Display.STATE_ON && mDisplayWhiteBalanceSettings.isEnabled()) {
+                mDisplayWhiteBalanceController.setEnabled(true);
+                mDisplayWhiteBalanceController.updateScreenColorTemperature();
+            } else {
+                mDisplayWhiteBalanceController.setEnabled(false);
+            }
+        }
+
         // Determine whether the display is ready for use in the newly requested state.
         // Note that we do not wait for the brightness ramp animation to complete before
         // reporting the display is ready because we only need to ensure the screen is in the
@@ -1702,6 +1739,12 @@
             pw.println();
             mBrightnessTracker.dump(pw);
         }
+
+        pw.println();
+        if (mDisplayWhiteBalanceController != null) {
+            mDisplayWhiteBalanceController.dump(pw);
+            mDisplayWhiteBalanceSettings.dump(pw);
+        }
     }
 
     private static String proximityToString(int state) {
@@ -1848,4 +1891,26 @@
             mAutomaticBrightnessController.setLoggingEnabled(enabled);
         }
     }
+
+    @Override // DisplayWhiteBalanceController.Callbacks
+    public void updateWhiteBalance() {
+        sendUpdatePowerState();
+    }
+
+    void setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
+        if (mDisplayWhiteBalanceController != null) {
+            mDisplayWhiteBalanceController.setLoggingEnabled(enabled);
+            mDisplayWhiteBalanceSettings.setLoggingEnabled(enabled);
+        }
+    }
+
+    void setAmbientColorTemperatureOverride(float cct) {
+        if (mDisplayWhiteBalanceController != null) {
+            mDisplayWhiteBalanceController.setAmbientColorTemperatureOverride(cct);
+            // The ambient color temperature override is only applied when the ambient color
+            // temperature changes or is updated, so it doesn't necessarily change the screen color
+            // temperature immediately. So, let's make it!
+            sendUpdatePowerState();
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/display/utils/History.java b/services/core/java/com/android/server/display/utils/History.java
new file mode 100644
index 0000000..ed171b8
--- /dev/null
+++ b/services/core/java/com/android/server/display/utils/History.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.utils;
+
+import java.time.Clock;
+
+/**
+ * A fixed-size buffer that keeps the most recent values and their times.
+ *
+ * This class is used for logging and debugging purposes only, so there's no way to retrieve the
+ * history other than toString(), and a non-monotonic clock is good enough.
+ */
+public class History {
+
+    private int mSize;
+    private int mCount;
+    private int mStart;
+    private int mEnd;
+
+    private long[] mTimes;
+    private float[] mValues;
+
+    private Clock mClock;
+
+    /**
+     * @param size
+     *      The maximum number of values kept.
+     */
+    public History(int size) {
+        this(size, Clock.systemUTC());
+    }
+
+    /**
+     * @param size
+     *    The maximum number of values kept.
+     * @param clock
+     *    The clock used.
+     */
+    public History(int size, Clock clock) {
+        mSize = size;
+        mCount = 0;
+        mStart = 0;
+        mEnd = 0;
+        mTimes = new long[size];
+        mValues = new float[size];
+        mClock = clock;
+    }
+
+    /**
+     * Add a value.
+     *
+     * @param value
+     *      The value.
+     */
+    public void add(float value) {
+        mTimes[mEnd] = mClock.millis();
+        mValues[mEnd] = value;
+        if (mCount < mSize) {
+            mCount++;
+        } else {
+            mStart = (mStart + 1) % mSize;
+        }
+        mEnd = (mEnd + 1) % mSize;
+    }
+
+    /**
+     * Convert the buffer to string.
+     *
+     * @return The buffer as string.
+     */
+    public String toString() {
+        StringBuffer sb = new StringBuffer();
+        sb.append("[");
+        for (int i = 0; i < mCount; i++) {
+            final int index = (mStart + i) % mSize;
+            final long time = mTimes[index];
+            final float value = mValues[index];
+            sb.append(value + " @ " + time);
+            if (i + 1 != mCount) {
+                sb.append(", ");
+            }
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/utils/RollingBuffer.java b/services/core/java/com/android/server/display/utils/RollingBuffer.java
new file mode 100644
index 0000000..dd5b7ab
--- /dev/null
+++ b/services/core/java/com/android/server/display/utils/RollingBuffer.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.utils;
+
+/**
+ * A buffer that supports adding new values and truncating old ones.
+ */
+public class RollingBuffer {
+
+    private static final int INITIAL_SIZE = 50;
+
+    private int mSize;
+    private int mCount;
+    private int mStart;
+    private int mEnd;
+
+    private long[] mTimes; // Milliseconds
+    private float[] mValues;
+
+    public RollingBuffer() {
+        mSize = INITIAL_SIZE;
+        mTimes = new long[INITIAL_SIZE];
+        mValues = new float[INITIAL_SIZE];
+        clear();
+    }
+
+    /**
+     * Add a value at a given time.
+     *
+     * @param time
+     *      The time (in milliseconds).
+     * @param value
+     *      The value.
+     */
+    public void add(long time, float value) {
+        if (mCount >= mSize) {
+            expandBuffer();
+        }
+        mTimes[mEnd] = time;
+        mValues[mEnd] = value;
+        mEnd = (mEnd + 1) % mSize;
+        mCount++;
+    }
+
+    /**
+     * Get the size of the buffer.
+     *
+     * @return The size of the buffer.
+     */
+    public int size() {
+        return mCount;
+    }
+
+    /**
+     * Return whether the buffer is empty or not.
+     *
+     * @return Whether the buffer is empty or not.
+     */
+    public boolean isEmpty() {
+        return size() == 0;
+    }
+
+    /**
+     * Get a time.
+     *
+     * @param index
+     *      The index of the time.
+     *
+     * @return The time.
+     */
+    public long getTime(int index) {
+        return mTimes[offsetOf(index)];
+    }
+
+    /**
+     * Get a value.
+     *
+     * @param index
+     *      The index of the value.
+     *
+     * @return The value.
+     */
+    public float getValue(int index) {
+        return mValues[offsetOf(index)];
+    }
+
+    /**
+     * Truncate old values.
+     *
+     * @param minTime
+     *      The minimum time (all values older than this time are truncated).
+     */
+    public void truncate(long minTime) {
+        if (isEmpty() || getTime(0) >= minTime) {
+            return;
+        }
+        final int index = getLatestIndexBefore(minTime);
+        mStart = offsetOf(index);
+        mCount -= index;
+        // Remove everything that happened before mTimes[index], but set the index-th value time to
+        // minTime rather than dropping it, as that would've been the value between the minTime and
+        // mTimes[index+1].
+        //
+        // -*---*---|---*---*- => xxxxxxxxx|*--*---*- rather than xxxxxxxxx|???*---*-
+        //      ^       ^                   ^  ^                               ^
+        //      i      i+1                  i i+1                             i+1
+        mTimes[mStart] = minTime;
+    }
+
+    /**
+     * Clears the buffer.
+     */
+    public void clear() {
+        mCount = 0;
+        mStart = 0;
+        mEnd = 0;
+    }
+
+    /**
+     * Convert the buffer to string.
+     *
+     * @return The buffer as string.
+     */
+    public String toString() {
+        StringBuffer sb = new StringBuffer();
+        sb.append("[");
+        for (int i = 0; i < mCount; i++) {
+            final int index = offsetOf(i);
+            sb.append(mValues[index] + " @ " + mTimes[index]);
+            if (i + 1 != mCount) {
+                sb.append(", ");
+            }
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+    private int offsetOf(int index) {
+        if (index < 0 || index >= mCount) {
+            throw new ArrayIndexOutOfBoundsException("invalid index: " + index + ", mCount= "
+                    + mCount);
+        }
+        return (mStart + index) % mSize;
+    }
+
+    private void expandBuffer() {
+        final int size = mSize * 2;
+        long[] times = new long[size];
+        float[] values = new float[size];
+        System.arraycopy(mTimes, mStart, times, 0, mCount - mStart);
+        System.arraycopy(mTimes, 0, times, mCount - mStart, mStart);
+        System.arraycopy(mValues, mStart, values, 0, mCount - mStart);
+        System.arraycopy(mValues, 0, values, mCount - mStart, mStart);
+        mSize = size;
+        mStart = 0;
+        mEnd = mCount;
+        mTimes = times;
+        mValues = values;
+    }
+
+    private int getLatestIndexBefore(long time) {
+        for (int i = 1; i < mCount; i++) {
+            if (mTimes[offsetOf(i)] > time) {
+                return i - 1;
+            }
+        }
+        return mCount - 1;
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java b/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java
new file mode 100644
index 0000000..532bbed
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java
@@ -0,0 +1,256 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.util.Slog;
+
+import com.android.server.display.utils.RollingBuffer;
+
+import java.io.PrintWriter;
+import java.util.Arrays;
+
+/**
+ * The DisplayWhiteBalanceController uses the AmbientFilter to average ambient changes over time,
+ * filter out the noise, and arrive at an estimate of the actual value.
+ *
+ * When the DisplayWhiteBalanceController detects a change in ambient brightness or color
+ * temperature, it passes it to the AmbientFilter, and when it needs the actual ambient value, it
+ * asks it for an estimate.
+ *
+ * Implementations:
+ * - {@link WeightedMovingAverageAmbientFilter}
+ *   A weighted average prioritising recent changes.
+ */
+abstract class AmbientFilter {
+
+    protected static final boolean DEBUG = false; // Enable for verbose logs.
+
+    protected final String mTag;
+    protected boolean mLoggingEnabled;
+
+    // How long ambient value changes are kept and taken into consideration.
+    private final int mHorizon; // Milliseconds
+
+    private final RollingBuffer mBuffer;
+
+    /**
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param horizon
+     *      How long ambient value changes are kept and taken into consideration.
+     *
+     * @throws IllegalArgumentException
+     *      - horizon is not positive.
+     */
+    AmbientFilter(String tag, int horizon) {
+        validateArguments(horizon);
+        mTag = tag;
+        mLoggingEnabled = false;
+        mHorizon = horizon;
+        mBuffer = new RollingBuffer();
+    }
+
+    /**
+     * Add an ambient value change.
+     *
+     * @param time
+     *      The time.
+     * @param value
+     *      The ambient value.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean addValue(long time, float value) {
+        if (value < 0.0f) {
+            return false;
+        }
+        truncateOldValues(time);
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "add value: " + value + " @ " + time);
+        }
+        mBuffer.add(time, value);
+        return true;
+    }
+
+    /**
+     * Get an estimate of the actual ambient color temperature.
+     *
+     * @param time
+     *      The time.
+     *
+     * @return An estimate of the actual ambient color temperature.
+     */
+    public float getEstimate(long time) {
+        truncateOldValues(time);
+        final float value = filter(time, mBuffer);
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "get estimate: " + value + " @ " + time);
+        }
+        return value;
+    }
+
+    /**
+     * Clears the filter state.
+     */
+    public void clear() {
+        mBuffer.clear();
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging is on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        return true;
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The PrintWriter used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("  " + mTag);
+        writer.println("    mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("    mHorizon=" + mHorizon);
+        writer.println("    mBuffer=" + mBuffer);
+    }
+
+    private void validateArguments(int horizon) {
+        if (horizon <= 0) {
+            throw new IllegalArgumentException("horizon must be positive");
+        }
+    }
+
+    private void truncateOldValues(long time) {
+        final long minTime = time - mHorizon;
+        mBuffer.truncate(minTime);
+    }
+
+    protected abstract float filter(long time, RollingBuffer buffer);
+
+    /**
+     * A weighted average prioritising recent changes.
+     */
+    static class WeightedMovingAverageAmbientFilter extends AmbientFilter {
+
+        // How long the latest ambient value change is predicted to last.
+        private static final int PREDICTION_TIME = 100; // Milliseconds
+
+        // Recent changes are prioritised by integrating their duration over y = x + mIntercept
+        // (the higher it is, the less prioritised recent changes are).
+        private final float mIntercept;
+
+        /**
+         * @param tag
+         *      The tag used for dumping and logging.
+         * @param horizon
+         *      How long ambient value changes are kept and taken into consideration.
+         * @param intercept
+         *      Recent changes are prioritised by integrating their duration over y = x + intercept
+         *      (the higher it is, the less prioritised recent changes are).
+         *
+         * @throws IllegalArgumentException
+         *      - horizon is not positive.
+         *      - intercept is NaN or negative.
+         */
+        WeightedMovingAverageAmbientFilter(String tag, int horizon, float intercept) {
+            super(tag, horizon);
+            validateArguments(intercept);
+            mIntercept = intercept;
+        }
+
+        /**
+         * See {@link AmbientFilter#dump base class}.
+         */
+        @Override
+        public void dump(PrintWriter writer) {
+            super.dump(writer);
+            writer.println("    mIntercept=" + mIntercept);
+        }
+
+        // Normalise the times to [t1=0, t2, ..., tN, now + PREDICTION_TIME], so the first change
+        // starts at 0 and the last change is predicted to last a bit, and divide them by 1000 as
+        // milliseconds are high enough to overflow.
+        // The weight of the value from t[i] to t[i+1] is the area under (A.K.A. the integral of)
+        // y = x + mIntercept from t[i] to t[i+1].
+        @Override
+        protected float filter(long time, RollingBuffer buffer) {
+            if (buffer.isEmpty()) {
+                return -1.0f;
+            }
+            float total = 0.0f;
+            float totalWeight = 0.0f;
+            final float[] weights = getWeights(time, buffer);
+            if (DEBUG && mLoggingEnabled) {
+                Slog.v(mTag, "filter: " + buffer + " => " + Arrays.toString(weights));
+            }
+            for (int i = 0; i < weights.length; i++) {
+                final float value = buffer.getValue(i);
+                final float weight = weights[i];
+                total += weight * value;
+                totalWeight += weight;
+            }
+            if (totalWeight == 0.0f) {
+                return buffer.getValue(buffer.size() - 1);
+            }
+            return total / totalWeight;
+        }
+
+        private void validateArguments(float intercept) {
+            if (Float.isNaN(intercept) || intercept < 0.0f) {
+                throw new IllegalArgumentException("intercept must be a non-negative number");
+            }
+        }
+
+        private float[] getWeights(long time, RollingBuffer buffer) {
+            float[] weights = new float[buffer.size()];
+            final long startTime = buffer.getTime(0);
+            float previousTime = 0.0f;
+            for (int i = 1; i < weights.length; i++) {
+                final float currentTime = (buffer.getTime(i) - startTime) / 1000.0f;
+                final float weight = calculateIntegral(previousTime, currentTime);
+                weights[i - 1] = weight;
+                previousTime = currentTime;
+            }
+            final float lastTime = (time + PREDICTION_TIME - startTime) / 1000.0f;
+            final float lastWeight = calculateIntegral(previousTime, lastTime);
+            weights[weights.length - 1] = lastWeight;
+            return weights;
+        }
+
+        private float calculateIntegral(float from, float to) {
+            return antiderivative(to) - antiderivative(from);
+        }
+
+        private float antiderivative(float x) {
+            // f(x) = x + c => F(x) = 1/2 * x^2 + c * x
+            return 0.5f * x * x + mIntercept * x;
+        }
+
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/AmbientSensor.java b/services/core/java/com/android/server/display/whitebalance/AmbientSensor.java
new file mode 100644
index 0000000..1707a62
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/AmbientSensor.java
@@ -0,0 +1,381 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.os.Handler;
+import android.util.Slog;
+
+import com.android.internal.util.Preconditions;
+import com.android.server.display.utils.History;
+
+import java.io.PrintWriter;
+
+/**
+ * The DisplayWhiteBalanceController uses the AmbientSensor to detect changes in the ambient
+ * brightness and color temperature.
+ *
+ * The AmbientSensor listens on an actual sensor, derives the ambient brightness or color
+ * temperature from its events, and calls back into the DisplayWhiteBalanceController to report it.
+ */
+abstract class AmbientSensor {
+
+    protected String mTag;
+    protected boolean mLoggingEnabled;
+
+    private final Handler mHandler;
+
+    protected final SensorManager mSensorManager;
+    protected Sensor mSensor;
+
+    private boolean mEnabled;
+
+    private int mRate; // Milliseconds
+
+    // The total events count and the most recent events are kept for debugging purposes.
+    private int mEventsCount;
+    private static final int HISTORY_SIZE = 50;
+    private History mEventsHistory;
+
+    /**
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param handler
+     *      The handler used to determine which thread to run on.
+     * @param sensorManager
+     *      The sensor manager used to acquire necessary sensors.
+     * @param rate
+     *      The sensor rate.
+     *
+     * @throws IllegalArgumentException
+     *      - rate is not positive.
+     * @throws NullPointerException
+     *      - handler is null;
+     *      - sensorManager is null.
+     * @throws IllegalStateException
+     *      - Cannot find the necessary sensor.
+     */
+    AmbientSensor(String tag, @NonNull Handler handler, @NonNull SensorManager sensorManager,
+            int rate) {
+        validateArguments(handler, sensorManager, rate);
+        mTag = tag;
+        mLoggingEnabled = false;
+        mHandler = handler;
+        mSensorManager = sensorManager;
+        mEnabled = false;
+        mRate = rate;
+        mEventsCount = 0;
+        mEventsHistory = new History(HISTORY_SIZE);
+    }
+
+    /**
+     * Enable/disable the sensor.
+     *
+     * @param enabled
+     *      Whether the sensor should be on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setEnabled(boolean enabled) {
+        if (enabled) {
+            return enable();
+        } else {
+            return disable();
+        }
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging should be on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        return true;
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The PrintWriter used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("  " + mTag);
+        writer.println("    mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("    mHandler=" + mHandler);
+        writer.println("    mSensorManager=" + mSensorManager);
+        writer.println("    mSensor=" + mSensor);
+        writer.println("    mEnabled=" + mEnabled);
+        writer.println("    mRate=" + mRate);
+        writer.println("    mEventsCount=" + mEventsCount);
+        writer.println("    mEventsHistory=" + mEventsHistory);
+    }
+
+
+    private static void validateArguments(Handler handler, SensorManager sensorManager, int rate) {
+        Preconditions.checkNotNull(handler, "handler cannot be null");
+        Preconditions.checkNotNull(sensorManager, "sensorManager cannot be null");
+        if (rate <= 0) {
+            throw new IllegalArgumentException("rate must be positive");
+        }
+    }
+
+    protected abstract void update(float value);
+
+    private boolean enable() {
+        if (mEnabled) {
+            return false;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "enabling");
+        }
+        mEnabled = true;
+        startListening();
+        return true;
+    }
+
+    private boolean disable() {
+        if (!mEnabled) {
+            return false;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "disabling");
+        }
+        mEnabled = false;
+        mEventsCount = 0;
+        stopListening();
+        return true;
+    }
+
+    private void startListening() {
+        if (mSensorManager == null) {
+            return;
+        }
+        mSensorManager.registerListener(mListener, mSensor, mRate * 1000, mHandler);
+    }
+
+    private void stopListening() {
+        if (mSensorManager == null) {
+            return;
+        }
+        mSensorManager.unregisterListener(mListener);
+    }
+
+    private void handleNewEvent(float value) {
+        // This shouldn't really happen, except for the race condition where the sensor is disabled
+        // with an event already in the handler queue, in which case we discard that event.
+        if (!mEnabled) {
+            return;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "handle new event: " + value);
+        }
+        mEventsCount++;
+        mEventsHistory.add(value);
+        update(value);
+    }
+
+    private SensorEventListener mListener = new SensorEventListener() {
+
+        @Override
+        public void onSensorChanged(SensorEvent event) {
+            final float value = event.values[0];
+            handleNewEvent(value);
+        }
+
+        @Override
+        public void onAccuracyChanged(Sensor sensor, int accuracy) {
+            // Not used.
+        }
+
+    };
+
+    /**
+     * A sensor that reports the ambient brightness.
+     */
+    static class AmbientBrightnessSensor extends AmbientSensor {
+
+        private static final String TAG = "AmbientBrightnessSensor";
+
+        // To decouple the DisplayWhiteBalanceController from the AmbientBrightnessSensor, the
+        // DWBC implements Callbacks and passes itself to the ABS so it can call back into it
+        // without knowing about it.
+        @Nullable
+        private Callbacks mCallbacks;
+
+        /**
+         * @param handler
+         *      The handler used to determine which thread to run on.
+         * @param sensorManager
+         *      The sensor manager used to acquire necessary sensors.
+         * @param rate
+         *      The sensor rate.
+         *
+         * @throws IllegalArgumentException
+         *      - rate is not positive.
+         * @throws NullPointerException
+         *      - handler is null;
+         *      - sensorManager is null.
+         * @throws IllegalStateException
+         *      - Cannot find the light sensor.
+         */
+        AmbientBrightnessSensor(@NonNull Handler handler, @NonNull SensorManager sensorManager,
+                int rate) {
+            super(TAG, handler, sensorManager, rate);
+            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
+            if (mSensor == null) {
+                throw new IllegalStateException("cannot find light sensor");
+            }
+            mCallbacks = null;
+        }
+
+        /**
+         * Set an object to call back to when the ambient brightness changes.
+         *
+         * @param callbacks
+         *      The object to call back to.
+         *
+         * @return Whether the method succeeded or not.
+         */
+        public boolean setCallbacks(Callbacks callbacks) {
+            if (mCallbacks == callbacks) {
+                return false;
+            }
+            mCallbacks = callbacks;
+            return true;
+        }
+
+        /**
+         * See {@link AmbientSensor#dump base class}.
+         */
+        @Override
+        public void dump(PrintWriter writer) {
+            super.dump(writer);
+            writer.println("    mCallbacks=" + mCallbacks);
+        }
+
+        interface Callbacks {
+            void onAmbientBrightnessChanged(float value);
+        }
+
+        @Override
+        protected void update(float value) {
+            if (mCallbacks != null) {
+                mCallbacks.onAmbientBrightnessChanged(value);
+            }
+        }
+
+    }
+
+    /**
+     * A sensor that reports the ambient color temperature.
+     */
+    static class AmbientColorTemperatureSensor extends AmbientSensor {
+
+        private static final String TAG = "AmbientColorTemperatureSensor";
+
+        // To decouple the DisplayWhiteBalanceController from the
+        // AmbientColorTemperatureSensor, the DWBC implements Callbacks and passes itself to the
+        // ACTS so it can call back into it without knowing about it.
+        @Nullable
+        private Callbacks mCallbacks;
+
+        /**
+         * @param handler
+         *      The handler used to determine which thread to run on.
+         * @param sensorManager
+         *      The sensor manager used to acquire necessary sensors.
+         * @param name
+         *      The color sensor name.
+         * @param rate
+         *      The sensor rate.
+         *
+         * @throws IllegalArgumentException
+         *      - rate is not positive.
+         * @throws NullPointerException
+         *      - handler is null;
+         *      - sensorManager is null.
+         * @throws IllegalStateException
+         *      - Cannot find the color sensor.
+         */
+        AmbientColorTemperatureSensor(@NonNull Handler handler,
+                @NonNull SensorManager sensorManager, String name, int rate) {
+            super(TAG, handler, sensorManager, rate);
+            mSensor = null;
+            for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) {
+                if (sensor.getStringType().equals(name)) {
+                    mSensor = sensor;
+                    break;
+                }
+            }
+            if (mSensor == null) {
+                throw new IllegalStateException("cannot find sensor " + name);
+            }
+            mCallbacks = null;
+        }
+
+        /**
+         * Set an object to call back to when the ambient color temperature changes.
+         *
+         * @param callbacks
+         *      The object to call back to.
+         *
+         * @return Whether the method succeeded or not.
+         */
+        public boolean setCallbacks(Callbacks callbacks) {
+            if (mCallbacks == callbacks) {
+                return false;
+            }
+            mCallbacks = callbacks;
+            return true;
+        }
+
+        /**
+         * See {@link AmbientSensor#dump base class}.
+         */
+        @Override
+        public void dump(PrintWriter writer) {
+            super.dump(writer);
+            writer.println("    mCallbacks=" + mCallbacks);
+        }
+
+        interface Callbacks {
+            void onAmbientColorTemperatureChanged(float value);
+        }
+
+        @Override
+        protected void update(float value) {
+            if (mCallbacks != null) {
+                mCallbacks.onAmbientColorTemperatureChanged(value);
+            }
+        }
+
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
new file mode 100644
index 0000000..7ae00af
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -0,0 +1,385 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.annotation.NonNull;
+import android.util.Slog;
+
+import com.android.internal.util.Preconditions;
+import com.android.server.LocalServices;
+import com.android.server.display.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.utils.History;
+
+import java.io.PrintWriter;
+
+/**
+ * The DisplayWhiteBalanceController drives display white-balance (automatically correcting the
+ * screen color temperature depending on the ambient color temperature).
+ *
+ * The DisplayWhiteBalanceController:
+ * - Uses the AmbientColorTemperatureSensor to detect changes in the ambient color temperature;
+ * - Uses the AmbientColorTemperatureFilter to average these changes over time, filter out the
+ *   noise, and arrive at an estimate of the actual ambient color temperature;
+ * - Uses the DisplayWhiteBalanceThrottler to decide whether the screen color tempearture should be
+ *   updated, suppressing changes that are too frequent or too minor.
+ */
+public class DisplayWhiteBalanceController implements
+        AmbientSensor.AmbientBrightnessSensor.Callbacks,
+        AmbientSensor.AmbientColorTemperatureSensor.Callbacks {
+
+    protected static final String TAG = "DisplayWhiteBalanceController";
+    protected boolean mLoggingEnabled;
+
+    private boolean mEnabled;
+
+    // To decouple the DisplayPowerController from the DisplayWhiteBalanceController, the DPC
+    // implements Callbacks and passes itself to the DWBC so it can call back into it without
+    // knowing about it.
+    private Callbacks mCallbacks;
+
+    private AmbientSensor.AmbientBrightnessSensor mBrightnessSensor;
+    private AmbientFilter mBrightnessFilter;
+    private AmbientSensor.AmbientColorTemperatureSensor mColorTemperatureSensor;
+    private AmbientFilter mColorTemperatureFilter;
+    private DisplayWhiteBalanceThrottler mThrottler;
+
+    // When the brightness drops below a certain threshold, it affects the color temperature
+    // accuracy, so we fall back to a fixed ambient color temperature.
+    private final float mLowLightAmbientBrightnessThreshold;
+    private final float mLowLightAmbientColorTemperature;
+
+    private float mAmbientColorTemperature;
+    private float mPendingAmbientColorTemperature;
+    private float mLastAmbientColorTemperature;
+
+    private ColorDisplayServiceInternal mColorDisplayServiceInternal;
+
+    // The most recent ambient color temperature values are kept for debugging purposes.
+    private static final int HISTORY_SIZE = 50;
+    private History mAmbientColorTemperatureHistory;
+
+    // Override the ambient color temperature for debugging purposes.
+    private float mAmbientColorTemperatureOverride;
+
+    /**
+     * @param brightnessSensor
+     *      The sensor used to detect changes in the ambient brightness.
+     * @param brightnessFilter
+     *      The filter used to avergae ambient brightness changes over time, filter out the noise
+     *      and arrive at an estimate of the actual ambient brightness.
+     * @param colorTemperatureSensor
+     *      The sensor used to detect changes in the ambient color temperature.
+     * @param colorTemperatureFilter
+     *      The filter used to average ambient color temperature changes over time, filter out the
+     *      noise and arrive at an estimate of the actual ambient color temperature.
+     * @param throttler
+     *      The throttler used to determine whether the new screen color temperature should be
+     *      updated or not.
+     * @param lowLightAmbientBrightnessThreshold
+     *      The ambient brightness threshold beneath which we fall back to a fixed ambient color
+     *      temperature.
+     * @param lowLightAmbientColorTemperature
+     *      The ambient color temperature to which we fall back when the ambient brightness drops
+     *      beneath a certain threshold.
+     *
+     * @throws NullPointerException
+     *      - brightnessSensor is null;
+     *      - brightnessFilter is null;
+     *      - colorTemperatureSensor is null;
+     *      - colorTemperatureFilter is null;
+     *      - throttler is null.
+     */
+    public DisplayWhiteBalanceController(
+            @NonNull AmbientSensor.AmbientBrightnessSensor brightnessSensor,
+            @NonNull AmbientFilter brightnessFilter,
+            @NonNull AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor,
+            @NonNull AmbientFilter colorTemperatureFilter,
+            @NonNull DisplayWhiteBalanceThrottler throttler,
+            float lowLightAmbientBrightnessThreshold, float lowLightAmbientColorTemperature) {
+        validateArguments(brightnessSensor, brightnessFilter, colorTemperatureSensor,
+                colorTemperatureFilter, throttler);
+        mLoggingEnabled = false;
+        mEnabled = false;
+        mCallbacks = null;
+        mBrightnessSensor = brightnessSensor;
+        mBrightnessFilter = brightnessFilter;
+        mColorTemperatureSensor = colorTemperatureSensor;
+        mColorTemperatureFilter = colorTemperatureFilter;
+        mThrottler = throttler;
+        mLowLightAmbientBrightnessThreshold = lowLightAmbientBrightnessThreshold;
+        mLowLightAmbientColorTemperature = lowLightAmbientColorTemperature;
+        mAmbientColorTemperature = -1.0f;
+        mPendingAmbientColorTemperature = -1.0f;
+        mLastAmbientColorTemperature = -1.0f;
+        mAmbientColorTemperatureHistory = new History(HISTORY_SIZE);
+        mAmbientColorTemperatureOverride = -1.0f;
+        mColorDisplayServiceInternal = LocalServices.getService(ColorDisplayServiceInternal.class);
+    }
+
+    /**
+     * Enable/disable the controller.
+     *
+     * @param enabled
+     *      Whether the controller should be on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setEnabled(boolean enabled) {
+        if (enabled) {
+            return enable();
+        } else {
+            return disable();
+        }
+    }
+
+    /**
+     * Set an object to call back to when the screen color temperature should be updated.
+     *
+     * @param callbacks
+     *      The object to call back to.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setCallbacks(Callbacks callbacks) {
+        if (mCallbacks == callbacks) {
+            return false;
+        }
+        mCallbacks = callbacks;
+        return true;
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging should be on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        mBrightnessSensor.setLoggingEnabled(loggingEnabled);
+        mBrightnessFilter.setLoggingEnabled(loggingEnabled);
+        mColorTemperatureSensor.setLoggingEnabled(loggingEnabled);
+        mColorTemperatureFilter.setLoggingEnabled(loggingEnabled);
+        mThrottler.setLoggingEnabled(loggingEnabled);
+        return true;
+    }
+
+    /**
+     * Set the ambient color temperature override.
+     *
+     * This is only applied when the ambient color temperature changes or is updated (in which case
+     * it overrides the ambient color temperature estimate); in other words, it doesn't necessarily
+     * change the screen color temperature immediately.
+     *
+     * @param ambientColorTemperatureOverride
+     *      The ambient color temperature override.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setAmbientColorTemperatureOverride(float ambientColorTemperatureOverride) {
+        if (mAmbientColorTemperatureOverride == ambientColorTemperatureOverride) {
+            return false;
+        }
+        mAmbientColorTemperatureOverride = ambientColorTemperatureOverride;
+        return true;
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The writer used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("DisplayWhiteBalanceController");
+        writer.println("  mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("  mEnabled=" + mEnabled);
+        writer.println("  mCallbacks=" + mCallbacks);
+        mBrightnessSensor.dump(writer);
+        mBrightnessFilter.dump(writer);
+        mColorTemperatureSensor.dump(writer);
+        mColorTemperatureFilter.dump(writer);
+        mThrottler.dump(writer);
+        writer.println("  mLowLightAmbientBrightnessThreshold="
+                + mLowLightAmbientBrightnessThreshold);
+        writer.println("  mLowLightAmbientColorTemperature=" + mLowLightAmbientColorTemperature);
+        writer.println("  mAmbientColorTemperature=" + mAmbientColorTemperature);
+        writer.println("  mPendingAmbientColorTemperature=" + mPendingAmbientColorTemperature);
+        writer.println("  mLastAmbientColorTemperature=" + mLastAmbientColorTemperature);
+        writer.println("  mAmbientColorTemperatureHistory=" + mAmbientColorTemperatureHistory);
+        writer.println("  mAmbientColorTemperatureOverride=" + mAmbientColorTemperatureOverride);
+    }
+
+    @Override // AmbientSensor.AmbientBrightnessSensor.Callbacks
+    public void onAmbientBrightnessChanged(float value) {
+        final long time = System.currentTimeMillis();
+        mBrightnessFilter.addValue(time, value);
+        updateAmbientColorTemperature();
+    }
+
+    @Override // AmbientSensor.AmbientColorTemperatureSensor.Callbacks
+    public void onAmbientColorTemperatureChanged(float value) {
+        final long time = System.currentTimeMillis();
+        mColorTemperatureFilter.addValue(time, value);
+        updateAmbientColorTemperature();
+    }
+
+    /**
+     * Updates the ambient color temperature.
+     */
+    public void updateAmbientColorTemperature() {
+        final long time = System.currentTimeMillis();
+        float ambientColorTemperature = mColorTemperatureFilter.getEstimate(time);
+
+        final float ambientBrightness = mBrightnessFilter.getEstimate(time);
+        if (ambientBrightness < mLowLightAmbientBrightnessThreshold) {
+            if (mLoggingEnabled) {
+                Slog.d(TAG, "low light ambient brightness: " + ambientBrightness + " < "
+                        + mLowLightAmbientBrightnessThreshold
+                        + ", falling back to fixed ambient color temperature: "
+                        + ambientColorTemperature + " => " + mLowLightAmbientColorTemperature);
+            }
+            ambientColorTemperature = mLowLightAmbientColorTemperature;
+        }
+
+        if (mAmbientColorTemperatureOverride != -1.0f) {
+            if (mLoggingEnabled) {
+                Slog.d(TAG, "override ambient color temperature: " + ambientColorTemperature
+                        + " => " + mAmbientColorTemperatureOverride);
+            }
+            ambientColorTemperature = mAmbientColorTemperatureOverride;
+        }
+
+        // When the screen color temperature needs to be updated, we call DisplayPowerController to
+        // call our updateColorTemperature. The reason we don't call it directly is that we want
+        // all changes to the system to happen in a predictable order in DPC's main loop
+        // (updatePowerState).
+        if (ambientColorTemperature == -1.0f || mThrottler.throttle(ambientColorTemperature)) {
+            return;
+        }
+
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "pending ambient color temperature: " + ambientColorTemperature);
+        }
+        mPendingAmbientColorTemperature = ambientColorTemperature;
+        if (mCallbacks != null) {
+            mCallbacks.updateWhiteBalance();
+        }
+    }
+
+    /**
+     * Updates the screen color temperature.
+     */
+    public void updateScreenColorTemperature() {
+        float ambientColorTemperature = -1.0f;
+
+        // If both the pending and the current ambient color temperatures are -1, it means the DWBC
+        // was just enabled, and we use the last ambient color temperature until new sensor events
+        // give us a better estimate.
+        if (mAmbientColorTemperature == -1.0f && mPendingAmbientColorTemperature == -1.0f) {
+            ambientColorTemperature = mLastAmbientColorTemperature;
+        }
+
+        // Otherwise, we use the pending ambient color temperature, but only if it's non-trivial
+        // and different than the current one.
+        if (mPendingAmbientColorTemperature != -1.0f
+                && mPendingAmbientColorTemperature != mAmbientColorTemperature) {
+            ambientColorTemperature = mPendingAmbientColorTemperature;
+        }
+
+        if (ambientColorTemperature == -1.0f) {
+            return;
+        }
+
+        mAmbientColorTemperature = ambientColorTemperature;
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "ambient color temperature: " + mAmbientColorTemperature);
+        }
+        mPendingAmbientColorTemperature = -1.0f;
+        mAmbientColorTemperatureHistory.add(mAmbientColorTemperature);
+        mColorDisplayServiceInternal.setDisplayWhiteBalanceColorTemperature(
+                (int) mAmbientColorTemperature);
+        mLastAmbientColorTemperature = mAmbientColorTemperature;
+    }
+
+    /**
+     * The DisplayWhiteBalanceController decouples itself from its parent (DisplayPowerController)
+     * by providing this interface to implement (and a method to set its callbacks object), and
+     * calling these methods.
+     */
+    public interface Callbacks {
+
+        /**
+         * Called whenever the display white-balance state has changed.
+         *
+         * Usually, this means the estimated ambient color temperature has changed enough, and the
+         * screen color temperature should be updated; but it is also called by
+         */
+        void updateWhiteBalance();
+    }
+
+    private void validateArguments(AmbientSensor.AmbientBrightnessSensor brightnessSensor,
+            AmbientFilter brightnessFilter,
+            AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor,
+            AmbientFilter colorTemperatureFilter,
+            DisplayWhiteBalanceThrottler throttler) {
+        Preconditions.checkNotNull(brightnessSensor, "brightnessSensor must not be null");
+        Preconditions.checkNotNull(brightnessFilter, "brightnessFilter must not be null");
+        Preconditions.checkNotNull(colorTemperatureSensor,
+                "colorTemperatureSensor must not be null");
+        Preconditions.checkNotNull(colorTemperatureFilter,
+                "colorTemperatureFilter must not be null");
+        Preconditions.checkNotNull(throttler, "throttler cannot be null");
+    }
+
+    private boolean enable() {
+        if (mEnabled) {
+            return false;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "enabling");
+        }
+        mEnabled = true;
+        mBrightnessSensor.setEnabled(true);
+        mColorTemperatureSensor.setEnabled(true);
+        return true;
+    }
+
+    private boolean disable() {
+        if (!mEnabled) {
+            return false;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "disabling");
+        }
+        mEnabled = false;
+        mBrightnessSensor.setEnabled(false);
+        mBrightnessFilter.clear();
+        mColorTemperatureSensor.setEnabled(false);
+        mColorTemperatureFilter.clear();
+        mThrottler.clear();
+        mAmbientColorTemperature = -1.0f;
+        mPendingAmbientColorTemperature = -1.0f;
+        return true;
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
new file mode 100644
index 0000000..fd78ddb
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.hardware.SensorManager;
+import android.os.Handler;
+import android.util.TypedValue;
+
+/**
+ * The DisplayWhiteBalanceFactory creates and configures an DisplayWhiteBalanceController.
+ */
+public class DisplayWhiteBalanceFactory {
+
+    private static final String BRIGHTNESS_FILTER_TAG = "AmbientBrightnessFilter";
+    private static final String COLOR_TEMPERATURE_FILTER_TAG = "AmbientColorTemperatureFilter";
+
+    /**
+     * Create and configure an DisplayWhiteBalanceController.
+     *
+     * @param handler
+     *      The handler used to determine which thread to run on.
+     * @param sensorManager
+     *      The sensor manager used to acquire necessary sensors.
+     * @param resources
+     *      The resources used to configure the various components.
+     *
+     * @return An DisplayWhiteBalanceController.
+     *
+     * @throws NullPointerException
+     *      - handler is null;
+     *      - sensorManager is null.
+     * @throws Resources.NotFoundException
+     *      - Configurations are missing.
+     * @throws IllegalArgumentException
+     *      - Configurations are invalid.
+     * @throws IllegalStateException
+     *      - Cannot find the necessary sensors.
+     */
+    public static DisplayWhiteBalanceController create(Handler handler,
+            SensorManager sensorManager, Resources resources) {
+        final AmbientSensor.AmbientBrightnessSensor brightnessSensor =
+                createBrightnessSensor(handler, sensorManager, resources);
+        final AmbientFilter brightnessFilter = createBrightnessFilter(resources);
+        final AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor =
+                createColorTemperatureSensor(handler, sensorManager, resources);
+        final AmbientFilter colorTemperatureFilter = createColorTemperatureFilter(resources);
+        final DisplayWhiteBalanceThrottler throttler = createThrottler(resources);
+        final float lowLightAmbientBrightnessThreshold = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceLowLightAmbientBrightnessThreshold);
+        final float lowLightAmbientColorTemperature = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceLowLightAmbientColorTemperature);
+        final DisplayWhiteBalanceController controller = new DisplayWhiteBalanceController(
+                brightnessSensor, brightnessFilter, colorTemperatureSensor, colorTemperatureFilter,
+                throttler, lowLightAmbientBrightnessThreshold, lowLightAmbientColorTemperature);
+        brightnessSensor.setCallbacks(controller);
+        colorTemperatureSensor.setCallbacks(controller);
+        return controller;
+    }
+
+    // Instantiation is disabled.
+    private DisplayWhiteBalanceFactory() { }
+
+    private static AmbientSensor.AmbientBrightnessSensor createBrightnessSensor(Handler handler,
+            SensorManager sensorManager, Resources resources) {
+        final int rate = resources.getInteger(
+                com.android.internal.R.integer.config_displayWhiteBalanceBrightnessSensorRate);
+        return new AmbientSensor.AmbientBrightnessSensor(handler, sensorManager, rate);
+    }
+
+    private static AmbientFilter createBrightnessFilter(Resources resources) {
+        final int horizon = resources.getInteger(
+                com.android.internal.R.integer.config_displayWhiteBalanceBrightnessFilterHorizon);
+        final float intercept = getFloat(resources,
+                com.android.internal.R.dimen.config_displayWhiteBalanceBrightnessFilterIntercept);
+        if (!Float.isNaN(intercept)) {
+            return new AmbientFilter.WeightedMovingAverageAmbientFilter(
+                    BRIGHTNESS_FILTER_TAG, horizon, intercept);
+        }
+        throw new IllegalArgumentException("missing configurations: "
+                + "expected config_displayWhiteBalanceBrightnessFilterIntercept");
+    }
+
+
+    private static AmbientSensor.AmbientColorTemperatureSensor createColorTemperatureSensor(
+            Handler handler, SensorManager sensorManager, Resources resources) {
+        final String name = resources.getString(
+                com.android.internal.R.string
+                .config_displayWhiteBalanceColorTemperatureSensorName);
+        final int rate = resources.getInteger(
+                com.android.internal.R.integer
+                .config_displayWhiteBalanceColorTemperatureSensorRate);
+        return new AmbientSensor.AmbientColorTemperatureSensor(handler, sensorManager, name, rate);
+    }
+
+    private static AmbientFilter createColorTemperatureFilter(Resources resources) {
+        final int horizon = resources.getInteger(
+                com.android.internal.R.integer
+                .config_displayWhiteBalanceColorTemperatureFilterHorizon);
+        final float intercept = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceColorTemperatureFilterIntercept);
+        if (!Float.isNaN(intercept)) {
+            return new AmbientFilter.WeightedMovingAverageAmbientFilter(
+                    COLOR_TEMPERATURE_FILTER_TAG, horizon, intercept);
+        }
+        throw new IllegalArgumentException("missing configurations: "
+                + "expected config_displayWhiteBalanceColorTemperatureFilterIntercept");
+    }
+
+    private static DisplayWhiteBalanceThrottler createThrottler(Resources resources) {
+        final int increaseDebounce = resources.getInteger(
+                com.android.internal.R.integer.config_displayWhiteBalanceDecreaseDebounce);
+        final int decreaseDebounce = resources.getInteger(
+                com.android.internal.R.integer.config_displayWhiteBalanceIncreaseDebounce);
+        final float[] baseThresholds = getFloatArray(resources,
+                com.android.internal.R.array.config_displayWhiteBalanceBaseThresholds);
+        final float[] increaseThresholds = getFloatArray(resources,
+                com.android.internal.R.array.config_displayWhiteBalanceIncreaseThresholds);
+        final float[] decreaseThresholds = getFloatArray(resources,
+                com.android.internal.R.array.config_displayWhiteBalanceDecreaseThresholds);
+        return new DisplayWhiteBalanceThrottler(increaseDebounce, decreaseDebounce, baseThresholds,
+                increaseThresholds, decreaseThresholds);
+    }
+
+    private static float getFloat(Resources resources, int id) {
+        TypedValue value = new TypedValue();
+        resources.getValue(id, value, true /* resolveRefs */);
+        if (value.type != TypedValue.TYPE_FLOAT) {
+            return Float.NaN;
+        }
+        return value.getFloat();
+    }
+
+    private static float[] getFloatArray(Resources resources, int id) {
+        TypedArray array = resources.obtainTypedArray(id);
+        try {
+            if (array.length() == 0) {
+                return null;
+            }
+            float[] values = new float[array.length()];
+            for (int i = 0; i < values.length; i++) {
+                values[i] = array.getFloat(i, Float.NaN);
+                if (Float.isNaN(values[i])) {
+                    return null;
+                }
+            }
+            return values;
+        } finally {
+            array.recycle();
+        }
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
new file mode 100644
index 0000000..a53e91c
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
@@ -0,0 +1,230 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.UserHandle;
+import android.provider.Settings.Secure;
+import android.util.Slog;
+
+import com.android.internal.util.Preconditions;
+import com.android.server.LocalServices;
+import com.android.server.display.ColorDisplayService;
+import com.android.server.display.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.whitebalance.DisplayWhiteBalanceController.Callbacks;
+
+import java.io.PrintWriter;
+
+/**
+ * The DisplayWhiteBalanceSettings holds the state of all the settings related to
+ * display white-balance, and can be used to decide whether to enable the
+ * DisplayWhiteBalanceController.
+ */
+public class DisplayWhiteBalanceSettings implements
+        ColorDisplayService.DisplayWhiteBalanceListener {
+
+    protected static final String TAG = "DisplayWhiteBalanceSettings";
+    protected boolean mLoggingEnabled;
+
+    private static final String SETTING_URI = Secure.DISPLAY_WHITE_BALANCE_ENABLED;
+    private static final int SETTING_DEFAULT = 0;
+    private static final int SETTING_ENABLED = 1;
+
+    private static final int MSG_SET_ACTIVE = 1;
+
+    private final Context mContext;
+    private final Handler mHandler;
+    private final SettingsObserver mSettingsObserver;
+
+    // To decouple the DisplayPowerController from the DisplayWhiteBalanceSettings, the DPC
+    // implements Callbacks and passes itself to the DWBS so it can call back into it without
+    // knowing about it.
+    private Callbacks mCallbacks;
+
+    private int mSetting;
+    private boolean mActive;
+
+    /**
+     * @param context
+     *      The context in which display white-balance is used.
+     * @param handler
+     *      The handler used to determine which thread to run on.
+     *
+     * @throws NullPointerException
+     *      - context is null;
+     *      - handler is null.
+     */
+    public DisplayWhiteBalanceSettings(@NonNull Context context, @NonNull Handler handler) {
+        validateArguments(context, handler);
+        mLoggingEnabled = false;
+        mContext = context;
+        mHandler = new DisplayWhiteBalanceSettingsHandler(handler.getLooper());
+        mSettingsObserver = new SettingsObserver(mHandler);
+        mSetting = getSetting();
+        mActive = false;
+        mCallbacks = null;
+
+        mContext.getContentResolver().registerContentObserver(
+                Secure.getUriFor(SETTING_URI), false /* notifyForDescendants */, mSettingsObserver,
+                UserHandle.USER_ALL);
+
+        ColorDisplayServiceInternal cds =
+                LocalServices.getService(ColorDisplayServiceInternal.class);
+        cds.setDisplayWhiteBalanceListener(this);
+    }
+
+    /**
+     * Set an object to call back to when the display white balance state should be updated.
+     *
+     * @param callbacks
+     *      The object to call back to.
+     *
+     * @return Whether the method suceeded or not.
+     */
+    public boolean setCallbacks(Callbacks callbacks) {
+        if (mCallbacks == callbacks) {
+            return false;
+        }
+        mCallbacks = callbacks;
+        return true;
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging should be on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        return true;
+    }
+
+    /**
+     * Returns whether display white-balance is enabled.
+     *
+     * @return Whether display white-balance is enabled.
+     */
+    public boolean isEnabled() {
+        return (mSetting == SETTING_ENABLED) && mActive;
+    }
+
+    /**
+     * Re-evaluate state after switching to a new user.
+     */
+    public void onSwitchUser() {
+        handleSettingChange();
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The writer used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("DisplayWhiteBalanceSettings");
+        writer.println("  mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("  mContext=" + mContext);
+        writer.println("  mHandler=" + mHandler);
+        writer.println("  mSettingsObserver=" + mSettingsObserver);
+        writer.println("  mSetting=" + mSetting);
+        writer.println("  mActive=" + mActive);
+        writer.println("  mCallbacks=" + mCallbacks);
+    }
+
+    @Override
+    public void onDisplayWhiteBalanceStatusChanged(boolean active) {
+        Message msg = mHandler.obtainMessage(MSG_SET_ACTIVE, active ? 1 : 0, 0);
+        msg.sendToTarget();
+    }
+
+    private void validateArguments(Context context, Handler handler) {
+        Preconditions.checkNotNull(context, "context must not be null");
+        Preconditions.checkNotNull(handler, "handler must not be null");
+    }
+
+    private int getSetting() {
+        return Secure.getIntForUser(mContext.getContentResolver(), SETTING_URI, SETTING_DEFAULT,
+                UserHandle.USER_CURRENT);
+    }
+
+    private void handleSettingChange() {
+        final int setting = getSetting();
+        if (mSetting == setting) {
+            return;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "Setting: " + setting);
+        }
+        mSetting = setting;
+        if (mCallbacks != null) {
+            mCallbacks.updateWhiteBalance();
+        }
+    }
+
+    private void setActive(boolean active) {
+        if (mActive == active) {
+            return;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(TAG, "Active: " + active);
+        }
+        mActive = active;
+        if (mCallbacks != null) {
+            mCallbacks.updateWhiteBalance();
+        }
+    }
+
+    private final class SettingsObserver extends ContentObserver {
+        SettingsObserver(Handler handler) {
+            super(handler);
+        }
+
+        @Override
+        public void onChange(boolean selfChange, Uri uri) {
+            handleSettingChange();
+        }
+    }
+
+    private final class DisplayWhiteBalanceSettingsHandler extends Handler {
+        DisplayWhiteBalanceSettingsHandler(Looper looper) {
+            super(looper, null, true /* async */);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MSG_SET_ACTIVE:
+                    setActive(msg.arg1 != 0);
+                    break;
+            }
+        }
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceThrottler.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceThrottler.java
new file mode 100644
index 0000000..c1f0e98
--- /dev/null
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceThrottler.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display.whitebalance;
+
+import android.util.Slog;
+
+import java.io.PrintWriter;
+import java.util.Arrays;
+
+/**
+ * The DisplayWhiteBalanceController uses the DisplayWhiteBalanceThrottler to decide whether the
+ * screen color temperature should be updated, suppressing changes that are too frequent or too
+ * minor.
+ */
+class DisplayWhiteBalanceThrottler {
+
+    protected static final String TAG = "DisplayWhiteBalanceThrottler";
+    protected boolean mLoggingEnabled;
+
+    private int mIncreaseDebounce;  // Milliseconds
+    private int mDecreaseDebounce;  // Milliseconds
+    private long mLastTime;         // Milliseconds
+
+    private float[] mBaseThresholds;
+    private float[] mIncreaseThresholds;
+    private float[] mDecreaseThresholds;
+    private float mIncreaseThreshold;
+    private float mDecreaseThreshold;
+    private float mLastValue;
+
+    /**
+     * @param increaseDebounce
+     *      The debounce time for increasing (throttled if {@code time < lastTime + debounce}).
+     * @param decreaseDebounce
+     *      The debounce time for decreasing (throttled if {@code time < lastTime + debounce}).
+     * @param baseThresholds
+     *      The ambient color temperature values used to determine the threshold as the
+     *      corresponding value in increaseThresholds/decreaseThresholds.
+     * @param increaseThresholds
+     *      The increase threshold values (throttled if {@code value < value * (1 + threshold)}).
+     * @param decreaseThresholds
+     *      The decrease threshold values (throttled if {@code value > value * (1 - threshold)}).
+     *
+     * @throws IllegalArgumentException
+     *      - increaseDebounce is negative;
+     *      - decreaseDebounce is negative;
+     *      - baseThresholds to increaseThresholds is not a valid mapping*;
+     *      - baseThresholds to decreaseThresholds is not a valid mapping*;
+     *
+     *      (*) The x to y mapping is valid if:
+     *          - x and y are not null;
+     *          - x and y are not empty;
+     *          - x and y contain only non-negative numbers;
+     *          - x is strictly increasing.
+     */
+    DisplayWhiteBalanceThrottler(int increaseDebounce, int decreaseDebounce,
+            float[] baseThresholds, float[] increaseThresholds, float[] decreaseThresholds) {
+        validateArguments(increaseDebounce, decreaseDebounce, baseThresholds, increaseThresholds,
+                decreaseThresholds);
+        mLoggingEnabled = false;
+        mIncreaseDebounce = increaseDebounce;
+        mDecreaseDebounce = decreaseDebounce;
+        mBaseThresholds = baseThresholds;
+        mIncreaseThresholds = increaseThresholds;
+        mDecreaseThresholds = decreaseThresholds;
+        clear();
+    }
+
+    /**
+     * Check whether the ambient color temperature should be throttled.
+     *
+     * @param value
+     *      The ambient color temperature value.
+     *
+     * @return Whether the ambient color temperature should be throttled.
+     */
+    public boolean throttle(float value) {
+        if (mLastTime != -1 && (tooSoon(value) || tooClose(value))) {
+            return true;
+        }
+        computeThresholds(value);
+        mLastTime = System.currentTimeMillis();
+        mLastValue = value;
+        return false;
+    }
+
+    /**
+     * Clears the throttler state.
+     */
+    public void clear() {
+        mLastTime = -1;
+        mIncreaseThreshold = -1.0f;
+        mDecreaseThreshold = -1.0f;
+        mLastValue = -1.0f;
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging is on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        return true;
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The PrintWriter used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("  DisplayWhiteBalanceThrottler");
+        writer.println("    mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("    mIncreaseDebounce=" + mIncreaseDebounce);
+        writer.println("    mDecreaseDebounce=" + mDecreaseDebounce);
+        writer.println("    mLastTime=" + mLastTime);
+        writer.println("    mBaseThresholds=" + Arrays.toString(mBaseThresholds));
+        writer.println("    mIncreaseThresholds=" + Arrays.toString(mIncreaseThresholds));
+        writer.println("    mDecreaseThresholds=" + Arrays.toString(mDecreaseThresholds));
+        writer.println("    mIncreaseThreshold=" + mIncreaseThreshold);
+        writer.println("    mDecreaseThreshold=" + mDecreaseThreshold);
+        writer.println("    mLastValue=" + mLastValue);
+    }
+
+    private void validateArguments(float increaseDebounce, float decreaseDebounce,
+            float[] baseThresholds, float[] increaseThresholds, float[] decreaseThresholds) {
+        if (Float.isNaN(increaseDebounce) || increaseDebounce < 0.0f) {
+            throw new IllegalArgumentException("increaseDebounce must be a non-negative number.");
+        }
+        if (Float.isNaN(decreaseDebounce) || decreaseDebounce < 0.0f) {
+            throw new IllegalArgumentException("decreaseDebounce must be a non-negative number.");
+        }
+        if (!isValidMapping(baseThresholds, increaseThresholds)) {
+            throw new IllegalArgumentException(
+                    "baseThresholds to increaseThresholds is not a valid mapping.");
+        }
+        if (!isValidMapping(baseThresholds, decreaseThresholds)) {
+            throw new IllegalArgumentException(
+                    "baseThresholds to decreaseThresholds is not a valid mapping.");
+        }
+    }
+
+    private static boolean isValidMapping(float[] x, float[] y) {
+        if (x == null || y == null || x.length == 0 || y.length == 0 || x.length != y.length) {
+            return false;
+        }
+        float prevX = -1.0f;
+        for (int i = 0; i < x.length; i++) {
+            if (Float.isNaN(x[i]) || Float.isNaN(y[i]) || x[i] < 0 || prevX >= x[i]) {
+                return false;
+            }
+            prevX = x[i];
+        }
+        return true;
+    }
+
+    private boolean tooSoon(float value) {
+        final long time = System.currentTimeMillis();
+        final long earliestTime;
+        if (value > mLastValue) {
+            earliestTime = mLastTime + mIncreaseDebounce;
+        } else { // value <= mLastValue
+            earliestTime = mLastTime + mDecreaseDebounce;
+        }
+        final boolean tooSoon = time < earliestTime;
+        if (mLoggingEnabled) {
+            Slog.d(TAG, (tooSoon ? "too soon: " : "late enough: ") + time
+                    + (tooSoon ? " < " : " > ") + earliestTime);
+        }
+        return tooSoon;
+    }
+
+    private boolean tooClose(float value) {
+        final float threshold;
+        final boolean tooClose;
+        if (value > mLastValue) {
+            threshold = mIncreaseThreshold;
+            tooClose = value < threshold;
+        } else { // value <= mLastValue
+            threshold = mDecreaseThreshold;
+            tooClose = value > threshold;
+        }
+        if (mLoggingEnabled) {
+            Slog.d(TAG, (tooClose ? "too close: " : "far enough: ") + value
+                    + (value > threshold ? " > " : " < ") + threshold);
+        }
+        return tooClose;
+    }
+
+    private void computeThresholds(float value) {
+        final int index = getHighestIndexBefore(value, mBaseThresholds);
+        mIncreaseThreshold = value * (1.0f + mIncreaseThresholds[index]);
+        mDecreaseThreshold = value * (1.0f - mDecreaseThresholds[index]);
+    }
+
+    private int getHighestIndexBefore(float value, float[] values) {
+        for (int i = 0; i < values.length; i++) {
+            if (values[i] >= value) {
+                return i;
+            }
+        }
+        return values.length - 1;
+    }
+
+}
diff --git a/services/core/java/com/android/server/hdmi/Constants.java b/services/core/java/com/android/server/hdmi/Constants.java
index 297a418..7c42cc2 100644
--- a/services/core/java/com/android/server/hdmi/Constants.java
+++ b/services/core/java/com/android/server/hdmi/Constants.java
@@ -393,15 +393,6 @@
             "persist.sys.hdmi.property_sytem_audio_mode_audio_port";
 
     /**
-     * Property to indicate if a CEC audio device should forward volume keys when system audio mode
-     * is off.
-     *
-     * <p>Default is false.
-     */
-    static final String PROPERTY_CEC_AUDIO_DEVICE_FORWARD_VOLUME_KEYS_SYSTEM_AUDIO_MODE_OFF =
-            "persist.sys.hdmi.property_cec_audio_device_forward_volume_keys_system_audio_mode_off";
-
-    /**
      * Property to strip local audio of amplifier and use local speaker
      * when TV does not support system audio mode.
      *
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
index cac1a95..1ba0c52 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
@@ -20,6 +20,7 @@
 import static com.android.server.hdmi.Constants.USE_LAST_STATE_SYSTEM_AUDIO_CONTROL_ON_POWER_ON;
 
 import android.annotation.Nullable;
+import android.content.ActivityNotFoundException;
 import android.content.Intent;
 import android.hardware.hdmi.HdmiControlManager;
 import android.hardware.hdmi.HdmiDeviceInfo;
@@ -458,9 +459,19 @@
     @ServiceThreadOnly
     protected boolean handleGiveSystemAudioModeStatus(HdmiCecMessage message) {
         assertRunOnServiceThread();
+        // If the audio system is initiating the system audio mode on and TV asks the sam status at
+        // the same time, respond with true. Since we know TV supports sam in this situation.
+        // If the query comes from STB, we should respond with the current sam status and the STB
+        // should listen to the <Set System Audio Mode> broadcasting.
+        boolean isSystemAudioModeOnOrTurningOn = isSystemAudioActivated();
+        if (!isSystemAudioModeOnOrTurningOn
+                && message.getSource() == Constants.ADDR_TV
+                && hasAction(SystemAudioInitiationActionFromAvr.class)) {
+            isSystemAudioModeOnOrTurningOn = true;
+        }
         mService.sendCecCommand(
                 HdmiCecMessageBuilder.buildReportSystemAudioMode(
-                        mAddress, message.getSource(), mSystemAudioActivated));
+                        mAddress, message.getSource(), isSystemAudioModeOnOrTurningOn));
         return true;
     }
 
@@ -1075,20 +1086,28 @@
 
     // For device to switch to specific TvInput with corresponding URI.
     private void switchToTvInput(String uri) {
-        mService.getContext().startActivity(new Intent(Intent.ACTION_VIEW,
-                TvContract.buildChannelUriForPassthroughInput(uri))
-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+        try {
+            mService.getContext().startActivity(new Intent(Intent.ACTION_VIEW,
+                    TvContract.buildChannelUriForPassthroughInput(uri))
+                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+        } catch (ActivityNotFoundException e) {
+            Slog.e(TAG, "Can't find activity to switch to " + uri, e);
+        }
     }
 
     // For device using TvInput to switch to Home.
     private void switchToHomeTvInput() {
-        Intent activityIntent = new Intent(Intent.ACTION_MAIN)
-                .addCategory(Intent.CATEGORY_HOME)
-                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
-                        | Intent.FLAG_ACTIVITY_SINGLE_TOP
-                        | Intent.FLAG_ACTIVITY_NEW_TASK
-                        | Intent.FLAG_ACTIVITY_NO_ANIMATION);
-        mService.getContext().startActivity(activityIntent);
+        try {
+            Intent activityIntent = new Intent(Intent.ACTION_MAIN)
+                    .addCategory(Intent.CATEGORY_HOME)
+                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
+                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
+                    | Intent.FLAG_ACTIVITY_NEW_TASK
+                    | Intent.FLAG_ACTIVITY_NO_ANIMATION);
+            mService.getContext().startActivity(activityIntent);
+        } catch (ActivityNotFoundException e) {
+            Slog.e(TAG, "Can't find activity to switch to HOME", e);
+        }
     }
 
     @Override
@@ -1131,7 +1150,8 @@
         if (routingInformationPath == mService.getPhysicalAddress()) {
             HdmiLogger.debug("Current device can't assign valid physical address"
                     + "to devices under it any more. "
-                    + "It's physical address is " + routingInformationPath);
+                    + "It's physical address is "
+                    + routingInformationPath);
             return;
         }
         // Otherwise will switch to the current active port and broadcast routing information.
@@ -1208,5 +1228,4 @@
         pw.decreaseIndent();
         super.dump(pw);
     }
-
 }
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index f3a1e46..c5eccdf 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -1392,11 +1392,15 @@
         }
 
         @Override
+        @Nullable
         public HdmiDeviceInfo getActiveSource() {
             enforceAccessPermission();
             HdmiCecLocalDeviceTv tv = tv();
             if (tv == null) {
-                Slog.w(TAG, "Local tv device not available");
+                if (isTvDevice()) {
+                    Slog.e(TAG, "Local tv device not available.");
+                    return null;
+                }
                 if (isPlaybackDevice()) {
                     // if playback device itself is the active source,
                     // return its own device info.
@@ -1457,7 +1461,10 @@
                                     HdmiControlService.this, deviceId, callback));
                             return;
                         }
-                        Slog.w(TAG, "Local tv device not available");
+                        if (isTvDevice()) {
+                            Slog.e(TAG, "Local tv device not available");
+                            return;
+                        }
                         invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
                         return;
                     }
diff --git a/services/core/java/com/android/server/location/GnssLocationProvider.java b/services/core/java/com/android/server/location/GnssLocationProvider.java
index d346ddc..ab9f711 100644
--- a/services/core/java/com/android/server/location/GnssLocationProvider.java
+++ b/services/core/java/com/android/server/location/GnssLocationProvider.java
@@ -332,9 +332,6 @@
     // true if we started navigation
     private boolean mStarted;
 
-    // true if single shot request is in progress
-    private boolean mSingleShot;
-
     // capabilities of the GPS engine
     private int mEngineCapabilities;
 
@@ -455,7 +452,7 @@
 
             switch (action) {
                 case ALARM_WAKEUP:
-                    startNavigating(false);
+                    startNavigating();
                     break;
                 case ALARM_TIMEOUT:
                     hibernate();
@@ -852,10 +849,9 @@
      * allowed mode from properties.
      *
      * @param agpsEnabled whether AGPS is enabled by settings value
-     * @param singleShot  whether "singleshot" is needed
      * @return SUPL mode (MSA vs MSB vs STANDALONE)
      */
-    private int getSuplMode(boolean agpsEnabled, boolean singleShot) {
+    private int getSuplMode(boolean agpsEnabled) {
         if (agpsEnabled) {
             int suplMode = mGnssConfiguration.getSuplMode(0);
             if (suplMode == 0) {
@@ -867,14 +863,6 @@
             if (hasCapability(GPS_CAPABILITY_MSB) && (suplMode & AGPS_SUPL_MODE_MSB) != 0) {
                 return GPS_POSITION_MODE_MS_BASED;
             }
-            // for now, just as the legacy code did, we fallback to MS-Assisted if it is available,
-            // do fallback only for single-shot requests, because it is too expensive to do for
-            // periodic requests as well
-            if (singleShot
-                    && hasCapability(GPS_CAPABILITY_MSA)
-                    && (suplMode & AGPS_SUPL_MODE_MSA) != 0) {
-                return GPS_POSITION_MODE_MS_ASSISTED;
-            }
         }
         return GPS_POSITION_MODE_STANDALONE;
     }
@@ -965,22 +953,6 @@
             return;
         }
 
-        boolean singleShot = false;
-
-        // see if the request is for a single update
-        if (mProviderRequest.locationRequests != null
-                && mProviderRequest.locationRequests.size() > 0) {
-            // if any request has zero or more than one updates
-            // requested, then this is not single-shot mode
-            singleShot = true;
-
-            for (LocationRequest lr : mProviderRequest.locationRequests) {
-                if (lr.getNumUpdates() != 1) {
-                    singleShot = false;
-                }
-            }
-        }
-
         if (DEBUG) Log.d(TAG, "setRequest " + mProviderRequest);
         if (mProviderRequest.reportLocation && !mDisableGps && isEnabled()) {
             // update client uids
@@ -1003,7 +975,7 @@
                 }
             } else if (!mStarted) {
                 // start GPS
-                startNavigating(singleShot);
+                startNavigating();
             } else {
                 // GNSS Engine is already ON, but no GPS_CAPABILITY_SCHEDULING
                 mAlarmManager.cancel(mTimeoutIntent);
@@ -1148,13 +1120,12 @@
         }
     }
 
-    private void startNavigating(boolean singleShot) {
+    private void startNavigating() {
         if (!mStarted) {
-            if (DEBUG) Log.d(TAG, "startNavigating, singleShot is " + singleShot);
+            if (DEBUG) Log.d(TAG, "startNavigating");
             mTimeToFirstFix = 0;
             mLastFixTime = 0;
             mStarted = true;
-            mSingleShot = singleShot;
             mPositionMode = GPS_POSITION_MODE_STANDALONE;
             // Notify about suppressed output, if speed limit was previously exceeded.
             // Elsewhere, we check again with every speed output reported.
@@ -1166,7 +1137,7 @@
             boolean agpsEnabled =
                     (Settings.Global.getInt(mContext.getContentResolver(),
                             Settings.Global.ASSISTED_GPS_ENABLED, 1) != 0);
-            mPositionMode = getSuplMode(agpsEnabled, singleShot);
+            mPositionMode = getSuplMode(agpsEnabled);
 
             if (DEBUG) {
                 String mode;
@@ -1221,7 +1192,6 @@
         if (DEBUG) Log.d(TAG, "stopNavigating");
         if (mStarted) {
             mStarted = false;
-            mSingleShot = false;
             native_stop();
             mLastFixTime = 0;
             // native_stop() may reset the position mode in hardware.
@@ -1300,10 +1270,6 @@
             mGnssStatusListenerHelper.onFirstFix(mTimeToFirstFix);
         }
 
-        if (mSingleShot) {
-            stopNavigating();
-        }
-
         if (mStarted && mStatus != LocationProvider.AVAILABLE) {
             // For devices that use framework scheduling, a timer may be set to ensure we don't
             // spend too much power searching for a location, when the requested update rate is
diff --git a/services/core/java/com/android/server/media/MediaSessionServiceImpl.java b/services/core/java/com/android/server/media/MediaSessionServiceImpl.java
index 409060e..5c73178 100644
--- a/services/core/java/com/android/server/media/MediaSessionServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaSessionServiceImpl.java
@@ -42,6 +42,8 @@
 import android.media.AudioSystem;
 import android.media.IAudioService;
 import android.media.IRemoteVolumeController;
+import android.media.MediaController2;
+import android.media.Session2CommandGroup;
 import android.media.Session2Token;
 import android.media.session.IActiveSessionsListener;
 import android.media.session.ICallback;
@@ -57,6 +59,7 @@
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.HandlerExecutor;
 import android.os.IBinder;
 import android.os.Message;
 import android.os.PowerManager;
@@ -1011,50 +1014,17 @@
                 if (DEBUG) {
                     Log.d(TAG, "Session2 is created " + sessionToken);
                 }
-                if (pid != sessionToken.getPid()) {
-                    throw new SecurityException("Unexpected Session2Token's PID, expected=" + pid
-                            + " but actually=" + sessionToken.getPid());
-                }
                 if (uid != sessionToken.getUid()) {
                     throw new SecurityException("Unexpected Session2Token's UID, expected=" + uid
                             + " but actually=" + sessionToken.getUid());
                 }
-                int userId = UserHandle.getUserId(uid);
-                List<Session2Token> session2Tokens = mSession2TokensPerUser.get(userId);
-                if (session2Tokens.contains(sessionToken)) {
-                    if (DEBUG) {
-                        Log.d(TAG, "notifySession2Created(): Ignoring already existing token "
-                                + sessionToken);
-                    }
-                    return;
-                }
-                session2Tokens.add(sessionToken);
-                pushSession2TokensChangedLocked(userId);
-            } finally {
-                Binder.restoreCallingIdentity(token);
-            }
-        }
-
-        @Override
-        public void notifySession2Destroyed(Session2Token sessionToken) throws RemoteException {
-            final int pid = Binder.getCallingPid();
-            final int uid = Binder.getCallingUid();
-            final long token = Binder.clearCallingIdentity();
-            try {
-                if (DEBUG) {
-                    Log.d(TAG, "Session2 is destroyed " + sessionToken);
-                }
-                if (pid != sessionToken.getPid()) {
-                    throw new SecurityException("Unexpected Session2Token's PID, expected=" + pid
-                            + " but actually=" + sessionToken.getPid());
-                }
-                if (uid != sessionToken.getUid()) {
-                    throw new SecurityException("Unexpected Session2Token's UID, expected=" + uid
-                            + " but actually=" + sessionToken.getUid());
-                }
-                int userId = UserHandle.getUserId(uid);
-                mSession2TokensPerUser.get(userId).remove(sessionToken);
-                pushSession2TokensChangedLocked(userId);
+                Controller2Callback callback = new Controller2Callback(sessionToken);
+                // Note: It's safe not to keep controller here because it wouldn't be GC'ed until
+                //       it's closed.
+                // TODO: Keep controller as well for better readability
+                //       because the GC behavior isn't straightforward.
+                MediaController2 controller = new MediaController2(mContext, sessionToken,
+                        new HandlerExecutor(mHandler), callback);
             } finally {
                 Binder.restoreCallingIdentity(token);
             }
@@ -2235,4 +2205,30 @@
             obtainMessage(MSG_SESSIONS_CHANGED, userIdInteger).sendToTarget();
         }
     }
+
+    private class Controller2Callback extends MediaController2.ControllerCallback {
+        private final Session2Token mToken;
+
+        Controller2Callback(Session2Token token) {
+            mToken = token;
+        }
+
+        @Override
+        public void onConnected(MediaController2 controller, Session2CommandGroup allowedCommands) {
+            synchronized (mLock) {
+                int userId = UserHandle.getUserId(mToken.getUid());
+                mSession2TokensPerUser.get(userId).add(mToken);
+                pushSession2TokensChangedLocked(userId);
+            }
+        }
+
+        @Override
+        public void onDisconnected(MediaController2 controller) {
+            synchronized (mLock) {
+                int userId = UserHandle.getUserId(mToken.getUid());
+                mSession2TokensPerUser.get(userId).remove(mToken);
+                pushSession2TokensChangedLocked(userId);
+            }
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
index 1cbf0bf..b0d2704 100644
--- a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
+++ b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
@@ -270,9 +270,7 @@
             Slog.d(TAG, "onTargetPackageUpgraded packageName=" + packageName + " userId=" + userId);
         }
 
-        if (updateAllOverlaysForTarget(packageName, userId, 0)) {
-            mListener.onOverlaysChanged(packageName, userId);
-        }
+        updateAllOverlaysForTarget(packageName, userId, 0);
     }
 
     void onTargetPackageRemoved(@NonNull final String packageName, final int userId) {
diff --git a/services/core/java/com/android/server/pm/ModuleInfoProvider.java b/services/core/java/com/android/server/pm/ModuleInfoProvider.java
index 642bfa2..e7dace0 100644
--- a/services/core/java/com/android/server/pm/ModuleInfoProvider.java
+++ b/services/core/java/com/android/server/pm/ModuleInfoProvider.java
@@ -138,7 +138,7 @@
                 // to dealing with this as we'll now have to listen to all config changes and
                 // regenerate the data if required. Also, is this the right way to parse a resource
                 // reference out of an XML file ?
-                final String moduleName = packageResources.getString(
+                final CharSequence moduleName = packageResources.getText(
                         Integer.parseInt(parser.getAttributeValue(null, "name").substring(1)));
                 final String modulePackageName = XmlUtils.readStringAttribute(parser,
                         "packageName");
diff --git a/services/core/java/com/android/server/pm/PackageDexOptimizer.java b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
index 94b1b36..5b38208 100644
--- a/services/core/java/com/android/server/pm/PackageDexOptimizer.java
+++ b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
@@ -507,7 +507,7 @@
         int flags = info.flags;
         boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
         // When an app or priv app is configured to run out of box, only verify it.
-        if (info.isCodeIntegrityPreferred()
+        if (info.isEmbeddedDexUsed()
                 || (info.isPrivilegedApp()
                     && DexManager.isPackageSelectedToRunOob(info.packageName))) {
             return "verify";
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index a3e0d8d..af50c87 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -204,13 +204,17 @@
         mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions");
         mSessionsDir.mkdirs();
 
-        mStagingManager = new StagingManager(pm);
+        mStagingManager = new StagingManager(pm, this);
     }
 
     private void setBootCompleted()  {
         mBootCompleted = true;
     }
 
+    boolean isBootCompleted()  {
+        return mBootCompleted;
+    }
+
     public void systemReady() {
         mAppOps = mContext.getSystemService(AppOpsManager.class);
 
@@ -245,13 +249,24 @@
             // the updated information.
             writeSessionsLocked();
 
+        }
+    }
+
+    void restoreAndApplyStagedSessionIfNeeded() {
+        List<PackageInstallerSession> stagedSessionsToRestore = new ArrayList<>();
+        synchronized (mSessions) {
             for (int i = 0; i < mSessions.size(); i++) {
                 final PackageInstallerSession session = mSessions.valueAt(i);
                 if (session.isStaged()) {
-                    mStagingManager.restoreSession(session);
+                    stagedSessionsToRestore.add(session);
                 }
             }
         }
+        // Don't hold mSessions lock when calling restoreSession, since it might trigger an APK
+        // atomic install which needs to query sessions, which requires lock on mSessions.
+        for (PackageInstallerSession session : stagedSessionsToRestore) {
+            mStagingManager.restoreSession(session);
+        }
     }
 
     @GuardedBy("mSessions")
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index de0849f..995f335 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -1001,10 +1001,6 @@
         // cannot be modified anymore, there is no leak of information. For staged sessions,
         // further validation is performed by the staging manager.
         if (!params.isMultiPackage) {
-            if ((params.installFlags & PackageManager.INSTALL_APEX) != 0) {
-                // For APEX, validation is done by StagingManager post-commit.
-                return;
-            }
             final PackageInfo pkgInfo = mPm.getPackageInfo(
                     params.appPackageName, PackageManager.GET_SIGNATURES
                             | PackageManager.MATCH_STATIC_SHARED_LIBRARIES /*flags*/, userId);
@@ -1012,7 +1008,11 @@
             resolveStageDirLocked();
 
             try {
-                validateApkInstallLocked(pkgInfo);
+                if ((params.installFlags & PackageManager.INSTALL_APEX) != 0) {
+                    validateApexInstallLocked();
+                } else {
+                    validateApkInstallLocked(pkgInfo);
+                }
             } catch (PackageManagerException e) {
                 throw e;
             } catch (Throwable e) {
@@ -1304,6 +1304,27 @@
     }
 
     /**
+     * Validate apex install.
+     * <p>
+     * Sets {@link #mResolvedBaseFile} for RollbackManager to use.
+     */
+    @GuardedBy("mLock")
+    private void validateApexInstallLocked()
+            throws PackageManagerException {
+        final File[] addedFiles = mResolvedStageDir.listFiles(sAddedFilter);
+        if (ArrayUtils.isEmpty(addedFiles)) {
+            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, "No packages staged");
+        }
+
+        if (ArrayUtils.size(addedFiles) > 1) {
+            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
+                    "Too many files for apex install");
+        }
+
+        mResolvedBaseFile = addedFiles[0];
+    }
+
+    /**
      * Validate install by confirming that all application packages are have
      * consistent package name, version code, and signing certificates.
      * <p>
@@ -1563,12 +1584,12 @@
                 }
             }
         }
-        if (baseApk.preferCodeIntegrity) {
+        if (baseApk.useEmbeddedDex) {
             for (File file : mResolvedStagedFiles) {
                 if (file.getName().endsWith(".apk")
-                        && !DexManager.auditUncompressedCodeInApk(file.getPath())) {
+                        && !DexManager.auditUncompressedDexInApk(file.getPath())) {
                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
-                            "Some code are not uncompressed and aligned correctly for "
+                            "Some dex are not uncompressed and aligned correctly for "
                             + mPackageName);
                 }
             }
@@ -1664,6 +1685,12 @@
         }
     }
 
+    String getInstallerPackageName() {
+        synchronized (mLock) {
+            return mInstallerPackageName;
+        }
+    }
+
     private static String getRelativePath(File file, File base) throws IOException {
         final String pathStr = file.getAbsolutePath();
         final String baseStr = base.getAbsolutePath();
@@ -1964,7 +1991,7 @@
 
         // Send broadcast to default launcher only if it's a new install
         final boolean isNewInstall = extras == null || !extras.getBoolean(Intent.EXTRA_REPLACING);
-        if (success && isNewInstall) {
+        if (success && isNewInstall && mPm.mInstallerService.isBootCompleted()) {
             mPm.sendSessionCommitBroadcast(generateInfo(), userId);
         }
 
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 6f9a290..c63dc32 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -3046,7 +3046,6 @@
                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
                         SharedLibraryInfo.VERSION_UNDEFINED);
-                mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr();
             } else {
                 mRequiredVerifierPackage = null;
                 mRequiredInstallerPackage = null;
@@ -3055,8 +3054,10 @@
                 mIntentFilterVerifier = null;
                 mServicesSystemSharedLibraryPackageName = null;
                 mSharedSystemSharedLibraryPackageName = null;
-                mRequiredPermissionControllerPackage = null;
             }
+            // PermissionController hosts default permission granting and role management, so it's a
+            // critical part of the core system.
+            mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr();
 
             // Initialize InstantAppRegistry's Instant App list for all users.
             final int[] userIds = UserManagerService.getInstance().getUserIds();
@@ -3967,6 +3968,7 @@
                     }
                     return generatePackageInfo(ps, flags, userId);
                 }
+                // TODO(b/123680735): support MATCH_APEX|MATCH_FACTORY_ONLY case
             }
 
             PackageParser.Package p = mPackages.get(packageName);
@@ -3996,6 +3998,30 @@
                 }
                 return generatePackageInfo(ps, flags, userId);
             }
+            //
+            if (!matchFactoryOnly && (flags & MATCH_APEX) != 0) {
+                //TODO(b/123052859) Don't do file operations every time there is a query.
+                final IApexService apex = IApexService.Stub.asInterface(
+                        ServiceManager.getService("apexservice"));
+                if (apex != null) {
+                    try {
+                        final ApexInfo activePkg = apex.getActivePackage(packageName);
+                        if (activePkg != null) {
+                            try {
+                                return PackageParser.generatePackageInfoFromApex(
+                                        new File(activePkg.packagePath), true /* collect certs */);
+                            } catch (PackageParserException pe) {
+                                throw new IllegalStateException("Unable to parse: " + activePkg,
+                                        pe);
+                            }
+                        }
+                    } catch (RemoteException e) {
+                        Log.e(TAG, "Unable to retrieve packages from apexservice: " + e.toString());
+                    }
+                } else {
+                    Log.e(TAG, "Unable to connect to apexservice for querying packages.");
+                }
+            }
         }
         return null;
     }
@@ -7889,6 +7915,8 @@
                 }
             }
             if (listApex) {
+                // TODO(b/119767311): include uninstalled/inactive APEX if
+                //  MATCH_UNINSTALLED_PACKAGES is set.
                 final IApexService apex = IApexService.Stub.asInterface(
                         ServiceManager.getService("apexservice"));
                 if (apex != null) {
@@ -20101,7 +20129,8 @@
         return mContext.getString(R.string.config_defaultWellbeingPackage);
     }
 
-    private String getAppPredictionServicePackageName() {
+    @Override
+    public String getAppPredictionServicePackageName() {
         String flattenedAppPredictionServiceComponentName =
                 mContext.getString(R.string.config_defaultAppPredictionService);
         if (flattenedAppPredictionServiceComponentName == null) {
@@ -20752,6 +20781,11 @@
         }
 
         mModuleInfoProvider.systemReady();
+
+        // Installer service might attempt to install some packages that have been staged for
+        // installation on reboot. Make sure this is the last component to be call since the
+        // installation might require other components to be ready.
+        mInstallerService.restoreAndApplyStagedSessionIfNeeded();
     }
 
     public void waitForAppDataPrepared() {
@@ -23302,6 +23336,8 @@
                     return mConfiguratorPackage;
                 case PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER:
                     return mIncidentReportApproverPackage;
+                case PackageManagerInternal.PACKAGE_APP_PREDICTOR:
+                    return mAppPredictionServicePackage;
             }
             return null;
         }
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index c4d27e5..84fd01a 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -21,6 +21,10 @@
 import android.apex.ApexInfoList;
 import android.apex.ApexSessionInfo;
 import android.apex.IApexService;
+import android.content.IIntentReceiver;
+import android.content.IIntentSender;
+import android.content.Intent;
+import android.content.IntentSender;
 import android.content.pm.PackageInstaller;
 import android.content.pm.PackageInstaller.SessionInfo;
 import android.content.pm.PackageManager;
@@ -29,7 +33,10 @@
 import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
 import android.content.pm.ParceledListSlice;
 import android.content.pm.Signature;
+import android.os.Bundle;
 import android.os.Handler;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.text.TextUtils;
@@ -40,9 +47,13 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.os.BackgroundThread;
 
+import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
 /**
@@ -53,14 +64,16 @@
 
     private static final String TAG = "StagingManager";
 
+    private final PackageInstallerService mPi;
     private final PackageManagerService mPm;
     private final Handler mBgHandler;
 
     @GuardedBy("mStagedSessions")
     private final SparseArray<PackageInstallerSession> mStagedSessions = new SparseArray<>();
 
-    StagingManager(PackageManagerService pm) {
+    StagingManager(PackageManagerService pm, PackageInstallerService pi) {
         mPm = pm;
+        mPi = pi;
         mBgHandler = BackgroundThread.getHandler();
     }
 
@@ -85,7 +98,7 @@
         return new ParceledListSlice<>(result);
     }
 
-    private static boolean validateApexSignatureLocked(String apexPath, String packageName) {
+    private static boolean validateApexSignature(String apexPath, String packageName) {
         final SigningDetails signingDetails;
         try {
             signingDetails = ApkSignatureVerifier.verify(apexPath, SignatureSchemeVersion.JAR);
@@ -173,6 +186,13 @@
     private void preRebootVerification(@NonNull PackageInstallerSession session) {
         boolean success = true;
 
+        if (!sessionContainsApex(session)) {
+            // TODO: Decide whether we want to fail fast by detecting signature mismatches for APKs,
+            // right away.
+            session.setStagedSessionReady();
+            return;
+        }
+
         final ApexInfoList apexInfoList = new ApexInfoList();
         // APEX checks. For single-package sessions, check if they contain an APEX. For
         // multi-package sessions, find all the child sessions that contain an APEX.
@@ -199,16 +219,13 @@
                     "APEX staging failed, check logcat messages from apexd for more details.");
         }
 
-        if (apexInfoList.apexInfos.length > 0) {
+        if (apexInfoList.apexInfos != null && apexInfoList.apexInfos.length > 0) {
             // For APEXes, we validate the signature here before we mark the session as ready,
             // so we fail the session early if there is a signature mismatch. For APKs, the
             // signature verification will be done by the package manager at the point at which
             // it applies the staged install.
-            //
-            // TODO: Decide whether we want to fail fast by detecting signature mismatches for APKs,
-            // right away.
             for (ApexInfo apexPackage : apexInfoList.apexInfos) {
-                if (!validateApexSignatureLocked(apexPackage.packagePath,
+                if (!validateApexSignature(apexPackage.packagePath,
                         apexPackage.packageName)) {
                     session.setStagedSessionFailed(SessionInfo.VERIFICATION_FAILED,
                             "APK-container signature verification failed for package "
@@ -229,35 +246,182 @@
         }
     }
 
+    private boolean sessionContainsApex(@NonNull PackageInstallerSession session) {
+        if (!session.isMultiPackage()) {
+            return isApexSession(session);
+        }
+        synchronized (mStagedSessions) {
+            return !(Arrays.stream(session.getChildSessionIds())
+                    // Retrieve cached sessions matching ids.
+                    .mapToObj(i -> mStagedSessions.get(i))
+                    // Filter only the ones containing APEX.
+                    .filter(childSession -> isApexSession(childSession))
+                    .collect(Collectors.toList())
+                    .isEmpty());
+        }
+    }
+
     private void resumeSession(@NonNull PackageInstallerSession session) {
-        // Check with apexservice whether the apex
-        // packages have been activated.
-        final IApexService apex = IApexService.Stub.asInterface(
-                ServiceManager.getService("apexservice"));
-        ApexSessionInfo apexSessionInfo;
-        try {
-            apexSessionInfo = apex.getStagedSessionInfo(session.sessionId);
-        } catch (RemoteException re) {
-            Slog.e(TAG, "Unable to contact apexservice", re);
-            // TODO should we retry here? Mark the session as failed?
+        if (sessionContainsApex(session)) {
+            // Check with apexservice whether the apex
+            // packages have been activated.
+            final IApexService apex = IApexService.Stub.asInterface(
+                    ServiceManager.getService("apexservice"));
+            ApexSessionInfo apexSessionInfo;
+            try {
+                apexSessionInfo = apex.getStagedSessionInfo(session.sessionId);
+            } catch (RemoteException re) {
+                Slog.e(TAG, "Unable to contact apexservice", re);
+                // TODO should we retry here? Mark the session as failed?
+                return;
+            }
+            if (apexSessionInfo.isActivationFailed || apexSessionInfo.isUnknown) {
+                session.setStagedSessionFailed(SessionInfo.ACTIVATION_FAILED,
+                        "APEX activation failed. Check logcat messages from apexd for "
+                                + "more information.");
+                return;
+            }
+            if (apexSessionInfo.isVerified) {
+                // Session has been previously submitted to apexd, but didn't complete all the
+                // pre-reboot verification, perhaps because the device rebooted in the meantime.
+                // Greedily re-trigger the pre-reboot verification.
+                Slog.d(TAG, "Found pending staged session " + session.sessionId + " still to be "
+                        + "verified, resuming pre-reboot verification");
+                mBgHandler.post(() -> preRebootVerification(session));
+                return;
+            }
+            if (!apexSessionInfo.isActivated) {
+                // In all the remaining cases apexd will try to apply the session again at next
+                // boot. Nothing to do here for now.
+                Slog.w(TAG, "Staged session " + session.sessionId + " scheduled to be applied "
+                        + "at boot didn't activate nor fail. This usually means that apexd will "
+                        + "retry at next reboot.");
+                return;
+            }
+        }
+        // The APEX part of the session is activated, proceed with the installation of APKs.
+        if (!installApksInSession(session)) {
+            session.setStagedSessionFailed(SessionInfo.ACTIVATION_FAILED,
+                    "APK installation for staged session " + session.sessionId + " failed.");
             return;
         }
-        if (apexSessionInfo.isActivationFailed || apexSessionInfo.isUnknown) {
-            session.setStagedSessionFailed(SessionInfo.ACTIVATION_FAILED,
-                    "APEX activation failed. Check logcat messages from apexd for "
-                                  + "more information.");
+        session.setStagedSessionApplied();
+    }
+
+    private String findFirstAPKInDir(File stageDir) {
+        if (stageDir != null && stageDir.exists()) {
+            for (File file : stageDir.listFiles()) {
+                if (file.getAbsolutePath().toLowerCase().endsWith(".apk")) {
+                    return file.getAbsolutePath();
+                }
+            }
         }
-        if (apexSessionInfo.isVerified) {
-            // Session has been previously submitted to apexd, but didn't complete all the
-            // pre-reboot verification, perhaps because the device rebooted in the meantime.
-            // Greedily re-trigger the pre-reboot verification.
-            mBgHandler.post(() -> preRebootVerification(session));
+        return null;
+    }
+
+    private PackageInstallerSession createAndWriteApkSession(
+            @NonNull PackageInstallerSession originalSession) {
+        // TODO(b/123629153): support split APKs.
+        if (originalSession.stageDir == null) {
+            Slog.wtf(TAG, "Attempting to install a staged APK session with no staging dir");
+            return null;
         }
-        if (apexSessionInfo.isActivated) {
-            session.setStagedSessionApplied();
-            // TODO(b/118865310) if multi-package proceed with the installation of APKs.
+        String apkFilePath = findFirstAPKInDir(originalSession.stageDir);
+        if (apkFilePath == null) {
+            Slog.w(TAG, "Can't find staged APK in " + originalSession.stageDir.getAbsolutePath());
+            return null;
         }
-        // In every other case apexd will retry to apply the session at next boot.
+        File apkFile = new File(apkFilePath);
+
+        PackageInstaller.SessionParams params = originalSession.params.copy();
+        params.isStaged = false;
+        int apkSessionId = mPi.createSession(
+                params, originalSession.getInstallerPackageName(), originalSession.userId);
+        PackageInstallerSession apkSession = mPi.getSession(apkSessionId);
+
+        try {
+            apkSession.open();
+            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(apkFile,
+                    ParcelFileDescriptor.MODE_READ_ONLY);
+            long sizeBytes = pfd.getStatSize();
+            if (sizeBytes < 0) {
+                Slog.e(TAG, "Unable to get size of: " + apkFilePath);
+                return null;
+            }
+            apkSession.write(apkFile.getName(), 0, sizeBytes, pfd);
+        } catch (IOException e) {
+            Slog.e(TAG, "Failure to install APK staged session " + originalSession.sessionId, e);
+            return null;
+        }
+        return apkSession;
+    }
+
+    private boolean commitApkSession(@NonNull PackageInstallerSession apkSession,
+                                     int originalSessionId) {
+        final LocalIntentReceiver receiver = new LocalIntentReceiver();
+        apkSession.commit(receiver.getIntentSender(), false);
+        final Intent result = receiver.getResult();
+        final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
+                PackageInstaller.STATUS_FAILURE);
+        if (status == PackageInstaller.STATUS_SUCCESS) {
+            return true;
+        }
+        Slog.e(TAG, "Failure to install APK staged session " + originalSessionId + " ["
+                + result.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + "]");
+        return false;
+    }
+
+    private boolean installApksInSession(@NonNull PackageInstallerSession session) {
+        if (!session.isMultiPackage() && !isApexSession(session)) {
+            // APK single-packaged staged session. Do a regular install.
+            PackageInstallerSession apkSession = createAndWriteApkSession(session);
+            if (apkSession == null) {
+                return false;
+            }
+            return commitApkSession(apkSession, session.sessionId);
+        } else if (session.isMultiPackage()) {
+            // For multi-package staged sessions containing APKs, we identify which child sessions
+            // contain an APK, and with those then create a new multi-package group of sessions,
+            // carrying over all the session parameters and unmarking them as staged. On commit the
+            // sessions will be installed atomically.
+            List<PackageInstallerSession> childSessions;
+            synchronized (mStagedSessions) {
+                childSessions =
+                        Arrays.stream(session.getChildSessionIds())
+                                // Retrieve cached sessions matching ids.
+                                .mapToObj(i -> mStagedSessions.get(i))
+                                // Filter only the ones containing APKs.s
+                                .filter(childSession -> !isApexSession(childSession))
+                                .collect(Collectors.toList());
+            }
+            if (childSessions.isEmpty()) {
+                // APEX-only multi-package staged session, nothing to do.
+                return true;
+            }
+            PackageInstaller.SessionParams params = session.params.copy();
+            params.isStaged = false;
+            int apkParentSessionId = mPi.createSession(
+                    params, session.getInstallerPackageName(), session.userId);
+            PackageInstallerSession apkParentSession = mPi.getSession(apkParentSessionId);
+            try {
+                apkParentSession.open();
+            } catch (IOException e) {
+                Slog.e(TAG, "Unable to prepare multi-package session for staged session "
+                        + session.sessionId);
+                return false;
+            }
+
+            for (PackageInstallerSession sessionToClone : childSessions) {
+                PackageInstallerSession apkChildSession = createAndWriteApkSession(sessionToClone);
+                if (apkChildSession == null) {
+                    return false;
+                }
+                apkParentSession.addChildSessionId(apkChildSession.sessionId);
+            }
+            return commitApkSession(apkParentSession, session.sessionId);
+        }
+        // APEX single-package staged session, nothing to do.
+        return true;
     }
 
     void commitSession(@NonNull PackageInstallerSession session) {
@@ -336,9 +500,36 @@
         } else {
             // Session had already being marked ready. Start the checks to verify if there is any
             // follow-up work.
-            // TODO(b/118865310): should this be synchronous to ensure it completes before
-            //                    systemReady() finishes?
-            mBgHandler.post(() -> resumeSession(session));
+            resumeSession(session);
+        }
+    }
+
+    private static class LocalIntentReceiver {
+        private final LinkedBlockingQueue<Intent> mResult = new LinkedBlockingQueue<>();
+
+        private IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
+            @Override
+            public void send(int code, Intent intent, String resolvedType, IBinder whitelistToken,
+                             IIntentReceiver finishedReceiver, String requiredPermission,
+                             Bundle options) {
+                try {
+                    mResult.offer(intent, 5, TimeUnit.SECONDS);
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        };
+
+        public IntentSender getIntentSender() {
+            return new IntentSender((IIntentSender) mLocalSender);
+        }
+
+        public Intent getResult() {
+            try {
+                return mResult.take();
+            } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+            }
         }
     }
 }
diff --git a/services/core/java/com/android/server/pm/dex/ArtManagerService.java b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
index 7d2dd65..23705db 100644
--- a/services/core/java/com/android/server/pm/dex/ArtManagerService.java
+++ b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
@@ -480,7 +480,7 @@
             final String apkPath = pkg.baseCodePath;
             final ApplicationInfo appInfo = pkg.applicationInfo;
             final String outDexFile = appInfo.dataDir + "/code_cache/compiled_view.dex";
-            if (appInfo.isPrivilegedApp() || appInfo.isCodeIntegrityPreferred()) {
+            if (appInfo.isPrivilegedApp() || appInfo.isEmbeddedDexUsed()) {
                 // Privileged apps prefer to load trusted code so they don't use compiled views.
                 // If the app is not privileged but prefers code integrity, also avoid compiling
                 // views.
diff --git a/services/core/java/com/android/server/pm/dex/DexManager.java b/services/core/java/com/android/server/pm/dex/DexManager.java
index abbddf3..2213901 100644
--- a/services/core/java/com/android/server/pm/dex/DexManager.java
+++ b/services/core/java/com/android/server/pm/dex/DexManager.java
@@ -740,10 +740,10 @@
     }
 
     /**
-     * Generates log if the archive located at {@code fileName} has uncompressed dex file and so
-     * files that can be direclty mapped.
+     * Generates log if the archive located at {@code fileName} has uncompressed dex file that can
+     * be direclty mapped.
      */
-    public static boolean auditUncompressedCodeInApk(String fileName) {
+    public static boolean auditUncompressedDexInApk(String fileName) {
         StrictJarFile jarFile = null;
         try {
             jarFile = new StrictJarFile(fileName,
@@ -762,16 +762,6 @@
                         Slog.w(TAG, "APK " + fileName + " has unaligned dex code " +
                                 entry.getName());
                     }
-                } else if (entry.getName().endsWith(".so")) {
-                    if (entry.getMethod() != ZipEntry.STORED) {
-                        allCorrect = false;
-                        Slog.w(TAG, "APK " + fileName + " has compressed native code " +
-                                entry.getName());
-                    } else if ((entry.getDataOffset() & (0x1000 - 1)) != 0) {
-                        allCorrect = false;
-                        Slog.w(TAG, "APK " + fileName + " has unaligned native code " +
-                                entry.getName());
-                    }
                 }
             }
             return allCorrect;
diff --git a/services/core/java/com/android/server/pm/permission/BasePermission.java b/services/core/java/com/android/server/pm/permission/BasePermission.java
index 848cee0..173d9a0 100644
--- a/services/core/java/com/android/server/pm/permission/BasePermission.java
+++ b/services/core/java/com/android/server/pm/permission/BasePermission.java
@@ -254,6 +254,9 @@
     public boolean isIncidentReportApprover() {
         return (protectionLevel & PermissionInfo.PROTECTION_FLAG_INCIDENT_REPORT_APPROVER) != 0;
     }
+    public boolean isAppPredictor() {
+        return (protectionLevel & PermissionInfo.PROTECTION_FLAG_APP_PREDICTOR) != 0;
+    }
 
     public void transfer(@NonNull String origPackageName, @NonNull String newPackageName) {
         if (!origPackageName.equals(sourcePackageName)) {
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 22780e6..a4413f9 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -1724,6 +1724,12 @@
                 // this app is the incident report approver, then it gets the permission.
                 allowed = true;
             }
+            if (!allowed && bp.isAppPredictor()
+                    && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
+                        PackageManagerInternal.PACKAGE_APP_PREDICTOR, UserHandle.USER_SYSTEM))) {
+                // Special permissions for the system app predictor.
+                allowed = true;
+            }
         }
         return allowed;
     }
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
index 8550bc3..1d74e1f 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
@@ -104,7 +104,6 @@
     private static final String KEY_AOD_DISABLED = "aod_disabled";
     // Go into deep Doze as soon as the screen turns off.
     private static final String KEY_QUICK_DOZE_ENABLED = "quick_doze_enabled";
-    private static final String KEY_SEND_TRON_LOG = "send_tron_log";
 
     private static final String KEY_CPU_FREQ_INTERACTIVE = "cpufreq-i";
     private static final String KEY_CPU_FREQ_NONINTERACTIVE = "cpufreq-n";
@@ -129,8 +128,7 @@
             new ArrayMap<>(), /* filesForNoninteractive */
             false, /* forceAllAppsStandby */
             false, /* forceBackgroundCheck */
-            PowerManager.LOCATION_MODE_NO_CHANGE, /* gpsMode */
-            false  /* sendTronLog */
+            PowerManager.LOCATION_MODE_NO_CHANGE /* gpsMode */
     );
 
     private static final Policy DEFAULT_ADAPTIVE_POLICY = OFF_POLICY;
@@ -154,8 +152,7 @@
             new ArrayMap<>(), /* filesForNoninteractive */
             true, /* forceAllAppsStandby */
             true, /* forceBackgroundCheck */
-            PowerManager.LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF, /* gpsMode */
-            false /* sendTronLog */
+            PowerManager.LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF /* gpsMode */
     );
 
     private final Object mLock;
@@ -418,13 +415,10 @@
         if (currPolicy.disableOptionalSensors) sb.append("S");
         if (currPolicy.disableAod) sb.append("o");
         if (currPolicy.enableQuickDoze) sb.append("q");
-        if (currPolicy.sendTronLog) sb.append("t");
 
         sb.append(currPolicy.gpsMode);
 
         mEventLogKeys = sb.toString();
-
-        mBatterySavingStats.setSendTronLog(currPolicy.sendTronLog);
     }
 
     static class Policy {
@@ -567,11 +561,6 @@
          */
         public final int gpsMode;
 
-        /**
-         * Whether BatterySavingStats should send tron events.
-         */
-        public final boolean sendTronLog;
-
         private final int mHashCode;
 
         Policy(
@@ -593,8 +582,7 @@
                 ArrayMap<String, String> filesForNoninteractive,
                 boolean forceAllAppsStandby,
                 boolean forceBackgroundCheck,
-                int gpsMode,
-                boolean sendTronLog) {
+                int gpsMode) {
 
             this.adjustBrightnessFactor = adjustBrightnessFactor;
             this.advertiseIsEnabled = advertiseIsEnabled;
@@ -615,7 +603,6 @@
             this.forceAllAppsStandby = forceAllAppsStandby;
             this.forceBackgroundCheck = forceBackgroundCheck;
             this.gpsMode = gpsMode;
-            this.sendTronLog = sendTronLog;
 
             mHashCode = Objects.hash(
                     adjustBrightnessFactor,
@@ -636,8 +623,7 @@
                     filesForNoninteractive,
                     forceAllAppsStandby,
                     forceBackgroundCheck,
-                    gpsMode,
-                    sendTronLog);
+                    gpsMode);
         }
 
         static Policy fromConfig(BatterySaverPolicyConfig config) {
@@ -674,8 +660,7 @@
                     (new CpuFrequencies()).parseString(cpuFreqNoninteractive).toSysFileMap(),
                     config.getForceAllAppsStandby(),
                     config.getForceBackgroundCheck(),
-                    config.getGpsMode(),
-                    OFF_POLICY.sendTronLog
+                    config.getGpsMode()
             );
         }
 
@@ -737,7 +722,6 @@
             boolean forceBackgroundCheck = parser.getBoolean(KEY_FORCE_BACKGROUND_CHECK,
                     defaultPolicy.forceBackgroundCheck);
             int gpsMode = parser.getInt(KEY_GPS_MODE, defaultPolicy.gpsMode);
-            boolean sendTronLog = parser.getBoolean(KEY_SEND_TRON_LOG, defaultPolicy.sendTronLog);
 
             return new Policy(
                     adjustBrightnessFactor,
@@ -761,8 +745,7 @@
                     (new CpuFrequencies()).parseString(cpuFreqNoninteractive).toSysFileMap(),
                     forceAllAppsStandby,
                     forceBackgroundCheck,
-                    gpsMode,
-                    sendTronLog
+                    gpsMode
             );
         }
 
@@ -788,7 +771,6 @@
                     && forceAllAppsStandby == other.forceAllAppsStandby
                     && forceBackgroundCheck == other.forceBackgroundCheck
                     && gpsMode == other.gpsMode
-                    && sendTronLog == other.sendTronLog
                     && filesForInteractive.equals(other.filesForInteractive)
                     && filesForNoninteractive.equals(other.filesForNoninteractive);
         }
@@ -1026,9 +1008,6 @@
         pw.println("  " + KEY_SOUNDTRIGGER_DISABLED + "=" + p.disableSoundTrigger);
         pw.print(indent);
         pw.println("  " + KEY_QUICK_DOZE_ENABLED + "=" + p.enableQuickDoze);
-        pw.print(indent);
-        pw.println("  " + KEY_SEND_TRON_LOG + "=" + p.sendTronLog);
-        pw.println();
 
         pw.print("    Interactive File values:\n");
         dumpMap(pw, "      ", p.filesForInteractive);
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java b/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
index 1d30a03..3dbc007 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
@@ -15,7 +15,6 @@
  */
 package com.android.server.power.batterysaver;
 
-import android.metrics.LogMaker;
 import android.os.BatteryManagerInternal;
 import android.os.SystemClock;
 import android.util.ArrayMap;
@@ -24,9 +23,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.server.EventLogTags;
 import com.android.server.LocalServices;
 
@@ -142,7 +138,6 @@
     }
 
     private BatteryManagerInternal mBatteryManagerInternal;
-    private final MetricsLogger mMetricsLogger;
 
     private static final int STATE_NOT_INITIALIZED = -1;
     private static final int STATE_CHARGING = -2;
@@ -172,28 +167,11 @@
     @GuardedBy("mLock")
     private long mLastBatterySaverDisabledTime = 0;
 
-    private final MetricsLoggerHelper mMetricsLoggerHelper = new MetricsLoggerHelper();
-
-    @VisibleForTesting
-    @GuardedBy("mLock")
-    private boolean mSendTronLog;
-
     /** Visible for unit tests */
     @VisibleForTesting
-    public BatterySavingStats(Object lock, MetricsLogger metricsLogger) {
+    public BatterySavingStats(Object lock) {
         mLock = lock;
         mBatteryManagerInternal = LocalServices.getService(BatteryManagerInternal.class);
-        mMetricsLogger = metricsLogger;
-    }
-
-    public BatterySavingStats(Object lock) {
-        this(lock, new MetricsLogger());
-    }
-
-    public void setSendTronLog(boolean send) {
-        synchronized (mLock) {
-            mSendTronLog = send;
-        }
     }
 
     private BatteryManagerInternal getBatteryManagerInternal() {
@@ -325,7 +303,6 @@
 
         endLastStateLocked(now, batteryLevel, batteryPercent);
         startNewStateLocked(newState, now, batteryLevel, batteryPercent);
-        mMetricsLoggerHelper.transitionStateLocked(newState, now, batteryLevel, batteryPercent);
     }
 
     @GuardedBy("mLock")
@@ -472,61 +449,4 @@
                 onStat.totalBatteryDrainPercent,
                 onStat.drainPerHour() / 1000.0));
     }
-
-    @VisibleForTesting
-    class MetricsLoggerHelper {
-        private int mLastState = STATE_NOT_INITIALIZED;
-        private long mStartTime;
-        private int mStartBatteryLevel;
-        private int mStartPercent;
-
-        private static final int STATE_CHANGE_DETECT_MASK =
-                (BatterySaverState.MASK << BatterySaverState.SHIFT) |
-                (InteractiveState.MASK << InteractiveState.SHIFT);
-
-        @GuardedBy("BatterySavingStats.this.mLock")
-        public void transitionStateLocked(
-                int newState, long now, int batteryLevel, int batteryPercent) {
-            final boolean stateChanging =
-                    ((mLastState >= 0) ^ (newState >= 0)) ||
-                    (((mLastState ^ newState) & STATE_CHANGE_DETECT_MASK) != 0);
-            if (stateChanging) {
-                if (mLastState >= 0) {
-                    final long deltaTime = now - mStartTime;
-
-                    reportLocked(mLastState, deltaTime, mStartBatteryLevel, mStartPercent,
-                            batteryLevel, batteryPercent);
-                }
-                mStartTime = now;
-                mStartBatteryLevel = batteryLevel;
-                mStartPercent = batteryPercent;
-            }
-            mLastState = newState;
-        }
-
-        @GuardedBy("BatterySavingStats.this.mLock")
-        void reportLocked(int state, long deltaTimeMs,
-                int startBatteryLevelUa, int startBatteryLevelPercent,
-                int endBatteryLevelUa, int endBatteryLevelPercent) {
-            if (!mSendTronLog) {
-                return;
-            }
-            final boolean batterySaverOn =
-                    BatterySaverState.fromIndex(state) != BatterySaverState.OFF;
-            final boolean interactive =
-                    InteractiveState.fromIndex(state) != InteractiveState.NON_INTERACTIVE;
-
-            final LogMaker logMaker = new LogMaker(MetricsProto.MetricsEvent.BATTERY_SAVER)
-                    .setSubtype(batterySaverOn ? 1 : 0)
-                    .addTaggedData(MetricsEvent.FIELD_INTERACTIVE, interactive ? 1 : 0)
-                    .addTaggedData(MetricsEvent.FIELD_DURATION_MILLIS, deltaTimeMs)
-                    .addTaggedData(MetricsEvent.FIELD_START_BATTERY_UA, startBatteryLevelUa)
-                    .addTaggedData(MetricsEvent.FIELD_START_BATTERY_PERCENT,
-                            startBatteryLevelPercent)
-                    .addTaggedData(MetricsEvent.FIELD_END_BATTERY_UA, endBatteryLevelUa)
-                    .addTaggedData(MetricsEvent.FIELD_END_BATTERY_PERCENT, endBatteryLevelPercent);
-
-            mMetricsLogger.write(logMaker);
-        }
-    }
 }
diff --git a/services/core/java/com/android/server/role/RoleUserState.java b/services/core/java/com/android/server/role/RoleUserState.java
index bc68dde..5030e34 100644
--- a/services/core/java/com/android/server/role/RoleUserState.java
+++ b/services/core/java/com/android/server/role/RoleUserState.java
@@ -376,7 +376,7 @@
 
             version = mVersion;
             packagesHash = mPackagesHash;
-            roles = getRoleHolders();
+            roles = snapshotRolesLocked();
         }
 
         AtomicFile atomicFile = new AtomicFile(getFile(mUserId), "roles-" + mUserId);
@@ -541,7 +541,7 @@
 
             version = mVersion;
             packagesHash = mPackagesHash;
-            roles = getRoleHolders();
+            roles = snapshotRolesLocked();
         }
 
         long fieldToken = dumpOutputStream.start(fieldName, fieldId);
@@ -578,18 +578,23 @@
     @NonNull
     public ArrayMap<String, ArraySet<String>> getRoleHolders() {
         synchronized (mLock) {
-            ArrayMap<String, ArraySet<String>> roles = new ArrayMap<>();
-            for (int i = 0, size = CollectionUtils.size(mRoles); i < size; ++i) {
-                String roleName = mRoles.keyAt(i);
-                ArraySet<String> roleHolders = mRoles.valueAt(i);
-
-                roleHolders = new ArraySet<>(roleHolders);
-                roles.put(roleName, roleHolders);
-            }
-            return roles;
+            return snapshotRolesLocked();
         }
     }
 
+    @GuardedBy("mLock")
+    private ArrayMap<String, ArraySet<String>> snapshotRolesLocked() {
+        ArrayMap<String, ArraySet<String>> roles = new ArrayMap<>();
+        for (int i = 0, size = CollectionUtils.size(mRoles); i < size; ++i) {
+            String roleName = mRoles.keyAt(i);
+            ArraySet<String> roleHolders = mRoles.valueAt(i);
+
+            roleHolders = new ArraySet<>(roleHolders);
+            roles.put(roleName, roleHolders);
+        }
+        return roles;
+    }
+
     /**
      * Destroy this user state and delete the corresponding file. Any pending writes to the file
      * will be cancelled, and any future interaction with this state will throw an exception.
diff --git a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
index 4613400..4c2b3c2 100644
--- a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
+++ b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
@@ -47,7 +47,6 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.server.LocalServices;
 import com.android.server.pm.Installer;
-import com.android.server.pm.PackageManagerServiceUtils;
 
 import java.io.File;
 import java.io.IOException;
@@ -329,15 +328,18 @@
                 int sessionId = packageInstaller.createSession(params);
                 PackageInstaller.Session session = packageInstaller.openSession(sessionId);
 
-                // TODO: Will it always be called "base.apk"? What about splits?
-                // What about apex?
-                File packageDir = new File(data.backupDir, info.getPackageName());
-                File baseApk = new File(packageDir, "base.apk");
-                try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(baseApk,
+                File packageCode = RollbackStore.getPackageCode(data, info.getPackageName());
+                if (packageCode == null) {
+                    sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE,
+                            "Backup copy of package code inaccessible");
+                    return;
+                }
+
+                try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(packageCode,
                         ParcelFileDescriptor.MODE_READ_ONLY)) {
                     final long token = Binder.clearCallingIdentity();
                     try {
-                        session.write("base.apk", 0, baseApk.length(), fd);
+                        session.write(packageCode.getName(), 0, packageCode.length(), fd);
                     } finally {
                         Binder.restoreCallingIdentity(token);
                     }
@@ -735,17 +737,19 @@
         VersionedPackage newVersion = new VersionedPackage(packageName, newPackage.versionCode);
 
         // Get information about the currently installed package.
-        PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
-        PackageParser.Package installedPackage = pm.getPackage(packageName);
-        if (installedPackage == null) {
+        PackageManager pm = mContext.getPackageManager();
+        PackageInfo pkgInfo = null;
+        try {
+            pkgInfo = pm.getPackageInfo(packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
             // TODO: Support rolling back fresh package installs rather than
             // fail here. Test this case.
             Log.e(TAG, packageName + " is not installed");
             return false;
         }
-        VersionedPackage installedVersion = new VersionedPackage(packageName,
-                installedPackage.getLongVersionCode());
 
+        VersionedPackage installedVersion = new VersionedPackage(packageName,
+                pkgInfo.getLongVersionCode());
 
         final IntArray pendingBackups = mUserdataHelper.snapshotAppData(packageName,
                 installedUsers);
@@ -769,16 +773,12 @@
             return false;
         }
 
-        File packageDir = mRollbackStore.packageCodePathForAvailableRollback(data, packageName);
-        packageDir.mkdirs();
-
-        // TODO: Copy by hard link instead to save on cpu and storage space?
-        int status = PackageManagerServiceUtils.copyPackage(installedPackage.codePath, packageDir);
-        if (status != PackageManager.INSTALL_SUCCEEDED) {
-            Log.e(TAG, "Unable to copy package for rollback for " + packageName);
+        try {
+            RollbackStore.backupPackageCode(data, packageName, pkgInfo.applicationInfo.sourceDir);
+        } catch (IOException e) {
+            Log.e(TAG, "Unable to copy package for rollback for " + packageName, e);
             return false;
         }
-
         return true;
     }
 
diff --git a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
index b3cc6de..8e04160 100644
--- a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
+++ b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
@@ -18,14 +18,18 @@
 
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.PackageInstaller;
+import android.content.pm.PackageManager;
 import android.content.pm.VersionedPackage;
 import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.RollbackInfo;
 import android.content.rollback.RollbackManager;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.text.TextUtils;
+import android.util.Slog;
+import android.util.StatsLog;
 
+import com.android.internal.R;
 import com.android.server.PackageWatchdog;
 import com.android.server.PackageWatchdog.PackageHealthObserver;
 import com.android.server.PackageWatchdog.PackageHealthObserverImpact;
@@ -53,10 +57,16 @@
     }
 
     @Override
-    public int onHealthCheckFailed(String packageName, long versionCode) {
+    public int onHealthCheckFailed(VersionedPackage failedPackage) {
+        VersionedPackage moduleMetadataPackage = getModuleMetadataPackage();
+        if (moduleMetadataPackage == null) {
+            // Ignore failure, no mainline update available
+            return PackageHealthObserverImpact.USER_IMPACT_NONE;
+        }
+
         RollbackInfo rollback =
-                getAvailableRollback(mContext.getSystemService(RollbackManager.class),
-                    packageName, versionCode);
+                getAvailableMainlineRollback(mContext.getSystemService(RollbackManager.class),
+                        failedPackage, moduleMetadataPackage);
         if (rollback == null) {
             // Don't handle the notification, no rollbacks available for the package
             return PackageHealthObserverImpact.USER_IMPACT_NONE;
@@ -66,31 +76,46 @@
     }
 
     @Override
-    public boolean execute(String packageName, long versionCode) {
-        RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
-        RollbackInfo rollback = getAvailableRollback(rollbackManager, packageName, versionCode);
-        if (rollback == null) {
-            // Expected a rollback to be available, what happened?
+    public boolean execute(VersionedPackage failedPackage) {
+        VersionedPackage moduleMetadataPackage = getModuleMetadataPackage();
+        if (moduleMetadataPackage == null) {
+            // Ignore failure, no mainline update available
             return false;
         }
 
-        // TODO(zezeozue): Only rollback if rollback version == failed package version
+        RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
+        RollbackInfo rollback = getAvailableMainlineRollback(rollbackManager,
+                failedPackage, moduleMetadataPackage);
+        if (rollback == null) {
+            Slog.w(TAG, "Expected rollback but no mainline rollback found for package: [ "
+                    + failedPackage.getPackageName() + "] with versionCode: ["
+                    + failedPackage.getVersionCode() + "]");
+            return false;
+        }
+
+        StatsLog.write(StatsLog.WATCHDOG_ROLLBACK_OCCURRED,
+                StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE,
+                moduleMetadataPackage.getPackageName(),
+                moduleMetadataPackage.getVersionCode());
         LocalIntentReceiver rollbackReceiver = new LocalIntentReceiver((Intent result) -> {
-            int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
-                    PackageInstaller.STATUS_FAILURE);
-            if (status == PackageInstaller.STATUS_SUCCESS) {
-                // TODO(zezeozue); Log success metrics
-                // Rolledback successfully, no action required by other observers
+            int status = result.getIntExtra(RollbackManager.EXTRA_STATUS,
+                    RollbackManager.STATUS_FAILURE);
+            if (status == RollbackManager.STATUS_SUCCESS) {
+                StatsLog.write(StatsLog.WATCHDOG_ROLLBACK_OCCURRED,
+                        StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS,
+                        moduleMetadataPackage.getPackageName(),
+                        moduleMetadataPackage.getVersionCode());
             } else {
-                // TODO(zezeozue); Log failure metrics
-                // Rollback failed other observers should have a shot
+                StatsLog.write(StatsLog.WATCHDOG_ROLLBACK_OCCURRED,
+                        StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_FAILURE,
+                        moduleMetadataPackage.getPackageName(),
+                        moduleMetadataPackage.getVersionCode());
             }
         });
 
-        // TODO(zezeozue): Log initiated metrics
         mHandler.post(() ->
                 rollbackManager.commitRollback(rollback.getRollbackId(),
-                    Collections.singletonList(new VersionedPackage(packageName, versionCode)),
+                    Collections.singletonList(moduleMetadataPackage),
                     rollbackReceiver.getIntentSender()));
         // Assume rollback executed successfully
         return true;
@@ -109,17 +134,41 @@
         PackageWatchdog.getInstance(mContext).startObservingHealth(this, packages, durationMs);
     }
 
-    private RollbackInfo getAvailableRollback(RollbackManager rollbackManager,
-            String packageName, long versionCode) {
+    private RollbackInfo getAvailableMainlineRollback(RollbackManager rollbackManager,
+            VersionedPackage failedPackage, VersionedPackage moduleMetadataPackage) {
         for (RollbackInfo rollback : rollbackManager.getAvailableRollbacks()) {
+            // We only rollback mainline packages, so check if rollback contains the
+            // module metadata provider, if it does, the rollback is a mainline rollback
+            boolean hasModuleMetadataPackage = false;
+            boolean hasFailedPackage = false;
             for (PackageRollbackInfo packageRollback : rollback.getPackages()) {
-                if (packageName.equals(packageRollback.getPackageName())
+                hasModuleMetadataPackage |= packageRollback.getPackageName().equals(
+                        moduleMetadataPackage.getPackageName());
+                hasFailedPackage |= packageRollback.getPackageName().equals(
+                        failedPackage.getPackageName())
                         && packageRollback.getVersionRolledBackFrom().getVersionCode()
-                        == versionCode) {
-                    return rollback;
-                }
+                        == failedPackage.getVersionCode();
+            }
+            if (hasModuleMetadataPackage && hasFailedPackage) {
+                return rollback;
             }
         }
         return null;
     }
+
+    private VersionedPackage getModuleMetadataPackage() {
+        String packageName = mContext.getResources().getString(
+                R.string.config_defaultModuleMetadataProvider);
+        if (!TextUtils.isEmpty(packageName)) {
+            return null;
+        }
+
+        try {
+            return new VersionedPackage(packageName, mContext.getPackageManager().getPackageInfo(
+                            packageName, 0 /* flags */).getLongVersionCode());
+        } catch (PackageManager.NameNotFoundException e) {
+            Slog.w(TAG, "Module metadata provider not found");
+            return null;
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/rollback/RollbackStore.java b/services/core/java/com/android/server/rollback/RollbackStore.java
index c70f47d..d8e1f62 100644
--- a/services/core/java/com/android/server/rollback/RollbackStore.java
+++ b/services/core/java/com/android/server/rollback/RollbackStore.java
@@ -33,6 +33,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
 import java.time.Instant;
 import java.time.format.DateTimeParseException;
 import java.util.ArrayList;
@@ -201,11 +202,30 @@
     }
 
     /**
-     * Returns the directory where the code for a package should be stored for
-     * given rollback <code>data</code> and <code>packageName</code>.
+     * Creates a backup copy of the apk or apex for a package.
      */
-    File packageCodePathForAvailableRollback(RollbackData data, String packageName) {
-        return new File(data.backupDir, packageName);
+    static void backupPackageCode(RollbackData data, String packageName, String codePath)
+            throws IOException {
+        File sourceFile = new File(codePath);
+        File targetDir = new File(data.backupDir, packageName);
+        targetDir.mkdirs();
+        File targetFile = new File(targetDir, sourceFile.getName());
+
+        // TODO: Copy by hard link instead to save on cpu and storage space?
+        Files.copy(sourceFile.toPath(), targetFile.toPath());
+    }
+
+    /**
+     * Returns the apk or apex file backed up for the given package.
+     * Returns null if none found.
+     */
+    static File getPackageCode(RollbackData data, String packageName) {
+        File targetDir = new File(data.backupDir, packageName);
+        File[] files = targetDir.listFiles();
+        if (files == null || files.length != 1) {
+            return null;
+        }
+        return files[0];
     }
 
     /**
diff --git a/services/core/java/com/android/server/stats/StatsCompanionService.java b/services/core/java/com/android/server/stats/StatsCompanionService.java
index 2be78fe3..48e64338 100644
--- a/services/core/java/com/android/server/stats/StatsCompanionService.java
+++ b/services/core/java/com/android/server/stats/StatsCompanionService.java
@@ -15,6 +15,8 @@
  */
 package com.android.server.stats;
 
+import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
+import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
 import static android.os.Process.getPidsForCommands;
 import static android.os.Process.getUidForPid;
 
@@ -41,6 +43,7 @@
 import android.content.IntentSender;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
 import android.content.pm.UserInfo;
 import android.hardware.fingerprint.FingerprintManager;
 import android.net.ConnectivityManager;
@@ -98,6 +101,7 @@
 import com.android.internal.os.BinderCallsStats.ExportedCallStat;
 import com.android.internal.os.KernelCpuSpeedReader;
 import com.android.internal.os.KernelCpuThreadReader;
+import com.android.internal.os.KernelCpuThreadReaderSettingsObserver;
 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
@@ -203,7 +207,7 @@
             "zygote64",
     };
 
-    private static final int CPU_TIME_PER_THREAD_FREQ_NUM_FREQUENCIES = 8;
+    private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
 
     static final class CompanionHandler extends Handler {
         CompanionHandler(Looper looper) {
@@ -332,7 +336,8 @@
         handlerThread.start();
         mHandler = new CompanionHandler(handlerThread.getLooper());
 
-        mKernelCpuThreadReader = KernelCpuThreadReader.create();
+        mKernelCpuThreadReader =
+                KernelCpuThreadReaderSettingsObserver.getSettingsModifiedReader(mContext);
     }
 
     @Override
@@ -1678,8 +1683,8 @@
             return;
         }
         int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
-        if (cpuFrequencies.length != CPU_TIME_PER_THREAD_FREQ_NUM_FREQUENCIES) {
-            Slog.w(TAG, "Expected " + CPU_TIME_PER_THREAD_FREQ_NUM_FREQUENCIES
+        if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
+            Slog.w(TAG, "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
                     + " frequencies, but got " + cpuFrequencies.length);
             return;
         }
@@ -1703,9 +1708,17 @@
                 e.writeInt(threadCpuUsage.threadId);
                 e.writeString(processCpuUsage.processName);
                 e.writeString(threadCpuUsage.threadName);
-                for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_NUM_FREQUENCIES; k++) {
-                    e.writeInt(cpuFrequencies[k]);
-                    e.writeInt(threadCpuUsage.usageTimesMillis[k]);
+                for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES; k++) {
+                    if (k < cpuFrequencies.length) {
+                        e.writeInt(cpuFrequencies[k]);
+                        e.writeInt(threadCpuUsage.usageTimesMillis[k]);
+                    } else {
+                        // If we have no more frequencies to write, we still must write empty data.
+                        // We know that this data is empty (and not just zero) because all
+                        // frequencies are expected to be greater than zero
+                        e.writeInt(0);
+                        e.writeInt(0);
+                    }
                 }
                 pulledData.add(e);
             }
@@ -1783,6 +1796,65 @@
         pulledData.add(e);
     }
 
+    private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            PackageManager pm = mContext.getPackageManager();
+
+            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+
+            int numUsers = users.size();
+            for (int userNum = 0; userNum < numUsers; userNum++) {
+                UserHandle user = users.get(userNum).getUserHandle();
+
+                List<PackageInfo> pkgs = pm.getInstalledPackagesAsUser(
+                        PackageManager.GET_PERMISSIONS, user.getIdentifier());
+
+                int numPkgs = pkgs.size();
+                for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
+                    PackageInfo pkg = pkgs.get(pkgNum);
+
+                    if (pkg.requestedPermissions == null) {
+                        continue;
+                    }
+
+                    int numPerms = pkg.requestedPermissions.length;
+                    for (int permNum  = 0; permNum < numPerms; permNum++) {
+                        String permName = pkg.requestedPermissions[permNum];
+
+                        PermissionInfo permissionInfo;
+                        try {
+                            permissionInfo = pm.getPermissionInfo(permName, 0);
+                        } catch (PackageManager.NameNotFoundException ignored) {
+                            continue;
+                        }
+
+                        if (permissionInfo.getProtection() != PROTECTION_DANGEROUS) {
+                            continue;
+                        }
+
+                        StatsLogEventWrapper e = new StatsLogEventWrapper(
+                                StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
+
+                        e.writeString(permName);
+                        e.writeInt(pkg.applicationInfo.uid);
+                        e.writeString(pkg.packageName);
+
+                        e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
+                                & REQUESTED_PERMISSION_GRANTED) != 0);
+
+                        pulledData.add(e);
+                    }
+                }
+            }
+        } catch (Throwable t) {
+            Log.e(TAG, "Could not read permissions", t);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
     /**
      * Add a RoleHolder atom for each package that holds a role.
      *
@@ -2015,6 +2087,10 @@
                 pullRoleHolders(elapsedNanos, wallClockNanos, ret);
                 break;
             }
+            case StatsLog.DANGEROUS_PERMISSION_STATE: {
+                pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
+                break;
+            }
             default:
                 Slog.w(TAG, "No such tagId data as " + tagId);
                 return null;
diff --git a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorService.java b/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorService.java
deleted file mode 100644
index 5f71b0b..0000000
--- a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorService.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.timezonedetector;
-
-import com.android.internal.util.DumpUtils;
-import com.android.server.SystemService;
-import android.app.timezonedetector.ITimeZoneDetectorService;
-import android.content.Context;
-import android.util.Slog;
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-
-public final class TimeZoneDetectorService extends ITimeZoneDetectorService.Stub {
-    private static final String TAG = "timezonedetector.TimeZoneDetectorService";
-
-    public static class Lifecycle extends SystemService {
-
-        public Lifecycle(Context context) {
-            super(context);
-        }
-
-        @Override
-        public void onStart() {
-            TimeZoneDetectorService service = TimeZoneDetectorService.create(getContext());
-            // Publish the binder service so it can be accessed from other (appropriately
-            // permissioned) processes.
-            publishBinderService(Context.TIME_ZONE_DETECTOR_SERVICE, service);
-        }
-    }
-
-    private final Context mContext;
-
-    private static TimeZoneDetectorService create(Context context) {
-        return new TimeZoneDetectorService(context);
-    }
-
-    public TimeZoneDetectorService(Context context) {
-        mContext = context;
-    }
-
-    @Override
-    public void stubbedCall() {
-        // Empty call for initial tests.
-        Slog.d(TAG, "stubbedCall() called");
-        // TODO: Remove when there are real methods.
-    }
-
-    @Override
-    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
-        // TODO: Implement when there is state.
-    }
-}
diff --git a/services/core/java/com/android/server/tv/TvInputHardwareManager.java b/services/core/java/com/android/server/tv/TvInputHardwareManager.java
old mode 100644
new mode 100755
index c1607e9..f08e585
--- a/services/core/java/com/android/server/tv/TvInputHardwareManager.java
+++ b/services/core/java/com/android/server/tv/TvInputHardwareManager.java
@@ -24,7 +24,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.pm.PackageManager;
 import android.hardware.hdmi.HdmiControlManager;
 import android.hardware.hdmi.HdmiDeviceInfo;
 import android.hardware.hdmi.HdmiHotplugEvent;
@@ -46,7 +45,6 @@
 import android.media.tv.TvInputHardwareInfo;
 import android.media.tv.TvInputInfo;
 import android.media.tv.TvStreamConfig;
-import android.os.Binder;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Message;
@@ -56,7 +54,6 @@
 import android.util.Slog;
 import android.util.SparseArray;
 import android.util.SparseBooleanArray;
-import android.view.KeyEvent;
 import android.view.Surface;
 
 import com.android.internal.util.DumpUtils;
@@ -943,7 +940,7 @@
                         sinkChannelMask = sinkConfig.channelMask();
                     }
                     if (sinkFormat == AudioFormat.ENCODING_DEFAULT) {
-                        sinkChannelMask = sinkConfig.format();
+                        sinkFormat = sinkConfig.format();
                     }
                 }
 
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index aa0c62c..38e8785 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -2065,7 +2065,8 @@
      * - should be either the topmost in task, or right below the top activity that is finishing
      * If all of these conditions are not met at the same time, the activity cannot be made active.
      */
-    private boolean shouldMakeActive(ActivityRecord activeActivity) {
+    @VisibleForTesting
+    boolean shouldMakeActive(ActivityRecord activeActivity) {
         // If the activity is stopped, stopping, cycle to an active state. We avoid doing
         // this when there is an activity waiting to become translucent as the extra binder
         // calls will lead to noticeable jank. A later call to
@@ -2080,6 +2081,11 @@
             return false;
         }
 
+        if (!mStackSupervisor.readyToResume()) {
+            // Making active is currently deferred (e.g. because an activity launch is in progress).
+            return false;
+        }
+
         if (this.mLaunchTaskBehind) {
             // This activity is being launched from behind, which means that it's not intended to be
             // presented to user right now, even if it's set to be visible.
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index d1cd1db..1d71d876 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -980,6 +980,10 @@
         if (mSupervisor.mRecentTasks.isCallerRecents(callingUid)) {
             return false;
         }
+        // don't abort if the callingPackage is a device owner
+        if (mService.getDevicePolicyManager().isDeviceOwnerApp(callingPackage)) {
+            return false;
+        }
         // anything that has fallen through would currently be aborted
         Slog.w(TAG, "Background activity start [callingPackage: " + callingPackage
                 + "; callingUid: " + callingUid
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 09ef4b9..14c4814 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -151,6 +151,7 @@
 import android.app.WaitResult;
 import android.app.WindowConfiguration;
 import android.app.admin.DevicePolicyCache;
+import android.app.admin.DevicePolicyManager;
 import android.app.assist.AssistContent;
 import android.app.assist.AssistStructure;
 import android.app.usage.UsageStatsManagerInternal;
@@ -362,6 +363,7 @@
     WindowManagerService mWindowManager;
     private UserManagerService mUserManager;
     private AppOpsService mAppOpsService;
+    private DevicePolicyManager mDpm;
     /** All active uids in the system. */
     private final SparseArray<Integer> mActiveUids = new SparseArray<>();
     private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
@@ -836,6 +838,13 @@
         return mAppOpsService;
     }
 
+    DevicePolicyManager getDevicePolicyManager() {
+        if (mDpm == null) {
+            mDpm = mContext.getSystemService(DevicePolicyManager.class);
+        }
+        return mDpm;
+    }
+
     boolean hasUserRestriction(String restriction, int userId) {
         return getUserManager().hasUserRestriction(restriction, userId);
     }
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index a52f1af..29ba166 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -978,8 +978,8 @@
     }
 
     @Override
-    void onParentSet() {
-        super.onParentSet();
+    void onParentChanged() {
+        super.onParentChanged();
 
         final Task task = getTask();
 
@@ -2852,10 +2852,13 @@
         // to check super here.
         final boolean reallyAnimating = super.isSelfAnimating();
         final boolean show = !isHidden() || reallyAnimating;
-        if (show && !mLastSurfaceShowing) {
-            mPendingTransaction.show(mSurfaceControl);
-        } else if (!show && mLastSurfaceShowing) {
-            mPendingTransaction.hide(mSurfaceControl);
+
+        if (mSurfaceControl != null) {
+            if (show && !mLastSurfaceShowing) {
+                mPendingTransaction.show(mSurfaceControl);
+            } else if (!show && mLastSurfaceShowing) {
+                mPendingTransaction.hide(mSurfaceControl);
+            }
         }
         if (mThumbnail != null) {
             mThumbnail.setShowing(mPendingTransaction, show);
diff --git a/services/core/java/com/android/server/wm/BlackFrame.java b/services/core/java/com/android/server/wm/BlackFrame.java
index fd72a4a..c90f5bf 100644
--- a/services/core/java/com/android/server/wm/BlackFrame.java
+++ b/services/core/java/com/android/server/wm/BlackFrame.java
@@ -48,7 +48,7 @@
 
             surface = dc.makeOverlay()
                     .setName("BlackSurface")
-                    .setColorLayer()
+                    .setColorLayer(true)
                     .setParent(null) // TODO: Work-around for b/69259549
                     .build();
             transaction.setWindowCrop(surface, w, h);
diff --git a/services/core/java/com/android/server/wm/ConfigurationContainer.java b/services/core/java/com/android/server/wm/ConfigurationContainer.java
index ce3fb51..d86cf0f 100644
--- a/services/core/java/com/android/server/wm/ConfigurationContainer.java
+++ b/services/core/java/com/android/server/wm/ConfigurationContainer.java
@@ -532,7 +532,7 @@
     /**
      * Must be called when new parent for the container was set.
      */
-    protected void onParentChanged() {
+    void onParentChanged() {
         final ConfigurationContainer parent = getParent();
         // Removing parent usually means that we've detached this entity to destroy it or to attach
         // to another parent. In both cases we don't need to update the configuration now.
diff --git a/services/core/java/com/android/server/wm/Dimmer.java b/services/core/java/com/android/server/wm/Dimmer.java
index 8f6b67a..c39060e 100644
--- a/services/core/java/com/android/server/wm/Dimmer.java
+++ b/services/core/java/com/android/server/wm/Dimmer.java
@@ -164,7 +164,7 @@
     private SurfaceControl makeDimLayer() {
         return mHost.makeChildSurface(null)
                 .setParent(mHost.getSurfaceControl())
-                .setColorLayer()
+                .setColorLayer(true)
                 .setName("Dim Layer for - " + mHost.getName())
                 .build();
     }
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 080f965..9fb922f 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -31,11 +31,14 @@
 import static android.view.Display.FLAG_PRIVATE;
 import static android.view.Display.INVALID_DISPLAY;
 import static android.view.InsetsState.TYPE_IME;
+import static android.view.InsetsState.TYPE_NAVIGATION_BAR;
+import static android.view.InsetsState.TYPE_TOP_BAR;
 import static android.view.Surface.ROTATION_0;
 import static android.view.Surface.ROTATION_180;
 import static android.view.Surface.ROTATION_270;
 import static android.view.Surface.ROTATION_90;
 import static android.view.View.GONE;
+import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
 import static android.view.WindowManager.DOCKED_BOTTOM;
 import static android.view.WindowManager.DOCKED_INVALID;
 import static android.view.WindowManager.DOCKED_TOP;
@@ -170,6 +173,7 @@
 import android.view.SurfaceControl.Transaction;
 import android.view.SurfaceSession;
 import android.view.View;
+import android.view.ViewRootImpl;
 import android.view.WindowManager;
 import android.view.WindowManagerPolicyConstants.PointerEventListener;
 
@@ -892,9 +896,7 @@
         mDividerControllerLocked = new DockedStackDividerController(service, this);
         mPinnedStackControllerLocked = new PinnedStackController(service, this);
 
-        final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(mSession)
-                .setOpaque(true)
-                .setContainerLayer();
+        final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(mSession).setOpaque(true);
         mWindowingLayer = b.setName("Display Root").build();
         mOverlayLayer = b.setName("Display Overlays").build();
 
@@ -4387,8 +4389,8 @@
         }
 
         @Override
-        void onParentSet() {
-            super.onParentSet();
+        void onParentChanged() {
+            super.onParentChanged();
             if (getParent() != null) {
                 mAppAnimationLayer = makeChildSurface(null)
                         .setName("animationLayer")
@@ -4598,7 +4600,7 @@
     @Override
     SurfaceControl.Builder makeChildSurface(WindowContainer child) {
         SurfaceSession s = child != null ? child.getSession() : getSession();
-        final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(s).setContainerLayer();
+        final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(s);
         if (child == null) {
             return b;
         }
@@ -4643,10 +4645,10 @@
     }
 
     @Override
-    void onParentSet() {
+    void onParentChanged() {
         // Since we are the top of the SurfaceControl hierarchy here
         // we create the root surfaces explicitly rather than chaining
-        // up as the default implementation in onParentSet does. So we
+        // up as the default implementation in onParentChanged does. So we
         // explicitly do NOT call super here.
     }
 
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index 2b2231a..3f77e1c 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -164,7 +164,7 @@
 
         if (mInputSurface == null) {
             mInputSurface = mService.makeSurfaceBuilder(mService.mRoot.getDisplayContent(displayId)
-                    .getSession()).setContainerLayer()
+                    .getSession()).setContainerLayer(true)
                     .setName("Drag and Drop Input Consumer").build();
         }
         final InputWindowHandle h = getInputWindowHandle();
diff --git a/services/core/java/com/android/server/wm/InputConsumerImpl.java b/services/core/java/com/android/server/wm/InputConsumerImpl.java
index ab95e4b..4df5a0b 100644
--- a/services/core/java/com/android/server/wm/InputConsumerImpl.java
+++ b/services/core/java/com/android/server/wm/InputConsumerImpl.java
@@ -22,11 +22,13 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
-import android.view.InputApplicationHandle;
 import android.view.InputChannel;
+import android.view.WindowManager;
+
+import android.view.InputApplicationHandle;
 import android.view.InputWindowHandle;
 import android.view.SurfaceControl;
-import android.view.WindowManager;
+import android.util.Slog;
 
 import java.io.PrintWriter;
 
@@ -87,7 +89,7 @@
         mWindowHandle.scaleFactor = 1.0f;
 
         mInputSurface = mService.makeSurfaceBuilder(mService.mRoot.getDisplayContent(displayId)
-                .getSession()).setContainerLayer().setName("Input Consumer " + name)
+                .getSession()).setContainerLayer(true).setName("Input Consumer " + name)
                 .build();
     }
 
diff --git a/services/core/java/com/android/server/wm/Letterbox.java b/services/core/java/com/android/server/wm/Letterbox.java
index 18fce67..434084c 100644
--- a/services/core/java/com/android/server/wm/Letterbox.java
+++ b/services/core/java/com/android/server/wm/Letterbox.java
@@ -149,7 +149,7 @@
 
         private void createSurface() {
             mSurface = mFactory.get().setName("Letterbox - " + mType)
-                    .setFlags(HIDDEN).setColorLayer().build();
+                    .setFlags(HIDDEN).setColorLayer(true).build();
             mSurface.setLayer(-1);
             mSurface.setColor(new float[]{0, 0, 0});
         }
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 476bd6e..7a86c96 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -252,8 +252,8 @@
     }
 
     @Override
-    void onParentSet() {
-        super.onParentSet();
+    void onParentChanged() {
+        super.onParentChanged();
 
         // Update task bounds if needed.
         adjustBoundsForDisplayChangeIfNeeded(getDisplayContent());
diff --git a/services/core/java/com/android/server/wm/TaskPositioningController.java b/services/core/java/com/android/server/wm/TaskPositioningController.java
index cdcb857..9163165 100644
--- a/services/core/java/com/android/server/wm/TaskPositioningController.java
+++ b/services/core/java/com/android/server/wm/TaskPositioningController.java
@@ -83,7 +83,7 @@
         final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
         if (mInputSurface == null) {
             mInputSurface = mService.makeSurfaceBuilder(dc.getSession())
-                    .setContainerLayer()
+                    .setContainerLayer(true)
                     .setName("Drag and Drop Input Consumer").build();
         }
 
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
index e6d646c..3c9a46b 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
@@ -26,6 +26,7 @@
 import android.app.ActivityManager.TaskSnapshot;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
+import android.hardware.HardwareBuffer;
 import android.os.Process;
 import android.os.SystemClock;
 import android.util.ArraySet;
@@ -359,7 +360,11 @@
         }
 
         boolean writeBuffer() {
-            final Bitmap bitmap = Bitmap.createHardwareBitmap(mSnapshot.getSnapshot());
+            // TODO(b/116112787) TaskSnapshot needs bookkeep the ColorSpace of the
+            // hardware bitmap when created.
+            final Bitmap bitmap = Bitmap.wrapHardwareBuffer(
+                    HardwareBuffer.createFromGraphicBuffer(mSnapshot.getSnapshot()),
+                    mSnapshot.getColorSpace());
             if (bitmap == null) {
                 Slog.e(TAG, "Invalid task snapshot hw bitmap");
                 return false;
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
index 938c8b4..2d3e3ae 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
@@ -61,12 +61,12 @@
 import android.util.Slog;
 import android.view.DisplayCutout;
 import android.view.IWindowSession;
-import android.view.InsetsState;
 import android.view.Surface;
 import android.view.SurfaceControl;
 import android.view.SurfaceSession;
 import android.view.View;
 import android.view.ViewGroup.LayoutParams;
+import android.view.InsetsState;
 import android.view.WindowManager;
 import android.view.WindowManagerGlobal;
 
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 59549e0..6d4bcdc 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -818,7 +818,7 @@
 
         updateSurfaceBounds();
         if (mAnimationBackgroundSurface == null) {
-            mAnimationBackgroundSurface = makeChildSurface(null).setColorLayer()
+            mAnimationBackgroundSurface = makeChildSurface(null).setColorLayer(true)
                     .setName("animation background stackId=" + mStackId)
                     .build();
         }
@@ -996,8 +996,8 @@
     }
 
     @Override
-    void onParentSet() {
-        super.onParentSet();
+    void onParentChanged() {
+        super.onParentChanged();
 
         if (getParent() != null || mDisplayContent == null) {
             return;
diff --git a/services/core/java/com/android/server/wm/WallpaperController.java b/services/core/java/com/android/server/wm/WallpaperController.java
index c15afc5..74fb3fa 100644
--- a/services/core/java/com/android/server/wm/WallpaperController.java
+++ b/services/core/java/com/android/server/wm/WallpaperController.java
@@ -34,8 +34,10 @@
 import static com.android.server.wm.WindowManagerService.H.WALLPAPER_DRAW_PENDING_TIMEOUT;
 
 import android.graphics.Bitmap;
+import android.graphics.ColorSpace;
 import android.graphics.GraphicBuffer;
 import android.graphics.Rect;
+import android.hardware.HardwareBuffer;
 import android.os.Bundle;
 import android.os.Debug;
 import android.os.IBinder;
@@ -729,7 +731,10 @@
             Slog.w(TAG_WM, "Failed to screenshot wallpaper");
             return null;
         }
-        return Bitmap.createHardwareBitmap(wallpaperBuffer);
+        // TODO(b/116112787) Now that hardware bitmap creation can take color space, we
+        // should continue to fix screenshot.
+        return Bitmap.wrapHardwareBuffer(HardwareBuffer.createFromGraphicBuffer(wallpaperBuffer),
+                                         ColorSpace.get(ColorSpace.Named.SRGB));
     }
 
     private WindowState getTopVisibleWallpaper() {
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 1905877..f330569 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -161,23 +161,16 @@
 
     final protected void setParent(WindowContainer<WindowContainer> parent) {
         mParent = parent;
-        // Removing parent usually means that we've detached this entity to destroy it or to attach
-        // to another parent. In both cases we don't need to update the configuration now.
-        if (mParent != null) {
-            // Update full configuration of this container and all its children.
-            onConfigurationChanged(mParent.getConfiguration());
-            // Update merged override configuration of this container and all its children.
-            onMergedOverrideConfigurationChanged();
-        }
-
-        onParentSet();
+        onParentChanged();
     }
 
     /**
      * Callback that is triggered when @link WindowContainer#setParent(WindowContainer)} was called.
      * Supposed to be overridden and contain actions that should be executed after parent was set.
      */
-    void onParentSet() {
+    @Override
+    void onParentChanged() {
+        super.onParentChanged();
         if (mParent == null) {
             return;
         }
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index 8da39b6..37e2200 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -364,8 +364,10 @@
         return mAllowBackgroundActivityStarts;
     }
 
-    public void setInstrumenting(boolean instrumenting) {
+    public void setInstrumenting(boolean instrumenting,
+            boolean hasBackgroundActivityStartPrivileges) {
         mInstrumenting = instrumenting;
+        mInstrumentingWithBackgroundActivityStartPrivileges = hasBackgroundActivityStartPrivileges;
     }
 
     boolean isInstrumenting() {
@@ -373,15 +375,6 @@
     }
 
     /**
-     * {@see isInstrumentingWithBackgroundActivityStartPrivileges}
-     */
-    public void setInstrumentingWithBackgroundActivityStartPrivileges(
-            boolean instrumentingWithBackgroundActivityStartPrivileges) {
-        mInstrumentingWithBackgroundActivityStartPrivileges =
-                instrumentingWithBackgroundActivityStartPrivileges;
-    }
-
-    /**
      * @return true if the instrumentation was started by a holder of
      * START_ACTIVITIES_FROM_BACKGROUND permission
      */
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 62e7200..05c19b5 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -747,8 +747,8 @@
     }
 
     @Override
-    void onParentSet() {
-        super.onParentSet();
+    void onParentChanged() {
+        super.onParentChanged();
         setDrawnStateEvaluated(false /*evaluated*/);
 
         getDisplayContent().reapplyMagnificationSpec();
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index f176bc4..8f5ce74 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -14078,6 +14078,10 @@
 
         enforceCrossUsersPermission(userHandle);
         synchronized (getLockObject()) {
+            if (mInjector.settingsSecureGetIntForUser(
+                    Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) {
+                return false;
+            }
             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
             if (admin != null) {
                 if (admin.mCrossProfileCalendarPackages == null) {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 6733440..71ed5ae 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -263,8 +263,6 @@
             "com.android.internal.car.CarServiceHelperService";
     private static final String TIME_DETECTOR_SERVICE_CLASS =
             "com.android.server.timedetector.TimeDetectorService$Lifecycle";
-    private static final String TIME_ZONE_DETECTOR_SERVICE_CLASS =
-            "com.android.server.timezonedetector.TimeZoneDetectorService$Lifecycle";
     private static final String ACCESSIBILITY_MANAGER_SERVICE_CLASS =
             "com.android.server.accessibility.AccessibilityManagerService$Lifecycle";
     private static final String ADB_SERVICE_CLASS =
@@ -1428,14 +1426,6 @@
                     reportWtf("starting StartTimeDetectorService service", e);
                 }
                 traceEnd();
-
-                traceBeginAndSlog("StartTimeZoneDetectorService");
-                try {
-                    mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS);
-                } catch (Throwable e) {
-                    reportWtf("starting StartTimeZoneDetectorService service", e);
-                }
-                traceEnd();
             }
 
             if (!isWatch) {
diff --git a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
index d4bb636..089a79b 100644
--- a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
@@ -194,6 +194,7 @@
                 false /* sticky */,
                 false /* initialSticky */,
                 userId,
-                false /* allowBackgroundActivityStarts */);
+                false, /* allowBackgroundActivityStarts */
+                false /* timeoutExempt */ );
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java b/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
index a01d589..0355e84 100644
--- a/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
+++ b/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
@@ -1156,6 +1156,11 @@
     }
 
     @Override
+    public String getAppPredictionServicePackageName() {
+        return null;
+    }
+
+    @Override
     public boolean isPackageStateProtected(String packageName, int userId) throws RemoteException {
         return false;
     }
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index 535198b..9ac91dd 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -5278,6 +5278,35 @@
         assertTrue(actual.containsAll(expected));
     }
 
+    public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
+        setAsProfileOwner(admin1);
+        dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
+        when(getServices().settings.settingsSecureGetIntForUser(
+                Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
+                0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
+        assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
+    }
+
+    public void testIsPackageAllowedToAccessCalendar_settingOff() {
+        final String testPackage = "TEST_PACKAGE";
+        setAsProfileOwner(admin1);
+        dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
+        when(getServices().settings.settingsSecureGetIntForUser(
+                Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
+                0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
+        assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
+    }
+
+    public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
+        final String testPackage = "TEST_PACKAGE";
+        setAsProfileOwner(admin1);
+        dpm.setCrossProfileCalendarPackages(admin1, null);
+        when(getServices().settings.settingsSecureGetIntForUser(
+                Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
+                0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
+        assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
+    }
+
     private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
         final long ident = mServiceContext.binder.clearCallingIdentity();
         mServiceContext.binder.callingUid =
diff --git a/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java b/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
index 79a654b..e3b1245 100644
--- a/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
@@ -37,6 +37,9 @@
 import android.hardware.SensorEventListener;
 import android.hardware.display.AmbientBrightnessDayStats;
 import android.hardware.display.BrightnessChangeEvent;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.DisplayedContentSample;
+import android.hardware.display.DisplayedContentSamplingAttributes;
 import android.os.BatteryManager;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -47,6 +50,7 @@
 import android.os.UserManager;
 import android.provider.Settings;
 import android.util.AtomicFile;
+import android.view.Display;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
@@ -116,28 +120,81 @@
         assertTrue(mInjector.mIdleScheduled);
         mInjector.sendScreenChange(/*screen on */ true);
         assertNotNull(mInjector.mSensorListener);
+        assertTrue(mInjector.mColorSamplingEnabled);
 
         mInjector.sendScreenChange(/*screen on */ false);
         assertNull(mInjector.mSensorListener);
+        assertFalse(mInjector.mColorSamplingEnabled);
 
         // Turn screen on while brightness mode is manual
         mInjector.setBrightnessMode(/* isBrightnessModeAutomatic */ false);
         mInjector.sendScreenChange(/*screen on */ true);
         assertNull(mInjector.mSensorListener);
+        assertFalse(mInjector.mColorSamplingEnabled);
 
         // Set brightness mode to automatic while screen is off.
         mInjector.sendScreenChange(/*screen on */ false);
         mInjector.setBrightnessMode(/* isBrightnessModeAutomatic */ true);
         assertNull(mInjector.mSensorListener);
+        assertFalse(mInjector.mColorSamplingEnabled);
 
         // Turn on screen while brightness mode is automatic.
         mInjector.sendScreenChange(/*screen on */ true);
         assertNotNull(mInjector.mSensorListener);
+        assertTrue(mInjector.mColorSamplingEnabled);
 
         mTracker.stop();
         assertNull(mInjector.mSensorListener);
         assertNull(mInjector.mBroadcastReceiver);
         assertFalse(mInjector.mIdleScheduled);
+        assertFalse(mInjector.mColorSamplingEnabled);
+    }
+
+    @Test
+    public void testNoColorSampling_WrongPixelFormat() {
+        mInjector.mDefaultSamplingAttributes =
+                new DisplayedContentSamplingAttributes(
+                        0x23,
+                        mInjector.mDefaultSamplingAttributes.getDataspace(),
+                        mInjector.mDefaultSamplingAttributes.getComponentMask());
+        startTracker(mTracker);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
+    }
+
+    @Test
+    public void testNoColorSampling_MissingComponent() {
+        mInjector.mDefaultSamplingAttributes =
+                new DisplayedContentSamplingAttributes(
+                        mInjector.mDefaultSamplingAttributes.getPixelFormat(),
+                        mInjector.mDefaultSamplingAttributes.getDataspace(),
+                        0x2);
+        startTracker(mTracker);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
+    }
+
+    @Test
+    public void testNoColorSampling_NoSupport() {
+        mInjector.mDefaultSamplingAttributes = null;
+        startTracker(mTracker);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
+    }
+
+    @Test
+    public void testColorSampling_FrameRateChange() {
+        startTracker(mTracker);
+        assertTrue(mInjector.mColorSamplingEnabled);
+        assertNotNull(mInjector.mDisplayListener);
+        int noFramesSampled = mInjector.mNoColorSamplingFrames;
+        mInjector.mFrameRate = 120.0f;
+        // Wrong display
+        mInjector.mDisplayListener.onDisplayChanged(Display.DEFAULT_DISPLAY + 10);
+        assertEquals(noFramesSampled, mInjector.mNoColorSamplingFrames);
+        // Correct display
+        mInjector.mDisplayListener.onDisplayChanged(Display.DEFAULT_DISPLAY);
+        assertEquals(noFramesSampled * 2, mInjector.mNoColorSamplingFrames);
     }
 
     @Test
@@ -149,26 +206,41 @@
         assertNotNull(mInjector.mBroadcastReceiver);
         assertNotNull(mInjector.mContentObserver);
         assertTrue(mInjector.mIdleScheduled);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
 
         mInjector.setBrightnessMode(/*isBrightnessModeAutomatic*/ true);
         assertNotNull(mInjector.mSensorListener);
+        assertTrue(mInjector.mColorSamplingEnabled);
+        assertNotNull(mInjector.mDisplayListener);
 
         SensorEventListener listener = mInjector.mSensorListener;
+        DisplayManager.DisplayListener displayListener = mInjector.mDisplayListener;
         mInjector.mSensorListener = null;
+        mInjector.mColorSamplingEnabled = false;
+        mInjector.mDisplayListener = null;
         // Duplicate notification
         mInjector.setBrightnessMode(/*isBrightnessModeAutomatic*/ true);
         // Sensor shouldn't have been registered as it was already registered.
         assertNull(mInjector.mSensorListener);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
         mInjector.mSensorListener = listener;
+        mInjector.mDisplayListener = displayListener;
+        mInjector.mColorSamplingEnabled = true;
 
         mInjector.setBrightnessMode(/*isBrightnessModeAutomatic*/ false);
         assertNull(mInjector.mSensorListener);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
 
         mTracker.stop();
         assertNull(mInjector.mSensorListener);
         assertNull(mInjector.mBroadcastReceiver);
         assertNull(mInjector.mContentObserver);
         assertFalse(mInjector.mIdleScheduled);
+        assertFalse(mInjector.mColorSamplingEnabled);
+        assertNull(mInjector.mDisplayListener);
     }
 
     @Test
@@ -229,6 +301,8 @@
         assertEquals(3333, event.colorTemperature);
         assertEquals("a.package", event.packageName);
         assertEquals(0, event.userId);
+        assertArrayEquals(new long[] {1, 10, 100, 1000, 300, 30, 10, 1}, event.colorValueBuckets);
+        assertEquals(10000, event.colorSampleDuration);
 
         assertEquals(1, eventsNoPackage.size());
         assertNull(eventsNoPackage.get(0).packageName);
@@ -342,7 +416,8 @@
                 + "lastNits=\"32\" "
                 + "batteryLevel=\"0.5\" nightMode=\"true\" colorTemperature=\"3235\"\n"
                 + "lux=\"132.2,131.1\" luxTimestamps=\""
-                + Long.toString(someTimeAgo) + "," + Long.toString(someTimeAgo) + "\"/>"
+                + Long.toString(someTimeAgo) + "," + Long.toString(someTimeAgo) + "\""
+                + "colorSampleDuration=\"3456\" colorValueBuckets=\"123,598,23,19\"/>"
                 // Event that is too old so shouldn't show up.
                 + "<event nits=\"142\" timestamp=\""
                 + Long.toString(twoMonthsAgo) + "\" packageName=\""
@@ -368,6 +443,7 @@
         assertTrue(event.isDefaultBrightnessConfig);
         assertEquals(0.5f, event.powerBrightnessFactor, FLOAT_DELTA);
         assertTrue(event.isUserSetBrightness);
+        assertNull(event.colorValueBuckets);
 
         events = tracker.getEvents(1, true).getList();
         assertEquals(1, events.size());
@@ -386,6 +462,8 @@
         assertFalse(event.isDefaultBrightnessConfig);
         assertEquals(1.0, event.powerBrightnessFactor, FLOAT_DELTA);
         assertFalse(event.isUserSetBrightness);
+        assertEquals(3456L, event.colorSampleDuration);
+        assertArrayEquals(new long[] {123L, 598L, 23L, 19L}, event.colorValueBuckets);
 
         // Pretend user 1 is a profile of user 0.
         mInjector.mProfiles = new int[]{0, 1};
@@ -481,6 +559,8 @@
         assertEquals(0.5f, event.powerBrightnessFactor, FLOAT_DELTA);
         assertTrue(event.isUserSetBrightness);
         assertFalse(event.isDefaultBrightnessConfig);
+        assertArrayEquals(new long[] {1, 10, 100, 1000, 300, 30, 10, 1}, event.colorValueBuckets);
+        assertEquals(10000, event.colorSampleDuration);
     }
 
     @Test
@@ -546,6 +626,7 @@
         builder.setNightMode(false);
         builder.setColorTemperature(345);
         builder.setLastBrightness(50f);
+        builder.setColorValues(new long[] {23, 34, 45}, 1000L);
         BrightnessChangeEvent event = builder.build();
 
         event.writeToParcel(parcel, 0);
@@ -568,6 +649,8 @@
         assertEquals(event.nightMode, event2.nightMode);
         assertEquals(event.colorTemperature, event2.colorTemperature);
         assertEquals(event.lastBrightness, event2.lastBrightness, FLOAT_DELTA);
+        assertArrayEquals(event.colorValueBuckets, event2.colorValueBuckets);
+        assertEquals(event.colorSampleDuration, event2.colorSampleDuration);
 
         parcel = Parcel.obtain();
         builder.setBatteryLevel(Float.NaN);
@@ -714,6 +797,7 @@
     private class TestInjector extends BrightnessTracker.Injector {
         SensorEventListener mSensorListener;
         BroadcastReceiver mBroadcastReceiver;
+        DisplayManager.DisplayListener mDisplayListener;
         Map<String, Integer> mSecureIntSettings = new HashMap<>();
         long mCurrentTimeMillis = System.currentTimeMillis();
         long mElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
@@ -723,6 +807,12 @@
         int[] mProfiles;
         ContentObserver mContentObserver;
         boolean mIsBrightnessModeAutomatic = true;
+        boolean mColorSamplingEnabled = false;
+        DisplayedContentSamplingAttributes mDefaultSamplingAttributes =
+                new DisplayedContentSamplingAttributes(0x37, 0, 0x4);
+        float mFrameRate = 60.0f;
+        int mNoColorSamplingFrames;
+
 
         public TestInjector(Handler handler) {
             mHandler = handler;
@@ -882,5 +972,43 @@
             return mSecureIntSettings.getOrDefault(Settings.Secure.NIGHT_DISPLAY_ACTIVATED,
                     0) == 1;
         }
+
+        @Override
+        public DisplayedContentSample sampleColor(int noFramesToSample) {
+            return new DisplayedContentSample(600L,
+                    null,
+                    null,
+                     new long[] {1, 10, 100, 1000, 300, 30, 10, 1},
+                    null);
+        }
+
+        @Override
+        public float getFrameRate(Context context) {
+            return mFrameRate;
+        }
+
+        @Override
+        public DisplayedContentSamplingAttributes getSamplingAttributes() {
+            return mDefaultSamplingAttributes;
+        }
+
+        @Override
+        public boolean enableColorSampling(boolean enable, int noFrames) {
+            mColorSamplingEnabled = enable;
+            mNoColorSamplingFrames = noFrames;
+            return true;
+        }
+
+        @Override
+        public void registerDisplayListener(Context context,
+                DisplayManager.DisplayListener listener, Handler handler) {
+            mDisplayListener = listener;
+        }
+
+        @Override
+        public void unRegisterDisplayListener(Context context,
+                DisplayManager.DisplayListener listener) {
+            mDisplayListener = null;
+        }
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySaverPolicyTest.java b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySaverPolicyTest.java
index 9cc2b10..e32a789 100644
--- a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySaverPolicyTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySaverPolicyTest.java
@@ -21,8 +21,6 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Mockito.mock;
-
 import android.content.Context;
 import android.os.PowerManager;
 import android.os.PowerManager.ServiceType;
@@ -34,10 +32,8 @@
 
 import com.android.frameworks.servicestests.R;
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
 import com.android.server.power.batterysaver.BatterySaverPolicy.Policy;
 
-import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 /**
@@ -87,9 +83,6 @@
         }
     }
 
-    @Mock
-    MetricsLogger mMetricsLogger = mock(MetricsLogger.class);
-
     private BatterySaverPolicyForTest mBatterySaverPolicy;
 
     private final ArrayMap<String, String> mMockGlobalSettings = new ArrayMap<>();
@@ -100,7 +93,7 @@
         MockitoAnnotations.initMocks(this);
         final Object lock = new Object();
         mBatterySaverPolicy = new BatterySaverPolicyForTest(lock, getContext(),
-                new BatterySavingStats(lock, mMetricsLogger));
+                new BatterySavingStats(lock));
         mBatterySaverPolicy.systemReady();
 
         mBatterySaverPolicy.setPolicyLevel(POLICY_LEVEL_FULL);
diff --git a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
index ba61fd2..76239fc 100644
--- a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
@@ -30,14 +30,12 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.server.power.batterysaver.BatterySavingStats.BatterySaverState;
 import com.android.server.power.batterysaver.BatterySavingStats.DozeState;
 import com.android.server.power.batterysaver.BatterySavingStats.InteractiveState;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
 
 import java.io.ByteArrayOutputStream;
 import java.io.PrintWriter;
@@ -54,7 +52,7 @@
         private int mBatteryLevel = 1_000_000_000;
 
         private BatterySavingStatsTestable() {
-            super(new Object(), mMetricsLogger);
+            super(new Object());
         }
 
         @Override
@@ -104,23 +102,13 @@
 
     public MetricsLogger mMetricsLogger = mock(MetricsLogger.class);
 
-    private boolean sendTronEvents;
-
     @Test
-    public void testAll_withTron() {
-        sendTronEvents = true;
-        checkAll();
-    }
-
-    @Test
-    public void testAll_noTron() {
-        sendTronEvents = false;
+    public void testAll() {
         checkAll();
     }
 
     private void checkAll() {
         final BatterySavingStatsTestable target = new BatterySavingStatsTestable();
-        target.setSendTronLog(sendTronEvents);
 
         target.assertDumpable();
 
@@ -240,46 +228,13 @@
                 target.toDebugString());
     }
 
-    private void assertLog(boolean batterySaver, boolean interactive, long deltaTimeMs,
-            int deltaBatteryLevelUa, int deltaBatteryLevelPercent) {
-        if (sendTronEvents) {
-            ArgumentCaptor<LogMaker> ac = ArgumentCaptor.forClass(LogMaker.class);
-            verify(mMetricsLogger, times(1)).write(ac.capture());
-
-            LogMaker lm = ac.getValue();
-            assertEquals(MetricsEvent.BATTERY_SAVER, lm.getCategory());
-            assertEquals(batterySaver ? 1 : 0,
-                    lm.getTaggedData(MetricsEvent.RESERVED_FOR_LOGBUILDER_SUBTYPE));
-            assertEquals(interactive ? 1 : 0, lm.getTaggedData(MetricsEvent.FIELD_INTERACTIVE));
-            assertEquals(deltaTimeMs, lm.getTaggedData(MetricsEvent.FIELD_DURATION_MILLIS));
-
-            assertEquals(deltaBatteryLevelUa,
-                    (int) lm.getTaggedData(MetricsEvent.FIELD_START_BATTERY_UA)
-                            - (int) lm.getTaggedData(MetricsEvent.FIELD_END_BATTERY_UA));
-            assertEquals(deltaBatteryLevelPercent,
-                    (int) lm.getTaggedData(MetricsEvent.FIELD_START_BATTERY_PERCENT)
-                            - (int) lm.getTaggedData(MetricsEvent.FIELD_END_BATTERY_PERCENT));
-        } else {
-            verify(mMetricsLogger, times(0)).write(any(LogMaker.class));
-        }
-    }
-
-
-    @Test
-    public void testMetricsLogger_withTron() {
-        sendTronEvents = true;
-        checkMetricsLogger();
+    private void assertLog() {
+        verify(mMetricsLogger, times(0)).write(any(LogMaker.class));
     }
 
     @Test
-    public void testMetricsLogger_noTron() {
-        sendTronEvents = false;
-        checkMetricsLogger();
-    }
-
-    private void checkMetricsLogger() {
+    public void testMetricsLogger() {
         final BatterySavingStatsTestable target = new BatterySavingStatsTestable();
-        target.setSendTronLog(sendTronEvents);
 
         target.advanceClock(1);
         target.drainBattery(1000);
@@ -300,7 +255,7 @@
                 InteractiveState.NON_INTERACTIVE,
                 DozeState.NOT_DOZING);
 
-        assertLog(false, true, 60_000, 2000, 200);
+        assertLog();
 
         target.advanceClock(1);
         target.drainBattery(2000);
@@ -331,7 +286,7 @@
                 InteractiveState.INTERACTIVE,
                 DozeState.NOT_DOZING);
 
-        assertLog(false, false, 60_000 * 3, 2000 * 3, 200 * 3);
+        assertLog();
 
         target.advanceClock(10);
         target.drainBattery(10000);
@@ -339,7 +294,7 @@
         reset(mMetricsLogger);
         target.startCharging();
 
-        assertLog(true, true, 60_000 * 10, 10000, 1000);
+        assertLog();
 
         target.advanceClock(1);
         target.drainBattery(2000);
@@ -357,6 +312,6 @@
 
         target.startCharging();
 
-        assertLog(true, false, 60_000, 2000, 200);
+        assertLog();
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorServiceTest.java b/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorServiceTest.java
deleted file mode 100644
index 0936fff..0000000
--- a/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorServiceTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.timezonedetector;
-
-import android.content.Context;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-/**
- * Unit tests for the {@link TimeZoneDetectorService}.
- */
-@RunWith(AndroidJUnit4.class)
-public class TimeZoneDetectorServiceTest {
-
-    private TimeZoneDetectorService mTimeZoneDetectorService;
-
-    @Before
-    public void setUp() {
-        final Context context = InstrumentationRegistry.getContext();
-        mTimeZoneDetectorService = new TimeZoneDetectorService(context);
-    }
-
-    @Test
-    public void testStubbedCall() {
-        mTimeZoneDetectorService.stubbedCall();
-    }
-}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
index 68d3e4c..9c7e028 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
@@ -67,7 +67,7 @@
 
     @Test
     public void testZenPolicyNothingSetToNotificationPolicy() {
-        ZenModeConfig config = getMutedAllConfig();
+        ZenModeConfig config = getCustomConfig();
         ZenPolicy zenPolicy = new ZenPolicy.Builder().build();
         assertEquals(config.toNotificationPolicy(), config.toNotificationPolicy(zenPolicy));
     }
@@ -219,6 +219,25 @@
         return config;
     }
 
+    private ZenModeConfig getCustomConfig() {
+        ZenModeConfig config = new ZenModeConfig();
+        // Some sounds allowed
+        config.allowAlarms = true;
+        config.allowMedia = false;
+        config.allowSystem = false;
+        config.allowCalls = true;
+        config.allowRepeatCallers = true;
+        config.allowMessages = false;
+        config.allowReminders = false;
+        config.allowEvents = false;
+        config.areChannelsBypassingDnd = false;
+        config.allowCallsFrom = ZenModeConfig.SOURCE_ANYONE;
+        config.allowMessagesFrom = ZenModeConfig.SOURCE_ANYONE;
+
+        config.suppressedVisualEffects = 0;
+        return config;
+    }
+
     private ZenModeConfig getMutedAllConfig() {
         ZenModeConfig config = new ZenModeConfig();
         // No sounds allowed
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 319ffed..f1506a0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -368,4 +368,15 @@
         verify(mService.getLifecycleManager()).scheduleTransaction(eq(mActivity.app.getThread()),
                 eq(mActivity.appToken), eq(expected));
     }
+
+    @Test
+    public void testShouldMakeActive_deferredResume() {
+        mActivity.setState(ActivityStack.ActivityState.STOPPED, "Testing");
+
+        mSupervisor.beginDeferResume();
+        assertEquals(false, mActivity.shouldMakeActive(null /* activeActivity */));
+
+        mSupervisor.endDeferResume();
+        assertEquals(true, mActivity.shouldMakeActive(null /* activeActivity */));
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index 62ec838..60f1ae26 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -61,6 +61,7 @@
 
 import android.app.ActivityOptions;
 import android.app.IApplicationThread;
+import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
@@ -561,7 +562,7 @@
         runAndVerifyBackgroundActivityStartsSubtest("allowed_noStartsAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
     }
 
     /**
@@ -576,7 +577,7 @@
                 "disallowed_unsupportedUsecase_aborted", true,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
     }
 
     /**
@@ -591,56 +592,61 @@
         runAndVerifyBackgroundActivityStartsSubtest("disallowed_rootUid_notAborted", false,
                 Process.ROOT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest("disallowed_systemUid_notAborted", false,
                 Process.SYSTEM_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest("disallowed_nfcUid_notAborted", false,
                 Process.NFC_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_callingUidHasVisibleWindow_notAborted", false,
                 UNIMPORTANT_UID, true, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_callingUidProcessStateTop_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_realCallingUidHasVisibleWindow_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, true, PROCESS_STATE_TOP + 1,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_realCallingUidProcessStateTop_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP,
-                false, false, false, false);
+                false, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_hasForegroundActivities_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                true, false, false, false);
+                true, false, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_callerIsRecents_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, true, false, false);
+                false, true, false, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_callerIsWhitelisted_notAborted", false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, true, false);
+                false, false, true, false, false);
         runAndVerifyBackgroundActivityStartsSubtest(
                 "disallowed_callerIsInstrumentingWithBackgroundActivityStartPrivileges_notAborted",
                 false,
                 UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
                 UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
-                false, false, false, true);
+                false, false, false, true, false);
+        runAndVerifyBackgroundActivityStartsSubtest(
+                "disallowed_callingPackageIsDeviceOwner_notAborted", false,
+                UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
+                UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
+                false, false, false, false, true);
     }
 
     private void runAndVerifyBackgroundActivityStartsSubtest(String name, boolean shouldHaveAborted,
@@ -648,7 +654,8 @@
             int realCallingUid, boolean realCallingUidHasVisibleWindow, int realCallingUidProcState,
             boolean hasForegroundActivities, boolean callerIsRecents,
             boolean callerIsTempWhitelisted,
-            boolean callerIsInstrumentingWithBackgroundActivityStartPrivileges) {
+            boolean callerIsInstrumentingWithBackgroundActivityStartPrivileges,
+            boolean isCallingPackageDeviceOwner) {
         // window visibility
         doReturn(callingUidHasVisibleWindow).when(mService.mWindowManager.mRoot)
                 .isAnyNonToastWindowVisibleForUid(callingUid);
@@ -672,8 +679,11 @@
         // caller is temp whitelisted
         callerApp.setAllowBackgroundActivityStarts(callerIsTempWhitelisted);
         // caller is instrumenting with background activity starts privileges
-        callerApp.setInstrumentingWithBackgroundActivityStartPrivileges(
+        callerApp.setInstrumenting(callerIsInstrumentingWithBackgroundActivityStartPrivileges,
                 callerIsInstrumentingWithBackgroundActivityStartPrivileges);
+        // caller is device owner
+        DevicePolicyManager dpmMock = mService.getDevicePolicyManager();
+        doReturn(isCallingPackageDeviceOwner).when(dpmMock).isDeviceOwnerApp(any());
 
         final ActivityOptions options = spy(ActivityOptions.makeBasic());
         ActivityStarter starter = prepareStarter(FLAG_ACTIVITY_NEW_TASK)
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index 3b399ff..e27dd94 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -42,6 +42,7 @@
 import android.app.ActivityManagerInternal;
 import android.app.ActivityOptions;
 import android.app.IApplicationThread;
+import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -424,6 +425,7 @@
             spyOn(getLifecycleManager());
             spyOn(getLockTaskController());
             doReturn(mock(IPackageManager.class)).when(this).getPackageManager();
+            doReturn(mock(DevicePolicyManager.class)).when(this).getDevicePolicyManager();
             // allow background activity starts by default
             doReturn(true).when(this).isBackgroundActivityStartsEnabled();
             doNothing().when(this).updateCpuStats();
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
index 19ace3c..3bf884f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
@@ -55,7 +55,7 @@
         mStack = createTaskStackOnDisplay(mDisplayContent);
         mTask = createTaskInStack(mStack, 0 /* userId */);
         mToken = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
-        mToken.mSkipOnParentSet = false;
+        mToken.mSkipOnParentChanged = false;
 
         mTask.addChild(mToken, 0);
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
index e156143..8628575 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
@@ -103,13 +103,13 @@
         assertEquals(secondLayer1, root.getChildAt(5));
         assertEquals(layer2, root.getChildAt(6));
 
-        assertTrue(layer1.mOnParentSetCalled);
-        assertTrue(secondLayer1.mOnParentSetCalled);
-        assertTrue(layer2.mOnParentSetCalled);
-        assertTrue(layerNeg1.mOnParentSetCalled);
-        assertTrue(layerNeg2.mOnParentSetCalled);
-        assertTrue(secondLayerNeg1.mOnParentSetCalled);
-        assertTrue(layer0.mOnParentSetCalled);
+        assertTrue(layer1.mOnParentChangedCalled);
+        assertTrue(secondLayer1.mOnParentChangedCalled);
+        assertTrue(layer2.mOnParentChangedCalled);
+        assertTrue(layerNeg1.mOnParentChangedCalled);
+        assertTrue(layerNeg2.mOnParentChangedCalled);
+        assertTrue(secondLayerNeg1.mOnParentChangedCalled);
+        assertTrue(layer0.mOnParentChangedCalled);
     }
 
     @Test
@@ -747,7 +747,7 @@
         private boolean mFillsParent;
         private Integer mOrientation;
 
-        private boolean mOnParentSetCalled;
+        private boolean mOnParentChangedCalled;
         private boolean mOnDescendantOverrideCalled;
 
         /**
@@ -801,8 +801,8 @@
         }
 
         @Override
-        void onParentSet() {
-            mOnParentSetCalled = true;
+        void onParentChanged() {
+            mOnParentChangedCalled = true;
         }
 
         @Override
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
index 2263cf3..a494889 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
@@ -152,7 +152,7 @@
     public static class TestAppWindowToken extends AppWindowToken {
         boolean mOnTop = false;
         private Transaction mPendingTransactionOverride;
-        boolean mSkipOnParentSet = true;
+        boolean mSkipOnParentChanged = true;
 
         private TestAppWindowToken(DisplayContent dc) {
             super(dc.mWmService, new IApplicationToken.Stub() {
@@ -200,9 +200,11 @@
         }
 
         @Override
-        void onParentSet() {
-            if (!mSkipOnParentSet) {
-                super.onParentSet();
+        void onParentChanged() {
+            if (!mSkipOnParentChanged) {
+                super.onParentChanged();
+            } else {
+                updateConfigurationFromParent(this);
             }
         }
 
@@ -223,6 +225,21 @@
         }
     }
 
+    /**
+     * Used when we don't want to perform surface related operation in
+     * {@link WindowContainer#onParentChanged} or the overridden method, but the configuration
+     * still needs to propagate from parent.
+     *
+     * @see ConfigurationContainer#onParentChanged
+     */
+    static void updateConfigurationFromParent(WindowContainer container) {
+        final WindowContainer parent = container.getParent();
+        if (parent != null) {
+            container.onConfigurationChanged(parent.getConfiguration());
+            container.onMergedOverrideConfigurationChanged();
+        }
+    }
+
     static TestWindowToken createTestWindowToken(int type, DisplayContent dc) {
         return createTestWindowToken(type, dc, false /* persistOnEmpty */);
     }
@@ -341,8 +358,8 @@
         }
 
         @Override
-        void onParentSet() {
-            // Do nothing;
+        void onParentChanged() {
+            updateConfigurationFromParent(this);
         }
     }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index e38118e..3cb2814 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -91,6 +91,12 @@
     WindowState mChildAppWindowBelow;
     HashSet<WindowState> mCommonWindows;
 
+    /**
+     * To restore the original SurfaceControl.Transaction factory if any tests changed
+     * {@link WindowManagerService#mTransactionFactory}.
+     */
+    private TransactionFactory mOriginalTransactionFactory;
+
     @Rule
     public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
             new DexmakerShareClassLoaderRule();
@@ -121,6 +127,7 @@
             final Context context = getInstrumentation().getTargetContext();
 
             mWm = TestSystemServices.getWindowManagerService();
+            mOriginalTransactionFactory = mWm.mTransactionFactory;
             beforeCreateDisplay();
 
             context.getDisplay().getDisplayInfo(mDisplayInfo);
@@ -170,6 +177,7 @@
             // stable state to clean up for consistency.
             waitUntilHandlersIdle();
 
+            mWm.mTransactionFactory = mOriginalTransactionFactory;
             final LinkedList<WindowState> nonCommonWindows = new LinkedList<>();
 
             synchronized (mWm.mGlobalLock) {
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 718f2d3..7cab432 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -613,11 +613,8 @@
         @Override
         public void showSession(IVoiceInteractionService service, Bundle args, int flags) {
             synchronized (this) {
-                if (mImpl == null || mImpl.mService == null
-                        || service.asBinder() != mImpl.mService.asBinder()) {
-                    throw new SecurityException(
-                            "Caller is not the current voice interaction service");
-                }
+                enforceIsCurrentVoiceInteractionService(service);
+
                 final long caller = Binder.clearCallingIdentity();
                 try {
                     mImpl.showSessionLocked(args, flags, null, null);
@@ -896,11 +893,7 @@
         public boolean isEnrolledForKeyphrase(IVoiceInteractionService service, int keyphraseId,
                 String bcp47Locale) {
             synchronized (this) {
-                if (mImpl == null || mImpl.mService == null
-                        || service.asBinder() != mImpl.mService.asBinder()) {
-                    throw new SecurityException(
-                            "Caller is not the current voice interaction service");
-                }
+                enforceIsCurrentVoiceInteractionService(service);
             }
 
             if (bcp47Locale == null) {
@@ -922,11 +915,7 @@
         public ModuleProperties getDspModuleProperties(IVoiceInteractionService service) {
             // Allow the call if this is the current voice interaction service.
             synchronized (this) {
-                if (mImpl == null || mImpl.mService == null
-                        || service == null || service.asBinder() != mImpl.mService.asBinder()) {
-                    throw new SecurityException(
-                            "Caller is not the current voice interaction service");
-                }
+                enforceIsCurrentVoiceInteractionService(service);
 
                 final long caller = Binder.clearCallingIdentity();
                 try {
@@ -943,11 +932,7 @@
                 RecognitionConfig recognitionConfig) {
             // Allow the call if this is the current voice interaction service.
             synchronized (this) {
-                if (mImpl == null || mImpl.mService == null
-                        || service == null || service.asBinder() != mImpl.mService.asBinder()) {
-                    throw new SecurityException(
-                            "Caller is not the current voice interaction service");
-                }
+                enforceIsCurrentVoiceInteractionService(service);
 
                 if (callback == null || recognitionConfig == null || bcp47Locale == null) {
                     throw new IllegalArgumentException("Illegal argument(s) in startRecognition");
@@ -983,11 +968,7 @@
                 IRecognitionStatusCallback callback) {
             // Allow the call if this is the current voice interaction service.
             synchronized (this) {
-                if (mImpl == null || mImpl.mService == null
-                        || service == null || service.asBinder() != mImpl.mService.asBinder()) {
-                    throw new SecurityException(
-                            "Caller is not the current voice interaction service");
-                }
+                enforceIsCurrentVoiceInteractionService(service);
             }
 
             final long caller = Binder.clearCallingIdentity();
@@ -1212,8 +1193,10 @@
         }
 
         @Override
-        public void setTranscription(String transcription) {
+        public void setTranscription(IVoiceInteractionService service, String transcription) {
             synchronized (this) {
+                enforceIsCurrentVoiceInteractionService(service);
+
                 final int size = mVoiceInteractionSessionListeners.beginBroadcast();
                 for (int i = 0; i < size; ++i) {
                     final IVoiceInteractionSessionListener listener =
@@ -1229,8 +1212,10 @@
         }
 
         @Override
-        public void clearTranscription(boolean immediate) {
+        public void clearTranscription(IVoiceInteractionService service, boolean immediate) {
             synchronized (this) {
+                enforceIsCurrentVoiceInteractionService(service);
+
                 final int size = mVoiceInteractionSessionListeners.beginBroadcast();
                 for (int i = 0; i < size; ++i) {
                     final IVoiceInteractionSessionListener listener =
@@ -1246,8 +1231,10 @@
         }
 
         @Override
-        public void setVoiceState(int state) {
+        public void setVoiceState(IVoiceInteractionService service, int state) {
             synchronized (this) {
+                enforceIsCurrentVoiceInteractionService(service);
+
                 final int size = mVoiceInteractionSessionListeners.beginBroadcast();
                 for (int i = 0; i < size; ++i) {
                     final IVoiceInteractionSessionListener listener =
@@ -1269,6 +1256,14 @@
             }
         }
 
+        private void enforceIsCurrentVoiceInteractionService(IVoiceInteractionService service) {
+            if (mImpl == null || mImpl.mService == null
+                    || service.asBinder() != mImpl.mService.asBinder()) {
+                throw new
+                    SecurityException("Caller is not the current voice interaction service");
+            }
+        }
+
         private void setImplLocked(VoiceInteractionManagerServiceImpl impl) {
             mImpl = impl;
             mAtmInternal.notifyActiveVoiceInteractionServiceChanged(
diff --git a/startop/iorap/TEST_MAPPING b/startop/iorap/DISABLED_TEST_MAPPING
similarity index 100%
rename from startop/iorap/TEST_MAPPING
rename to startop/iorap/DISABLED_TEST_MAPPING
diff --git a/startop/view_compiler/TEST_MAPPING b/startop/view_compiler/TEST_MAPPING
index 7006075..5f7d3f9 100644
--- a/startop/view_compiler/TEST_MAPPING
+++ b/startop/view_compiler/TEST_MAPPING
@@ -4,6 +4,14 @@
       "name": "dex-builder-test"
     },
     {
+      "name": "CtsViewTestCases",
+      "options": [
+        {
+          "include-filter": "android.view.cts.PrecompiledLayoutTest"
+        }
+      ]
+    },
+    {
       "name": "view-compiler-tests",
       "host": true
     }
diff --git a/startop/view_compiler/dex_builder.cc b/startop/view_compiler/dex_builder.cc
index a78f7d5..4c1a0dc7 100644
--- a/startop/view_compiler/dex_builder.cc
+++ b/startop/view_compiler/dex_builder.cc
@@ -21,8 +21,6 @@
 #include <fstream>
 #include <memory>
 
-#define DCHECK_NOT_NULL(p) DCHECK((p) != nullptr)
-
 namespace startop {
 namespace dex {
 
@@ -32,6 +30,8 @@
 using ::dex::kAccPublic;
 using Op = Instruction::Op;
 
+using Opcode = ::art::Instruction::Code;
+
 const TypeDescriptor TypeDescriptor::Int() { return TypeDescriptor{"I"}; };
 const TypeDescriptor TypeDescriptor::Void() { return TypeDescriptor{"V"}; };
 
@@ -42,6 +42,23 @@
 // Strings lengths can be 32 bits long, but encoded as LEB128 this can take up to five bytes.
 constexpr size_t kMaxEncodedStringLength{5};
 
+// Converts invoke-* to invoke-*/range
+constexpr Opcode InvokeToInvokeRange(Opcode opcode) {
+  switch (opcode) {
+    case ::art::Instruction::INVOKE_VIRTUAL:
+      return ::art::Instruction::INVOKE_VIRTUAL_RANGE;
+    case ::art::Instruction::INVOKE_DIRECT:
+      return ::art::Instruction::INVOKE_DIRECT_RANGE;
+    case ::art::Instruction::INVOKE_STATIC:
+      return ::art::Instruction::INVOKE_STATIC_RANGE;
+    case ::art::Instruction::INVOKE_INTERFACE:
+      return ::art::Instruction::INVOKE_INTERFACE_RANGE;
+    default:
+      LOG(FATAL) << opcode << " is not a recognized invoke opcode.";
+      UNREACHABLE();
+  }
+}
+
 }  // namespace
 
 std::ostream& operator<<(std::ostream& out, const Instruction::Op& opcode) {
@@ -55,6 +72,9 @@
     case Instruction::Op::kMove:
       out << "kMove";
       return out;
+    case Instruction::Op::kMoveObject:
+      out << "kMoveObject";
+      return out;
     case Instruction::Op::kInvokeVirtual:
       out << "kInvokeVirtual";
       return out;
@@ -233,6 +253,11 @@
   return shorty;
 }
 
+const TypeDescriptor& Prototype::ArgType(size_t index) const {
+  CHECK_LT(index, param_types_.size());
+  return param_types_[index];
+}
+
 ClassBuilder::ClassBuilder(DexBuilder* parent, const std::string& name, ir::Class* class_def)
     : parent_(parent), type_descriptor_{TypeDescriptor::FromClassname(name)}, class_(class_def) {}
 
@@ -257,10 +282,10 @@
   method->access_flags = kAccPublic | ::dex::kAccStatic;
 
   auto* code = dex_->Alloc<ir::Code>();
-  DCHECK_NOT_NULL(decl_->prototype);
+  CHECK(decl_->prototype != nullptr);
   size_t const num_args =
       decl_->prototype->param_types != nullptr ? decl_->prototype->param_types->types.size() : 0;
-  code->registers = num_registers_ + num_args;
+  code->registers = num_registers_ + num_args + kMaxScratchRegisters;
   code->ins_count = num_args;
   EncodeInstructions();
   code->instructions = slicer::ArrayView<const ::dex::u2>(buffer_.data(), buffer_.size());
@@ -292,7 +317,7 @@
 }
 
 void MethodBuilder::BuildConst4(Value target, int value) {
-  DCHECK_LT(value, 16);
+  CHECK_LT(value, 16);
   AddInstruction(Instruction::OpWithArgs(Op::kMove, target, Value::Immediate(value)));
 }
 
@@ -315,6 +340,7 @@
     case Instruction::Op::kReturnObject:
       return EncodeReturn(instruction, ::art::Instruction::RETURN_OBJECT);
     case Instruction::Op::kMove:
+    case Instruction::Op::kMoveObject:
       return EncodeMove(instruction);
     case Instruction::Op::kInvokeVirtual:
       return EncodeInvoke(instruction, art::Instruction::INVOKE_VIRTUAL);
@@ -338,33 +364,43 @@
 }
 
 void MethodBuilder::EncodeReturn(const Instruction& instruction, ::art::Instruction::Code opcode) {
-  DCHECK(!instruction.dest().has_value());
+  CHECK(!instruction.dest().has_value());
   if (instruction.args().size() == 0) {
     Encode10x(art::Instruction::RETURN_VOID);
   } else {
-    DCHECK_EQ(1, instruction.args().size());
+    CHECK_EQ(1, instruction.args().size());
     size_t source = RegisterValue(instruction.args()[0]);
     Encode11x(opcode, source);
   }
 }
 
 void MethodBuilder::EncodeMove(const Instruction& instruction) {
-  DCHECK_EQ(Instruction::Op::kMove, instruction.opcode());
-  DCHECK(instruction.dest().has_value());
-  DCHECK(instruction.dest()->is_register() || instruction.dest()->is_parameter());
-  DCHECK_EQ(1, instruction.args().size());
+  CHECK(Instruction::Op::kMove == instruction.opcode() ||
+        Instruction::Op::kMoveObject == instruction.opcode());
+  CHECK(instruction.dest().has_value());
+  CHECK(instruction.dest()->is_variable());
+  CHECK_EQ(1, instruction.args().size());
 
   const Value& source = instruction.args()[0];
 
   if (source.is_immediate()) {
     // TODO: support more registers
-    DCHECK_LT(RegisterValue(*instruction.dest()), 16);
+    CHECK_LT(RegisterValue(*instruction.dest()), 16);
     Encode11n(art::Instruction::CONST_4, RegisterValue(*instruction.dest()), source.value());
   } else if (source.is_string()) {
     constexpr size_t kMaxRegisters = 256;
-    DCHECK_LT(RegisterValue(*instruction.dest()), kMaxRegisters);
-    DCHECK_LT(source.value(), 65536);  // make sure we don't need a jumbo string
+    CHECK_LT(RegisterValue(*instruction.dest()), kMaxRegisters);
+    CHECK_LT(source.value(), 65536);  // make sure we don't need a jumbo string
     Encode21c(::art::Instruction::CONST_STRING, RegisterValue(*instruction.dest()), source.value());
+  } else if (source.is_variable()) {
+    // For the moment, we only use this when we need to reshuffle registers for
+    // an invoke instruction, meaning we are too big for the 4-bit version.
+    // We'll err on the side of caution and always generate the 16-bit form of
+    // the instruction.
+    Opcode opcode = instruction.opcode() == Instruction::Op::kMove
+                        ? ::art::Instruction::MOVE_16
+                        : ::art::Instruction::MOVE_OBJECT_16;
+    Encode32x(opcode, RegisterValue(*instruction.dest()), RegisterValue(source));
   } else {
     UNIMPLEMENTED(FATAL);
   }
@@ -373,22 +409,61 @@
 void MethodBuilder::EncodeInvoke(const Instruction& instruction, ::art::Instruction::Code opcode) {
   constexpr size_t kMaxArgs = 5;
 
+  // Currently, we only support up to 5 arguments.
   CHECK_LE(instruction.args().size(), kMaxArgs);
 
   uint8_t arguments[kMaxArgs]{};
+  bool has_long_args = false;
   for (size_t i = 0; i < instruction.args().size(); ++i) {
     CHECK(instruction.args()[i].is_variable());
     arguments[i] = RegisterValue(instruction.args()[i]);
+    if (!IsShortRegister(arguments[i])) {
+      has_long_args = true;
+    }
   }
 
-  Encode35c(opcode,
-            instruction.args().size(),
-            instruction.method_id(),
-            arguments[0],
-            arguments[1],
-            arguments[2],
-            arguments[3],
-            arguments[4]);
+  if (has_long_args) {
+    // Some of the registers don't fit in the four bit short form of the invoke
+    // instruction, so we need to do an invoke/range. To do this, we need to
+    // first move all the arguments into contiguous temporary registers.
+    std::array<Value, kMaxArgs> scratch{GetScratchRegisters<kMaxArgs>()};
+
+    const auto& prototype = dex_->GetPrototypeByMethodId(instruction.method_id());
+    CHECK(prototype.has_value());
+
+    for (size_t i = 0; i < instruction.args().size(); ++i) {
+      Instruction::Op move_op;
+      if (opcode == ::art::Instruction::INVOKE_VIRTUAL ||
+          opcode == ::art::Instruction::INVOKE_DIRECT) {
+        // In this case, there is an implicit `this` argument, which is always an object.
+        if (i == 0) {
+          move_op = Instruction::Op::kMoveObject;
+        } else {
+          move_op = prototype->ArgType(i - 1).is_object() ? Instruction::Op::kMoveObject
+                                                          : Instruction::Op::kMove;
+        }
+      } else {
+        move_op = prototype->ArgType(i).is_object() ? Instruction::Op::kMoveObject
+                                                    : Instruction::Op::kMove;
+      }
+
+      EncodeMove(Instruction::OpWithArgs(move_op, scratch[i], instruction.args()[i]));
+    }
+
+    Encode3rc(InvokeToInvokeRange(opcode),
+              instruction.args().size(),
+              instruction.method_id(),
+              RegisterValue(scratch[0]));
+  } else {
+    Encode35c(opcode,
+              instruction.args().size(),
+              instruction.method_id(),
+              arguments[0],
+              arguments[1],
+              arguments[2],
+              arguments[3],
+              arguments[4]);
+  }
 
   // If there is a return value, add a move-result instruction
   if (instruction.dest().has_value()) {
@@ -416,26 +491,26 @@
 }
 
 void MethodBuilder::EncodeNew(const Instruction& instruction) {
-  DCHECK_EQ(Instruction::Op::kNew, instruction.opcode());
-  DCHECK(instruction.dest().has_value());
-  DCHECK(instruction.dest()->is_variable());
-  DCHECK_EQ(1, instruction.args().size());
+  CHECK_EQ(Instruction::Op::kNew, instruction.opcode());
+  CHECK(instruction.dest().has_value());
+  CHECK(instruction.dest()->is_variable());
+  CHECK_EQ(1, instruction.args().size());
 
   const Value& type = instruction.args()[0];
-  DCHECK_LT(RegisterValue(*instruction.dest()), 256);
-  DCHECK(type.is_type());
+  CHECK_LT(RegisterValue(*instruction.dest()), 256);
+  CHECK(type.is_type());
   Encode21c(::art::Instruction::NEW_INSTANCE, RegisterValue(*instruction.dest()), type.value());
 }
 
 void MethodBuilder::EncodeCast(const Instruction& instruction) {
-  DCHECK_EQ(Instruction::Op::kCheckCast, instruction.opcode());
-  DCHECK(instruction.dest().has_value());
-  DCHECK(instruction.dest()->is_variable());
-  DCHECK_EQ(1, instruction.args().size());
+  CHECK_EQ(Instruction::Op::kCheckCast, instruction.opcode());
+  CHECK(instruction.dest().has_value());
+  CHECK(instruction.dest()->is_variable());
+  CHECK_EQ(1, instruction.args().size());
 
   const Value& type = instruction.args()[0];
-  DCHECK_LT(RegisterValue(*instruction.dest()), 256);
-  DCHECK(type.is_type());
+  CHECK_LT(RegisterValue(*instruction.dest()), 256);
+  CHECK(type.is_type());
   Encode21c(::art::Instruction::CHECK_CAST, RegisterValue(*instruction.dest()), type.value());
 }
 
@@ -443,9 +518,9 @@
   if (value.is_register()) {
     return value.value();
   } else if (value.is_parameter()) {
-    return value.value() + num_registers_;
+    return value.value() + num_registers_ + kMaxScratchRegisters;
   }
-  DCHECK(false && "Must be either a parameter or a register");
+  CHECK(false && "Must be either a parameter or a register");
   return 0;
 }
 
@@ -498,7 +573,7 @@
     // update the index -> ir node map (see tools/dexter/slicer/dex_ir_builder.cc)
     auto new_index = dex_file_->methods_indexes.AllocateIndex();
     auto& ir_node = dex_file_->methods_map[new_index];
-    SLICER_CHECK(ir_node == nullptr);
+    CHECK(ir_node == nullptr);
     ir_node = decl;
     decl->orig_index = decl->index = new_index;
 
@@ -508,6 +583,15 @@
   return entry;
 }
 
+std::optional<const Prototype> DexBuilder::GetPrototypeByMethodId(size_t method_id) const {
+  for (const auto& entry : method_id_map_) {
+    if (entry.second.id == method_id) {
+      return entry.first.prototype;
+    }
+  }
+  return {};
+}
+
 ir::Proto* DexBuilder::GetOrEncodeProto(Prototype prototype) {
   ir::Proto*& ir_proto = proto_map_[prototype];
   if (ir_proto == nullptr) {
diff --git a/startop/view_compiler/dex_builder.h b/startop/view_compiler/dex_builder.h
index 757d863..541d800 100644
--- a/startop/view_compiler/dex_builder.h
+++ b/startop/view_compiler/dex_builder.h
@@ -16,6 +16,7 @@
 #ifndef DEX_BUILDER_H_
 #define DEX_BUILDER_H_
 
+#include <array>
 #include <forward_list>
 #include <map>
 #include <optional>
@@ -70,6 +71,8 @@
   // Return the shorty descriptor, such as I or L
   std::string short_descriptor() const { return descriptor().substr(0, 1); }
 
+  bool is_object() const { return short_descriptor() == "L"; }
+
   bool operator<(const TypeDescriptor& rhs) const { return descriptor_ < rhs.descriptor_; }
 
  private:
@@ -92,6 +95,8 @@
   // Get the shorty descriptor, such as VII for (Int, Int) -> Void
   std::string Shorty() const;
 
+  const TypeDescriptor& ArgType(size_t index) const;
+
   bool operator<(const Prototype& rhs) const {
     return std::make_tuple(return_type_, param_types_) <
            std::make_tuple(rhs.return_type_, rhs.param_types_);
@@ -124,11 +129,13 @@
 
   size_t value() const { return value_; }
 
- private:
-  enum class Kind { kLocalRegister, kParameter, kImmediate, kString, kLabel, kType };
+  constexpr Value() : value_{0}, kind_{Kind::kInvalid} {}
 
-  const size_t value_;
-  const Kind kind_;
+ private:
+  enum class Kind { kInvalid, kLocalRegister, kParameter, kImmediate, kString, kLabel, kType };
+
+  size_t value_;
+  Kind kind_;
 
   constexpr Value(size_t value, Kind kind) : value_{value}, kind_{kind} {}
 };
@@ -151,6 +158,7 @@
     kInvokeStatic,
     kInvokeVirtual,
     kMove,
+    kMoveObject,
     kNew,
     kReturn,
     kReturnObject,
@@ -172,7 +180,7 @@
 
   // A cast instruction. Basically, `(type)val`
   static inline Instruction Cast(Value val, Value type) {
-    DCHECK(type.is_type());
+    CHECK(type.is_type());
     return OpWithArgs(Op::kCheckCast, val, type);
   }
 
@@ -343,21 +351,48 @@
     buffer_.push_back(b);
   }
 
+  inline void Encode32x(art::Instruction::Code opcode, uint16_t a, uint16_t b) {
+    buffer_.push_back(opcode);
+    buffer_.push_back(a);
+    buffer_.push_back(b);
+  }
+
   inline void Encode35c(art::Instruction::Code opcode, size_t a, uint16_t b, uint8_t c, uint8_t d,
                         uint8_t e, uint8_t f, uint8_t g) {
     // a|g|op|bbbb|f|e|d|c
 
     CHECK_LE(a, 5);
-    CHECK_LT(c, 16);
-    CHECK_LT(d, 16);
-    CHECK_LT(e, 16);
-    CHECK_LT(f, 16);
-    CHECK_LT(g, 16);
+    CHECK(IsShortRegister(c));
+    CHECK(IsShortRegister(d));
+    CHECK(IsShortRegister(e));
+    CHECK(IsShortRegister(f));
+    CHECK(IsShortRegister(g));
     buffer_.push_back((a << 12) | (g << 8) | opcode);
     buffer_.push_back(b);
     buffer_.push_back((f << 12) | (e << 8) | (d << 4) | c);
   }
 
+  inline void Encode3rc(art::Instruction::Code opcode, size_t a, uint16_t b, uint16_t c) {
+    CHECK_LE(a, 255);
+    buffer_.push_back((a << 8) | opcode);
+    buffer_.push_back(b);
+    buffer_.push_back(c);
+  }
+
+  static constexpr bool IsShortRegister(size_t register_value) { return register_value < 16; }
+
+  // Returns an array of num_regs scratch registers. These are guaranteed to be
+  // contiguous, so they are suitable for the invoke-*/range instructions.
+  template <int num_regs>
+  std::array<Value, num_regs> GetScratchRegisters() const {
+    static_assert(num_regs <= kMaxScratchRegisters);
+    std::array<Value, num_regs> regs;
+    for (size_t i = 0; i < num_regs; ++i) {
+      regs[i] = std::move(Value::Local(num_registers_ + i));
+    }
+    return regs;
+  }
+
   // Converts a register or parameter to its DEX register number.
   size_t RegisterValue(const Value& value) const;
 
@@ -379,6 +414,10 @@
   // A buffer to hold instructions that have been encoded.
   std::vector<::dex::u2> buffer_;
 
+  // We create some scratch registers for when we have to shuffle registers
+  // around to make legal DEX code.
+  static constexpr size_t kMaxScratchRegisters = 5;
+
   // How many registers we've allocated
   size_t num_registers_{0};
 
@@ -447,6 +486,8 @@
   const MethodDeclData& GetOrDeclareMethod(TypeDescriptor type, const std::string& name,
                                            Prototype prototype);
 
+  std::optional<const Prototype> GetPrototypeByMethodId(size_t method_id) const;
+
  private:
   // Looks up the ir::Proto* corresponding to this given prototype, or creates one if it does not
   // exist.
diff --git a/startop/view_compiler/dex_builder_test.cc b/startop/view_compiler/dex_builder_test.cc
index 61c86b4..90c256f 100644
--- a/startop/view_compiler/dex_builder_test.cc
+++ b/startop/view_compiler/dex_builder_test.cc
@@ -140,3 +140,41 @@
 
   EXPECT_TRUE(EncodeAndVerify(&dex_file));
 }
+
+// Write out and verify a DEX file that corresponds to:
+//
+// package dextest;
+// public class DexTest {
+//     public static int foo(String s) { return s.length(); }
+// }
+TEST(DexBuilderTest, VerifyDexCallManyRegisters) {
+  DexBuilder dex_file;
+
+  auto cbuilder{dex_file.MakeClass("dextest.DexTest")};
+
+  MethodBuilder method{cbuilder.CreateMethod(
+      "foo", Prototype{TypeDescriptor::Int()})};
+
+  Value result = method.MakeRegister();
+
+  // Make a bunch of registers
+  for (size_t i = 0; i < 25; ++i) {
+    method.MakeRegister();
+  }
+
+  // Now load a string literal into a register
+  Value string_val = method.MakeRegister();
+  method.BuildConstString(string_val, "foo");
+
+  MethodDeclData string_length =
+      dex_file.GetOrDeclareMethod(TypeDescriptor::FromClassname("java.lang.String"),
+                                  "length",
+                                  Prototype{TypeDescriptor::Int()});
+
+  method.AddInstruction(Instruction::InvokeVirtual(string_length.id, result, string_val));
+  method.BuildReturn(result);
+
+  method.Encode();
+
+  EXPECT_TRUE(EncodeAndVerify(&dex_file));
+}
diff --git a/startop/view_compiler/dex_builder_test/Android.bp b/startop/view_compiler/dex_builder_test/Android.bp
index d4f38ed..ac60e96 100644
--- a/startop/view_compiler/dex_builder_test/Android.bp
+++ b/startop/view_compiler/dex_builder_test/Android.bp
@@ -15,7 +15,7 @@
 //
 
 genrule {
-    name: "generate_compiled_layout",
+    name: "generate_compiled_layout1",
     tools: [":viewcompiler"],
     cmd: "$(location :viewcompiler) $(in) --dex --out $(out) --package android.startop.test",
     srcs: ["res/layout/layout1.xml"],
@@ -24,6 +24,16 @@
     ],
 }
 
+genrule {
+    name: "generate_compiled_layout2",
+    tools: [":viewcompiler"],
+    cmd: "$(location :viewcompiler) $(in) --dex --out $(out) --package android.startop.test",
+    srcs: ["res/layout/layout2.xml"],
+    out: [
+        "layout2.dex",
+    ],
+}
+
 android_test {
     name: "dex-builder-test",
     srcs: [
@@ -31,7 +41,7 @@
         "src/android/startop/test/LayoutCompilerTest.java",
     ],
     sdk_version: "current",
-    data: [":generate_dex_testcases", ":generate_compiled_layout"],
+    data: [":generate_dex_testcases", ":generate_compiled_layout1", ":generate_compiled_layout2"],
     static_libs: [
         "android-support-test",
         "guava",
diff --git a/startop/view_compiler/dex_builder_test/AndroidTest.xml b/startop/view_compiler/dex_builder_test/AndroidTest.xml
index 68d8fdc..92e2a71 100644
--- a/startop/view_compiler/dex_builder_test/AndroidTest.xml
+++ b/startop/view_compiler/dex_builder_test/AndroidTest.xml
@@ -26,6 +26,7 @@
         <option name="push" value="trivial.dex->/data/local/tmp/dex-builder-test/trivial.dex" />
         <option name="push" value="simple.dex->/data/local/tmp/dex-builder-test/simple.dex" />
         <option name="push" value="layout1.dex->/data/local/tmp/dex-builder-test/layout1.dex" />
+        <option name="push" value="layout2.dex->/data/local/tmp/dex-builder-test/layout2.dex" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/startop/view_compiler/dex_builder_test/res/layout/layout2.xml b/startop/view_compiler/dex_builder_test/res/layout/layout2.xml
new file mode 100644
index 0000000..b092e1c
--- /dev/null
+++ b/startop/view_compiler/dex_builder_test/res/layout/layout2.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <TableRow
+        android:layout_width="match_parent"
+        android:layout_height="match_parent" >
+
+        <Button
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Button" />
+
+        <TableRow
+            android:layout_width="match_parent"
+            android:layout_height="match_parent" >
+
+            <Button
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:text="Button" />
+            <TableRow
+                android:layout_width="match_parent"
+                android:layout_height="match_parent" >
+
+                <Button
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="Button" />
+
+                <TableRow
+                    android:layout_width="match_parent"
+                    android:layout_height="match_parent" >
+
+                    <Button
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:text="Button" />
+                </TableRow>
+
+            </TableRow>
+        </TableRow>
+    </TableRow>
+</LinearLayout>
diff --git a/startop/view_compiler/dex_builder_test/src/android/startop/test/LayoutCompilerTest.java b/startop/view_compiler/dex_builder_test/src/android/startop/test/LayoutCompilerTest.java
index ce3ce83..a3b1b6c 100644
--- a/startop/view_compiler/dex_builder_test/src/android/startop/test/LayoutCompilerTest.java
+++ b/startop/view_compiler/dex_builder_test/src/android/startop/test/LayoutCompilerTest.java
@@ -36,11 +36,20 @@
     }
 
     @Test
-    public void loadAndInflaterLayout1() throws Exception {
+    public void loadAndInflateLayout1() throws Exception {
         ClassLoader dex_file = loadDexFile("layout1.dex");
         Class compiled_view = dex_file.loadClass("android.startop.test.CompiledView");
         Method layout1 = compiled_view.getMethod("layout1", Context.class, int.class);
         Context context = InstrumentationRegistry.getTargetContext();
         layout1.invoke(null, context, R.layout.layout1);
     }
+
+    @Test
+    public void loadAndInflateLayout2() throws Exception {
+        ClassLoader dex_file = loadDexFile("layout2.dex");
+        Class compiled_view = dex_file.loadClass("android.startop.test.CompiledView");
+        Method layout1 = compiled_view.getMethod("layout2", Context.class, int.class);
+        Context context = InstrumentationRegistry.getTargetContext();
+        layout1.invoke(null, context, R.layout.layout1);
+    }
 }
diff --git a/telecomm/java/android/telecom/DefaultDialerManager.java b/telecomm/java/android/telecom/DefaultDialerManager.java
index b2fa5d4..57ae5d3 100644
--- a/telecomm/java/android/telecom/DefaultDialerManager.java
+++ b/telecomm/java/android/telecom/DefaultDialerManager.java
@@ -22,17 +22,22 @@
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
 import android.net.Uri;
 import android.os.AsyncTask;
 import android.os.Binder;
 import android.os.Process;
 import android.os.UserHandle;
 import android.text.TextUtils;
+import android.util.Slog;
 
 import com.android.internal.util.CollectionUtils;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 /**
  * Class for managing the default dialer application that will receive incoming calls, and be
@@ -71,19 +76,15 @@
             int user) {
         long identity = Binder.clearCallingIdentity();
         try {
+            RoleManagerCallback.Future cb = new RoleManagerCallback.Future();
             context.getSystemService(RoleManager.class).addRoleHolderAsUser(
                     RoleManager.ROLE_DIALER, packageName, UserHandle.of(user),
-                    AsyncTask.THREAD_POOL_EXECUTOR, new RoleManagerCallback() {
-                        @Override
-                        public void onSuccess() {}
-
-                        @Override
-                        public void onFailure() {
-                            Log.w(TAG, "Failed to set default dialer to %s for user %s",
-                                    packageName, user);
-                        }
-                    });
+                    AsyncTask.THREAD_POOL_EXECUTOR, cb);
+            cb.get(5, TimeUnit.SECONDS);
             return true;
+        } catch (InterruptedException | ExecutionException | TimeoutException e) {
+            Slog.e(TAG, "Failed to set default dialer to " + packageName + " for user " + user, e);
+            return false;
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
@@ -162,7 +163,9 @@
 
         final Intent dialIntentWithTelScheme = new Intent(Intent.ACTION_DIAL);
         dialIntentWithTelScheme.setData(Uri.fromParts(PhoneAccount.SCHEME_TEL, "", null));
-        return filterByIntent(context, packageNames, dialIntentWithTelScheme, userId);
+        packageNames = filterByIntent(context, packageNames, dialIntentWithTelScheme, userId);
+        packageNames = requireInCallService(packageNames, userId, context);
+        return packageNames;
     }
 
     public static List<String> getInstalledDialerApplications(Context context) {
@@ -220,6 +223,35 @@
         return result;
     }
 
+    private static List<String> requireInCallService(List<String> packageNames, int userId,
+            Context context) {
+        if (packageNames == null || packageNames.isEmpty()) {
+            return new ArrayList<>();
+        }
+
+        final Intent intent = new Intent(InCallService.SERVICE_INTERFACE);
+        final List<ResolveInfo> resolveInfoList = context.getPackageManager()
+                .queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, userId);
+        final List<String> result = new ArrayList<>();
+        final int length = resolveInfoList.size();
+        for (int i = 0; i < length; i++) {
+            final ServiceInfo info = resolveInfoList.get(i).serviceInfo;
+            if (info == null || info.metaData == null) {
+                continue;
+            }
+            if (!info.metaData.getBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_UI)) {
+                continue;
+            }
+            if (info.metaData.getBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_CAR_MODE_UI)) {
+                continue;
+            }
+            if (packageNames.contains(info.packageName) && !result.contains(info.packageName)) {
+                result.add(info.packageName);
+            }
+        }
+
+        return result;
+    }
 
     private static TelecomManager getTelecomManager(Context context) {
         return (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 12a5344..0e17a33 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -1404,8 +1404,14 @@
      *
      * @return {@code true} if there is a call which will be rejected or terminated, {@code false}
      * otherwise.
+     * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
+     * instead.  Apps performing call screening should use the {@link CallScreeningService} API
+     * instead.
      */
+
+
     @RequiresPermission(Manifest.permission.ANSWER_PHONE_CALLS)
+    @Deprecated
     public boolean endCall() {
         try {
             if (isServiceConnected()) {
@@ -1426,11 +1432,15 @@
      *
      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
      * {@link android.Manifest.permission#ANSWER_PHONE_CALLS}
+     *
+     * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
+     * instead.
      */
     //TODO: L-release - need to convert all invocation of ITelecmmService#answerRingingCall to use
     // this method (clockwork & gearhead).
     @RequiresPermission(anyOf =
             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
+    @Deprecated
     public void acceptRingingCall() {
         try {
             if (isServiceConnected()) {
@@ -1449,9 +1459,12 @@
      * {@link android.Manifest.permission#ANSWER_PHONE_CALLS}
      *
      * @param videoState The desired video state to answer the call with.
+     * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
+     * instead.
      */
     @RequiresPermission(anyOf =
             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
+    @Deprecated
     public void acceptRingingCall(int videoState) {
         try {
             if (isServiceConnected()) {
diff --git a/telephony/java/android/telephony/CallAttributes.java b/telephony/java/android/telephony/CallAttributes.java
index 2d29875..a4cce9c 100644
--- a/telephony/java/android/telephony/CallAttributes.java
+++ b/telephony/java/android/telephony/CallAttributes.java
@@ -50,10 +50,9 @@
     }
 
     private CallAttributes(Parcel in) {
-        mPreciseCallState = (PreciseCallState)
-                in.readValue(PreciseCallState.class.getClassLoader());
-        mNetworkType = in.readInt();
-        mCallQuality = (CallQuality) in.readValue(CallQuality.class.getClassLoader());
+        this.mPreciseCallState = in.readParcelable(PreciseCallState.class.getClassLoader());
+        this.mNetworkType = in.readInt();
+        this.mCallQuality = in.readParcelable(CallQuality.class.getClassLoader());
     }
 
     // getters
@@ -134,9 +133,9 @@
      * {@link Parcelable#writeToParcel}
      */
     public void writeToParcel(Parcel dest, @Parcelable.WriteFlags int flags) {
-        mPreciseCallState.writeToParcel(dest, flags);
+        dest.writeParcelable(mPreciseCallState, flags);
         dest.writeInt(mNetworkType);
-        mCallQuality.writeToParcel(dest, flags);
+        dest.writeParcelable(mCallQuality, flags);
     }
 
     public static final Parcelable.Creator<CallAttributes> CREATOR = new Parcelable.Creator() {
diff --git a/telephony/java/android/telephony/CellSignalStrengthNr.java b/telephony/java/android/telephony/CellSignalStrengthNr.java
index 061cd4b..6f84ec5 100644
--- a/telephony/java/android/telephony/CellSignalStrengthNr.java
+++ b/telephony/java/android/telephony/CellSignalStrengthNr.java
@@ -77,6 +77,14 @@
     }
 
     /**
+     * @hide
+     * @param ss signal strength from modem.
+     */
+    public CellSignalStrengthNr(android.hardware.radio.V1_4.NrSignalStrength ss) {
+        this(ss.csiRsrp, ss.csiRsrq, ss.csiSinr, ss.ssRsrp, ss.ssRsrq, ss.ssSinr);
+    }
+
+    /**
      * Reference: 3GPP TS 38.215.
      * Range: -140 dBm to -44 dBm.
      * @return SS reference signal received power, {@link CellInfo#UNAVAILABLE} means unreported
diff --git a/telephony/java/android/telephony/SignalStrength.java b/telephony/java/android/telephony/SignalStrength.java
index 91375bc..d2ae106 100644
--- a/telephony/java/android/telephony/SignalStrength.java
+++ b/telephony/java/android/telephony/SignalStrength.java
@@ -85,6 +85,7 @@
     CellSignalStrengthWcdma mWcdma;
     CellSignalStrengthTdscdma mTdscdma;
     CellSignalStrengthLte mLte;
+    CellSignalStrengthNr mNr;
 
     /**
      * Create a new SignalStrength from a intent notifier Bundle
@@ -116,7 +117,7 @@
     public SignalStrength() {
         this(new CellSignalStrengthCdma(), new CellSignalStrengthGsm(),
                 new CellSignalStrengthWcdma(), new CellSignalStrengthTdscdma(),
-                new CellSignalStrengthLte());
+                new CellSignalStrengthLte(), new CellSignalStrengthNr());
     }
 
     /**
@@ -129,12 +130,14 @@
             @NonNull CellSignalStrengthGsm gsm,
             @NonNull CellSignalStrengthWcdma wcdma,
             @NonNull CellSignalStrengthTdscdma tdscdma,
-            @NonNull CellSignalStrengthLte lte) {
+            @NonNull CellSignalStrengthLte lte,
+            @NonNull CellSignalStrengthNr nr) {
         mCdma = cdma;
         mGsm = gsm;
         mWcdma = wcdma;
         mTdscdma = tdscdma;
         mLte = lte;
+        mNr = nr;
     }
 
     /**
@@ -147,7 +150,8 @@
                 new CellSignalStrengthGsm(signalStrength.gw),
                 new CellSignalStrengthWcdma(),
                 new CellSignalStrengthTdscdma(signalStrength.tdScdma),
-                new CellSignalStrengthLte(signalStrength.lte));
+                new CellSignalStrengthLte(signalStrength.lte),
+                new CellSignalStrengthNr());
     }
 
     /**
@@ -160,7 +164,23 @@
                 new CellSignalStrengthGsm(signalStrength.gsm),
                 new CellSignalStrengthWcdma(signalStrength.wcdma),
                 new CellSignalStrengthTdscdma(signalStrength.tdScdma),
-                new CellSignalStrengthLte(signalStrength.lte));
+                new CellSignalStrengthLte(signalStrength.lte),
+                new CellSignalStrengthNr());
+    }
+
+    /**
+     * Constructor for Radio HAL V1.4.
+     *
+     * @param signalStrength signal strength reported from modem.
+     * @hide
+     */
+    public SignalStrength(android.hardware.radio.V1_4.SignalStrength signalStrength) {
+        this(new CellSignalStrengthCdma(signalStrength.cdma, signalStrength.evdo),
+                new CellSignalStrengthGsm(signalStrength.gsm),
+                new CellSignalStrengthWcdma(signalStrength.wcdma),
+                new CellSignalStrengthTdscdma(signalStrength.tdscdma),
+                new CellSignalStrengthLte(signalStrength.lte),
+                new CellSignalStrengthNr(signalStrength.nr));
     }
 
     private CellSignalStrength getPrimary() {
@@ -171,6 +191,7 @@
         if (mTdscdma.isValid()) return mTdscdma;
         if (mWcdma.isValid()) return mWcdma;
         if (mGsm.isValid()) return mGsm;
+        if (mNr.isValid()) return mNr;
         return mLte;
     }
 
@@ -200,6 +221,7 @@
         if (mTdscdma.isValid()) cssList.add(mTdscdma);
         if (mWcdma.isValid()) cssList.add(mWcdma);
         if (mGsm.isValid()) cssList.add(mGsm);
+        if (mNr.isValid()) cssList.add(mNr);
         return cssList;
     }
 
@@ -210,6 +232,7 @@
         mWcdma.updateLevel(cc, ss);
         mTdscdma.updateLevel(cc, ss);
         mLte.updateLevel(cc, ss);
+        mNr.updateLevel(cc, ss);
     }
 
     /**
@@ -234,6 +257,7 @@
         mWcdma = new CellSignalStrengthWcdma(s.mWcdma);
         mTdscdma = new CellSignalStrengthTdscdma(s.mTdscdma);
         mLte = new CellSignalStrengthLte(s.mLte);
+        mNr = new CellSignalStrengthNr(s.mNr);
     }
 
     /**
@@ -250,6 +274,7 @@
         mWcdma = in.readParcelable(CellSignalStrengthWcdma.class.getClassLoader());
         mTdscdma = in.readParcelable(CellSignalStrengthTdscdma.class.getClassLoader());
         mLte = in.readParcelable(CellSignalStrengthLte.class.getClassLoader());
+        mNr = in.readParcelable(CellSignalStrengthLte.class.getClassLoader());
     }
 
     /**
@@ -261,6 +286,7 @@
         out.writeParcelable(mWcdma, flags);
         out.writeParcelable(mTdscdma, flags);
         out.writeParcelable(mLte, flags);
+        out.writeParcelable(mNr, flags);
     }
 
     /**
@@ -814,7 +840,7 @@
      */
     @Override
     public int hashCode() {
-        return Objects.hash(mCdma, mGsm, mWcdma, mTdscdma, mLte);
+        return Objects.hash(mCdma, mGsm, mWcdma, mTdscdma, mLte, mNr);
     }
 
     /**
@@ -830,7 +856,8 @@
             && mGsm.equals(s.mGsm)
             && mWcdma.equals(s.mWcdma)
             && mTdscdma.equals(s.mTdscdma)
-            && mLte.equals(s.mLte);
+            && mLte.equals(s.mLte)
+            && mNr.equals(s.mNr);
     }
 
     /**
@@ -844,6 +871,7 @@
             .append(",mWcdma=").append(mWcdma)
             .append(",mTdscdma=").append(mTdscdma)
             .append(",mLte=").append(mLte)
+            .append(",mNr=").append(mNr)
             .append(",primary=").append(getPrimary().getClass().getSimpleName())
             .append("}")
             .toString();
@@ -866,6 +894,7 @@
         mWcdma = m.getParcelable("Wcdma");
         mTdscdma = m.getParcelable("Tdscdma");
         mLte = m.getParcelable("Lte");
+        mNr = m.getParcelable("Nr");
     }
 
     /**
@@ -885,6 +914,7 @@
         m.putParcelable("Wcdma", mWcdma);
         m.putParcelable("Tdscdma", mTdscdma);
         m.putParcelable("Lte", mLte);
+        m.putParcelable("Nr", mNr);
     }
 
     /**
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index a1fb090..7c3bde4 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -354,27 +354,26 @@
      * Returns 3 for Tri standby mode.(Tri SIM functionality)
      */
     public int getPhoneCount() {
-        int phoneCount = 0;
-
-        // check for voice and data support, 0 if not supported
-        if (!isVoiceCapable() && !isSmsCapable()) {
-            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
-                    Context.CONNECTIVITY_SERVICE);
-            if (cm != null) {
-                if (!cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
-                    return phoneCount;
+        int phoneCount = 1;
+        switch (getMultiSimConfiguration()) {
+            case UNKNOWN:
+                ConnectivityManager cm = mContext == null ? null : (ConnectivityManager) mContext
+                        .getSystemService(Context.CONNECTIVITY_SERVICE);
+                // check for voice and data support, 0 if not supported
+                if (!isVoiceCapable() && !isSmsCapable() && cm != null
+                        && !cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
+                    phoneCount = 0;
+                } else {
+                    phoneCount = 1;
                 }
-            }
-        }
-
-        phoneCount = 1;
-        try {
-            ITelephony telephony = getITelephony();
-            if (telephony != null) {
-                phoneCount = telephony.getNumOfActiveSims();
-            }
-        } catch (RemoteException ex) {
-            Rlog.e(TAG, "getNumOfActiveSims RemoteException", ex);
+                break;
+            case DSDS:
+            case DSDA:
+                phoneCount = PhoneConstants.MAX_PHONE_COUNT_DUAL_SIM;
+                break;
+            case TSTS:
+                phoneCount = PhoneConstants.MAX_PHONE_COUNT_TRI_SIM;
+                break;
         }
         return phoneCount;
     }
diff --git a/telephony/java/android/telephony/euicc/EuiccManager.java b/telephony/java/android/telephony/euicc/EuiccManager.java
index b2f5802..1bbf9f4 100644
--- a/telephony/java/android/telephony/euicc/EuiccManager.java
+++ b/telephony/java/android/telephony/euicc/EuiccManager.java
@@ -408,7 +408,7 @@
     public static final int EUICC_OTA_STATUS_UNAVAILABLE = 5;
 
     private final Context mContext;
-    private final int mCardId;
+    private int mCardId;
 
     /** @hide */
     public EuiccManager(Context context) {
@@ -446,7 +446,7 @@
     public boolean isEnabled() {
         // In the future, this may reach out to IEuiccController (if non-null) to check any dynamic
         // restrictions.
-        return getIEuiccController() != null && mCardId != TelephonyManager.INVALID_CARD_ID;
+        return getIEuiccController() != null;
     }
 
     /**
@@ -456,11 +456,11 @@
      * current eUICC. A calling app with carrier privileges for one eUICC may not necessarily have
      * access to the EID of another eUICC.
      *
-     * @return the EID. May be null if {@link #isEnabled()} is false or the eUICC is not ready.
+     * @return the EID. May be null if the eUICC is not ready.
      */
     @Nullable
     public String getEid() {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             return null;
         }
         try {
@@ -475,15 +475,15 @@
      *
      * <p>Requires the {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
      *
-     * @return the status of eUICC OTA. If {@link #isEnabled()} is false or the eUICC is not ready,
-     *     {@link OtaStatus#EUICC_OTA_STATUS_UNAVAILABLE} will be returned.
+     * @return the status of eUICC OTA. If the eUICC is not ready,
+     *         {@link OtaStatus#EUICC_OTA_STATUS_UNAVAILABLE} will be returned.
      *
      * @hide
      */
     @SystemApi
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public int getOtaStatus() {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             return EUICC_OTA_STATUS_UNAVAILABLE;
         }
         try {
@@ -518,7 +518,7 @@
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void downloadSubscription(DownloadableSubscription subscription,
             boolean switchAfterDownload, PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -580,7 +580,7 @@
     @SystemApi
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void continueOperation(Intent resolutionIntent, Bundle resolutionExtras) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             PendingIntent callbackIntent =
                     resolutionIntent.getParcelableExtra(
                             EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT);
@@ -617,7 +617,7 @@
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void getDownloadableSubscriptionMetadata(
             DownloadableSubscription subscription, PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -647,7 +647,7 @@
     @SystemApi
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void getDefaultDownloadableSubscriptionList(PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -662,12 +662,11 @@
     /**
      * Returns information about the eUICC chip/device.
      *
-     * @return the {@link EuiccInfo}. May be null if {@link #isEnabled()} is false or the eUICC is
-     *     not ready.
+     * @return the {@link EuiccInfo}. May be null if the eUICC is not ready.
      */
     @Nullable
     public EuiccInfo getEuiccInfo() {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             return null;
         }
         try {
@@ -692,7 +691,7 @@
      */
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void deleteSubscription(int subscriptionId, PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -732,7 +731,7 @@
      */
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void switchToSubscription(int subscriptionId, PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -758,7 +757,7 @@
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void updateSubscriptionNickname(
             int subscriptionId, String nickname, PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -782,7 +781,7 @@
     @SystemApi
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
     public void eraseSubscriptions(PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -812,7 +811,7 @@
      * @hide
      */
     public void retainSubscriptionsForFactoryReset(PendingIntent callbackIntent) {
-        if (!isEnabled()) {
+        if (!refreshCardIdIfInvalid()) {
             sendUnavailableError(callbackIntent);
             return;
         }
@@ -823,6 +822,19 @@
         }
     }
 
+    private boolean refreshCardIdIfInvalid() {
+        if (!isEnabled()) {
+            return false;
+        }
+        // Refresh mCardId if it's invalid.
+        if (mCardId == TelephonyManager.INVALID_CARD_ID) {
+            TelephonyManager tm = (TelephonyManager)
+                    mContext.getSystemService(Context.TELEPHONY_SERVICE);
+            mCardId = tm.getCardIdForDefaultEuicc();
+        }
+        return true;
+    }
+
     private static void sendUnavailableError(PendingIntent callbackIntent) {
         try {
             callbackIntent.send(EMBEDDED_SUBSCRIPTION_RESULT_ERROR);
diff --git a/telephony/java/com/android/internal/telephony/EncodeException.java b/telephony/java/com/android/internal/telephony/EncodeException.java
index 4e3fac1..cdc853e 100644
--- a/telephony/java/com/android/internal/telephony/EncodeException.java
+++ b/telephony/java/com/android/internal/telephony/EncodeException.java
@@ -22,6 +22,12 @@
  * {@hide}
  */
 public class EncodeException extends Exception {
+
+    private int mError = ERROR_UNENCODABLE;
+
+    public static final int ERROR_UNENCODABLE = 0;
+    public static final int ERROR_EXCEED_SIZE = 1;
+
     public EncodeException() {
         super();
     }
@@ -31,9 +37,18 @@
         super(s);
     }
 
+    public EncodeException(String s, int error) {
+        super(s);
+        mError = error;
+    }
+
     @UnsupportedAppUsage
     public EncodeException(char c) {
         super("Unencodable char: '" + c + "'");
     }
+
+    public int getError() {
+        return mError;
+    }
 }
 
diff --git a/telephony/java/com/android/internal/telephony/GsmAlphabet.java b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
index 84c0e64..a774cdc 100644
--- a/telephony/java/com/android/internal/telephony/GsmAlphabet.java
+++ b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
@@ -388,7 +388,7 @@
      *     GSM extension table
      * @return the encoded message
      *
-     * @throws EncodeException if String is too large to encode
+     * @throws EncodeException if String is too large to encode or any characters are unencodable
      */
     @UnsupportedAppUsage
     public static byte[] stringToGsm7BitPacked(String data, int startingSeptetOffset,
@@ -402,7 +402,8 @@
         }
         septetCount += startingSeptetOffset;
         if (septetCount > 255) {
-            throw new EncodeException("Payload cannot exceed 255 septets");
+            throw new EncodeException(
+                    "Payload cannot exceed 255 septets", EncodeException.ERROR_EXCEED_SIZE);
         }
         int byteCount = ((septetCount * 7) + 7) / 8;
         byte[] ret = new byte[byteCount + 1];  // Include space for one byte length prefix.
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 762d886..bc43fea 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -1843,11 +1843,6 @@
      * @hide
      */
     void switchMultiSimConfig(int numOfSims);
-    /**
-     * Get how many modems have been activated on the phone
-     * @hide
-     */
-    int getNumOfActiveSims();
 
     /**
      * Get if reboot is required upon altering modems configurations
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
index 4f5bfa9..015efa6 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
@@ -384,16 +384,22 @@
                 }
             }
         } catch (EncodeException ex) {
-            // Encoding to the 7-bit alphabet failed. Let's see if we can
-            // send it as a UCS-2 encoded message
-            try {
-                userData = encodeUCS2(message, header);
-                encoding = ENCODING_16BIT;
-            } catch(UnsupportedEncodingException uex) {
-                Rlog.e(LOG_TAG,
-                        "Implausible UnsupportedEncodingException ",
-                        uex);
+            if (ex.getError() == EncodeException.ERROR_EXCEED_SIZE) {
+                Rlog.e(LOG_TAG, "Exceed size limitation EncodeException", ex);
                 return null;
+            } else {
+                // Encoding to the 7-bit alphabet failed. Let's see if we can
+                // send it as a UCS-2 encoded message
+                try {
+                    userData = encodeUCS2(message, header);
+                    encoding = ENCODING_16BIT;
+                } catch (EncodeException ex1) {
+                    Rlog.e(LOG_TAG, "Exceed size limitation EncodeException", ex1);
+                    return null;
+                } catch (UnsupportedEncodingException uex) {
+                    Rlog.e(LOG_TAG, "Implausible UnsupportedEncodingException ", uex);
+                    return null;
+                }
             }
         }
 
@@ -438,9 +444,10 @@
      *
      * @return encoded message as UCS2
      * @throws UnsupportedEncodingException
+     * @throws EncodeException if String is too large to encode
      */
     private static byte[] encodeUCS2(String message, byte[] header)
-        throws UnsupportedEncodingException {
+            throws UnsupportedEncodingException, EncodeException {
         byte[] userData, textPart;
         textPart = message.getBytes("utf-16be");
 
@@ -455,6 +462,10 @@
         else {
             userData = textPart;
         }
+        if (userData.length > 255) {
+            throw new EncodeException(
+                    "Payload cannot exceed 255 bytes", EncodeException.ERROR_EXCEED_SIZE);
+        }
         byte[] ret = new byte[userData.length+1];
         ret[0] = (byte) (userData.length & 0xff );
         System.arraycopy(userData, 0, ret, 1, userData.length);
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AutomationUtils.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AutomationUtils.java
index 6bac675..6306f0e 100644
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AutomationUtils.java
+++ b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AutomationUtils.java
@@ -173,7 +173,7 @@
             BySelector splitscreenButtonSelector = By.text("Split screen");
             UiObject2 splitscreenButton = device.wait(Until.findObject(splitscreenButtonSelector),
                     FIND_TIMEOUT);
-            assertNotNull("Unable to find Split screen button in Overview", overviewIcon);
+            assertNotNull("Unable to find Split screen button in Overview", splitscreenButton);
             splitscreenButton.click();
         } else {
             // Classic long press recents
diff --git a/tests/FrameworkPerf/AndroidManifest.xml b/tests/FrameworkPerf/AndroidManifest.xml
index ca25386..4fd2043 100644
--- a/tests/FrameworkPerf/AndroidManifest.xml
+++ b/tests/FrameworkPerf/AndroidManifest.xml
@@ -14,7 +14,7 @@
             </intent-filter>
         </activity>
         <service android:name="SchedulerService"
-            android:foregroundServiceType="sync">
+                 android:foregroundServiceType="dataSync|mediaPlayback|phoneCall|location|connectedDevice">
         </service>
         <service android:name="TestService" android:process=":test">
         </service>
@@ -23,7 +23,6 @@
         <receiver android:name="Receiver" android:exported="true">
         </receiver>
     </application>
-
     <instrumentation android:name="android.test.InstrumentationTestRunner"
         android:targetPackage="com.android.frameworkperf"
         android:label="Framework Perf Runner"
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index f330b83..1a4ec94 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -1027,5 +1027,15 @@
             </intent-filter>
         </activity>
 
+        <activity
+            android:name="PositionListenerActivity"
+            android:label="RenderNode/PositionListener"
+            android:screenOrientation="fullSensor">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="com.android.test.hwui.TEST" />
+            </intent-filter>
+        </activity>
+
     </application>
 </manifest>
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java
new file mode 100644
index 0000000..316aad3
--- /dev/null
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.test.hwui;
+
+import android.app.Activity;
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.RenderNode;
+import android.os.Bundle;
+import android.widget.LinearLayout;
+import android.widget.ProgressBar;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+@SuppressWarnings({"UnusedDeclaration"})
+public class PositionListenerActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        final LinearLayout layout = new LinearLayout(this);
+        layout.setOrientation(LinearLayout.VERTICAL);
+
+        ProgressBar spinner = new ProgressBar(this, null, android.R.attr.progressBarStyleLarge);
+        layout.addView(spinner);
+
+        ScrollView scrollingThing = new ScrollView(this);
+        scrollingThing.addView(new MyPositionReporter(this));
+        layout.addView(scrollingThing);
+
+        setContentView(layout);
+    }
+
+    static class MyPositionReporter extends TextView implements RenderNode.PositionUpdateListener {
+        RenderNode mNode;
+        int mCurrentCount = 0;
+        int mTranslateY = 0;
+
+        MyPositionReporter(Context c) {
+            super(c);
+            mNode = new RenderNode("positionListener");
+            mNode.requestPositionUpdates(this);
+            setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
+        }
+
+        @Override
+        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+            setMeasuredDimension(getMeasuredWidth(), 10000);
+        }
+
+        @Override
+        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+            mNode.setLeftTopRightBottom(left, top, right, bottom);
+        }
+
+        @Override
+        protected void onDraw(Canvas canvas) {
+            ScrollView parent = (ScrollView) getParent();
+            canvas.translate(0, parent.getScrollY());
+            super.onDraw(canvas);
+            canvas.translate(0, -parent.getScrollY());
+            // Inject our listener proxy
+            canvas.drawRenderNode(mNode);
+        }
+
+        @Override
+        public void positionChanged(long frameNumber, int left, int top, int right, int bottom) {
+            post(() -> {
+                mCurrentCount++;
+                setText(String.format("%d: Position [%d, %d, %d, %d]", mCurrentCount,
+                        left, top, right, bottom));
+            });
+        }
+
+        @Override
+        public void positionLost(long frameNumber) {
+            post(() -> {
+                mCurrentCount++;
+                setText(mCurrentCount + " No position");
+            });
+        }
+    }
+}
diff --git a/tests/JankBench/Android.mk b/tests/JankBench/Android.mk
index 75282ba..89c21b7 100644
--- a/tests/JankBench/Android.mk
+++ b/tests/JankBench/Android.mk
@@ -19,7 +19,7 @@
 
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
-    androidx.design_design \
+    com.google.android.material_material \
     androidx.legacy_legacy-support-v4 \
     androidx.appcompat_appcompat \
     androidx.cardview_cardview \
diff --git a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
index 47db602..4de51fb 100644
--- a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
+++ b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
@@ -19,22 +19,24 @@
 import android.content.Intent;
 import android.os.AsyncTask;
 import android.os.Bundle;
-import android.support.design.widget.FloatingActionButton;
-import androidx.appcompat.app.AppCompatActivity;
-import androidx.appcompat.widget.Toolbar;
 import android.view.LayoutInflater;
-import android.view.View;
 import android.view.Menu;
 import android.view.MenuItem;
+import android.view.View;
 import android.view.ViewGroup;
 import android.widget.Button;
 import android.widget.ExpandableListView;
 import android.widget.Toast;
 
-import com.android.benchmark.registry.BenchmarkRegistry;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.appcompat.widget.Toolbar;
+
 import com.android.benchmark.R;
+import com.android.benchmark.registry.BenchmarkRegistry;
 import com.android.benchmark.results.GlobalResultsStore;
 
+import com.google.android.material.floatingactionbutton.FloatingActionButton;
+
 import java.io.IOException;
 import java.util.LinkedList;
 import java.util.Queue;
diff --git a/tests/JankBench/app/src/main/res/layout/activity_home.xml b/tests/JankBench/app/src/main/res/layout/activity_home.xml
index fb30747..160d9d7 100644
--- a/tests/JankBench/app/src/main/res/layout/activity_home.xml
+++ b/tests/JankBench/app/src/main/res/layout/activity_home.xml
@@ -23,7 +23,7 @@
     android:fitsSystemWindows="true"
     tools:context=".app.HomeActivity">
 
-    <android.support.design.widget.AppBarLayout
+    <com.google.android.material.appbar.AppBarLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:theme="@style/AppTheme.AppBarOverlay">
@@ -35,7 +35,7 @@
             android:background="?attr/colorPrimary"
             app:popupTheme="@style/AppTheme.PopupOverlay" />
 
-    </android.support.design.widget.AppBarLayout>
+    </com.google.android.material.appbar.AppBarLayout>
 
     <include layout="@layout/content_main" />
 
diff --git a/tests/JankBench/app/src/main/res/layout/fragment_dashboard.xml b/tests/JankBench/app/src/main/res/layout/fragment_dashboard.xml
index 3c72dc9..2f4813f 100644
--- a/tests/JankBench/app/src/main/res/layout/fragment_dashboard.xml
+++ b/tests/JankBench/app/src/main/res/layout/fragment_dashboard.xml
@@ -22,14 +22,14 @@
     android:layout_height="fill_parent"
     android:fitsSystemWindows="true">
 
-    <android.support.design.widget.AppBarLayout
+    <com.google.android.material.appbar.AppBarLayout
         android:id="@+id/appbar"
         android:layout_width="match_parent"
         android:layout_height="@dimen/detail_backdrop_height"
         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
         android:fitsSystemWindows="true">
 
-        <android.support.design.widget.CollapsingToolbarLayout
+        <com.google.android.material.appbar.CollapsingToolbarLayout
             android:id="@+id/collapsing_toolbar"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
@@ -55,9 +55,9 @@
                 android:fitsSystemWindows="true"
                 app:layout_collapseMode="parallax" />
 
-        </android.support.design.widget.CollapsingToolbarLayout>
+        </com.google.android.material.appbar.CollapsingToolbarLayout>
 
-    </android.support.design.widget.AppBarLayout>
+    </com.google.android.material.appbar.AppBarLayout>
 
     <androidx.core.widget.NestedScrollView
         android:layout_width="match_parent"
@@ -78,7 +78,7 @@
 
     </androidx.core.widget.NestedScrollView>
 
-    <android.support.design.widget.FloatingActionButton
+    <com.google.android.material.floatingactionbutton.FloatingActionButton
         android:id="@+id/start_button"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
diff --git a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
index c1c598d..77cd62e 100644
--- a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
+++ b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
@@ -242,8 +242,9 @@
         PackageWatchdog watchdog = createWatchdog();
         long differentVersionCode = 2L;
         TestObserver observer = new TestObserver(OBSERVER_NAME_1) {
-                public int onHealthCheckFailed(String packageName, long versionCode) {
-                    if (versionCode == VERSION_CODE) {
+                @Override
+                public int onHealthCheckFailed(VersionedPackage versionedPackage) {
+                    if (versionedPackage.getVersionCode() == VERSION_CODE) {
                         // Only rollback for specific versionCode
                         return PackageHealthObserverImpact.USER_IMPACT_MEDIUM;
                     }
@@ -457,12 +458,12 @@
             mImpact = impact;
         }
 
-        public int onHealthCheckFailed(String packageName, long versionCode) {
+        public int onHealthCheckFailed(VersionedPackage versionedPackage) {
             return mImpact;
         }
 
-        public boolean execute(String packageName, long versionCode) {
-            mFailedPackages.add(packageName);
+        public boolean execute(VersionedPackage versionedPackage) {
+            mFailedPackages.add(versionedPackage.getPackageName());
             return true;
         }
 
diff --git a/tests/RollbackTest/src/com/android/tests/rollback/RollbackTest.java b/tests/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
index 4b277ae..ace0e6d 100644
--- a/tests/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
+++ b/tests/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
@@ -37,6 +37,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
@@ -628,9 +629,12 @@
         assertEquals(versionRolledBackTo, info.getVersionRolledBackTo().getLongVersionCode());
     }
 
+    // TODO: Allow installing test app along atomically with module metadata package so that
+    // a failed test app will be flagged as a failed mainline app
     /**
      * Test bad update automatic rollback.
      */
+    @Ignore
     @Test
     public void testBadUpdateRollback() throws Exception {
         BroadcastReceiver crashCountReceiver = null;
diff --git a/tests/UiBench/Android.mk b/tests/UiBench/Android.mk
index 6ec0fbb..608bf2f 100644
--- a/tests/UiBench/Android.mk
+++ b/tests/UiBench/Android.mk
@@ -15,7 +15,7 @@
 LOCAL_USE_AAPT2 := true
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
-    androidx.design_design \
+    com.google.android.material_material \
     androidx.legacy_legacy-support-v4 \
     androidx.appcompat_appcompat \
     androidx.cardview_cardview \
diff --git a/tests/UiBench/res/layout/activity_navigation_drawer.xml b/tests/UiBench/res/layout/activity_navigation_drawer.xml
index 282fb78..383432a 100644
--- a/tests/UiBench/res/layout/activity_navigation_drawer.xml
+++ b/tests/UiBench/res/layout/activity_navigation_drawer.xml
@@ -27,7 +27,7 @@
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
 
-    <android.support.design.widget.NavigationView
+    <com.google.android.material.navigation.NavigationView
         android:id="@+id/nav_view"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
diff --git a/tests/UiBench/res/layout/app_bar_navigation_drawer.xml b/tests/UiBench/res/layout/app_bar_navigation_drawer.xml
index b979134..cf209ac 100644
--- a/tests/UiBench/res/layout/app_bar_navigation_drawer.xml
+++ b/tests/UiBench/res/layout/app_bar_navigation_drawer.xml
@@ -21,7 +21,7 @@
     android:layout_height="match_parent"
     android:fitsSystemWindows="true">
 
-    <android.support.design.widget.AppBarLayout
+    <com.google.android.material.appbar.AppBarLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
@@ -31,6 +31,6 @@
             android:layout_width="match_parent"
             android:layout_height="?attr/actionBarSize"
             android:background="?attr/colorPrimary"/>
-    </android.support.design.widget.AppBarLayout>
+    </com.google.android.material.appbar.AppBarLayout>
 
 </androidx.coordinatorlayout.widget.CoordinatorLayout>
diff --git a/tests/UiBench/src/com/android/test/uibench/ClippedListActivity.java b/tests/UiBench/src/com/android/test/uibench/ClippedListActivity.java
index 6e24ce1..2bf6040 100644
--- a/tests/UiBench/src/com/android/test/uibench/ClippedListActivity.java
+++ b/tests/UiBench/src/com/android/test/uibench/ClippedListActivity.java
@@ -16,18 +16,20 @@
 package com.android.test.uibench;
 
 import android.os.Bundle;
-import android.support.design.widget.NavigationView;
-import androidx.fragment.app.FragmentManager;
-import androidx.fragment.app.ListFragment;
-import androidx.core.view.GravityCompat;
-import androidx.drawerlayout.widget.DrawerLayout;
-import androidx.appcompat.app.ActionBarDrawerToggle;
-import androidx.appcompat.app.AppCompatActivity;
-import androidx.appcompat.widget.Toolbar;
 import android.view.MenuItem;
 import android.widget.ArrayAdapter;
 import android.widget.ListAdapter;
 
+import androidx.appcompat.app.ActionBarDrawerToggle;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.appcompat.widget.Toolbar;
+import androidx.core.view.GravityCompat;
+import androidx.drawerlayout.widget.DrawerLayout;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.ListFragment;
+
+import com.google.android.material.navigation.NavigationView;
+
 public class ClippedListActivity extends AppCompatActivity
         implements NavigationView.OnNavigationItemSelectedListener {
 
diff --git a/tests/UiBench/src/com/android/test/uibench/NavigationDrawerActivity.java b/tests/UiBench/src/com/android/test/uibench/NavigationDrawerActivity.java
index 6a7761ce..7784539 100644
--- a/tests/UiBench/src/com/android/test/uibench/NavigationDrawerActivity.java
+++ b/tests/UiBench/src/com/android/test/uibench/NavigationDrawerActivity.java
@@ -16,13 +16,15 @@
 package com.android.test.uibench;
 
 import android.os.Bundle;
-import android.support.design.widget.NavigationView;
-import androidx.core.view.GravityCompat;
-import androidx.drawerlayout.widget.DrawerLayout;
+import android.view.MenuItem;
+
 import androidx.appcompat.app.ActionBarDrawerToggle;
 import androidx.appcompat.app.AppCompatActivity;
 import androidx.appcompat.widget.Toolbar;
-import android.view.MenuItem;
+import androidx.core.view.GravityCompat;
+import androidx.drawerlayout.widget.DrawerLayout;
+
+import com.google.android.material.navigation.NavigationView;
 
 public class NavigationDrawerActivity extends AppCompatActivity
         implements NavigationView.OnNavigationItemSelectedListener {
diff --git a/tools/aapt2/Android.bp b/tools/aapt2/Android.bp
index 8f75287..bc3a9a1 100644
--- a/tools/aapt2/Android.bp
+++ b/tools/aapt2/Android.bp
@@ -108,6 +108,7 @@
         "link/ProductFilter.cpp",
         "link/PrivateAttributeMover.cpp",
         "link/ReferenceLinker.cpp",
+        "link/ResourceExcluder.cpp",
         "link/TableMerger.cpp",
         "link/XmlCompatVersioner.cpp",
         "link/XmlNamespaceRemover.cpp",
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
index 729447e..8463046 100644
--- a/tools/aapt2/cmd/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -59,6 +59,7 @@
 #include "link/ManifestFixer.h"
 #include "link/NoDefaultResourceRemover.h"
 #include "link/ReferenceLinker.h"
+#include "link/ResourceExcluder.h"
 #include "link/TableMerger.h"
 #include "link/XmlCompatVersioner.h"
 #include "optimize/ResourceDeduper.h"
@@ -1828,6 +1829,29 @@
       }
     }
 
+    if (!options_.exclude_configs_.empty()) {
+      std::vector<ConfigDescription> excluded_configs;
+
+      for (auto& config_string : options_.exclude_configs_) {
+        ConfigDescription config_description;
+
+        if (!ConfigDescription::Parse(config_string, &config_description)) {
+          context_->GetDiagnostics()->Error(DiagMessage()
+                                                << "failed to parse --excluded-configs "
+                                                << config_string);
+          return 1;
+        }
+
+        excluded_configs.push_back(config_description);
+      }
+
+      ResourceExcluder excluder(excluded_configs);
+      if (!excluder.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
+        return 1;
+      }
+    }
+
     if (!options_.no_resource_deduping) {
       ResourceDeduper deduper;
       if (!deduper.Consume(context_, &final_table_)) {
diff --git a/tools/aapt2/cmd/Link.h b/tools/aapt2/cmd/Link.h
index f70470a..590a6bb 100644
--- a/tools/aapt2/cmd/Link.h
+++ b/tools/aapt2/cmd/Link.h
@@ -82,6 +82,9 @@
   std::vector<SplitConstraints> split_constraints;
   std::vector<std::string> split_paths;
 
+  // Configurations to exclude
+  std::vector<std::string> exclude_configs_;
+
   // Stable ID options.
   std::unordered_map<ResourceName, ResourceId> stable_id_map;
   Maybe<std::string> resource_id_map_path;
@@ -255,6 +258,9 @@
             "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
             "On Windows, use a semicolon ';' separator instead.",
         &split_args_);
+    AddOptionalFlagList("--exclude-configs",
+        "Excludes values of resources whose configs contain the specified qualifiers.",
+        &options_.exclude_configs_);
     AddOptionalSwitch("--debug-mode",
         "Inserts android:debuggable=\"true\" in to the application node of the\n"
             "manifest, making the application debuggable even on production devices.",
diff --git a/tools/aapt2/link/ResourceExcluder.cpp b/tools/aapt2/link/ResourceExcluder.cpp
new file mode 100644
index 0000000..2555995
--- /dev/null
+++ b/tools/aapt2/link/ResourceExcluder.cpp
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "link/ResourceExcluder.h"
+
+#include <algorithm>
+
+#include "DominatorTree.h"
+#include "ResourceTable.h"
+
+using android::ConfigDescription;
+
+namespace aapt {
+
+namespace {
+
+void RemoveIfExcluded(std::set<std::pair<ConfigDescription, int>>& excluded_configs_,
+                      IAaptContext* context,
+                      ResourceEntry* entry,
+                      ResourceConfigValue* value) {
+  const ConfigDescription& config = value->config;
+
+  // If this entry is a default, ignore
+  if (config == ConfigDescription::DefaultConfig()) {
+    return;
+  }
+
+  for (auto& excluded_pair : excluded_configs_) {
+
+    const ConfigDescription& excluded_config = excluded_pair.first;
+    const int& excluded_diff = excluded_pair.second;
+
+    // Check whether config contains all flags in excluded config
+    int node_diff = config.diff(excluded_config);
+    int masked_diff = excluded_diff & node_diff;
+
+    if (masked_diff == 0) {
+      if (context->IsVerbose()) {
+        context->GetDiagnostics()->Note(
+            DiagMessage(value->value->GetSource())
+                << "excluded resource \""
+                << entry->name
+                << "\" with config "
+                << config.toString());
+      }
+      value->value = {};
+      return;
+    }
+  }
+}
+
+}  // namespace
+
+bool ResourceExcluder::Consume(IAaptContext* context, ResourceTable* table) {
+  for (auto& package : table->packages) {
+    for (auto& type : package->types) {
+      for (auto& entry : type->entries) {
+        for (auto& value : entry->values) {
+          RemoveIfExcluded(excluded_configs_, context, entry.get(), value.get());
+        }
+
+        // Erase the values that were removed.
+        entry->values.erase(
+            std::remove_if(
+                entry->values.begin(), entry->values.end(),
+                [](const std::unique_ptr<ResourceConfigValue>& val) -> bool {
+                  return val == nullptr || val->value == nullptr;
+                }),
+            entry->values.end());
+      }
+    }
+  }
+  return true;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/link/ResourceExcluder.h b/tools/aapt2/link/ResourceExcluder.h
new file mode 100644
index 0000000..1890b34
--- /dev/null
+++ b/tools/aapt2/link/ResourceExcluder.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef AAPT_LINK_RESOURCEEXCLUDER_H
+#define AAPT_LINK_RESOURCEEXCLUDER_H
+
+#include "android-base/macros.h"
+
+#include "process/IResourceTableConsumer.h"
+
+using android::ConfigDescription;
+
+namespace aapt {
+
+// Removes excluded configs from resources.
+class ResourceExcluder : public IResourceTableConsumer {
+ public:
+  explicit ResourceExcluder(std::vector<ConfigDescription>& excluded_configs) {
+    for (auto& config: excluded_configs) {
+      int diff_from_default = config.diff(ConfigDescription::DefaultConfig());
+      excluded_configs_.insert(std::pair(config, diff_from_default));
+    }
+  }
+
+  bool Consume(IAaptContext* context, ResourceTable* table) override;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(ResourceExcluder);
+
+  std::set<std::pair<ConfigDescription, int>> excluded_configs_;
+};
+
+} // namespace aapt
+
+#endif  // AAPT_LINK_RESOURCEEXCLUDER_H
diff --git a/tools/aapt2/link/ResourceExcluder_test.cpp b/tools/aapt2/link/ResourceExcluder_test.cpp
new file mode 100644
index 0000000..c9d01e4
--- /dev/null
+++ b/tools/aapt2/link/ResourceExcluder_test.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "link/ResourceExcluder.h"
+
+#include "ResourceTable.h"
+#include "test/Test.h"
+
+using ::aapt::test::HasValue;
+using ::android::ConfigDescription;
+using ::testing::Not;
+
+namespace {
+
+ConfigDescription BuildArg(const std::string arg) {
+  ConfigDescription config_description;
+  ConfigDescription::Parse(arg, &config_description);
+  return config_description;
+}
+
+std::vector<ConfigDescription> BuildArgList(const std::string arg) {
+  ConfigDescription config_description;
+  ConfigDescription::Parse(arg, &config_description);
+  return { config_description };
+}
+
+} // namespace
+
+namespace aapt {
+
+TEST(ResourceExcluderTest, NonMatchConfigNotExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto fr_config = test::ParseConfigOrDie("fr");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .Build();
+
+  auto args = BuildArgList("en");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, HasValue("android:string/test", fr_config));
+}
+
+TEST(ResourceExcluderTest, ExactConfigExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto fr_config = test::ParseConfigOrDie("fr");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .Build();
+
+  auto args = BuildArgList("fr");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_config)));
+}
+
+TEST(ResourceExcluderTest, MoreSpecificConfigExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto fr_land_config = test::ParseConfigOrDie("fr-land");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, fr_land_config, "fr-land")
+          .Build();
+
+  auto args = BuildArgList("fr");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_land_config)));
+}
+
+TEST(ResourceExcluderTest, MultipleMoreSpecificConfigExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto night_config = test::ParseConfigOrDie("night");
+  auto fr_config = test::ParseConfigOrDie("fr");
+  auto fr_land_config = test::ParseConfigOrDie("fr-land");
+  auto fr_night_config = test::ParseConfigOrDie("fr-night");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, night_config, "night")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .AddString("android:string/test", ResourceId{}, fr_land_config, "fr-land")
+          .AddString("android:string/test", ResourceId{}, fr_night_config, "fr-night")
+          .Build();
+
+  auto args = BuildArgList("fr");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, HasValue("android:string/test", night_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_config)));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_land_config)));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_night_config)));
+}
+
+TEST(ResourceExcluderTest, MultipleConfigsExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto night_config = test::ParseConfigOrDie("night");
+  auto fr_config = test::ParseConfigOrDie("fr");
+  auto fr_land_config = test::ParseConfigOrDie("fr-land");
+  auto fr_night_config = test::ParseConfigOrDie("fr-night");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, night_config, "night")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .AddString("android:string/test", ResourceId{}, fr_land_config, "fr-land")
+          .AddString("android:string/test", ResourceId{}, fr_night_config, "fr-night")
+          .Build();
+
+  std::vector<ConfigDescription> args;
+  args.push_back(BuildArg("land"));
+  args.push_back(BuildArg("night"));
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", night_config)));
+  EXPECT_THAT(table, HasValue("android:string/test", fr_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_land_config)));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_night_config)));
+}
+
+TEST(ResourceExcluderTest, LessSpecificConfigNotExcluded) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto fr_config = test::ParseConfigOrDie("fr");
+  auto fr_land_config = test::ParseConfigOrDie("fr-land");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .AddString("android:string/test", ResourceId{}, fr_land_config, "fr-land")
+          .Build();
+
+  auto args = BuildArgList("fr-land");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, HasValue("android:string/test", fr_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_land_config)));
+}
+
+TEST(ResourceExcluderTest, LowerPrecedenceStillExcludes) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto fr_config = test::ParseConfigOrDie("fr");
+  auto fr_night_config = test::ParseConfigOrDie("fr-night");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, fr_config, "fr")
+          .AddString("android:string/test", ResourceId{}, fr_night_config, "fr-night")
+          .Build();
+
+  // "night" is lower precedence than "fr"
+  auto args = BuildArgList("night");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, HasValue("android:string/test", fr_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", fr_night_config)));
+}
+
+TEST(ResourceExcluderTest, OnlyExcludesSpecificTier) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  ConfigDescription default_config;
+  auto mdpi_config = test::ParseConfigOrDie("mdpi");
+  auto hdpi_config = test::ParseConfigOrDie("hdpi");
+  auto xhdpi_config = test::ParseConfigOrDie("xhdpi");
+
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddString("android:string/test", ResourceId{}, default_config, "default")
+          .AddString("android:string/test", ResourceId{}, mdpi_config, "mdpi")
+          .AddString("android:string/test", ResourceId{}, hdpi_config, "hdpi")
+          .AddString("android:string/test", ResourceId{}, xhdpi_config, "xhdpi")
+          .Build();
+
+  auto args = BuildArgList("hdpi");
+
+  ASSERT_TRUE(ResourceExcluder(args).Consume(context.get(), table.get()));
+  EXPECT_THAT(table, HasValue("android:string/test", default_config));
+  EXPECT_THAT(table, HasValue("android:string/test", mdpi_config));
+  EXPECT_THAT(table, Not(HasValue("android:string/test", hdpi_config)));
+  EXPECT_THAT(table, HasValue("android:string/test", xhdpi_config));
+}
+
+}  // namespace aapt
diff --git a/wifi/java/android/net/wifi/rtt/CivicLocation.java b/wifi/java/android/net/wifi/rtt/CivicLocation.java
new file mode 100644
index 0000000..a669d77
--- /dev/null
+++ b/wifi/java/android/net/wifi/rtt/CivicLocation.java
@@ -0,0 +1,323 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.rtt;
+
+import android.annotation.Nullable;
+import android.location.Address;
+import android.net.wifi.rtt.CivicLocationKeys.CivicLocationKeysType;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.Parcelable.Creator;
+import android.util.SparseArray;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+import java.util.Objects;
+
+/**
+ * Decodes the Type Length Value (TLV) elements found in a Location Civic Record as defined by IEEE
+ * P802.11-REVmc/D8.0 section 9.4.2.22.13 using the format described in IETF RFC 4776.
+ *
+ * <p>The TLVs each define a key, value pair for a civic address type such as apt, street, city,
+ * county, and country. The class provides a general getter method to extract a value for an element
+ * key, returning null if not set.
+ *
+ * @hide
+ */
+public final class CivicLocation implements Parcelable {
+    // Address (class) line indexes
+    private static final int ADDRESS_LINE_0_ROOM_DESK_FLOOR = 0;
+    private static final int ADDRESS_LINE_1_NUMBER_ROAD_SUFFIX_APT = 1;
+    private static final int ADDRESS_LINE_2_CITY = 2;
+    private static final int ADDRESS_LINE_3_STATE_POSTAL_CODE = 3;
+    private static final int ADDRESS_LINE_4_COUNTRY = 4;
+
+    // Buffer management
+    private static final int MIN_CIVIC_BUFFER_SIZE = 3;
+    private static final int MAX_CIVIC_BUFFER_SIZE = 256;
+    private static final int COUNTRY_CODE_LENGTH = 2;
+    private static final int BYTE_MASK = 0xFF;
+    private static final int TLV_TYPE_INDEX = 0;
+    private static final int TLV_LENGTH_INDEX = 1;
+    private static final int TLV_VALUE_INDEX = 2;
+
+    private final boolean mIsValid;
+    private final String mCountryCode; // Two character country code (ISO 3166 standard).
+    private SparseArray<String> mCivicAddressElements =
+            new SparseArray<>(MIN_CIVIC_BUFFER_SIZE);
+
+
+    /**
+     * Constructor
+     *
+     * @param civicTLVs    a byte buffer containing parameters in the form type, length, value
+     * @param countryCode the two letter code defined by the ISO 3166 standard
+     *
+     * @hide
+     */
+    public CivicLocation(@Nullable byte[] civicTLVs, @Nullable String countryCode) {
+        this.mCountryCode = countryCode;
+        if (countryCode == null || countryCode.length() != COUNTRY_CODE_LENGTH) {
+            this.mIsValid = false;
+            return;
+        }
+        boolean isValid = false;
+        if (civicTLVs != null
+                && civicTLVs.length >= MIN_CIVIC_BUFFER_SIZE
+                && civicTLVs.length < MAX_CIVIC_BUFFER_SIZE) {
+            isValid = parseCivicTLVs(civicTLVs);
+        }
+
+        mIsValid = isValid;
+    }
+
+    private CivicLocation(Parcel in) {
+        mIsValid = in.readByte() != 0;
+        mCountryCode = in.readString();
+        mCivicAddressElements = in.readSparseArray(this.getClass().getClassLoader());
+    }
+
+    public static final Creator<CivicLocation> CREATOR = new Creator<CivicLocation>() {
+        @Override
+        public CivicLocation createFromParcel(Parcel in) {
+            return new CivicLocation(in);
+        }
+
+        @Override
+        public CivicLocation[] newArray(int size) {
+            return new CivicLocation[size];
+        }
+    };
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+        parcel.writeByte((byte) (mIsValid ? 1 : 0));
+        parcel.writeString(mCountryCode);
+        parcel.writeSparseArray((android.util.SparseArray) mCivicAddressElements);
+    }
+
+    /**
+     * Check TLV format and store TLV key/value pairs in this object so they can be queried by key.
+     *
+     * @param civicTLVs the buffer of TLV elements
+     * @return a boolean indicating success of the parsing process
+     */
+    private boolean parseCivicTLVs(byte[] civicTLVs) {
+        int bufferPtr = 0;
+        int bufferLength = civicTLVs.length;
+
+        // Iterate through the sub-elements contained in the LCI IE checking the accumulated
+        // element lengths do not overflow the total buffer length
+        while (bufferPtr < bufferLength) {
+            int civicAddressType = civicTLVs[bufferPtr + TLV_TYPE_INDEX] & BYTE_MASK;
+            int civicAddressTypeLength = civicTLVs[bufferPtr + TLV_LENGTH_INDEX];
+            if (civicAddressTypeLength != 0) {
+                if (bufferPtr + TLV_VALUE_INDEX + civicAddressTypeLength > bufferLength) {
+                    return false;
+                }
+                mCivicAddressElements.put(civicAddressType,
+                        new String(civicTLVs, bufferPtr + TLV_VALUE_INDEX,
+                                civicAddressTypeLength, StandardCharsets.UTF_8));
+            }
+            bufferPtr += civicAddressTypeLength + TLV_VALUE_INDEX;
+        }
+        return true;
+    }
+
+    /**
+     * Getter for the value of a civic Address element type.
+     *
+     * @param key an integer code for the element type key
+     * @return the string value associated with that element type
+     */
+    @Nullable
+    public String getCivicElementValue(@CivicLocationKeysType int key) {
+        return mCivicAddressElements.get(key);
+    }
+
+    /**
+     * Generates a comma separated string of all the defined elements.
+     *
+     * @return a compiled string representing all elements
+     */
+    @Override
+    public String toString() {
+        return mCivicAddressElements.toString();
+    }
+
+    /**
+     * Converts Civic Location to the best effort Address Object.
+     *
+     * @return the {@link Address} object based on the Civic Location data
+     */
+    @Nullable
+    public Address toAddress() {
+        if (!mIsValid) {
+            return null;
+        }
+        Address address = new Address(Locale.US);
+        String room = formatAddressElement("Room: ", getCivicElementValue(CivicLocationKeys.ROOM));
+        String desk =
+                formatAddressElement(" Desk: ", getCivicElementValue(CivicLocationKeys.DESK));
+        String floor =
+                formatAddressElement(", Flr: ", getCivicElementValue(CivicLocationKeys.FLOOR));
+        String houseNumber = formatAddressElement("", getCivicElementValue(CivicLocationKeys.HNO));
+        String houseNumberSuffix =
+                formatAddressElement("", getCivicElementValue(CivicLocationKeys.HNS));
+        String road =
+                formatAddressElement(" ", getCivicElementValue(
+                        CivicLocationKeys.PRIMARY_ROAD_NAME));
+        String roadSuffix = formatAddressElement(" ", getCivicElementValue(CivicLocationKeys.STS));
+        String apt = formatAddressElement(", Apt: ", getCivicElementValue(CivicLocationKeys.APT));
+        String city = formatAddressElement("", getCivicElementValue(CivicLocationKeys.CITY));
+        String state = formatAddressElement("", getCivicElementValue(CivicLocationKeys.STATE));
+        String postalCode =
+                formatAddressElement(" ", getCivicElementValue(CivicLocationKeys.POSTAL_CODE));
+
+        // Aggregation into common address format
+        String addressLine0 =
+                new StringBuilder().append(room).append(desk).append(floor).toString();
+        String addressLine1 =
+                new StringBuilder().append(houseNumber).append(houseNumberSuffix).append(road)
+                        .append(roadSuffix).append(apt).toString();
+        String addressLine2 = city;
+        String addressLine3 = new StringBuilder().append(state).append(postalCode).toString();
+        String addressLine4 = mCountryCode;
+
+        // Setting Address object line fields by common convention.
+        address.setAddressLine(ADDRESS_LINE_0_ROOM_DESK_FLOOR, addressLine0);
+        address.setAddressLine(ADDRESS_LINE_1_NUMBER_ROAD_SUFFIX_APT, addressLine1);
+        address.setAddressLine(ADDRESS_LINE_2_CITY, addressLine2);
+        address.setAddressLine(ADDRESS_LINE_3_STATE_POSTAL_CODE, addressLine3);
+        address.setAddressLine(ADDRESS_LINE_4_COUNTRY, addressLine4);
+
+        // Other compatible fields between the CIVIC_ADDRESS and the Address Class.
+        address.setFeatureName(getCivicElementValue(CivicLocationKeys.NAM)); // Structure name
+        address.setSubThoroughfare(getCivicElementValue(CivicLocationKeys.HNO));
+        address.setThoroughfare(getCivicElementValue(CivicLocationKeys.PRIMARY_ROAD_NAME));
+        address.setSubLocality(getCivicElementValue(CivicLocationKeys.NEIGHBORHOOD));
+        address.setSubAdminArea(getCivicElementValue(CivicLocationKeys.COUNTY));
+        address.setAdminArea(getCivicElementValue(CivicLocationKeys.STATE));
+        address.setPostalCode(getCivicElementValue(CivicLocationKeys.POSTAL_CODE));
+        address.setCountryCode(mCountryCode); // Country
+        return address;
+    }
+
+    /**
+     * Prepares an address element so that it can be integrated into an address line convention.
+     *
+     * <p>If an address element is null, the return string will be empty e.g. "".
+     *
+     * @param label a string defining the type of address element
+     * @param value a string defining the elements value
+     * @return the formatted version of the value, with null values converted to empty strings
+     */
+    private String formatAddressElement(String label, String value) {
+        if (value != null) {
+            return label + value;
+        } else {
+            return "";
+        }
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof CivicLocation)) {
+            return false;
+        }
+        CivicLocation other = (CivicLocation) obj;
+        return mIsValid == other.mIsValid
+                && Objects.equals(mCountryCode, other.mCountryCode)
+                && isSparseArrayStringEqual(mCivicAddressElements, other.mCivicAddressElements);
+    }
+
+    @Override
+    public int hashCode() {
+        int[] civicAddressKeys = getSparseArrayKeys(mCivicAddressElements);
+        String[] civicAddressValues = getSparseArrayValues(mCivicAddressElements);
+        return Objects.hash(mIsValid, mCountryCode, civicAddressKeys, civicAddressValues);
+    }
+
+    /**
+     * Tests if the Civic Location object is valid
+     *
+     * @return a boolean defining mIsValid
+     */
+    public boolean isValid() {
+        return mIsValid;
+    }
+
+    /**
+     * Tests if two sparse arrays are equal on a key for key basis
+     *
+     * @param sa1 the first sparse array
+     * @param sa2 the second sparse array
+     * @return the boolean result after comparing values key by key
+     */
+    private boolean isSparseArrayStringEqual(SparseArray<String> sa1, SparseArray<String> sa2) {
+        int size = sa1.size();
+        if (size != sa2.size()) {
+            return false;
+        }
+        for (int i = 0; i < size; i++) {
+            String sa1Value = sa1.valueAt(i);
+            String sa2Value = sa2.valueAt(i);
+            if (!sa1Value.equals(sa2Value)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Extract an array of all the keys in a SparseArray<String>
+     *
+     * @param sa the sparse array of Strings
+     * @return an integer array of all keys in the SparseArray<String>
+     */
+    private int[] getSparseArrayKeys(SparseArray<String> sa) {
+        int size = sa.size();
+        int[] keys = new int[size];
+        for (int i = 0; i < size; i++) {
+            keys[i] = sa.keyAt(i);
+        }
+        return keys;
+    }
+
+    /**
+     * Extract an array of all the String values in a SparseArray<String>
+     *
+     * @param sa the sparse array of Strings
+     * @return a String array of all values in the SparseArray<String>
+     */
+    private String[] getSparseArrayValues(SparseArray<String> sa) {
+        int size = sa.size();
+        String[] values = new String[size];
+        for (int i = 0; i < size; i++) {
+            values[i] = sa.valueAt(i);
+        }
+        return values;
+    }
+}
diff --git a/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java b/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java
new file mode 100644
index 0000000..17c3671
--- /dev/null
+++ b/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.rtt;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Civic Address key types used to define address elements.
+ *
+ * <p>These keys can be used in ResponderLocation look-up the corresponding string values.</p>
+ *
+ * @hide
+ */
+public class CivicLocationKeys {
+
+    /**
+     * An enumeration of all civic location keys.
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef({LANGUAGE, STATE, COUNTY, CITY, BOROUGH, NEIGHBORHOOD, GROUP_OF_STREETS, PRD, POD, STS,
+            HNO, HNS, LMK, LOC, NAM, POSTAL_CODE, BUILDING, APT, FLOOR, ROOM, TYPE_OF_PLACE, PCN,
+            PO_BOX, ADDITIONAL_CODE, DESK, PRIMARY_ROAD_NAME, ROAD_SECTION, BRANCH_ROAD_NAME,
+            SUBBRANCH_ROAD_NAME, STREET_NAME_PRE_MODIFIER, STREET_NAME_POST_MODIFIER, SCRIPT})
+    public @interface CivicLocationKeysType {
+    }
+
+    /** Language key e.g. i-default. */
+    public static final int LANGUAGE = 0;
+    /** Category label A1 key e.g. California. */
+    public static final int STATE = 1;
+    /** Category label A2 key e.g. Marin. */
+    public static final int COUNTY = 2;
+    /** Category label A3 key e.g. San Francisco. */
+    public static final int CITY = 3;
+    /** Category label A4 key e.g. Westminster. */
+    public static final int BOROUGH = 4;
+    /** Category label A5 key e.g. Pacific Heights. */
+    public static final int NEIGHBORHOOD = 5;
+    /** Category label A6 key e.g. University District. */
+    public static final int GROUP_OF_STREETS = 6;
+    // 7 - 15 not defined
+    /** Leading Street direction key e.g. N. */
+    public static final int PRD = 16;
+    /** Trailing street suffix key e.g. SW. */
+    public static final int POD = 17;
+    /** Street suffix or Type key e.g Ave, Platz. */
+    public static final int STS = 18;
+    /** House Number key e.g. 123. */
+    public static final int HNO = 19;
+    /** House number suffix key e.g. A, 1/2. */
+    public static final int HNS = 20;
+    /** Landmark or vanity address key e.g. Columbia Univ. */
+    public static final int LMK = 21;
+    /** Additional Location info key e.g. South Wing. */
+    public static final int LOC = 22;
+    /** Name of residence key e.g. Joe's Barbershop. */
+    public static final int NAM = 23;
+    /** Postal or ZIP code key e.g. 10027-1234. */
+    public static final int POSTAL_CODE = 24;
+    /** Building key e.g. Low Library. */
+    public static final int BUILDING = 25;
+    /** Apartment or suite key e.g. Apt 42. */
+    public static final int APT = 26;
+    /** Floor key e.g. 4. */
+    public static final int FLOOR = 27;
+    /** Room key e.g. 450F. */
+    public static final int ROOM = 28;
+    /** Type of place key e.g. office. */
+    public static final int TYPE_OF_PLACE = 29;
+    /** Postal community name key e.g. Leonia. */
+    public static final int PCN = 30;
+    /** Post Office Box key e.g. 12345. */
+    public static final int PO_BOX = 31;
+    /** Additional Code key e.g. 13203000003. */
+    public static final int ADDITIONAL_CODE = 32;
+    /** Seat, desk, pole, or cubical key e.g. WS 181. */
+    public static final int DESK = 33;
+    /** Primary road name key e.g. Shoreline. */
+    public static final int PRIMARY_ROAD_NAME = 34;
+    /** Road Section key e.g. 14. */
+    public static final int ROAD_SECTION = 35;
+    /** Branch Rd Name key e.g. Lane 7. */
+    public static final int BRANCH_ROAD_NAME = 36;
+    /** Subbranch Rd Name key e.g. Alley 8. */
+    public static final int SUBBRANCH_ROAD_NAME = 37;
+    /** Premodifier key e.g. Old. */
+    public static final int STREET_NAME_PRE_MODIFIER = 38;
+    /** Postmodifier key e.g. Service. */
+    public static final int STREET_NAME_POST_MODIFIER = 39;
+    /** Script key e.g. Latn. */
+    public static final int SCRIPT = 128;
+
+    /** private constructor */
+    private CivicLocationKeys() {}
+}
+
diff --git a/wifi/java/android/net/wifi/rtt/RangingResult.java b/wifi/java/android/net/wifi/rtt/RangingResult.java
index 758a8d5..b53b35c 100644
--- a/wifi/java/android/net/wifi/rtt/RangingResult.java
+++ b/wifi/java/android/net/wifi/rtt/RangingResult.java
@@ -82,12 +82,14 @@
     private final int mNumSuccessfulMeasurements;
     private final byte[] mLci;
     private final byte[] mLcr;
+    private final ResponderLocation mResponderLocation;
     private final long mTimestamp;
 
     /** @hide */
     public RangingResult(@RangeResultStatus int status, @NonNull MacAddress mac, int distanceMm,
             int distanceStdDevMm, int rssi, int numAttemptedMeasurements,
-            int numSuccessfulMeasurements, byte[] lci, byte[] lcr, long timestamp) {
+            int numSuccessfulMeasurements, byte[] lci, byte[] lcr,
+            ResponderLocation responderLocation, long timestamp) {
         mStatus = status;
         mMac = mac;
         mPeerHandle = null;
@@ -98,13 +100,15 @@
         mNumSuccessfulMeasurements = numSuccessfulMeasurements;
         mLci = lci == null ? EMPTY_BYTE_ARRAY : lci;
         mLcr = lcr == null ? EMPTY_BYTE_ARRAY : lcr;
+        mResponderLocation = responderLocation;
         mTimestamp = timestamp;
     }
 
     /** @hide */
     public RangingResult(@RangeResultStatus int status, PeerHandle peerHandle, int distanceMm,
             int distanceStdDevMm, int rssi, int numAttemptedMeasurements,
-            int numSuccessfulMeasurements, byte[] lci, byte[] lcr, long timestamp) {
+            int numSuccessfulMeasurements, byte[] lci, byte[] lcr,
+            ResponderLocation responderLocation, long timestamp) {
         mStatus = status;
         mMac = null;
         mPeerHandle = peerHandle;
@@ -115,6 +119,7 @@
         mNumSuccessfulMeasurements = numSuccessfulMeasurements;
         mLci = lci == null ? EMPTY_BYTE_ARRAY : lci;
         mLcr = lcr == null ? EMPTY_BYTE_ARRAY : lcr;
+        mResponderLocation = responderLocation;
         mTimestamp = timestamp;
     }
 
@@ -240,6 +245,24 @@
     }
 
     /**
+     * @return The responder location represented as {@link ResponderLocation} which captures
+     * location information the responder is programmed to broadcast.
+     * <p>
+     * Will return a {@code null} when the location information cannot be parsed.
+     * <p>
+     * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
+     * exception.
+     */
+    @Nullable
+    public ResponderLocation getResponderLocation() {
+        if (mStatus != STATUS_SUCCESS) {
+            throw new IllegalStateException(
+                    "getResponderLocation(): invoked on an invalid result: getStatus()=" + mStatus);
+        }
+        return mResponderLocation;
+    }
+
+    /**
      * @return The Location Configuration Information (LCI) as self-reported by the peer. The format
      * is specified in the IEEE 802.11-2016 specifications, section 9.4.2.22.10.
      * <p>
@@ -322,6 +345,7 @@
         dest.writeInt(mNumSuccessfulMeasurements);
         dest.writeByteArray(mLci);
         dest.writeByteArray(mLcr);
+        dest.writeParcelable(mResponderLocation, flags);
         dest.writeLong(mTimestamp);
     }
 
@@ -351,13 +375,17 @@
             int numSuccessfulMeasurements = in.readInt();
             byte[] lci = in.createByteArray();
             byte[] lcr = in.createByteArray();
+            ResponderLocation responderLocation =
+                    in.readParcelable(this.getClass().getClassLoader());
             long timestamp = in.readLong();
             if (peerHandlePresent) {
                 return new RangingResult(status, peerHandle, distanceMm, distanceStdDevMm, rssi,
-                        numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, timestamp);
+                        numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr,
+                        responderLocation, timestamp);
             } else {
                 return new RangingResult(status, mac, distanceMm, distanceStdDevMm, rssi,
-                        numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, timestamp);
+                        numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr,
+                        responderLocation, timestamp);
             }
         }
     };
@@ -372,7 +400,8 @@
                 ", rssi=").append(mRssi).append(", numAttemptedMeasurements=").append(
                 mNumAttemptedMeasurements).append(", numSuccessfulMeasurements=").append(
                 mNumSuccessfulMeasurements).append(", lci=").append(mLci).append(", lcr=").append(
-                mLcr).append(", timestamp=").append(mTimestamp).append("]").toString();
+                mLcr).append(", responderLocation=").append(mResponderLocation)
+                .append(", timestamp=").append(mTimestamp).append("]").toString();
     }
 
     @Override
@@ -393,12 +422,14 @@
                 && mNumAttemptedMeasurements == lhs.mNumAttemptedMeasurements
                 && mNumSuccessfulMeasurements == lhs.mNumSuccessfulMeasurements
                 && Arrays.equals(mLci, lhs.mLci) && Arrays.equals(mLcr, lhs.mLcr)
-                && mTimestamp == lhs.mTimestamp;
+                && mTimestamp == lhs.mTimestamp
+                && Objects.equals(mResponderLocation, lhs.mResponderLocation);
     }
 
     @Override
     public int hashCode() {
         return Objects.hash(mStatus, mMac, mPeerHandle, mDistanceMm, mDistanceStdDevMm, mRssi,
-                mNumAttemptedMeasurements, mNumSuccessfulMeasurements, mLci, mLcr, mTimestamp);
+                mNumAttemptedMeasurements, mNumSuccessfulMeasurements, mLci, mLcr,
+                mResponderLocation, mTimestamp);
     }
 }
diff --git a/wifi/java/android/net/wifi/rtt/ResponderLocation.java b/wifi/java/android/net/wifi/rtt/ResponderLocation.java
new file mode 100644
index 0000000..2912a67
--- /dev/null
+++ b/wifi/java/android/net/wifi/rtt/ResponderLocation.java
@@ -0,0 +1,1356 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.rtt;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.annotation.IntDef;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.location.Address;
+import android.net.MacAddress;
+import android.net.wifi.rtt.CivicLocationKeys.CivicLocationKeysType;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.lang.annotation.Retention;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * ResponderLocation is both a Location Configuration Information (LCI) decoder and a Location Civic
+ * Report (LCR) decoder for information received from a Wi-Fi Access Point (AP) during Wi-Fi RTT
+ * ranging process.
+ *
+ * <p>This is based on the IEEE P802.11-REVmc/D8.0 spec section 9.4.2.22, under Measurement Report
+ * Element. Subelement location data-fields parsed from separate input LCI and LCR Information
+ * Elements are unified in this class.</p>
+ *
+ * <p>Note: The information provided by this class is broadcast by a responder (usually an Access
+ * Point), and passed on as-is. There is no guarantee this information is accurate or correct, and
+ * as a result developers should carefully consider how this information should be used and provide
+ * corresponding advice to users.</p>
+ */
+public final class ResponderLocation implements Parcelable {
+    private static final int BYTE_MASK = 0xFF;
+    private static final int LSB_IN_BYTE = 0x01;
+    private static final int MSB_IN_BYTE = 0x80;
+    private static final int MIN_BUFFER_SIZE = 3; // length of LEAD_LCI_ELEMENT_BYTES
+    private static final int MAX_BUFFER_SIZE = 256;
+
+    // Information Element (IE) fields
+    private static final byte MEASUREMENT_TOKEN_AUTONOMOUS = 0x01;
+    private static final byte MEASUREMENT_REPORT_MODE = 0x00;
+    private static final byte MEASUREMENT_TYPE_LCI = 0x08;
+    private static final byte MEASUREMENT_TYPE_LCR = 0x0b;
+
+    // LCI Subelement IDs
+    private static final byte SUBELEMENT_LCI = 0x00;
+    private static final byte SUBELEMENT_Z = 0x04;
+    private static final byte SUBELEMENT_USAGE = 0x06;
+    private static final byte SUBELEMENT_BSSID_LIST = 0x07;
+
+    // LCI Subelement Lengths
+    private static final int SUBELEMENT_LCI_LENGTH = 16;
+    private static final int SUBELEMENT_Z_LENGTH = 6;
+    private static final int SUBELEMENT_USAGE_LENGTH1 = 1;
+    private static final int SUBELEMENT_USAGE_LENGTH3 = 3;
+    private static final int SUBELEMENT_BSSID_LIST_MIN_BUFFER_LENGTH = 1;
+
+    private static final byte[] LEAD_LCI_ELEMENT_BYTES = {
+            MEASUREMENT_TOKEN_AUTONOMOUS, MEASUREMENT_REPORT_MODE, MEASUREMENT_TYPE_LCI
+    };
+
+    // Subelement LCI constants
+
+    /* The LCI subelement bit-field lengths are described in Figure 9-214 of the REVmc spec and
+    represented here as a an array of integers */
+    private static final int[] SUBELEMENT_LCI_BIT_FIELD_LENGTHS = {
+            6, 34, 6, 34, 4, 6, 30, 3, 1, 1, 1, 2
+    };
+    private static final int LATLNG_FRACTION_BITS = 25;
+    private static final int LATLNG_UNCERTAINTY_BASE = 8;
+    private static final int ALTITUDE_FRACTION_BITS = 8;
+    private static final int ALTITUDE_UNCERTAINTY_BASE = 21;
+    private static final double LAT_ABS_LIMIT = 90.0;
+    private static final double LNG_ABS_LIMIT = 180.0;
+    private static final int UNCERTAINTY_UNDEFINED = 0;
+
+    // Subelement LCI fields indices
+    private static final int SUBELEMENT_LCI_LAT_UNCERTAINTY_INDEX = 0;
+    private static final int SUBELEMENT_LCI_LAT_INDEX = 1;
+    private static final int SUBELEMENT_LCI_LNG_UNCERTAINTY_INDEX = 2;
+    private static final int SUBELEMENT_LCI_LNG_INDEX = 3;
+    private static final int SUBELEMENT_LCI_ALT_TYPE_INDEX = 4;
+    private static final int SUBELEMENT_LCI_ALT_UNCERTAINTY_INDEX = 5;
+    private static final int SUBELEMENT_LCI_ALT_INDEX = 6;
+    private static final int SUBELEMENT_LCI_DATUM_INDEX = 7;
+    private static final int SUBELEMENT_LCI_REGLOC_AGREEMENT_INDEX = 8;
+    private static final int SUBELEMENT_LCI_REGLOC_DSE_INDEX = 9;
+    private static final int SUBELEMENT_LCI_DEPENDENT_STA_INDEX = 10;
+    private static final int SUBELEMENT_LCI_VERSION_INDEX = 11;
+
+    /**
+     * The Altitude value is interpreted based on the Altitude Type, and the selected mDatum.
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef({ALTITUDE_UNDEFINED, ALTITUDE_METERS, ALTITUDE_FLOORS})
+    public @interface AltitudeType {
+    }
+
+    /**
+     * Altitude is not defined for the Responder.
+     * The altitude and altitude uncertainty should not be used: see section 2.4 of IETF RFC 6225.
+     */
+    public static final int ALTITUDE_UNDEFINED = 0;
+    /** Responder Altitude is measured in meters.  */
+    public static final int ALTITUDE_METERS = 1;
+    /** Responder Altitude is measured in floors. */
+    public static final int ALTITUDE_FLOORS = 2;
+
+    /**
+     * The Datum value determines how coordinates are organized in relation to the real world.
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef({DATUM_UNDEFINED, DATUM_WGS84, DATUM_NAD83_NAV88, DATUM_NAD83_MLLW})
+    public @interface DatumType {
+    }
+
+    /** Datum is not defined. */
+    public static final int DATUM_UNDEFINED = 0;
+    /** Datum used is WGS84. */
+    public static final int DATUM_WGS84 = 1;
+    /** Datum used is NAD83 NAV88. */
+    public static final int DATUM_NAD83_NAV88 = 2;
+    /** Datum used is NAD83 MLLW. */
+    public static final int DATUM_NAD83_MLLW = 3;
+
+
+    /** Version of the LCI protocol is 1.0, the only defined protocol at this time. */
+    public static final int LCI_VERSION_1 = 1;
+
+    /**
+     * Enumerates the flags contained in getLciFlags()
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef(flag = true, value = {LCI_FLAGS_MASK_REGLOC_AGREEMENT, LCI_FLAGS_MASK_REGLOC_DSE,
+        LCI_FLAGS_MASK_DEPENDENT_STA, LCI_FLAGS_MASK_VERSION})
+    public @interface LciFlagMasks {
+    }
+    /** Location agreement flag is obtained by ANDing this mask with the getLciFlags() value.*/
+    public static final int LCI_FLAGS_MASK_REGLOC_AGREEMENT = 0x10;
+    /** Location DSE flag is obtained by ANDing this mask with the getLciFlags() value.*/
+    public static final int LCI_FLAGS_MASK_REGLOC_DSE = 0x08;
+    /** Dependent station flag is obtained by ANDing this mask with the getLciFlags() value. */
+    public static final int LCI_FLAGS_MASK_DEPENDENT_STA = 0x04;
+    /** Version bits are obtained by ANDing this mask with the getLciFlags() value.*/
+    public static final int LCI_FLAGS_MASK_VERSION = 0x03;
+
+    // LCI Subelement Z constants
+    private static final int[] SUBELEMENT_Z_BIT_FIELD_LENGTHS = {2, 14, 24, 8};
+    private static final int Z_FLOOR_NUMBER_FRACTION_BITS = 4;
+    private static final int Z_FLOOR_HEIGHT_FRACTION_BITS = 12;
+    private static final int Z_MAX_HEIGHT_UNCERTAINTY_FACTOR = 25;
+
+    // LCI Subelement Z fields indices
+    private static final int SUBELEMENT_Z_LAT_EXPECTED_TO_MOVE_INDEX = 0;
+    private static final int SUBELEMENT_Z_STA_FLOOR_NUMBER_INDEX = 1;
+    private static final int SUBELEMENT_Z_STA_HEIGHT_ABOVE_FLOOR_INDEX = 2;
+    private static final int SUBELEMENT_Z_STA_HEIGHT_ABOVE_FLOOR_UNCERTAINTY_INDEX = 3;
+
+    // LCI Subelement Usage Rules constants
+    private static final int SUBELEMENT_USAGE_MASK_RETRANSMIT = 0x01;
+    private static final int SUBELEMENT_USAGE_MASK_RETENTION_EXPIRES = 0x02;
+    private static final int SUBELEMENT_USAGE_MASK_STA_LOCATION_POLICY = 0x04;
+
+    // LCI Subelement Usage Rules field indices
+    private static final int SUBELEMENT_USAGE_PARAMS_INDEX = 0; // 8 bits
+
+    // LCI Subelement BSSID List
+    private static final int SUBELEMENT_BSSID_MAX_INDICATOR_INDEX = 0;
+    private static final int SUBELEMENT_BSSID_LIST_INDEX = 1;
+    private static final int BYTES_IN_A_BSSID = 6;
+
+    /**
+     * The Expected-To-Move value determines how mobile we expect the STA to be.
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef({LOCATION_FIXED, LOCATION_VARIABLE, LOCATION_MOVEMENT_UNKNOWN, LOCATION_RESERVED})
+    public @interface ExpectedToMoveType {
+    }
+
+    /** Location of responder is fixed (does not move) */
+    public static final int LOCATION_FIXED = 0;
+    /** Location of the responder is variable, and may move */
+    public static final int LOCATION_VARIABLE = 1;
+    /** Location of the responder is not known to be either fixed or variable. */
+    public static final int LOCATION_MOVEMENT_UNKNOWN = 2;
+    /** Location of the responder status is a reserved value */
+    public static final int LOCATION_RESERVED = 3;
+
+    // LCR Subelement IDs
+    private static final byte SUBELEMENT_LOCATION_CIVIC = 0x00;
+    private static final byte SUBELEMENT_MAP_IMAGE = 0x05;
+
+    // LCR Subelement Lengths
+    private static final int SUBELEMENT_LOCATION_CIVIC_MIN_LENGTH = 2;
+    private static final int SUBELEMENT_LOCATION_CIVIC_MAX_LENGTH = 256;
+    private static final int SUBELEMENT_MAP_IMAGE_URL_MAX_LENGTH = 256;
+
+    private static final byte[] LEAD_LCR_ELEMENT_BYTES = {
+            MEASUREMENT_TOKEN_AUTONOMOUS, MEASUREMENT_REPORT_MODE, MEASUREMENT_TYPE_LCR
+    };
+
+    // LCR Location Civic Subelement
+    private static final int CIVIC_COUNTRY_CODE_INDEX = 0;
+    private static final int CIVIC_TLV_LIST_INDEX = 2;
+
+    // LCR Map Image Subelement field indexes.
+    private static final int SUBELEMENT_IMAGE_MAP_TYPE_INDEX = 0;
+
+    /**
+     * The Map Type value specifies the image format type.
+     *
+     * @hide
+     */
+    @Retention(SOURCE)
+    @IntDef({
+            MAP_TYPE_URL_DEFINED,
+            MAP_TYPE_PNG,
+            MAP_TYPE_GIF,
+            MAP_TYPE_JPG,
+            MAP_TYPE_SVG,
+            MAP_TYPE_DXF,
+            MAP_TYPE_DWG,
+            MAP_TYPE_DWF,
+            MAP_TYPE_CAD,
+            MAP_TYPE_TIFF,
+            MAP_TYPE_GML,
+            MAP_TYPE_KML,
+            MAP_TYPE_BMP,
+            MAP_TYPE_PGM,
+            MAP_TYPE_PPM,
+            MAP_TYPE_XBM,
+            MAP_TYPE_XPM,
+            MAP_TYPE_ICO
+    })
+    public @interface MapImageType {
+    }
+
+    /** File type defined by the file suffix itself. */
+    public static final int MAP_TYPE_URL_DEFINED = 0;
+    /** File type is in PNG format. */
+    public static final int MAP_TYPE_PNG = 1;
+    /** File type is in GIF format. */
+    public static final int MAP_TYPE_GIF = 2;
+    /** File type is in JPG format. */
+    public static final int MAP_TYPE_JPG = 3;
+    /** File type is in SVG format. */
+    public static final int MAP_TYPE_SVG = 4;
+    /** File type is in DXF format. */
+    public static final int MAP_TYPE_DXF = 5;
+    /** File type is in DWG format. */
+    public static final int MAP_TYPE_DWG = 6;
+    /** File type is in DWF format. */
+    public static final int MAP_TYPE_DWF = 7;
+    /** File type is in CAD format. */
+    public static final int MAP_TYPE_CAD = 8;
+    /** File type is in TIFF format. */
+    public static final int MAP_TYPE_TIFF = 9;
+    /** File type is in GML format. */
+    public static final int MAP_TYPE_GML = 10;
+    /** File type is in KML format. */
+    public static final int MAP_TYPE_KML = 11;
+    /** File type is in BMP format. */
+    public static final int MAP_TYPE_BMP = 12;
+    /** File type is in PGM format. */
+    public static final int MAP_TYPE_PGM = 13;
+    /** File type is in PPM format. */
+    public static final int MAP_TYPE_PPM = 14;
+    /** File type is in XBM format. */
+    public static final int MAP_TYPE_XBM = 15;
+    /** File type is in XPM format. */
+    public static final int MAP_TYPE_XPM = 16;
+    /** File type is in ICO format. */
+    public static final int MAP_TYPE_ICO = 17;
+
+    // General LCI and LCR state
+    private final boolean mIsValid;
+
+    /*
+      These members are not final because we are not sure if the corresponding subelement will be
+      present until after the parsing process. However, the default value should be set as listed.
+    */
+    private boolean mIsLciValid = false;
+    private boolean mIsZValid = false;
+    private boolean mIsUsageValid = true; // By default this is assumed true
+    private boolean mIsBssidListValid = false;
+    private boolean mIsLocationCivicValid = false;
+    private boolean mIsMapImageValid = false;
+
+    // LCI Subelement LCI state
+    private double mLatitudeUncertainty;
+    private double mLatitude;
+    private double mLongitudeUncertainty;
+    private double mLongitude;
+    private int mAltitudeType;
+    private double mAltitudeUncertainty;
+    private double mAltitude;
+    private int mDatum;
+    private int mLciFlags;
+
+    // LCI Subelement Z state
+    private int mExpectedToMove;
+    private double mStaFloorNumber;
+    private double mStaHeightAboveFloorMeters;
+    private double mStaHeightAboveFloorUncertaintyMeters;
+
+    // LCI Subelement Usage Rights state
+    private boolean mUsageRetransmit;
+    private boolean mUsageRetentionExpires;
+    private boolean mUsageExtraInfoOnAssociation;
+
+    // LCI Subelement BSSID List state
+    private ArrayList<MacAddress> mBssidList;
+
+    // LCR Subelement Location Civic state
+    private String mCivicLocationCountryCode;
+    private String mCivicLocationString;
+    private CivicLocation mCivicLocation;
+
+    // LCR Subelement Map Image state
+    private int mMapImageType;
+    private URL mMapImageUrl;
+
+    /**
+     * Constructor
+     *
+     * @param lciBuffer the bytes received in the LCI Measurement Report Information Element
+     * @param lcrBuffer the bytes received in the LCR Measurement Report Information Element
+     *
+     * @hide
+     */
+    public ResponderLocation(byte[] lciBuffer, byte[] lcrBuffer) {
+        boolean isLciIeValid = false;
+        boolean isLcrIeValid = false;
+        setLciSubelementDefaults();
+        setZSubelementDefaults();
+        setUsageSubelementDefaults();
+        setBssidListSubelementDefaults();
+        setCivicLocationSubelementDefaults();
+        setMapImageSubelementDefaults();
+        if (lciBuffer != null && lciBuffer.length > LEAD_LCI_ELEMENT_BYTES.length) {
+            isLciIeValid = parseInformationElementBuffer(
+                MEASUREMENT_TYPE_LCI, lciBuffer, LEAD_LCI_ELEMENT_BYTES);
+        }
+        if (lcrBuffer != null && lcrBuffer.length > LEAD_LCR_ELEMENT_BYTES.length) {
+            isLcrIeValid = parseInformationElementBuffer(
+                MEASUREMENT_TYPE_LCR, lcrBuffer, LEAD_LCR_ELEMENT_BYTES);
+        }
+
+        boolean isLciValid = isLciIeValid && mIsUsageValid
+                && (mIsLciValid || mIsZValid || mIsBssidListValid);
+
+        boolean isLcrValid = isLcrIeValid && mIsUsageValid
+                && (mIsLocationCivicValid || mIsMapImageValid);
+
+        mIsValid = isLciValid || isLcrValid;
+
+        if (!mIsValid) {
+            setLciSubelementDefaults();
+            setZSubelementDefaults();
+            setCivicLocationSubelementDefaults();
+            setMapImageSubelementDefaults();
+        }
+    }
+
+    private ResponderLocation(Parcel in) {
+        // Object Validation
+        mIsValid = in.readByte() != 0;
+        mIsLciValid = in.readByte() != 0;
+        mIsZValid = in.readByte() != 0;
+        mIsUsageValid = in.readByte() != 0;
+        mIsBssidListValid = in.readByte() != 0;
+        mIsLocationCivicValid = in.readByte() != 0;
+        mIsMapImageValid = in.readByte() != 0;
+
+        // LCI Subelement LCI state
+        mLatitudeUncertainty = in.readDouble();
+        mLatitude = in.readDouble();
+        mLongitudeUncertainty = in.readDouble();
+        mLongitude = in.readDouble();
+        mAltitudeType = in.readInt();
+        mAltitudeUncertainty = in.readDouble();
+        mAltitude = in.readDouble();
+        mDatum = in.readInt();
+        mLciFlags = in.readInt();
+
+        // LCI Subelement Z state
+        mExpectedToMove = in.readInt();
+        mStaFloorNumber = in.readDouble();
+        mStaHeightAboveFloorMeters = in.readDouble();
+        mStaHeightAboveFloorUncertaintyMeters = in.readDouble();
+
+        // LCI Usage Rights
+        mUsageRetransmit = in.readByte() != 0;
+        mUsageRetentionExpires = in.readByte() != 0;
+        mUsageExtraInfoOnAssociation = in.readByte() != 0;
+
+        // LCI Subelement BSSID List
+        mBssidList = in.readArrayList(MacAddress.class.getClassLoader());
+
+        // LCR Subelement Location Civic
+        mCivicLocationCountryCode = in.readString();
+        mCivicLocationString = in.readString();
+        mCivicLocation = in.readParcelable(this.getClass().getClassLoader());
+
+        // LCR Subelement Map Image
+        mMapImageType = in.readInt();
+        try {
+            mMapImageUrl = new URL(in.readString());
+        } catch (MalformedURLException e) {
+            mMapImageUrl = null;
+        }
+    }
+
+    public static final Creator<ResponderLocation> CREATOR = new Creator<ResponderLocation>() {
+        @Override
+        public ResponderLocation createFromParcel(Parcel in) {
+            return new ResponderLocation(in);
+        }
+
+        @Override
+        public ResponderLocation[] newArray(int size) {
+            return new ResponderLocation[size];
+        }
+    };
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+        // Object
+        parcel.writeByte((byte) (mIsValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsLciValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsZValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsUsageValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsBssidListValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsLocationCivicValid ? 1 : 0));
+        parcel.writeByte((byte) (mIsMapImageValid ? 1 : 0));
+
+        // LCI Subelement LCI state
+        parcel.writeDouble(mLatitudeUncertainty);
+        parcel.writeDouble(mLatitude);
+        parcel.writeDouble(mLongitudeUncertainty);
+        parcel.writeDouble(mLongitude);
+        parcel.writeInt(mAltitudeType);
+        parcel.writeDouble(mAltitudeUncertainty);
+        parcel.writeDouble(mAltitude);
+        parcel.writeInt(mDatum);
+        parcel.writeInt(mLciFlags);
+
+        // LCI Subelement Z state
+        parcel.writeInt(mExpectedToMove);
+        parcel.writeDouble(mStaFloorNumber);
+        parcel.writeDouble(mStaHeightAboveFloorMeters);
+        parcel.writeDouble(mStaHeightAboveFloorUncertaintyMeters);
+
+        // LCI Usage Rights
+        parcel.writeByte((byte) (mUsageRetransmit ? 1 : 0));
+        parcel.writeByte((byte) (mUsageRetentionExpires ? 1 : 0));
+        parcel.writeByte((byte) (mUsageExtraInfoOnAssociation ? 1 : 0));
+
+        // LCI Subelement BSSID List
+        parcel.writeList(mBssidList);
+
+        // LCR Subelement Location Civic
+        parcel.writeString(mCivicLocationCountryCode);
+        parcel.writeString(mCivicLocationString);
+        parcel.writeParcelable(mCivicLocation, flags);
+
+        // LCR Subelement Map Image
+        parcel.writeInt(mMapImageType);
+        if (mMapImageUrl != null) {
+            parcel.writeString(mMapImageUrl.toString());
+        } else {
+            parcel.writeString("");
+        }
+    }
+
+    /**
+     * Test if the Information Element (IE) is in the correct format, and then parse its Subelements
+     * based on their type, and setting state in this object when present.
+     *
+     * @return a boolean indicating the success of the parsing function
+     */
+    private boolean parseInformationElementBuffer(
+            int ieType, byte[] buffer, byte[] expectedLeadBytes) {
+        int bufferPtr = 0;
+        int bufferLength = buffer.length;
+
+        // Ensure the buffer size is within expected limits
+        if (bufferLength < MIN_BUFFER_SIZE || bufferLength > MAX_BUFFER_SIZE) {
+            return false;
+        }
+
+        // Ensure the IE contains the correct leading bytes
+        byte[] leadBufferBytes = Arrays.copyOfRange(buffer, bufferPtr, expectedLeadBytes.length);
+        if (!Arrays.equals(leadBufferBytes, expectedLeadBytes)) {
+            return false;
+        }
+
+        // Iterate through the sub-elements contained in the Information Element (IE)
+        bufferPtr += expectedLeadBytes.length;
+        // Loop over the buffer ensuring there are 2-bytes available for each new subelement tested.
+        while (bufferPtr + 1 < bufferLength) {
+            byte subelement = buffer[bufferPtr++];
+            int subelementLength = buffer[bufferPtr++];
+            // Check there is enough data for the next subelement
+            if ((bufferPtr + subelementLength) > bufferLength || subelementLength <= 0) {
+                return false;
+            }
+
+            byte[] subelementData =
+                    Arrays.copyOfRange(buffer, bufferPtr, bufferPtr + subelementLength);
+
+            if (ieType == MEASUREMENT_TYPE_LCI) {
+                switch (subelement) {
+                    case SUBELEMENT_LCI:
+                        mIsLciValid = parseSubelementLci(subelementData);
+                        if (!mIsLciValid || (mLciFlags & LCI_FLAGS_MASK_VERSION) != LCI_VERSION_1) {
+                            setLciSubelementDefaults();
+                        }
+                        break;
+                    case SUBELEMENT_Z:
+                        mIsZValid = parseSubelementZ(subelementData);
+                        if (!mIsZValid) {
+                            setZSubelementDefaults();
+                        }
+                        break;
+                    case SUBELEMENT_USAGE:
+                        mIsUsageValid = parseSubelementUsage(subelementData);
+                        // Note: if the Usage Subelement is not valid, don't reset the state, as
+                        // it is now indicating the whole ResponderLocation is invalid.
+                        break;
+                    case SUBELEMENT_BSSID_LIST:
+                        mIsBssidListValid = parseSubelementBssidList(subelementData);
+                        if (!mIsBssidListValid) {
+                            setBssidListSubelementDefaults();
+                        }
+                        break;
+                    default:
+                        break; // skip over unused or vendor specific subelements
+                }
+            } else if (ieType == MEASUREMENT_TYPE_LCR) {
+                switch (subelement) {
+                    case SUBELEMENT_LOCATION_CIVIC:
+                        mIsLocationCivicValid = parseSubelementLocationCivic(subelementData);
+                        if (!mIsLocationCivicValid) {
+                            setCivicLocationSubelementDefaults();
+                        }
+                        break;
+                    case SUBELEMENT_MAP_IMAGE:
+                        mIsMapImageValid = parseSubelementMapImage(subelementData);
+                        if (!mIsMapImageValid) {
+                            setMapImageSubelementDefaults();
+                        }
+                        break;
+                    default:
+                        break; // skip over unused or other vendor specific subelements
+                }
+            }
+
+            bufferPtr += subelementLength;
+        }
+        return true;
+    }
+
+    /**
+     * Parse the LCI Sub-Element in the LCI Information Element (IE).
+     *
+     * @param buffer a buffer containing the subelement
+     * @return boolean true indicates success
+     */
+    private boolean parseSubelementLci(byte[] buffer) {
+        if (buffer.length > SUBELEMENT_LCI_LENGTH) {
+            return false;
+        }
+        swapEndianByteByByte(buffer);
+        long[] subelementLciFields = getFieldData(buffer, SUBELEMENT_LCI_BIT_FIELD_LENGTHS);
+        if (subelementLciFields == null) {
+            return false;
+        }
+        // Set member state based on parsed buffer data
+        mLatitudeUncertainty = decodeLciLatLngUncertainty(
+                subelementLciFields[SUBELEMENT_LCI_LAT_UNCERTAINTY_INDEX]);
+        mLatitude = decodeLciLatLng(subelementLciFields, SUBELEMENT_LCI_BIT_FIELD_LENGTHS,
+                SUBELEMENT_LCI_LAT_INDEX, LAT_ABS_LIMIT);
+        mLongitudeUncertainty = decodeLciLatLngUncertainty(
+                subelementLciFields[SUBELEMENT_LCI_LNG_UNCERTAINTY_INDEX]);
+        mLongitude =
+                decodeLciLatLng(subelementLciFields, SUBELEMENT_LCI_BIT_FIELD_LENGTHS,
+                        SUBELEMENT_LCI_LNG_INDEX, LNG_ABS_LIMIT);
+        mAltitudeType = (int) subelementLciFields[SUBELEMENT_LCI_ALT_TYPE_INDEX] & BYTE_MASK;
+        mAltitudeUncertainty =
+                decodeLciAltUncertainty(subelementLciFields[SUBELEMENT_LCI_ALT_UNCERTAINTY_INDEX]);
+        mAltitude =
+                Math.scalb(subelementLciFields[SUBELEMENT_LCI_ALT_INDEX], -ALTITUDE_FRACTION_BITS);
+        mDatum = (int) subelementLciFields[SUBELEMENT_LCI_DATUM_INDEX] & BYTE_MASK;
+        mLciFlags =
+                (int) subelementLciFields[SUBELEMENT_LCI_REGLOC_AGREEMENT_INDEX]
+                        * LCI_FLAGS_MASK_REGLOC_AGREEMENT
+                        | (int) subelementLciFields[SUBELEMENT_LCI_REGLOC_DSE_INDEX]
+                        * LCI_FLAGS_MASK_REGLOC_DSE
+                        | (int) subelementLciFields[SUBELEMENT_LCI_DEPENDENT_STA_INDEX]
+                        * LCI_FLAGS_MASK_DEPENDENT_STA
+                        | (int) subelementLciFields[SUBELEMENT_LCI_VERSION_INDEX];
+        return true;
+    }
+
+    /**
+     * Decode the floating point value of an encoded lat or lng in the LCI subelement field.
+     *
+     * @param fields        the array of field data represented as longs
+     * @param bitFieldSizes the lengths of each field
+     * @param offset        the offset of the field being decoded
+     * @param limit the maximum absolute value (note: different for lat vs lng)
+     * @return the floating point value of the lat or lng
+     */
+    private double decodeLciLatLng(long[] fields, int[] bitFieldSizes, int offset, double limit) {
+        double angle;
+        if ((fields[offset] & (long) Math.pow(2, bitFieldSizes[offset] - 1)) != 0) {
+            // Negative 2's complement value
+            // Note: The Math.pow(...) method cannot return a NaN value because the bitFieldSize
+            // for Lat or Lng is limited to exactly 34 bits.
+            angle = Math.scalb(fields[offset] - Math.pow(2, bitFieldSizes[offset]),
+                    -LATLNG_FRACTION_BITS);
+        } else {
+            // Positive 2's complement value
+            angle = Math.scalb(fields[offset], -LATLNG_FRACTION_BITS);
+        }
+        if (angle > limit) {
+            angle = limit;
+        } else if (angle < -limit) {
+            angle = -limit;
+        }
+        return angle;
+    }
+
+    /**
+     * Coverts an encoded Lat/Lng uncertainty into a number of degrees.
+     *
+     * @param encodedValue the encoded uncertainty
+     * @return the value in degrees
+     */
+    private double decodeLciLatLngUncertainty(long encodedValue) {
+        return Math.pow(2, LATLNG_UNCERTAINTY_BASE - encodedValue);
+    }
+
+    /**
+     * Converts an encoded Alt uncertainty into a number of degrees.
+     *
+     * @param encodedValue the encoded uncertainty
+     * @return the value in degrees
+     */
+    private double decodeLciAltUncertainty(long encodedValue) {
+        return Math.pow(2, ALTITUDE_UNCERTAINTY_BASE - encodedValue);
+    }
+
+    /**
+     * Parse the Z subelement of the LCI IE.
+     *
+     * @param buffer a buffer containing the subelement
+     * @return boolean true indicates success
+     */
+    private boolean parseSubelementZ(byte[] buffer) {
+        if (buffer.length != SUBELEMENT_Z_LENGTH) {
+            return false;
+        }
+        swapEndianByteByByte(buffer);
+        long[] subelementZFields = getFieldData(buffer, SUBELEMENT_Z_BIT_FIELD_LENGTHS);
+        if (subelementZFields == null) {
+            return false;
+        }
+
+        mExpectedToMove =
+                (int) subelementZFields[SUBELEMENT_Z_LAT_EXPECTED_TO_MOVE_INDEX] & BYTE_MASK;
+
+        mStaFloorNumber = decodeZUnsignedToSignedValue(subelementZFields,
+                SUBELEMENT_Z_BIT_FIELD_LENGTHS, SUBELEMENT_Z_STA_FLOOR_NUMBER_INDEX,
+                Z_FLOOR_NUMBER_FRACTION_BITS);
+
+        mStaHeightAboveFloorMeters = decodeZUnsignedToSignedValue(subelementZFields,
+                SUBELEMENT_Z_BIT_FIELD_LENGTHS, SUBELEMENT_Z_STA_HEIGHT_ABOVE_FLOOR_INDEX,
+                Z_FLOOR_HEIGHT_FRACTION_BITS);
+
+        long zHeightUncertainty =
+                subelementZFields[SUBELEMENT_Z_STA_HEIGHT_ABOVE_FLOOR_UNCERTAINTY_INDEX];
+        if (zHeightUncertainty > 0 && zHeightUncertainty < Z_MAX_HEIGHT_UNCERTAINTY_FACTOR) {
+            mStaHeightAboveFloorUncertaintyMeters =
+                    Math.pow(2, Z_FLOOR_HEIGHT_FRACTION_BITS - zHeightUncertainty - 1);
+        } else {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Decode a two's complement encoded value, to a signed double based on the field length.
+     *
+     * @param fieldValues the array of field values reprented as longs
+     * @param fieldLengths the array of field lengths
+     * @param index the index of the field being decoded
+     * @param fraction the number of fractional bits in the value
+     * @return the signed value represented as a double
+     */
+    private double decodeZUnsignedToSignedValue(long[] fieldValues, int[] fieldLengths, int index,
+            int fraction) {
+        int value = (int) fieldValues[index];
+        int maxPositiveValue = (int) Math.pow(2, fieldLengths[index] - 1) - 1;
+        if (value > maxPositiveValue) {
+            value -= Math.pow(2, fieldLengths[index]);
+        }
+        return Math.scalb(value, -fraction);
+    }
+
+    /**
+     * Parse Subelement Usage Rights
+     */
+    private boolean parseSubelementUsage(byte[] buffer) {
+        if (buffer.length != SUBELEMENT_USAGE_LENGTH1
+                && buffer.length != SUBELEMENT_USAGE_LENGTH3) {
+            return false;
+        }
+        mUsageRetransmit =
+                (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_RETRANSMIT) != 0;
+        mUsageRetentionExpires =
+                (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_RETENTION_EXPIRES)
+                        != 0;
+        mUsageExtraInfoOnAssociation =
+                (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_STA_LOCATION_POLICY)
+                        != 0;
+        // Note: the Retransmit flag must be true, and RetentionExpires, false for the
+        // ResponderLocation object to be usable by public applications.
+        return (mUsageRetransmit && !mUsageRetentionExpires);
+    }
+
+    /**
+     * Parse the BSSID List Subelement of the LCI IE.
+     *
+     * @param buffer a buffer containing the subelement
+     * @return boolean true indicates success
+     */
+    private boolean parseSubelementBssidList(byte[] buffer) {
+        if (buffer.length < SUBELEMENT_BSSID_LIST_MIN_BUFFER_LENGTH) {
+            return false;
+        }
+        if ((buffer.length - 1) % BYTES_IN_A_BSSID != 0) {
+            return false;
+        }
+
+        int maxBssidIndicator = (int) buffer[SUBELEMENT_BSSID_MAX_INDICATOR_INDEX] & BYTE_MASK;
+        int bssidListLength = (buffer.length - 1) / BYTES_IN_A_BSSID;
+        // Check the max number of BSSIDs agrees with the list length.
+        if (maxBssidIndicator != bssidListLength) {
+            return false;
+        }
+
+        int bssidOffset = SUBELEMENT_BSSID_LIST_INDEX;
+        for (int i = 0; i < bssidListLength; i++) {
+            byte[] bssid = Arrays.copyOfRange(buffer, bssidOffset, bssidOffset + BYTES_IN_A_BSSID);
+            MacAddress macAddress = MacAddress.fromBytes(bssid);
+            mBssidList.add(macAddress);
+            bssidOffset += BYTES_IN_A_BSSID;
+        }
+        return true;
+    }
+
+    /**
+     * Parse the Location Civic subelement in the LCR IE.
+     *
+     * @param buffer a buffer containing the subelement
+     * @return boolean true indicates success
+     */
+    private boolean parseSubelementLocationCivic(byte[] buffer) {
+        if (buffer.length <  SUBELEMENT_LOCATION_CIVIC_MIN_LENGTH
+                || buffer.length > SUBELEMENT_LOCATION_CIVIC_MAX_LENGTH) {
+            return false;
+        }
+        mCivicLocationCountryCode =
+                new String(Arrays.copyOfRange(buffer, CIVIC_COUNTRY_CODE_INDEX,
+                        CIVIC_TLV_LIST_INDEX)).toUpperCase();
+        CivicLocation civicLocation =
+                new CivicLocation(
+                        Arrays.copyOfRange(buffer, CIVIC_TLV_LIST_INDEX, buffer.length),
+                        mCivicLocationCountryCode);
+        if (!civicLocation.isValid()) {
+            return false;
+        }
+        this.mCivicLocation = civicLocation;
+        mCivicLocationString = civicLocation.toString();
+        return true;
+    }
+
+    /**
+     * Parse the Map Image subelement in the LCR IE.
+     *
+     * @param buffer a buffer containing the subelement
+     * @return boolean true indicates success
+     */
+    private boolean parseSubelementMapImage(byte[] buffer) {
+        if (buffer.length > SUBELEMENT_MAP_IMAGE_URL_MAX_LENGTH) {
+            return false;
+        }
+        int mapImageType = buffer[SUBELEMENT_IMAGE_MAP_TYPE_INDEX];
+        if (mapImageType < MAP_TYPE_URL_DEFINED || mapImageType > MAP_TYPE_DWG) {
+            return false;
+        }
+        this.mMapImageType = mapImageType;
+        byte[] urlBytes = Arrays.copyOfRange(buffer, 1, buffer.length);
+        try {
+            mMapImageUrl = new URL(new String(urlBytes));
+        } catch (MalformedURLException e) {
+            mMapImageUrl = null;
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Converts a byte array containing fields of variable size, into an array of longs where the
+     * field boundaries are defined in a constant int array passed as an argument.
+     *
+     * @param buffer        the byte array containing all the fields
+     * @param bitFieldSizes the int array defining the size of each field
+     */
+    private long[] getFieldData(byte[] buffer, int[] bitFieldSizes) {
+        int bufferLengthBits = buffer.length * Byte.SIZE;
+        int sumBitFieldSizes = 0;
+        for (int i : bitFieldSizes) {
+            if (i > Long.SIZE) {
+                return null;
+            }
+            sumBitFieldSizes += i;
+        }
+        if (bufferLengthBits != sumBitFieldSizes) {
+            return null;
+        }
+        long[] fieldData = new long[bitFieldSizes.length];
+        int bufferBitPos = 0;
+        for (int fieldIndex = 0; fieldIndex < bitFieldSizes.length; fieldIndex++) {
+            int bitFieldSize = bitFieldSizes[fieldIndex];
+            long field = 0;
+            for (int n = 0; n < bitFieldSize; n++) {
+                field |= ((long) getBitAtBitOffsetInByteArray(buffer, bufferBitPos + n) << n);
+            }
+            fieldData[fieldIndex] = field;
+            bufferBitPos += bitFieldSize;
+        }
+        return fieldData;
+    }
+
+    /**
+     * Retrieves state of a bit at the bit-offset in a byte array, where the offset represents the
+     * bytes in contiguous data with each value in big endian order.
+     *
+     * @param buffer          the data buffer of bytes containing all the fields
+     * @param bufferBitOffset the bit offset into the entire buffer
+     * @return a zero or one value, representing the state of that bit.
+     */
+    private int getBitAtBitOffsetInByteArray(byte[] buffer, int bufferBitOffset) {
+        int bufferIndex = bufferBitOffset / Byte.SIZE; // The byte index that contains the bit
+        int bitOffsetInByte = bufferBitOffset % Byte.SIZE; // The bit offset within that byte
+        int result = (buffer[bufferIndex] & (MSB_IN_BYTE >> bitOffsetInByte)) == 0 ? 0 : 1;
+        return result;
+    }
+
+    /**
+     * Reverses the order of the bits in each byte of a byte array.
+     *
+     * @param buffer the array containing each byte that will be reversed
+     */
+    private void swapEndianByteByByte(byte[] buffer) {
+        for (int n = 0; n < buffer.length; n++) {
+            byte currentByte = buffer[n];
+            byte reversedByte = 0; // Cleared value
+            byte bitSelectorMask = LSB_IN_BYTE;
+            for (int i = 0; i < Byte.SIZE; i++) {
+                reversedByte = (byte) (reversedByte << 1);
+                if ((currentByte & bitSelectorMask) != 0) {
+                    reversedByte = (byte) (reversedByte | LSB_IN_BYTE);
+                }
+                bitSelectorMask = (byte) (bitSelectorMask << 1);
+            }
+            buffer[n] = reversedByte;
+        }
+    }
+
+    /**
+     * Sets the LCI subelement fields to the default undefined values.
+     */
+    private void setLciSubelementDefaults() {
+        mIsLciValid = false;
+        mLatitudeUncertainty = UNCERTAINTY_UNDEFINED;
+        mLatitude = 0;
+        mLongitudeUncertainty = UNCERTAINTY_UNDEFINED;
+        mLongitude = 0;
+        mAltitudeType = ALTITUDE_UNDEFINED;
+        mAltitudeUncertainty = UNCERTAINTY_UNDEFINED;
+        mAltitude = 0;
+        mDatum = DATUM_UNDEFINED;
+        mLciFlags = 0;
+    }
+
+    /**
+     * Sets the Z subelement fields to the default values when undefined.
+     */
+    private void setZSubelementDefaults() {
+        mIsZValid = false;
+        mExpectedToMove = 0;
+        mStaFloorNumber = 0;
+        mStaHeightAboveFloorMeters = 0;
+        mStaHeightAboveFloorUncertaintyMeters = 0;
+    }
+
+    /**
+     * Sets the Usage Policy subelement fields to the default undefined values.
+     */
+    private void setUsageSubelementDefaults() {
+        mUsageRetransmit = true;
+        mUsageRetentionExpires = false;
+        mUsageExtraInfoOnAssociation = false;
+    }
+
+    /**
+     * Sets the BSSID List subelement fields to the default values when undefined.
+     */
+    private void setBssidListSubelementDefaults() {
+        mIsBssidListValid = false;
+        mBssidList = new ArrayList<>();
+    }
+
+    /**
+     * Sets the LCR Civic Location subelement field to the default undefined value.
+     *
+     * @hide
+     */
+    public void setCivicLocationSubelementDefaults() {
+        mIsLocationCivicValid = false;
+        mCivicLocationCountryCode = "";
+        mCivicLocationString = "";
+        mCivicLocation = null;
+    }
+
+    /**
+     * Sets the LCR Map Image subelement field to the default values when undefined.
+     */
+    private void setMapImageSubelementDefaults() {
+        mIsMapImageValid = false;
+        mMapImageType = MAP_TYPE_URL_DEFINED;
+        mMapImageUrl = null;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null || getClass() != obj.getClass()) {
+            return false;
+        }
+        ResponderLocation other = (ResponderLocation) obj;
+        return mIsValid == other.mIsValid
+                && mIsLciValid == other.mIsLciValid
+                && mIsZValid == other.mIsZValid
+                && mIsUsageValid == other.mIsUsageValid
+                && mIsBssidListValid == other.mIsBssidListValid
+                && mIsLocationCivicValid == other.mIsLocationCivicValid
+                && mIsMapImageValid == other.mIsMapImageValid
+                && mLatitudeUncertainty == other.mLatitudeUncertainty
+                && mLatitude == other.mLatitude
+                && mLongitudeUncertainty == other.mLongitudeUncertainty
+                && mLongitude == other.mLongitude
+                && mAltitudeType == other.mAltitudeType
+                && mAltitudeUncertainty == other.mAltitudeUncertainty
+                && mAltitude == other.mAltitude
+                && mDatum == other.mDatum
+                && mLciFlags == other.mLciFlags
+                && mExpectedToMove == other.mExpectedToMove
+                && mStaFloorNumber == other.mStaFloorNumber
+                && mStaHeightAboveFloorMeters == other.mStaHeightAboveFloorMeters
+                && mStaHeightAboveFloorUncertaintyMeters
+                        == other.mStaHeightAboveFloorUncertaintyMeters
+                && mUsageRetransmit == other.mUsageRetransmit
+                && mUsageRetentionExpires == other.mUsageRetentionExpires
+                && mUsageExtraInfoOnAssociation == other.mUsageExtraInfoOnAssociation
+                && mBssidList.equals(other.mBssidList)
+                && mCivicLocationCountryCode.equals(other.mCivicLocationCountryCode)
+                && mCivicLocationString.equals(other.mCivicLocationString)
+                && Objects.equals(mCivicLocation, other.mCivicLocation)
+                && mMapImageType == other.mMapImageType
+                && Objects.equals(mMapImageUrl, other.mMapImageUrl);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(mIsValid, mIsLciValid, mIsZValid, mIsUsageValid, mIsBssidListValid,
+                mIsLocationCivicValid, mIsMapImageValid, mLatitudeUncertainty, mLatitude,
+                mLongitudeUncertainty, mLongitude, mAltitudeType, mAltitudeUncertainty, mAltitude,
+                mDatum, mLciFlags, mExpectedToMove, mStaFloorNumber, mStaHeightAboveFloorMeters,
+                mStaHeightAboveFloorUncertaintyMeters, mUsageRetransmit, mUsageRetentionExpires,
+                mUsageExtraInfoOnAssociation, mBssidList, mCivicLocationCountryCode,
+                mCivicLocationString, mCivicLocation, mMapImageType, mMapImageUrl);
+    }
+
+    /**
+     * @return true if the ResponderLocation object is valid and contains useful information
+     * relevant to the location of the Responder. If this is ever false, this object will not be
+     * available to developers, and have a null value.
+     *
+     * @hide
+     */
+    public boolean isValid() {
+        return mIsValid;
+    }
+
+    /**
+     * @return true if the LCI subelement (containing Latitude, Longitude and Altitude) is valid.
+     *
+     * <p> This method tells us if the responder has provided its Location Configuration
+     * Information (LCI) directly, and is useful when an external database of responder locations
+     * is not available</p>
+     *
+     * <p>If isLciSubelementValid() returns true, all the LCI values provided by the corresponding
+     * getter methods will have been set as described by the responder, or else if false, they
+     * should not be used and will throw an IllegalStateException.</p>
+     */
+    public boolean isLciSubelementValid() {
+        return mIsLciValid;
+    }
+
+    /**
+     * @return the latitude uncertainty in degrees.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     *
+     * <p> An unknown uncertainty is indicated by 0.</p>
+     */
+    public double getLatitudeUncertainty() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mLatitudeUncertainty;
+    }
+
+    /**
+     * @return the latitude in degrees
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     */
+    public double getLatitude() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLatitude(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mLatitude;
+    }
+
+    /**
+     * @return the Longitude uncertainty in degrees.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     *
+     * <p> An unknown uncertainty is indicated by 0.</p>
+     */
+    public double getLongitudeUncertainty() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLongitudeUncertainty(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mLongitudeUncertainty;
+    }
+
+    /**
+     * @return the Longitude in degrees..
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     */
+    public double getLongitude() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mLongitude;
+    }
+
+    /**
+     * @return the Altitude type.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     */
+    @AltitudeType
+    public int getAltitudeType() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mAltitudeType;
+    }
+
+    /**
+     * @return the Altitude uncertainty in meters.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     *
+     * <p>An unknown uncertainty is indicated by 0.</p>
+     */
+    public double getAltitudeUncertainty() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mAltitudeUncertainty;
+    }
+
+    /**
+     * @return the Altitude in units defined by the altitude type.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     */
+    public double getAltitude() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getAltitude(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mAltitude;
+    }
+
+    /**
+     * @return the Datum used for the LCI positioning information.
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     */
+    @DatumType
+    public int getDatum() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getDatum(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mDatum;
+    }
+
+    /**
+     * @return the LCI sub-element flags (5-bits).
+     *
+     * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
+     *
+     * <p>Note: The flags/version can be extracted by bitwise ANDing this value with the
+     * corresponding LCI_FLAGS_MASK_* .</p>
+     */
+    public int getLciFlags() {
+        if (!mIsLciValid) {
+            throw new IllegalStateException(
+                "getLciFlags(): invoked on an invalid result: mIsLciValid = false)");
+        }
+        return mLciFlags;
+    }
+
+    /**
+     * @return if the Z subelement (containing mobility, Floor, Height above floor) is valid.
+     */
+    public boolean isZsubelementValid() {
+        return mIsZValid;
+    }
+
+    /**
+     * @return an integer representing the mobility of the responder.
+     *
+     * Only valid if {@link #isZsubelementValid()} returns true, or will throw an exception.
+     */
+    @ExpectedToMoveType
+    public int getExpectedToMove() {
+        if (!mIsZValid) {
+            throw new IllegalStateException(
+                "getExpectedToMove(): invoked on an invalid result: mIsZValid = false)");
+        }
+        return mExpectedToMove;
+    }
+
+    /**
+     * @return the Z sub element STA Floor Number.
+     *
+     * Only valid if {@link #isZsubelementValid()} returns true, or will throw an exception.
+     *
+     * <p>Note: this number can be positive or negative, with value increments of +/- 1/16 of a
+     * floor.</p>.
+     */
+    public double getStaFloorNumber() {
+        if (!mIsZValid) {
+            throw new IllegalStateException(
+                "getStaFloorNumber(): invoked on an invalid result: mIsZValid = false)");
+        }
+        return mStaFloorNumber;
+    }
+
+    /**
+     * @return the Z subelement STA Height above the floor in meters.
+     *
+     * Only valid if {@link #isZsubelementValid()} returns true, or will throw an exception.
+     *
+     * <p>This value can be positive or negative. </p>
+     */
+    public double getStaHeightAboveFloorMeters() {
+        if (!mIsZValid) {
+            throw new IllegalStateException(
+                "getStaHeightAboveFloorMeters(): invoked on an invalid result: mIsZValid = false)");
+        }
+        return mStaHeightAboveFloorMeters;
+    }
+
+    /**
+     * @return the Z subelement STA Height above the floor uncertainty in meters.
+     *
+     * Only valid if {@link #isZsubelementValid()} returns true, or will throw an exception.
+     *
+     * <p>An unknown uncertainty is indicated by 0.</p>
+     */
+    public double getStaHeightAboveFloorUncertaintyMeters() {
+        if (!mIsZValid) {
+            throw new IllegalStateException(
+                "getStaHeightAboveFloorUncertaintyMeters():"
+                    + "invoked on an invalid result: mIsZValid = false)");
+        }
+        return mStaHeightAboveFloorUncertaintyMeters;
+    }
+
+    /**
+     * @return true if the location information received from the responder can be
+     * retransmitted to another device, physically separate from the one that received it.
+     *
+     * @hide
+     */
+    public boolean getRetransmitPolicyIndication() {
+        return mUsageRetransmit;
+    }
+
+    /**
+     * @return true if location-data received should expire (and be deleted)
+     * by the time provided in the getRelativeExpirationTimeHours() method.
+     *
+     *
+     * @hide
+     */
+    public boolean getRetentionExpiresIndication() {
+        return mUsageRetentionExpires;
+    }
+
+    /**
+     * @return true if there is extra location info available on association.
+     *
+     * @hide
+     */
+    @SystemApi
+    public boolean getExtraInfoOnAssociationIndication() {
+        return mUsageExtraInfoOnAssociation;
+    }
+
+    /**
+     * @return the list of colocated BSSIDs at the responder.
+     *
+     * <p> Will return an empty list when there are no bssids listed.
+     */
+    public List<MacAddress> getColocatedBssids() {
+        return mBssidList;
+    }
+
+    /**
+     * @return the civic location represented as an {@link Address} object (best effort).
+     *
+     * <p> Will return a {@code null} when there is no Civic Location define defined.
+     *
+     * @hide
+     */
+    @Nullable
+    public Address toCivicLocationAddress() {
+        if (mCivicLocation != null && mCivicLocation.isValid()) {
+            return mCivicLocation.toAddress();
+        } else {
+            return null;
+        }
+    }
+
+
+    /**
+     * @return the civic location two upper-case ASCII character country code defined in ISO 3166.
+     *
+     * <p> Will return a {@code null} when there is no country code defined.
+     *
+     * @hide
+     */
+    @Nullable
+    public String getCivicLocationCountryCode() {
+        return mCivicLocationCountryCode;
+    }
+
+    /**
+     * @return the value of the Civic Location String associated with a key.
+     *
+     * <p> Will return a {@code null} when there is no value associated with the key provided.
+     *
+     * @param key used to find a corresponding value in the Civic Location Tuple list
+     *
+     * @hide
+     */
+    @Nullable
+    public String getCivicLocationElementValue(@CivicLocationKeysType int key) {
+        return mCivicLocation.getCivicElementValue(key);
+    }
+
+    /**
+     * @return the Map Image file type, referred to by getMapImageUrl(), encoded as an integer.
+     */
+    @MapImageType
+    public int getMapImageType() {
+        return mMapImageType;
+    }
+
+    /**
+     * @return a Url referencing a map-file showing the local floor plan.
+     *
+     * <p> Will return a {@code null} when there is no URL defined.
+     */
+    @Nullable
+    public URL getMapImageUrl() {
+        return mMapImageUrl;
+    }
+}
diff --git a/wifi/tests/src/android/net/wifi/rtt/CivicLocationTest.java b/wifi/tests/src/android/net/wifi/rtt/CivicLocationTest.java
new file mode 100644
index 0000000..f746fb7
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/rtt/CivicLocationTest.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.rtt;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertNull;
+import static junit.framework.Assert.assertTrue;
+
+import android.location.Address;
+import android.os.Parcel;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Tests for {@link CivicLocation}.
+ */
+@RunWith(JUnit4.class)
+public class CivicLocationTest {
+    private static final String sUsCountryCode = "US";
+
+    private static final byte[] sEmptyBuffer = {};
+
+    private static final byte[] sTestCivicLocationBuffer = {
+            (byte) 17,
+            (byte) 3,
+            (byte) 'a',
+            (byte) 'b',
+            (byte) 'c',
+            (byte) 4,
+            (byte) 4,
+            (byte) 'd',
+            (byte) 'e',
+            (byte) 'f',
+            (byte) 'g',
+            (byte) 12,
+            (byte) 1,
+            (byte) 'h'
+    };
+
+    private static final byte[] sTestCivicLocationBufferWithAddress = {
+            (byte) CivicLocationKeys.HNO,
+            (byte) 2,
+            (byte) '1',
+            (byte) '5',
+            (byte) CivicLocationKeys.PRIMARY_ROAD_NAME,
+            (byte) 4,
+            (byte) 'A',
+            (byte) 'l',
+            (byte) 't',
+            (byte) 'o',
+            (byte) CivicLocationKeys.STREET_NAME_POST_MODIFIER,
+            (byte) 4,
+            (byte) 'R',
+            (byte) 'o',
+            (byte) 'a',
+            (byte) 'd',
+            (byte) CivicLocationKeys.CITY,
+            (byte) 8,
+            (byte) 'M',
+            (byte) 't',
+            (byte) 'n',
+            (byte) ' ',
+            (byte) 'V',
+            (byte) 'i',
+            (byte) 'e',
+            (byte) 'w',
+            (byte) CivicLocationKeys.STATE,
+            (byte) 2,
+            (byte) 'C',
+            (byte) 'A',
+            (byte) CivicLocationKeys.POSTAL_CODE,
+            (byte) 5,
+            (byte) '9',
+            (byte) '4',
+            (byte) '0',
+            (byte) '4',
+            (byte) '3'
+    };
+
+    /**
+     * Test inValid for null CountryCode.
+     */
+    @Test
+    public void testCivicLocationNullCountryCode() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, null);
+
+        boolean valid = civicLocation.isValid();
+
+        assertFalse(valid);
+    }
+
+    /**
+     * Test inValid for CountryCode too short.
+     */
+    @Test
+    public void testCivicLocationCountryCodeTooShort() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, "X");
+
+        boolean valid = civicLocation.isValid();
+
+        assertFalse(valid);
+    }
+
+    /**
+     * Test inValid for CountryCode too long.
+     */
+    @Test
+    public void testCivicLocationCountryCodeTooLong() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, "XYZ");
+
+        boolean valid = civicLocation.isValid();
+
+        assertFalse(valid);
+    }
+
+    /**
+     * Test inValid for null CivicLocation Buffer
+     */
+    @Test
+    public void testCivicLocationNullBuffer() {
+        CivicLocation civicLocation = new CivicLocation(null, sUsCountryCode);
+
+        boolean valid = civicLocation.isValid();
+
+        assertFalse(valid);
+    }
+
+    /**
+     * Test inValid for Empty CivicLocation Buffer.
+     */
+    @Test
+    public void testCivicLocationEmptyBuffer() {
+        CivicLocation civicLocation = new CivicLocation(sEmptyBuffer, sUsCountryCode);
+
+        boolean valid = civicLocation.isValid();
+
+        assertFalse(valid);
+    }
+
+    /**
+     * Test for valid CivicLocationBuffer and Country Code.
+     */
+    @Test
+    public void testCivicLocationValid() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, sUsCountryCode);
+
+        boolean valid = civicLocation.isValid();
+
+        assertTrue(valid);
+    }
+
+    /**
+     * Test toString Representation
+     */
+    @Test
+    public void testCivicLocationToString() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, sUsCountryCode);
+
+        String str = civicLocation.toString();
+
+        assertEquals("{4=defg, 12=h, 17=abc}", str);
+    }
+
+    /**
+     * Test the toString
+     */
+    @Test
+    public void testCivicLocationgetElementValue() {
+        CivicLocation civicLocation = new CivicLocation(sTestCivicLocationBuffer, sUsCountryCode);
+
+        String value1 = civicLocation.getCivicElementValue(4);
+        String value2 = civicLocation.getCivicElementValue(17);
+        String value3 = civicLocation.getCivicElementValue(12);
+        String value4 = civicLocation.getCivicElementValue(156); // not in test data
+        String value5 = civicLocation.getCivicElementValue(276); // greater than key index
+
+        assertEquals("defg", value1);
+        assertEquals("abc", value2);
+        assertEquals("h", value3);
+        assertNull(value4);
+        assertNull(value5);
+    }
+
+    /* Test toAddress representation */
+    @Test
+    public void testCivicLocationToAddress() {
+        CivicLocation civicLocation =
+                new CivicLocation(sTestCivicLocationBufferWithAddress, sUsCountryCode);
+
+        Address address = civicLocation.toAddress();
+
+        assertEquals("", address.getAddressLine(0));
+        assertEquals("15 Alto", address.getAddressLine(1));
+        assertEquals("Mtn View", address.getAddressLine(2));
+        assertEquals("CA 94043", address.getAddressLine(3));
+        assertEquals("US", address.getAddressLine(4));
+    }
+
+    /**
+     * Test toString Representation
+     */
+    @Test
+    public void testCivicLocationToString2() {
+        CivicLocation civicLocation =
+                new CivicLocation(sTestCivicLocationBufferWithAddress, sUsCountryCode);
+
+        String str = civicLocation.toString();
+
+        assertEquals("{1=CA, 3=Mtn View, 19=15, 24=94043, 34=Alto, 39=Road}", str);
+    }
+
+    /** Test object is Parcellable */
+    @Test
+    public void testCivicLocationParcelable() {
+        CivicLocation civicLocation =
+                new CivicLocation(sTestCivicLocationBufferWithAddress, sUsCountryCode);
+
+        Parcel parcel = Parcel.obtain();
+        civicLocation.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        CivicLocation civicLocationFromParcel =
+                CivicLocation.CREATOR.createFromParcel(parcel);
+
+        assertEquals(civicLocationFromParcel, civicLocation);
+    }
+}
diff --git a/wifi/tests/src/android/net/wifi/rtt/ResponderLocationTest.java b/wifi/tests/src/android/net/wifi/rtt/ResponderLocationTest.java
new file mode 100644
index 0000000..9efb642
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/rtt/ResponderLocationTest.java
@@ -0,0 +1,551 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.rtt;
+
+import android.location.Address;
+import android.net.MacAddress;
+import android.os.Parcel;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.List;
+
+/**
+ * Tests for {@link ResponderLocation}.
+ */
+@RunWith(JUnit4.class)
+public class ResponderLocationTest {
+    private static final double LATLNG_TOLERANCE_DEGREES = 0.001;
+    private static final double ALT_TOLERANCE_METERS = 0.01;
+    private static final double HEIGHT_TOLERANCE_METERS = 0.01;
+    private static final int INDEX_ELEMENT_TYPE = 2;
+    private static final int INDEX_SUBELEMENT_TYPE = 0;
+    private static final int INDEX_SUBELEMENT_LENGTH = 1;
+
+    /* Test Buffers */
+
+    private static final byte[] sTestLciIeHeader = {
+            (byte) 0x01, (byte) 0x00, (byte) 0x08 // LCI Information Element (IE)
+    };
+
+    private static final byte[] sTestLciShortBuffer = {
+        (byte) 0x00
+    };
+
+    private static final byte[] sTestLciSE = {
+            (byte) 0x00, // Subelement LCI
+            (byte) 16,   // Subelement LCI length always = 16
+            (byte) 0x52,
+            (byte) 0x83,
+            (byte) 0x4d,
+            (byte) 0x12,
+            (byte) 0xef,
+            (byte) 0xd2,
+            (byte) 0xb0,
+            (byte) 0x8b,
+            (byte) 0x9b,
+            (byte) 0x4b,
+            (byte) 0xf1,
+            (byte) 0xcc,
+            (byte) 0x2c,
+            (byte) 0x00,
+            (byte) 0x00,
+            (byte) 0x41
+    };
+
+    private static final byte[] sTestZHeightSE = {
+            (byte) 0x04, // Subelement Z
+            (byte) 6, // Length always 6
+            (byte) 0x00, // LSB STA Floor Info (2 bytes)
+            (byte) 0x01, // MSB
+            (byte) 0xcd, // LSB Height(m) (3 bytes)
+            (byte) 0x2c,
+            (byte) 0x00, // MSB Height(m)
+            (byte) 0x0e, // STA Height Uncertainty
+    };
+
+    private static final byte[] sTestUsageSE1 = {
+            (byte) 0x06, // Subelement Usage Rights
+            (byte) 1, // Length 1 (with no retention limit)
+            (byte) 0x01, // Retransmit ok, No expiration, no extra info available
+    };
+
+    private static final byte[] sTestUsageSE2 = {
+            (byte) 0x06, // Subelement Usage Rights
+            (byte) 3,    // Length 3 (including retention limit)
+            (byte) 0x06, // Retransmit not ok, Expiration, extra info available
+            (byte) 0x00, // LSB expiration time  (0x8000 = 32768 hrs)
+            (byte) 0x80  // MSB expiration time
+    };
+
+    private static final byte[] sTestBssidListSE = {
+            (byte) 0x07, // Subelement BSSID list
+            (byte) 13, // length dependent on number of BSSIDs in list
+            (byte) 0x02, // Number of BSSIDs in list
+            (byte) 0x01, // BSSID #1 (MSB)
+            (byte) 0x02,
+            (byte) 0x03,
+            (byte) 0x04,
+            (byte) 0x05,
+            (byte) 0x06, // (LSB)
+            (byte) 0xf1, // BSSID #2 (MSB)
+            (byte) 0xf2,
+            (byte) 0xf3,
+            (byte) 0xf4,
+            (byte) 0xf5,
+            (byte) 0xf6 // (LSB)
+    };
+
+    private static final byte[] sTestLcrBufferHeader = {
+            (byte) 0x01, (byte) 0x00, (byte) 0x0b,
+    };
+
+    private static final byte[] sEmptyBuffer = {};
+
+    private static final byte[] sTestCivicLocationSEWithAddress = {
+            (byte) 0, // Civic Location Subelement
+            (byte) 39, // Length of subelement value
+            (byte) 'U', // CountryCodeChar1
+            (byte) 'S', // CountryCodeChar2
+            (byte) CivicLocationKeys.HNO,
+            (byte) 2,
+            (byte) '1',
+            (byte) '5',
+            (byte) CivicLocationKeys.PRIMARY_ROAD_NAME,
+            (byte) 4,
+            (byte) 'A',
+            (byte) 'l',
+            (byte) 't',
+            (byte) 'o',
+            (byte) CivicLocationKeys.STREET_NAME_POST_MODIFIER,
+            (byte) 4,
+            (byte) 'R',
+            (byte) 'o',
+            (byte) 'a',
+            (byte) 'd',
+            (byte) CivicLocationKeys.CITY,
+            (byte) 8,
+            (byte) 'M',
+            (byte) 't',
+            (byte) 'n',
+            (byte) ' ',
+            (byte) 'V',
+            (byte) 'i',
+            (byte) 'e',
+            (byte) 'w',
+            (byte) CivicLocationKeys.STATE,
+            (byte) 2,
+            (byte) 'C',
+            (byte) 'A',
+            (byte) CivicLocationKeys.POSTAL_CODE,
+            (byte) 5,
+            (byte) '9',
+            (byte) '4',
+            (byte) '0',
+            (byte) '4',
+            (byte) '3'
+    };
+
+    // Buffer representing: "https://map.com/mall.jpg"
+    private static final byte[] sTestMapUrlSE = {
+            (byte) 5, // Map URL Subelement
+            (byte) 25,
+            (byte) ResponderLocation.MAP_TYPE_URL_DEFINED,
+            (byte) 'h',
+            (byte) 't',
+            (byte) 't',
+            (byte) 'p',
+            (byte) 's',
+            (byte) ':',
+            (byte) '/',
+            (byte) '/',
+            (byte) 'm',
+            (byte) 'a',
+            (byte) 'p',
+            (byte) '.',
+            (byte) 'c',
+            (byte) 'o',
+            (byte) 'm',
+            (byte) '/',
+            (byte) 'm',
+            (byte) 'a',
+            (byte) 'l',
+            (byte) 'l',
+            (byte) '.',
+            (byte) 'j',
+            (byte) 'p',
+            (byte) 'g'
+    };
+
+    /**
+     * Test if the lci and lcr buffers are null.
+     */
+    @Test
+    public void testIfLciOrLcrIsNull() {
+        ResponderLocation responderLocation = new ResponderLocation(null, null);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test if the lci and lcr buffers are empty.
+     */
+    @Test
+    public void testIfLciOrLcrIsEmpty() {
+        ResponderLocation responderLocation = new ResponderLocation(sEmptyBuffer, sEmptyBuffer);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test if the lci subelement only has one byte
+     */
+    @Test
+    public void testIfLciShortBuffer() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciShortBuffer);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test that the example buffer contains a valid LCI Subelement.
+     */
+    @Test
+    public void testLciValidSubelement() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertTrue(valid);
+        assertTrue(lciValid);
+        assertFalse(zValid);
+        assertEquals(0.0009765625, responderLocation.getLatitudeUncertainty());
+        assertEquals(-33.857009, responderLocation.getLatitude(),
+                LATLNG_TOLERANCE_DEGREES);
+        assertEquals(0.0009765625, responderLocation.getLongitudeUncertainty());
+        assertEquals(151.215200, responderLocation.getLongitude(),
+                LATLNG_TOLERANCE_DEGREES);
+        assertEquals(1, responderLocation.getAltitudeType());
+        assertEquals(64.0, responderLocation.getAltitudeUncertainty());
+        assertEquals(11.2, responderLocation.getAltitude(), ALT_TOLERANCE_METERS);
+        assertEquals(1, responderLocation.getDatum()); // WGS84
+        int lciFlags = responderLocation.getLciFlags();
+        assertEquals(0, lciFlags & ResponderLocation.LCI_FLAGS_MASK_REGLOC_AGREEMENT);
+        assertEquals(0, lciFlags & ResponderLocation.LCI_FLAGS_MASK_REGLOC_DSE);
+        assertEquals(0, lciFlags & ResponderLocation.LCI_FLAGS_MASK_DEPENDENT_STA);
+        assertEquals(1, lciFlags & ResponderLocation.LCI_FLAGS_MASK_VERSION);
+    }
+
+    /**
+     * Test for an invalid LCI element.
+     */
+    @Test
+    public void testLciInvalidElement() {
+        byte[] testBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        testBuffer[INDEX_ELEMENT_TYPE] = (byte) 0xFF;
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test for an invalid subelement type.
+     */
+    @Test
+    public void testSkipLciSubElementUnusedOrUnknown() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        // Corrupt the subelement type to an unknown type.
+        testLciBuffer[sTestLciIeHeader.length + INDEX_SUBELEMENT_TYPE] = (byte) 0x77;
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test for a subelement LCI length too small.
+     */
+    @Test
+    public void testInvalidLciSubElementLengthTooSmall() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        // Corrupt the length making it too small.
+        testLciBuffer[sTestLciIeHeader.length + INDEX_SUBELEMENT_LENGTH] = (byte) 0x01;
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test for a subelement LCI length too big.
+     */
+    @Test
+    public void testInvalidLciSubElementLengthTooBig() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        // Corrupt the length making it too big.
+        testLciBuffer[sTestLciIeHeader.length + INDEX_SUBELEMENT_TYPE] = (byte) 0x11;
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean lciValid = responderLocation.isLciSubelementValid();
+        boolean zValid = responderLocation.isZsubelementValid();
+
+        assertFalse(valid);
+        assertFalse(lciValid);
+        assertFalse(zValid);
+    }
+
+    /**
+     * Test for a valid Z (Height) subelement following an LCI subelement.
+     */
+    @Test
+    public void testLciValidZBufferSEAfterLci() {
+        byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testBuffer = concatenateArrays(testBufferTmp, sTestZHeightSE);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean isValid = responderLocation.isValid();
+        boolean isZValid = responderLocation.isZsubelementValid();
+        boolean isLciValid = responderLocation.isLciSubelementValid();
+        double staFloorNumber = responderLocation.getStaFloorNumber();
+        double staHeightAboveFloorMeters = responderLocation.getStaHeightAboveFloorMeters();
+        double staHeightAboveFloorUncertaintyMeters =
+                responderLocation.getStaHeightAboveFloorUncertaintyMeters();
+
+        assertTrue(isValid);
+        assertTrue(isZValid);
+        assertTrue(isLciValid);
+        assertEquals(4.0, staFloorNumber);
+        assertEquals(2.8, staHeightAboveFloorMeters, HEIGHT_TOLERANCE_METERS);
+        assertEquals(0.125, staHeightAboveFloorUncertaintyMeters);
+    }
+
+    /**
+     * Test for a valid Usage Policy that is unrestrictive
+     */
+    @Test
+    public void testLciOpenUsagePolicy() {
+        byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testBuffer = concatenateArrays(testBufferTmp, sTestUsageSE1);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean retransmit = responderLocation.getRetransmitPolicyIndication();
+        boolean expiration = responderLocation.getRetentionExpiresIndication();
+        boolean extraInfo = responderLocation.getExtraInfoOnAssociationIndication();
+
+        assertTrue(valid);
+        assertTrue(retransmit);
+        assertFalse(expiration);
+        assertFalse(extraInfo);
+    }
+
+    /**
+     * Test for a valid Usage Policy that is restrictive
+     */
+    @Test
+    public void testLciRestrictiveUsagePolicy() {
+        byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testBuffer = concatenateArrays(testBufferTmp, sTestUsageSE2);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        boolean retransmit = responderLocation.getRetransmitPolicyIndication();
+        boolean expiration = responderLocation.getRetentionExpiresIndication();
+        boolean extraInfo = responderLocation.getExtraInfoOnAssociationIndication();
+
+        assertFalse(valid);
+        assertFalse(retransmit);
+        assertTrue(expiration);
+        assertTrue(extraInfo);
+    }
+
+    /**
+     * Test for a valid BSSID element following an LCI subelement.
+     */
+    @Test
+    public void testLciBssidListSEAfterLci() {
+        byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testBuffer = concatenateArrays(testBufferTmp, sTestBssidListSE);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        List<MacAddress> bssidList = responderLocation.getColocatedBssids();
+
+        assertTrue(valid);
+        assertEquals(2, bssidList.size());
+        MacAddress macAddress1 = bssidList.get(0);
+        assertEquals("01:02:03:04:05:06", macAddress1.toString());
+        MacAddress macAddress2 = bssidList.get(1);
+        assertEquals("f1:f2:f3:f4:f5:f6", macAddress2.toString());
+    }
+
+    /**
+     * Test for a valid BSSID element before and LCI element
+     */
+    @Test
+    public void testLciBssidListSEBeforeLci() {
+        byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestBssidListSE);
+        byte[] testBuffer = concatenateArrays(testBufferTmp, sTestLciSE);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+        boolean valid = responderLocation.isValid();
+        List<MacAddress> bssidList = responderLocation.getColocatedBssids();
+
+        assertTrue(valid);
+        assertEquals(2, bssidList.size());
+        MacAddress macAddress1 = bssidList.get(0);
+        assertEquals("01:02:03:04:05:06", macAddress1.toString());
+        MacAddress macAddress2 = bssidList.get(1);
+        assertEquals("f1:f2:f3:f4:f5:f6", macAddress2.toString());
+    }
+
+    /**
+     * Test that a valid address can be extracted from a valid lcr buffer with Civic Location.
+     */
+    @Test
+    public void testLcrTestCivicLocationAddress() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testLcrBuffer =
+                concatenateArrays(sTestLcrBufferHeader, sTestCivicLocationSEWithAddress);
+        ResponderLocation responderLocation = new ResponderLocation(testLciBuffer, testLcrBuffer);
+
+        boolean valid = responderLocation.isValid();
+        String countryCode = responderLocation.getCivicLocationCountryCode();
+        Address address = responderLocation.toCivicLocationAddress();
+
+        assertTrue(valid);
+        assertEquals("US", countryCode);
+        assertEquals("", address.getAddressLine(0));
+        assertEquals("15 Alto", address.getAddressLine(1));
+        assertEquals("Mtn View", address.getAddressLine(2));
+        assertEquals("CA 94043", address.getAddressLine(3));
+        assertEquals("US", address.getAddressLine(4));
+    }
+
+    /**
+     * Test that a URL can be extracted from a valid lcr buffer with a map image subelement.
+     */
+    @Test
+    public void testLcrCheckMapUrlIsValid() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        byte[] testLcrBuffer = concatenateArrays(sTestLcrBufferHeader, sTestMapUrlSE);
+        ResponderLocation responderLocation = new ResponderLocation(testLciBuffer, testLcrBuffer);
+
+        boolean valid = responderLocation.isValid();
+        int mapImageType = responderLocation.getMapImageType();
+        String urlString = "";
+        if (responderLocation.getMapImageUrl() != null) {
+            urlString = responderLocation.getMapImageUrl().toString();
+        }
+
+        assertTrue(valid);
+        assertEquals(ResponderLocation.MAP_TYPE_URL_DEFINED, mapImageType);
+        assertEquals("https://map.com/mall.jpg", urlString);
+    }
+
+    /**
+     * Test the object is parcelable
+     */
+    @Test
+    public void testResponderLocationParcelable() {
+        byte[] testLciBuffer = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+        ResponderLocation responderLocation =
+                new ResponderLocation(testLciBuffer, sTestLcrBufferHeader);
+
+        Parcel parcel = Parcel.obtain();
+        responderLocation.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        ResponderLocation responderLocationFromParcel =
+                ResponderLocation.CREATOR.createFromParcel(parcel);
+
+        assertEquals(responderLocationFromParcel, responderLocation);
+    }
+
+    /* Helper Method */
+
+    /**
+     * Concatenate two arrays.
+     *
+     * @param a first array
+     * @param b second array
+     * @return a third array which is the concatenation of the two array params
+     */
+    private byte[] concatenateArrays(byte[] a, byte[] b) {
+        int aLen = a.length;
+        int bLen = b.length;
+        byte[] c = new byte[aLen + bLen];
+        System.arraycopy(a, 0, c, 0, aLen);
+        System.arraycopy(b, 0, c, aLen, bLen);
+        return c;
+    }
+}
diff --git a/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java b/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
index afc7dff..53bd837 100644
--- a/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
@@ -81,7 +81,7 @@
         List<RangingResult> results = new ArrayList<>();
         results.add(
                 new RangingResult(RangingResult.STATUS_SUCCESS, MacAddress.BROADCAST_ADDRESS, 15, 5,
-                        10, 8, 5, null, null, 666));
+                        10, 8, 5, null, null, null, 666));
         RangingResultCallback callbackMock = mock(RangingResultCallback.class);
         ArgumentCaptor<IRttCallback> callbackCaptor = ArgumentCaptor.forClass(IRttCallback.class);
 
@@ -243,7 +243,7 @@
 
         // RangingResults constructed with a MAC address
         RangingResult result = new RangingResult(status, mac, distanceCm, distanceStdDevCm, rssi,
-                numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, timestamp);
+                numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, null, timestamp);
 
         Parcel parcelW = Parcel.obtain();
         result.writeToParcel(parcelW, 0);
@@ -259,7 +259,7 @@
 
         // RangingResults constructed with a PeerHandle
         result = new RangingResult(status, peerHandle, distanceCm, distanceStdDevCm, rssi,
-                numAttemptedMeasurements, numSuccessfulMeasurements, null, null, timestamp);
+                numAttemptedMeasurements, numSuccessfulMeasurements, null, null, null, timestamp);
 
         parcelW = Parcel.obtain();
         result.writeToParcel(parcelW, 0);
@@ -292,9 +292,9 @@
         byte[] lcr = { };
 
         RangingResult rr1 = new RangingResult(status, mac, distanceCm, distanceStdDevCm, rssi,
-                numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, timestamp);
+                numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr, null, timestamp);
         RangingResult rr2 = new RangingResult(status, mac, distanceCm, distanceStdDevCm, rssi,
-                numAttemptedMeasurements, numSuccessfulMeasurements, null, null, timestamp);
+                numAttemptedMeasurements, numSuccessfulMeasurements, null, null, null, timestamp);
 
         assertEquals(rr1, rr2);
     }