Merge "Create configuration resources for the Double Tap Power Button Gesture" into main
diff --git a/core/api/current.txt b/core/api/current.txt
index 59dc314..5b9f1ef 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -23,6 +23,7 @@
field public static final String ACTIVITY_RECOGNITION = "android.permission.ACTIVITY_RECOGNITION";
field public static final String ADD_VOICEMAIL = "com.android.voicemail.permission.ADD_VOICEMAIL";
field public static final String ANSWER_PHONE_CALLS = "android.permission.ANSWER_PHONE_CALLS";
+ field @FlaggedApi("android.media.tv.flags.apply_picture_profiles") public static final String APPLY_PICTURE_PROFILE = "android.permission.APPLY_PICTURE_PROFILE";
field public static final String BATTERY_STATS = "android.permission.BATTERY_STATS";
field public static final String BIND_ACCESSIBILITY_SERVICE = "android.permission.BIND_ACCESSIBILITY_SERVICE";
field public static final String BIND_APPWIDGET = "android.permission.BIND_APPWIDGET";
@@ -336,7 +337,7 @@
field public static final String WRITE_SECURE_SETTINGS = "android.permission.WRITE_SECURE_SETTINGS";
field public static final String WRITE_SETTINGS = "android.permission.WRITE_SETTINGS";
field public static final String WRITE_SYNC_SETTINGS = "android.permission.WRITE_SYNC_SETTINGS";
- field @FlaggedApi("com.android.settingslib.flags.settings_catalyst") public static final String WRITE_SYSTEM_PREFERENCES = "android.permission.WRITE_SYSTEM_PREFERENCES";
+ field @FlaggedApi("com.android.settingslib.flags.write_system_preference_permission_enabled") public static final String WRITE_SYSTEM_PREFERENCES = "android.permission.WRITE_SYSTEM_PREFERENCES";
field public static final String WRITE_VOICEMAIL = "com.android.voicemail.permission.WRITE_VOICEMAIL";
}
@@ -17497,6 +17498,25 @@
method public void setIntUniform(@NonNull String, @NonNull int[]);
}
+ @FlaggedApi("com.android.graphics.hwui.flags.runtime_color_filters_blenders") public class RuntimeXfermode extends android.graphics.Xfermode {
+ ctor public RuntimeXfermode(@NonNull String);
+ method public void setColorUniform(@NonNull String, @ColorInt int);
+ method public void setColorUniform(@NonNull String, @ColorLong long);
+ method public void setColorUniform(@NonNull String, @NonNull android.graphics.Color);
+ method public void setFloatUniform(@NonNull String, float);
+ method public void setFloatUniform(@NonNull String, float, float);
+ method public void setFloatUniform(@NonNull String, float, float, float);
+ method public void setFloatUniform(@NonNull String, float, float, float, float);
+ method public void setFloatUniform(@NonNull String, @NonNull float[]);
+ method public void setInputColorFilter(@NonNull String, @NonNull android.graphics.ColorFilter);
+ method public void setInputShader(@NonNull String, @NonNull android.graphics.Shader);
+ method public void setIntUniform(@NonNull String, int);
+ method public void setIntUniform(@NonNull String, int, int);
+ method public void setIntUniform(@NonNull String, int, int, int);
+ method public void setIntUniform(@NonNull String, int, int, int, int);
+ method public void setIntUniform(@NonNull String, @NonNull int[]);
+ }
+
public class Shader {
ctor @Deprecated public Shader();
method public boolean getLocalMatrix(@NonNull android.graphics.Matrix);
@@ -21050,7 +21070,6 @@
method public abstract android.inputmethodservice.AbstractInputMethodService.AbstractInputMethodImpl onCreateInputMethodInterface();
method public abstract android.inputmethodservice.AbstractInputMethodService.AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface();
method public boolean onGenericMotionEvent(android.view.MotionEvent);
- method @FlaggedApi("android.view.inputmethod.verify_key_event") public boolean onShouldVerifyKeyEvent(@NonNull android.view.KeyEvent);
method public boolean onTrackballEvent(android.view.MotionEvent);
}
@@ -21068,7 +21087,6 @@
method public void dispatchTrackballEvent(int, android.view.MotionEvent, android.view.inputmethod.InputMethodSession.EventCallback);
method public boolean isEnabled();
method public boolean isRevoked();
- method @FlaggedApi("android.view.inputmethod.verify_key_event") public boolean onShouldVerifyKeyEvent(@NonNull android.view.KeyEvent);
method public void revokeSelf();
method public void setEnabled(boolean);
}
@@ -29876,6 +29894,7 @@
method @NonNull public java.util.List<android.net.vcn.VcnUnderlyingNetworkTemplate> getVcnUnderlyingNetworkPriorities();
method public boolean hasGatewayOption(int);
method @FlaggedApi("android.net.vcn.safe_mode_config") public boolean isSafeModeEnabled();
+ field @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public static final int MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET = -1; // 0xffffffff
field public static final int VCN_GATEWAY_OPTION_ENABLE_DATA_STALL_RECOVERY_WITH_MOBILITY = 0; // 0x0
}
@@ -40737,6 +40756,7 @@
method public int describeContents();
method @Deprecated @Nullable public android.os.Bundle getClientState();
method @Nullable public java.util.List<android.service.autofill.FillEventHistory.Event> getEvents();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public int getSessionId();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillEventHistory> CREATOR;
}
@@ -40746,10 +40766,12 @@
method @Nullable public android.os.Bundle getClientState();
method @Nullable public String getDatasetId();
method @NonNull public java.util.Map<android.view.autofill.AutofillId,android.service.autofill.FieldClassification> getFieldsClassification();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") @Nullable public android.view.autofill.AutofillId getFocusedId();
method @NonNull public java.util.Set<java.lang.String> getIgnoredDatasetIds();
method @NonNull public java.util.Map<android.view.autofill.AutofillId,java.util.Set<java.lang.String>> getManuallyEnteredField();
method public int getNoSaveUiReason();
method @NonNull public java.util.Set<java.lang.String> getSelectedDatasetIds();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") @NonNull public java.util.Set<java.lang.String> getShownDatasetIds();
method public int getType();
method public int getUiType();
field public static final int NO_SAVE_UI_REASON_DATASET_MATCH = 6; // 0x6
@@ -40758,6 +40780,7 @@
field public static final int NO_SAVE_UI_REASON_NONE = 0; // 0x0
field public static final int NO_SAVE_UI_REASON_NO_SAVE_INFO = 1; // 0x1
field public static final int NO_SAVE_UI_REASON_NO_VALUE_CHANGED = 4; // 0x4
+ field @FlaggedApi("android.service.autofill.autofill_w_metrics") public static final int NO_SAVE_UI_REASON_USING_CREDMAN = 7; // 0x7
field public static final int NO_SAVE_UI_REASON_WITH_DELAY_SAVE_FLAG = 2; // 0x2
field public static final int TYPE_AUTHENTICATION_SELECTED = 2; // 0x2
field public static final int TYPE_CONTEXT_COMMITTED = 4; // 0x4
@@ -40766,6 +40789,7 @@
field public static final int TYPE_DATASET_SELECTED = 0; // 0x0
field public static final int TYPE_SAVE_SHOWN = 3; // 0x3
field public static final int TYPE_VIEW_REQUESTED_AUTOFILL = 6; // 0x6
+ field @FlaggedApi("android.service.autofill.autofill_w_metrics") public static final int UI_TYPE_CREDMAN = 4; // 0x4
field public static final int UI_TYPE_DIALOG = 3; // 0x3
field public static final int UI_TYPE_INLINE = 2; // 0x2
field public static final int UI_TYPE_MENU = 1; // 0x1
@@ -42051,6 +42075,7 @@
public abstract class QuickAccessWalletService extends android.app.Service {
ctor public QuickAccessWalletService();
+ method @FlaggedApi("android.service.quickaccesswallet.launch_wallet_option_on_power_double_tap") @Nullable public android.app.PendingIntent getGestureTargetActivityPendingIntent();
method @Nullable public android.app.PendingIntent getTargetActivityPendingIntent();
method @Nullable public android.os.IBinder onBind(@NonNull android.content.Intent);
method public abstract void onWalletCardSelected(@NonNull android.service.quickaccesswallet.SelectWalletCardRequest);
@@ -49736,6 +49761,14 @@
method public abstract void updateMeasureState(@NonNull android.text.TextPaint);
}
+ @FlaggedApi("android.view.inputmethod.writing_tools") public final class NoWritingToolsSpan implements android.text.ParcelableSpan {
+ ctor public NoWritingToolsSpan();
+ method public int describeContents();
+ method public int getSpanTypeId();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.text.style.NoWritingToolsSpan> CREATOR;
+ }
+
public interface ParagraphStyle {
}
@@ -54907,6 +54940,8 @@
method public abstract void setTransformation(android.graphics.Matrix);
method public abstract void setVisibility(int);
method public abstract void setWebDomain(@Nullable String);
+ field @FlaggedApi("android.service.autofill.autofill_w_metrics") public static final String EXTRA_VIRTUAL_STRUCTURE_TYPE = "android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_TYPE";
+ field @FlaggedApi("android.service.autofill.autofill_w_metrics") public static final String EXTRA_VIRTUAL_STRUCTURE_VERSION_NUMBER = "android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER";
}
public abstract static class ViewStructure.HtmlInfo {
@@ -56629,6 +56664,11 @@
public final class AutofillId implements android.os.Parcelable {
method @NonNull public static android.view.autofill.AutofillId create(@NonNull android.view.View, int);
method public int describeContents();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public int getAutofillVirtualId();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public int getSessionId();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public int getViewId();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public boolean isInAutofillSession();
+ method @FlaggedApi("android.service.autofill.autofill_w_metrics") public boolean isVirtual();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.view.autofill.AutofillId> CREATOR;
}
diff --git a/core/api/lint-baseline.txt b/core/api/lint-baseline.txt
index 4ada53e..ad5bd31 100644
--- a/core/api/lint-baseline.txt
+++ b/core/api/lint-baseline.txt
@@ -1,4 +1,10 @@
// Baseline format: 1.0
+ActionValue: android.view.ViewStructure#EXTRA_VIRTUAL_STRUCTURE_TYPE:
+ Inconsistent extra value; expected `android.view.extra.VIRTUAL_STRUCTURE_TYPE`, was `android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_TYPE`
+ActionValue: android.view.ViewStructure#EXTRA_VIRTUAL_STRUCTURE_VERSION_NUMBER:
+ Inconsistent extra value; expected `android.view.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER`, was `android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER`
+
+
BroadcastBehavior: android.app.AlarmManager#ACTION_NEXT_ALARM_CLOCK_CHANGED:
Field 'ACTION_NEXT_ALARM_CLOCK_CHANGED' is missing @BroadcastBehavior
BroadcastBehavior: android.app.AlarmManager#ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED:
@@ -1185,6 +1191,10 @@
New API must be flagged with @FlaggedApi: field android.R.dimen.system_corner_radius_xlarge
UnflaggedApi: android.R.dimen#system_corner_radius_xsmall:
New API must be flagged with @FlaggedApi: field android.R.dimen.system_corner_radius_xsmall
+UnflaggedApi: android.R.integer#status_bar_notification_info_maxnum:
+ Changes from not deprecated to deprecated must be flagged with @FlaggedApi: field android.R.integer.status_bar_notification_info_maxnum
+UnflaggedApi: android.R.string#status_bar_notification_info_overflow:
+ Changes from not deprecated to deprecated must be flagged with @FlaggedApi: field android.R.string.status_bar_notification_info_overflow
UnflaggedApi: android.accessibilityservice.AccessibilityService#OVERLAY_RESULT_INTERNAL_ERROR:
New API must be flagged with @FlaggedApi: field android.accessibilityservice.AccessibilityService.OVERLAY_RESULT_INTERNAL_ERROR
UnflaggedApi: android.accessibilityservice.AccessibilityService#OVERLAY_RESULT_INVALID:
@@ -1477,7 +1487,6 @@
New API must be flagged with @FlaggedApi: method android.graphics.text.PositionedGlyphs.getItalicOverride(int)
UnflaggedApi: android.graphics.text.PositionedGlyphs#getWeightOverride(int):
New API must be flagged with @FlaggedApi: method android.graphics.text.PositionedGlyphs.getWeightOverride(int)
-
UnflaggedApi: android.media.MediaRoute2Info#TYPE_REMOTE_CAR:
New API must be flagged with @FlaggedApi: field android.media.MediaRoute2Info.TYPE_REMOTE_CAR
UnflaggedApi: android.media.MediaRoute2Info#TYPE_REMOTE_COMPUTER:
diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt
index dcb4a40..1a949d84 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -251,6 +251,10 @@
package android.net {
+ @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public final class ConnectivityFrameworkInitializerBaklava {
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public static void registerServiceWrappers();
+ }
+
public class LocalSocket implements java.io.Closeable {
ctor public LocalSocket(@NonNull java.io.FileDescriptor);
}
@@ -310,6 +314,25 @@
}
+package android.net.vcn {
+
+ @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public final class VcnTransportInfo implements android.os.Parcelable android.net.TransportInfo {
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public int describeContents();
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public long getApplicableRedactions();
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public int getMinUdpPort4500NatTimeoutSeconds();
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") @NonNull public android.net.TransportInfo makeCopy(long);
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @FlaggedApi("android.net.vcn.mainline_vcn_module_api") @NonNull public static final android.os.Parcelable.Creator<android.net.vcn.VcnTransportInfo> CREATOR;
+ }
+
+ @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public static final class VcnTransportInfo.Builder {
+ ctor @FlaggedApi("android.net.vcn.mainline_vcn_module_api") public VcnTransportInfo.Builder();
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") @NonNull public android.net.vcn.VcnTransportInfo build();
+ method @FlaggedApi("android.net.vcn.mainline_vcn_module_api") @NonNull public android.net.vcn.VcnTransportInfo.Builder setMinUdpPort4500NatTimeoutSeconds(@IntRange(from=0x78) int);
+ }
+
+}
+
package android.net.wifi {
public final class WifiMigration {
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index fee53d6..0ea00f5 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -65,6 +65,7 @@
field @FlaggedApi("android.crashrecovery.flags.enable_crashrecovery") public static final String BIND_EXPLICIT_HEALTH_CHECK_SERVICE = "android.permission.BIND_EXPLICIT_HEALTH_CHECK_SERVICE";
field public static final String BIND_EXTERNAL_STORAGE_SERVICE = "android.permission.BIND_EXTERNAL_STORAGE_SERVICE";
field public static final String BIND_FIELD_CLASSIFICATION_SERVICE = "android.permission.BIND_FIELD_CLASSIFICATION_SERVICE";
+ field @FlaggedApi("android.security.afl_api") public static final String BIND_FORENSIC_EVENT_TRANSPORT_SERVICE = "android.permission.BIND_FORENSIC_EVENT_TRANSPORT_SERVICE";
field public static final String BIND_GBA_SERVICE = "android.permission.BIND_GBA_SERVICE";
field public static final String BIND_HOTWORD_DETECTION_SERVICE = "android.permission.BIND_HOTWORD_DETECTION_SERVICE";
field public static final String BIND_IMS_SERVICE = "android.permission.BIND_IMS_SERVICE";
@@ -209,6 +210,7 @@
field @FlaggedApi("android.permission.flags.enhanced_confirmation_mode_apis_enabled") public static final String MANAGE_ENHANCED_CONFIRMATION_STATES = "android.permission.MANAGE_ENHANCED_CONFIRMATION_STATES";
field public static final String MANAGE_ETHERNET_NETWORKS = "android.permission.MANAGE_ETHERNET_NETWORKS";
field public static final String MANAGE_FACTORY_RESET_PROTECTION = "android.permission.MANAGE_FACTORY_RESET_PROTECTION";
+ field @FlaggedApi("android.security.afl_api") public static final String MANAGE_FORENSIC_STATE = "android.permission.MANAGE_FORENSIC_STATE";
field public static final String MANAGE_GAME_ACTIVITY = "android.permission.MANAGE_GAME_ACTIVITY";
field public static final String MANAGE_GAME_MODE = "android.permission.MANAGE_GAME_MODE";
field @FlaggedApi("android.media.tv.flags.media_quality_fw") public static final String MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE = "android.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE";
@@ -304,6 +306,7 @@
field public static final String READ_CONTENT_RATING_SYSTEMS = "android.permission.READ_CONTENT_RATING_SYSTEMS";
field public static final String READ_DEVICE_CONFIG = "android.permission.READ_DEVICE_CONFIG";
field public static final String READ_DREAM_STATE = "android.permission.READ_DREAM_STATE";
+ field @FlaggedApi("android.security.afl_api") public static final String READ_FORENSIC_STATE = "android.permission.READ_FORENSIC_STATE";
field public static final String READ_GLOBAL_APP_SEARCH_DATA = "android.permission.READ_GLOBAL_APP_SEARCH_DATA";
field @FlaggedApi("android.content.pm.get_resolved_apk_path") public static final String READ_INSTALLED_SESSION_PATHS = "android.permission.READ_INSTALLED_SESSION_PATHS";
field public static final String READ_INSTALL_SESSIONS = "android.permission.READ_INSTALL_SESSIONS";
@@ -1336,8 +1339,10 @@
public class DevicePolicyManager {
method @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public int checkProvisioningPrecondition(@NonNull String, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING) public void clearAuditLogEventCallback();
- method @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public android.os.UserHandle createAndProvisionManagedProfile(@NonNull android.app.admin.ManagedProfileProvisioningParams) throws android.app.admin.ProvisioningException;
+ method @Deprecated @FlaggedApi("android.app.admin.flags.split_create_managed_profile_enabled") @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public android.os.UserHandle createAndProvisionManagedProfile(@NonNull android.app.admin.ManagedProfileProvisioningParams) throws android.app.admin.ProvisioningException;
+ method @FlaggedApi("android.app.admin.flags.split_create_managed_profile_enabled") @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public android.os.UserHandle createManagedProfile(@NonNull android.app.admin.ManagedProfileProvisioningParams) throws android.app.admin.ProvisioningException;
method @Nullable public android.content.Intent createProvisioningIntentFromNfcIntent(@NonNull android.content.Intent);
+ method @FlaggedApi("android.app.admin.flags.split_create_managed_profile_enabled") @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public void finalizeCreateManagedProfile(@NonNull android.app.admin.ManagedProfileProvisioningParams, @NonNull android.os.UserHandle) throws android.app.admin.ProvisioningException;
method @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) public void finalizeWorkProfileProvisioning(@NonNull android.os.UserHandle, @Nullable android.accounts.Account);
method @NonNull @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS) public java.util.Set<java.lang.Integer> getApplicationExemptions(@NonNull String) throws android.content.pm.PackageManager.NameNotFoundException;
method @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public boolean getBluetoothContactSharingDisabled(@NonNull android.os.UserHandle);
@@ -5045,15 +5050,27 @@
package android.hardware.camera2 {
+ public final class CameraCharacteristics extends android.hardware.camera2.CameraMetadata<android.hardware.camera2.CameraCharacteristics.Key<?>> {
+ field @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.SharedSessionConfiguration> SHARED_SESSION_CONFIGURATION;
+ }
+
public abstract class CameraDevice implements java.lang.AutoCloseable {
method @Deprecated public abstract void createCustomCaptureSession(android.hardware.camera2.params.InputConfiguration, @NonNull java.util.List<android.hardware.camera2.params.OutputConfiguration>, int, @NonNull android.hardware.camera2.CameraCaptureSession.StateCallback, @Nullable android.os.Handler) throws android.hardware.camera2.CameraAccessException;
field public static final int SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED = 1; // 0x1
field public static final int SESSION_OPERATION_MODE_NORMAL = 0; // 0x0
+ field @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public static final int SESSION_OPERATION_MODE_SHARED = 2; // 0x2
field public static final int SESSION_OPERATION_MODE_VENDOR_START = 32768; // 0x8000
}
+ public abstract static class CameraDevice.StateCallback {
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public void onClientSharedAccessPriorityChanged(@NonNull android.hardware.camera2.CameraDevice, boolean);
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public void onOpenedInSharedMode(@NonNull android.hardware.camera2.CameraDevice, boolean);
+ }
+
public final class CameraManager {
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public boolean isCameraDeviceSharingSupported(@NonNull String) throws android.hardware.camera2.CameraAccessException;
method @RequiresPermission(allOf={android.Manifest.permission.SYSTEM_CAMERA, android.Manifest.permission.CAMERA}) public void openCamera(@NonNull String, int, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.camera2.CameraDevice.StateCallback) throws android.hardware.camera2.CameraAccessException;
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") @RequiresPermission(allOf={android.Manifest.permission.SYSTEM_CAMERA, android.Manifest.permission.CAMERA}) public void openSharedCamera(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.camera2.CameraDevice.StateCallback) throws android.hardware.camera2.CameraAccessException;
}
public abstract static class CameraManager.AvailabilityCallback {
@@ -5061,6 +5078,12 @@
method @RequiresPermission(android.Manifest.permission.CAMERA_OPEN_CLOSE_LISTENER) public void onCameraOpened(@NonNull String, @NonNull String);
}
+ @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public abstract class CameraSharedCaptureSession extends android.hardware.camera2.CameraCaptureSession {
+ ctor public CameraSharedCaptureSession();
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public abstract int startStreaming(@NonNull java.util.List<android.view.Surface>, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.camera2.CameraCaptureSession.CaptureCallback) throws android.hardware.camera2.CameraAccessException;
+ method @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public abstract void stopStreaming() throws android.hardware.camera2.CameraAccessException;
+ }
+
}
package android.hardware.camera2.extension {
@@ -5169,6 +5192,83 @@
field public static final int ROTATION_90 = 1; // 0x1
}
+ public final class SessionConfiguration implements android.os.Parcelable {
+ field @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public static final int SESSION_SHARED = 2; // 0x2
+ }
+
+ @FlaggedApi("com.android.internal.camera.flags.camera_multi_client") public final class SharedSessionConfiguration {
+ method @Nullable public android.graphics.ColorSpace getColorSpace();
+ method @NonNull public java.util.List<android.hardware.camera2.params.SharedSessionConfiguration.SharedOutputConfiguration> getOutputStreamsInformation();
+ }
+
+ public static final class SharedSessionConfiguration.SharedOutputConfiguration {
+ method public int getDataspace();
+ method public int getFormat();
+ method public int getMirrorMode();
+ method @Nullable public String getPhysicalCameraId();
+ method @NonNull public android.util.Size getSize();
+ method public long getStreamUseCase();
+ method public int getSurfaceType();
+ method public int getTimestampBase();
+ method public long getUsage();
+ method public boolean isReadoutTimestampEnabled();
+ }
+
+}
+
+package android.hardware.contexthub {
+
+ @FlaggedApi("android.chre.flags.offload_api") public class HubDiscoveryInfo {
+ method @NonNull public android.hardware.contexthub.HubEndpointInfo getHubEndpointInfo();
+ }
+
+ @FlaggedApi("android.chre.flags.offload_api") public class HubEndpoint {
+ method @Nullable public android.hardware.contexthub.IHubEndpointLifecycleCallback getLifecycleCallback();
+ method @Nullable public String getTag();
+ }
+
+ public static final class HubEndpoint.Builder {
+ ctor public HubEndpoint.Builder(@NonNull android.content.Context);
+ method @NonNull public android.hardware.contexthub.HubEndpoint build();
+ method @NonNull public android.hardware.contexthub.HubEndpoint.Builder setLifecycleCallback(@NonNull android.hardware.contexthub.IHubEndpointLifecycleCallback);
+ method @NonNull public android.hardware.contexthub.HubEndpoint.Builder setLifecycleCallback(@NonNull java.util.concurrent.Executor, @NonNull android.hardware.contexthub.IHubEndpointLifecycleCallback);
+ method @NonNull public android.hardware.contexthub.HubEndpoint.Builder setTag(@NonNull String);
+ }
+
+ @FlaggedApi("android.chre.flags.offload_api") public final class HubEndpointInfo implements android.os.Parcelable {
+ method public int describeContents();
+ method @NonNull public android.hardware.contexthub.HubEndpointInfo.HubEndpointIdentifier getIdentifier();
+ method @NonNull public String getName();
+ method @Nullable public String getTag();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.hardware.contexthub.HubEndpointInfo> CREATOR;
+ }
+
+ public static class HubEndpointInfo.HubEndpointIdentifier {
+ method public long getEndpoint();
+ method public long getHub();
+ }
+
+ @FlaggedApi("android.chre.flags.offload_api") public class HubEndpointSession implements java.lang.AutoCloseable {
+ method public void close();
+ }
+
+ @FlaggedApi("android.chre.flags.offload_api") public class HubEndpointSessionResult {
+ method @NonNull public static android.hardware.contexthub.HubEndpointSessionResult accept();
+ method @Nullable public String getReason();
+ method public boolean isAccepted();
+ method @NonNull public static android.hardware.contexthub.HubEndpointSessionResult reject(@NonNull String);
+ }
+
+ @FlaggedApi("android.chre.flags.offload_api") public interface IHubEndpointLifecycleCallback {
+ method public void onSessionClosed(@NonNull android.hardware.contexthub.HubEndpointSession, int);
+ method @NonNull public android.hardware.contexthub.HubEndpointSessionResult onSessionOpenRequest(@NonNull android.hardware.contexthub.HubEndpointInfo);
+ method public void onSessionOpened(@NonNull android.hardware.contexthub.HubEndpointSession);
+ field public static final int REASON_CLOSE_ENDPOINT_SESSION_REQUESTED = 4; // 0x4
+ field public static final int REASON_OPEN_ENDPOINT_SESSION_REQUEST_REJECTED = 3; // 0x3
+ field public static final int REASON_UNSPECIFIED = 0; // 0x0
+ }
+
}
package android.hardware.devicestate {
@@ -6162,6 +6262,7 @@
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubClient createClient(@NonNull android.hardware.location.ContextHubInfo, @NonNull android.app.PendingIntent, long);
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubTransaction<java.lang.Void> disableNanoApp(@NonNull android.hardware.location.ContextHubInfo, long);
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubTransaction<java.lang.Void> enableNanoApp(@NonNull android.hardware.location.ContextHubInfo, long);
+ method @FlaggedApi("android.chre.flags.offload_api") @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public java.util.List<android.hardware.contexthub.HubDiscoveryInfo> findEndpoints(long);
method @Deprecated @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public int[] findNanoAppOnHub(int, @NonNull android.hardware.location.NanoAppFilter);
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public int[] getContextHubHandles();
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubInfo getContextHubInfo(int);
@@ -6169,13 +6270,16 @@
method @Deprecated @Nullable @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.NanoAppInstanceInfo getNanoAppInstanceInfo(int);
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public int loadNanoApp(int, @NonNull android.hardware.location.NanoApp);
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubTransaction<java.lang.Void> loadNanoApp(@NonNull android.hardware.location.ContextHubInfo, @NonNull android.hardware.location.NanoAppBinary);
+ method @FlaggedApi("android.chre.flags.offload_api") @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public void openSession(@NonNull android.hardware.contexthub.HubEndpoint, @NonNull android.hardware.contexthub.HubEndpointInfo);
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubTransaction<java.util.List<android.hardware.location.NanoAppState>> queryNanoApps(@NonNull android.hardware.location.ContextHubInfo);
method @Deprecated public int registerCallback(@NonNull android.hardware.location.ContextHubManager.Callback);
method @Deprecated public int registerCallback(android.hardware.location.ContextHubManager.Callback, android.os.Handler);
+ method @FlaggedApi("android.chre.flags.offload_api") @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public void registerEndpoint(@NonNull android.hardware.contexthub.HubEndpoint);
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public int sendMessage(int, int, @NonNull android.hardware.location.ContextHubMessage);
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public int unloadNanoApp(int);
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public android.hardware.location.ContextHubTransaction<java.lang.Void> unloadNanoApp(@NonNull android.hardware.location.ContextHubInfo, long);
method @Deprecated public int unregisterCallback(@NonNull android.hardware.location.ContextHubManager.Callback);
+ method @FlaggedApi("android.chre.flags.offload_api") @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB) public void unregisterEndpoint(@NonNull android.hardware.contexthub.HubEndpoint);
field public static final int AUTHORIZATION_DENIED = 0; // 0x0
field public static final int AUTHORIZATION_DENIED_GRACE_PERIOD = 1; // 0x1
field public static final int AUTHORIZATION_GRANTED = 2; // 0x2
@@ -12571,6 +12675,29 @@
}
+package android.security.forensic {
+
+ @FlaggedApi("android.security.afl_api") public class ForensicManager {
+ method @RequiresPermission(android.Manifest.permission.READ_FORENSIC_STATE) public void addStateCallback(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
+ method @RequiresPermission(android.Manifest.permission.MANAGE_FORENSIC_STATE) public void disable(@NonNull java.util.concurrent.Executor, @NonNull android.security.forensic.ForensicManager.CommandCallback);
+ method @RequiresPermission(android.Manifest.permission.MANAGE_FORENSIC_STATE) public void enable(@NonNull java.util.concurrent.Executor, @NonNull android.security.forensic.ForensicManager.CommandCallback);
+ method @RequiresPermission(android.Manifest.permission.READ_FORENSIC_STATE) public void removeStateCallback(@NonNull java.util.function.Consumer<java.lang.Integer>);
+ field public static final int ERROR_DATA_SOURCE_UNAVAILABLE = 4; // 0x4
+ field public static final int ERROR_PERMISSION_DENIED = 1; // 0x1
+ field public static final int ERROR_TRANSPORT_UNAVAILABLE = 3; // 0x3
+ field public static final int ERROR_UNKNOWN = 0; // 0x0
+ field public static final int STATE_DISABLED = 1; // 0x1
+ field public static final int STATE_ENABLED = 2; // 0x2
+ field public static final int STATE_UNKNOWN = 0; // 0x0
+ }
+
+ public static interface ForensicManager.CommandCallback {
+ method public void onFailure(int);
+ method public void onSuccess();
+ }
+
+}
+
package android.security.keystore {
public class AndroidKeyStoreProvider extends java.security.Provider {
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 1192713..136c636 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -3240,6 +3240,7 @@
method @Nullable public android.content.Intent createWalletIntent();
method @Nullable public android.content.Intent createWalletSettingsIntent();
method public void disconnect();
+ method @FlaggedApi("android.service.quickaccesswallet.launch_wallet_option_on_power_double_tap") public void getGestureTargetActivityPendingIntent(@NonNull java.util.concurrent.Executor, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.GesturePendingIntentCallback);
method public void getWalletCards(@NonNull android.service.quickaccesswallet.GetWalletCardsRequest, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.OnWalletCardsRetrievedCallback);
method public void getWalletCards(@NonNull java.util.concurrent.Executor, @NonNull android.service.quickaccesswallet.GetWalletCardsRequest, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.OnWalletCardsRetrievedCallback);
method public void getWalletPendingIntent(@NonNull java.util.concurrent.Executor, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.WalletPendingIntentCallback);
@@ -3251,6 +3252,10 @@
method public void selectWalletCard(@NonNull android.service.quickaccesswallet.SelectWalletCardRequest);
}
+ @FlaggedApi("android.service.quickaccesswallet.launch_wallet_option_on_power_double_tap") public static interface QuickAccessWalletClient.GesturePendingIntentCallback {
+ method @FlaggedApi("android.service.quickaccesswallet.launch_wallet_option_on_power_double_tap") public void onGesturePendingIntentRetrieved(@Nullable android.app.PendingIntent);
+ }
+
public static interface QuickAccessWalletClient.OnWalletCardsRetrievedCallback {
method public void onWalletCardRetrievalError(@NonNull android.service.quickaccesswallet.GetWalletCardsError);
method public void onWalletCardsRetrieved(@NonNull android.service.quickaccesswallet.GetWalletCardsResponse);
diff --git a/core/api/test-lint-baseline.txt b/core/api/test-lint-baseline.txt
index 08bb082..c2fac70 100644
--- a/core/api/test-lint-baseline.txt
+++ b/core/api/test-lint-baseline.txt
@@ -1,4 +1,10 @@
// Baseline format: 1.0
+ActionValue: android.view.contentcapture.ViewNode.ViewStructureImpl#EXTRA_VIRTUAL_STRUCTURE_TYPE:
+ Inconsistent extra value; expected `android.view.contentcapture.extra.VIRTUAL_STRUCTURE_TYPE`, was `android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_TYPE`
+ActionValue: android.view.contentcapture.ViewNode.ViewStructureImpl#EXTRA_VIRTUAL_STRUCTURE_VERSION_NUMBER:
+ Inconsistent extra value; expected `android.view.contentcapture.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER`, was `android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER`
+
+
BannedThrow: android.os.vibrator.persistence.VibrationXmlSerializer#serialize(android.os.VibrationEffect, java.io.Writer):
Methods must not throw unchecked exceptions
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 8b37dbd..ce0ec60 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -1624,9 +1624,19 @@
/** @hide Access to read oxygen saturation. */
public static final int OP_READ_OXYGEN_SATURATION = AppOpEnums.APP_OP_READ_OXYGEN_SATURATION;
+ /** @hide Access to write system preferences. */
+ public static final int OP_WRITE_SYSTEM_PREFERENCES =
+ AppOpEnums.APP_OP_WRITE_SYSTEM_PREFERENCES;
+
+ /** @hide Access to audio playback and control APIs. */
+ public static final int OP_CONTROL_AUDIO = AppOpEnums.APP_OP_CONTROL_AUDIO;
+
+ /** @hide Similar to {@link OP_CONTROL_AUDIO}, but doesn't require capabilities. */
+ public static final int OP_CONTROL_AUDIO_PARTIAL = AppOpEnums.APP_OP_CONTROL_AUDIO_PARTIAL;
+
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int _NUM_OP = 153;
+ public static final int _NUM_OP = 156;
/**
* All app ops represented as strings.
@@ -1783,6 +1793,9 @@
OPSTR_READ_SKIN_TEMPERATURE,
OPSTR_RANGING,
OPSTR_READ_OXYGEN_SATURATION,
+ OPSTR_WRITE_SYSTEM_PREFERENCES,
+ OPSTR_CONTROL_AUDIO,
+ OPSTR_CONTROL_AUDIO_PARTIAL,
})
public @interface AppOpString {}
@@ -2540,6 +2553,15 @@
@FlaggedApi(Flags.FLAG_RANGING_PERMISSION_ENABLED)
public static final String OPSTR_RANGING = "android:ranging";
+ /** @hide Access to system preferences write services */
+ public static final String OPSTR_WRITE_SYSTEM_PREFERENCES = "android:write_system_preferences";
+
+ /** @hide Access to audio playback and control APIs */
+ public static final String OPSTR_CONTROL_AUDIO = "android:control_audio";
+
+ /** @hide Access to a audio playback and control APIs without capability requirements */
+ public static final String OPSTR_CONTROL_AUDIO_PARTIAL = "android:control_audio_partial";
+
/** {@link #sAppOpsToNote} not initialized yet for this op */
private static final byte SHOULD_COLLECT_NOTE_OP_NOT_INITIALIZED = 0;
/** Should not collect noting of this app-op in {@link #sAppOpsToNote} */
@@ -2656,6 +2678,7 @@
OP_RECEIVE_SANDBOX_TRIGGER_AUDIO,
OP_MEDIA_ROUTING_CONTROL,
OP_READ_SYSTEM_GRAMMATICAL_GENDER,
+ OP_WRITE_SYSTEM_PREFERENCES,
};
@SuppressWarnings("FlaggedApi")
@@ -3144,6 +3167,14 @@
Flags.replaceBodySensorPermissionEnabled()
? HealthPermissions.READ_OXYGEN_SATURATION : null)
.setDefaultMode(AppOpsManager.MODE_ALLOWED).build(),
+ new AppOpInfo.Builder(OP_WRITE_SYSTEM_PREFERENCES, OPSTR_WRITE_SYSTEM_PREFERENCES,
+ "WRITE_SYSTEM_PREFERENCES").setPermission(
+ com.android.settingslib.flags.Flags.writeSystemPreferencePermissionEnabled()
+ ? Manifest.permission.WRITE_SYSTEM_PREFERENCES : null).build(),
+ new AppOpInfo.Builder(OP_CONTROL_AUDIO, OPSTR_CONTROL_AUDIO,
+ "CONTROL_AUDIO").setDefaultMode(AppOpsManager.MODE_FOREGROUND).build(),
+ new AppOpInfo.Builder(OP_CONTROL_AUDIO_PARTIAL, OPSTR_CONTROL_AUDIO_PARTIAL,
+ "CONTROL_AUDIO_PARTIAL").setDefaultMode(AppOpsManager.MODE_FOREGROUND).build(),
};
// The number of longs needed to form a full bitmask of app ops
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index e2479169..7e0a9b6 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -16,6 +16,7 @@
package android.app;
+import static android.app.PropertyInvalidatedCache.MODULE_SYSTEM;
import static android.app.PropertyInvalidatedCache.createSystemCacheKey;
import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_COLORED;
import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_NOT_COLORED;
@@ -783,43 +784,24 @@
}
/**
+ * The API and cache name for hasSystemFeature.
+ */
+ private static final String HAS_SYSTEM_FEATURE_API = "has_system_feature";
+
+ /**
* Identifies a single hasSystemFeature query.
*/
- @Immutable
- private static final class HasSystemFeatureQuery {
- public final String name;
- public final int version;
- public HasSystemFeatureQuery(String n, int v) {
- name = n;
- version = v;
- }
- @Override
- public String toString() {
- return String.format("HasSystemFeatureQuery(name=\"%s\", version=%d)",
- name, version);
- }
- @Override
- public boolean equals(@Nullable Object o) {
- if (o instanceof HasSystemFeatureQuery) {
- HasSystemFeatureQuery r = (HasSystemFeatureQuery) o;
- return Objects.equals(name, r.name) && version == r.version;
- } else {
- return false;
- }
- }
- @Override
- public int hashCode() {
- return Objects.hashCode(name) * 13 + version;
- }
- }
+ private record HasSystemFeatureQuery(String name, int version) {}
// Make this cache relatively large. There are many system features and
// none are ever invalidated. MPTS tests suggests that the cache should
// hold at least 150 entries.
private final static PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>
- mHasSystemFeatureCache =
- new PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>(
- 256, createSystemCacheKey("has_system_feature")) {
+ mHasSystemFeatureCache = new PropertyInvalidatedCache<>(
+ new PropertyInvalidatedCache.Args(MODULE_SYSTEM)
+ .api(HAS_SYSTEM_FEATURE_API).maxEntries(256).isolateUids(false),
+ HAS_SYSTEM_FEATURE_API, null) {
+
@Override
public Boolean recompute(HasSystemFeatureQuery query) {
try {
diff --git a/core/java/android/app/IActivityClientController.aidl b/core/java/android/app/IActivityClientController.aidl
index 9615015..7a329cd 100644
--- a/core/java/android/app/IActivityClientController.aidl
+++ b/core/java/android/app/IActivityClientController.aidl
@@ -112,8 +112,8 @@
oneway void requestMultiwindowFullscreen(in IBinder token, in int request,
in IRemoteCallback callback);
- oneway void startLockTaskModeByToken(in IBinder token);
- oneway void stopLockTaskModeByToken(in IBinder token);
+ void startLockTaskModeByToken(in IBinder token);
+ void stopLockTaskModeByToken(in IBinder token);
oneway void showLockTaskEscapeMessage(in IBinder token);
void setTaskDescription(in IBinder token, in ActivityManager.TaskDescription values);
diff --git a/core/java/android/app/PropertyInvalidatedCache.java b/core/java/android/app/PropertyInvalidatedCache.java
index 1dc7742..675152f 100644
--- a/core/java/android/app/PropertyInvalidatedCache.java
+++ b/core/java/android/app/PropertyInvalidatedCache.java
@@ -1947,10 +1947,12 @@
}
// Return true if this cache has had any activity. If the hits, misses, and skips are all
- // zero then the client never tried to use the cache.
- private boolean isActive() {
+ // zero then the client never tried to use the cache. If invalidations and corks are also
+ // zero then the server never tried to use the cache.
+ private boolean isActive(NonceHandler.Stats stats) {
synchronized (mLock) {
- return mHits + mMisses + getSkipsLocked() > 0;
+ return mHits + mMisses + getSkipsLocked()
+ + stats.invalidated + stats.corkedInvalidates > 0;
}
}
@@ -1968,15 +1970,15 @@
NonceHandler.Stats stats = mNonce.getStats();
synchronized (mLock) {
- if (brief && !isActive()) {
+ if (brief && !isActive(stats)) {
return;
}
pw.println(formatSimple(" Cache Name: %s", cacheName()));
pw.println(formatSimple(" Property: %s", mPropertyName));
pw.println(formatSimple(
- " Hits: %d, Misses: %d, Skips: %d, Clears: %d, Uids: %d",
- mHits, mMisses, getSkipsLocked(), mClears, mCache.size()));
+ " Hits: %d, Misses: %d, Skips: %d, Clears: %d",
+ mHits, mMisses, getSkipsLocked(), mClears));
// Print all the skip reasons.
pw.format(" Skip-%s: %d", sNonceName[0], mSkips[0]);
@@ -1986,7 +1988,7 @@
pw.println();
pw.println(formatSimple(
- " Nonce: 0x%016x, Invalidates: %d, CorkedInvalidates: %d",
+ " Nonce: 0x%016x, Invalidates: %d, Corked: %d",
mLastSeenNonce, stats.invalidated, stats.corkedInvalidates));
pw.println(formatSimple(
" Current Size: %d, Max Size: %d, HW Mark: %d, Overflows: %d",
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index ee0c38c..a063917 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -163,6 +163,7 @@
import android.media.tv.tunerresourcemanager.TunerResourceManager;
import android.nearby.NearbyFrameworkInitializer;
import android.net.ConnectivityFrameworkInitializer;
+import android.net.ConnectivityFrameworkInitializerBaklava;
import android.net.ConnectivityFrameworkInitializerTiramisu;
import android.net.INetworkPolicyManager;
import android.net.IPacProxyManager;
@@ -173,7 +174,6 @@
import android.net.PacProxyManager;
import android.net.TetheringManager;
import android.net.VpnManager;
-import android.net.vcn.VcnFrameworkInitializer;
import android.net.wifi.WifiFrameworkInitializer;
import android.net.wifi.nl80211.WifiNl80211Manager;
import android.net.wifi.sharedconnectivity.app.SharedConnectivityManager;
@@ -239,6 +239,8 @@
import android.security.advancedprotection.IAdvancedProtectionService;
import android.security.attestationverification.AttestationVerificationManager;
import android.security.attestationverification.IAttestationVerificationManagerService;
+import android.security.forensic.ForensicManager;
+import android.security.forensic.IForensicService;
import android.security.keystore.KeyStoreManager;
import android.service.oemlock.IOemLockService;
import android.service.oemlock.OemLockManager;
@@ -1793,6 +1795,18 @@
}
});
+ registerService(Context.FORENSIC_SERVICE, ForensicManager.class,
+ new CachedServiceFetcher<ForensicManager>() {
+ @Override
+ public ForensicManager createService(ContextImpl ctx)
+ throws ServiceNotFoundException {
+ IBinder b = ServiceManager.getServiceOrThrow(
+ Context.FORENSIC_SERVICE);
+ IForensicService service = IForensicService.Stub.asInterface(b);
+ return new ForensicManager(service);
+ }
+ });
+
sInitializing = true;
try {
// Note: the following functions need to be @SystemApis, once they become mainline
@@ -1821,7 +1835,7 @@
OnDevicePersonalizationFrameworkInitializer.registerServiceWrappers();
DeviceLockFrameworkInitializer.registerServiceWrappers();
VirtualizationFrameworkInitializer.registerServiceWrappers();
- VcnFrameworkInitializer.registerServiceWrappers();
+ ConnectivityFrameworkInitializerBaklava.registerServiceWrappers();
if (com.android.server.telecom.flags.Flags.telecomMainlineBlockedNumbersManager()) {
ProviderFrameworkInitializer.registerServiceWrappers();
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 4e68b5a..e766ae2 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -16,6 +16,7 @@
package android.app.admin;
+import static android.app.admin.flags.Flags.FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED;
import static android.Manifest.permission.INTERACT_ACROSS_USERS;
import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
import static android.Manifest.permission.LOCK_DEVICE;
@@ -17196,11 +17197,14 @@
* @throws SecurityException if the caller does not hold
* {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
* @throws ProvisioningException if an error occurred during provisioning.
+ * @deprecated Use {@link #createManagedProfile} and {@link #finalizeCreateManagedProfile}
* @hide
*/
@Nullable
@SystemApi
+ @Deprecated
@RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
+ @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED)
public UserHandle createAndProvisionManagedProfile(
@NonNull ManagedProfileProvisioningParams provisioningParams)
throws ProvisioningException {
@@ -17218,6 +17222,69 @@
}
/**
+ * Creates a managed profile and sets the
+ * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
+ * owner. The method {@link #finalizeCreateManagedProfile} must be called after to finalize the
+ * creation of the managed profile.
+ *
+ * <p>The method {@link #checkProvisioningPrecondition} must return {@link #STATUS_OK}
+ * before calling this method. If it doesn't, a ProvisioningException will be thrown.
+ *
+ * @param provisioningParams Params required to provision a managed profile,
+ * see {@link ManagedProfileProvisioningParams}.
+ * @return The {@link UserHandle} of the created profile or {@code null} if the service is
+ * not available.
+ * @throws ProvisioningException if an error occurred during provisioning.
+ * @hide
+ */
+ @Nullable
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
+ @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED)
+ public UserHandle createManagedProfile(
+ @NonNull ManagedProfileProvisioningParams provisioningParams)
+ throws ProvisioningException {
+ if (mService == null) {
+ return null;
+ }
+ try {
+ return mService.createManagedProfile(provisioningParams, mContext.getPackageName());
+ } catch (ServiceSpecificException e) {
+ throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Finalizes the creation of a managed profile by informing the necessary components that
+ * the managed profile is ready.
+ *
+ * @param provisioningParams Params required to provision a managed profile,
+ * see {@link ManagedProfileProvisioningParams}.
+ * @param managedProfileUser The recently created managed profile.
+ * @throws ProvisioningException if an error occurred during provisioning.
+ * @hide
+ */
+ @SuppressLint("UserHandle")
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
+ @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED)
+ public void finalizeCreateManagedProfile(
+ @NonNull ManagedProfileProvisioningParams provisioningParams,
+ @NonNull UserHandle managedProfileUser)
+ throws ProvisioningException {
+ if (mService == null) {
+ return;
+ }
+ try {
+ mService.finalizeCreateManagedProfile(provisioningParams, managedProfileUser);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Removes a manged profile from the device only when called from a managed profile's context
*
* @param user UserHandle of the profile to be removed
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index fa984af..d048b53 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -570,6 +570,8 @@
void setOrganizationIdForUser(in String callerPackage, in String enterpriseId, int userId);
UserHandle createAndProvisionManagedProfile(in ManagedProfileProvisioningParams provisioningParams, in String callerPackage);
+ UserHandle createManagedProfile(in ManagedProfileProvisioningParams provisioningParams, in String callerPackage);
+ void finalizeCreateManagedProfile(in ManagedProfileProvisioningParams provisioningParams, in UserHandle managedProfileUser);
void provisionFullyManagedDevice(in FullyManagedDeviceProvisioningParams provisioningParams, in String callerPackage);
void finalizeWorkProfileProvisioning(in UserHandle managedProfileUser, in Account migratedAccount);
diff --git a/core/java/android/app/admin/flags/flags.aconfig b/core/java/android/app/admin/flags/flags.aconfig
index 404471e..581efa5 100644
--- a/core/java/android/app/admin/flags/flags.aconfig
+++ b/core/java/android/app/admin/flags/flags.aconfig
@@ -343,6 +343,16 @@
}
flag {
+ name: "active_admin_cleanup"
+ namespace: "enterprise"
+ description: "Remove ActiveAdmin from EnforcingAdmin and related cleanups"
+ bug: "335663055"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "user_provisioning_same_state"
namespace: "enterprise"
description: "Handle exceptions while setting same provisioning state."
@@ -372,7 +382,7 @@
is_exported: true
namespace: "enterprise"
description: "Allows DPMS to enable or disable SupervisionService based on whether the device is being managed by the supervision role holder."
- bug: "376213673"
+ bug: "358134581"
}
flag {
diff --git a/services/supervision/java/com/android/server/supervision/SupervisionManagerInternal.java b/core/java/android/app/supervision/SupervisionManagerInternal.java
similarity index 84%
rename from services/supervision/java/com/android/server/supervision/SupervisionManagerInternal.java
rename to core/java/android/app/supervision/SupervisionManagerInternal.java
index 5df9dd5..d571e14 100644
--- a/services/supervision/java/com/android/server/supervision/SupervisionManagerInternal.java
+++ b/core/java/android/app/supervision/SupervisionManagerInternal.java
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-package com.android.server.supervision;
+package android.app.supervision;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
-import android.os.Bundle;
+import android.os.PersistableBundle;
/**
* Local system service interface for {@link SupervisionService}.
@@ -35,6 +35,11 @@
public abstract boolean isSupervisionEnabledForUser(@UserIdInt int userId);
/**
+ * Returns whether the supervision lock screen needs to be shown.
+ */
+ public abstract boolean isSupervisionLockscreenEnabledForUser(@UserIdInt int userId);
+
+ /**
* Set whether supervision is enabled for the specified user.
*
* @param userId The user to set the supervision state for
@@ -50,5 +55,5 @@
* @param options Optional configuration parameters for the supervision lock screen
*/
public abstract void setSupervisionLockscreenEnabledForUser(
- @UserIdInt int userId, boolean enabled, @Nullable Bundle options);
+ @UserIdInt int userId, boolean enabled, @Nullable PersistableBundle options);
}
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 3152ff4..13b13b9 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -292,6 +292,10 @@
* <p>
* The value of a property will only have a single type, as defined by
* the property itself.
+ *
+ * <p class="note"><strong>Note:</strong>
+ * In android version {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and earlier,
+ * the {@code equals} and {@code hashCode} methods for this class may not function as expected.
*/
public static final class Property implements Parcelable {
private static final int TYPE_BOOLEAN = 1;
@@ -523,6 +527,40 @@
return new Property[size];
}
};
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Property)) {
+ return false;
+ }
+ final Property property = (Property) obj;
+ return mType == property.mType &&
+ Objects.equals(mName, property.mName) &&
+ Objects.equals(mClassName, property.mClassName) &&
+ Objects.equals(mPackageName, property.mPackageName) &&
+ (mType == TYPE_BOOLEAN ? mBooleanValue == property.mBooleanValue :
+ mType == TYPE_FLOAT ? Float.compare(mFloatValue, property.mFloatValue) == 0 :
+ mType == TYPE_INTEGER ? mIntegerValue == property.mIntegerValue :
+ mType == TYPE_RESOURCE ? mIntegerValue == property.mIntegerValue :
+ mStringValue.equals(property.mStringValue));
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hash(mName, mType, mClassName, mPackageName);
+ if (mType == TYPE_BOOLEAN) {
+ result = 31 * result + (mBooleanValue ? 1 : 0);
+ } else if (mType == TYPE_FLOAT) {
+ result = 31 * result + Float.floatToIntBits(mFloatValue);
+ } else if (mType == TYPE_INTEGER) {
+ result = 31 * result + mIntegerValue;
+ } else if (mType == TYPE_RESOURCE) {
+ result = 31 * result + mIntegerValue;
+ } else if (mType == TYPE_STRING) {
+ result = 31 * result + mStringValue.hashCode();
+ }
+ return result;
+ }
}
/**
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 58e524e..5533a64 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -19,9 +19,9 @@
import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.camera2.impl.CameraMetadataNative;
-import android.hardware.camera2.impl.ExtensionKey;
import android.hardware.camera2.impl.PublicKey;
import android.hardware.camera2.impl.SyntheticKey;
import android.hardware.camera2.params.DeviceStateSensorOrientationMap;
@@ -6172,6 +6172,66 @@
public static final Key<android.hardware.camera2.params.StreamConfigurationDuration[]> JPEGR_AVAILABLE_JPEG_R_STALL_DURATIONS_MAXIMUM_RESOLUTION =
new Key<android.hardware.camera2.params.StreamConfigurationDuration[]>("android.jpegr.availableJpegRStallDurationsMaximumResolution", android.hardware.camera2.params.StreamConfigurationDuration[].class);
+ /**
+ * <p>Color space used for shared session configuration for all the output targets
+ * when camera is opened in shared mode. This should be one of the values specified in
+ * availableColorSpaceProfilesMap.</p>
+ * <p><b>Possible values:</b></p>
+ * <ul>
+ * <li>{@link #SHARED_SESSION_COLOR_SPACE_UNSPECIFIED UNSPECIFIED}</li>
+ * <li>{@link #SHARED_SESSION_COLOR_SPACE_SRGB SRGB}</li>
+ * <li>{@link #SHARED_SESSION_COLOR_SPACE_DISPLAY_P3 DISPLAY_P3}</li>
+ * <li>{@link #SHARED_SESSION_COLOR_SPACE_BT2020_HLG BT2020_HLG}</li>
+ * </ul>
+ *
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * @see #SHARED_SESSION_COLOR_SPACE_UNSPECIFIED
+ * @see #SHARED_SESSION_COLOR_SPACE_SRGB
+ * @see #SHARED_SESSION_COLOR_SPACE_DISPLAY_P3
+ * @see #SHARED_SESSION_COLOR_SPACE_BT2020_HLG
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final Key<Integer> SHARED_SESSION_COLOR_SPACE =
+ new Key<Integer>("android.sharedSession.colorSpace", int.class);
+
+ /**
+ * <p>List of shared output configurations that this camera device supports when
+ * camera is opened in shared mode. Array contains following entries for each supported
+ * shared configuration:
+ * 1) surface type
+ * 2) width
+ * 3) height
+ * 4) format
+ * 5) mirrorMode
+ * 6) useReadoutTimestamp
+ * 7) timestampBase
+ * 8) dataspace
+ * 9) usage
+ * 10) streamUsecase
+ * 11) physical camera id len
+ * 12) physical camera id as UTF-8 null terminated string.</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final Key<long[]> SHARED_SESSION_OUTPUT_CONFIGURATIONS =
+ new Key<long[]>("android.sharedSession.outputConfigurations", long[].class);
+
+ /**
+ * <p>The available stream configurations that this camera device supports for
+ * shared capture session when camera is opened in shared mode. Android camera framework
+ * will generate this tag if the camera device can be opened in shared mode.</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * @hide
+ */
+ @SystemApi
+ @NonNull
+ @SyntheticKey
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final Key<android.hardware.camera2.params.SharedSessionConfiguration> SHARED_SESSION_CONFIGURATION =
+ new Key<android.hardware.camera2.params.SharedSessionConfiguration>("android.sharedSession.configuration", android.hardware.camera2.params.SharedSessionConfiguration.class);
+
/**
* Mapping from INFO_SESSION_CONFIGURATION_QUERY_VERSION to session characteristics key.
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index fb381d9..852f047 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -446,6 +446,17 @@
public static final int SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED =
1; // ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;
+ /**
+ * Shared camera operation mode.
+ *
+ * @see #CameraSharedCaptureSession
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final int SESSION_OPERATION_MODE_SHARED =
+ 2; // ICameraDeviceUser.SHARED_MODE;
+
/**
* First vendor-specific operating mode
*
@@ -461,6 +472,7 @@
@IntDef(prefix = {"SESSION_OPERATION_MODE"}, value =
{SESSION_OPERATION_MODE_NORMAL,
SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED,
+ SESSION_OPERATION_MODE_SHARED,
SESSION_OPERATION_MODE_VENDOR_START})
public @interface SessionOperatingMode {};
@@ -1240,7 +1252,6 @@
*
* </ul>
*
- *
* @param config A session configuration (see {@link SessionConfiguration}).
*
* @throws IllegalArgumentException In case the session configuration is invalid; or the output
@@ -1559,6 +1570,48 @@
public abstract void onOpened(@NonNull CameraDevice camera); // Must implement
/**
+ * The method called when a camera device has finished opening in shared mode,
+ * where there can be more than one client accessing the same camera.
+ *
+ * <p>At this point, the camera device is ready to use, and
+ * {@link CameraDevice#createCaptureSession} can be called to set up the shared capture
+ * session.</p>
+ *
+ * @param camera the camera device that has become opened
+ * @param isPrimaryClient true if the client opening the camera is currently the primary
+ * client.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void onOpenedInSharedMode(@NonNull CameraDevice camera, boolean isPrimaryClient) {
+ // Default empty implementation
+ }
+
+ /**
+ * The method called when client access priorities have changed for a camera device opened
+ * in shared mode where there can be more than one client accessing the same camera.
+ *
+ * If the client priority changed from secondary to primary, then it can now
+ * create capture request and change the capture request parameters. If client priority
+ * changed from primary to secondary, that implies that a higher priority client has also
+ * opened the camera in shared mode and the new client is now a primary client
+ *
+ * @param camera the camera device whose access priorities have changed.
+ * @param isPrimaryClient true if the client is now the primary client.
+ * false if another higher priority client also opened the
+ * camera and is now the new primary client and this client is
+ * now a secondary client.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void onClientSharedAccessPriorityChanged(@NonNull CameraDevice camera,
+ boolean isPrimaryClient) {
+ // Default empty implementation
+ }
+
+ /**
* The method called when a camera device has been closed with
* {@link CameraDevice#close}.
*
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index 75e2058..266efb7 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -976,6 +976,46 @@
}
/**
+ * Checks if a camera device can be opened in a shared mode for a given {@code cameraId}.
+ * If this method returns false for a {@code cameraId}, calling {@link #openSharedCamera}
+ * for that {@code cameraId} will throw an {@link UnsupportedOperationException}.
+ *
+ * @param cameraId The unique identifier of the camera device for which sharing support is
+ * being queried. This identifier must be present in
+ * {@link #getCameraIdList()}.
+ *
+ * @return {@code true} if camera can be opened in shared mode
+ * for the provided {@code cameraId}; {@code false} otherwise.
+ *
+ * @throws IllegalArgumentException If {@code cameraId} is null, or if {@code cameraId} does not
+ * match any device in {@link #getCameraIdList()}.
+ * @throws CameraAccessException if the camera device has been disconnected.
+ *
+ * @see #getCameraIdList()
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ @SystemApi
+ public boolean isCameraDeviceSharingSupported(@NonNull String cameraId)
+ throws CameraAccessException {
+ if (cameraId == null) {
+ throw new IllegalArgumentException("Camera ID was null");
+ }
+
+ if (CameraManagerGlobal.sCameraServiceDisabled
+ || !Arrays.asList(CameraManagerGlobal.get().getCameraIdList(mContext.getDeviceId(),
+ getDevicePolicyFromContext(mContext))).contains(cameraId)) {
+ throw new IllegalArgumentException(
+ "Camera ID '" + cameraId + "' not available on device.");
+ }
+
+ CameraCharacteristics chars = getCameraCharacteristics(cameraId);
+ long[] sharedOutputConfiguration =
+ chars.get(CameraCharacteristics.SHARED_SESSION_OUTPUT_CONFIGURATIONS);
+ return (sharedOutputConfiguration != null);
+ }
+
+ /**
* Retrieves the AttributionSourceState to pass to the CameraService.
*
* @param deviceIdOverride An override of the AttributionSource's deviceId, if not equal to
@@ -1036,6 +1076,9 @@
* @param cameraId The unique identifier of the camera device to open
* @param callback The callback for the camera. Must not be null.
* @param executor The executor to invoke the callback with. Must not be null.
+ * @param oomScoreOffset The minimum oom score that cameraservice must see for this client.
+ * @param rotationOverride The type of rotation override.
+ * @param sharedMode Parameter specifying if the camera should be opened in shared mode.
*
* @throws CameraAccessException if the camera is disabled by device policy,
* too many camera devices are already open, or the cameraId does not match
@@ -1051,7 +1094,8 @@
*/
private CameraDevice openCameraDeviceUserAsync(String cameraId,
CameraDevice.StateCallback callback, Executor executor,
- final int oomScoreOffset, int rotationOverride) throws CameraAccessException {
+ final int oomScoreOffset, int rotationOverride, boolean sharedMode)
+ throws CameraAccessException {
CameraCharacteristics characteristics = getCameraCharacteristics(cameraId);
CameraDevice device = null;
synchronized (mLock) {
@@ -1070,7 +1114,7 @@
characteristics,
this,
mContext.getApplicationInfo().targetSdkVersion,
- mContext, cameraDeviceSetup);
+ mContext, cameraDeviceSetup, sharedMode);
ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks();
try {
@@ -1091,7 +1135,7 @@
mContext.getApplicationInfo().targetSdkVersion,
rotationOverride,
clientAttribution,
- getDevicePolicyFromContext(mContext));
+ getDevicePolicyFromContext(mContext), sharedMode);
} catch (ServiceSpecificException e) {
if (e.errorCode == ICameraService.ERROR_DEPRECATED_HAL) {
throw new AssertionError("Should've gone down the shim path");
@@ -1218,7 +1262,8 @@
@NonNull final CameraDevice.StateCallback callback, @Nullable Handler handler)
throws CameraAccessException {
- openCameraImpl(cameraId, callback, CameraDeviceImpl.checkAndWrapHandler(handler));
+ openCameraImpl(cameraId, callback, CameraDeviceImpl.checkAndWrapHandler(handler),
+ /*oomScoreOffset*/0, getRotationOverride(mContext), /*sharedMode*/false);
}
/**
@@ -1258,7 +1303,7 @@
/*oomScoreOffset*/0,
overrideToPortrait
? ICameraService.ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT
- : ICameraService.ROTATION_OVERRIDE_NONE);
+ : ICameraService.ROTATION_OVERRIDE_NONE, /*sharedMode*/false);
}
/**
@@ -1303,10 +1348,57 @@
if (executor == null) {
throw new IllegalArgumentException("executor was null");
}
- openCameraImpl(cameraId, callback, executor);
+ openCameraImpl(cameraId, callback, executor, /*oomScoreOffset*/0,
+ getRotationOverride(mContext), /*sharedMode*/false);
}
/**
+ * Opens a shared connection to a camera with the given ID.
+ *
+ * <p>The behavior of this method matches that of
+ * {@link #openCamera(String, Executor, StateCallback)}, except that it opens the camera in
+ * shared mode where more than one client can access the camera at the same time.</p>
+ *
+ * @param cameraId The unique identifier of the camera device to open.
+ * @param executor The executor which will be used when invoking the callback.
+ * @param callback The callback which is invoked once the camera is opened
+ *
+ * @throws CameraAccessException if the camera is disabled by device policy, or is being used
+ * by a higher-priority client in non-shared mode or the device
+ * has reached its maximal resource and cannot open this camera
+ * device.
+ *
+ * @throws IllegalArgumentException if cameraId, the callback or the executor was null,
+ * or the cameraId does not match any currently or previously
+ * available camera device.
+ *
+ * @throws SecurityException if the application does not have permission to
+ * access the camera
+ *
+ * @see #getCameraIdList
+ * @see android.app.admin.DevicePolicyManager#setCameraDisabled
+ *
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.SYSTEM_CAMERA,
+ android.Manifest.permission.CAMERA,
+ })
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void openSharedCamera(@NonNull String cameraId,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull final CameraDevice.StateCallback callback)
+ throws CameraAccessException {
+ if (executor == null) {
+ throw new IllegalArgumentException("executor was null");
+ }
+ openCameraImpl(cameraId, callback, executor, /*oomScoreOffset*/0,
+ getRotationOverride(mContext), /*sharedMode*/true);
+ }
+
+
+ /**
* Open a connection to a camera with the given ID. Also specify what oom score must be offset
* by cameraserver for this client. This api can be useful for system
* components which want to assume a lower priority (for camera arbitration) than other clients
@@ -1372,29 +1464,35 @@
"oomScoreOffset < 0, cannot increase priority of camera client");
}
openCameraImpl(cameraId, callback, executor, oomScoreOffset,
- getRotationOverride(mContext));
+ getRotationOverride(mContext), /*sharedMode*/false);
}
/**
* Open a connection to a camera with the given ID, on behalf of another application.
- * Also specify the minimum oom score and process state the application
- * should have, as seen by the cameraserver.
*
- * <p>The behavior of this method matches that of {@link #openCamera}, except that it allows
- * the caller to specify the UID to use for permission/etc verification. This can only be
- * done by services trusted by the camera subsystem to act on behalf of applications and
- * to forward the real UID.</p>
- *
+ * @param cameraId
+ * The unique identifier of the camera device to open
+ * @param callback
+ * The callback which is invoked once the camera is opened
+ * @param executor
+ * The executor which will be used when invoking the callback.
* @param oomScoreOffset
* The minimum oom score that cameraservice must see for this client.
* @param rotationOverride
* The type of rotation override (none, override_to_portrait, rotation_only)
* that should be followed for this camera id connection
+ * @param sharedMode
+ * Parameter specifying if the camera should be opened in shared mode.
+ *
+ * @throws CameraAccessException if the camera is disabled by device policy,
+ * has been disconnected, or is being used by a higher-priority camera API client in
+ * non shared mode.
+ *
* @hide
*/
public void openCameraImpl(@NonNull String cameraId,
@NonNull final CameraDevice.StateCallback callback, @NonNull Executor executor,
- int oomScoreOffset, int rotationOverride)
+ int oomScoreOffset, int rotationOverride, boolean sharedMode)
throws CameraAccessException {
if (cameraId == null) {
@@ -1407,24 +1505,7 @@
}
openCameraDeviceUserAsync(cameraId, callback, executor, oomScoreOffset,
- rotationOverride);
- }
-
- /**
- * Open a connection to a camera with the given ID, on behalf of another application.
- *
- * <p>The behavior of this method matches that of {@link #openCamera}, except that it allows
- * the caller to specify the UID to use for permission/etc verification. This can only be
- * done by services trusted by the camera subsystem to act on behalf of applications and
- * to forward the real UID.</p>
- *
- * @hide
- */
- public void openCameraImpl(@NonNull String cameraId,
- @NonNull final CameraDevice.StateCallback callback, @NonNull Executor executor)
- throws CameraAccessException {
- openCameraImpl(cameraId, callback, executor, /*oomScoreOffset*/0,
- getRotationOverride(mContext));
+ rotationOverride, sharedMode);
}
/**
@@ -2541,6 +2622,10 @@
}
@Override
public void onCameraClosed(String id, int deviceId) {
+ }
+ @Override
+ public void onCameraOpenedInSharedMode(String id, String clientPackageId,
+ int deviceId, boolean primaryClient) {
}};
String[] cameraIds;
@@ -3325,6 +3410,11 @@
}
@Override
+ public void onCameraOpenedInSharedMode(String cameraId, String clientPackageId,
+ int deviceId, boolean primaryClient) {
+ }
+
+ @Override
public void onCameraOpened(String cameraId, String clientPackageId, int deviceId) {
synchronized (mLock) {
onCameraOpenedLocked(new DeviceCameraInfo(cameraId, deviceId), clientPackageId);
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index 8d36fbd..d2fcfd6 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -2121,6 +2121,38 @@
public static final int AUTOMOTIVE_LOCATION_EXTRA_RIGHT = 10;
//
+ // Enumeration values for CameraCharacteristics#SHARED_SESSION_COLOR_SPACE
+ //
+
+ /**
+ * @see CameraCharacteristics#SHARED_SESSION_COLOR_SPACE
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final int SHARED_SESSION_COLOR_SPACE_UNSPECIFIED = -1;
+
+ /**
+ * @see CameraCharacteristics#SHARED_SESSION_COLOR_SPACE
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final int SHARED_SESSION_COLOR_SPACE_SRGB = 0;
+
+ /**
+ * @see CameraCharacteristics#SHARED_SESSION_COLOR_SPACE
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final int SHARED_SESSION_COLOR_SPACE_DISPLAY_P3 = 7;
+
+ /**
+ * @see CameraCharacteristics#SHARED_SESSION_COLOR_SPACE
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public static final int SHARED_SESSION_COLOR_SPACE_BT2020_HLG = 16;
+
+ //
// Enumeration values for CaptureRequest#COLOR_CORRECTION_MODE
//
diff --git a/core/java/android/hardware/camera2/CameraSharedCaptureSession.java b/core/java/android/hardware/camera2/CameraSharedCaptureSession.java
new file mode 100644
index 0000000..5426d4d
--- /dev/null
+++ b/core/java/android/hardware/camera2/CameraSharedCaptureSession.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2024 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.hardware.camera2;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.view.Surface;
+
+import com.android.internal.camera.flags.Flags;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * A shared capture session for a {@link CameraDevice}, when a camera device is opened in shared
+ * mode possibly by multiple clients at the same time.
+ *
+ * <p>An active shared capture session is a special type of capture session used exclusively
+ * for shared camera access by multiple applications, provided the camera device supports this
+ * mode. To determine if a camera device supports shared mode, use the
+ * {@link android.hardware.camera2.CameraManager#isCameraDeviceSharingSupported} API.
+ * If supported, multiple clients can open the camera by calling
+ * {@link android.hardware.camera2.CameraManager#openSharedCamera} and create a shared capture
+ * session by calling {@link CameraDevice#createCaptureSession(SessionConfiguration)} and using
+ * session type as {@link android.hardware.camera2.params.SessionConfiguration#SESSION_SHARED}</p>
+ *
+ * <p>When an application has opened a camera device in shared mode, it can only create a shared
+ * capture session using session type as
+ * {@link android.hardware.camera2.params.SessionConfiguration#SESSION_SHARED}. Any other session
+ * type value will trigger {@link IllegalArgumentException}. Once the configuration is complete and
+ * the session is ready to actually capture data, the provided
+ * {@link CameraCaptureSession.StateCallback}'s
+ * {@link CameraCaptureSession.StateCallback#onConfigured} callback will be called and will
+ * receive a CameraCaptureSession (castable to {@link CameraSharedCaptureSession}).</p>
+ *
+ * <p>Shared capture sessions uses a predefined configuration detailed in
+ * {@link CameraCharacteristics#SHARED_SESSION_CONFIGURATION}. Using different configuration values
+ * when creating session will result in an {@link IllegalArgumentException}.</p>
+ *
+ * <p>When camera is opened in shared mode, the highest priority client among all the clients will
+ * be the primary client while the others would be secondary clients. Clients will know if they are
+ * primary or secondary by the device state callback
+ * {@link CameraDevice.StateCallback#onOpenedInSharedMode}. Once the camera has been opened in
+ * shared mode, their access priorities of being a primary or secondary client can change if
+ * another higher priority client opens the camera later. Once the camera has been opened,
+ * any change in primary client status will be shared by the device state callback
+ * {@link CameraDevice.StateCallback#onClientSharedAccessPriorityChanged}.</p>
+ *
+ * <p>The priority of client access is determined by considering two factors: its current process
+ * state and its "out of memory" score. Clients operating in the background are assigned a lower
+ * priority. In contrast, clients running in the foreground, along with system-level clients, are
+ * given a higher priority.</p>
+ *
+ * <p>Primary clients can create capture requests, modify any capture parameters and send them to
+ * the capture session for a one-shot capture or as a repeating request using the following apis:
+ * </p>
+ *
+ * <ul>
+ *
+ * <li>{@link CameraSharedCaptureSession#capture}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#captureSingleRequest}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#setRepeatingRequest}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#setSingleRepeatingRequest}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#stopRepeating}</li>
+ *
+ * </ul>
+ *
+ * <p>Secondary clients cannot create a capture request and modify any capture parameters. However,
+ * they can start the camera streaming to desired surface targets using
+ * {@link CameraSharedCaptureSession#startStreaming}, which will apply default parameters. Once the
+ * streaming has successfully started, then they can stop the streaming using
+ * {@link CameraSharedCaptureSession#stopStreaming}.</p>
+ *
+ * <p>The following APIs are not supported in shared capture sessions by either the primary or
+ * secondary client.</p>
+ *
+ * <ul>
+ *
+ * <li>{@link CameraSharedCaptureSession#captureBurst}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#captureBurstRequests}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#setRepeatingBurst}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#setRepeatingBurstRequests}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#switchToOffline}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#updateOutputConfiguration}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#finalizeOutputConfigurations}</li>
+ *
+ * <li>{@link CameraSharedCaptureSession#prepare}</li>
+ *
+ * </ul>
+ *
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+@SystemApi
+public abstract class CameraSharedCaptureSession extends CameraCaptureSession {
+
+ /**
+ * Request start of the streaming of camera images by this shared capture session.
+ *
+ * <p>With this method, the camera device will continually capture images
+ * using the settings provided by primary client if there is ongoing repeating request
+ * by the primary client or default settings if no ongoing streaming request in progress.</p>
+ *
+ * <p> startStreaming has lower priority than the capture requests submitted
+ * through {@link #capture} by primary client, so if {@link #capture} is called when a
+ * streaming is active, the capture request will be processed before any further
+ * streaming requests are processed.</p>
+ *
+ * <p>To stop the streaming, call {@link #stopStreaming}</p>
+ *
+ * <p>Calling this method will replace any earlier streaming set up by this method.</p>
+ *
+ * @param surfaces List of target surfaces to use for streaming.
+ * @param executor The executor which will be used for invoking the listener.
+ * @param listener The callback object to notify the status and progress of the image capture.
+ *
+ * @return int A unique capture sequence ID used by
+ * {@link CaptureCallback#onCaptureSequenceCompleted}.
+ *
+ * @throws CameraAccessException if the camera device is no longer connected or has
+ * encountered a fatal error
+ * @throws IllegalStateException if this session is no longer active, either because the session
+ * was explicitly closed, a new session has been created
+ * or the camera device has been closed.
+ * @throws IllegalArgumentException If the request references no surfaces or references surfaces
+ * that are not currently configured as outputs; or
+ * the executor is null, or the listener is null.
+ * @see #stopStreaming
+ *
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ @SystemApi
+ public abstract int startStreaming(@NonNull List<Surface> surfaces,
+ @NonNull @CallbackExecutor Executor executor, @NonNull CaptureCallback listener)
+ throws CameraAccessException;
+
+ /**
+ * <p>Cancel any ongoing streaming started by {@link #startStreaming}</p>
+ *
+ * @throws CameraAccessException if the camera device is no longer connected or has
+ * encountered a fatal error
+ * @throws IllegalStateException if this session is no longer active, either because the session
+ * was explicitly closed, a new session has been created
+ * or the camera device has been closed.
+ *
+ * @see #startStreaming
+ *
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ @SystemApi
+ public abstract void stopStreaming() throws CameraAccessException;
+}
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index 8407258..ea70abb 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -18,6 +18,7 @@
import static com.android.internal.util.function.pooled.PooledLambda.obtainRunnable;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.compat.CompatChanges;
@@ -41,12 +42,15 @@
import android.hardware.camera2.ICameraDeviceUser;
import android.hardware.camera2.ICameraOfflineSession;
import android.hardware.camera2.TotalCaptureResult;
+import android.hardware.camera2.params.DynamicRangeProfiles;
import android.hardware.camera2.params.ExtensionSessionConfiguration;
import android.hardware.camera2.params.InputConfiguration;
import android.hardware.camera2.params.MultiResolutionStreamConfigurationMap;
import android.hardware.camera2.params.MultiResolutionStreamInfo;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
+import android.hardware.camera2.params.SharedSessionConfiguration;
+import android.hardware.camera2.params.SharedSessionConfiguration.SharedOutputConfiguration;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.hardware.camera2.utils.SubmitInfo;
import android.hardware.camera2.utils.SurfaceUtils;
@@ -188,6 +192,8 @@
private ExecutorService mOfflineSwitchService;
private CameraOfflineSessionImpl mOfflineSessionImpl;
+ private boolean mSharedMode;
+ private boolean mIsPrimaryClient;
// Runnables for all state transitions, except error, which needs the
// error code argument
@@ -208,6 +214,25 @@
}
};
+ private final Runnable mCallOnOpenedInSharedMode = new Runnable() {
+ @Override
+ public void run() {
+ if (!Flags.cameraMultiClient()) {
+ return;
+ }
+ StateCallbackKK sessionCallback = null;
+ synchronized (mInterfaceLock) {
+ if (mRemoteDevice == null) return; // Camera already closed
+
+ sessionCallback = mSessionStateCallback;
+ }
+ if (sessionCallback != null) {
+ sessionCallback.onOpenedInSharedMode(CameraDeviceImpl.this, mIsPrimaryClient);
+ }
+ mDeviceCallback.onOpenedInSharedMode(CameraDeviceImpl.this, mIsPrimaryClient);
+ }
+ };
+
private final Runnable mCallOnUnconfigured = new Runnable() {
@Override
public void run() {
@@ -322,6 +347,32 @@
}
});
}
+
+ public void onOpenedInSharedMode(@NonNull CameraDevice camera, boolean primaryClient) {
+ if (!Flags.cameraMultiClient()) {
+ return;
+ }
+ mClientExecutor.execute(new Runnable() {
+ @Override
+ public void run() {
+ mClientStateCallback.onOpenedInSharedMode(camera, primaryClient);
+ }
+ });
+ }
+
+ public void onClientSharedAccessPriorityChanged(@NonNull CameraDevice camera,
+ boolean primaryClient) {
+ if (!Flags.cameraMultiClient()) {
+ return;
+ }
+ mClientExecutor.execute(new Runnable() {
+ @Override
+ public void run() {
+ mClientStateCallback.onClientSharedAccessPriorityChanged(camera, primaryClient);
+ }
+ });
+ }
+
@Override
public void onOpened(@NonNull CameraDevice camera) {
mClientExecutor.execute(new Runnable() {
@@ -358,7 +409,8 @@
@NonNull CameraManager manager,
int appTargetSdkVersion,
Context ctx,
- @Nullable CameraDevice.CameraDeviceSetup cameraDeviceSetup) {
+ @Nullable CameraDevice.CameraDeviceSetup cameraDeviceSetup,
+ boolean sharedMode) {
if (cameraId == null || callback == null || executor == null || characteristics == null
|| manager == null) {
throw new IllegalArgumentException("Null argument given");
@@ -375,6 +427,7 @@
mAppTargetSdkVersion = appTargetSdkVersion;
mContext = ctx;
mCameraDeviceSetup = cameraDeviceSetup;
+ mSharedMode = sharedMode;
final int MAX_TAG_LEN = 23;
String tag = String.format("CameraDevice-JV-%s", mCameraId);
@@ -438,7 +491,12 @@
}
}
- mDeviceExecutor.execute(mCallOnOpened);
+ if (Flags.cameraMultiClient() && mSharedMode) {
+ mIsPrimaryClient = mRemoteDevice.isPrimaryClient();
+ mDeviceExecutor.execute(mCallOnOpenedInSharedMode);
+ } else {
+ mDeviceExecutor.execute(mCallOnOpened);
+ }
mDeviceExecutor.execute(mCallOnUnconfigured);
mRemoteDeviceInit = true;
@@ -576,7 +634,11 @@
stopRepeating();
try {
- waitUntilIdle();
+ // if device is opened in shared mode, there can be multiple clients accessing the
+ // camera device. So do not wait for idle if the device is opened in shared mode.
+ if (!mSharedMode) {
+ waitUntilIdle();
+ }
mRemoteDevice.beginConfigure();
@@ -764,6 +826,54 @@
checkAndWrapHandler(handler), operatingMode, /*sessionParams*/ null);
}
+ private boolean checkSharedOutputConfiguration(OutputConfiguration outConfig) {
+ if (!Flags.cameraMultiClient()) {
+ return false;
+ }
+ SharedSessionConfiguration sharedSessionConfiguration =
+ mCharacteristics.get(CameraCharacteristics.SHARED_SESSION_CONFIGURATION);
+ if (sharedSessionConfiguration == null) {
+ return false;
+ }
+
+ List<SharedOutputConfiguration> sharedConfigs =
+ sharedSessionConfiguration.getOutputStreamsInformation();
+ for (SharedOutputConfiguration sharedConfig : sharedConfigs) {
+ if (outConfig.getConfiguredSize().equals(sharedConfig.getSize())
+ && (outConfig.getConfiguredFormat() == sharedConfig.getFormat())
+ && (outConfig.getSurfaceGroupId() == OutputConfiguration.SURFACE_GROUP_ID_NONE)
+ && (outConfig.getSurfaceType() == sharedConfig.getSurfaceType())
+ && (outConfig.getMirrorMode() == sharedConfig.getMirrorMode())
+ && (outConfig.getUsage() == sharedConfig.getUsage())
+ && (outConfig.isReadoutTimestampEnabled()
+ == sharedConfig.isReadoutTimestampEnabled())
+ && (outConfig.getTimestampBase() == sharedConfig.getTimestampBase())
+ && (outConfig.getStreamUseCase() == sharedConfig.getStreamUseCase())
+ && (outConfig.getColorSpace().equals(
+ sharedSessionConfiguration.getColorSpace()))
+ && (outConfig.getDynamicRangeProfile()
+ == DynamicRangeProfiles.STANDARD)
+ && (outConfig.getConfiguredDataspace() == sharedConfig.getDataspace())
+ && (Objects.equals(outConfig.getPhysicalCameraId(),
+ sharedConfig.getPhysicalCameraId()))
+ && (outConfig.getSensorPixelModes().isEmpty())
+ && (!outConfig.isShared())) {
+ //Found valid config, return true
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean checkSharedSessionConfiguration(List<OutputConfiguration> outputConfigs) {
+ for (OutputConfiguration out : outputConfigs) {
+ if (!checkSharedOutputConfiguration(out)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
@Override
public void createCaptureSession(SessionConfiguration config)
throws CameraAccessException {
@@ -778,6 +888,14 @@
if (config.getExecutor() == null) {
throw new IllegalArgumentException("Invalid executor");
}
+ if (mSharedMode) {
+ if (config.getSessionType() != SessionConfiguration.SESSION_SHARED) {
+ throw new IllegalArgumentException("Invalid session type");
+ }
+ if (!checkSharedSessionConfiguration(outputConfigs)) {
+ throw new IllegalArgumentException("Invalid output configurations");
+ }
+ }
createCaptureSessionInternal(config.getInputConfiguration(), outputConfigs,
config.getStateCallback(), config.getExecutor(), config.getSessionType(),
config.getSessionParameters());
@@ -801,6 +919,11 @@
throw new IllegalArgumentException("Constrained high speed session doesn't support"
+ " input configuration yet.");
}
+ boolean isSharedSession = (operatingMode == ICameraDeviceUser.SHARED_MODE);
+ if (isSharedSession && inputConfig != null) {
+ throw new IllegalArgumentException("Shared capture session doesn't support"
+ + " input configuration yet.");
+ }
if (mCurrentExtensionSession != null) {
mCurrentExtensionSession.commitStats();
@@ -860,6 +983,10 @@
newSession = new CameraConstrainedHighSpeedCaptureSessionImpl(mNextSessionId++,
callback, executor, this, mDeviceExecutor, configureSuccess,
mCharacteristics);
+ } else if (isSharedSession) {
+ newSession = new CameraSharedCaptureSessionImpl(mNextSessionId++,
+ callback, executor, this, mDeviceExecutor, configureSuccess,
+ mIsPrimaryClient);
} else {
newSession = new CameraCaptureSessionImpl(mNextSessionId++, input,
callback, executor, this, mDeviceExecutor, configureSuccess);
@@ -1882,6 +2009,40 @@
}
}
+ /**
+ * Callback when client access priorities change when camera is opened in shared mode.
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void onClientSharedAccessPriorityChanged(boolean primaryClient) {
+ if (DEBUG) {
+ Log.d(TAG, String.format(
+ "onClientSharedAccessPriorityChanged received, primary client = "
+ + primaryClient));
+ }
+ synchronized (mInterfaceLock) {
+ if (mRemoteDevice == null && mRemoteDeviceInit) {
+ return; // Camera already closed, user is not interested in this callback anymore.
+ }
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ mDeviceExecutor.execute(obtainRunnable(
+ CameraDeviceImpl::notifyClientSharedAccessPriorityChanged, this,
+ primaryClient).recycleOnUse());
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
+ }
+
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ private void notifyClientSharedAccessPriorityChanged(boolean primaryClient) {
+ if (!CameraDeviceImpl.this.isClosed()) {
+ mIsPrimaryClient = primaryClient;
+ mDeviceCallback.onClientSharedAccessPriorityChanged(CameraDeviceImpl.this,
+ primaryClient);
+ }
+ }
+
public void onDeviceError(final int errorCode, CaptureResultExtras resultExtras) {
if (DEBUG) {
Log.d(TAG, String.format(
@@ -2447,6 +2608,12 @@
}
@Override
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void onClientSharedAccessPriorityChanged(boolean primaryClient) {
+ CameraDeviceImpl.this.onClientSharedAccessPriorityChanged(primaryClient);
+ }
+
+ @Override
public void onPrepared(int streamId) {
final OutputConfiguration output;
final StateCallbackKK sessionCallback;
diff --git a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
index 1cc0856..c0a5928 100644
--- a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
+++ b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
@@ -63,6 +63,7 @@
import android.hardware.camera2.params.RecommendedStreamConfiguration;
import android.hardware.camera2.params.RecommendedStreamConfigurationMap;
import android.hardware.camera2.params.ReprocessFormatsMap;
+import android.hardware.camera2.params.SharedSessionConfiguration;
import android.hardware.camera2.params.StreamConfiguration;
import android.hardware.camera2.params.StreamConfigurationDuration;
import android.hardware.camera2.params.StreamConfigurationMap;
@@ -866,6 +867,15 @@
return (T) metadata.getLensIntrinsicSamples();
}
});
+ sGetCommandMap.put(
+ CameraCharacteristics.SHARED_SESSION_CONFIGURATION.getNativeKey(),
+ new GetCommand() {
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
+ return (T) metadata.getSharedSessionConfiguration();
+ }
+ });
}
private int[] getAvailableFormats() {
@@ -1658,6 +1668,22 @@
listHighResolution);
}
+ private SharedSessionConfiguration getSharedSessionConfiguration() {
+ if (!Flags.cameraMultiClient()) {
+ return null;
+ }
+ Integer sharedSessionColorSpace = getBase(
+ CameraCharacteristics.SHARED_SESSION_COLOR_SPACE);
+ long[] sharedOutputConfigurations = getBase(
+ CameraCharacteristics.SHARED_SESSION_OUTPUT_CONFIGURATIONS);
+
+ if ((sharedSessionColorSpace == null) || (sharedOutputConfigurations == null)) {
+ return null;
+ }
+
+ return new SharedSessionConfiguration(sharedSessionColorSpace, sharedOutputConfigurations);
+ }
+
private StreamConfigurationMap getStreamConfigurationMapMaximumResolution() {
StreamConfiguration[] configurations = getBase(
CameraCharacteristics.SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION);
diff --git a/core/java/android/hardware/camera2/impl/CameraOfflineSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraOfflineSessionImpl.java
index eb2ff88..1769c46 100644
--- a/core/java/android/hardware/camera2/impl/CameraOfflineSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraOfflineSessionImpl.java
@@ -16,11 +16,13 @@
package android.hardware.camera2.impl;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import android.annotation.FlaggedApi;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
-import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraOfflineSession;
import android.hardware.camera2.CameraOfflineSession.CameraOfflineSessionCallback;
import android.hardware.camera2.CaptureFailure;
@@ -40,15 +42,15 @@
import android.util.SparseArray;
import android.view.Surface;
+import com.android.internal.camera.flags.Flags;
+
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.Executor;
-
-import static com.android.internal.util.Preconditions.*;
+import java.util.concurrent.atomic.AtomicBoolean;
public class CameraOfflineSessionImpl extends CameraOfflineSession
implements IBinder.DeathRecipient {
@@ -176,6 +178,12 @@
}
@Override
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ public void onClientSharedAccessPriorityChanged(boolean primaryClient) {
+ Log.v(TAG, "onClientSharedAccessPriorityChanged primaryClient = " + primaryClient);
+ }
+
+ @Override
public void onDeviceIdle() {
synchronized(mInterfaceLock) {
if (mRemoteSession == null) {
diff --git a/core/java/android/hardware/camera2/impl/CameraSharedCaptureSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraSharedCaptureSessionImpl.java
new file mode 100644
index 0000000..a1f31c0
--- /dev/null
+++ b/core/java/android/hardware/camera2/impl/CameraSharedCaptureSessionImpl.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (C) 2024 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.hardware.camera2.impl;
+
+import android.annotation.FlaggedApi;
+import android.hardware.camera2.CameraAccessException;
+import android.hardware.camera2.CameraCaptureSession;
+import android.hardware.camera2.CameraDevice;
+import android.hardware.camera2.CameraSharedCaptureSession;
+import android.hardware.camera2.CaptureRequest;
+import android.hardware.camera2.params.OutputConfiguration;
+import android.os.ConditionVariable;
+import android.os.Handler;
+import android.view.Surface;
+
+import com.android.internal.camera.flags.Flags;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Standard implementation of CameraSharedCaptureSession.
+ *
+ * <p>
+ * Mostly just forwards calls to an instance of CameraCaptureSessionImpl,
+ * but implements the few necessary behavior changes and additional methods required
+ * for the shared session mode.
+ * </p>
+ */
+@FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+public class CameraSharedCaptureSessionImpl
+ extends CameraSharedCaptureSession implements CameraCaptureSessionCore {
+ private static final String TAG = "CameraSharedCaptureSessionImpl";
+ private final CameraCaptureSessionImpl mSessionImpl;
+ private final ConditionVariable mInitialized = new ConditionVariable();
+ private boolean mIsPrimary;
+
+ /**
+ * Create a new CameraCaptureSession.
+ */
+ CameraSharedCaptureSessionImpl(int id,
+ CameraCaptureSession.StateCallback callback, Executor stateExecutor,
+ android.hardware.camera2.impl.CameraDeviceImpl deviceImpl,
+ Executor deviceStateExecutor, boolean configureSuccess, boolean isPrimary) {
+ CameraCaptureSession.StateCallback wrapperCallback = new WrapperCallback(callback);
+ mSessionImpl = new CameraCaptureSessionImpl(id, /*input*/null, wrapperCallback,
+ stateExecutor, deviceImpl, deviceStateExecutor, configureSuccess);
+ mIsPrimary = isPrimary;
+ mInitialized.open();
+ }
+
+ @Override
+ public int startStreaming(List<Surface> surfaces, Executor executor, CaptureCallback listener)
+ throws CameraAccessException {
+ // Todo: Need to add implementation.
+ return 0;
+ }
+
+ @Override
+ public void stopStreaming() throws CameraAccessException {
+ // Todo: Need to add implementation.
+ }
+
+ @Override
+ public void close() {
+ mSessionImpl.close();
+ }
+
+ @Override
+ public Surface getInputSurface() {
+ return null;
+ }
+
+ @Override
+ public boolean isReprocessable() {
+ return false;
+ }
+
+ @Override
+ public void abortCaptures() throws CameraAccessException {
+ if (mIsPrimary) {
+ mSessionImpl.abortCaptures();
+ }
+ }
+
+ @Override
+ public int setRepeatingRequest(CaptureRequest request, CaptureCallback listener,
+ Handler handler) throws CameraAccessException {
+ if (mIsPrimary) {
+ return mSessionImpl.setRepeatingRequest(request, listener, handler);
+ }
+ throw new UnsupportedOperationException("Shared capture session only supports this method"
+ + " for primary clients");
+ }
+
+ @Override
+ public void stopRepeating() throws CameraAccessException {
+ if (mIsPrimary) {
+ mSessionImpl.stopRepeating();
+ }
+ }
+
+ @Override
+ public int capture(CaptureRequest request, CaptureCallback listener, Handler handler)
+ throws CameraAccessException {
+ if (mIsPrimary) {
+ return mSessionImpl.capture(request, listener, handler);
+ }
+ throw new UnsupportedOperationException("Shared capture session only supports this method"
+ + " for primary clients");
+ }
+
+ @Override
+ public void tearDown(Surface surface) throws CameraAccessException {
+ mSessionImpl.tearDown(surface);
+ }
+
+ @Override
+ public CameraDevice getDevice() {
+ return mSessionImpl.getDevice();
+ }
+
+ @Override
+ public boolean isAborting() {
+ return mSessionImpl.isAborting();
+ }
+
+ @Override
+ public CameraDeviceImpl.StateCallbackKK getDeviceStateCallback() {
+ return mSessionImpl.getDeviceStateCallback();
+ }
+
+ @Override
+ public void replaceSessionClose() {
+ mSessionImpl.replaceSessionClose();
+ }
+
+ @Override
+ public int setRepeatingBurst(List<CaptureRequest> requests, CaptureCallback listener,
+ Handler handler) throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared Capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public int captureBurst(List<CaptureRequest> requests, CaptureCallback listener,
+ Handler handler) throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared Capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public void updateOutputConfiguration(OutputConfiguration config)
+ throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public void finalizeOutputConfigurations(List<OutputConfiguration> deferredOutputConfigs)
+ throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public void prepare(Surface surface) throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public void prepare(int maxCount, Surface surface) throws CameraAccessException {
+ throw new UnsupportedOperationException("Shared capture session doesn't support"
+ + " this method");
+ }
+
+ @Override
+ public void closeWithoutDraining() {
+ throw new UnsupportedOperationException("Shared capture session doesn't support"
+ + " this method");
+ }
+
+ private class WrapperCallback extends StateCallback {
+ private final StateCallback mCallback;
+
+ WrapperCallback(StateCallback callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public void onConfigured(CameraCaptureSession session) {
+ mInitialized.block();
+ mCallback.onConfigured(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onConfigureFailed(CameraCaptureSession session) {
+ mInitialized.block();
+ mCallback.onConfigureFailed(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onReady(CameraCaptureSession session) {
+ mCallback.onReady(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onActive(CameraCaptureSession session) {
+ mCallback.onActive(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onCaptureQueueEmpty(CameraCaptureSession session) {
+ mCallback.onCaptureQueueEmpty(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onClosed(CameraCaptureSession session) {
+ mCallback.onClosed(CameraSharedCaptureSessionImpl.this);
+ }
+
+ @Override
+ public void onSurfacePrepared(CameraCaptureSession session, Surface surface) {
+ mCallback.onSurfacePrepared(CameraSharedCaptureSessionImpl.this,
+ surface);
+ }
+ }
+}
diff --git a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
index aec2cff..831c75ec 100644
--- a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
+++ b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
@@ -301,4 +301,16 @@
}
}
+ /**
+ * API to check if the client is primary client when camera device is opened in shared mode.
+ */
+ public boolean isPrimaryClient() throws CameraAccessException {
+ try {
+ return mRemoteDevice.isPrimaryClient();
+ } catch (ServiceSpecificException e) {
+ throw ExceptionUtils.throwAsPublicException(e);
+ } catch (RemoteException e) {
+ throw ExceptionUtils.throwAsPublicException(e);
+ }
+ }
}
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index d38be9b..e12c463 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -29,6 +29,7 @@
import android.graphics.ColorSpace;
import android.graphics.ImageFormat;
import android.graphics.ImageFormat.Format;
+import android.hardware.DataSpace.NamedDataSpace;
import android.hardware.HardwareBuffer;
import android.hardware.HardwareBuffer.Usage;
import android.hardware.camera2.CameraCaptureSession;
@@ -1729,6 +1730,79 @@
}
/**
+ * Get the configured format associated with this {@link OutputConfiguration}.
+ *
+ * @return {@link android.graphics.ImageFormat#Format} associated with this
+ * {@link OutputConfiguration}.
+ *
+ * @hide
+ */
+ public @Format int getConfiguredFormat() {
+ return mConfiguredFormat;
+ }
+
+ /**
+ * Get the usage flag associated with this {@link OutputConfiguration}.
+ *
+ * @return {@link HardwareBuffer#Usage} associated with this {@link OutputConfiguration}.
+ *
+ * @hide
+ */
+ public @Usage long getUsage() {
+ return mUsage;
+ }
+
+ /**
+ * Get the surface type associated with this {@link OutputConfiguration}.
+ *
+ * @return The surface type associated with this {@link OutputConfiguration}.
+ *
+ * @see #SURFACE_TYPE_SURFACE_VIEW
+ * @see #SURFACE_TYPE_SURFACE_TEXTURE
+ * @see #SURFACE_TYPE_MEDIA_RECORDER
+ * @see #SURFACE_TYPE_MEDIA_CODEC
+ * @see #SURFACE_TYPE_IMAGE_READER
+ * @see #SURFACE_TYPE_UNKNOWN
+ * @hide
+ */
+ public int getSurfaceType() {
+ return mSurfaceType;
+ }
+
+ /**
+ * Get the sensor pixel modes associated with this {@link OutputConfiguration}.
+ *
+ * @return List of {@link #SensorPixelMode} associated with this {@link OutputConfiguration}.
+ *
+ * @hide
+ */
+ public @NonNull List<Integer> getSensorPixelModes() {
+ return mSensorPixelModesUsed;
+ }
+
+ /**
+ * Get the sharing mode associated with this {@link OutputConfiguration}.
+ *
+ * @return true if surface sharing is enabled with this {@link OutputConfiguration}.
+ *
+ * @hide
+ */
+ public boolean isShared() {
+ return mIsShared;
+ }
+
+ /**
+ * Get the dataspace associated with this {@link OutputConfiguration}.
+ *
+ * @return {@link Dataspace#NamedDataSpace} for this {@link OutputConfiguration}.
+ *
+ * @hide
+ */
+ public @NamedDataSpace int getConfiguredDataspace() {
+ return mConfiguredDataspace;
+ }
+
+ /**
* Get the physical camera ID associated with this {@link OutputConfiguration}.
*
* <p>If this OutputConfiguration isn't targeting a physical camera of a logical
diff --git a/core/java/android/hardware/camera2/params/SessionConfiguration.java b/core/java/android/hardware/camera2/params/SessionConfiguration.java
index 50c6b5b..82aa64b 100644
--- a/core/java/android/hardware/camera2/params/SessionConfiguration.java
+++ b/core/java/android/hardware/camera2/params/SessionConfiguration.java
@@ -23,6 +23,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
+import android.annotation.SystemApi;
import android.graphics.ColorSpace;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
@@ -78,6 +79,19 @@
CameraDevice.SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED;
/**
+ * A shared session type containing instances of {@link OutputConfiguration} from a set of
+ * predefined stream configurations. A shared session can be shared among multiple clients.
+ * Shared session does not have any {@link InputConfiguration} as it does not support
+ * reprocessable sessions.
+ *
+ * @see CameraDevice#createCaptureSession(SessionConfiguration)
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+ @SystemApi
+ public static final int SESSION_SHARED = CameraDevice.SESSION_OPERATION_MODE_SHARED;
+
+ /**
* First vendor-specific session mode
* @hide
*/
diff --git a/core/java/android/hardware/camera2/params/SharedSessionConfiguration.java b/core/java/android/hardware/camera2/params/SharedSessionConfiguration.java
new file mode 100644
index 0000000..cdcc92c
--- /dev/null
+++ b/core/java/android/hardware/camera2/params/SharedSessionConfiguration.java
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2024 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.hardware.camera2.params;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SuppressLint;
+import android.annotation.SystemApi;
+import android.graphics.ColorSpace;
+import android.graphics.ImageFormat.Format;
+import android.hardware.DataSpace.NamedDataSpace;
+import android.hardware.HardwareBuffer.Usage;
+import android.hardware.camera2.params.OutputConfiguration.MirrorMode;
+import android.hardware.camera2.params.OutputConfiguration.StreamUseCase;
+import android.hardware.camera2.params.OutputConfiguration.TimestampBase;
+import android.util.Log;
+import android.util.Size;
+
+import com.android.internal.camera.flags.Flags;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Immutable class to store the shared session configuration
+ * {@link CameraCharacteristics#SHARED_SESSION_CONFIGURATION} to set up
+ * {@link android.view.Surface Surfaces} for creating a
+ * {@link android.hardware.camera2.CameraSharedCaptureSession capture session} using
+ * {@link android.hardware.camera2.CameraDevice#createCaptureSession(SessionConfiguration)} and
+ * {@link android.hardware.camera2.params.SessionConfiguration#SESSION_SHARED
+ * shared capture session} when camera has been opened in shared mode using
+ * {@link #openSharedCamera(String, Executor, StateCallback)}.
+ *
+ * <p>This is the authoritative list for all output configurations that are supported by a camera
+ * device when opened in shared mode.</p>
+ *
+ * <p>An instance of this object is available from {@link CameraCharacteristics} using
+ * the {@link CameraCharacteristics#SHARED_SESSION_CONFIGURATION} key and the
+ * {@link CameraCharacteristics#get} method.</p>
+ *
+ * <pre><code>{@code
+ * CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
+ * StreamConfigurationMap configs = characteristics.get(
+ * CameraCharacteristics.SHARED_SESSION_CONFIGURATION);
+ * }</code></pre>
+ *
+ * @see CameraCharacteristics#SHARED_SESSION_CONFIGURATION
+ * @see CameraDevice#createCaptureSession(SessionConfiguration)
+ * @see SessionConfiguration#SESSION_SHARED
+ * @see CameraManager#openSharedCamera(String, Executor, StateCallback)
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_CAMERA_MULTI_CLIENT)
+public final class SharedSessionConfiguration {
+ private static final String TAG = "SharedSessionConfiguration";
+ // Metadata android.info.availableSharedOutputConfigurations has list of shared output
+ // configurations. Each output configuration has minimum of 11 entries of size long
+ // followed by the physical camera id if present.
+ // See android.info.availableSharedOutputConfigurations for details.
+ private static final int SHARED_OUTPUT_CONFIG_NUM_OF_ENTRIES = 11;
+ /**
+ * Immutable class to store shared output stream information.
+ */
+ public static final class SharedOutputConfiguration {
+ private final int mSurfaceType;
+ private final Size mSize;
+ private final int mFormat;
+ private final int mDataspace;
+ private final long mStreamUseCase;
+ private String mPhysicalCameraId;
+ private final long mUsage;
+ private int mTimestampBase;
+ private int mMirrorMode;
+ private boolean mReadoutTimestampEnabled;
+
+ /**
+ * Create a new {@link SharedOutputConfiguration}.
+ *
+ * @param surfaceType Surface Type for this output configuration.
+ * @param sz Size for this output configuration.
+ * @param format {@link android.graphics.ImageFormat#Format} associated with this
+ * {@link OutputConfiguration}.
+ * @param mirrorMode {@link OutputConfiguration#MirrorMode} for this output configuration.
+ * @param readoutTimeStampEnabled Flag indicating whether readout timestamp is enabled
+ * for this output configuration.
+ * @param timestampBase {@link OutputConfiguration#TimestampBase} for this output
+ * configuration.
+ * @param dataspace {@link Dataspace#NamedDataSpace} for this output configuration.
+ * @param usage {@link HardwareBuffer#Usage} for this output configuration.
+ * @param streamUseCase {@link OutputConfiguration#StreamUseCase} for this output
+ * configuration.
+ * @param physicalCamId Physical Camera Id for this output configuration.
+ *
+ * @hide
+ */
+ public SharedOutputConfiguration(int surfaceType, @NonNull Size sz, @Format int format,
+ @MirrorMode int mirrorMode, boolean readoutTimeStampEnabled,
+ @TimestampBase int timestampBase, @NamedDataSpace int dataspace, @Usage long usage,
+ @StreamUseCase long streamUseCase, @Nullable String physicalCamId) {
+ mSurfaceType = surfaceType;
+ mSize = sz;
+ mFormat = format;
+ mMirrorMode = mirrorMode;
+ mReadoutTimestampEnabled = readoutTimeStampEnabled;
+ mTimestampBase = timestampBase;
+ mDataspace = dataspace;
+ mUsage = usage;
+ mStreamUseCase = streamUseCase;
+ mPhysicalCameraId = physicalCamId;
+ }
+
+ /**
+ * Returns the surface type configured for the shared output configuration.
+ * @return SURFACE_TYPE_UNKNOWN = -1
+ * SURFACE_TYPE_SURFACE_VIEW = 0
+ * SURFACE_TYPE_SURFACE_TEXTURE = 1
+ * SURFACE_TYPE_MEDIA_RECORDER = 2
+ * SURFACE_TYPE_MEDIA_CODEC = 3
+ * SURFACE_TYPE_IMAGE_READER = 4
+ */
+ public int getSurfaceType() {
+ return mSurfaceType;
+ }
+
+ /**
+ * Returns the format of the shared output configuration.
+ * @return format The format of the configured output. This must be one of the
+ * {@link android.graphics.ImageFormat} or {@link android.graphics.PixelFormat}
+ * constants. Note that not all formats are supported by the camera device.
+ */
+ public @Format int getFormat() {
+ return mFormat;
+ }
+
+ /**
+ * Returns the configured size for the shared output configuration.
+ * @return surfaceSize Size for the shared output configuration
+ *
+ */
+ public @NonNull Size getSize() {
+ return mSize;
+ }
+
+ /**
+ * Return datatspace configured for the shared output configuration.
+ *
+ * @return {@link Dataspace#NamedDataSpace} configured for shared session
+ */
+ public @NamedDataSpace int getDataspace() {
+ return mDataspace;
+ }
+
+ /**
+ * Get the mirroring mode configured for the shared output configuration.
+ *
+ * @return {@link OutputConfiguration#MirrorMode} configured for the shared session
+ */
+ public @MirrorMode int getMirrorMode() {
+ return mMirrorMode;
+ }
+
+ /**
+ * Get the stream use case configured for the shared output configuration.
+ *
+ * @return {@link OutputConfiguration#StreamUseCase} configured for the shared session
+ */
+ public @StreamUseCase long getStreamUseCase() {
+ return mStreamUseCase;
+ }
+
+ /**
+ * Get the timestamp base configured for the shared output configuration.
+ *
+ * @return {@link OutputConfiguration#TimestampBase} configured for the shared session
+ */
+ public @TimestampBase int getTimestampBase() {
+ return mTimestampBase;
+ }
+
+ /** Whether readout timestamp is used for this shared output configuration.
+ *
+ */
+ public boolean isReadoutTimestampEnabled() {
+ return mReadoutTimestampEnabled;
+ }
+
+ /** Returns the usage if set for this shared output configuration.
+ *
+ * @return {@link HardwareBuffer#Usage} flags if set for shared output configuration with
+ * the ImageReader output surface.
+ */
+ public @Usage long getUsage() {
+ return mUsage;
+ }
+
+ public @Nullable String getPhysicalCameraId() {
+ return mPhysicalCameraId;
+ }
+ }
+
+ /**
+ * Create a new {@link SharedSessionConfiguration}.
+ *
+ * <p>The array parameters ownership is passed to this object after creation; do not
+ * write to them after this constructor is invoked.</p>
+ *
+ * @param sharedColorSpace the colorspace to be used for the shared output configurations.
+ * @param sharedOutputConfigurations a non-{@code null} array of metadata
+ * android.info.availableSharedOutputConfigurations
+ *
+ * @hide
+ */
+ public SharedSessionConfiguration(int sharedColorSpace,
+ @NonNull long[] sharedOutputConfigurations) {
+ mColorSpace = sharedColorSpace;
+ byte physicalCameraIdLen;
+ int surfaceType, width, height, format, mirrorMode, timestampBase, dataspace;
+ long usage, streamUseCase;
+ boolean isReadOutTimestampEnabled;
+ // Parse metadata android.info.availableSharedOutputConfigurations which contains
+ // list of shared output configurations.
+ int numOfEntries = sharedOutputConfigurations.length;
+ int i = 0;
+ while (numOfEntries >= SharedSessionConfiguration.SHARED_OUTPUT_CONFIG_NUM_OF_ENTRIES) {
+ surfaceType = (int) sharedOutputConfigurations[i];
+ width = (int) sharedOutputConfigurations[i + 1];
+ height = (int) sharedOutputConfigurations[i + 2];
+ format = (int) sharedOutputConfigurations[i + 3];
+ mirrorMode = (int) sharedOutputConfigurations[i + 4];
+ isReadOutTimestampEnabled = (sharedOutputConfigurations[i + 5] != 0);
+ timestampBase = (int) sharedOutputConfigurations[i + 6];
+ dataspace = (int) sharedOutputConfigurations[i + 7];
+ usage = sharedOutputConfigurations[i + 8];
+ streamUseCase = sharedOutputConfigurations[i + 9];
+ physicalCameraIdLen = (byte) sharedOutputConfigurations[i + 10];
+ numOfEntries -= SharedSessionConfiguration.SHARED_OUTPUT_CONFIG_NUM_OF_ENTRIES;
+ i += SharedSessionConfiguration.SHARED_OUTPUT_CONFIG_NUM_OF_ENTRIES;
+ if (numOfEntries < physicalCameraIdLen) {
+ Log.e(TAG, "Number of remaining data in shared configuration is less than"
+ + " physical camera id length . Malformed metadata"
+ + " android.info.availableSharedOutputConfigurations.");
+ break;
+ }
+ StringBuilder physicalCameraId = new StringBuilder();
+ long asciiValue;
+ for (int j = 0; j < physicalCameraIdLen; j++) {
+ asciiValue = sharedOutputConfigurations[i + j];
+ if (asciiValue == 0) { // Check for null terminator
+ break;
+ }
+ physicalCameraId.append((char) asciiValue);
+ }
+ SharedOutputConfiguration outputInfo;
+ outputInfo = new SharedOutputConfiguration(surfaceType, new Size(width, height),
+ format, mirrorMode, isReadOutTimestampEnabled, timestampBase,
+ dataspace, usage, streamUseCase, physicalCameraId.toString());
+ mOutputStreamConfigurations.add(outputInfo);
+ i += physicalCameraIdLen;
+ numOfEntries -= physicalCameraIdLen;
+ }
+ if (numOfEntries != 0) {
+ Log.e(TAG, "Unexpected entries left in shared output configuration."
+ + " Malformed metadata android.info.availableSharedOutputConfigurations.");
+ }
+ }
+
+ /**
+ * Return the shared session color space which is configured.
+ *
+ * @return the shared session color space
+ */
+ @SuppressLint("MethodNameUnits")
+ public @Nullable ColorSpace getColorSpace() {
+ if (mColorSpace != ColorSpaceProfiles.UNSPECIFIED) {
+ return ColorSpace.get(ColorSpace.Named.values()[mColorSpace]);
+ } else {
+ return null;
+ }
+ }
+ /**
+ * Get information about each shared output configuarion in the shared session.
+ *
+ * @return Non-modifiable list of output configuration.
+ *
+ */
+ public @NonNull List<SharedOutputConfiguration> getOutputStreamsInformation() {
+ return Collections.unmodifiableList(mOutputStreamConfigurations);
+ }
+
+ private int mColorSpace;
+ private final ArrayList<SharedOutputConfiguration> mOutputStreamConfigurations =
+ new ArrayList<SharedOutputConfiguration>();
+}
+
diff --git a/core/java/android/hardware/contexthub/HubDiscoveryInfo.java b/core/java/android/hardware/contexthub/HubDiscoveryInfo.java
new file mode 100644
index 0000000..875c4b4
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubDiscoveryInfo.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+import android.hardware.location.ContextHubManager;
+
+/**
+ * Class that represents the result of from an hub endpoint discovery.
+ *
+ * <p>The type is returned from an endpoint discovery query via {@link
+ * ContextHubManager#findEndpoints}. Application may use the values {@link #getHubEndpointInfo} to
+ * retrieve the {@link HubEndpointInfo} that describes the endpoint that matches the query. The
+ * class provides flexibility in returning more information (e.g. service provided by the endpoint)
+ * in addition to the information about the endpoint.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public class HubDiscoveryInfo {
+ // TODO(b/375487784): Add ServiceInfo to the result.
+ android.hardware.contexthub.HubEndpointInfo mEndpointInfo;
+
+ /**
+ * Constructor for internal use.
+ *
+ * @hide
+ */
+ public HubDiscoveryInfo(android.hardware.contexthub.HubEndpointInfo endpointInfo) {
+ mEndpointInfo = endpointInfo;
+ }
+
+ /** Get the {@link android.hardware.contexthub.HubEndpointInfo} for the endpoint found. */
+ @NonNull
+ public HubEndpointInfo getHubEndpointInfo() {
+ return mEndpointInfo;
+ }
+}
diff --git a/core/java/android/hardware/contexthub/HubEndpoint.java b/core/java/android/hardware/contexthub/HubEndpoint.java
new file mode 100644
index 0000000..99b05da
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubEndpoint.java
@@ -0,0 +1,406 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+import android.content.Context;
+import android.hardware.location.IContextHubService;
+import android.os.RemoteException;
+import android.util.Log;
+import android.util.SparseArray;
+
+import androidx.annotation.GuardedBy;
+
+import java.util.concurrent.Executor;
+
+/**
+ * An object representing an endpoint exposed to ContextHub and VendorHub. The object encapsulates
+ * the lifecycle and message callbacks for an endpoint.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public class HubEndpoint {
+ private static final String TAG = "HubEndpoint";
+
+ private final Object mLock = new Object();
+ private final HubEndpointInfo mPendingHubEndpointInfo;
+ @Nullable private final IHubEndpointLifecycleCallback mLifecycleCallback;
+ @NonNull private final Executor mLifecycleCallbackExecutor;
+
+ @GuardedBy("mLock")
+ private final SparseArray<HubEndpointSession> mActiveSessions = new SparseArray<>();
+
+ private final IContextHubEndpointCallback mServiceCallback =
+ new IContextHubEndpointCallback.Stub() {
+ @Override
+ public void onSessionOpenRequest(int sessionId, HubEndpointInfo initiator)
+ throws RemoteException {
+ HubEndpointSession activeSession;
+ synchronized (mLock) {
+ activeSession = mActiveSessions.get(sessionId);
+ // TODO(b/378974199): Consider refactor these assertions
+ if (activeSession != null) {
+ Log.i(
+ TAG,
+ "onSessionOpenComplete: session already exists, id="
+ + sessionId);
+ return;
+ }
+ }
+
+ if (mLifecycleCallback != null) {
+ mLifecycleCallbackExecutor.execute(
+ () ->
+ processSessionOpenRequestResult(
+ sessionId,
+ initiator,
+ mLifecycleCallback.onSessionOpenRequest(
+ initiator)));
+ }
+ }
+
+ private void processSessionOpenRequestResult(
+ int sessionId, HubEndpointInfo initiator, HubEndpointSessionResult result) {
+ if (result == null) {
+ throw new IllegalArgumentException(
+ "HubEndpointSessionResult shouldn't be null.");
+ }
+
+ if (result.isAccepted()) {
+ acceptSession(sessionId, initiator);
+ } else {
+ Log.i(
+ TAG,
+ "Session "
+ + sessionId
+ + " from "
+ + initiator
+ + " was rejected, reason="
+ + result.getReason());
+ rejectSession(sessionId);
+ }
+ }
+
+ private void acceptSession(int sessionId, HubEndpointInfo initiator) {
+ if (mServiceToken == null || mAssignedHubEndpointInfo == null) {
+ // No longer registered?
+ return;
+ }
+
+ // Retrieve the active session
+ HubEndpointSession activeSession;
+ synchronized (mLock) {
+ activeSession = mActiveSessions.get(sessionId);
+ // TODO(b/378974199): Consider refactor these assertions
+ if (activeSession != null) {
+ Log.e(
+ TAG,
+ "onSessionOpenRequestResult: session already exists, id="
+ + sessionId);
+ return;
+ }
+
+ activeSession =
+ new HubEndpointSession(
+ sessionId,
+ HubEndpoint.this,
+ mAssignedHubEndpointInfo,
+ initiator);
+ try {
+ // oneway call to notify system service that the request is completed
+ mServiceToken.openSessionRequestComplete(sessionId);
+ } catch (RemoteException e) {
+ Log.e(TAG, "onSessionOpenRequestResult: ", e);
+ return;
+ }
+
+ mActiveSessions.put(sessionId, activeSession);
+ }
+
+ // Execute the callback
+ activeSession.setOpened();
+ if (mLifecycleCallback != null) {
+ final HubEndpointSession finalActiveSession = activeSession;
+ mLifecycleCallbackExecutor.execute(
+ () -> mLifecycleCallback.onSessionOpened(finalActiveSession));
+ }
+ }
+
+ private void rejectSession(int sessionId) {
+ if (mServiceToken == null || mAssignedHubEndpointInfo == null) {
+ // No longer registered?
+ return;
+ }
+
+ try {
+ mServiceToken.closeSession(
+ sessionId,
+ IHubEndpointLifecycleCallback
+ .REASON_OPEN_ENDPOINT_SESSION_REQUEST_REJECTED);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public void onSessionOpenComplete(int sessionId) throws RemoteException {
+ final HubEndpointSession activeSession;
+
+ // Retrieve the active session
+ synchronized (mLock) {
+ activeSession = mActiveSessions.get(sessionId);
+ }
+ // TODO(b/378974199): Consider refactor these assertions
+ if (activeSession == null) {
+ Log.i(
+ TAG,
+ "onSessionOpenComplete: no pending session open request? id="
+ + sessionId);
+ return;
+ }
+
+ // Execute the callback
+ activeSession.setOpened();
+ if (mLifecycleCallback != null) {
+ mLifecycleCallbackExecutor.execute(
+ () -> mLifecycleCallback.onSessionOpened(activeSession));
+ }
+ }
+
+ @Override
+ public void onSessionClosed(int sessionId, int reason) throws RemoteException {
+ final HubEndpointSession activeSession;
+
+ // Retrieve the active session
+ synchronized (mLock) {
+ activeSession = mActiveSessions.get(sessionId);
+ }
+ // TODO(b/378974199): Consider refactor these assertions
+ if (activeSession == null) {
+ Log.i(TAG, "onSessionClosed: session not active, id=" + sessionId);
+ return;
+ }
+
+ // Execute the callback
+ if (mLifecycleCallback != null) {
+ mLifecycleCallbackExecutor.execute(
+ () -> {
+ mLifecycleCallback.onSessionClosed(activeSession, reason);
+
+ // Remove the session object first to call
+ activeSession.setClosed();
+ synchronized (mLock) {
+ mActiveSessions.remove(sessionId);
+ }
+ });
+ }
+ }
+ };
+
+ /** Binder returned from system service, non-null while registered. */
+ @Nullable private IContextHubEndpoint mServiceToken;
+
+ /** HubEndpointInfo with the assigned endpoint id from system service. */
+ @Nullable private HubEndpointInfo mAssignedHubEndpointInfo;
+
+ private HubEndpoint(
+ @NonNull HubEndpointInfo pendingEndpointInfo,
+ @Nullable IHubEndpointLifecycleCallback endpointLifecycleCallback,
+ @NonNull Executor lifecycleCallbackExecutor) {
+ mPendingHubEndpointInfo = pendingEndpointInfo;
+ mLifecycleCallback = endpointLifecycleCallback;
+ mLifecycleCallbackExecutor = lifecycleCallbackExecutor;
+ }
+
+ /** @hide */
+ public void register(IContextHubService service) {
+ // TODO(b/378974199): Consider refactor these assertions
+ if (mServiceToken != null) {
+ // Already registered
+ return;
+ }
+ try {
+ IContextHubEndpoint serviceToken =
+ service.registerEndpoint(mPendingHubEndpointInfo, mServiceCallback);
+ mAssignedHubEndpointInfo = serviceToken.getAssignedHubEndpointInfo();
+ mServiceToken = serviceToken;
+ } catch (RemoteException e) {
+ Log.e(TAG, "registerEndpoint: failed to register endpoint", e);
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ /** @hide */
+ public void unregister() {
+ IContextHubEndpoint serviceToken = mServiceToken;
+ // TODO(b/378974199): Consider refactor these assertions
+ if (serviceToken == null) {
+ // Not yet registered
+ return;
+ }
+
+ try {
+ synchronized (mLock) {
+ // Don't call HubEndpointSession.close() here.
+ for (int i = 0; i < mActiveSessions.size(); i++) {
+ mActiveSessions.get(mActiveSessions.keyAt(i)).setClosed();
+ }
+ mActiveSessions.clear();
+ }
+ mServiceToken.unregister();
+ } catch (RemoteException e) {
+ Log.e(TAG, "unregisterEndpoint: failed to unregister endpoint", e);
+ e.rethrowFromSystemServer();
+ } finally {
+ mServiceToken = null;
+ mAssignedHubEndpointInfo = null;
+ }
+ }
+
+ /** @hide */
+ public void openSession(HubEndpointInfo destinationInfo) {
+ // TODO(b/378974199): Consider refactor these assertions
+ if (mServiceToken == null || mAssignedHubEndpointInfo == null) {
+ // No longer registered?
+ return;
+ }
+
+ HubEndpointSession newSession;
+ try {
+ // Request system service to assign session id.
+ int sessionId = mServiceToken.openSession(destinationInfo);
+
+ // Save the newly created session
+ synchronized (mLock) {
+ newSession =
+ new HubEndpointSession(
+ sessionId,
+ HubEndpoint.this,
+ destinationInfo,
+ mAssignedHubEndpointInfo);
+ mActiveSessions.put(sessionId, newSession);
+ }
+ } catch (RemoteException e) {
+ // Move this to toString
+ Log.e(TAG, "openSession: failed to open session to " + destinationInfo, e);
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ /** @hide */
+ public void closeSession(HubEndpointSession session) {
+ IContextHubEndpoint serviceToken = mServiceToken;
+ // TODO(b/378974199): Consider refactor these assertions
+ if (serviceToken == null || mAssignedHubEndpointInfo == null) {
+ // Not registered
+ return;
+ }
+
+ synchronized (mLock) {
+ if (!mActiveSessions.contains(session.getId())) {
+ // Already closed?
+ return;
+ }
+ session.setClosed();
+ mActiveSessions.remove(session.getId());
+ }
+
+ try {
+ // Oneway notification to system service
+ serviceToken.closeSession(
+ session.getId(),
+ IHubEndpointLifecycleCallback.REASON_CLOSE_ENDPOINT_SESSION_REQUESTED);
+ } catch (RemoteException e) {
+ Log.e(TAG, "closeSession: failed to close session " + session, e);
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ @Nullable
+ public String getTag() {
+ return mPendingHubEndpointInfo.getTag();
+ }
+
+ @Nullable
+ public IHubEndpointLifecycleCallback getLifecycleCallback() {
+ return mLifecycleCallback;
+ }
+
+ /** Builder for a {@link HubEndpoint} object. */
+ public static final class Builder {
+ private final String mPackageName;
+
+ @Nullable private IHubEndpointLifecycleCallback mLifecycleCallback;
+
+ @NonNull private Executor mLifecycleCallbackExecutor;
+
+ @Nullable private String mTag;
+
+ /** Create a builder for {@link HubEndpoint} */
+ public Builder(@NonNull Context context) {
+ mPackageName = context.getPackageName();
+ mLifecycleCallbackExecutor = context.getMainExecutor();
+ }
+
+ /**
+ * Set a tag string. The tag can be used to further identify the creator of the endpoint.
+ * Endpoints created by the same package share the same name but should have different tags.
+ */
+ @NonNull
+ public Builder setTag(@NonNull String tag) {
+ mTag = tag;
+ return this;
+ }
+
+ /** Attach a callback interface for lifecycle events for this Endpoint */
+ @NonNull
+ public Builder setLifecycleCallback(
+ @NonNull IHubEndpointLifecycleCallback lifecycleCallback) {
+ mLifecycleCallback = lifecycleCallback;
+ return this;
+ }
+
+ /**
+ * Attach a callback interface for lifecycle events for this Endpoint with a specified
+ * executor
+ */
+ @NonNull
+ public Builder setLifecycleCallback(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull IHubEndpointLifecycleCallback lifecycleCallback) {
+ mLifecycleCallbackExecutor = executor;
+ mLifecycleCallback = lifecycleCallback;
+ return this;
+ }
+
+ /** Build the {@link HubEndpoint} object. */
+ @NonNull
+ public HubEndpoint build() {
+ return new HubEndpoint(
+ new HubEndpointInfo(mPackageName, mTag),
+ mLifecycleCallback,
+ mLifecycleCallbackExecutor);
+ }
+ }
+}
diff --git a/core/java/android/hardware/contexthub/HubEndpointInfo.aidl b/core/java/android/hardware/contexthub/HubEndpointInfo.aidl
new file mode 100644
index 0000000..025b2b1
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubEndpointInfo.aidl
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+/** @hide */
+parcelable HubEndpointInfo;
diff --git a/core/java/android/hardware/contexthub/HubEndpointInfo.java b/core/java/android/hardware/contexthub/HubEndpointInfo.java
new file mode 100644
index 0000000..ed8ff29
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubEndpointInfo.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Objects;
+
+/**
+ * Parcelable representing an endpoint from ContextHub or VendorHub.
+ *
+ * <p>HubEndpointInfo contains information about an endpoint, including its name, tag and other
+ * information. A HubEndpointInfo object can be used to accurately identify a specific endpoint.
+ * Application can use this object to identify and describe an endpoint.
+ *
+ * <p>See: {@link android.hardware.location.ContextHubManager#findEndpoints} for how to retrieve
+ * {@link HubEndpointInfo} for endpoints on a hub.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public final class HubEndpointInfo implements Parcelable {
+ /**
+ * A unique identifier for one endpoint. A unique identifier for one endpoint consists of two
+ * parts: (1) a unique long number for a hub and (2) a long number for the endpoint, unique
+ * within a hub. This class overrides equality methods and can be used to compare if two
+ * endpoints are the same.
+ */
+ public static class HubEndpointIdentifier {
+ private final long mEndpointId;
+ private final long mHubId;
+
+ /** @hide */
+ public HubEndpointIdentifier(long hubId, long endpointId) {
+ mEndpointId = endpointId;
+ mHubId = hubId;
+ }
+
+ /** @hide */
+ public HubEndpointIdentifier(android.hardware.contexthub.EndpointId halEndpointId) {
+ mEndpointId = halEndpointId.id;
+ mHubId = halEndpointId.hubId;
+ }
+
+ /** Get the endpoint portion of the identifier. */
+ public long getEndpoint() {
+ return mEndpointId;
+ }
+
+ /** Get the hub portion of the identifier. */
+ public long getHub() {
+ return mHubId;
+ }
+
+ /**
+ * Create an invalid endpoint id, to represent endpoint that are not yet registered with the
+ * HAL.
+ *
+ * @hide
+ */
+ public static HubEndpointIdentifier invalid() {
+ return new HubEndpointIdentifier(
+ android.hardware.contexthub.HubInfo.HUB_ID_INVALID,
+ android.hardware.contexthub.EndpointId.ENDPOINT_ID_INVALID);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mEndpointId, mHubId);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof HubEndpointIdentifier other)) {
+ return false;
+ }
+ if (other.mHubId != mHubId) {
+ return false;
+ }
+ return other.mEndpointId == mEndpointId;
+ }
+ }
+
+ private final HubEndpointIdentifier mId;
+ private final String mName;
+ @Nullable private final String mTag;
+
+ // TODO(b/375487784): Add Service/version and other information to this object
+
+ /** @hide */
+ public HubEndpointInfo(android.hardware.contexthub.EndpointInfo endpointInfo) {
+ mId = new HubEndpointIdentifier(endpointInfo.id.hubId, endpointInfo.id.id);
+ mName = endpointInfo.name;
+ mTag = endpointInfo.tag;
+ }
+
+ /** @hide */
+ public HubEndpointInfo(String name, @Nullable String tag) {
+ mId = HubEndpointIdentifier.invalid();
+ mName = name;
+ mTag = tag;
+ }
+
+ private HubEndpointInfo(Parcel in) {
+ long hubId = in.readLong();
+ long endpointId = in.readLong();
+ mName = in.readString();
+ mTag = in.readString();
+
+ mId = new HubEndpointIdentifier(hubId, endpointId);
+ }
+
+ /** Parcel implementation details */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /** Parcel implementation details */
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeLong(mId.getHub());
+ dest.writeLong(mId.getEndpoint());
+ dest.writeString(mName);
+ dest.writeString(mTag);
+ }
+
+ /** Get a unique identifier for this endpoint. */
+ @NonNull
+ public HubEndpointIdentifier getIdentifier() {
+ return mId;
+ }
+
+ /** Get the human-readable name of this endpoint (for debugging purposes). */
+ @NonNull
+ public String getName() {
+ return mName;
+ }
+
+ /**
+ * Get the tag that further identifies the submodule that created this endpoint. For example, a
+ * single application could provide multiple endpoints. These endpoints will share the same
+ * name, but will have different tags. This tag can be used to identify the submodule within the
+ * application that provided the endpoint.
+ */
+ @Nullable
+ public String getTag() {
+ return mTag;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder out = new StringBuilder();
+ out.append("Endpoint [0x");
+ out.append(Long.toHexString(mId.getEndpoint()));
+ out.append("@ Hub 0x");
+ out.append(Long.toHexString(mId.getHub()));
+ out.append("] Name=");
+ out.append(mName);
+ out.append(", Tag=");
+ out.append(mTag);
+ return out.toString();
+ }
+
+ public static final @android.annotation.NonNull Creator<HubEndpointInfo> CREATOR =
+ new Creator<>() {
+ public HubEndpointInfo createFromParcel(Parcel in) {
+ return new HubEndpointInfo(in);
+ }
+
+ public HubEndpointInfo[] newArray(int size) {
+ return new HubEndpointInfo[size];
+ }
+ };
+}
diff --git a/core/java/android/hardware/contexthub/HubEndpointSession.java b/core/java/android/hardware/contexthub/HubEndpointSession.java
new file mode 100644
index 0000000..ef989f1f
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubEndpointSession.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+import android.util.CloseGuard;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * An object representing a communication session between two different hub endpoints.
+ *
+ * <p>A published enpoint can receive
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public class HubEndpointSession implements AutoCloseable {
+ private final CloseGuard mCloseGuard = new CloseGuard();
+
+ private final int mId;
+
+ // TODO(b/377717509): Implement Message sending API & interface
+ @NonNull private final HubEndpoint mHubEndpoint;
+ @NonNull private final HubEndpointInfo mInitiator;
+ @NonNull private final HubEndpointInfo mDestination;
+
+ private final AtomicBoolean mIsClosed = new AtomicBoolean(true);
+
+ /** @hide */
+ HubEndpointSession(
+ int id,
+ @NonNull HubEndpoint hubEndpoint,
+ @NonNull HubEndpointInfo destination,
+ @NonNull HubEndpointInfo initiator) {
+ mId = id;
+ mHubEndpoint = hubEndpoint;
+ mDestination = destination;
+ mInitiator = initiator;
+ }
+
+ /** @hide */
+ public int getId() {
+ return mId;
+ }
+
+ /** @hide */
+ public void setOpened() {
+ mIsClosed.set(false);
+ mCloseGuard.open("close");
+ }
+
+ /** @hide */
+ public void setClosed() {
+ mIsClosed.set(true);
+ mCloseGuard.close();
+ }
+
+ /**
+ * Closes the connection for this session between an endpoint and the Context Hub Service.
+ *
+ * <p>When this function is invoked, the messaging associated with this session is invalidated.
+ * All futures messages targeted for this client are dropped.
+ */
+ public void close() {
+ if (!mIsClosed.getAndSet(true)) {
+ mCloseGuard.close();
+ mHubEndpoint.closeSession(this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("Session [");
+ stringBuilder.append(mId);
+ stringBuilder.append("]: [");
+ stringBuilder.append(mInitiator);
+ stringBuilder.append("]->[");
+ stringBuilder.append(mDestination);
+ stringBuilder.append("]");
+ return stringBuilder.toString();
+ }
+
+ /** @hide */
+ protected void finalize() throws Throwable {
+ try {
+ // Note that guard could be null if the constructor threw.
+ if (mCloseGuard != null) {
+ mCloseGuard.warnIfOpen();
+ }
+ close();
+ } finally {
+ super.finalize();
+ }
+ }
+}
diff --git a/core/java/android/hardware/contexthub/HubEndpointSessionResult.java b/core/java/android/hardware/contexthub/HubEndpointSessionResult.java
new file mode 100644
index 0000000..1f2bdb9
--- /dev/null
+++ b/core/java/android/hardware/contexthub/HubEndpointSessionResult.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+
+/**
+ * Return type of {@link IHubEndpointLifecycleCallback#onSessionOpenRequest}. The value determines
+ * whether a open session request from the remote is accepted or not.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public class HubEndpointSessionResult {
+ private final boolean mAccepted;
+
+ @Nullable private final String mReason;
+
+ private HubEndpointSessionResult(boolean accepted, @Nullable String reason) {
+ mAccepted = accepted;
+ mReason = reason;
+ }
+
+ /**
+ * Retrieve the decision of the session request.
+ *
+ * @return Whether a session request was accepted or not, previously set with {@link #accept()}
+ * or {@link #reject(String)}.
+ */
+ public boolean isAccepted() {
+ return mAccepted;
+ }
+
+ /**
+ * Retrieve the decision of the session request.
+ *
+ * @return The reason previously set in {@link #reject(String)}. If the result was {@link
+ * #accept()}, the reason will be null.
+ */
+ @Nullable
+ public String getReason() {
+ return mReason;
+ }
+
+ /** Accept the request. */
+ @NonNull
+ public static HubEndpointSessionResult accept() {
+ return new HubEndpointSessionResult(true, null);
+ }
+
+ /**
+ * Reject the request with a reason.
+ *
+ * @param reason Reason why the request was rejected, for diagnostic purposes.
+ */
+ @NonNull
+ public static HubEndpointSessionResult reject(@NonNull String reason) {
+ return new HubEndpointSessionResult(false, reason);
+ }
+}
diff --git a/core/java/android/hardware/contexthub/IContextHubEndpoint.aidl b/core/java/android/hardware/contexthub/IContextHubEndpoint.aidl
new file mode 100644
index 0000000..61e60e3
--- /dev/null
+++ b/core/java/android/hardware/contexthub/IContextHubEndpoint.aidl
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2024 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.hardware.contexthub;
+
+import android.hardware.contexthub.HubEndpointInfo;
+
+/**
+ * @hide
+ */
+interface IContextHubEndpoint {
+ /**
+ * Retrieve the up-to-date EndpointInfo, with assigned endpoint id.
+ */
+ HubEndpointInfo getAssignedHubEndpointInfo();
+
+ /**
+ * Request system service to open a session with a specific destination.
+ *
+ * @param destination A valid HubEndpointInfo representing the destination.
+ *
+ * @throws IllegalArgumentException If the HubEndpointInfo is not valid.
+ * @throws IllegalStateException If there are too many opened sessions.
+ */
+ int openSession(in HubEndpointInfo destination);
+
+ /**
+ * Request system service to close a specific session
+ *
+ * @param sessionId An integer identifying the session, assigned by system service
+ * @param reason An integer identifying the reason
+ *
+ * @throws IllegalStateException If the session wasn't opened.
+ */
+ void closeSession(int sessionId, int reason);
+
+ /**
+ * Callback when a session is opened. This callback is the status callback for a previous
+ * IContextHubEndpointCallback.onSessionOpenRequest().
+ *
+ * @param sessionId The integer representing the communication session, previously set in
+ * onSessionOpenRequest().
+ *
+ * @throws IllegalStateException If the session wasn't opened.
+ */
+ void openSessionRequestComplete(int sessionId);
+
+ /**
+ * Unregister this endpoint from the HAL, invalidate the EndpointInfo previously assigned.
+ */
+ void unregister();
+}
diff --git a/core/java/android/hardware/contexthub/IContextHubEndpointCallback.aidl b/core/java/android/hardware/contexthub/IContextHubEndpointCallback.aidl
new file mode 100644
index 0000000..5656a4a
--- /dev/null
+++ b/core/java/android/hardware/contexthub/IContextHubEndpointCallback.aidl
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2024 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.hardware.contexthub;
+
+import android.hardware.contexthub.HubEndpointInfo;
+
+/**
+ * @hide
+ */
+oneway interface IContextHubEndpointCallback {
+ /**
+ * Request from system service to open a session, requested by a specific initiator.
+ *
+ * @param sessionId An integer identifying the session, assigned by the initiator
+ * @param initiator HubEndpointInfo representing the requester
+ */
+ void onSessionOpenRequest(int sessionId, in HubEndpointInfo initiator);
+
+ /**
+ * Request from system service to close a specific session
+ *
+ * @param sessionId An integer identifying the session
+ * @param reason An integer identifying the reason
+ */
+ void onSessionClosed(int sessionId, int reason);
+
+
+ /**
+ * Notifies the system service that the session requested by IContextHubEndpoint.openSession
+ * is ready to use.
+ *
+ * @param sessionId The integer representing the communication session, previously set in
+ * IContextHubEndpoint.openSession(). This id is assigned by the HAL.
+ */
+ void onSessionOpenComplete(int sessionId);
+}
diff --git a/core/java/android/hardware/contexthub/IHubEndpointLifecycleCallback.java b/core/java/android/hardware/contexthub/IHubEndpointLifecycleCallback.java
new file mode 100644
index 0000000..5bd3c0e
--- /dev/null
+++ b/core/java/android/hardware/contexthub/IHubEndpointLifecycleCallback.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2024 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.hardware.contexthub;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.chre.flags.Flags;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Interface for listening to lifecycle events of a hub endpoint.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_OFFLOAD_API)
+public interface IHubEndpointLifecycleCallback {
+ /** Unknown reason. */
+ int REASON_UNSPECIFIED = 0;
+
+ /** The peer rejected the request to open this endpoint session. */
+ int REASON_OPEN_ENDPOINT_SESSION_REQUEST_REJECTED = 3;
+
+ /** The peer closed this endpoint session. */
+ int REASON_CLOSE_ENDPOINT_SESSION_REQUESTED = 4;
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ REASON_UNSPECIFIED,
+ REASON_OPEN_ENDPOINT_SESSION_REQUEST_REJECTED,
+ REASON_CLOSE_ENDPOINT_SESSION_REQUESTED,
+ })
+ @interface EndpointLifecycleReason {}
+
+ /**
+ * Called when an endpoint is requesting a session be opened with another endpoint.
+ *
+ * @param requester The {@link HubEndpointInfo} object representing the requester
+ */
+ @NonNull
+ HubEndpointSessionResult onSessionOpenRequest(@NonNull HubEndpointInfo requester);
+
+ /**
+ * Called when a communication session is opened and ready to be used.
+ *
+ * @param session The {@link HubEndpointSession} object that can be used for communication
+ */
+ void onSessionOpened(@NonNull HubEndpointSession session);
+
+ /**
+ * Called when a communication session is requested to be closed, or the peer endpoint rejected
+ * the session open request.
+ *
+ * @param session The {@link HubEndpointSession} object that is now closed and shouldn't be
+ * used.
+ * @param reason The reason why this session was closed.
+ */
+ void onSessionClosed(@NonNull HubEndpointSession session, @EndpointLifecycleReason int reason);
+}
diff --git a/core/java/android/hardware/contexthub/OWNERS b/core/java/android/hardware/contexthub/OWNERS
new file mode 100644
index 0000000..a65a2bf
--- /dev/null
+++ b/core/java/android/hardware/contexthub/OWNERS
@@ -0,0 +1,2 @@
+# ContextHub team
+file:platform/system/chre:/OWNERS
diff --git a/core/java/android/hardware/display/DisplayManagerGlobal.java b/core/java/android/hardware/display/DisplayManagerGlobal.java
index be710b1..1e66bee 100644
--- a/core/java/android/hardware/display/DisplayManagerGlobal.java
+++ b/core/java/android/hardware/display/DisplayManagerGlobal.java
@@ -17,6 +17,7 @@
package android.hardware.display;
+import static android.app.PropertyInvalidatedCache.MODULE_SYSTEM;
import static android.hardware.display.DisplayManager.EventFlag;
import static android.Manifest.permission.MANAGE_DISPLAYS;
import static android.view.Display.HdrCapabilities.HdrType;
@@ -188,9 +189,11 @@
}
private PropertyInvalidatedCache<Integer, DisplayInfo> mDisplayCache =
- new PropertyInvalidatedCache<Integer, DisplayInfo>(
- 8, // size of display cache
- CACHE_KEY_DISPLAY_INFO_PROPERTY) {
+ new PropertyInvalidatedCache<>(
+ new PropertyInvalidatedCache.Args(MODULE_SYSTEM)
+ .maxEntries(8).api(CACHE_KEY_DISPLAY_INFO_API).isolateUids(false),
+ CACHE_KEY_DISPLAY_INFO_API, null) {
+
@Override
public DisplayInfo recompute(Integer id) {
try {
@@ -1514,18 +1517,17 @@
}
/**
- * Name of the property containing a unique token which changes every time we update the
- * system's display configuration.
+ * The API portion of the key that identifies the unique PropertyInvalidatedCache token which
+ * changes every time we update the system's display configuration.
*/
- public static final String CACHE_KEY_DISPLAY_INFO_PROPERTY =
- PropertyInvalidatedCache.createSystemCacheKey("display_info");
+ private static final String CACHE_KEY_DISPLAY_INFO_API = "display_info";
/**
* Invalidates the contents of the display info cache for all applications. Can only
* be called by system_server.
*/
public static void invalidateLocalDisplayInfoCaches() {
- PropertyInvalidatedCache.invalidateCache(CACHE_KEY_DISPLAY_INFO_PROPERTY);
+ PropertyInvalidatedCache.invalidateCache(MODULE_SYSTEM, CACHE_KEY_DISPLAY_INFO_API);
}
/**
diff --git a/core/java/android/hardware/location/ContextHubManager.java b/core/java/android/hardware/location/ContextHubManager.java
index 494bfc9..b2c3bb8 100644
--- a/core/java/android/hardware/location/ContextHubManager.java
+++ b/core/java/android/hardware/location/ContextHubManager.java
@@ -34,6 +34,10 @@
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.contexthub.ErrorCode;
+import android.hardware.contexthub.HubDiscoveryInfo;
+import android.hardware.contexthub.HubEndpoint;
+import android.hardware.contexthub.HubEndpointInfo;
+import android.hardware.contexthub.IHubEndpointLifecycleCallback;
import android.os.Handler;
import android.os.HandlerExecutor;
import android.os.Looper;
@@ -42,6 +46,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
@@ -679,6 +684,29 @@
}
/**
+ * Find a list of endpoints that matches a specific ID.
+ *
+ * @param endpointId Statically generated ID for an endpoint.
+ * @return A list of {@link HubDiscoveryInfo} objects that represents the result of discovery.
+ */
+ @FlaggedApi(Flags.FLAG_OFFLOAD_API)
+ @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @NonNull
+ public List<HubDiscoveryInfo> findEndpoints(long endpointId) {
+ try {
+ List<HubEndpointInfo> endpointInfos = mService.findEndpoints(endpointId);
+ List<HubDiscoveryInfo> results = new ArrayList<>(endpointInfos.size());
+ // Wrap with result type
+ for (HubEndpointInfo endpointInfo : endpointInfos) {
+ results.add(new HubDiscoveryInfo(endpointInfo));
+ }
+ return results;
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Set a callback to receive messages from the context hub
*
* @param callback Callback object
@@ -1010,6 +1038,55 @@
}
/**
+ * Registers an endpoint and its callback with the Context Hub Service.
+ *
+ * <p>An endpoint is registered with the Context Hub Service and published to the HAL. When the
+ * registration succeeds, the endpoint can receive notifications through the provided callback.
+ *
+ * @param hubEndpoint {@link HubEndpoint} object created by {@link HubEndpoint.Builder}
+ */
+ @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @FlaggedApi(Flags.FLAG_OFFLOAD_API)
+ public void registerEndpoint(@NonNull HubEndpoint hubEndpoint) {
+ hubEndpoint.register(mService);
+ }
+
+ /**
+ * Use a registered endpoint to connect to another endpoint (destination).
+ *
+ * <p>Context Hub Service will create the endpoint session and notify the registered endpoint.
+ * The registered endpoint will receive callbacks on its {@link IHubEndpointLifecycleCallback}
+ * object regarding the lifecycle events of the session
+ *
+ * @param hubEndpoint {@link HubEndpoint} object previously registered via {@link
+ * ContextHubManager#registerEndpoint(HubEndpoint)}.
+ * @param destination {@link HubEndpointInfo} object that represents an endpoint from previous
+ * endpoint discovery results (e.g. from {@link ContextHubManager#findEndpoints(long)}).
+ */
+ @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @FlaggedApi(Flags.FLAG_OFFLOAD_API)
+ public void openSession(
+ @NonNull HubEndpoint hubEndpoint, @NonNull HubEndpointInfo destination) {
+ hubEndpoint.openSession(destination);
+ }
+
+ /**
+ * Unregisters an endpoint and its callback with the Context Hub Service.
+ *
+ * <p>An endpoint is unregistered from the HAL. The endpoint object will no longer receive
+ * notification through the provided callback.
+ *
+ * @param hubEndpoint {@link HubEndpoint} object created by {@link HubEndpoint.Builder}. This
+ * should match a previously registered object via {@link
+ * ContextHubManager#registerEndpoint(HubEndpoint)}.
+ */
+ @RequiresPermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @FlaggedApi(Flags.FLAG_OFFLOAD_API)
+ public void unregisterEndpoint(@NonNull HubEndpoint hubEndpoint) {
+ hubEndpoint.unregister();
+ }
+
+ /**
* Queries for the list of preloaded nanoapp IDs on the system.
*
* @param hubInfo The Context Hub to query a list of nanoapp IDs from.
@@ -1168,6 +1245,7 @@
requireNonNull(mainLooper, "mainLooper cannot be null");
mService = service;
mMainLooper = mainLooper;
+
try {
mService.registerCallback(mClientCallback);
} catch (RemoteException e) {
diff --git a/core/java/android/hardware/location/IContextHubService.aidl b/core/java/android/hardware/location/IContextHubService.aidl
index b0cc763..5128723 100644
--- a/core/java/android/hardware/location/IContextHubService.aidl
+++ b/core/java/android/hardware/location/IContextHubService.aidl
@@ -18,17 +18,20 @@
// Declare any non-default types here with import statements
import android.app.PendingIntent;
-import android.hardware.location.HubInfo;
+import android.hardware.contexthub.HubEndpointInfo;
+import android.hardware.contexthub.IContextHubEndpoint;
+import android.hardware.contexthub.IContextHubEndpointCallback;
import android.hardware.location.ContextHubInfo;
import android.hardware.location.ContextHubMessage;
-import android.hardware.location.NanoApp;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppFilter;
-import android.hardware.location.NanoAppInstanceInfo;
+import android.hardware.location.HubInfo;
import android.hardware.location.IContextHubCallback;
import android.hardware.location.IContextHubClient;
import android.hardware.location.IContextHubClientCallback;
import android.hardware.location.IContextHubTransactionCallback;
+import android.hardware.location.NanoApp;
+import android.hardware.location.NanoAppBinary;
+import android.hardware.location.NanoAppFilter;
+import android.hardware.location.NanoAppInstanceInfo;
/**
* @hide
@@ -122,4 +125,12 @@
// Enables or disables test mode
@EnforcePermission("ACCESS_CONTEXT_HUB")
boolean setTestMode(in boolean enable);
+
+ // Finds all endpoints that havea specific ID
+ @EnforcePermission("ACCESS_CONTEXT_HUB")
+ List<HubEndpointInfo> findEndpoints(long endpointId);
+
+ // Register an endpoint with the context hub
+ @EnforcePermission("ACCESS_CONTEXT_HUB")
+ IContextHubEndpoint registerEndpoint(in HubEndpointInfo pendingEndpointInfo, in IContextHubEndpointCallback callback);
}
diff --git a/core/java/android/inputmethodservice/AbstractInputMethodService.java b/core/java/android/inputmethodservice/AbstractInputMethodService.java
index 26308f6..4bc5bd2 100644
--- a/core/java/android/inputmethodservice/AbstractInputMethodService.java
+++ b/core/java/android/inputmethodservice/AbstractInputMethodService.java
@@ -16,9 +16,6 @@
package android.inputmethodservice;
-import static android.view.inputmethod.Flags.FLAG_VERIFY_KEY_EVENT;
-
-import android.annotation.FlaggedApi;
import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -196,12 +193,6 @@
}
}
- @FlaggedApi(FLAG_VERIFY_KEY_EVENT)
- @Override
- public boolean onShouldVerifyKeyEvent(@NonNull KeyEvent event) {
- return AbstractInputMethodService.this.onShouldVerifyKeyEvent(event);
- }
-
/**
* Take care of dispatching incoming trackball events to the appropriate
* callbacks on the service, and tell the client when this is done.
@@ -317,14 +308,6 @@
return false;
}
- /**
- * @see InputMethodService#onShouldVerifyKeyEvent(KeyEvent)
- */
- @FlaggedApi(FLAG_VERIFY_KEY_EVENT)
- public boolean onShouldVerifyKeyEvent(@NonNull KeyEvent event) {
- return false;
- }
-
/** @hide */
@Override
public final int getWindowType() {
diff --git a/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java b/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java
index 9b37533..62b131a 100644
--- a/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java
+++ b/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java
@@ -16,16 +16,12 @@
package android.inputmethodservice;
-import static android.view.inputmethod.Flags.verifyKeyEvent;
-
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Rect;
-import android.hardware.input.InputManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
-import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;
import android.view.InputChannel;
@@ -45,8 +41,6 @@
import com.android.internal.os.HandlerCaller;
import com.android.internal.os.SomeArgs;
-import java.util.Objects;
-
class IInputMethodSessionWrapper extends IInputMethodSession.Stub
implements HandlerCaller.Callback {
private static final String TAG = "InputMethodWrapper";
@@ -62,7 +56,6 @@
private static final int DO_REMOVE_IME_SURFACE = 130;
private static final int DO_FINISH_INPUT = 140;
private static final int DO_INVALIDATE_INPUT = 150;
- private final Context mContext;
@UnsupportedAppUsage
@@ -73,7 +66,6 @@
public IInputMethodSessionWrapper(Context context,
InputMethodSession inputMethodSession, InputChannel channel) {
- mContext = context;
mCaller = new HandlerCaller(context, null,
this, true /*asyncHandler*/);
mInputMethodSession = inputMethodSession;
@@ -241,8 +233,6 @@
}
private final class ImeInputEventReceiver extends InputEventReceiver
implements InputMethodSession.EventCallback {
- // Time after which a KeyEvent is invalid
- private static final long KEY_EVENT_ALLOW_PERIOD_MS = 100L;
private final SparseArray<InputEvent> mPendingEvents = new SparseArray<InputEvent>();
public ImeInputEventReceiver(InputChannel inputChannel, Looper looper) {
@@ -257,23 +247,10 @@
return;
}
- if (event instanceof KeyEvent keyEvent && needsVerification(keyEvent)) {
- // any KeyEvent with modifiers (e.g. Ctrl/Alt/Fn) must be verified that
- // they originated from system.
- InputManager im = mContext.getSystemService(InputManager.class);
- Objects.requireNonNull(im);
- final long age = SystemClock.uptimeMillis() - keyEvent.getEventTime();
- if (age >= KEY_EVENT_ALLOW_PERIOD_MS && im.verifyInputEvent(keyEvent) == null) {
- Log.w(TAG, "Unverified or Invalid KeyEvent injected into IME. Dropping "
- + keyEvent);
- finishInputEvent(event, false /* handled */);
- return;
- }
- }
-
final int seq = event.getSequenceNumber();
mPendingEvents.put(seq, event);
- if (event instanceof KeyEvent keyEvent) {
+ if (event instanceof KeyEvent) {
+ KeyEvent keyEvent = (KeyEvent)event;
mInputMethodSession.dispatchKeyEvent(seq, keyEvent, this);
} else {
MotionEvent motionEvent = (MotionEvent)event;
@@ -294,21 +271,5 @@
finishInputEvent(event, handled);
}
}
-
- private boolean hasKeyModifiers(KeyEvent event) {
- if (event.hasNoModifiers()) {
- return false;
- }
- return event.hasModifiers(KeyEvent.META_CTRL_ON)
- || event.hasModifiers(KeyEvent.META_ALT_ON)
- || event.hasModifiers(KeyEvent.KEYCODE_FUNCTION);
- }
-
- private boolean needsVerification(KeyEvent event) {
- //TODO(b/331730488): Handle a11y events as well.
- return verifyKeyEvent()
- && (hasKeyModifiers(event)
- || mInputMethodSession.onShouldVerifyKeyEvent(event));
- }
}
}
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index a8fde4a..dadb5c38 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -56,7 +56,6 @@
import static android.view.inputmethod.ConnectionlessHandwritingCallback.CONNECTIONLESS_HANDWRITING_ERROR_UNSUPPORTED;
import static android.view.inputmethod.Flags.FLAG_CONNECTIONLESS_HANDWRITING;
import static android.view.inputmethod.Flags.FLAG_IME_SWITCHER_REVAMP_API;
-import static android.view.inputmethod.Flags.FLAG_VERIFY_KEY_EVENT;
import static android.view.inputmethod.Flags.ctrlShiftShortcut;
import static android.view.inputmethod.Flags.predictiveBackIme;
@@ -3736,23 +3735,6 @@
}
/**
- * Received by the IME before dispatch to {@link #onKeyDown(int, KeyEvent)} to let the system
- * know if the {@link KeyEvent} needs to be verified that it originated from the system.
- * {@link KeyEvent}s may originate from outside of the system and any sensitive keys should be
- * marked for verification. One example of this could be using key shortcuts for switching to
- * another IME.
- *
- * @param keyEvent the event that may need verification.
- * @return {@code true} if {@link KeyEvent} should have its HMAC verified before dispatch,
- * {@code false} otherwise.
- */
- @FlaggedApi(FLAG_VERIFY_KEY_EVENT)
- @Override
- public boolean onShouldVerifyKeyEvent(@NonNull KeyEvent keyEvent) {
- return false;
- }
-
- /**
* Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
* KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
* the event).
diff --git a/core/java/android/net/vcn/VcnFrameworkInitializer.java b/core/java/android/net/ConnectivityFrameworkInitializerBaklava.java
similarity index 86%
rename from core/java/android/net/vcn/VcnFrameworkInitializer.java
rename to core/java/android/net/ConnectivityFrameworkInitializerBaklava.java
index 8cb213b..1f0fa92 100644
--- a/core/java/android/net/vcn/VcnFrameworkInitializer.java
+++ b/core/java/android/net/ConnectivityFrameworkInitializerBaklava.java
@@ -14,15 +14,21 @@
* limitations under the License.
*/
-package android.net.vcn;
+package android.net;
+import static android.net.vcn.Flags.FLAG_MAINLINE_VCN_MODULE_API;
+
+import android.annotation.FlaggedApi;
import android.annotation.Nullable;
+import android.annotation.SystemApi;
import android.app.SystemServiceRegistry;
import android.compat.Compatibility;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
import android.content.Context;
import android.content.pm.PackageManager;
+import android.net.vcn.IVcnManagementService;
+import android.net.vcn.VcnManager;
import android.os.Build;
import android.os.SystemProperties;
@@ -31,8 +37,9 @@
*
* @hide
*/
-// TODO: Expose it as @SystemApi(client = MODULE_LIBRARIES)
-public final class VcnFrameworkInitializer {
+@FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+public final class ConnectivityFrameworkInitializerBaklava {
/**
* Starting with {@link VANILLA_ICE_CREAM}, Telephony feature flags (e.g. {@link
* PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}) are being checked before returning managers
@@ -55,7 +62,7 @@
*/
private static final int VENDOR_API_FOR_ANDROID_V = 202404;
- private VcnFrameworkInitializer() {}
+ private ConnectivityFrameworkInitializerBaklava() {}
// Suppressing AndroidFrameworkCompatChange because we're querying vendor
// partition SDK level, not application's target SDK version (which BTW we
@@ -86,7 +93,10 @@
*
* @throws IllegalStateException if this is called anywhere besides {@link
* SystemServiceRegistry}.
+ * @hide
*/
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static void registerServiceWrappers() {
SystemServiceRegistry.registerContextAwareService(
VcnManager.VCN_MANAGEMENT_SERVICE_STRING,
diff --git a/core/java/android/net/vcn/VcnGatewayConnectionConfig.java b/core/java/android/net/vcn/VcnGatewayConnectionConfig.java
index af93c96..3219ce8 100644
--- a/core/java/android/net/vcn/VcnGatewayConnectionConfig.java
+++ b/core/java/android/net/vcn/VcnGatewayConnectionConfig.java
@@ -16,6 +16,7 @@
package android.net.vcn;
import static android.net.ipsec.ike.IkeSessionParams.IKE_OPTION_MOBIKE;
+import static android.net.vcn.Flags.FLAG_MAINLINE_VCN_MODULE_API;
import static android.net.vcn.Flags.FLAG_SAFE_MODE_CONFIG;
import static android.net.vcn.VcnUnderlyingNetworkTemplate.MATCH_REQUIRED;
@@ -82,7 +83,15 @@
* </ul>
*/
public final class VcnGatewayConnectionConfig {
- /** @hide */
+ /**
+ * Minimum NAT timeout not set.
+ *
+ * <p>When the timeout is not set, the device will automatically choose a keepalive interval and
+ * may reduce the keepalive frequency for power-optimization.
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ // This constant does not represent a minimum value. It indicates the value is not configured.
+ @SuppressLint("MinMaxConstant")
public static final int MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET = -1;
/** @hide */
@@ -773,7 +782,7 @@
*
* @param minUdpPort4500NatTimeoutSeconds the maximum keepalive timeout supported by the VCN
* Gateway Connection, generally the minimum duration a NAT mapping is cached on the VCN
- * Gateway.
+ * Gateway; or {@link MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET} to clear this value.
* @return this {@link Builder} instance, for chaining
*/
@NonNull
@@ -781,8 +790,10 @@
@IntRange(from = MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS)
int minUdpPort4500NatTimeoutSeconds) {
Preconditions.checkArgument(
- minUdpPort4500NatTimeoutSeconds >= MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS,
- "Timeout must be at least 120s");
+ minUdpPort4500NatTimeoutSeconds == MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET
+ || minUdpPort4500NatTimeoutSeconds
+ >= MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS,
+ "Timeout must be at least 120s or MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET");
mMinUdpPort4500NatTimeoutSeconds = minUdpPort4500NatTimeoutSeconds;
return this;
diff --git a/core/java/android/net/vcn/VcnTransportInfo.java b/core/java/android/net/vcn/VcnTransportInfo.java
index 1fc91ee..3638429 100644
--- a/core/java/android/net/vcn/VcnTransportInfo.java
+++ b/core/java/android/net/vcn/VcnTransportInfo.java
@@ -17,13 +17,16 @@
package android.net.vcn;
import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
+import static android.net.vcn.Flags.FLAG_MAINLINE_VCN_MODULE_API;
import static android.net.vcn.VcnGatewayConnectionConfig.MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS;
import static android.net.vcn.VcnGatewayConnectionConfig.MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+import android.annotation.FlaggedApi;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SystemApi;
import android.net.NetworkCapabilities;
import android.net.TransportInfo;
import android.net.wifi.WifiInfo;
@@ -52,23 +55,29 @@
* @hide
*/
// TODO: Do not store WifiInfo and subscription ID in VcnTransportInfo anymore
-public class VcnTransportInfo implements TransportInfo, Parcelable {
+@FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+public final class VcnTransportInfo implements TransportInfo, Parcelable {
@Nullable private final WifiInfo mWifiInfo;
private final int mSubId;
private final int mMinUdpPort4500NatTimeoutSeconds;
+ /** @hide */
public VcnTransportInfo(@NonNull WifiInfo wifiInfo) {
this(wifiInfo, INVALID_SUBSCRIPTION_ID, MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET);
}
+ /** @hide */
public VcnTransportInfo(@NonNull WifiInfo wifiInfo, int minUdpPort4500NatTimeoutSeconds) {
this(wifiInfo, INVALID_SUBSCRIPTION_ID, minUdpPort4500NatTimeoutSeconds);
}
+ /** @hide */
public VcnTransportInfo(int subId) {
this(null /* wifiInfo */, subId, MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET);
}
+ /** @hide */
public VcnTransportInfo(int subId, int minUdpPort4500NatTimeoutSeconds) {
this(null /* wifiInfo */, subId, minUdpPort4500NatTimeoutSeconds);
}
@@ -86,6 +95,7 @@
* <p>If the underlying Network for the associated VCN is Cellular, returns null.
*
* @return the WifiInfo if there is an underlying WiFi connection, else null.
+ * @hide
*/
@Nullable
public WifiInfo getWifiInfo() {
@@ -100,17 +110,27 @@
*
* @return the Subscription ID if a cellular underlying Network is present, else {@link
* android.telephony.SubscriptionManager#INVALID_SUBSCRIPTION_ID}.
+ * @hide
*/
public int getSubId() {
return mSubId;
}
/**
- * Get the VCN provided UDP port 4500 NAT timeout
+ * Get the minimum duration that the VCN Gateway guarantees to preserve a NAT mapping.
*
- * @return the UDP 4500 NAT timeout, or
+ * <p>To ensure uninterrupted connectivity, the device must send keepalive packets before the
+ * timeout. Failure to do so may result in the mapping being cleared and connection termination.
+ * This value is used as a power-optimization hint for other IKEv2/IPsec use cases (e.g. VPNs,
+ * or IWLAN) to reduce the necessary keepalive frequency, thus conserving power and data.
+ *
+ * @return the minimum duration that the VCN Gateway guarantees to preserve a NAT mapping, or
* VcnGatewayConnectionConfig.MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET if not set.
+ * @see VcnGatewayConnectionConfig.Builder#setMinUdpPort4500NatTimeoutSeconds(int)
+ * @hide
*/
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public int getMinUdpPort4500NatTimeoutSeconds() {
return mMinUdpPort4500NatTimeoutSeconds;
}
@@ -129,12 +149,21 @@
&& mMinUdpPort4500NatTimeoutSeconds == that.mMinUdpPort4500NatTimeoutSeconds;
}
- /** {@inheritDoc} */
+ /**
+ * {@inheritDoc}
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@Override
public int describeContents() {
return 0;
}
+ /** @hide */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@Override
@NonNull
public TransportInfo makeCopy(long redactions) {
@@ -149,6 +178,9 @@
mMinUdpPort4500NatTimeoutSeconds);
}
+ /** @hide */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@Override
public long getApplicableRedactions() {
long redactions = REDACT_FOR_NETWORK_SETTINGS;
@@ -161,7 +193,13 @@
return redactions;
}
- /** {@inheritDoc} */
+ /**
+ * {@inheritDoc}
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeInt(mSubId);
@@ -174,7 +212,13 @@
return "VcnTransportInfo { mWifiInfo = " + mWifiInfo + ", mSubId = " + mSubId + " }";
}
- /** Implement the Parcelable interface */
+ /**
+ * Implement the Parcelable interface
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final @NonNull Creator<VcnTransportInfo> CREATOR =
new Creator<VcnTransportInfo>() {
public VcnTransportInfo createFromParcel(Parcel in) {
@@ -201,37 +245,63 @@
}
};
- /** This class can be used to construct a {@link VcnTransportInfo}. */
+ /**
+ * This class can be used to construct a {@link VcnTransportInfo}.
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final class Builder {
private int mMinUdpPort4500NatTimeoutSeconds = MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET;
- /** Construct Builder */
+ /**
+ * Construct Builder
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public Builder() {}
/**
- * Sets the maximum supported IKEv2/IPsec NATT keepalive timeout.
+ * Set the minimum duration that the VCN Gateway guarantees to preserve a NAT mapping.
*
* <p>This is used as a power-optimization hint for other IKEv2/IPsec use cases (e.g. VPNs,
* or IWLAN) to reduce the necessary keepalive frequency, thus conserving power and data.
*
- * @param minUdpPort4500NatTimeoutSeconds the maximum keepalive timeout supported by the VCN
- * Gateway Connection, generally the minimum duration a NAT mapping is cached on the VCN
- * Gateway.
+ * @param minUdpPort4500NatTimeoutSeconds the minimum duration that the VCN Gateway
+ * guarantees to preserve a NAT mapping, or {@link MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET}
+ * to clear this value. To ensure uninterrupted connectivity, the device must send
+ * keepalive packets within this interval. Failure to do so may result in the mapping
+ * being cleared and connection termination.
* @return this {@link Builder} instance, for chaining
+ * @see VcnGatewayConnectionConfig.Builder#setMinUdpPort4500NatTimeoutSeconds(int)
+ * @hide
*/
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@NonNull
public Builder setMinUdpPort4500NatTimeoutSeconds(
@IntRange(from = MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS)
int minUdpPort4500NatTimeoutSeconds) {
Preconditions.checkArgument(
- minUdpPort4500NatTimeoutSeconds >= MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS,
- "Timeout must be at least 120s");
+ minUdpPort4500NatTimeoutSeconds == MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET
+ || minUdpPort4500NatTimeoutSeconds
+ >= MIN_UDP_PORT_4500_NAT_TIMEOUT_SECONDS,
+ "Timeout must be at least 120s or MIN_UDP_PORT_4500_NAT_TIMEOUT_UNSET");
mMinUdpPort4500NatTimeoutSeconds = minUdpPort4500NatTimeoutSeconds;
return Builder.this;
}
- /** Build a VcnTransportInfo instance */
+ /**
+ * Build a VcnTransportInfo instance
+ *
+ * @hide
+ */
+ @FlaggedApi(FLAG_MAINLINE_VCN_MODULE_API)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@NonNull
public VcnTransportInfo build() {
return new VcnTransportInfo(
diff --git a/core/java/android/os/CombinedMessageQueue/MessageQueue.java b/core/java/android/os/CombinedMessageQueue/MessageQueue.java
index 7529ab9..9ad2e7f 100644
--- a/core/java/android/os/CombinedMessageQueue/MessageQueue.java
+++ b/core/java/android/os/CombinedMessageQueue/MessageQueue.java
@@ -19,6 +19,8 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.TestApi;
+import android.app.ActivityThread;
+import android.app.Instrumentation;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Process;
import android.os.UserHandle;
@@ -31,7 +33,6 @@
import android.util.proto.ProtoOutputStream;
import dalvik.annotation.optimization.NeverCompile;
-import dalvik.system.VMDebug;
import java.io.FileDescriptor;
import java.lang.annotation.Retention;
@@ -111,7 +112,20 @@
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
MessageQueue(boolean quitAllowed) {
- mUseConcurrent = UserHandle.isCore(Process.myUid()) && !VMDebug.isDebuggingEnabled();
+ // Concurrent mode modifies behavior that is observable via reflection and is commonly used
+ // by tests.
+ // For now, we limit it to system processes to avoid breaking apps and their tests.
+ mUseConcurrent = UserHandle.isCore(Process.myUid());
+ // Even then, we don't use it if instrumentation is loaded as it breaks some
+ // platform tests.
+ final ActivityThread activityThread = ActivityThread.currentActivityThread();
+ if (activityThread != null) {
+ final Instrumentation instrumentation = activityThread.getInstrumentation();
+ mUseConcurrent &= instrumentation == null || !instrumentation.isInstrumenting();
+ }
+ // We can lift this restriction in the future after we've made it possible for test authors
+ // to test Looper and MessageQueue without resorting to reflection.
+
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
diff --git a/core/java/android/permission/flags.aconfig b/core/java/android/permission/flags.aconfig
index 6264fbb..0a35fe3 100644
--- a/core/java/android/permission/flags.aconfig
+++ b/core/java/android/permission/flags.aconfig
@@ -399,4 +399,13 @@
namespace: "supervision"
description: "This flag is used to enable all the remaining permissions required to the supervision role"
bug: "367333883"
-}
\ No newline at end of file
+}
+
+flag {
+ name: "permission_request_short_circuit_enabled"
+ is_fixed_read_only: true
+ is_exported: true
+ namespace: "permissions"
+ description: "This flag is used to short circuit the request for permananently denied permissions"
+ bug: "378923900"
+}
diff --git a/core/java/android/security/forensic/ForensicManager.java b/core/java/android/security/forensic/ForensicManager.java
new file mode 100644
index 0000000..9126182
--- /dev/null
+++ b/core/java/android/security/forensic/ForensicManager.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2024 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.security.forensic;
+
+import static android.Manifest.permission.MANAGE_FORENSIC_STATE;
+import static android.Manifest.permission.READ_FORENSIC_STATE;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.annotation.SystemApi;
+import android.annotation.SystemService;
+import android.content.Context;
+import android.os.RemoteException;
+import android.security.Flags;
+import android.util.Log;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+import java.util.function.Consumer;
+
+/**
+ * ForensicManager manages the forensic logging on Android devices.
+ * Upon user consent, forensic logging collects various device events for
+ * off-device investigation of potential device compromise.
+ * <p>
+ * Forensic logging can either be enabled ({@link #STATE_ENABLED}
+ * or disabled ({@link #STATE_DISABLED}).
+ * <p>
+ * The Forensic logs will be transferred to
+ * {@link android.security.forensic.ForensicEventTransport}.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(Flags.FLAG_AFL_API)
+@SystemService(Context.FORENSIC_SERVICE)
+public class ForensicManager {
+ private static final String TAG = "ForensicManager";
+
+ /** @hide */
+ @Target(ElementType.TYPE_USE)
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = { "STATE_" }, value = {
+ STATE_UNKNOWN,
+ STATE_DISABLED,
+ STATE_ENABLED
+ })
+ public @interface ForensicState {}
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = { "ERROR_" }, value = {
+ ERROR_UNKNOWN,
+ ERROR_PERMISSION_DENIED,
+ ERROR_TRANSPORT_UNAVAILABLE,
+ ERROR_DATA_SOURCE_UNAVAILABLE
+ })
+ public @interface ForensicError {}
+
+ /**
+ * Indicates an unknown state
+ */
+ public static final int STATE_UNKNOWN = IForensicServiceStateCallback.State.UNKNOWN;
+
+ /**
+ * Indicates an state that the forensic is turned off.
+ */
+ public static final int STATE_DISABLED = IForensicServiceStateCallback.State.DISABLED;
+
+ /**
+ * Indicates an state that the forensic is turned on.
+ */
+ public static final int STATE_ENABLED = IForensicServiceStateCallback.State.ENABLED;
+
+ /**
+ * Indicates an unknown error
+ */
+ public static final int ERROR_UNKNOWN = IForensicServiceCommandCallback.ErrorCode.UNKNOWN;
+
+ /**
+ * Indicates an error due to insufficient access rights.
+ */
+ public static final int ERROR_PERMISSION_DENIED =
+ IForensicServiceCommandCallback.ErrorCode.PERMISSION_DENIED;
+
+ /**
+ * Indicates an error due to unavailability of the forensic event transport.
+ */
+ public static final int ERROR_TRANSPORT_UNAVAILABLE =
+ IForensicServiceCommandCallback.ErrorCode.TRANSPORT_UNAVAILABLE;
+
+ /**
+ * Indicates an error due to unavailability of the data source.
+ */
+ public static final int ERROR_DATA_SOURCE_UNAVAILABLE =
+ IForensicServiceCommandCallback.ErrorCode.DATA_SOURCE_UNAVAILABLE;
+
+
+ private final IForensicService mService;
+
+ private final ConcurrentHashMap<Consumer<Integer>, IForensicServiceStateCallback>
+ mStateCallbacks = new ConcurrentHashMap<>();
+
+ /**
+ * Constructor
+ *
+ * @param service A valid instance of IForensicService.
+ * @hide
+ */
+ public ForensicManager(IForensicService service) {
+ mService = service;
+ }
+
+ /**
+ * Add a callback to monitor the state of the ForensicService.
+ *
+ * @param executor The executor through which the callback should be invoked.
+ * @param callback The callback for state change.
+ * Once the callback is registered, the callback will be called
+ * to reflect the init state.
+ * The callback can be registered only once.
+ */
+ @RequiresPermission(READ_FORENSIC_STATE)
+ public void addStateCallback(@NonNull @CallbackExecutor Executor executor,
+ @NonNull @ForensicState Consumer<Integer> callback) {
+ Objects.requireNonNull(executor);
+ Objects.requireNonNull(callback);
+
+ if (mStateCallbacks.get(callback) != null) {
+ Log.d(TAG, "addStateCallback callback already present");
+ return;
+ }
+
+ final IForensicServiceStateCallback wrappedCallback =
+ new IForensicServiceStateCallback.Stub() {
+ @Override
+ public void onStateChange(int state) {
+ executor.execute(() -> callback.accept(state));
+ }
+ };
+ try {
+ mService.addStateCallback(wrappedCallback);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+
+ mStateCallbacks.put(callback, wrappedCallback);
+ }
+
+ /**
+ * Remove a callback to monitor the state of the ForensicService.
+ *
+ * @param callback The callback to remove.
+ */
+ @RequiresPermission(READ_FORENSIC_STATE)
+ public void removeStateCallback(@NonNull Consumer<@ForensicState Integer> callback) {
+ Objects.requireNonNull(callback);
+ if (!mStateCallbacks.containsKey(callback)) {
+ Log.d(TAG, "removeStateCallback callback not present");
+ return;
+ }
+
+ IForensicServiceStateCallback wrappedCallback = mStateCallbacks.get(callback);
+
+ try {
+ mService.removeStateCallback(wrappedCallback);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+
+ mStateCallbacks.remove(callback);
+ }
+
+ /**
+ * Enable forensic logging.
+ * If successful, ForensicService will transition to {@link #STATE_ENABLED} state.
+ * <p>
+ * When forensic logging is enabled, various device events will be collected and
+ * sent over to the registered {@link android.security.forensic.ForensicEventTransport}.
+ *
+ * @param executor The executor through which the callback should be invoked.
+ * @param callback The callback for the command result.
+ */
+ @RequiresPermission(MANAGE_FORENSIC_STATE)
+ public void enable(@NonNull @CallbackExecutor Executor executor,
+ @NonNull CommandCallback callback) {
+ Objects.requireNonNull(executor);
+ Objects.requireNonNull(callback);
+ try {
+ mService.enable(new IForensicServiceCommandCallback.Stub() {
+ @Override
+ public void onSuccess() {
+ executor.execute(callback::onSuccess);
+ }
+
+ @Override
+ public void onFailure(int error) {
+ executor.execute(() -> callback.onFailure(error));
+ }
+ });
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Disable forensic logging.
+ * If successful, ForensicService will transition to {@link #STATE_DISABLED}.
+ * <p>
+ * When forensic logging is disabled, device events will no longer be collected.
+ * Any events that have been collected but not yet sent to ForensicEventTransport
+ * will be transferred as a final batch.
+ *
+ * @param executor The executor through which the callback should be invoked.
+ * @param callback The callback for the command result.
+ */
+ @RequiresPermission(MANAGE_FORENSIC_STATE)
+ public void disable(@NonNull @CallbackExecutor Executor executor,
+ @NonNull CommandCallback callback) {
+ Objects.requireNonNull(executor);
+ Objects.requireNonNull(callback);
+ try {
+ mService.disable(new IForensicServiceCommandCallback.Stub() {
+ @Override
+ public void onSuccess() {
+ executor.execute(callback::onSuccess);
+ }
+
+ @Override
+ public void onFailure(int error) {
+ executor.execute(() -> callback.onFailure(error));
+ }
+ });
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Callback used in {@link #enable} and {@link #disable} to indicate the result of the command.
+ */
+ public interface CommandCallback {
+ /**
+ * Called when command succeeds.
+ */
+ void onSuccess();
+
+ /**
+ * Called when command fails.
+ * @param error The error number.
+ */
+ void onFailure(@ForensicError int error);
+ }
+}
diff --git a/core/java/android/security/forensic/IBackupTransport.aidl b/core/java/android/security/forensic/IForensicEventTransport.aidl
similarity index 96%
rename from core/java/android/security/forensic/IBackupTransport.aidl
rename to core/java/android/security/forensic/IForensicEventTransport.aidl
index c2cbc83..80e78eb 100644
--- a/core/java/android/security/forensic/IBackupTransport.aidl
+++ b/core/java/android/security/forensic/IForensicEventTransport.aidl
@@ -20,7 +20,7 @@
import com.android.internal.infra.AndroidFuture;
/** {@hide} */
-oneway interface IBackupTransport {
+oneway interface IForensicEventTransport {
/**
* Initialize the server side.
*/
diff --git a/core/java/android/security/forensic/IForensicService.aidl b/core/java/android/security/forensic/IForensicService.aidl
index a944b18..8039b26 100644
--- a/core/java/android/security/forensic/IForensicService.aidl
+++ b/core/java/android/security/forensic/IForensicService.aidl
@@ -24,9 +24,12 @@
* @hide
*/
interface IForensicService {
- void monitorState(IForensicServiceStateCallback callback);
- void makeVisible(IForensicServiceCommandCallback callback);
- void makeInvisible(IForensicServiceCommandCallback callback);
+ @EnforcePermission("READ_FORENSIC_STATE")
+ void addStateCallback(IForensicServiceStateCallback callback);
+ @EnforcePermission("READ_FORENSIC_STATE")
+ void removeStateCallback(IForensicServiceStateCallback callback);
+ @EnforcePermission("MANAGE_FORENSIC_STATE")
void enable(IForensicServiceCommandCallback callback);
+ @EnforcePermission("MANAGE_FORENSIC_STATE")
void disable(IForensicServiceCommandCallback callback);
}
diff --git a/core/java/android/security/forensic/IForensicServiceCommandCallback.aidl b/core/java/android/security/forensic/IForensicServiceCommandCallback.aidl
index 7fa0c7f..6d1456e 100644
--- a/core/java/android/security/forensic/IForensicServiceCommandCallback.aidl
+++ b/core/java/android/security/forensic/IForensicServiceCommandCallback.aidl
@@ -25,8 +25,8 @@
UNKNOWN = 0,
PERMISSION_DENIED = 1,
INVALID_STATE_TRANSITION = 2,
- BACKUP_TRANSPORT_UNAVAILABLE = 3,
- DATA_SOURCE_UNAVAILABLE = 3,
+ TRANSPORT_UNAVAILABLE = 3,
+ DATA_SOURCE_UNAVAILABLE = 4,
}
void onSuccess();
void onFailure(ErrorCode error);
diff --git a/core/java/android/security/forensic/IForensicServiceStateCallback.aidl b/core/java/android/security/forensic/IForensicServiceStateCallback.aidl
index 0cda350..1b68c7b 100644
--- a/core/java/android/security/forensic/IForensicServiceStateCallback.aidl
+++ b/core/java/android/security/forensic/IForensicServiceStateCallback.aidl
@@ -23,9 +23,8 @@
@Backing(type="int")
enum State{
UNKNOWN = 0,
- INVISIBLE = 1,
- VISIBLE = 2,
- ENABLED = 3,
+ DISABLED = 1,
+ ENABLED = 2,
}
void onStateChange(State state);
}
diff --git a/core/java/android/service/autofill/FillEventHistory.java b/core/java/android/service/autofill/FillEventHistory.java
index 98dda10..14a14e6 100644
--- a/core/java/android/service/autofill/FillEventHistory.java
+++ b/core/java/android/service/autofill/FillEventHistory.java
@@ -16,8 +16,10 @@
package android.service.autofill;
+import static android.service.autofill.Flags.FLAG_AUTOFILL_W_METRICS;
import static android.view.autofill.Helper.sVerbose;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -63,14 +65,21 @@
private static final String TAG = "FillEventHistory";
/**
- * Not in parcel. The ID of the autofill session that created the {@link FillResponse}.
+ * The ID of the autofill session that created the {@link FillResponse}.
+ *
+ * TODO: add this to the parcel.
*/
private final int mSessionId;
@Nullable private final Bundle mClientState;
@Nullable List<Event> mEvents;
- /** @hide */
+ /**
+ * Returns the unique identifier of this FillEventHistory.
+ *
+ * <p>This is used to differentiate individual FillEventHistory.
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
public int getSessionId() {
return mSessionId;
}
@@ -283,6 +292,13 @@
/** All fields matched contents of datasets. */
public static final int NO_SAVE_UI_REASON_DATASET_MATCH = 6;
+ /**
+ * Credential Manager is invoked instead of Autofill. When that happens, Save Dialog cannot
+ * be shown, and this will be populated in
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ public static final int NO_SAVE_UI_REASON_USING_CREDMAN = 7;
+
/** @hide */
@IntDef(prefix = { "NO_SAVE_UI_REASON_" }, value = {
NO_SAVE_UI_REASON_NONE,
@@ -310,11 +326,20 @@
public static final int UI_TYPE_DIALOG = 3;
/**
- * The autofill suggestion is shown os a credman bottom sheet
- * @hide
+ * The autofill suggestion is shown os a credman bottom sheet
+ *
+ * <p>Note, this was introduced as bottom sheet even though it applies to all credman UI
+ * types. Instead of exposing this directly to the public, the generic UI_TYPE_CREDMAN is
+ * introduced with the same number.
+ *
+ * @hide
*/
public static final int UI_TYPE_CREDMAN_BOTTOM_SHEET = 4;
+ /** Credential Manager suggestions are shown instead of Autofill suggestion */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ public static final int UI_TYPE_CREDMAN = 4;
+
/** @hide */
@IntDef(prefix = { "UI_TYPE_" }, value = {
UI_TYPE_UNKNOWN,
@@ -359,6 +384,13 @@
return mEventType;
}
+ /** Gets the {@code AutofillId} that's focused at the time of action */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ @Nullable
+ public AutofillId getFocusedId() {
+ return null;
+ }
+
/**
* Returns the id of dataset the id was on.
*
@@ -391,6 +423,17 @@
}
/**
+ * Returns which datasets were shown to the user.
+ *
+ * <p><b>Note: </b>Only set on events of type {@link #TYPE_DATASETS_SHOWN}.
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ @NonNull
+ public Set<String> getShownDatasetIds() {
+ return Collections.emptySet();
+ }
+
+ /**
* Returns which datasets were NOT selected by the user.
*
* <p><b>Note: </b>Only set on events of type {@link #TYPE_CONTEXT_COMMITTED}.
diff --git a/core/java/android/service/quickaccesswallet/IQuickAccessWalletService.aidl b/core/java/android/service/quickaccesswallet/IQuickAccessWalletService.aidl
index 0dca78d..03e27b8 100644
--- a/core/java/android/service/quickaccesswallet/IQuickAccessWalletService.aidl
+++ b/core/java/android/service/quickaccesswallet/IQuickAccessWalletService.aidl
@@ -43,4 +43,6 @@
oneway void unregisterWalletServiceEventListener(in WalletServiceEventListenerRequest request);
// Request to get a PendingIntent to launch an activity from which the user can manage their cards.
oneway void onTargetActivityIntentRequested(in IQuickAccessWalletServiceCallbacks callbacks);
+ // Request to get a PendingIntent to launch an activity, triggered when the user performs a gesture.
+ oneway void onGestureTargetActivityIntentRequested(in IQuickAccessWalletServiceCallbacks callbacks);
}
\ No newline at end of file
diff --git a/core/java/android/service/quickaccesswallet/IQuickAccessWalletServiceCallbacks.aidl b/core/java/android/service/quickaccesswallet/IQuickAccessWalletServiceCallbacks.aidl
index 1b69ca1..61d7fd1 100644
--- a/core/java/android/service/quickaccesswallet/IQuickAccessWalletServiceCallbacks.aidl
+++ b/core/java/android/service/quickaccesswallet/IQuickAccessWalletServiceCallbacks.aidl
@@ -37,4 +37,6 @@
oneway void onWalletServiceEvent(in WalletServiceEvent event);
// Called in response to onTargetActivityIntentRequested. May only be called once per request.
oneway void onTargetActivityPendingIntentReceived(in PendingIntent pendingIntent);
+ //Called in response to onGesturePendingIntent
+ oneway void onGestureTargetActivityPendingIntentReceived(in PendingIntent pendingIntent);
}
\ No newline at end of file
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
index faa5b2f..b5251db 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
@@ -17,6 +17,7 @@
package android.service.quickaccesswallet;
import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
@@ -181,6 +182,23 @@
}
/**
+ * Gets the {@link PendingIntent} provided by QuickAccessWalletService to be sent when the user
+ * launches Wallet via gesture.
+ */
+ @FlaggedApi(Flags.FLAG_LAUNCH_WALLET_OPTION_ON_POWER_DOUBLE_TAP)
+ void getGestureTargetActivityPendingIntent(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull GesturePendingIntentCallback gesturePendingIntentCallback);
+
+ /** Callback interface for getGesturePendingIntent. */
+ @FlaggedApi(Flags.FLAG_LAUNCH_WALLET_OPTION_ON_POWER_DOUBLE_TAP)
+ interface GesturePendingIntentCallback {
+ /** Callback method for getGesturePendingIntent */
+ @FlaggedApi(Flags.FLAG_LAUNCH_WALLET_OPTION_ON_POWER_DOUBLE_TAP)
+ void onGesturePendingIntentRetrieved(@Nullable PendingIntent pendingIntent);
+ }
+
+ /**
* The manifest entry for the QuickAccessWalletService may also publish information about the
* activity that hosts the Wallet view. This is typically the home screen of the Wallet
* application.
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
index a59f026..97a4bef 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
@@ -267,6 +267,34 @@
}
@Override
+ public void getGestureTargetActivityPendingIntent(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull GesturePendingIntentCallback gesturePendingIntentCallback) {
+ BaseCallbacks callbacks =
+ new BaseCallbacks() {
+ @Override
+ public void onGestureTargetActivityPendingIntentReceived(
+ PendingIntent pendingIntent) {
+ if (!Flags.launchWalletOptionOnPowerDoubleTap()) {
+ return;
+ }
+ executor.execute(
+ () ->
+ gesturePendingIntentCallback
+ .onGesturePendingIntentRetrieved(pendingIntent));
+ }
+ };
+
+ executeApiCall(
+ new ApiCaller("getGestureTargetActivityPendingIntent") {
+ @Override
+ void performApiCall(IQuickAccessWalletService service) throws RemoteException {
+ service.onGestureTargetActivityIntentRequested(callbacks);
+ }
+ });
+ }
+
+ @Override
@Nullable
public Intent createWalletSettingsIntent() {
if (mServiceInfo == null) {
@@ -506,5 +534,9 @@
public void onTargetActivityPendingIntentReceived(PendingIntent pendingIntent) {
throw new IllegalStateException();
}
+
+ public void onGestureTargetActivityPendingIntentReceived(PendingIntent pendingIntent) {
+ throw new IllegalStateException();
+ }
}
}
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletService.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletService.java
index 36fa21c..90136ae 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletService.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletService.java
@@ -16,6 +16,9 @@
package android.service.quickaccesswallet;
+import static android.service.quickaccesswallet.Flags.launchWalletOptionOnPowerDoubleTap;
+
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SdkConstant;
@@ -247,6 +250,19 @@
callbacks));
}
+ @FlaggedApi(Flags.FLAG_LAUNCH_WALLET_OPTION_ON_POWER_DOUBLE_TAP)
+ @Override
+ public void onGestureTargetActivityIntentRequested(
+ @NonNull IQuickAccessWalletServiceCallbacks callbacks) {
+ if (launchWalletOptionOnPowerDoubleTap()) {
+ mHandler.post(
+ () ->
+ QuickAccessWalletService.this
+ .onGestureTargetActivityIntentRequestedInternal(
+ callbacks));
+ }
+ }
+
public void registerWalletServiceEventListener(
@NonNull WalletServiceEventListenerRequest request,
@NonNull IQuickAccessWalletServiceCallbacks callback) {
@@ -275,6 +291,20 @@
}
}
+ private void onGestureTargetActivityIntentRequestedInternal(
+ IQuickAccessWalletServiceCallbacks callbacks) {
+ if (!Flags.launchWalletOptionOnPowerDoubleTap()) {
+ return;
+ }
+
+ try {
+ callbacks.onGestureTargetActivityPendingIntentReceived(
+ getGestureTargetActivityPendingIntent());
+ } catch (RemoteException e) {
+ Log.w(TAG, "Error", e);
+ }
+ }
+
@Override
@Nullable
public IBinder onBind(@NonNull Intent intent) {
@@ -349,6 +379,18 @@
return null;
}
+ /**
+ * Specify a {@link PendingIntent} to be launched on user gesture.
+ *
+ * <p>The pending intent will be sent when the user performs a gesture to open Wallet.
+ * The pending intent should launch an activity.
+ */
+ @Nullable
+ @FlaggedApi(Flags.FLAG_LAUNCH_WALLET_OPTION_ON_POWER_DOUBLE_TAP)
+ public PendingIntent getGestureTargetActivityPendingIntent() {
+ return null;
+ }
+
private void sendWalletServiceEventInternal(WalletServiceEvent serviceEvent) {
if (mEventListener == null) {
Log.i(TAG, "No dismiss listener registered");
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index 032f592..cb72b97 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -50,6 +50,7 @@
import android.text.style.LineBreakConfigSpan;
import android.text.style.LineHeightSpan;
import android.text.style.LocaleSpan;
+import android.text.style.NoWritingToolsSpan;
import android.text.style.ParagraphStyle;
import android.text.style.QuoteSpan;
import android.text.style.RelativeSizeSpan;
@@ -817,7 +818,9 @@
/** @hide */
public static final int LINE_BREAK_CONFIG_SPAN = 30;
/** @hide */
- public static final int LAST_SPAN = LINE_BREAK_CONFIG_SPAN;
+ public static final int NO_WRITING_TOOLS_SPAN = 31;
+ /** @hide */
+ public static final int LAST_SPAN = NO_WRITING_TOOLS_SPAN;
/**
* Flatten a CharSequence and whatever styles can be copied across processes
@@ -1025,6 +1028,10 @@
span = LineBreakConfigSpan.CREATOR.createFromParcel(p);
break;
+ case NO_WRITING_TOOLS_SPAN:
+ span = NoWritingToolsSpan.CREATOR.createFromParcel(p);
+ break;
+
default:
throw new RuntimeException("bogus span encoding " + kind);
}
diff --git a/core/java/android/text/style/NoWritingToolsSpan.java b/core/java/android/text/style/NoWritingToolsSpan.java
new file mode 100644
index 0000000..90f85aa
--- /dev/null
+++ b/core/java/android/text/style/NoWritingToolsSpan.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2024 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.text.style;
+
+import static android.view.inputmethod.Flags.FLAG_WRITING_TOOLS;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.text.ParcelableSpan;
+import android.text.TextUtils;
+
+/**
+ * A span that signals to IMEs that writing tools should not modify the text.
+ *
+ * <p>For example, a text field may contain a mix of user input text and quoted text. The app
+ * can apply {@code NoWritingToolsSpan} to the quoted text so that the IME knows that writing
+ * tools should only rewrite the user input text, and not modify the quoted text.
+ */
+@FlaggedApi(FLAG_WRITING_TOOLS)
+public final class NoWritingToolsSpan implements ParcelableSpan {
+
+ /**
+ * Creates a {@link NoWritingToolsSpan}.
+ */
+ public NoWritingToolsSpan() {
+ }
+
+ @Override
+ public int getSpanTypeId() {
+ return getSpanTypeIdInternal();
+ }
+
+ /** @hide */
+ @Override
+ public int getSpanTypeIdInternal() {
+ return TextUtils.NO_WRITING_TOOLS_SPAN;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ writeToParcelInternal(dest, flags);
+ }
+
+ /** @hide */
+ @Override
+ public void writeToParcelInternal(@NonNull Parcel dest, int flags) {
+ }
+
+ @Override
+ public String toString() {
+ return "NoWritingToolsSpan{}";
+ }
+
+ @NonNull
+ public static final Creator<NoWritingToolsSpan> CREATOR = new Creator<>() {
+
+ @Override
+ public NoWritingToolsSpan createFromParcel(Parcel source) {
+ return new NoWritingToolsSpan();
+ }
+
+ @Override
+ public NoWritingToolsSpan[] newArray(int size) {
+ return new NoWritingToolsSpan[size];
+ }
+ };
+}
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index e50662a..19d3dc4 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -2516,6 +2516,11 @@
public void notifyInsetsAnimationRunningStateChanged(boolean running) {
if (sToolkitSetFrameRateReadOnlyFlagValue) {
mInsetsAnimationRunning = running;
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
+ Trace.instant(Trace.TRACE_TAG_VIEW,
+ TextUtils.formatSimple("notifyInsetsAnimationRunningStateChanged(%s)",
+ Boolean.toString(running)));
+ }
}
}
diff --git a/core/java/android/view/ViewStructure.java b/core/java/android/view/ViewStructure.java
index 1af9387..1be7f48 100644
--- a/core/java/android/view/ViewStructure.java
+++ b/core/java/android/view/ViewStructure.java
@@ -17,6 +17,7 @@
package android.view;
import static android.service.autofill.Flags.FLAG_AUTOFILL_CREDMAN_DEV_INTEGRATION;
+import static android.service.autofill.Flags.FLAG_AUTOFILL_W_METRICS;
import android.annotation.FlaggedApi;
import android.annotation.NonNull;
@@ -79,27 +80,24 @@
* Key used for writing the type of the view that generated the virtual structure of its
* children.
*
- * For example, if the virtual structure is generated by a webview, the value would be
+ * <p>For example, if the virtual structure is generated by a webview, the value would be
* "WebView". If the virtual structure is generated by a compose view, then the value would be
* "ComposeView". The value is of type String.
*
- * This value is added to mainly help with debugging purpose.
- *
- * @hide
+ * <p>This value is added to mainly help with debugging purpose.
*/
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
public static final String EXTRA_VIRTUAL_STRUCTURE_TYPE =
"android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_TYPE";
-
/**
* Key used for specifying the version of the view that generated the virtual structure for
* itself and its children
*
- * For example, if the virtual structure is generated by a webview of version "104.0.5112.69",
- * then the value should be "104.0.5112.69"
- *
- * @hide
+ * <p>For example, if the virtual structure is generated by a webview of version
+ * "104.0.5112.69", then the value should be "104.0.5112.69"
*/
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
public static final String EXTRA_VIRTUAL_STRUCTURE_VERSION_NUMBER =
"android.view.ViewStructure.extra.VIRTUAL_STRUCTURE_VERSION_NUMBER";
diff --git a/core/java/android/view/autofill/AutofillId.java b/core/java/android/view/autofill/AutofillId.java
index 6b60858..bd27778 100644
--- a/core/java/android/view/autofill/AutofillId.java
+++ b/core/java/android/view/autofill/AutofillId.java
@@ -15,6 +15,9 @@
*/
package android.view.autofill;
+import static android.service.autofill.Flags.FLAG_AUTOFILL_W_METRICS;
+
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
@@ -111,12 +114,43 @@
return new AutofillId(flags, id.mViewId, virtualChildId, NO_SESSION);
}
- /** @hide */
+ /**
+ * Returns the assigned unique identifier of this AutofillID.
+ *
+ * See @link{android.view.View#getAutofillId()} for more information on
+ * how this is generated for native Views.
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
public int getViewId() {
return mViewId;
}
/**
+ * Gets the virtual id. This is set if the view is a virtual view, most commonly set if the View
+ * is of {@link android.webkit.WebView}.
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ public int getAutofillVirtualId() {
+ return mVirtualIntId;
+ }
+
+ /** Checks whether this AutofillId represents a virtual view. */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ public boolean isVirtual() {
+ return !isNonVirtual();
+ }
+
+ /**
+ * Checks if this node is generate as part of a {@link android.app.assist.AssistStructure}. This
+ * will usually return true if it should be used by an autofill service provider, and false
+ * otherwise.
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
+ public boolean isInAutofillSession() {
+ return hasSession();
+ }
+
+ /**
* Gets the virtual child id.
*
* <p>Should only be used on subsystems where such id is represented by an {@code int}
@@ -181,7 +215,12 @@
return (mFlags & FLAG_HAS_SESSION) != 0;
}
- /** @hide */
+ /**
+ * Used to get the Session identifier associated with this AutofillId.
+ *
+ * @return a non-zero integer if {@link #isInAutofillSession()} returns true
+ */
+ @FlaggedApi(FLAG_AUTOFILL_W_METRICS)
public int getSessionId() {
return mSessionId;
}
diff --git a/core/java/android/view/inputmethod/InputMethodSession.java b/core/java/android/view/inputmethod/InputMethodSession.java
index 0f48f12..4f48cb6 100644
--- a/core/java/android/view/inputmethod/InputMethodSession.java
+++ b/core/java/android/view/inputmethod/InputMethodSession.java
@@ -16,7 +16,6 @@
package android.view.inputmethod;
-import android.annotation.NonNull;
import android.graphics.Rect;
import android.inputmethodservice.InputMethodService;
import android.os.Bundle;
@@ -126,11 +125,6 @@
public void dispatchKeyEvent(int seq, KeyEvent event, EventCallback callback);
/**
- * @hide
- */
- boolean onShouldVerifyKeyEvent(@NonNull KeyEvent event);
-
- /**
* This method is called when there is a track ball event.
*
* <p>
diff --git a/core/java/android/view/inputmethod/flags.aconfig b/core/java/android/view/inputmethod/flags.aconfig
index 63f8c80..deaf957 100644
--- a/core/java/android/view/inputmethod/flags.aconfig
+++ b/core/java/android/view/inputmethod/flags.aconfig
@@ -177,9 +177,10 @@
}
flag {
- name: "verify_key_event"
+ name: "adaptive_handwriting_bounds"
+ is_exported: true
namespace: "input_method"
- description: "Verify KeyEvents in IME"
- bug: "331730488"
+ description: "Feature flag for adaptively increasing handwriting bounds."
+ bug: "350047836"
is_fixed_read_only: true
-}
\ No newline at end of file
+}
diff --git a/core/java/android/window/flags/windowing_frontend.aconfig b/core/java/android/window/flags/windowing_frontend.aconfig
index 4f924a82..ff69610 100644
--- a/core/java/android/window/flags/windowing_frontend.aconfig
+++ b/core/java/android/window/flags/windowing_frontend.aconfig
@@ -418,6 +418,17 @@
}
flag {
+ name: "record_task_snapshots_before_shutdown"
+ namespace: "windowing_frontend"
+ description: "Record task snapshots before shutdown"
+ bug: "376821232"
+ is_fixed_read_only: true
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "predictive_back_three_button_nav"
namespace: "systemui"
description: "Enable Predictive Back Animation for 3-button-nav"
diff --git a/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java b/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
index a1c987f..eb682df 100644
--- a/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
@@ -676,15 +676,30 @@
return internMap.get(string);
}
+ protected boolean validateGroups(ILogger logger, String[] groups) {
+ for (int i = 0; i < groups.length; i++) {
+ String group = groups[i];
+ IProtoLogGroup g = mLogGroups.get(group);
+ if (g == null) {
+ logger.log("No IProtoLogGroup named " + group);
+ return false;
+ }
+ }
+ return true;
+ }
+
private int setTextLogging(boolean value, ILogger logger, String... groups) {
+ if (!validateGroups(logger, groups)) {
+ return -1;
+ }
+
for (int i = 0; i < groups.length; i++) {
String group = groups[i];
IProtoLogGroup g = mLogGroups.get(group);
if (g != null) {
g.setLogToLogcat(value);
} else {
- logger.log("No IProtoLogGroup named " + group);
- return -1;
+ throw new RuntimeException("No IProtoLogGroup named " + group);
}
}
diff --git a/core/java/com/android/internal/protolog/ProcessedPerfettoProtoLogImpl.java b/core/java/com/android/internal/protolog/ProcessedPerfettoProtoLogImpl.java
index 70d148a..967a5ed 100644
--- a/core/java/com/android/internal/protolog/ProcessedPerfettoProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/ProcessedPerfettoProtoLogImpl.java
@@ -113,6 +113,10 @@
*/
@Override
public int startLoggingToLogcat(String[] groups, @NonNull ILogger logger) {
+ if (!validateGroups(logger, groups)) {
+ return -1;
+ }
+
mViewerConfigReader.loadViewerConfig(groups, logger);
return super.startLoggingToLogcat(groups, logger);
}
@@ -125,8 +129,19 @@
*/
@Override
public int stopLoggingToLogcat(String[] groups, @NonNull ILogger logger) {
+ if (!validateGroups(logger, groups)) {
+ return -1;
+ }
+
+ var status = super.stopLoggingToLogcat(groups, logger);
+
+ if (status != 0) {
+ throw new RuntimeException("Failed to stop logging to logcat");
+ }
+
+ // If we successfully disabled logging, unload the viewer config.
mViewerConfigReader.unloadViewerConfig(groups, logger);
- return super.stopLoggingToLogcat(groups, logger);
+ return status;
}
@Deprecated
diff --git a/core/java/com/android/internal/ravenwood/RavenwoodEnvironment.java b/core/java/com/android/internal/ravenwood/RavenwoodEnvironment.java
index 3303d87..8df3f2a 100644
--- a/core/java/com/android/internal/ravenwood/RavenwoodEnvironment.java
+++ b/core/java/com/android/internal/ravenwood/RavenwoodEnvironment.java
@@ -88,15 +88,19 @@
/** @hide */
public static class CompatIdsForTest {
// Enabled by default
+ /** Used for testing */
@ChangeId
public static final long TEST_COMPAT_ID_1 = 368131859L;
+ /** Used for testing */
@Disabled
@ChangeId public static final long TEST_COMPAT_ID_2 = 368131701L;
+ /** Used for testing */
@EnabledAfter(targetSdkVersion = S)
@ChangeId public static final long TEST_COMPAT_ID_3 = 368131659L;
+ /** Used for testing */
@EnabledAfter(targetSdkVersion = UPSIDE_DOWN_CAKE)
@ChangeId public static final long TEST_COMPAT_ID_4 = 368132057L;
}
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 450b88b..1925b3a 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -1342,8 +1342,9 @@
}
}
-static jobject convertDeviceProductInfoToJavaObject(
- JNIEnv* env, const std::optional<DeviceProductInfo>& info) {
+static jobject convertDeviceProductInfoToJavaObject(JNIEnv* env,
+ const std::optional<DeviceProductInfo>& info,
+ bool isInternal) {
using ModelYear = android::DeviceProductInfo::ModelYear;
using ManufactureYear = android::DeviceProductInfo::ManufactureYear;
using ManufactureWeekAndYear = android::DeviceProductInfo::ManufactureWeekAndYear;
@@ -1378,7 +1379,8 @@
// Section 8.7 - Physical Address of HDMI Specification Version 1.3a
using android::hardware::display::IDeviceProductInfoConstants;
if (info->relativeAddress.size() != 4) {
- connectionToSinkType = IDeviceProductInfoConstants::CONNECTION_TO_SINK_UNKNOWN;
+ connectionToSinkType = isInternal ? IDeviceProductInfoConstants::CONNECTION_TO_SINK_BUILT_IN
+ : IDeviceProductInfoConstants::CONNECTION_TO_SINK_UNKNOWN;
} else if (info->relativeAddress[0] == 0) {
connectionToSinkType = IDeviceProductInfoConstants::CONNECTION_TO_SINK_BUILT_IN;
} else if (info->relativeAddress[1] == 0) {
@@ -1400,12 +1402,14 @@
jobject object =
env->NewObject(gStaticDisplayInfoClassInfo.clazz, gStaticDisplayInfoClassInfo.ctor);
- env->SetBooleanField(object, gStaticDisplayInfoClassInfo.isInternal,
- info.connectionType == ui::DisplayConnectionType::Internal);
+
+ const bool isInternal = info.connectionType == ui::DisplayConnectionType::Internal;
+ env->SetBooleanField(object, gStaticDisplayInfoClassInfo.isInternal, isInternal);
env->SetFloatField(object, gStaticDisplayInfoClassInfo.density, info.density);
env->SetBooleanField(object, gStaticDisplayInfoClassInfo.secure, info.secure);
env->SetObjectField(object, gStaticDisplayInfoClassInfo.deviceProductInfo,
- convertDeviceProductInfoToJavaObject(env, info.deviceProductInfo));
+ convertDeviceProductInfoToJavaObject(env, info.deviceProductInfo,
+ isInternal));
env->SetIntField(object, gStaticDisplayInfoClassInfo.installOrientation,
static_cast<uint32_t>(info.installOrientation));
return object;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 3e0c120..95d07df 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1080,6 +1080,52 @@
<permission android:name="android.permission.SATELLITE_COMMUNICATION"
android:protectionLevel="role|signature|privileged" />
+ <!-- ================================== -->
+ <!-- Permissions associated with picture and sound profiles -->
+ <!-- ================================== -->
+ <eat-comment />
+
+ <!-- @FlaggedApi(android.media.tv.flags.Flags.FLAG_APPLY_PICTURE_PROFILES)
+ Allows an app to apply a {@link MediaQualityManager.PictureProfile} to a layer via
+ {@link MediaCodec.PARAMETER_KEY_PICTURE_PROFILE} and, additionally, system apps via
+ {@link SurfaceControl.Transaction#setPictureProfileHandle}.
+ -->
+ <permission android:name="android.permission.APPLY_PICTURE_PROFILE"
+ android:protectionLevel="normal"
+ android:featureFlag="android.media.tv.flags.apply_picture_profiles"/>
+
+ <!-- @hide
+ Allows MediaQualityService to observe any {@link MediaQualityManager.PictureProfile}
+ applied to any layer in the system by apps via
+ {@link MediaCodec.PARAMETER_KEY_PICTURE_PROFILE} and by system apps via
+ {@link SurfaceControl.Transaction#setPictureProfileHandle}.
+ -->
+ <permission android:name="android.permission.OBSERVE_PICTURE_PROFILES"
+ android:protectionLevel="signature|privileged"
+ android:featureFlag="android.media.tv.flags.apply_picture_profiles"/>
+
+ <!--
+ @SystemApi
+ @FlaggedApi("android.media.tv.flags.media_quality_fw")
+ Allows an application to access its picture profile from the media quality database.
+ <p> Protection level: signature|privileged|vendor privileged
+ @hide
+ -->
+ <permission android:name="android.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE"
+ android:protectionLevel="signature|privileged|vendorPrivileged"
+ android:featureFlag="android.media.tv.flags.media_quality_fw"/>
+
+ <!--
+ @SystemApi
+ @FlaggedApi("android.media.tv.flags.media_quality_fw")
+ Allows an application to access its sound profile from the media quality database.
+ <p> Protection level: signature|privileged|vendor privileged
+ @hide
+ -->
+ <permission android:name="android.permission.MANAGE_GLOBAL_SOUND_QUALITY_SERVICE"
+ android:protectionLevel="signature|privileged|vendorPrivileged"
+ android:featureFlag="android.media.tv.flags.media_quality_fw"/>
+
<!-- ====================================================================== -->
<!-- Permissions for accessing external storage -->
<!-- ====================================================================== -->
@@ -4144,6 +4190,37 @@
<uses-permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
android:featureFlag="android.security.aapm_api"/>
+ <!-- Allows an application to read the state of the ForensicService
+ @FlaggedApi(android.security.Flags.FLAG_AFL_API)
+ @SystemApi
+ @hide -->
+ <permission android:name="android.permission.READ_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"
+ android:protectionLevel="signature|privileged" />
+ <uses-permission android:name="android.permission.READ_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"/>
+
+ <!-- Allows an application to change the state of the ForensicService
+ @FlaggedApi(android.security.Flags.FLAG_AFL_API)
+ @SystemApi
+ @hide -->
+ <permission android:name="android.permission.MANAGE_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"
+ android:protectionLevel="signature|privileged" />
+ <uses-permission android:name="android.permission.MANAGE_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"/>
+
+ <!-- Must be required by any ForensicEventTransportService to ensure that
+ only the system can bind to it.
+ @FlaggedApi(android.security.Flags.FLAG_AFL_API)
+ @SystemApi
+ @hide -->
+ <permission android:name="android.permission.BIND_FORENSIC_EVENT_TRANSPORT_SERVICE"
+ android:featureFlag="android.security.afl_api"
+ android:protectionLevel="signature" />
+ <uses-permission android:name="android.permission.BIND_FORENSIC_EVENT_TRANSPORT_SERVICE"
+ android:featureFlag="android.security.afl_api"/>
+
<!-- @SystemApi @hide Allows an application to set a device owner on retail demo devices.-->
<permission android:name="android.permission.PROVISION_DEMO_DEVICE"
android:protectionLevel="signature|setup|knownSigner"
@@ -4991,16 +5068,16 @@
android:protectionLevel="signature|privileged|role"
android:featureFlag="com.android.settingslib.flags.settings_catalyst" />
- <!-- @FlaggedApi(com.android.settingslib.flags.Flags.FLAG_SETTINGS_CATALYST)
+ <!-- @FlaggedApi(com.android.settingslib.flags.Flags.FLAG_WRITE_SYSTEM_PREFERENCE_PERMISSION_ENABLED)
Allows an application to access the Settings Preference services to write settings
values exposed by the system Settings app and system apps that contribute settings surfaced
in the Settings app.
<p>This allows the calling application to write settings values
through the host application, agnostic of underlying storage.
- <p>Protection Level: signature|privileged|appop - appop to be added in followup -->
+ <p>Protection Level: signature|privileged|appop -->
<permission android:name="android.permission.WRITE_SYSTEM_PREFERENCES"
- android:protectionLevel="signature|privileged"
- android:featureFlag="com.android.settingslib.flags.settings_catalyst" />
+ android:protectionLevel="signature|privileged|appop"
+ android:featureFlag="com.android.settingslib.flags.write_system_preference_permission_enabled" />
<!-- ========================================= -->
<!-- Permissions for special development tools -->
@@ -8565,27 +8642,6 @@
<permission android:name="android.permission.RESERVED_FOR_TESTING_SIGNATURE"
android:protectionLevel="signature"/>
- <!--
- @SystemApi
- @FlaggedApi("android.media.tv.flags.media_quality_fw")
- Allows an application to access its picture profile from the media quality database.
- <p> Protection level: signature|privileged|vendor privileged
- @hide
- -->
- <permission android:name="android.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE"
- android:protectionLevel="signature|privileged|vendorPrivileged"
- android:featureFlag="android.media.tv.flags.media_quality_fw"/>
-
- <!--
- @SystemApi
- @FlaggedApi("android.media.tv.flags.media_quality_fw")
- Allows an application to access its sound profile from the media quality database.
- <p> Protection level: signature|privileged|vendor privileged
- @hide
- -->
- <permission android:name="android.permission.MANAGE_GLOBAL_SOUND_QUALITY_SERVICE"
- android:protectionLevel="signature|privileged|vendorPrivileged"
- android:featureFlag="android.media.tv.flags.media_quality_fw"/>
<!-- @SystemApi
@FlaggedApi("android.content.pm.verification_service")
Allows app to be the verification agent to verify packages.
diff --git a/core/res/res/layout/list_content_simple.xml b/core/res/res/layout/list_content_simple.xml
index 6f9f1e0..961668e 100644
--- a/core/res/res/layout/list_content_simple.xml
+++ b/core/res/res/layout/list_content_simple.xml
@@ -20,5 +20,6 @@
<ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
+ android:fitsSystemWindows="true"
android:drawSelectorOnTop="false"
/>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index e6dedce..72467b3 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -10285,22 +10285,25 @@
</declare-styleable>
<!-- @hide -->
+ <attr name="modifierState">
+ <flag name="META" value="0x10000" />
+ <flag name="CTRL" value="0x1000" />
+ <flag name="ALT" value="0x02" />
+ <flag name="SHIFT" value="0x1" />
+ <flag name="SYM" value="0x4" />
+ <flag name="FUNCTION" value="0x8" />
+ <flag name="CAPS_LOCK" value="0x100000" />
+ <flag name="NUM_LOCK" value="0x200000" />
+ <flag name="SCROLL_LOCK" value="0x400000" />
+ </attr>
+
+ <!-- @hide -->
<declare-styleable name="HardwareDefinedShortcut">
<attr name="keycode" />
<!-- The values are taken from public constants for modifier state defined in
{@see KeyEvent.java}. Here we allow multiple modifier flags as value, since this
represents the modifier state -->
- <attr name="modifierState">
- <flag name="META" value="0x10000" />
- <flag name="CTRL" value="0x1000" />
- <flag name="ALT" value="0x02" />
- <flag name="SHIFT" value="0x1" />
- <flag name="SYM" value="0x4" />
- <flag name="FUNCTION" value="0x8" />
- <flag name="CAPS_LOCK" value="0x100000" />
- <flag name="NUM_LOCK" value="0x200000" />
- <flag name="SCROLL_LOCK" value="0x400000" />
- </attr>
+ <attr name="modifierState" />
<attr name="outKeycode" />
</declare-styleable>
@@ -10309,6 +10312,11 @@
<attr name="keycode" />
</declare-styleable>
+ <declare-styleable name="Bookmark">
+ <attr name="keycode" />
+ <attr name="modifierState" />
+ </declare-styleable>
+
<declare-styleable name="MediaRouteButton">
<!-- This drawable is a state list where the "activated" state
indicates active media routing. Non-activated indicates
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index e83e4f9..089b4b3 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -6575,7 +6575,7 @@
</string-array>
<!-- the number of the max cached processes in the system. -->
- <integer name="config_customizedMaxCachedProcesses">32</integer>
+ <integer name="config_customizedMaxCachedProcesses">1024</integer>
<!-- Whether this device should support taking app snapshots on closure -->
<bool name="config_disableTaskSnapshots">false</bool>
@@ -7220,8 +7220,8 @@
<!-- Package for opening identity check settings page [CHAR LIMIT=NONE] [DO NOT TRANSLATE] -->
<string name="identity_check_settings_package_name">com\u002eandroid\u002esettings</string>
- <!-- The name of the service for forensic backup transport. -->
- <string name="config_forensicBackupTransport" translatable="false"></string>
+ <!-- The name of the service for forensic event transport. -->
+ <string name="config_forensicEventTransport" translatable="false"></string>
<!-- Whether to enable fp unlock when screen turns off on udfps devices -->
<bool name="config_screen_off_udfps_enabled">false</bool>
diff --git a/core/res/res/values/config_telephony.xml b/core/res/res/values/config_telephony.xml
index 31e9913..4ec27a3 100644
--- a/core/res/res/values/config_telephony.xml
+++ b/core/res/res/values/config_telephony.xml
@@ -318,6 +318,12 @@
<bool name="config_oem_enabled_satellite_access_allow">true</bool>
<java-symbol type="bool" name="config_oem_enabled_satellite_access_allow" />
+ <!-- Whether the satellite modem support concurrent TN scanning while device is in
+ NTN mode.
+ -->
+ <bool name="config_satellite_modem_support_concurrent_tn_scanning">true</bool>
+ <java-symbol type="bool" name="config_satellite_modem_support_concurrent_tn_scanning" />
+
<!-- The time duration in seconds which is used to decide whether the Location returned from
LocationManager#getLastKnownLocation is fresh.
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 07f122f..0e12075 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -5682,8 +5682,8 @@
<java-symbol type="string" name="identity_check_settings_action" />
<java-symbol type="string" name="identity_check_settings_package_name" />
- <!-- Forensic backup transport -->
- <java-symbol type="string" name="config_forensicBackupTransport" />
+ <!-- Forensic event transport -->
+ <java-symbol type="string" name="config_forensicEventTransport" />
<!-- Fingerprint screen off unlock config -->
<java-symbol type="bool" name="config_screen_off_udfps_enabled" />
diff --git a/core/res/res/xml/bookmarks.xml b/core/res/res/xml/bookmarks.xml
index 22d0226..e735784 100644
--- a/core/res/res/xml/bookmarks.xml
+++ b/core/res/res/xml/bookmarks.xml
@@ -31,29 +31,37 @@
'u': Calculator
'y': YouTube
-->
-<bookmarks>
+<bookmarks xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
<bookmark
role="android.app.role.BROWSER"
- shortcut="b" />
+ androidprv:keycode="KEYCODE_B"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CONTACTS"
- shortcut="c" />
+ androidprv:keycode="KEYCODE_C"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_EMAIL"
- shortcut="e" />
+ androidprv:keycode="KEYCODE_E"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALENDAR"
- shortcut="k" />
+ androidprv:keycode="KEYCODE_K"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MAPS"
- shortcut="m" />
+ androidprv:keycode="KEYCODE_M"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MUSIC"
- shortcut="p" />
+ androidprv:keycode="KEYCODE_P"
+ androidprv:modifierState="META" />
<bookmark
role="android.app.role.SMS"
- shortcut="s" />
+ androidprv:keycode="KEYCODE_S"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALCULATOR"
- shortcut="u" />
+ androidprv:keycode="KEYCODE_U"
+ androidprv:modifierState="META" />
</bookmarks>
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 541ca60..fea7cb4 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -93,6 +93,10 @@
<permission name="android.permission.INTERACT_ACROSS_USERS"/>
</privapp-permissions>
+ <privapp-permissions package="com.android.media.quality">
+ <permission name="android.permission.OBSERVE_PICTURE_PROFILES"/>
+ </privapp-permissions>
+
<privapp-permissions package="com.android.mtp">
<permission name="android.permission.ACCESS_MTP"/>
<permission name="android.permission.MANAGE_USB"/>
@@ -262,6 +266,8 @@
<!-- BLUETOOTH_PRIVILEGED is needed for test only -->
<permission name="android.permission.BLUETOOTH_PRIVILEGED"/>
<permission name="android.permission.BIND_APPWIDGET"/>
+ <!-- Needed for CTS tests only -->
+ <permission name="android.permission.OBSERVE_PICTURE_PROFILES"/>
<permission name="android.permission.CHANGE_APP_IDLE_STATE"/>
<permission name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"/>
<permission name="android.permission.CHANGE_CONFIGURATION"/>
@@ -597,6 +603,9 @@
<!-- Permissions required for CTS test - SettingsPreferenceServiceClientTest -->
<permission name="android.permission.READ_SYSTEM_PREFERENCES" />
<permission name="android.permission.WRITE_SYSTEM_PREFERENCES" />
+ <!-- Permission required for CTS test - ForensicManagerTest -->
+ <permission name="android.permission.READ_FORENSIC_STATE" />
+ <permission name="android.permission.MANAGE_FORENSIC_STATE" />
</privapp-permissions>
<privapp-permissions package="com.android.statementservice">
diff --git a/graphics/java/android/graphics/BlendMode.java b/graphics/java/android/graphics/BlendMode.java
index 5c294aa..c6ae680 100644
--- a/graphics/java/android/graphics/BlendMode.java
+++ b/graphics/java/android/graphics/BlendMode.java
@@ -571,10 +571,10 @@
}
@NonNull
- private final Xfermode mXfermode;
+ private final PorterDuffXfermode mXfermode;
BlendMode(int mode) {
- mXfermode = new Xfermode();
+ mXfermode = new PorterDuffXfermode();
mXfermode.porterDuffMode = mode;
}
@@ -582,7 +582,7 @@
* @hide
*/
@NonNull
- public Xfermode getXfermode() {
+ public PorterDuffXfermode getXfermode() {
return mXfermode;
}
}
diff --git a/graphics/java/android/graphics/ComposeShader.java b/graphics/java/android/graphics/ComposeShader.java
index 977aeaa..e714568 100644
--- a/graphics/java/android/graphics/ComposeShader.java
+++ b/graphics/java/android/graphics/ComposeShader.java
@@ -40,9 +40,12 @@
* @param mode The mode that combines the colors from the two shaders. If mode
* is null, then SRC_OVER is assumed.
*/
+ //TODO(358126864): allow a ComposeShader to accept a RuntimeXfermode
@Deprecated
public ComposeShader(@NonNull Shader shaderA, @NonNull Shader shaderB, @NonNull Xfermode mode) {
- this(shaderA, shaderB, mode.porterDuffMode);
+ this(shaderA, shaderB,
+ mode instanceof PorterDuffXfermode ? ((PorterDuffXfermode) mode).porterDuffMode
+ : BlendMode.SRC_OVER.getXfermode().porterDuffMode);
}
/**
diff --git a/graphics/java/android/graphics/Paint.java b/graphics/java/android/graphics/Paint.java
index 56bb0f0..9bf4d65 100644
--- a/graphics/java/android/graphics/Paint.java
+++ b/graphics/java/android/graphics/Paint.java
@@ -71,6 +71,7 @@
private long mNativePaint;
private long mNativeShader;
private long mNativeColorFilter;
+ private long mNativeXfermode;
// Use a Holder to allow static initialization of Paint in the boot image.
private static class NoImagePreloadHolder {
@@ -735,6 +736,7 @@
mPathEffect = null;
mShader = null;
mNativeShader = 0;
+ mNativeXfermode = 0;
mTypeface = null;
mXfermode = null;
@@ -780,6 +782,7 @@
mNativeShader = paint.mNativeShader;
mTypeface = paint.mTypeface;
mXfermode = paint.mXfermode;
+ mNativeXfermode = paint.mNativeXfermode;
mHasCompatScaling = paint.mHasCompatScaling;
mCompatScaling = paint.mCompatScaling;
@@ -815,7 +818,7 @@
*
* Note: Although this method is |synchronized|, this is simply so it
* is not thread-hostile to multiple threads calling this method. It
- * is still unsafe to attempt to change the Shader/ColorFilter while
+ * is still unsafe to attempt to change the Shader/ColorFilter/Xfermode while
* another thread attempts to access the native object.
*
* @hide
@@ -833,6 +836,15 @@
mNativeColorFilter = newNativeColorFilter;
nSetColorFilter(mNativePaint, mNativeColorFilter);
}
+ if (com.android.graphics.hwui.flags.Flags.runtimeColorFiltersBlenders()) {
+ if (mXfermode instanceof RuntimeXfermode) {
+ long newNativeXfermode = ((RuntimeXfermode) mXfermode).createNativeInstance();
+ if (newNativeXfermode != mNativeXfermode) {
+ mNativeXfermode = newNativeXfermode;
+ nSetXfermode(mNativePaint, mNativeXfermode);
+ }
+ }
+ }
return mNativePaint;
}
@@ -1427,16 +1439,17 @@
}
/**
- * Get the paint's blend mode object.
+ * Get the paint's blend mode object. Will return null if there is a Xfermode applied that
+ * cannot be represented by a blend mode (i.e. a custom {@code RuntimeXfermode}
*
* @return the paint's blend mode (or null)
*/
@Nullable
public BlendMode getBlendMode() {
- if (mXfermode == null) {
+ if (mXfermode == null || !(mXfermode instanceof PorterDuffXfermode)) {
return null;
} else {
- return BlendMode.fromValue(mXfermode.porterDuffMode);
+ return BlendMode.fromValue(((PorterDuffXfermode) mXfermode).porterDuffMode);
}
}
@@ -1459,8 +1472,17 @@
@Nullable
private Xfermode installXfermode(Xfermode xfermode) {
- int newMode = xfermode != null ? xfermode.porterDuffMode : Xfermode.DEFAULT;
- int curMode = mXfermode != null ? mXfermode.porterDuffMode : Xfermode.DEFAULT;
+ if (com.android.graphics.hwui.flags.Flags.runtimeColorFiltersBlenders()) {
+ if (xfermode instanceof RuntimeXfermode) {
+ mXfermode = xfermode;
+ nSetXfermode(mNativePaint, ((RuntimeXfermode) xfermode).createNativeInstance());
+ return xfermode;
+ }
+ }
+ int newMode = (xfermode instanceof PorterDuffXfermode)
+ ? ((PorterDuffXfermode) xfermode).porterDuffMode : PorterDuffXfermode.DEFAULT;
+ int curMode = (mXfermode instanceof PorterDuffXfermode)
+ ? ((PorterDuffXfermode) mXfermode).porterDuffMode : PorterDuffXfermode.DEFAULT;
if (newMode != curMode) {
nSetXfermode(mNativePaint, newMode);
}
@@ -3823,6 +3845,8 @@
@CriticalNative
private static native void nSetXfermode(long paintPtr, int xfermode);
@CriticalNative
+ private static native void nSetXfermode(long paintPtr, long xfermodePtr);
+ @CriticalNative
private static native long nSetPathEffect(long paintPtr, long effect);
@CriticalNative
private static native long nSetMaskFilter(long paintPtr, long maskfilter);
diff --git a/graphics/java/android/graphics/PorterDuffXfermode.java b/graphics/java/android/graphics/PorterDuffXfermode.java
index ff9ff8b..83d0507 100644
--- a/graphics/java/android/graphics/PorterDuffXfermode.java
+++ b/graphics/java/android/graphics/PorterDuffXfermode.java
@@ -29,6 +29,9 @@
*
* @param mode The porter-duff mode that is applied
*/
+ static final int DEFAULT = PorterDuff.Mode.SRC_OVER.nativeInt;
+ int porterDuffMode = DEFAULT;
+ PorterDuffXfermode() {}
public PorterDuffXfermode(PorterDuff.Mode mode) {
porterDuffMode = mode.nativeInt;
}
diff --git a/graphics/java/android/graphics/RuntimeXfermode.java b/graphics/java/android/graphics/RuntimeXfermode.java
new file mode 100644
index 0000000..f5a6568
--- /dev/null
+++ b/graphics/java/android/graphics/RuntimeXfermode.java
@@ -0,0 +1,312 @@
+/*
+ * Copyright 2024 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.graphics;
+
+import android.annotation.ColorInt;
+import android.annotation.ColorLong;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+
+import com.android.graphics.hwui.flags.Flags;
+
+import libcore.util.NativeAllocationRegistry;
+
+
+/**
+ * <p>A {@link RuntimeXfermode} calculates a per-pixel color based on the output of a user
+ * * defined Android Graphics Shading Language (AGSL) function.</p>
+ *
+ * <p>This AGSL function takes in two input colors to be operated on. These colors are in sRGB
+ * * and the output is also interpreted as sRGB. The AGSL function signature expects a single input
+ * * of color (packed as a half4 or float4 or vec4).</p>
+ *
+ * <pre class="prettyprint">
+ * vec4 main(half4 src, half4 dst);
+ * </pre>
+ */
+@FlaggedApi(Flags.FLAG_RUNTIME_COLOR_FILTERS_BLENDERS)
+public class RuntimeXfermode extends Xfermode {
+
+ private static class NoImagePreloadHolder {
+ public static final NativeAllocationRegistry sRegistry =
+ NativeAllocationRegistry.createMalloced(
+ RuntimeXfermode.class.getClassLoader(), nativeGetFinalizer());
+ }
+
+ private long mBuilderNativeInstance;
+
+ /**
+ * Creates a new RuntimeBlender.
+ *
+ * @param agsl The text of AGSL color filter program to run.
+ */
+ public RuntimeXfermode(@NonNull String agsl) {
+ if (agsl == null) {
+ throw new NullPointerException("RuntimeShader requires a non-null AGSL string");
+ }
+ mBuilderNativeInstance = nativeCreateBlenderBuilder(agsl);
+ RuntimeXfermode.NoImagePreloadHolder.sRegistry.registerNativeAllocation(
+ this, mBuilderNativeInstance);
+ }
+ /**
+ * Sets the uniform color value corresponding to this color filter. If the effect does not have
+ * a uniform with that name or if the uniform is declared with a type other than vec3 or vec4
+ * and corresponding layout(color) annotation then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the color uniform declared in the AGSL program
+ * @param color the provided sRGB color
+ */
+ public void setColorUniform(@NonNull String uniformName, @ColorInt int color) {
+ setUniform(uniformName, Color.valueOf(color).getComponents(), true);
+ }
+
+ /**
+ * Sets the uniform color value corresponding to this color filter. If the effect does not have
+ * a uniform with that name or if the uniform is declared with a type other than vec3 or vec4
+ * and corresponding layout(color) annotation then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the color uniform declared in the AGSL program
+ * @param color the provided sRGB color
+ */
+ public void setColorUniform(@NonNull String uniformName, @ColorLong long color) {
+ Color exSRGB = Color.valueOf(color).convert(ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB));
+ setUniform(uniformName, exSRGB.getComponents(), true);
+ }
+
+ /**
+ * Sets the uniform color value corresponding to this color filter. If the effect does not have
+ * a uniform with that name or if the uniform is declared with a type other than vec3 or vec4
+ * and corresponding layout(color) annotation then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the color uniform declared in the AGSL program
+ * @param color the provided sRGB color
+ */
+ public void setColorUniform(@NonNull String uniformName, @NonNull Color color) {
+ if (color == null) {
+ throw new NullPointerException("The color parameter must not be null");
+ }
+ Color exSRGB = color.convert(ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB));
+ setUniform(uniformName, exSRGB.getComponents(), true);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than a float or
+ * float[1] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setFloatUniform(@NonNull String uniformName, float value) {
+ setFloatUniform(uniformName, value, 0.0f, 0.0f, 0.0f, 1);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than a vec2 or
+ * float[2] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setFloatUniform(@NonNull String uniformName, float value1, float value2) {
+ setFloatUniform(uniformName, value1, value2, 0.0f, 0.0f, 2);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than a vec3 or
+ * float[3] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setFloatUniform(@NonNull String uniformName, float value1, float value2,
+ float value3) {
+ setFloatUniform(uniformName, value1, value2, value3, 0.0f, 3);
+
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than a vec4 or
+ * float[4] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setFloatUniform(@NonNull String uniformName, float value1, float value2,
+ float value3, float value4) {
+ setFloatUniform(uniformName, value1, value2, value3, value4, 4);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than a float
+ * (for N=1), vecN, or float[N] where N is the length of the values param then an
+ * IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setFloatUniform(@NonNull String uniformName, @NonNull float[] values) {
+ setUniform(uniformName, values, false);
+ }
+
+ private void setFloatUniform(@NonNull String uniformName, float value1, float value2,
+ float value3, float value4, int count) {
+ if (uniformName == null) {
+ throw new NullPointerException("The uniformName parameter must not be null");
+ }
+ nativeUpdateUniforms(mBuilderNativeInstance, uniformName, value1, value2, value3, value4,
+ count);
+ }
+
+ private void setUniform(@NonNull String uniformName, @NonNull float[] values, boolean isColor) {
+ if (uniformName == null) {
+ throw new NullPointerException("The uniformName parameter must not be null");
+ }
+ if (values == null) {
+ throw new NullPointerException("The uniform values parameter must not be null");
+ }
+ nativeUpdateUniforms(mBuilderNativeInstance, uniformName, values, isColor);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than an int or int[1]
+ * then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setIntUniform(@NonNull String uniformName, int value) {
+ setIntUniform(uniformName, value, 0, 0, 0, 1);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than an ivec2 or
+ * int[2] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setIntUniform(@NonNull String uniformName, int value1, int value2) {
+ setIntUniform(uniformName, value1, value2, 0, 0, 2);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than an ivec3 or
+ * int[3] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setIntUniform(@NonNull String uniformName, int value1, int value2, int value3) {
+ setIntUniform(uniformName, value1, value2, value3, 0, 3);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than an ivec4 or
+ * int[4] then an IllegalArgumentException is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setIntUniform(@NonNull String uniformName, int value1, int value2,
+ int value3, int value4) {
+ setIntUniform(uniformName, value1, value2, value3, value4, 4);
+ }
+
+ /**
+ * Sets the uniform value corresponding to this color filter. If the effect does not have a
+ * uniform with that name or if the uniform is declared with a type other than an int (for N=1),
+ * ivecN, or int[N] where N is the length of the values param then an IllegalArgumentException
+ * is thrown.
+ *
+ * @param uniformName name matching the uniform declared in the AGSL program
+ */
+ public void setIntUniform(@NonNull String uniformName, @NonNull int[] values) {
+ if (uniformName == null) {
+ throw new NullPointerException("The uniformName parameter must not be null");
+ }
+ if (values == null) {
+ throw new NullPointerException("The uniform values parameter must not be null");
+ }
+ nativeUpdateUniforms(mBuilderNativeInstance, uniformName, values);
+ }
+
+ private void setIntUniform(@NonNull String uniformName, int value1, int value2, int value3,
+ int value4, int count) {
+ if (uniformName == null) {
+ throw new NullPointerException("The uniformName parameter must not be null");
+ }
+ nativeUpdateUniforms(mBuilderNativeInstance, uniformName, value1, value2, value3, value4,
+ count);
+ }
+
+ /**
+ * Assigns the uniform shader to the provided shader parameter. If the shader program does not
+ * have a uniform shader with that name then an IllegalArgumentException is thrown.
+ *
+ * @param shaderName name matching the uniform declared in the AGSL program
+ * @param shader shader passed into the AGSL program for sampling
+ */
+ public void setInputShader(@NonNull String shaderName, @NonNull Shader shader) {
+ if (shaderName == null) {
+ throw new NullPointerException("The shaderName parameter must not be null");
+ }
+ if (shader == null) {
+ throw new NullPointerException("The shader parameter must not be null");
+ }
+ nativeUpdateChild(mBuilderNativeInstance, shaderName, shader.getNativeInstance());
+ }
+
+ /**
+ * Assigns the uniform color filter to the provided color filter parameter. If the shader
+ * program does not have a uniform color filter with that name then an IllegalArgumentException
+ * is thrown.
+ *
+ * @param filterName name matching the uniform declared in the AGSL program
+ * @param colorFilter filter passed into the AGSL program for sampling
+ */
+ public void setInputColorFilter(@NonNull String filterName, @NonNull ColorFilter colorFilter) {
+ if (filterName == null) {
+ throw new NullPointerException("The filterName parameter must not be null");
+ }
+ if (colorFilter == null) {
+ throw new NullPointerException("The colorFilter parameter must not be null");
+ }
+ nativeUpdateChild(mBuilderNativeInstance, filterName, colorFilter.getNativeInstance());
+ }
+
+ /** @hide */
+ public long createNativeInstance() {
+ return nativeCreateNativeInstance(mBuilderNativeInstance);
+ }
+
+ /** @hide */
+ private static native long nativeGetFinalizer();
+ private static native long nativeCreateBlenderBuilder(String agsl);
+ private static native long nativeCreateNativeInstance(long builder);
+ private static native void nativeUpdateUniforms(
+ long builder, String uniformName, float[] uniforms, boolean isColor);
+ private static native void nativeUpdateUniforms(
+ long builder, String uniformName, float value1, float value2, float value3,
+ float value4, int count);
+ private static native void nativeUpdateUniforms(
+ long builder, String uniformName, int[] uniforms);
+ private static native void nativeUpdateUniforms(
+ long builder, String uniformName, int value1, int value2, int value3,
+ int value4, int count);
+ private static native void nativeUpdateChild(long builder, String childName, long child);
+
+}
diff --git a/graphics/java/android/graphics/Xfermode.java b/graphics/java/android/graphics/Xfermode.java
index 6bb22a1..fb689e4 100644
--- a/graphics/java/android/graphics/Xfermode.java
+++ b/graphics/java/android/graphics/Xfermode.java
@@ -21,9 +21,6 @@
package android.graphics;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Build;
-
/**
* Xfermode is the base class for objects that are called to implement custom
* "transfer-modes" in the drawing pipeline. The static function Create(Modes)
@@ -31,8 +28,4 @@
* specified in the Modes enum. When an Xfermode is assigned to a Paint, then
* objects drawn with that paint have the xfermode applied.
*/
-public class Xfermode {
- static final int DEFAULT = PorterDuff.Mode.SRC_OVER.nativeInt;
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- int porterDuffMode = DEFAULT;
-}
+public class Xfermode {}
diff --git a/libs/WindowManager/Shell/res/values/dimen.xml b/libs/WindowManager/Shell/res/values/dimen.xml
index 249e9a2..7078d66 100644
--- a/libs/WindowManager/Shell/res/values/dimen.xml
+++ b/libs/WindowManager/Shell/res/values/dimen.xml
@@ -661,4 +661,7 @@
<dimen name="desktop_windowing_education_promo_height">352dp</dimen>
<!-- The corner radius of the desktop windowing education promo. -->
<dimen name="desktop_windowing_education_promo_corner_radius">28dp</dimen>
+
+ <!-- The corner radius of freeform tasks in desktop windowing. -->
+ <dimen name="desktop_windowing_freeform_rounded_corner_radius">16dp</dimen>
</resources>
diff --git a/libs/WindowManager/Shell/shared/src/com/android/wm/shell/shared/GroupedTaskInfo.java b/libs/WindowManager/Shell/shared/src/com/android/wm/shell/shared/GroupedTaskInfo.java
index a31acc8..4300e84 100644
--- a/libs/WindowManager/Shell/shared/src/com/android/wm/shell/shared/GroupedTaskInfo.java
+++ b/libs/WindowManager/Shell/shared/src/com/android/wm/shell/shared/GroupedTaskInfo.java
@@ -168,6 +168,16 @@
}
/**
+ * @return The task info for the task in this group with the given {@code taskId}.
+ */
+ @Nullable
+ public TaskInfo getTaskById(int taskId) {
+ return mTasks.stream()
+ .filter(task -> task.taskId == taskId)
+ .findFirst().orElse(null);
+ }
+
+ /**
* Get all {@link RecentTaskInfo}s grouped together.
*/
@NonNull
@@ -176,6 +186,14 @@
}
/**
+ * @return Whether this grouped task contains a task with the given {@code taskId}.
+ */
+ public boolean containsTask(int taskId) {
+ return mTasks.stream()
+ .anyMatch((task -> task.taskId == taskId));
+ }
+
+ /**
* Return {@link SplitBounds} if this is a split screen entry or {@code null}
*/
@Nullable
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
index 823c533..39dc267 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
@@ -274,11 +274,8 @@
private final DragAndDropController mDragAndDropController;
/** Used to send bubble events to launcher. */
private Bubbles.BubbleStateListener mBubbleStateListener;
- /**
- * Used to track previous navigation mode to detect switch to buttons navigation. Set to
- * true to switch the bubble bar to the opposite side for 3 nav buttons mode on device boot.
- */
- private boolean mIsPrevNavModeGestures = true;
+ /** Used to track previous navigation mode to detect switch to buttons navigation. */
+ private boolean mIsPrevNavModeGestures;
/** Used to send updates to the views from {@link #mBubbleDataListener}. */
private BubbleViewCallback mBubbleViewCallback;
@@ -360,6 +357,7 @@
}
};
mExpandedViewManager = BubbleExpandedViewManager.fromBubbleController(this);
+ mIsPrevNavModeGestures = ContextUtils.isGestureNavigationMode(mContext);
}
private void registerOneHandedState(OneHandedController oneHanded) {
@@ -595,9 +593,9 @@
if (mBubbleStateListener != null) {
boolean isCurrentNavModeGestures = ContextUtils.isGestureNavigationMode(mContext);
if (mIsPrevNavModeGestures && !isCurrentNavModeGestures) {
- BubbleBarLocation bubbleBarLocation = ContextUtils.isRtl(mContext)
+ BubbleBarLocation navButtonsLocation = ContextUtils.isRtl(mContext)
? BubbleBarLocation.RIGHT : BubbleBarLocation.LEFT;
- mBubblePositioner.setBubbleBarLocation(bubbleBarLocation);
+ mBubblePositioner.setBubbleBarLocation(navButtonsLocation);
}
mIsPrevNavModeGestures = isCurrentNavModeGestures;
BubbleBarUpdate update = mBubbleData.getInitialStateForBubbleBar();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
index f532be6..12d20bf 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
@@ -96,6 +96,14 @@
}
/**
+ * Get all the displays from DisplayManager.
+ */
+ public Display[] getDisplays() {
+ final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
+ return displayManager.getDisplays();
+ }
+
+ /**
* Gets the DisplayLayout associated with a display.
*/
public @Nullable DisplayLayout getDisplayLayout(int displayId) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index 77e041e..02df38e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -795,13 +795,14 @@
static KeyguardTransitionHandler provideKeyguardTransitionHandler(
ShellInit shellInit,
ShellController shellController,
+ DisplayController displayController,
Transitions transitions,
TaskStackListenerImpl taskStackListener,
@ShellMainThread Handler mainHandler,
@ShellMainThread ShellExecutor mainExecutor) {
return new KeyguardTransitionHandler(
- shellInit, shellController, transitions, taskStackListener, mainHandler,
- mainExecutor);
+ shellInit, shellController, displayController, transitions, taskStackListener,
+ mainHandler, mainExecutor);
}
@WMSingleton
@@ -1024,10 +1025,13 @@
@WMSingleton
@Provides
static TaskStackTransitionObserver provideTaskStackTransitionObserver(
- Lazy<Transitions> transitions,
- ShellInit shellInit
+ ShellInit shellInit,
+ Lazy<ShellTaskOrganizer> shellTaskOrganizer,
+ ShellCommandHandler shellCommandHandler,
+ Lazy<Transitions> transitions
) {
- return new TaskStackTransitionObserver(transitions, shellInit);
+ return new TaskStackTransitionObserver(shellInit, shellTaskOrganizer, shellCommandHandler,
+ transitions);
}
//
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandler.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandler.kt
index 2001f97..82c2ebc 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandler.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandler.kt
@@ -23,6 +23,7 @@
import android.os.IBinder
import android.view.SurfaceControl
import android.view.WindowManager
+import android.view.WindowManager.TRANSIT_OPEN
import android.window.DesktopModeFlags
import android.window.TransitionInfo
import android.window.TransitionInfo.Change
@@ -95,7 +96,7 @@
fun startLaunchTransition(
@WindowManager.TransitionType transitionType: Int,
wct: WindowContainerTransaction,
- taskId: Int,
+ taskId: Int?,
minimizingTaskId: Int? = null,
exitingImmersiveTask: Int? = null,
): IBinder {
@@ -216,12 +217,12 @@
): Boolean {
// Check if there's also an immersive change during this launch.
val immersiveExitChange = pending.exitingImmersiveTask?.let { exitingTask ->
- findDesktopTaskChange(info, exitingTask)
+ findTaskChange(info, exitingTask)
}
val minimizeChange = pending.minimizingTask?.let { minimizingTask ->
- findDesktopTaskChange(info, minimizingTask)
+ findTaskChange(info, minimizingTask)
}
- val launchChange = findDesktopTaskChange(info, pending.launchingTask)
+ val launchChange = findDesktopTaskLaunchChange(info, pending.launchingTask)
if (launchChange == null) {
check(minimizeChange == null)
check(immersiveExitChange == null)
@@ -291,7 +292,7 @@
): Boolean {
if (!DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_BACK_NAVIGATION.isTrue) return false
- val minimizeChange = findDesktopTaskChange(info, pending.minimizingTask)
+ val minimizeChange = findTaskChange(info, pending.minimizingTask)
if (minimizeChange == null) {
logW("Should have minimizing desktop task")
return false
@@ -417,8 +418,24 @@
}
}
- private fun findDesktopTaskChange(info: TransitionInfo, taskId: Int): TransitionInfo.Change? {
- return info.changes.firstOrNull { change -> change.taskInfo?.taskId == taskId }
+ private fun findTaskChange(info: TransitionInfo, taskId: Int): TransitionInfo.Change? =
+ info.changes.firstOrNull { change -> change.taskInfo?.taskId == taskId }
+
+ private fun findDesktopTaskLaunchChange(
+ info: TransitionInfo,
+ launchTaskId: Int?
+ ): TransitionInfo.Change? {
+ return if (launchTaskId != null) {
+ // Launching a known task (probably from background or moving to front), so
+ // specifically look for it.
+ findTaskChange(info, launchTaskId)
+ } else {
+ // Launching a new task, so the first opening freeform task.
+ info.changes.firstOrNull { change ->
+ change.mode == TRANSIT_OPEN
+ && change.taskInfo != null && change.taskInfo!!.isFreeform
+ }
+ }
}
private fun WindowContainerTransaction?.merge(
@@ -441,7 +458,7 @@
/** A task is opening or moving to front. */
data class Launch(
override val transition: IBinder,
- val launchingTask: Int,
+ val launchingTask: Int?,
val minimizingTask: Int?,
val exitingImmersiveTask: Int?,
) : PendingMixedTransition()
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
index 08ca55f..7fcb767 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
@@ -411,6 +411,12 @@
desktopTaskDataByDisplayId[displayId]?.freeformTasksInZOrder?.toDumpString())
// Remove task from unminimized task if it is minimized.
unminimizeTask(displayId, taskId)
+ // Mark task as not in immersive if it was immersive.
+ setTaskInFullImmersiveState(
+ displayId = displayId,
+ taskId = taskId,
+ immersive = false
+ )
removeActiveTask(taskId)
removeVisibleTask(taskId)
if (DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PERSISTENCE.isTrue()) {
@@ -487,6 +493,9 @@
mainCoroutineScope.launch {
try {
persistentRepository.addOrUpdateDesktop(
+ // Use display id as desktop id for now since only once desktop per display
+ // is supported.
+ desktopId = displayId,
visibleTasks = desktopTaskDataByDisplayIdCopy.visibleTasks,
minimizedTasks = desktopTaskDataByDisplayIdCopy.minimizedTasks,
freeformTasksInZOrder = desktopTaskDataByDisplayIdCopy.freeformTasksInZOrder
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
index 6928c25..4db0be5 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
@@ -89,7 +89,6 @@
import com.android.wm.shell.common.SingleInstanceRemoteListener
import com.android.wm.shell.common.SyncTransactionQueue
import com.android.wm.shell.compatui.isTopActivityExemptFromDesktopWindowing
-import com.android.wm.shell.desktopmode.DesktopImmersiveController.ExitResult
import com.android.wm.shell.desktopmode.DesktopModeVisualIndicator.DragStartState
import com.android.wm.shell.desktopmode.DesktopModeVisualIndicator.IndicatorType
import com.android.wm.shell.desktopmode.DesktopRepository.VisibleTasksListener
@@ -618,25 +617,18 @@
private fun moveBackgroundTaskToFront(taskId: Int, remoteTransition: RemoteTransition?) {
logV("moveBackgroundTaskToFront taskId=%s", taskId)
val wct = WindowContainerTransaction()
- // TODO: b/342378842 - Instead of using default display, support multiple displays
- val exitResult = desktopImmersiveController.exitImmersiveIfApplicable(
- wct = wct,
- displayId = DEFAULT_DISPLAY,
- excludeTaskId = taskId,
- )
wct.startTask(
taskId,
ActivityOptions.makeBasic().apply {
launchWindowingMode = WINDOWING_MODE_FREEFORM
}.toBundle(),
)
- val transition = startLaunchTransition(
+ startLaunchTransition(
TRANSIT_OPEN,
wct,
taskId,
remoteTransition = remoteTransition
)
- exitResult.asExit()?.runOnTransitionStart?.invoke(transition)
}
/**
@@ -655,47 +647,53 @@
}
val wct = WindowContainerTransaction()
wct.reorder(taskInfo.token, true /* onTop */, true /* includingParents */)
- val result = desktopImmersiveController.exitImmersiveIfApplicable(
- wct = wct,
- displayId = taskInfo.displayId,
- excludeTaskId = taskInfo.taskId,
- )
- val exitResult = if (result is ExitResult.Exit) { result } else { null }
- val transition = startLaunchTransition(
+ startLaunchTransition(
transitionType = TRANSIT_TO_FRONT,
wct = wct,
- taskId = taskInfo.taskId,
- exitingImmersiveTask = exitResult?.exitingTask,
+ launchingTaskId = taskInfo.taskId,
remoteTransition = remoteTransition,
displayId = taskInfo.displayId,
)
- exitResult?.runOnTransitionStart?.invoke(transition)
}
private fun startLaunchTransition(
transitionType: Int,
wct: WindowContainerTransaction,
- taskId: Int,
- exitingImmersiveTask: Int? = null,
+ launchingTaskId: Int?,
remoteTransition: RemoteTransition? = null,
displayId: Int = DEFAULT_DISPLAY,
): IBinder {
- val taskIdToMinimize = addAndGetMinimizeChanges(displayId, wct, taskId)
+ val taskIdToMinimize = if (launchingTaskId != null) {
+ addAndGetMinimizeChanges(displayId, wct, newTaskId = launchingTaskId)
+ } else {
+ logW("Starting desktop task launch without checking the task-limit")
+ // TODO(b/378920066): This currently does not respect the desktop window limit.
+ // It's possible that |launchingTaskId| is null when launching using an intent, and
+ // the task-limit should be respected then too.
+ null
+ }
+ val exitImmersiveResult = desktopImmersiveController.exitImmersiveIfApplicable(
+ wct = wct,
+ displayId = displayId,
+ excludeTaskId = launchingTaskId,
+ )
if (remoteTransition == null) {
val t = desktopMixedTransitionHandler.startLaunchTransition(
transitionType = transitionType,
wct = wct,
- taskId = taskId,
+ taskId = launchingTaskId,
minimizingTaskId = taskIdToMinimize,
- exitingImmersiveTask = exitingImmersiveTask,
+ exitingImmersiveTask = exitImmersiveResult.asExit()?.exitingTask,
)
taskIdToMinimize?.let { addPendingMinimizeTransition(t, it) }
+ exitImmersiveResult.asExit()?.runOnTransitionStart?.invoke(t)
return t
}
if (taskIdToMinimize == null) {
val remoteTransitionHandler = OneShotRemoteHandler(mainExecutor, remoteTransition)
val t = transitions.startTransition(transitionType, wct, remoteTransitionHandler)
remoteTransitionHandler.setTransition(t)
+ exitImmersiveResult.asExit()?.runOnTransitionStart?.invoke(t)
return t
}
val remoteTransitionHandler =
@@ -704,6 +702,7 @@
val t = transitions.startTransition(transitionType, wct, remoteTransitionHandler)
remoteTransitionHandler.setTransition(t)
taskIdToMinimize.let { addPendingMinimizeTransition(t, it) }
+ exitImmersiveResult.asExit()?.runOnTransitionStart?.invoke(t)
return t
}
@@ -1472,10 +1471,14 @@
)
}
WINDOWING_MODE_FREEFORM -> {
- // TODO(b/336289597): This currently does not respect the desktop window limit.
val wct = WindowContainerTransaction()
wct.sendPendingIntent(launchIntent, fillIn, options.toBundle())
- transitions.startTransition(TRANSIT_OPEN, wct, null)
+ startLaunchTransition(
+ transitionType = TRANSIT_OPEN,
+ wct = wct,
+ launchingTaskId = null,
+ displayId = callingTaskInfo.displayId
+ )
}
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
index e848b88..2ae9828 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
@@ -254,8 +254,13 @@
finishT.hide(sc);
final Rect startBounds = new Rect(change.getStartAbsBounds());
animator.addUpdateListener(animation -> {
- t.setPosition(sc, startBounds.left,
- startBounds.top + (animation.getAnimatedFraction() * screenHeight));
+ final float newTop = startBounds.top + (animation.getAnimatedFraction() * screenHeight);
+ t.setPosition(sc, startBounds.left, newTop);
+ if (newTop > screenHeight) {
+ // At this point the task surface is off-screen, so hide it to prevent flicker
+ // failures. See b/377651666.
+ t.hide(sc);
+ }
t.apply();
});
animator.addListener(
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
index b618bf1..319bfac 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
@@ -42,6 +42,7 @@
import android.os.RemoteException;
import android.util.ArrayMap;
import android.util.Log;
+import android.view.Display;
import android.view.SurfaceControl;
import android.view.WindowManager;
import android.window.IRemoteTransition;
@@ -54,6 +55,7 @@
import com.android.internal.protolog.ProtoLog;
import com.android.window.flags.Flags;
+import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.common.TaskStackListenerCallback;
import com.android.wm.shell.common.TaskStackListenerImpl;
@@ -80,6 +82,8 @@
private final Transitions mTransitions;
private final ShellController mShellController;
+
+ private final DisplayController mDisplayController;
private final Handler mMainHandler;
private final ShellExecutor mMainExecutor;
@@ -121,12 +125,14 @@
public KeyguardTransitionHandler(
@NonNull ShellInit shellInit,
@NonNull ShellController shellController,
+ @NonNull DisplayController displayController,
@NonNull Transitions transitions,
@NonNull TaskStackListenerImpl taskStackListener,
@NonNull Handler mainHandler,
@NonNull ShellExecutor mainExecutor) {
mTransitions = transitions;
mShellController = shellController;
+ mDisplayController = displayController;
mMainHandler = mainHandler;
mMainExecutor = mainExecutor;
mTaskStackListener = taskStackListener;
@@ -429,10 +435,10 @@
@Override
public void startKeyguardTransition(boolean keyguardShowing, boolean aodShowing) {
final WindowContainerTransaction wct = new WindowContainerTransaction();
- final KeyguardState keyguardState =
- new KeyguardState.Builder(android.view.Display.DEFAULT_DISPLAY)
- .setKeyguardShowing(keyguardShowing).setAodShowing(aodShowing).build();
- wct.addKeyguardState(keyguardState);
+ for (Display display : mDisplayController.getDisplays()) {
+ wct.addKeyguardState(new KeyguardState.Builder(display.getDisplayId())
+ .setKeyguardShowing(keyguardShowing).setAodShowing(aodShowing).build());
+ }
mMainExecutor.execute(() -> {
mTransitions.startTransition(keyguardShowing ? TRANSIT_TO_FRONT : TRANSIT_TO_BACK,
wct, KeyguardTransitionHandler.this);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipController.java
index e901c39..6d2df95 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipController.java
@@ -16,6 +16,7 @@
package com.android.wm.shell.pip2.phone;
+import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
@@ -293,6 +294,11 @@
// Update the display layout caches even if we are not in PiP.
setDisplayLayout(mDisplayController.getDisplayLayout(displayId));
+ if (toRotation != ROTATION_UNDEFINED) {
+ // Make sure we rotate to final rotation ourselves in case display change is coming
+ // from the remote rotation as a part of an already collecting transition.
+ mPipDisplayLayoutState.rotateTo(toRotation);
+ }
if (!mPipTransitionState.isInPip()) {
// Skip the PiP-relevant updates if we aren't in a valid PiP state.
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
index d415c10..08e6727 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
@@ -241,7 +241,7 @@
extra.putParcelable(PIP_TASK_LEASH, pipChange.getLeash());
mPipTransitionState.setState(PipTransitionState.ENTERING_PIP, extra);
- if (mPipTransitionState.isInSwipePipToHomeTransition()) {
+ if (isInSwipePipToHomeTransition()) {
// If this is the second transition as a part of swipe PiP to home cuj,
// handle this transition as a special case with no-op animation.
return handleSwipePipToHomeTransition(info, startTransaction, finishTransaction,
@@ -702,6 +702,13 @@
@NonNull TransitionInfo.Change pipChange) {
TransitionInfo.Change fixedRotationChange = findFixedRotationChange(info);
int startRotation = pipChange.getStartRotation();
+ if (pipChange.getEndRotation() != ROTATION_UNDEFINED
+ && startRotation != pipChange.getEndRotation()) {
+ // If PiP change was collected along with the display change and the orientation change
+ // happened in sync with the PiP change, then do not treat this as fixed-rotation case.
+ return ROTATION_0;
+ }
+
int endRotation = fixedRotationChange != null
? fixedRotationChange.getEndFixedRotation() : mPipDisplayLayoutState.getRotation();
int delta = endRotation == ROTATION_UNDEFINED ? ROTATION_0
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java b/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
index 49cf8ae..35e6c8d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
@@ -46,6 +46,8 @@
"ShellBackPreview"),
WM_SHELL_RECENT_TASKS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
Consts.TAG_WM_SHELL),
+ WM_SHELL_TASK_OBSERVER(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, true,
+ Consts.TAG_WM_SHELL),
// TODO(b/282232877): turn logToLogcat to false.
WM_SHELL_PICTURE_IN_PICTURE(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, true,
Consts.TAG_WM_SHELL),
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/IRecentTasksListener.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/IRecentTasksListener.aidl
index b58f068..68dc0f2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/IRecentTasksListener.aidl
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/IRecentTasksListener.aidl
@@ -45,9 +45,15 @@
*/
void onRunningTaskChanged(in RunningTaskInfo taskInfo);
- /** A task has moved to front. */
- void onTaskMovedToFront(in GroupedTaskInfo[] visibleTasks);
+ /** A task has moved to front. Only used if enableShellTopTaskTracking() is disabled. */
+ void onTaskMovedToFront(in GroupedTaskInfo taskToFront);
- /** A task info has changed. */
+ /** A task info has changed. Only used if enableShellTopTaskTracking() is disabled. */
void onTaskInfoChanged(in RunningTaskInfo taskInfo);
+
+ /**
+ * If enableShellTopTaskTracking() is enabled, this reports the set of all visible tasks.
+ * Otherwise, this reports only the new top most visible task.
+ */
+ void onVisibleTasksChanged(in GroupedTaskInfo[] visibleTasks);
}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentTasksController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentTasksController.java
index cea4d33..6da4f51 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentTasksController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentTasksController.java
@@ -17,14 +17,18 @@
package com.android.wm.shell.recents;
import static android.app.ActivityTaskManager.INVALID_TASK_ID;
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.content.pm.PackageManager.FEATURE_PC;
+import static com.android.wm.shell.Flags.enableShellTopTaskTracking;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TASK_OBSERVER;
import static com.android.wm.shell.shared.ShellSharedConstants.KEY_EXTRA_SHELL_RECENT_TASKS;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
+import android.app.ActivityManager.RunningTaskInfo;
import android.app.ActivityTaskManager;
import android.app.IApplicationThread;
import android.app.KeyguardManager;
@@ -65,7 +69,6 @@
import com.android.wm.shell.sysui.ShellCommandHandler;
import com.android.wm.shell.sysui.ShellController;
import com.android.wm.shell.sysui.ShellInit;
-import com.android.wm.shell.transition.Transitions;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -111,6 +114,11 @@
private final Map<Integer, SplitBounds> mTaskSplitBoundsMap = new HashMap<>();
/**
+ * Cached list of the visible tasks, sorted from top most to bottom most.
+ */
+ private final List<RunningTaskInfo> mVisibleTasks = new ArrayList<>();
+
+ /**
* Creates {@link RecentTasksController}, returns {@code null} if the feature is not
* supported.
*/
@@ -170,10 +178,8 @@
mShellCommandHandler.addDumpCallback(this::dump, this);
mTaskStackListener.addListener(this);
mDesktopRepository.ifPresent(it -> it.addActiveTaskListener(this));
- if (Transitions.ENABLE_SHELL_TRANSITIONS) {
- mTaskStackTransitionObserver.addTaskStackTransitionObserverListener(this,
- mMainExecutor);
- }
+ mTaskStackTransitionObserver.addTaskStackTransitionObserverListener(this,
+ mMainExecutor);
mContext.getSystemService(KeyguardManager.class).addKeyguardLockedStateListener(
mMainExecutor, isKeyguardLocked -> notifyRecentTasksChanged());
}
@@ -259,7 +265,10 @@
@Override
public void onTaskStackChanged() {
- notifyRecentTasksChanged();
+ if (!enableShellTopTaskTracking()) {
+ // Skip notifying recent tasks changed whenever task stack changes
+ notifyRecentTasksChanged();
+ }
}
@Override
@@ -273,15 +282,18 @@
notifyRecentTasksChanged();
}
- public void onTaskAdded(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onTaskAdded(RunningTaskInfo taskInfo) {
notifyRunningTaskAppeared(taskInfo);
}
- public void onTaskRemoved(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onTaskRemoved(RunningTaskInfo taskInfo) {
// Remove any split pairs associated with this task
removeSplitPair(taskInfo.taskId);
- notifyRecentTasksChanged();
notifyRunningTaskVanished(taskInfo);
+ if (!enableShellTopTaskTracking()) {
+ // Only notify recent tasks changed if we aren't already notifying the visible tasks
+ notifyRecentTasksChanged();
+ }
}
/**
@@ -289,7 +301,7 @@
*
* This currently includes windowing mode and visibility.
*/
- public void onTaskRunningInfoChanged(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onTaskRunningInfoChanged(RunningTaskInfo taskInfo) {
notifyRecentTasksChanged();
notifyRunningTaskChanged(taskInfo);
}
@@ -300,14 +312,21 @@
}
@Override
+ public void onTaskMovedToFrontThroughTransition(RunningTaskInfo runningTaskInfo) {
+ notifyTaskMovedToFront(runningTaskInfo);
+ }
+
+ @Override
public void onTaskChangedThroughTransition(@NonNull ActivityManager.RunningTaskInfo taskInfo) {
notifyTaskInfoChanged(taskInfo);
}
@Override
- public void onTaskMovedToFrontThroughTransition(
- ActivityManager.RunningTaskInfo runningTaskInfo) {
- notifyTaskMovedToFront(runningTaskInfo);
+ public void onVisibleTasksChanged(@NonNull List<? extends RunningTaskInfo> visibleTasks) {
+ mVisibleTasks.clear();
+ mVisibleTasks.addAll(visibleTasks);
+ // Notify with all the info and not just the running task info
+ notifyVisibleTasksChanged(visibleTasks);
}
@VisibleForTesting
@@ -326,7 +345,7 @@
/**
* Notify the running task listener that a task appeared on desktop environment.
*/
- private void notifyRunningTaskAppeared(ActivityManager.RunningTaskInfo taskInfo) {
+ private void notifyRunningTaskAppeared(RunningTaskInfo taskInfo) {
if (mListener == null
|| !shouldEnableRunningTasksForDesktopMode()
|| taskInfo.realActivity == null) {
@@ -340,9 +359,25 @@
}
/**
+ * Notify the running task listener that a task was changed on desktop environment.
+ */
+ private void notifyRunningTaskChanged(RunningTaskInfo taskInfo) {
+ if (mListener == null
+ || !shouldEnableRunningTasksForDesktopMode()
+ || taskInfo.realActivity == null) {
+ return;
+ }
+ try {
+ mListener.onRunningTaskChanged(taskInfo);
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Failed call onRunningTaskChanged", e);
+ }
+ }
+
+ /**
* Notify the running task listener that a task was removed on desktop environment.
*/
- private void notifyRunningTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
+ private void notifyRunningTaskVanished(RunningTaskInfo taskInfo) {
if (mListener == null
|| !shouldEnableRunningTasksForDesktopMode()
|| taskInfo.realActivity == null) {
@@ -356,25 +391,30 @@
}
/**
- * Notify the running task listener that a task was changed on desktop environment.
+ * Notify the recents task listener that a task moved to front via a transition.
*/
- private void notifyRunningTaskChanged(ActivityManager.RunningTaskInfo taskInfo) {
+ private void notifyTaskMovedToFront(ActivityManager.RunningTaskInfo taskInfo) {
if (mListener == null
- || !shouldEnableRunningTasksForDesktopMode()
- || taskInfo.realActivity == null) {
+ || !DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL.isTrue()
+ || taskInfo.realActivity == null
+ || enableShellTopTaskTracking()) {
return;
}
try {
- mListener.onRunningTaskChanged(taskInfo);
+ mListener.onTaskMovedToFront(GroupedTaskInfo.forFullscreenTasks(taskInfo));
} catch (RemoteException e) {
- Slog.w(TAG, "Failed call onRunningTaskChanged", e);
+ Slog.w(TAG, "Failed call onTaskMovedToFront", e);
}
}
+ /**
+ * Notify the recents task listener that a task changed via a transition.
+ */
private void notifyTaskInfoChanged(ActivityManager.RunningTaskInfo taskInfo) {
if (mListener == null
|| !DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL.isTrue()
- || taskInfo.realActivity == null) {
+ || taskInfo.realActivity == null
+ || enableShellTopTaskTracking()) {
return;
}
try {
@@ -384,17 +424,21 @@
}
}
- private void notifyTaskMovedToFront(ActivityManager.RunningTaskInfo taskInfo) {
+ /**
+ * Notifies that the test of visible tasks have changed.
+ */
+ private void notifyVisibleTasksChanged(@NonNull List<? extends RunningTaskInfo> visibleTasks) {
if (mListener == null
|| !DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL.isTrue()
- || taskInfo.realActivity == null) {
+ || !enableShellTopTaskTracking()) {
return;
}
try {
- GroupedTaskInfo runningTask = GroupedTaskInfo.forFullscreenTasks(taskInfo);
- mListener.onTaskMovedToFront(new GroupedTaskInfo[]{ runningTask });
+ // Compute the visible recent tasks in order, and move the task to the top
+ mListener.onVisibleTasksChanged(generateList(visibleTasks)
+ .toArray(new GroupedTaskInfo[0]));
} catch (RemoteException e) {
- Slog.w(TAG, "Failed call onTaskMovedToFront", e);
+ Slog.w(TAG, "Failed call onVisibleTasksChanged", e);
}
}
@@ -407,6 +451,11 @@
@VisibleForTesting
void registerRecentTasksListener(IRecentTasksListener listener) {
mListener = listener;
+ if (enableShellTopTaskTracking()) {
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "registerRecentTasksListener");
+ // Post a notification for the current set of visible tasks
+ mMainExecutor.executeDelayed(() -> notifyVisibleTasksChanged(mVisibleTasks), 0);
+ }
}
@VisibleForTesting
@@ -421,14 +470,18 @@
@VisibleForTesting
ArrayList<GroupedTaskInfo> getRecentTasks(int maxNum, int flags, int userId) {
- // Note: the returned task list is from the most-recent to least-recent order
- final List<RecentTaskInfo> rawList = mActivityTaskManager.getRecentTasks(
- maxNum, flags, userId);
+ // Note: the returned task list is ordered from the most-recent to least-recent order
+ return generateList(mActivityTaskManager.getRecentTasks(maxNum, flags, userId));
+ }
+ /**
+ * Generates a list of GroupedTaskInfos for the given list of tasks.
+ */
+ private <T extends TaskInfo> ArrayList<GroupedTaskInfo> generateList(@NonNull List<T> tasks) {
// Make a mapping of task id -> task info
final SparseArray<TaskInfo> rawMapping = new SparseArray<>();
- for (int i = 0; i < rawList.size(); i++) {
- final TaskInfo taskInfo = rawList.get(i);
+ for (int i = 0; i < tasks.size(); i++) {
+ final TaskInfo taskInfo = tasks.get(i);
rawMapping.put(taskInfo.taskId, taskInfo);
}
@@ -437,10 +490,10 @@
int mostRecentFreeformTaskIndex = Integer.MAX_VALUE;
+ ArrayList<GroupedTaskInfo> groupedTasks = new ArrayList<>();
// Pull out the pairs as we iterate back in the list
- ArrayList<GroupedTaskInfo> recentTasks = new ArrayList<>();
- for (int i = 0; i < rawList.size(); i++) {
- final RecentTaskInfo taskInfo = rawList.get(i);
+ for (int i = 0; i < tasks.size(); i++) {
+ final TaskInfo taskInfo = tasks.get(i);
if (!rawMapping.contains(taskInfo.taskId)) {
// If it's not in the mapping, then it was already paired with another task
continue;
@@ -451,7 +504,7 @@
&& mDesktopRepository.get().isActiveTask(taskInfo.taskId)) {
// Freeform tasks will be added as a separate entry
if (mostRecentFreeformTaskIndex == Integer.MAX_VALUE) {
- mostRecentFreeformTaskIndex = recentTasks.size();
+ mostRecentFreeformTaskIndex = groupedTasks.size();
}
// If task has their app bounds set to null which happens after reboot, set the
// app bounds to persisted lastFullscreenBounds. Also set the position in parent
@@ -471,36 +524,34 @@
}
final int pairedTaskId = mSplitTasks.get(taskInfo.taskId, INVALID_TASK_ID);
- if (pairedTaskId != INVALID_TASK_ID && rawMapping.contains(
- pairedTaskId)) {
+ if (pairedTaskId != INVALID_TASK_ID && rawMapping.contains(pairedTaskId)) {
final TaskInfo pairedTaskInfo = rawMapping.get(pairedTaskId);
rawMapping.remove(pairedTaskId);
- recentTasks.add(GroupedTaskInfo.forSplitTasks(taskInfo, pairedTaskInfo,
+ groupedTasks.add(GroupedTaskInfo.forSplitTasks(taskInfo, pairedTaskInfo,
mTaskSplitBoundsMap.get(pairedTaskId)));
} else {
- recentTasks.add(GroupedTaskInfo.forFullscreenTasks(taskInfo));
+ // TODO(346588978): Consolidate multiple visible fullscreen tasks into the same
+ // grouped task
+ groupedTasks.add(GroupedTaskInfo.forFullscreenTasks(taskInfo));
}
}
// Add a special entry for freeform tasks
if (!freeformTasks.isEmpty()) {
- recentTasks.add(mostRecentFreeformTaskIndex,
+ groupedTasks.add(mostRecentFreeformTaskIndex,
GroupedTaskInfo.forFreeformTasks(
freeformTasks,
minimizedFreeformTasks));
}
- return recentTasks;
- }
+ if (enableShellTopTaskTracking()) {
+ // We don't current send pinned tasks as a part of recent or running tasks, so remove
+ // them from the list here
+ groupedTasks.removeIf(
+ gti -> gti.getTaskInfo1().getWindowingMode() == WINDOWING_MODE_PINNED);
+ }
- /**
- * Returns the top running leaf task.
- */
- @Nullable
- public ActivityManager.RunningTaskInfo getTopRunningTask() {
- List<ActivityManager.RunningTaskInfo> tasks = mActivityTaskManager.getTasks(1,
- false /* filterOnlyVisibleRecents */);
- return tasks.isEmpty() ? null : tasks.get(0);
+ return groupedTasks;
}
/**
@@ -508,12 +559,13 @@
* NOTE: This path currently makes assumptions that ignoreTaskToken is for the top task.
*/
@Nullable
- public ActivityManager.RunningTaskInfo getTopRunningTask(
+ public RunningTaskInfo getTopRunningTask(
@Nullable WindowContainerToken ignoreTaskToken) {
- List<ActivityManager.RunningTaskInfo> tasks = mActivityTaskManager.getTasks(2,
- false /* filterOnlyVisibleRecents */);
+ final List<RunningTaskInfo> tasks = enableShellTopTaskTracking()
+ ? mVisibleTasks
+ : mActivityTaskManager.getTasks(2, false /* filterOnlyVisibleRecents */);
for (int i = 0; i < tasks.size(); i++) {
- final ActivityManager.RunningTaskInfo task = tasks.get(i);
+ final RunningTaskInfo task = tasks.get(i);
if (task.token.equals(ignoreTaskToken)) {
continue;
}
@@ -551,7 +603,7 @@
}
/**
- * Find the background task that match the given taskId.
+ * Find the background task (in the recent tasks list) that matches the given taskId.
*/
@Nullable
public RecentTaskInfo findTaskInBackground(int taskId) {
@@ -648,29 +700,34 @@
}
@Override
- public void onRunningTaskAppeared(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onRunningTaskAppeared(RunningTaskInfo taskInfo) {
mListener.call(l -> l.onRunningTaskAppeared(taskInfo));
}
@Override
- public void onRunningTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onRunningTaskVanished(RunningTaskInfo taskInfo) {
mListener.call(l -> l.onRunningTaskVanished(taskInfo));
}
@Override
- public void onRunningTaskChanged(ActivityManager.RunningTaskInfo taskInfo) {
+ public void onRunningTaskChanged(RunningTaskInfo taskInfo) {
mListener.call(l -> l.onRunningTaskChanged(taskInfo));
}
@Override
- public void onTaskMovedToFront(GroupedTaskInfo[] taskInfo) {
- mListener.call(l -> l.onTaskMovedToFront(taskInfo));
+ public void onTaskMovedToFront(GroupedTaskInfo taskToFront) {
+ mListener.call(l -> l.onTaskMovedToFront(taskToFront));
}
@Override
public void onTaskInfoChanged(ActivityManager.RunningTaskInfo taskInfo) {
mListener.call(l -> l.onTaskInfoChanged(taskInfo));
}
+
+ @Override
+ public void onVisibleTasksChanged(GroupedTaskInfo[] visibleTasks) {
+ mListener.call(l -> l.onVisibleTasksChanged(visibleTasks));
+ }
};
public IRecentTasksImpl(RecentTasksController controller) {
@@ -724,12 +781,12 @@
}
@Override
- public ActivityManager.RunningTaskInfo[] getRunningTasks(int maxNum) {
- final ActivityManager.RunningTaskInfo[][] tasks =
- new ActivityManager.RunningTaskInfo[][]{null};
+ public RunningTaskInfo[] getRunningTasks(int maxNum) {
+ final RunningTaskInfo[][] tasks =
+ new RunningTaskInfo[][]{null};
executeRemoteCallWithTaskPermission(mController, "getRunningTasks",
(controller) -> tasks[0] = ActivityTaskManager.getInstance().getTasks(maxNum)
- .toArray(new ActivityManager.RunningTaskInfo[0]),
+ .toArray(new RunningTaskInfo[0]),
true /* blocking */);
return tasks[0];
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/TaskStackTransitionObserver.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/TaskStackTransitionObserver.kt
index d28a462..93f2e4c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/TaskStackTransitionObserver.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/TaskStackTransitionObserver.kt
@@ -17,37 +17,162 @@
package com.android.wm.shell.recents
import android.app.ActivityManager.RunningTaskInfo
+import android.app.WindowConfiguration.WINDOWING_MODE_PINNED
import android.os.IBinder
import android.util.ArrayMap
import android.view.SurfaceControl
import android.view.WindowManager.TRANSIT_CHANGE
import android.window.DesktopModeFlags
import android.window.TransitionInfo
+import com.android.internal.protolog.ProtoLog
+import com.android.wm.shell.Flags.enableShellTopTaskTracking
+import com.android.wm.shell.ShellTaskOrganizer
+import com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TASK_OBSERVER
import com.android.wm.shell.shared.TransitionUtil
+import com.android.wm.shell.sysui.ShellCommandHandler
import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
import dagger.Lazy
+import java.io.PrintWriter
+import java.util.StringJoiner
import java.util.concurrent.Executor
/**
- * A [Transitions.TransitionObserver] that observes shell transitions and sends updates to listeners
- * about task stack changes.
+ * A [Transitions.TransitionObserver] that observes shell transitions, tracks the visible tasks
+ * and notifies listeners whenever the visible tasks change (at the start and end of a transition).
*
- * TODO(346588978) Move split/pip signals here as well so that launcher don't need to handle it
+ * This can be replaced once we have a generalized task repository tracking visible tasks.
*/
class TaskStackTransitionObserver(
+ shellInit: ShellInit,
+ private val shellTaskOrganizer: Lazy<ShellTaskOrganizer>,
+ private val shellCommandHandler: ShellCommandHandler,
private val transitions: Lazy<Transitions>,
- shellInit: ShellInit
-) : Transitions.TransitionObserver {
+) : Transitions.TransitionObserver, ShellTaskOrganizer.TaskVanishedListener {
+
+ // List of currently visible tasks sorted in z-order from top-most to bottom-most, only used
+ // when Flags.enableShellTopTaskTracking() is enabled.
+ private var visibleTasks: MutableList<RunningTaskInfo> = mutableListOf()
+ private val pendingCloseTasks: MutableList<RunningTaskInfo> = mutableListOf()
+ // Set of listeners to notify when the visible tasks change
private val taskStackTransitionObserverListeners =
ArrayMap<TaskStackTransitionObserverListener, Executor>()
+ // Used to filter out leaf-tasks
+ private val leafTaskFilter: TransitionUtil.LeafTaskFilter = TransitionUtil.LeafTaskFilter()
init {
shellInit.addInitCallback(::onInit, this)
}
fun onInit() {
+ shellTaskOrganizer.get().addTaskVanishedListener(this)
+ shellCommandHandler.addDumpCallback(::dump, this)
transitions.get().registerObserver(this)
+
+ // TODO(346588978): We need to update the running tasks once the ShellTaskOrganizer is
+ // registered since there is no existing transition (yet) corresponding for the already
+ // visible tasks
+ }
+
+ /**
+ * This method handles transition ready when only
+ * DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL is set.
+ */
+ private fun onDesktopOnlyFlagTransitionReady(info: TransitionInfo) {
+ for (change in info.changes) {
+ if (change.flags and TransitionInfo.FLAG_IS_WALLPAPER != 0) {
+ continue
+ }
+
+ val taskInfo = change.taskInfo
+ if (taskInfo == null || taskInfo.taskId == -1) {
+ continue
+ }
+
+ // Find the first task that is opening, this should be the one at the front after
+ // the transition
+ if (TransitionUtil.isOpeningType(change.mode)) {
+ notifyOnTaskMovedToFront(taskInfo)
+ break
+ } else if (change.mode == TRANSIT_CHANGE) {
+ notifyOnTaskChanged(taskInfo)
+ }
+ }
+ }
+
+ /**
+ * This method handles transition ready when Flags.enableShellTopTaskTracking() is set.
+ */
+ private fun onShellTopTaskTrackerFlagTransitionReady(info: TransitionInfo) {
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "Transition ready: %d", info.debugId)
+
+ // Filter out non-leaf tasks (we will likely need them later, but visible task tracking
+ // is currently used only for visible leaf tasks)
+ val changesReversed = mutableListOf<TransitionInfo.Change>()
+ for (change in info.changes) {
+ if (!leafTaskFilter.test(change)) {
+ // Not a leaf task
+ continue
+ }
+ changesReversed.add(0, change)
+ }
+
+ // We iterate the change list in reverse order because changes are sorted top to bottom and
+ // we want to update the lists such that the top most tasks are inserted at the front last
+ var notifyChanges = false
+ for (change in changesReversed) {
+ val taskInfo = change.taskInfo
+ if (taskInfo == null || taskInfo.taskId == -1) {
+ // Not a valid task
+ continue
+ }
+
+ if (TransitionUtil.isClosingMode(change.mode)) {
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "\tClosing task=%d", taskInfo.taskId)
+
+ // Closing task's visibilities are not committed until after the transition
+ // completes, so track such tasks so that we can notify on finish
+ if (!pendingCloseTasks.any { it.taskId == taskInfo.taskId }) {
+ pendingCloseTasks.add(taskInfo)
+ }
+ } else if (TransitionUtil.isOpeningMode(change.mode)
+ || TransitionUtil.isOrderOnly(change)) {
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "\tOpening task=%d", taskInfo.taskId)
+
+ // Remove from pending close tasks list if it's being opened again
+ pendingCloseTasks.removeIf { it.taskId == taskInfo.taskId }
+ // Move the task to the front of the visible tasks list
+ visibleTasks.removeIf { it.taskId == taskInfo.taskId }
+ visibleTasks.add(0, taskInfo)
+ notifyChanges = true
+ }
+ }
+
+ // TODO(346588978): We should verify the task list has actually changed before notifying
+ // (ie. starting an activity that's already top-most would result in no visible change)
+ if (notifyChanges) {
+ updateVisibleTasksList("transition-start")
+ }
+ }
+
+ private fun updateVisibleTasksList(reason: String) {
+ // This simply constructs a list of visible tasks, where the always-on-top tasks are moved
+ // to the front of the list in-order, to ensure that they match the visible z order
+ val orderedVisibleTasks = mutableListOf<RunningTaskInfo>()
+ var numAlwaysOnTop = 0
+ for (info in visibleTasks) {
+ if (info.windowingMode == WINDOWING_MODE_PINNED
+ || info.configuration.windowConfiguration.isAlwaysOnTop) {
+ orderedVisibleTasks.add(numAlwaysOnTop, info)
+ numAlwaysOnTop++
+ } else {
+ orderedVisibleTasks.add(info)
+ }
+ }
+ visibleTasks = orderedVisibleTasks
+
+ dumpVisibleTasks(reason)
+ notifyVisibleTasksChanged(visibleTasks)
}
override fun onTransitionReady(
@@ -56,26 +181,10 @@
startTransaction: SurfaceControl.Transaction,
finishTransaction: SurfaceControl.Transaction
) {
- if (DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL.isTrue) {
- for (change in info.changes) {
- if (change.flags and TransitionInfo.FLAG_IS_WALLPAPER != 0) {
- continue
- }
-
- val taskInfo = change.taskInfo
- if (taskInfo == null || taskInfo.taskId == -1) {
- continue
- }
-
- // Find the first task that is opening, this should be the one at the front after
- // the transition
- if (TransitionUtil.isOpeningType(change.mode)) {
- notifyOnTaskMovedToFront(taskInfo)
- break
- } else if (change.mode == TRANSIT_CHANGE) {
- notifyOnTaskChanged(taskInfo)
- }
- }
+ if (enableShellTopTaskTracking()) {
+ onShellTopTaskTrackerFlagTransitionReady(info)
+ } else if (DesktopModeFlags.ENABLE_TASK_STACK_OBSERVER_IN_SHELL.isTrue) {
+ onDesktopOnlyFlagTransitionReady(info)
}
}
@@ -83,8 +192,35 @@
override fun onTransitionMerged(merged: IBinder, playing: IBinder) {}
- override fun onTransitionFinished(transition: IBinder, aborted: Boolean) {}
+ override fun onTransitionFinished(transition: IBinder, aborted: Boolean) {
+ if (enableShellTopTaskTracking()) {
+ if (pendingCloseTasks.isNotEmpty()) {
+ // Update the visible task list based on the pending close tasks
+ for (change in pendingCloseTasks) {
+ visibleTasks.removeIf {
+ it.taskId == change.taskId
+ }
+ }
+ updateVisibleTasksList("transition-finished")
+ }
+ }
+ }
+ override fun onTaskVanished(taskInfo: RunningTaskInfo?) {
+ if (!enableShellTopTaskTracking()) {
+ return
+ }
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "Task vanished: task=%d", taskInfo?.taskId)
+ pendingCloseTasks.removeIf { it.taskId == taskInfo?.taskId }
+ if (visibleTasks.any { it.taskId == taskInfo?.taskId }) {
+ visibleTasks.removeIf { it.taskId == taskInfo?.taskId }
+ updateVisibleTasksList("task-vanished")
+ }
+ }
+
+ /**
+ * Adds a new task stack observer.
+ */
fun addTaskStackTransitionObserverListener(
taskStackTransitionObserverListener: TaskStackTransitionObserverListener,
executor: Executor
@@ -92,6 +228,9 @@
taskStackTransitionObserverListeners[taskStackTransitionObserverListener] = executor
}
+ /**
+ * Removes an existing task stack observer.
+ */
fun removeTaskStackTransitionObserverListener(
taskStackTransitionObserverListener: TaskStackTransitionObserverListener
) {
@@ -99,22 +238,66 @@
}
private fun notifyOnTaskMovedToFront(taskInfo: RunningTaskInfo) {
+ if (enableShellTopTaskTracking()) {
+ return
+ }
taskStackTransitionObserverListeners.forEach { (listener, executor) ->
executor.execute { listener.onTaskMovedToFrontThroughTransition(taskInfo) }
}
}
private fun notifyOnTaskChanged(taskInfo: RunningTaskInfo) {
+ if (enableShellTopTaskTracking()) {
+ return
+ }
taskStackTransitionObserverListeners.forEach { (listener, executor) ->
executor.execute { listener.onTaskChangedThroughTransition(taskInfo) }
}
}
+ private fun notifyVisibleTasksChanged(visibleTasks: List<RunningTaskInfo>) {
+ taskStackTransitionObserverListeners.forEach { (listener, executor) ->
+ executor.execute { listener.onVisibleTasksChanged(visibleTasks) }
+ }
+ }
+
+ fun dump(pw: PrintWriter, prefix: String) {
+ pw.println("${prefix}$TAG:")
+
+ if (visibleTasks.isEmpty()) {
+ pw.println("$prefix visibleTasks=[]")
+ } else {
+ val stringJoiner = StringJoiner(",\n\t", "[\n\t", "\n]")
+ visibleTasks.forEach {
+ stringJoiner.add("id=${it.taskId} cmp=${it.baseIntent.component}")
+ }
+ pw.println("$prefix visibleTasks=$stringJoiner")
+ }
+ }
+
+ /** Dumps the set of visible tasks to protolog */
+ private fun dumpVisibleTasks(reason: String) {
+ if (!WM_SHELL_TASK_OBSERVER.isEnabled) {
+ return
+ }
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "\tVisible tasks (%s)", reason)
+ for (task in visibleTasks) {
+ ProtoLog.v(WM_SHELL_TASK_OBSERVER, "\t\ttaskId=%d package=%s", task.taskId,
+ task.baseIntent.component?.packageName)
+ }
+ }
+
/** Listener to use to get updates regarding task stack from this observer */
interface TaskStackTransitionObserverListener {
/** Called when a task is moved to front. */
fun onTaskMovedToFrontThroughTransition(taskInfo: RunningTaskInfo) {}
+ /** Called when the set of visible tasks have changed. */
+ fun onVisibleTasksChanged(visibleTasks: List<RunningTaskInfo>) {}
/** Called when a task info has changed. */
fun onTaskChangedThroughTransition(taskInfo: RunningTaskInfo) {}
}
+
+ companion object {
+ const val TAG = "TaskStackTransitionObserver"
+ }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
index cdcf14e..9cb9d25 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
@@ -81,7 +81,6 @@
import android.window.WindowContainerTransaction;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.policy.ScreenDecorationsUtils;
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.icons.IconProvider;
import com.android.window.flags.Flags;
@@ -1008,8 +1007,10 @@
relayoutParams.mWindowDecorConfig = windowDecorConfig;
if (DesktopModeStatus.useRoundedCorners()) {
- relayoutParams.mCornerRadius =
- (int) ScreenDecorationsUtils.getWindowCornerRadius(context);
+ relayoutParams.mCornerRadius = taskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM
+ ? loadDimensionPixelSize(context.getResources(),
+ R.dimen.desktop_windowing_freeform_rounded_corner_radius)
+ : INVALID_CORNER_RADIUS;
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
index a3c75bf..99f3799 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
@@ -107,6 +107,11 @@
static final int INPUT_SINK_Z_ORDER = -2;
/**
+ * Invalid corner radius that signifies that corner radius should not be set.
+ */
+ static final int INVALID_CORNER_RADIUS = -1;
+
+ /**
* System-wide context. Only used to create context with overridden configurations.
*/
final Context mContext;
@@ -449,20 +454,22 @@
startT.show(mTaskSurface);
}
- if (mTaskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
- if (!DesktopModeStatus.isVeiledResizeEnabled()) {
- // When fluid resize is enabled, add a background to freeform tasks
- int backgroundColorInt = mTaskInfo.taskDescription.getBackgroundColor();
- mTmpColor[0] = (float) Color.red(backgroundColorInt) / 255.f;
- mTmpColor[1] = (float) Color.green(backgroundColorInt) / 255.f;
- mTmpColor[2] = (float) Color.blue(backgroundColorInt) / 255.f;
- startT.setColor(mTaskSurface, mTmpColor);
- }
- startT.setCornerRadius(mTaskSurface, params.mCornerRadius);
- finishT.setCornerRadius(mTaskSurface, params.mCornerRadius);
+ if (mTaskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM
+ && !DesktopModeStatus.isVeiledResizeEnabled()) {
+ // When fluid resize is enabled, add a background to freeform tasks
+ int backgroundColorInt = mTaskInfo.taskDescription.getBackgroundColor();
+ mTmpColor[0] = (float) Color.red(backgroundColorInt) / 255.f;
+ mTmpColor[1] = (float) Color.green(backgroundColorInt) / 255.f;
+ mTmpColor[2] = (float) Color.blue(backgroundColorInt) / 255.f;
+ startT.setColor(mTaskSurface, mTmpColor);
} else if (!DesktopModeStatus.isVeiledResizeEnabled()) {
startT.unsetColor(mTaskSurface);
}
+
+ if (params.mCornerRadius != INVALID_CORNER_RADIUS) {
+ startT.setCornerRadius(mTaskSurface, params.mCornerRadius);
+ finishT.setCornerRadius(mTaskSurface, params.mCornerRadius);
+ }
}
/**
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontLandscape.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontLandscape.kt
new file mode 100644
index 0000000..898964f
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontLandscape.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker
+
+import android.tools.Rotation.ROTATION_90
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.DesktopModeFlickerScenarios.Companion.BRING_APPS_TO_FRONT
+import com.android.wm.shell.scenarios.BringDesktopAppsToFront
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Bring apps to front by clicking on the App Header.
+ *
+ * Assert that the app windows move to front.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class BringDesktopAppsToFrontLandscape : BringDesktopAppsToFront(rotation = ROTATION_90) {
+
+ @ExpectedScenarios(["BRING_APPS_TO_FRONT"])
+ @Test
+ override fun bringDesktopAppsToFront() = super.bringDesktopAppsToFront()
+
+ companion object {
+ @JvmStatic
+ @FlickerConfigProvider
+ fun flickerConfigProvider(): FlickerConfig =
+ FlickerConfig()
+ .use(FlickerServiceConfig.DEFAULT)
+ .use(BRING_APPS_TO_FRONT)
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontPortrait.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontPortrait.kt
new file mode 100644
index 0000000..b123d7d
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/BringDesktopAppsToFrontPortrait.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker
+
+import android.tools.Rotation.ROTATION_0
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.DesktopModeFlickerScenarios.Companion.BRING_APPS_TO_FRONT
+import com.android.wm.shell.scenarios.BringDesktopAppsToFront
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Bring apps to front by clicking on the App Header.
+ *
+ * Assert that the app windows move to front.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class BringDesktopAppsToFrontPortrait : BringDesktopAppsToFront(rotation = ROTATION_0) {
+
+ @ExpectedScenarios(["BRING_APPS_TO_FRONT"])
+ @Test
+ override fun bringDesktopAppsToFront() = super.bringDesktopAppsToFront()
+
+ companion object {
+ @JvmStatic
+ @FlickerConfigProvider
+ fun flickerConfigProvider(): FlickerConfig =
+ FlickerConfig()
+ .use(FlickerServiceConfig.DEFAULT)
+ .use(BRING_APPS_TO_FRONT)
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/DesktopModeFlickerScenarios.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/DesktopModeFlickerScenarios.kt
index 4cddf31..88dc548 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/DesktopModeFlickerScenarios.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/DesktopModeFlickerScenarios.kt
@@ -25,6 +25,7 @@
import android.tools.flicker.assertors.assertions.AppLayerIsVisibleAtStart
import android.tools.flicker.assertors.assertions.AppWindowAlignsWithOnlyOneDisplayCornerAtEnd
import android.tools.flicker.assertors.assertions.AppWindowBecomesInvisible
+import android.tools.flicker.assertors.assertions.AppWindowBecomesTopWindow
import android.tools.flicker.assertors.assertions.AppWindowBecomesVisible
import android.tools.flicker.assertors.assertions.AppWindowCoversLeftHalfScreenAtEnd
import android.tools.flicker.assertors.assertions.AppWindowCoversRightHalfScreenAtEnd
@@ -345,6 +346,30 @@
).associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
)
+ val BRING_APPS_TO_FRONT =
+ FlickerConfigEntry(
+ scenarioId = ScenarioId("BRING_APPS_TO_FRONT"),
+ extractor =
+ ShellTransitionScenarioExtractor(
+ transitionMatcher =
+ object : ITransitionMatcher {
+ override fun findAll(
+ transitions: Collection<Transition>
+ ): Collection<Transition> {
+ return transitions.filter {
+ it.type == TransitionType.TO_FRONT
+ }
+ }
+ }
+ ),
+ assertions =
+ AssertionTemplates.COMMON_ASSERTIONS +
+ listOf(
+ AppWindowBecomesTopWindow(DESKTOP_MODE_APP),
+ AppWindowOnTopAtEnd(DESKTOP_MODE_APP),
+ ).associateBy({ it }, { AssertionInvocationGroup.BLOCKING })
+ )
+
val CASCADE_APP =
FlickerConfigEntry(
scenarioId = ScenarioId("CASCADE_APP"),
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZoneLandscape.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZoneLandscape.kt
new file mode 100644
index 0000000..e1120bd
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZoneLandscape.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker
+
+import android.tools.Rotation.ROTATION_90
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.DesktopModeFlickerScenarios.Companion.MAXIMIZE_APP
+import com.android.wm.shell.scenarios.MaximizeAppWindowWithDragToTopDragZone
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Maximize app window by dragging it to the top drag zone.
+ *
+ * Assert that the app window keeps the same increases in size, filling the vertical and horizontal
+ * stable display bounds.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class MaximizeAppWindowWithDragToTopDragZoneLandscape : MaximizeAppWindowWithDragToTopDragZone(
+ rotation = ROTATION_90
+) {
+ @ExpectedScenarios(["MAXIMIZE_APP"])
+ @Test
+ override fun maximizeAppWithDragToTopDragZone() = super.maximizeAppWithDragToTopDragZone()
+
+ companion object {
+ @JvmStatic
+ @FlickerConfigProvider
+ fun flickerConfigProvider(): FlickerConfig =
+ FlickerConfig().use(FlickerServiceConfig.DEFAULT).use(MAXIMIZE_APP)
+ }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZonePortrait.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZonePortrait.kt
new file mode 100644
index 0000000..fb910c7
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/flicker-service/src/com/android/wm/shell/flicker/MaximizeAppWindowWithDragToTopDragZonePortrait.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker
+
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.DesktopModeFlickerScenarios.Companion.MAXIMIZE_APP
+import com.android.wm.shell.scenarios.MaximizeAppWindowWithDragToTopDragZone
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Maximize app window by dragging it to the top drag zone.
+ *
+ * Assert that the app window keeps the same increases in size, filling the vertical and horizontal
+ * stable display bounds.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class MaximizeAppWindowWithDragToTopDragZonePortrait : MaximizeAppWindowWithDragToTopDragZone() {
+ @ExpectedScenarios(["MAXIMIZE_APP"])
+ @Test
+ override fun maximizeAppWithDragToTopDragZone() = super.maximizeAppWithDragToTopDragZone()
+
+ companion object {
+ @JvmStatic
+ @FlickerConfigProvider
+ fun flickerConfigProvider(): FlickerConfig =
+ FlickerConfig().use(FlickerServiceConfig.DEFAULT).use(MAXIMIZE_APP)
+ }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/functional/BringDesktopAppsToFrontTest.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/functional/BringDesktopAppsToFrontTest.kt
new file mode 100644
index 0000000..6c8cc68
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/functional/BringDesktopAppsToFrontTest.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.functional
+
+import android.platform.test.annotations.Postsubmit
+import com.android.wm.shell.scenarios.BringDesktopAppsToFront
+import org.junit.runner.RunWith
+import org.junit.runners.BlockJUnit4ClassRunner
+
+/** Functional test for [BringDesktopAppsToFront]. */
+@RunWith(BlockJUnit4ClassRunner::class)
+@Postsubmit
+class BringDesktopAppsToFrontTest : BringDesktopAppsToFront()
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/BringDesktopAppsToFront.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/BringDesktopAppsToFront.kt
new file mode 100644
index 0000000..1db22eb
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/BringDesktopAppsToFront.kt
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.scenarios
+
+import android.tools.NavBar
+import android.tools.Rotation
+import android.tools.flicker.rules.ChangeDisplayOrientationRule
+import com.android.server.wm.flicker.helpers.DesktopModeAppHelper
+import com.android.server.wm.flicker.helpers.MailAppHelper
+import com.android.window.flags.Flags
+import com.android.wm.shell.Utils
+import org.junit.After
+import org.junit.Assume
+import org.junit.Before
+import org.junit.Ignore
+import org.junit.Rule
+import org.junit.Test
+
+@Ignore("Test Base Class")
+abstract class BringDesktopAppsToFront(
+ val rotation: Rotation = Rotation.ROTATION_0,
+ isResizable: Boolean = true,
+ isLandscapeApp: Boolean = true,
+) : DesktopScenarioCustomAppTestBase(isResizable, isLandscapeApp) {
+
+ private val mailApp = DesktopModeAppHelper(MailAppHelper(instrumentation))
+
+ @Rule
+ @JvmField val testSetupRule = Utils.testSetupRule(NavBar.MODE_GESTURAL, rotation)
+
+ @Before
+ fun setup() {
+ Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
+ tapl.setEnableRotation(true)
+ tapl.setExpectedRotation(rotation.value)
+ ChangeDisplayOrientationRule.setRotation(rotation)
+ tapl.enableTransientTaskbar(false)
+ // Launch a first app and snap it to left side so that it doesn't overlap too much with
+ // the next launching app, and their headers are visible enough to switch focus by tapping
+ // on them.
+ testApp.enterDesktopMode(wmHelper, device)
+ testApp.snapResizeDesktopApp(wmHelper, device, instrumentation.context, toLeft = true)
+ mailApp.launchViaIntent(wmHelper)
+ }
+
+ @Test
+ open fun bringDesktopAppsToFront() {
+ testApp.bringToFront(wmHelper, device)
+ mailApp.bringToFront(wmHelper, device)
+ testApp.bringToFront(wmHelper, device)
+ mailApp.bringToFront(wmHelper, device)
+ }
+
+ @After
+ fun teardown() {
+ mailApp.exit(wmHelper)
+ testApp.exit(wmHelper)
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/CloseAllAppsWithAppHeaderExit.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/CloseAllAppsWithAppHeaderExit.kt
index 351a700..f9bf49e 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/CloseAllAppsWithAppHeaderExit.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/CloseAllAppsWithAppHeaderExit.kt
@@ -57,7 +57,7 @@
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
nonResizeableApp.launchViaIntent(wmHelper)
}
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindow.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindow.kt
index 3f9927f..16e5373 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindow.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindow.kt
@@ -40,7 +40,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
newTasksApp.launchViaIntent(wmHelper)
imeApp.launchViaIntent(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindowAndPip.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindowAndPip.kt
index 6d52a11..c43a575 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindowAndPip.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowMultiWindowAndPip.kt
@@ -47,7 +47,7 @@
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
// Set string extra to ensure the app is on PiP mode at launch
pipApp.launchViaIntentAndWaitForPip(wmHelper, stringExtras = mapOf("enter_pip" to "true"))
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
newTasksApp.launchViaIntent(wmHelper)
imeApp.launchViaIntent(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowSingleWindow.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowSingleWindow.kt
index 91cfd17..786a8b7 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowSingleWindow.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/DragAppWindowSingleWindow.kt
@@ -36,7 +36,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/EnterDesktopWithDrag.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/EnterDesktopWithDrag.kt
index 967bd29..0f546cd 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/EnterDesktopWithDrag.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/EnterDesktopWithDrag.kt
@@ -49,7 +49,7 @@
@Test
open fun enterDesktopWithDrag() {
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopModeWithDrag(wmHelper, device)
}
@After
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ExitDesktopWithDragToTopDragZone.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ExitDesktopWithDragToTopDragZone.kt
index f442fdb..2800839 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ExitDesktopWithDragToTopDragZone.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ExitDesktopWithDragToTopDragZone.kt
@@ -46,7 +46,7 @@
instrumentation.context.resources.getBoolean(R.bool.config_dragToMaximizeInDesktopMode))
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximiseAppWithCornerResize.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximiseAppWithCornerResize.kt
index 6637b01..5cf51e3 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximiseAppWithCornerResize.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximiseAppWithCornerResize.kt
@@ -66,7 +66,7 @@
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
ChangeDisplayOrientationRule.setRotation(rotation)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
testApp.cornerResize(
wmHelper,
device,
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindow.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindow.kt
index a54d497..d2be494 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindow.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindow.kt
@@ -58,7 +58,7 @@
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
ChangeDisplayOrientationRule.setRotation(rotation)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindowWithDragToTopDragZone.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindowWithDragToTopDragZone.kt
index a2b88f2..60a0fb5 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindowWithDragToTopDragZone.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MaximizeAppWindowWithDragToTopDragZone.kt
@@ -59,7 +59,7 @@
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
ChangeDisplayOrientationRule.setRotation(rotation)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeAppWindows.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeAppWindows.kt
index b548363..971637b 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeAppWindows.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeAppWindows.kt
@@ -61,7 +61,7 @@
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
ChangeDisplayOrientationRule.setRotation(rotation)
- testApp1.enterDesktopWithDrag(wmHelper, device)
+ testApp1.enterDesktopMode(wmHelper, device)
testApp2.launchViaIntent(wmHelper)
testApp3.launchViaIntent(wmHelper)
}
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeWindowOnAppOpen.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeWindowOnAppOpen.kt
index b86765e..7987f7e 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeWindowOnAppOpen.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/MinimizeWindowOnAppOpen.kt
@@ -58,7 +58,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
newTasksApp.launchViaIntent(wmHelper)
imeApp.launchViaIntent(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/OpenAppsInDesktopMode.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/OpenAppsInDesktopMode.kt
index aad266f..6ce36f5 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/OpenAppsInDesktopMode.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/OpenAppsInDesktopMode.kt
@@ -61,7 +61,7 @@
tapl.setExpectedRotation(rotation.value)
tapl.enableTransientTaskbar(false)
ChangeDisplayOrientationRule.setRotation(rotation)
- firstApp.enterDesktopWithDrag(wmHelper, device)
+ firstApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindow.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindow.kt
index bfee318..eefa0bb 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindow.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindow.kt
@@ -61,7 +61,7 @@
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
newTasksApp.launchViaIntent(wmHelper)
imeApp.launchViaIntent(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindowAndPip.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindowAndPip.kt
index 5b1b64e..0226eb3 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindowAndPip.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppCornerMultiWindowAndPip.kt
@@ -65,7 +65,7 @@
tapl.setExpectedRotation(rotation.value)
// Set string extra to ensure the app is on PiP mode at launch
pipApp.launchViaIntentAndWaitForPip(wmHelper, stringExtras = mapOf("enter_pip" to "true"))
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
mailApp.launchViaIntent(wmHelper)
newTasksApp.launchViaIntent(wmHelper)
imeApp.launchViaIntent(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithCornerResize.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithCornerResize.kt
index a7cebf4..6463623 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithCornerResize.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithCornerResize.kt
@@ -67,7 +67,7 @@
tapl.setEnableRotation(true)
ChangeDisplayOrientationRule.setRotation(rotation)
tapl.setExpectedRotation(rotation.value)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithEdgeResize.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithEdgeResize.kt
index 6780238..f198cfe 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithEdgeResize.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/ResizeAppWithEdgeResize.kt
@@ -60,7 +60,7 @@
)
tapl.setEnableRotation(true)
tapl.setExpectedRotation(rotation.value)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithButton.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithButton.kt
index 2b40497..fd4c243 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithButton.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithButton.kt
@@ -56,7 +56,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithDrag.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithDrag.kt
index b4bd7e1..62e860e 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithDrag.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SnapResizeAppWindowWithDrag.kt
@@ -56,7 +56,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionResizeAndDrag.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionResizeAndDrag.kt
index f08e50e..de330e0 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionResizeAndDrag.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionResizeAndDrag.kt
@@ -59,7 +59,7 @@
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
tapl.setEnableRotation(true)
tapl.setExpectedRotation(0)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionWithMaxDesktopWindows.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionWithMaxDesktopWindows.kt
index ce235d4..4b3f15f 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionWithMaxDesktopWindows.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartAppMediaProjectionWithMaxDesktopWindows.kt
@@ -67,7 +67,7 @@
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
tapl.setEnableRotation(true)
tapl.setExpectedRotation(0)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartScreenMediaProjectionWithMaxDesktopWindows.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartScreenMediaProjectionWithMaxDesktopWindows.kt
index 0051952..a108367 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartScreenMediaProjectionWithMaxDesktopWindows.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/StartScreenMediaProjectionWithMaxDesktopWindows.kt
@@ -62,7 +62,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SwitchToOverviewFromDesktop.kt b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SwitchToOverviewFromDesktop.kt
index dad2eb6..1455bd1 100644
--- a/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SwitchToOverviewFromDesktop.kt
+++ b/libs/WindowManager/Shell/tests/e2e/desktopmode/scenarios/src/com/android/wm/shell/scenarios/SwitchToOverviewFromDesktop.kt
@@ -54,7 +54,7 @@
@Before
fun setup() {
Assume.assumeTrue(Flags.enableDesktopWindowingMode() && tapl.isTablet)
- testApp.enterDesktopWithDrag(wmHelper, device)
+ testApp.enterDesktopMode(wmHelper, device)
}
@Test
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestSyncExecutor.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestSyncExecutor.kt
new file mode 100644
index 0000000..528ca7e
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestSyncExecutor.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2024 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.wm.shell
+
+import com.android.wm.shell.common.ShellExecutor
+
+/**
+ * Test ShellExecutor that runs everything synchronously.
+ */
+class TestSyncExecutor : ShellExecutor {
+ override fun execute(runnable: Runnable) {
+ runnable.run()
+ }
+
+ override fun executeDelayed(runnable: Runnable, delayMillis: Long) {
+ runnable.run()
+ }
+
+ override fun removeCallbacks(runnable: Runnable) {
+ }
+
+ override fun hasCallback(runnable: Runnable): Boolean {
+ return false
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandlerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandlerTest.kt
index f21f264..62717a3 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandlerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopMixedTransitionHandlerTest.kt
@@ -31,6 +31,8 @@
import android.testing.TestableLooper.RunWithLooper
import android.view.SurfaceControl
import android.view.WindowManager
+import android.view.WindowManager.TRANSIT_CHANGE
+import android.view.WindowManager.TRANSIT_NONE
import android.view.WindowManager.TRANSIT_OPEN
import android.view.WindowManager.TRANSIT_TO_BACK
import android.view.WindowManager.TransitionType
@@ -47,6 +49,7 @@
import com.android.wm.shell.freeform.FreeformTaskTransitionHandler
import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
+import com.android.wm.shell.util.StubTransaction
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -491,6 +494,72 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_FULLY_IMMERSIVE_IN_DESKTOP)
+ fun startLaunchTransition_unknownLaunchingTask_animates() {
+ val wct = WindowContainerTransaction()
+ val task = createTask(WINDOWING_MODE_FREEFORM)
+ val transition = Binder()
+ whenever(transitions.startTransition(eq(TRANSIT_OPEN), eq(wct), anyOrNull()))
+ .thenReturn(transition)
+ whenever(transitions.dispatchTransition(eq(transition), any(), any(), any(), any(), any()))
+ .thenReturn(mock())
+
+ mixedHandler.startLaunchTransition(
+ transitionType = TRANSIT_OPEN,
+ wct = wct,
+ taskId = null,
+ )
+
+ val started = mixedHandler.startAnimation(
+ transition,
+ createTransitionInfo(
+ TRANSIT_OPEN,
+ listOf(createChange(task, mode = TRANSIT_OPEN))
+ ),
+ StubTransaction(),
+ StubTransaction(),
+ ) { }
+
+ assertThat(started).isEqualTo(true)
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_FULLY_IMMERSIVE_IN_DESKTOP)
+ fun startLaunchTransition_unknownLaunchingTaskOverImmersive_animatesImmersiveChange() {
+ val wct = WindowContainerTransaction()
+ val immersiveTask = createTask(WINDOWING_MODE_FREEFORM)
+ val openingTask = createTask(WINDOWING_MODE_FREEFORM)
+ val transition = Binder()
+ whenever(transitions.startTransition(eq(TRANSIT_OPEN), eq(wct), anyOrNull()))
+ .thenReturn(transition)
+ whenever(transitions.dispatchTransition(eq(transition), any(), any(), any(), any(), any()))
+ .thenReturn(mock())
+
+ mixedHandler.startLaunchTransition(
+ transitionType = TRANSIT_OPEN,
+ wct = wct,
+ taskId = null,
+ exitingImmersiveTask = immersiveTask.taskId,
+ )
+
+ val immersiveChange = createChange(immersiveTask, mode = TRANSIT_CHANGE)
+ val openingChange = createChange(openingTask, mode = TRANSIT_OPEN)
+ val started = mixedHandler.startAnimation(
+ transition,
+ createTransitionInfo(
+ TRANSIT_OPEN,
+ listOf(immersiveChange, openingChange)
+ ),
+ StubTransaction(),
+ StubTransaction(),
+ ) { }
+
+ assertThat(started).isEqualTo(true)
+ verify(desktopImmersiveController)
+ .animateResizeChange(eq(immersiveChange), any(), any(), any())
+ }
+
+ @Test
@EnableFlags(Flags.FLAG_ENABLE_DESKTOP_APP_LAUNCH_TRANSITIONS)
fun addPendingAndAnimateLaunchTransition_noMinimizeChange_doesNotReparentMinimizeChange() {
val wct = WindowContainerTransaction()
@@ -712,9 +781,13 @@
changes.forEach { change -> addChange(change) }
}
- private fun createChange(task: RunningTaskInfo): TransitionInfo.Change =
+ private fun createChange(
+ task: RunningTaskInfo,
+ @TransitionInfo.TransitionMode mode: Int = TRANSIT_NONE
+ ): TransitionInfo.Change =
TransitionInfo.Change(task.token, SurfaceControl()).apply {
taskInfo = task
+ setMode(mode)
}
private fun createTask(@WindowingMode windowingMode: Int): RunningTaskInfo =
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
index ad266ea..2319716 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
@@ -100,6 +100,7 @@
import com.android.wm.shell.common.MultiInstanceHelper
import com.android.wm.shell.common.ShellExecutor
import com.android.wm.shell.common.SyncTransactionQueue
+import com.android.wm.shell.desktopmode.DesktopImmersiveController.ExitResult
import com.android.wm.shell.desktopmode.DesktopModeEventLogger.Companion.ResizeTrigger
import com.android.wm.shell.desktopmode.DesktopTasksController.SnapPosition
import com.android.wm.shell.desktopmode.DesktopTasksController.TaskbarDesktopTaskListener
@@ -167,6 +168,7 @@
import org.mockito.Mockito.times
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
+import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.capture
import org.mockito.kotlin.eq
@@ -294,10 +296,10 @@
whenever(rootTaskDisplayAreaOrganizer.getDisplayAreaInfo(DEFAULT_DISPLAY)).thenReturn(tda)
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(any(), any<RunningTaskInfo>()))
- .thenReturn(DesktopImmersiveController.ExitResult.NoExit)
+ .thenReturn(ExitResult.NoExit)
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(any(), anyInt(), anyOrNull()))
- .thenReturn(DesktopImmersiveController.ExitResult.NoExit)
+ .thenReturn(ExitResult.NoExit)
controller = createController()
controller.setSplitScreenController(splitScreenController)
@@ -1833,7 +1835,8 @@
whenever(freeformTaskTransitionStarter.startMinimizedModeTransition(any()))
.thenReturn(transition)
whenever(mMockDesktopImmersiveController.exitImmersiveIfApplicable(any(), eq(task)))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = task.taskId,
runOnTransitionStart = runOnTransit,
))
@@ -3214,13 +3217,43 @@
fun newWindow_fromFreeformAddsNewWindow() {
setUpLandscapeDisplay()
val task = setUpFreeformTask()
- val wctCaptor = ArgumentCaptor.forClass(WindowContainerTransaction::class.java)
+ val wctCaptor = argumentCaptor<WindowContainerTransaction>()
+ val transition = Binder()
+ whenever(mMockDesktopImmersiveController
+ .exitImmersiveIfApplicable(any(), anyInt(), anyOrNull()))
+ .thenReturn(ExitResult.NoExit)
+ whenever(desktopMixedTransitionHandler
+ .startLaunchTransition(anyInt(), any(), anyOrNull(), anyOrNull(), anyOrNull()))
+ .thenReturn(transition)
+
runOpenNewWindow(task)
- verify(transitions).startTransition(anyInt(), wctCaptor.capture(), anyOrNull())
- assertThat(ActivityOptions.fromBundle(wctCaptor.value.hierarchyOps[0].launchOptions)
+
+ verify(desktopMixedTransitionHandler)
+ .startLaunchTransition(anyInt(), wctCaptor.capture(), anyOrNull(), anyOrNull(), anyOrNull())
+ assertThat(ActivityOptions.fromBundle(wctCaptor.firstValue.hierarchyOps[0].launchOptions)
.launchWindowingMode).isEqualTo(WINDOWING_MODE_FREEFORM)
}
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MULTI_INSTANCE_FEATURES)
+ fun newWindow_fromFreeform_exitsImmersiveIfNeeded() {
+ setUpLandscapeDisplay()
+ val immersiveTask = setUpFreeformTask()
+ val task = setUpFreeformTask()
+ val runOnStart = RunOnStartTransitionCallback()
+ val transition = Binder()
+ whenever(mMockDesktopImmersiveController
+ .exitImmersiveIfApplicable(any(), anyInt(), anyOrNull()))
+ .thenReturn(ExitResult.Exit(immersiveTask.taskId, runOnStart))
+ whenever(desktopMixedTransitionHandler
+ .startLaunchTransition(anyInt(), any(), anyOrNull(), anyOrNull(), anyOrNull()))
+ .thenReturn(transition)
+
+ runOpenNewWindow(task)
+
+ runOnStart.assertOnlyInvocation(transition)
+ }
+
private fun runOpenNewWindow(task: RunningTaskInfo) {
markTaskVisible(task)
task.baseActivity = mock(ComponentName::class.java)
@@ -3314,7 +3347,8 @@
.thenReturn(transition)
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(any(), eq(immersiveTask.displayId), eq(freeformTask.taskId)))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = immersiveTask.taskId,
runOnTransitionStart = runOnStartTransit,
))
@@ -3719,7 +3753,8 @@
val transition = Binder()
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(wct, task.displayId, task.taskId))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = 5,
runOnTransitionStart = runOnStartTransit,
))
@@ -3740,7 +3775,8 @@
val transition = Binder()
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(wct, task.displayId, task.taskId))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = 5,
runOnTransitionStart = runOnStartTransit,
))
@@ -3760,7 +3796,8 @@
val transition = Binder()
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(any(), eq(task.displayId), eq(task.taskId)))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = 5,
runOnTransitionStart = runOnStartTransit,
))
@@ -3782,7 +3819,8 @@
val transition = Binder()
whenever(mMockDesktopImmersiveController
.exitImmersiveIfApplicable(any(), eq(task.displayId), eq(task.taskId)))
- .thenReturn(DesktopImmersiveController.ExitResult.Exit(
+ .thenReturn(
+ ExitResult.Exit(
exitingTask = 5,
runOnTransitionStart = runOnStartTransit,
))
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/GroupedTaskInfoTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/GroupedTaskInfoTest.kt
index 2b30bc3..fd3adab 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/GroupedTaskInfoTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/GroupedTaskInfoTest.kt
@@ -176,6 +176,30 @@
assertThat(recentTaskInfoParcel.minimizedTaskIds).isEqualTo(arrayOf(2).toIntArray())
}
+ @Test
+ fun testGetTaskById_singleTasks() {
+ val task1 = createTaskInfo(id = 1234)
+
+ val taskInfo = GroupedTaskInfo.forFullscreenTasks(task1)
+
+ assertThat(taskInfo.getTaskById(1234)).isEqualTo(task1)
+ assertThat(taskInfo.containsTask(1234)).isTrue()
+ }
+
+ @Test
+ fun testGetTaskById_multipleTasks() {
+ val task1 = createTaskInfo(id = 1)
+ val task2 = createTaskInfo(id = 2)
+ val splitBounds = SplitBounds(Rect(), Rect(), 1, 2, SNAP_TO_2_50_50)
+
+ val taskInfo = GroupedTaskInfo.forSplitTasks(task1, task2, splitBounds)
+
+ assertThat(taskInfo.getTaskById(1)).isEqualTo(task1)
+ assertThat(taskInfo.getTaskById(2)).isEqualTo(task2)
+ assertThat(taskInfo.containsTask(1)).isTrue()
+ assertThat(taskInfo.containsTask(2)).isTrue()
+ }
+
private fun createTaskInfo(id: Int) = ActivityManager.RecentTaskInfo().apply {
taskId = id
token = WindowContainerToken(mock(IWindowContainerToken::class.java))
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/RecentTasksControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/RecentTasksControllerTest.java
index dede583..12c3978 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/RecentTasksControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/RecentTasksControllerTest.java
@@ -610,7 +610,7 @@
mRecentTasksControllerReal.onTaskMovedToFrontThroughTransition(taskInfo);
GroupedTaskInfo runningTask = GroupedTaskInfo.forFullscreenTasks(taskInfo);
- verify(mRecentTasksListener).onTaskMovedToFront(eq(new GroupedTaskInfo[] { runningTask }));
+ verify(mRecentTasksListener).onTaskMovedToFront(eq(runningTask));
}
@Test
@@ -656,6 +656,35 @@
assertEquals(splitBounds4, pair2Bounds);
}
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ public void shellTopTaskTracker_onTaskStackChanged_expectNoRecentsChanged() throws Exception {
+ mRecentTasksControllerReal.registerRecentTasksListener(mRecentTasksListener);
+ mRecentTasksControllerReal.onTaskStackChanged();
+ verify(mRecentTasksListener, never()).onRecentTasksChanged();
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ public void shellTopTaskTracker_onTaskRemoved_expectNoRecentsChanged() throws Exception {
+ mRecentTasksControllerReal.registerRecentTasksListener(mRecentTasksListener);
+ ActivityManager.RunningTaskInfo taskInfo = makeRunningTaskInfo(/* taskId= */10);
+ mRecentTasksControllerReal.onTaskRemoved(taskInfo);
+ verify(mRecentTasksListener, never()).onRecentTasksChanged();
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ public void shellTopTaskTracker_onVisibleTasksChanged() throws Exception {
+ mRecentTasksControllerReal.registerRecentTasksListener(mRecentTasksListener);
+ ActivityManager.RunningTaskInfo taskInfo = makeRunningTaskInfo(/* taskId= */10);
+ mRecentTasksControllerReal.onVisibleTasksChanged(List.of(taskInfo));
+ verify(mRecentTasksListener, never()).onVisibleTasksChanged(any());
+ }
+
/**
* Helper to create a task with a given task id.
*/
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/TaskStackTransitionObserverTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/TaskStackTransitionObserverTest.kt
index efe4fb1..9919462 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/TaskStackTransitionObserverTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/recents/TaskStackTransitionObserverTest.kt
@@ -16,21 +16,36 @@
package com.android.wm.shell.recents
-import android.app.ActivityManager
+import android.app.ActivityManager.RunningTaskInfo
+import android.app.TaskInfo
import android.app.WindowConfiguration
+import android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN
+import android.app.WindowConfiguration.WINDOWING_MODE_PINNED
+import android.content.ComponentName
+import android.content.Intent
import android.os.IBinder
+import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import android.testing.AndroidTestingRunner
import android.view.SurfaceControl
import android.view.WindowManager
+import android.view.WindowManager.TRANSIT_CHANGE
+import android.view.WindowManager.TRANSIT_CLOSE
+import android.view.WindowManager.TRANSIT_FIRST_CUSTOM
+import android.view.WindowManager.TRANSIT_OPEN
+import android.view.WindowManager.TRANSIT_TO_FRONT
import android.window.IWindowContainerToken
import android.window.TransitionInfo
+import android.window.TransitionInfo.FLAG_MOVED_TO_TOP
import android.window.WindowContainerToken
import androidx.test.filters.SmallTest
import com.android.window.flags.Flags
+import com.android.wm.shell.ShellTaskOrganizer
import com.android.wm.shell.TestShellExecutor
+import com.android.wm.shell.TestSyncExecutor
import com.android.wm.shell.common.ShellExecutor
+import com.android.wm.shell.sysui.ShellCommandHandler
import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.TransitionInfoBuilder
import com.android.wm.shell.transition.Transitions
@@ -61,7 +76,10 @@
@JvmField @Rule val setFlagsRule = SetFlagsRule()
@Mock private lateinit var shellInit: ShellInit
- @Mock lateinit var testExecutor: ShellExecutor
+ @Mock private lateinit var shellTaskOrganizerLazy: Lazy<ShellTaskOrganizer>
+ @Mock private lateinit var shellTaskOrganizer: ShellTaskOrganizer
+ @Mock private lateinit var shellCommandHandler: ShellCommandHandler
+ @Mock private lateinit var testExecutor: ShellExecutor
@Mock private lateinit var transitionsLazy: Lazy<Transitions>
@Mock private lateinit var transitions: Transitions
@Mock private lateinit var mockTransitionBinder: IBinder
@@ -73,24 +91,23 @@
MockitoAnnotations.initMocks(this)
shellInit = Mockito.spy(ShellInit(testExecutor))
whenever(transitionsLazy.get()).thenReturn(transitions)
- transitionObserver = TaskStackTransitionObserver(transitionsLazy, shellInit)
- if (Transitions.ENABLE_SHELL_TRANSITIONS) {
- val initRunnableCaptor = ArgumentCaptor.forClass(Runnable::class.java)
- verify(shellInit)
- .addInitCallback(initRunnableCaptor.capture(), same(transitionObserver))
- initRunnableCaptor.value.run()
- } else {
- transitionObserver.onInit()
- }
+ whenever(shellTaskOrganizerLazy.get()).thenReturn(shellTaskOrganizer)
+ transitionObserver = TaskStackTransitionObserver(shellInit, shellTaskOrganizerLazy,
+ shellCommandHandler, transitionsLazy)
+
+ val initRunnableCaptor = ArgumentCaptor.forClass(Runnable::class.java)
+ verify(shellInit)
+ .addInitCallback(initRunnableCaptor.capture(), same(transitionObserver))
+ initRunnableCaptor.value.run()
}
@Test
- @EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun testRegistersObserverAtInit() {
verify(transitions).registerObserver(same(transitionObserver))
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun taskCreated_freeformWindow_listenerNotified() {
val listener = TestListener()
@@ -98,11 +115,11 @@
transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
val change =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val transitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(change).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(change).build()
callOnTransitionReady(transitionInfo)
callOnTransitionFinished()
@@ -114,6 +131,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun taskCreated_fullscreenWindow_listenerNotified() {
val listener = TestListener()
@@ -121,11 +139,11 @@
transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
val change =
createChange(
- WindowManager.TRANSIT_OPEN,
- createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FULLSCREEN)
+ TRANSIT_OPEN,
+ createTaskInfo(1, WINDOWING_MODE_FULLSCREEN)
)
val transitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(change).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(change).build()
callOnTransitionReady(transitionInfo)
callOnTransitionFinished()
@@ -133,10 +151,11 @@
assertThat(listener.taskInfoOnTaskMovedToFront.taskId).isEqualTo(1)
assertThat(listener.taskInfoOnTaskMovedToFront.windowingMode)
- .isEqualTo(WindowConfiguration.WINDOWING_MODE_FULLSCREEN)
+ .isEqualTo(WINDOWING_MODE_FULLSCREEN)
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun taskCreated_freeformWindowOnTopOfFreeform_listenerNotified() {
val listener = TestListener()
@@ -144,7 +163,7 @@
transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
val freeformOpenChange =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val freeformReorderChange =
@@ -153,7 +172,7 @@
createTaskInfo(2, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val transitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0)
+ TransitionInfoBuilder(TRANSIT_OPEN, 0)
.addChange(freeformOpenChange)
.addChange(freeformReorderChange)
.build()
@@ -169,6 +188,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun transitionMerged_withChange_onlyOpenChangeIsNotified() {
val listener = TestListener()
@@ -178,11 +198,11 @@
// Create open transition
val change =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val transitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(change).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(change).build()
// create change transition to be merged to above transition
val mergedChange =
@@ -212,6 +232,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun transitionMerged_withOpen_lastOpenChangeIsNotified() {
val listener = TestListener()
@@ -221,20 +242,20 @@
// Create open transition
val change =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val transitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(change).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(change).build()
// create change transition to be merged to above transition
val mergedChange =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(2, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val mergedTransitionInfo =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(mergedChange).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(mergedChange).build()
val mergedTransition = Mockito.mock(IBinder::class.java)
callOnTransitionReady(transitionInfo)
@@ -250,6 +271,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun taskChange_freeformWindowToFullscreenWindow_listenerNotified() {
val listener = TestListener()
@@ -257,11 +279,11 @@
transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
val freeformState =
createChange(
- WindowManager.TRANSIT_OPEN,
+ TRANSIT_OPEN,
createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val transitionInfoOpen =
- TransitionInfoBuilder(WindowManager.TRANSIT_OPEN, 0).addChange(freeformState).build()
+ TransitionInfoBuilder(TRANSIT_OPEN, 0).addChange(freeformState).build()
callOnTransitionReady(transitionInfoOpen)
callOnTransitionFinished()
executor.flushAll()
@@ -276,7 +298,7 @@
val fullscreenState =
createChange(
WindowManager.TRANSIT_CHANGE,
- createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FULLSCREEN)
+ createTaskInfo(1, WINDOWING_MODE_FULLSCREEN)
)
val transitionInfoChange =
TransitionInfoBuilder(WindowManager.TRANSIT_CHANGE, 0)
@@ -301,6 +323,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun singleTransition_withOpenAndChange_onlyOpenIsNotified() {
val listener = TestListener()
@@ -310,13 +333,13 @@
// Creating multiple changes to be fired in a single transition
val freeformState =
createChange(
- mode = WindowManager.TRANSIT_OPEN,
+ mode = TRANSIT_OPEN,
taskInfo = createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FREEFORM)
)
val fullscreenState =
createChange(
mode = WindowManager.TRANSIT_CHANGE,
- taskInfo = createTaskInfo(1, WindowConfiguration.WINDOWING_MODE_FULLSCREEN)
+ taskInfo = createTaskInfo(1, WINDOWING_MODE_FULLSCREEN)
)
val transitionInfoWithChanges =
@@ -336,6 +359,7 @@
}
@Test
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
@EnableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
fun singleTransition_withMultipleChanges_listenerNotified_forEachChange() {
val listener = TestListener()
@@ -349,7 +373,7 @@
listOf(
WindowConfiguration.WINDOWING_MODE_FREEFORM,
WindowConfiguration.WINDOW_CONFIG_DISPLAY_ROTATION,
- WindowConfiguration.WINDOWING_MODE_FULLSCREEN
+ WINDOWING_MODE_FULLSCREEN
)
.map { change ->
createChange(
@@ -376,19 +400,259 @@
}
}
- class TestListener : TaskStackTransitionObserver.TaskStackTransitionObserverListener {
- var taskInfoOnTaskMovedToFront = ActivityManager.RunningTaskInfo()
- var taskInfoOnTaskChanged = mutableListOf<ActivityManager.RunningTaskInfo>()
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun openTransition_visibleTasksChanged() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
- override fun onTaskMovedToFrontThroughTransition(
- taskInfo: ActivityManager.RunningTaskInfo
- ) {
+ // Model an opening task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ // Assert that the task is reported visible
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+ assertVisibleTasks(listener, listOf(1))
+
+ // Model opening another task
+ val nextOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 2, WINDOWING_MODE_FULLSCREEN),
+ createChange(TRANSIT_CLOSE, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(nextOpeningTransition)
+ // Assert that the visible list from top to bottom is valid (opening, closing)
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(2)
+ assertVisibleTasks(listener, listOf(2, 1))
+
+ callOnTransitionFinished()
+ // Assert that after the transition finishes, there is only the opening task remaining
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(3)
+ assertVisibleTasks(listener, listOf(2))
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun toFrontTransition_visibleTasksChanged() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
+
+ // Model an opening task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ // Assert that the task is reported visible
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+ assertVisibleTasks(listener, listOf(1))
+
+ // Model opening another task
+ val nextOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 2, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(nextOpeningTransition)
+ callOnTransitionFinished()
+ // Assert that the visible list from top to bottom is valid
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(2)
+ assertVisibleTasks(listener, listOf(2, 1))
+
+ // Model the first task moving to front
+ val toFrontTransition =
+ createTransitionInfo(TRANSIT_TO_FRONT,
+ listOf(
+ createChange(TRANSIT_CHANGE, 1, WINDOWING_MODE_FULLSCREEN,
+ FLAG_MOVED_TO_TOP),
+ )
+ )
+
+ callOnTransitionReady(toFrontTransition)
+ callOnTransitionFinished()
+ // Assert that the visible list from top to bottom is valid
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(3)
+ assertVisibleTasks(listener, listOf(1, 2))
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun closeTransition_visibleTasksChanged() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
+
+ // Model an opening task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+
+ // Model a closing task
+ val nextOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_CLOSE, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(nextOpeningTransition)
+ // Assert that the visible list hasn't changed (the close is pending)
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+
+ callOnTransitionFinished()
+ // Assert that after the transition finishes, there is only the opening task remaining
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(2)
+ assertVisibleTasks(listener, listOf())
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun changeTransition_visibleTasksUnchanged() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
+
+ // Model an opening task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+
+ // Model a closing task
+ val nextOpeningTransition =
+ createTransitionInfo(
+ TRANSIT_FIRST_CUSTOM,
+ listOf(
+ createChange(TRANSIT_CHANGE, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(nextOpeningTransition)
+ // Assert that the visible list hasn't changed
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun taskVanished_visibleTasksChanged() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
+
+ // Model an opening task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ // Assert that the task is reported visible
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+ assertVisibleTasks(listener, listOf(1))
+
+ // Trigger task vanished
+ val removedTaskInfo = createTaskInfo(1, WINDOWING_MODE_FULLSCREEN)
+ transitionObserver.onTaskVanished(removedTaskInfo)
+
+ // Assert that the visible list is now empty
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(2)
+ assertVisibleTasks(listener, listOf())
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_TASK_STACK_OBSERVER_IN_SHELL)
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_SHELL_TOP_TASK_TRACKING)
+ fun alwaysOnTop_taskIsTopMostVisible() {
+ val listener = TestListener()
+ val executor = TestSyncExecutor()
+ transitionObserver.addTaskStackTransitionObserverListener(listener, executor)
+
+ // Model an opening PIP task
+ val pipOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 1, WINDOWING_MODE_PINNED),
+ )
+ )
+
+ callOnTransitionReady(pipOpeningTransition)
+ callOnTransitionFinished()
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(1)
+ assertVisibleTasks(listener, listOf(1))
+
+ // Model an opening fullscreen task
+ val firstOpeningTransition =
+ createTransitionInfo(TRANSIT_OPEN,
+ listOf(
+ createChange(TRANSIT_OPEN, 2, WINDOWING_MODE_FULLSCREEN),
+ )
+ )
+
+ callOnTransitionReady(firstOpeningTransition)
+ callOnTransitionFinished()
+ assertThat(listener.visibleTasksUpdatedCount).isEqualTo(2)
+ assertVisibleTasks(listener, listOf(1, 2))
+ }
+
+ class TestListener : TaskStackTransitionObserver.TaskStackTransitionObserverListener {
+ // Only used if FLAG_ENABLE_SHELL_TOP_TASK_TRACKING is disabled
+ var taskInfoOnTaskMovedToFront = RunningTaskInfo()
+ var taskInfoOnTaskChanged = mutableListOf<RunningTaskInfo>()
+ // Only used if FLAG_ENABLE_SHELL_TOP_TASK_TRACKING is enabled
+ var visibleTasks = mutableListOf<TaskInfo>()
+ var visibleTasksUpdatedCount = 0
+
+ override fun onTaskMovedToFrontThroughTransition(taskInfo: RunningTaskInfo) {
taskInfoOnTaskMovedToFront = taskInfo
}
- override fun onTaskChangedThroughTransition(taskInfo: ActivityManager.RunningTaskInfo) {
+ override fun onTaskChangedThroughTransition(taskInfo: RunningTaskInfo) {
taskInfoOnTaskChanged += taskInfo
}
+
+ override fun onVisibleTasksChanged(visibleTasks: List<RunningTaskInfo>) {
+ this.visibleTasks.clear()
+ this.visibleTasks.addAll(visibleTasks)
+ visibleTasksUpdatedCount++
+ }
}
/** Simulate calling the onTransitionReady() method */
@@ -412,27 +676,64 @@
transitionObserver.onTransitionMerged(merged, playing)
}
+ /**
+ * Asserts that the listener has the given expected task ids (in order).
+ */
+ private fun assertVisibleTasks(
+ listener: TestListener,
+ expectedVisibleTaskIds: List<Int>
+ ) {
+ assertThat(listener.visibleTasks.size).isEqualTo(expectedVisibleTaskIds.size)
+ expectedVisibleTaskIds.forEachIndexed { index, taskId ->
+ assertThat(listener.visibleTasks[index].taskId).isEqualTo(taskId)
+ }
+ }
+
companion object {
- fun createTaskInfo(taskId: Int, windowingMode: Int): ActivityManager.RunningTaskInfo {
- val taskInfo = ActivityManager.RunningTaskInfo()
+ fun createTaskInfo(taskId: Int, windowingMode: Int): RunningTaskInfo {
+ val taskInfo = RunningTaskInfo()
+ taskInfo.baseIntent = Intent().setComponent(
+ ComponentName(javaClass.packageName, "Test"))
taskInfo.taskId = taskId
taskInfo.configuration.windowConfiguration.windowingMode = windowingMode
-
+ if (windowingMode == WINDOWING_MODE_PINNED) {
+ taskInfo.configuration.windowConfiguration.isAlwaysOnTop = true
+ }
return taskInfo
}
fun createChange(
mode: Int,
- taskInfo: ActivityManager.RunningTaskInfo
+ taskInfo: RunningTaskInfo,
+ flags: Int = 0,
): TransitionInfo.Change {
val change =
TransitionInfo.Change(
WindowContainerToken(Mockito.mock(IWindowContainerToken::class.java)),
Mockito.mock(SurfaceControl::class.java)
)
+ change.flags = flags
change.mode = mode
change.taskInfo = taskInfo
return change
}
+
+ fun createChange(
+ mode: Int,
+ taskId: Int,
+ windowingMode: Int,
+ flags: Int = 0,
+ ): TransitionInfo.Change {
+ return createChange(mode, createTaskInfo(taskId, windowingMode), flags)
+ }
+
+ fun createTransitionInfo(
+ transitionType: Int,
+ changes: List<TransitionInfo.Change>
+ ): TransitionInfo {
+ return TransitionInfoBuilder(transitionType, 0)
+ .apply { changes.forEach { c -> this@apply.addChange(c) } }
+ .build()
+ }
}
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/unfold/UnfoldTransitionHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/unfold/UnfoldTransitionHandlerTest.java
index c36b88e..71af97e 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/unfold/UnfoldTransitionHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/unfold/UnfoldTransitionHandlerTest.java
@@ -43,6 +43,7 @@
import android.window.TransitionRequestInfo;
import android.window.WindowContainerTransaction;
+import com.android.wm.shell.TestSyncExecutor;
import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.shared.TransactionPool;
import com.android.wm.shell.sysui.ShellInit;
@@ -475,27 +476,6 @@
}
}
- private static class TestSyncExecutor implements ShellExecutor {
- @Override
- public void execute(Runnable runnable) {
- runnable.run();
- }
-
- @Override
- public void executeDelayed(Runnable runnable, long delayMillis) {
- runnable.run();
- }
-
- @Override
- public void removeCallbacks(Runnable runnable) {
- }
-
- @Override
- public boolean hasCallback(Runnable runnable) {
- return false;
- }
- }
-
private TransitionInfo createUnfoldTransitionInfo() {
TransitionInfo transitionInfo = new TransitionInfo(TRANSIT_CHANGE, /* flags= */ 0);
TransitionInfo.Change change = new TransitionInfo.Change(null, mock(SurfaceControl.class));
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
index 1d2d0f0..f7b190c 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
@@ -30,6 +30,7 @@
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static com.android.wm.shell.MockSurfaceControlHelper.createMockSurfaceControlTransaction;
import static com.android.wm.shell.windowdecor.DesktopModeWindowDecoration.CLOSE_MAXIMIZE_MENU_DELAY_MS;
+import static com.android.wm.shell.windowdecor.WindowDecoration.INVALID_CORNER_RADIUS;
import static com.google.common.truth.Truth.assertThat;
@@ -312,8 +313,9 @@
}
@Test
- public void updateRelayoutParams_noSysPropFlagsSet_roundedCornersAreEnabled() {
+ public void updateRelayoutParams_noSysPropFlagsSet_roundedCornersSetForFreeform() {
final ActivityManager.RunningTaskInfo taskInfo = createTaskInfo(/* visible= */ true);
+ taskInfo.configuration.windowConfiguration.setWindowingMode(WINDOWING_MODE_FREEFORM);
fillRoundedCornersResources(/* fillValue= */ 30);
RelayoutParams relayoutParams = new RelayoutParams();
@@ -334,6 +336,29 @@
}
@Test
+ public void updateRelayoutParams_noSysPropFlagsSet_roundedCornersNotSetForFullscreen() {
+ final ActivityManager.RunningTaskInfo taskInfo = createTaskInfo(/* visible= */ true);
+ taskInfo.configuration.windowConfiguration.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
+ fillRoundedCornersResources(/* fillValue= */ 30);
+ RelayoutParams relayoutParams = new RelayoutParams();
+
+ DesktopModeWindowDecoration.updateRelayoutParams(
+ relayoutParams,
+ mTestableContext,
+ taskInfo,
+ /* applyStartTransactionOnDraw= */ true,
+ /* shouldSetTaskPositionAndCrop */ false,
+ /* isStatusBarVisible */ true,
+ /* isKeyguardVisibleAndOccluded */ false,
+ /* inFullImmersiveMode */ false,
+ new InsetsState(),
+ /* hasGlobalFocus= */ true,
+ mExclusionRegion);
+
+ assertThat(relayoutParams.mCornerRadius).isEqualTo(INVALID_CORNER_RADIUS);
+ }
+
+ @Test
@EnableFlags(Flags.FLAG_ENABLE_APP_HEADER_WITH_TASK_DENSITY)
public void updateRelayoutParams_appHeader_usesTaskDensity() {
final int systemDensity = mTestableContext.getOrCreateTestableResources().getResources()
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index fcb7efc..e2db2c9 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -355,6 +355,7 @@
"jni/AnimatedImageDrawable.cpp",
"jni/Bitmap.cpp",
"jni/BitmapRegionDecoder.cpp",
+ "jni/RuntimeXfermode.cpp",
"jni/BufferUtils.cpp",
"jni/HardwareBufferHelpers.cpp",
"jni/BitmapFactory.cpp",
diff --git a/libs/hwui/apex/jni_runtime.cpp b/libs/hwui/apex/jni_runtime.cpp
index 15b2bac..56de568 100644
--- a/libs/hwui/apex/jni_runtime.cpp
+++ b/libs/hwui/apex/jni_runtime.cpp
@@ -28,6 +28,7 @@
extern int register_android_graphics_Bitmap(JNIEnv*);
extern int register_android_graphics_BitmapFactory(JNIEnv*);
extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
+extern int register_android_graphics_RuntimeXfermode(JNIEnv*);
extern int register_android_graphics_ByteBufferStreamAdaptor(JNIEnv* env);
extern int register_android_graphics_Camera(JNIEnv* env);
extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
@@ -107,6 +108,7 @@
REG_JNI(register_android_graphics_Bitmap),
REG_JNI(register_android_graphics_BitmapFactory),
REG_JNI(register_android_graphics_BitmapRegionDecoder),
+ REG_JNI(register_android_graphics_RuntimeXfermode),
REG_JNI(register_android_graphics_ByteBufferStreamAdaptor),
REG_JNI(register_android_graphics_Camera),
REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
diff --git a/libs/hwui/jni/Paint.cpp b/libs/hwui/jni/Paint.cpp
index da23792..a7d855d 100644
--- a/libs/hwui/jni/Paint.cpp
+++ b/libs/hwui/jni/Paint.cpp
@@ -906,6 +906,13 @@
paint->setBlendMode(mode);
}
+ static void setRuntimeXfermode(CRITICAL_JNI_PARAMS_COMMA jlong paintHandle,
+ jlong xfermodeHandle) {
+ Paint* paint = reinterpret_cast<Paint*>(paintHandle);
+ SkBlender* blender = reinterpret_cast<SkBlender*>(xfermodeHandle);
+ paint->setBlender(sk_ref_sp(blender));
+ }
+
static jlong setPathEffect(CRITICAL_JNI_PARAMS_COMMA jlong objHandle, jlong effectHandle) {
Paint* obj = reinterpret_cast<Paint*>(objHandle);
SkPathEffect* effect = reinterpret_cast<SkPathEffect*>(effectHandle);
@@ -1233,6 +1240,7 @@
{"nSetShader", "(JJ)J", (void*)PaintGlue::setShader},
{"nSetColorFilter", "(JJ)J", (void*)PaintGlue::setColorFilter},
{"nSetXfermode", "(JI)V", (void*)PaintGlue::setXfermode},
+ {"nSetXfermode", "(JJ)V", (void*)PaintGlue::setRuntimeXfermode},
{"nSetPathEffect", "(JJ)J", (void*)PaintGlue::setPathEffect},
{"nSetMaskFilter", "(JJ)J", (void*)PaintGlue::setMaskFilter},
{"nSetTypeface", "(JJ)V", (void*)PaintGlue::setTypeface},
diff --git a/libs/hwui/jni/RuntimeXfermode.cpp b/libs/hwui/jni/RuntimeXfermode.cpp
new file mode 100644
index 0000000..c1c8964
--- /dev/null
+++ b/libs/hwui/jni/RuntimeXfermode.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2024 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 "GraphicsJNI.h"
+#include "RuntimeEffectUtils.h"
+#include "SkBlender.h"
+
+using namespace android::uirenderer;
+
+static void SkRuntimeEffectBuilder_delete(SkRuntimeEffectBuilder* builder) {
+ delete builder;
+}
+
+static jlong RuntimeXfermode_getNativeFinalizer(JNIEnv*, jobject) {
+ return static_cast<jlong>(reinterpret_cast<uintptr_t>(&SkRuntimeEffectBuilder_delete));
+}
+
+static jlong RuntimeXfermode_createBuilder(JNIEnv* env, jobject, jstring sksl) {
+ ScopedUtfChars strSksl(env, sksl);
+ auto result =
+ SkRuntimeEffect::MakeForBlender(SkString(strSksl.c_str()), SkRuntimeEffect::Options{});
+ if (result.effect.get() == nullptr) {
+ doThrowIAE(env, result.errorText.c_str());
+ return 0;
+ }
+ return reinterpret_cast<jlong>(new SkRuntimeEffectBuilder(std::move(result.effect)));
+}
+
+static jlong RuntimeXfermode_create(JNIEnv* env, jobject, jlong builderPtr) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ sk_sp<SkBlender> blender = builder->makeBlender();
+ if (!blender) {
+ doThrowIAE(env);
+ }
+ return reinterpret_cast<jlong>(blender.release());
+}
+
+static void RuntimeXfermode_updateFloatArrayUniforms(JNIEnv* env, jobject, jlong builderPtr,
+ jstring uniformName, jfloatArray uniforms,
+ jboolean isColor) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ ScopedUtfChars name(env, uniformName);
+ AutoJavaFloatArray autoValues(env, uniforms, 0, kRO_JNIAccess);
+ UpdateFloatUniforms(env, builder, name.c_str(), autoValues.ptr(), autoValues.length(), isColor);
+}
+
+static void RuntimeXfermode_updateFloatUniforms(JNIEnv* env, jobject, jlong builderPtr,
+ jstring uniformName, jfloat value1, jfloat value2,
+ jfloat value3, jfloat value4, jint count) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ ScopedUtfChars name(env, uniformName);
+ const float values[4] = {value1, value2, value3, value4};
+ UpdateFloatUniforms(env, builder, name.c_str(), values, count, false);
+}
+
+static void RuntimeXfermode_updateIntArrayUniforms(JNIEnv* env, jobject, jlong builderPtr,
+ jstring uniformName, jintArray uniforms) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ ScopedUtfChars name(env, uniformName);
+ AutoJavaIntArray autoValues(env, uniforms, 0);
+ UpdateIntUniforms(env, builder, name.c_str(), autoValues.ptr(), autoValues.length());
+}
+
+static void RuntimeXfermode_updateIntUniforms(JNIEnv* env, jobject, jlong builderPtr,
+ jstring uniformName, jint value1, jint value2,
+ jint value3, jint value4, jint count) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ ScopedUtfChars name(env, uniformName);
+ const int values[4] = {value1, value2, value3, value4};
+ UpdateIntUniforms(env, builder, name.c_str(), values, count);
+}
+
+static void RuntimeXfermode_updateChild(JNIEnv* env, jobject, jlong builderPtr, jstring childName,
+ jlong childPtr) {
+ auto* builder = reinterpret_cast<SkRuntimeEffectBuilder*>(builderPtr);
+ ScopedUtfChars name(env, childName);
+ auto* child = reinterpret_cast<SkFlattenable*>(childPtr);
+ if (child) {
+ UpdateChild(env, builder, name.c_str(), child);
+ }
+}
+
+static const JNINativeMethod gRuntimeXfermodeMethods[] = {
+ {"nativeGetFinalizer", "()J", (void*)RuntimeXfermode_getNativeFinalizer},
+ {"nativeCreateBlenderBuilder", "(Ljava/lang/String;)J",
+ (void*)RuntimeXfermode_createBuilder},
+ {"nativeCreateNativeInstance", "(J)J", (void*)RuntimeXfermode_create},
+ {"nativeUpdateUniforms", "(JLjava/lang/String;[FZ)V",
+ (void*)RuntimeXfermode_updateFloatArrayUniforms},
+ {"nativeUpdateUniforms", "(JLjava/lang/String;FFFFI)V",
+ (void*)RuntimeXfermode_updateFloatUniforms},
+ {"nativeUpdateUniforms", "(JLjava/lang/String;[I)V",
+ (void*)RuntimeXfermode_updateIntArrayUniforms},
+ {"nativeUpdateUniforms", "(JLjava/lang/String;IIIII)V",
+ (void*)RuntimeXfermode_updateIntUniforms},
+ {"nativeUpdateChild", "(JLjava/lang/String;J)V", (void*)RuntimeXfermode_updateChild},
+};
+
+int register_android_graphics_RuntimeXfermode(JNIEnv* env) {
+ android::RegisterMethodsOrDie(env, "android/graphics/RuntimeXfermode", gRuntimeXfermodeMethods,
+ NELEM(gRuntimeXfermodeMethods));
+
+ return 0;
+}
diff --git a/media/java/android/media/ImageWriter.java b/media/java/android/media/ImageWriter.java
index 9325999..0a79f41 100644
--- a/media/java/android/media/ImageWriter.java
+++ b/media/java/android/media/ImageWriter.java
@@ -1157,7 +1157,11 @@
@Override
public void setFence(@NonNull SyncFence fence) throws IOException {
throwISEIfImageIsInvalid();
- nativeSetFenceFd(fence.getFdDup().detachFd());
+ if (fence.isValid()) {
+ nativeSetFenceFd(fence.getFdDup().detachFd());
+ } else {
+ nativeSetFenceFd(-1);
+ }
}
@Override
diff --git a/media/java/android/media/flags/projection.aconfig b/media/java/android/media/flags/projection.aconfig
index 17d1ff6..1bb9a8e 100644
--- a/media/java/android/media/flags/projection.aconfig
+++ b/media/java/android/media/flags/projection.aconfig
@@ -18,3 +18,10 @@
bug: "362720120"
is_exported: true
}
+
+flag {
+ namespace: "media_projection"
+ name: "stop_media_projection_on_call_end"
+ description: "Stops MediaProjection sessions when a call ends"
+ bug: "368336349"
+}
\ No newline at end of file
diff --git a/media/java/android/media/tv/extension/oad/IOadUpdateInterface.aidl b/media/java/android/media/tv/extension/oad/IOadUpdateInterface.aidl
new file mode 100644
index 0000000..2a2e71a
--- /dev/null
+++ b/media/java/android/media/tv/extension/oad/IOadUpdateInterface.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.oad;
+
+/**
+ * @hide
+ */
+interface IOadUpdateInterface {
+ // Enable or disable the OAD function.
+ void setOadStatus(boolean enable);
+ // Get status of OAD function.
+ boolean getOadStatus();
+ // Start OAD scan of all frequency in the program list.
+ void startScan();
+ // Stop OAD scan of all frequency in the program list.
+ void stopScan();
+ // Start OAD detect for the current channel.
+ void startDetect();
+ // Stop OAD detect for the current channel.
+ void stopDetect();
+ // Start OAD download after it has been detected or scanned.
+ void startDownload();
+ // Stop OAD download.
+ void stopDownload();
+ // Retrieves current OAD software version.
+ int getSoftwareVersion();
+}
diff --git a/media/java/android/media/tv/extension/rating/IDownloadableRatingTableMonitor.aidl b/media/java/android/media/tv/extension/rating/IDownloadableRatingTableMonitor.aidl
new file mode 100644
index 0000000..bf1a385
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IDownloadableRatingTableMonitor.aidl
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.os.Bundle;
+
+/**
+ * @hide
+ */
+interface IDownloadableRatingTableMonitor {
+ // Get RRT rating info on downloadable rating data
+ Bundle[] getTable();
+}
diff --git a/media/java/android/media/tv/extension/rating/IPmtRatingInterface.aidl b/media/java/android/media/tv/extension/rating/IPmtRatingInterface.aidl
new file mode 100644
index 0000000..06cac3d
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IPmtRatingInterface.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.media.tv.extension.rating.IPmtRatingListener;
+
+/**
+ * @hide
+ */
+interface IPmtRatingInterface {
+ // Get Pmt rating information.
+ String getPmtRating(String sessionToken);
+ // Register a listener for pmt rating updates.
+ void addPmtRatingListener(String clientToken, in IPmtRatingListener listener);
+ // Remove the previously added IPmtRatingListener.
+ void removePmtRatingListener(in IPmtRatingListener listener);
+}
diff --git a/media/java/android/media/tv/extension/rating/IPmtRatingListener.aidl b/media/java/android/media/tv/extension/rating/IPmtRatingListener.aidl
new file mode 100644
index 0000000..d88ae94
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IPmtRatingListener.aidl
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+/**
+ * @hide
+ */
+oneway interface IPmtRatingListener {
+ void onPmtRatingChanged(String sessionToken, String newTvContentRating);
+}
diff --git a/media/java/android/media/tv/extension/rating/IProgramRatingInfo.aidl b/media/java/android/media/tv/extension/rating/IProgramRatingInfo.aidl
new file mode 100644
index 0000000..a490491
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IProgramRatingInfo.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.media.tv.extension.rating.IProgramRatingInfoListener;
+import android.os.Bundle;
+
+/**
+ * @hide
+ */
+interface IProgramRatingInfo {
+ // Register a listener to receive notifications when ProgramRatingInfo is updated.
+ void addProgramRatingInfoListener(String clientToken, in IProgramRatingInfoListener listener);
+ // Remove a listener for ProgramRatingInfo update notifications.
+ void removeProgramRatingInfoListener(in IProgramRatingInfoListener listener);
+ // Get ProgramRatingInfo that may only be obtained when viewing.
+ Bundle getProgramRatingInfo(String sessionToken);
+}
diff --git a/media/java/android/media/tv/extension/rating/IProgramRatingInfoListener.aidl b/media/java/android/media/tv/extension/rating/IProgramRatingInfoListener.aidl
new file mode 100644
index 0000000..6777cd3
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IProgramRatingInfoListener.aidl
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.os.Bundle;
+
+/**
+ * @hide
+ */
+interface IProgramRatingInfoListener {
+ void onProgramInfoChanged(String sessionToken,in Bundle changedProgramInfo);
+}
diff --git a/media/java/android/media/tv/extension/rating/IRatingInterface.aidl b/media/java/android/media/tv/extension/rating/IRatingInterface.aidl
new file mode 100644
index 0000000..d68fe76
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IRatingInterface.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.os.Bundle;
+
+/**
+ * @hide
+ */
+interface IRatingInterface {
+ // Get RRT rating information
+ Bundle getRRTRatingInfo();
+ // Set RRT rating information when user select
+ boolean setRRTRatingInfo(in Bundle param);
+ // Reset RRT5 to clear information
+ boolean setResetRrt5();
+}
diff --git a/media/java/android/media/tv/extension/rating/IVbiRatingInterface.aidl b/media/java/android/media/tv/extension/rating/IVbiRatingInterface.aidl
new file mode 100644
index 0000000..bad4067
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IVbiRatingInterface.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+import android.media.tv.extension.rating.IVbiRatingListener;
+
+/**
+ * @hide
+ */
+interface IVbiRatingInterface {
+ // Get Vbi rating.
+ String getVbiRating(String sessionToken);
+ // Register a listener for Vbi rating updates.
+ void addVbiRatingListener(String clientToken, in IVbiRatingListener listener);
+ // Remove the previously added VbiRatingListener.
+ void removeVbiRatingListener(in IVbiRatingListener listener);
+}
diff --git a/media/java/android/media/tv/extension/rating/IVbiRatingListener.aidl b/media/java/android/media/tv/extension/rating/IVbiRatingListener.aidl
new file mode 100644
index 0000000..36d523f
--- /dev/null
+++ b/media/java/android/media/tv/extension/rating/IVbiRatingListener.aidl
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.rating;
+
+/**
+ * @hide
+ */
+oneway interface IVbiRatingListener {
+ void onVbiRatingChanged(String sessionToken, String newTvContentRating);
+}
diff --git a/media/java/android/media/tv/extension/time/IBroadcastTime.aidl b/media/java/android/media/tv/extension/time/IBroadcastTime.aidl
new file mode 100644
index 0000000..123d00f
--- /dev/null
+++ b/media/java/android/media/tv/extension/time/IBroadcastTime.aidl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2024 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.tv.extension.time;
+
+import android.os.Bundle;
+
+/**
+ * @hide
+ */
+interface IBroadcastTime {
+ long getUtcTime();
+ long getLocalTime();
+ Bundle getTimeZoneInfo();
+ long getUtcTimePerStream(String SessionToken);
+ long getLocalTimePerStream(String SessionToken);
+}
\ No newline at end of file
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
index ac85ab7..88c1c43 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
@@ -257,6 +257,16 @@
public void onRepeatingRequestError(long lastFrameNumber, int repeatingRequestId) {
// TODO Auto-generated method stub
}
+
+ /*
+ * (non-Javadoc)
+ * @see android.hardware.camera2.ICameraDeviceCallbacks#onClientSharedAccessPriorityChanged
+ */
+ @Override
+ public void onClientSharedAccessPriorityChanged(boolean primaryClient) {
+ // TODO Auto-generated method stub
+ }
+
}
@SmallTest
@@ -276,7 +286,7 @@
0 /*oomScoreOffset*/,
getContext().getApplicationInfo().targetSdkVersion,
ICameraService.ROTATION_OVERRIDE_NONE, clientAttribution,
- DEVICE_POLICY_DEFAULT);
+ DEVICE_POLICY_DEFAULT, false/*sharedMode*/);
assertNotNull(String.format("Camera %s was null", cameraId), cameraUser);
Log.v(TAG, String.format("Camera %s connected", cameraId));
@@ -320,6 +330,13 @@
Log.v(TAG, String.format("Camera " + cameraId + " torch strength level changed to "
+ torchStrength ));
}
+ @Override
+ public void onCameraOpenedInSharedMode(String cameraId, String clientPackageName,
+ int deviceId, boolean primaryClient) {
+ Log.v(TAG, "Camera " + cameraId + " is opened in shared mode by "
+ + "client package " + clientPackageName + " as primary client="
+ + primaryClient);
+ }
}
/**
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
index 35ad924..3758c51 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
@@ -175,6 +175,15 @@
public void onRepeatingRequestError(long lastFrameNumber, int repeatingRequestId) {
// TODO Auto-generated method stub
}
+
+ /**
+ * (non-Javadoc)
+ * @see android.hardware.camera2.ICameraDeviceCallbacks#onClientSharedAccessPriorityChanged
+ */
+ @Override
+ public void onClientSharedAccessPriorityChanged(boolean primaryClient) {
+ // TODO Auto-generated method stub
+ }
}
class IsMetadataNotEmpty implements ArgumentMatcher<CameraMetadataNative> {
@@ -250,7 +259,8 @@
mCameraUser = mUtils.getCameraService().connectDevice(mMockCb, mCameraId,
/*oomScoreOffset*/0, getContext().getApplicationInfo().targetSdkVersion,
- ICameraService.ROTATION_OVERRIDE_NONE, clientAttribution, DEVICE_POLICY_DEFAULT);
+ ICameraService.ROTATION_OVERRIDE_NONE, clientAttribution, DEVICE_POLICY_DEFAULT,
+ /*sharedMode*/false);
assertNotNull(String.format("Camera %s was null", mCameraId), mCameraUser);
mHandlerThread = new HandlerThread(TAG);
mHandlerThread.start();
diff --git a/nfc/api/system-current.txt b/nfc/api/system-current.txt
index c25f77b..79a0607 100644
--- a/nfc/api/system-current.txt
+++ b/nfc/api/system-current.txt
@@ -89,12 +89,12 @@
method public void onBootFinished(int);
method public void onBootStarted();
method public void onCardEmulationActivated(boolean);
- method public void onDisable(@NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onDisableFinished(int);
+ method public void onDisableRequested(@NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onDisableStarted();
method public void onEeListenActivated(boolean);
- method public void onEnable(@NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onEnableFinished(int);
+ method public void onEnableRequested(@NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onEnableStarted();
method public void onGetOemAppSearchIntent(@NonNull java.util.List<java.lang.String>, @NonNull java.util.function.Consumer<android.content.Intent>);
method public void onHceEventReceived(int);
@@ -183,6 +183,12 @@
method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<android.nfc.cardemulation.ApduServiceInfo> getServices(@NonNull String, int);
method @FlaggedApi("android.nfc.nfc_override_recover_routing_table") public void overrideRoutingTable(@NonNull android.app.Activity, int, int);
method @FlaggedApi("android.nfc.nfc_override_recover_routing_table") public void recoverRoutingTable(@NonNull android.app.Activity);
+ method @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public int setServiceEnabledForCategoryOther(@NonNull android.content.ComponentName, boolean);
+ field @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_ALREADY_SET = 3; // 0x3
+ field @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_FEATURE_UNSUPPORTED = 1; // 0x1
+ field @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_INVALID_SERVICE = 2; // 0x2
+ field @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_UNKNOWN_ERROR = 4; // 0x4
+ field @FlaggedApi("android.nfc.nfc_set_service_enabled_for_category_other") public static final int SET_SERVICE_ENABLED_STATUS_OK = 0; // 0x0
}
}
diff --git a/nfc/java/android/nfc/INfcCardEmulation.aidl b/nfc/java/android/nfc/INfcCardEmulation.aidl
index 5e2e92d..633d8bf 100644
--- a/nfc/java/android/nfc/INfcCardEmulation.aidl
+++ b/nfc/java/android/nfc/INfcCardEmulation.aidl
@@ -47,7 +47,7 @@
boolean unsetPreferredService();
boolean supportsAidPrefixRegistration();
ApduServiceInfo getPreferredPaymentService(int userHandle);
- boolean setServiceEnabledForCategoryOther(int userHandle, in ComponentName app, boolean status);
+ int setServiceEnabledForCategoryOther(int userHandle, in ComponentName app, boolean status);
boolean isDefaultPaymentRegistered();
void overrideRoutingTable(int userHandle, String protocol, String technology, in String pkg);
diff --git a/nfc/java/android/nfc/NfcOemExtension.java b/nfc/java/android/nfc/NfcOemExtension.java
index 57ee981..fd131b8 100644
--- a/nfc/java/android/nfc/NfcOemExtension.java
+++ b/nfc/java/android/nfc/NfcOemExtension.java
@@ -23,11 +23,11 @@
import android.Manifest;
import android.annotation.CallbackExecutor;
+import android.annotation.DurationMillisLong;
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.content.ComponentName;
import android.content.Context;
@@ -233,8 +233,7 @@
* {@link Boolean#TRUE}, otherwise call with {@link Boolean#FALSE}.
* false if NFC cannot be enabled at this time.
*/
- @SuppressLint("MethodNameTense")
- void onEnable(@NonNull Consumer<Boolean> isAllowed);
+ void onEnableRequested(@NonNull Consumer<Boolean> isAllowed);
/**
* Method to check if Nfc is allowed to be disabled by OEMs.
* @param isAllowed The {@link Consumer} to be completed. If disabling NFC is allowed,
@@ -242,7 +241,7 @@
* {@link Boolean#TRUE}, otherwise call with {@link Boolean#FALSE}.
* false if NFC cannot be disabled at this time.
*/
- void onDisable(@NonNull Consumer<Boolean> isAllowed);
+ void onDisableRequested(@NonNull Consumer<Boolean> isAllowed);
/**
* Callback to indicate that Nfc starts to boot.
@@ -255,7 +254,7 @@
void onEnableStarted();
/**
- * Callback to indicate that Nfc starts to enable.
+ * Callback to indicate that Nfc starts to disable.
*/
void onDisableStarted();
@@ -605,12 +604,12 @@
/**
* Pauses NFC tag reader mode polling for a {@code timeoutInMs} millisecond.
* In case of {@code timeoutInMs} is zero or invalid polling will be stopped indefinitely
- * use {@link #resumePolling() to resume the polling.
- * @param timeoutInMs the pause polling duration in millisecond
+ * use {@link #resumePolling()} to resume the polling.
+ * @param timeoutInMs the pause polling duration in millisecond, ranging from 0 to 40000.
*/
@FlaggedApi(Flags.FLAG_NFC_OEM_EXTENSION)
@RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
- public void pausePolling(int timeoutInMs) {
+ public void pausePolling(@DurationMillisLong int timeoutInMs) {
NfcAdapter.callService(() -> NfcAdapter.sService.pausePolling(timeoutInMs));
}
@@ -799,13 +798,13 @@
public void onEnable(ResultReceiver isAllowed) throws RemoteException {
mCallbackMap.forEach((cb, ex) ->
handleVoidCallback(
- new ReceiverWrapper<>(isAllowed), cb::onEnable, ex));
+ new ReceiverWrapper<>(isAllowed), cb::onEnableRequested, ex));
}
@Override
public void onDisable(ResultReceiver isAllowed) throws RemoteException {
mCallbackMap.forEach((cb, ex) ->
handleVoidCallback(
- new ReceiverWrapper<>(isAllowed), cb::onDisable, ex));
+ new ReceiverWrapper<>(isAllowed), cb::onDisableRequested, ex));
}
@Override
public void onBootStarted() throws RemoteException {
diff --git a/nfc/java/android/nfc/cardemulation/CardEmulation.java b/nfc/java/android/nfc/cardemulation/CardEmulation.java
index eb28c3b..8917524 100644
--- a/nfc/java/android/nfc/cardemulation/CardEmulation.java
+++ b/nfc/java/android/nfc/cardemulation/CardEmulation.java
@@ -185,6 +185,65 @@
@FlaggedApi(Flags.FLAG_NFC_OVERRIDE_RECOVER_ROUTING_TABLE)
public static final int PROTOCOL_AND_TECHNOLOGY_ROUTE_UNSET = -1;
+ /**
+ * Status code returned when {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * succeeded.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ public static final int SET_SERVICE_ENABLED_STATUS_OK = 0;
+
+ /**
+ * Status code returned when {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * failed due to the unsupported feature.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_FEATURE_UNSUPPORTED = 1;
+
+ /**
+ * Status code returned when {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * failed due to the invalid service.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_INVALID_SERVICE = 2;
+
+ /**
+ * Status code returned when {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * failed due to the service is already set to the requested status.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_ALREADY_SET = 3;
+
+ /**
+ * Status code returned when {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * failed due to unknown error.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ public static final int SET_SERVICE_ENABLED_STATUS_FAILURE_UNKNOWN_ERROR = 4;
+
+ /**
+ * Status code returned by {@link #setServiceEnabledForCategoryOther(ComponentName, boolean)}
+ * @hide
+ */
+ @IntDef(prefix = "SET_SERVICE_ENABLED_STATUS_", value = {
+ SET_SERVICE_ENABLED_STATUS_OK,
+ SET_SERVICE_ENABLED_STATUS_FAILURE_FEATURE_UNSUPPORTED,
+ SET_SERVICE_ENABLED_STATUS_FAILURE_INVALID_SERVICE,
+ SET_SERVICE_ENABLED_STATUS_FAILURE_ALREADY_SET,
+ SET_SERVICE_ENABLED_STATUS_FAILURE_UNKNOWN_ERROR
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface SetServiceEnabledStatusCode {}
+
static boolean sIsInitialized = false;
static HashMap<Context, CardEmulation> sCardEmus = new HashMap<Context, CardEmulation>();
static INfcCardEmulation sService;
@@ -883,22 +942,24 @@
}
/**
- * Allows to set or unset preferred service (category other) to avoid AID Collision.
+ * Allows to set or unset preferred service (category other) to avoid AID Collision. The user
+ * should use corresponding context using {@link Context#createContextAsUser(UserHandle, int)}
*
* @param service The ComponentName of the service
* @param status true to enable, false to disable
- * @param userId the user handle of the user whose information is being requested.
- * @return set service for the category and true if service is already set return false.
+ * @return true if preferred service is successfully set or unset, otherwise return false.
*
* @hide
*/
- public boolean setServiceEnabledForCategoryOther(ComponentName service, boolean status,
- int userId) {
- if (service == null) {
- throw new NullPointerException("activity or service or category is null");
- }
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_NFC_SET_SERVICE_ENABLED_FOR_CATEGORY_OTHER)
+ @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
+ @SetServiceEnabledStatusCode
+ public int setServiceEnabledForCategoryOther(@NonNull ComponentName service,
+ boolean status) {
return callServiceReturn(() ->
- sService.setServiceEnabledForCategoryOther(userId, service, status), false);
+ sService.setServiceEnabledForCategoryOther(mContext.getUser().getIdentifier(),
+ service, status), SET_SERVICE_ENABLED_STATUS_FAILURE_UNKNOWN_ERROR);
}
/** @hide */
diff --git a/nfc/java/android/nfc/flags.aconfig b/nfc/java/android/nfc/flags.aconfig
index 34f0200..8a37aa2 100644
--- a/nfc/java/android/nfc/flags.aconfig
+++ b/nfc/java/android/nfc/flags.aconfig
@@ -173,3 +173,11 @@
description: "Share wallet role routing priority with associated services"
bug: "366243361"
}
+
+flag {
+ name: "nfc_set_service_enabled_for_category_other"
+ is_exported: true
+ namespace: "nfc"
+ description: "Enable set service enabled for category other"
+ bug: "338157113"
+}
diff --git a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/GetPreferenceGraphApiHandler.kt b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/GetPreferenceGraphApiHandler.kt
index 5ceee6d..088bef2 100644
--- a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/GetPreferenceGraphApiHandler.kt
+++ b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/GetPreferenceGraphApiHandler.kt
@@ -22,11 +22,13 @@
import com.android.settingslib.ipc.ApiHandler
import com.android.settingslib.ipc.MessageCodec
import com.android.settingslib.metadata.PreferenceScreenRegistry
+import com.android.settingslib.preference.PreferenceScreenProvider
import java.util.Locale
/** API to get preference graph. */
-abstract class GetPreferenceGraphApiHandler :
- ApiHandler<GetPreferenceGraphRequest, PreferenceGraphProto> {
+abstract class GetPreferenceGraphApiHandler(
+ private val preferenceScreenProviders: Set<Class<out PreferenceScreenProvider>>
+) : ApiHandler<GetPreferenceGraphRequest, PreferenceGraphProto> {
override val requestCodec: MessageCodec<GetPreferenceGraphRequest>
get() = GetPreferenceGraphRequestCodec
@@ -40,14 +42,16 @@
callingUid: Int,
request: GetPreferenceGraphRequest,
): PreferenceGraphProto {
- val builderRequest =
- if (request.screenKeys.isEmpty()) {
- val keys = PreferenceScreenRegistry.preferenceScreens.keys
- GetPreferenceGraphRequest(keys, request.visitedScreens, request.locale)
- } else {
- request
+ val builder = PreferenceGraphBuilder.of(application, request)
+ if (request.screenKeys.isEmpty()) {
+ for (key in PreferenceScreenRegistry.preferenceScreens.keys) {
+ builder.addPreferenceScreenFromRegistry(key)
}
- return PreferenceGraphBuilder.of(application, builderRequest).build()
+ for (provider in preferenceScreenProviders) {
+ builder.addPreferenceScreenProvider(provider)
+ }
+ }
+ return builder.build()
}
}
diff --git a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceGraphBuilder.kt b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceGraphBuilder.kt
index 2256bb3..6760e72 100644
--- a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceGraphBuilder.kt
+++ b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceGraphBuilder.kt
@@ -133,7 +133,7 @@
null
}
- private suspend fun addPreferenceScreenFromRegistry(key: String): Boolean {
+ suspend fun addPreferenceScreenFromRegistry(key: String): Boolean {
val metadata = PreferenceScreenRegistry[key] ?: return false
return addPreferenceScreenMetadata(metadata)
}
@@ -146,7 +146,7 @@
}
}
- private suspend fun addPreferenceScreenProvider(activityClass: Class<*>) {
+ suspend fun addPreferenceScreenProvider(activityClass: Class<*>) {
Log.d(TAG, "add $activityClass")
createPreferenceScreen { activityClass.newInstance() }
?.let {
diff --git a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceSetterApi.kt b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceSetterApi.kt
index 6e4db1d..7cfce0d 100644
--- a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceSetterApi.kt
+++ b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/PreferenceSetterApi.kt
@@ -22,6 +22,7 @@
import com.android.settingslib.graph.proto.PreferenceValueProto
import com.android.settingslib.ipc.ApiDescriptor
import com.android.settingslib.ipc.ApiHandler
+import com.android.settingslib.ipc.ApiPermissionChecker
import com.android.settingslib.ipc.IntMessageCodec
import com.android.settingslib.ipc.MessageCodec
import com.android.settingslib.metadata.BooleanValue
@@ -45,7 +46,11 @@
PreferenceSetterResult.OK,
PreferenceSetterResult.UNSUPPORTED,
PreferenceSetterResult.DISABLED,
+ PreferenceSetterResult.RESTRICTED,
PreferenceSetterResult.UNAVAILABLE,
+ PreferenceSetterResult.REQUIRE_APP_PERMISSION,
+ PreferenceSetterResult.REQUIRE_USER_AGREEMENT,
+ PreferenceSetterResult.DISALLOW,
PreferenceSetterResult.INVALID_REQUEST,
PreferenceSetterResult.INTERNAL_ERROR,
)
@@ -87,14 +92,17 @@
}
/** Preference setter API implementation. */
-class PreferenceSetterApiHandler(override val id: Int) : ApiHandler<PreferenceSetterRequest, Int> {
+class PreferenceSetterApiHandler(
+ override val id: Int,
+ private val permissionChecker: ApiPermissionChecker<PreferenceSetterRequest>,
+) : ApiHandler<PreferenceSetterRequest, Int> {
override fun hasPermission(
application: Application,
myUid: Int,
callingUid: Int,
request: PreferenceSetterRequest,
- ): Boolean = true
+ ) = permissionChecker.hasPermission(application, myUid, callingUid, request)
override suspend fun invoke(
application: Application,
diff --git a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/ProtoConverters.kt b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/ProtoConverters.kt
index d9b9590..1bda277 100644
--- a/packages/SettingsLib/Graph/src/com/android/settingslib/graph/ProtoConverters.kt
+++ b/packages/SettingsLib/Graph/src/com/android/settingslib/graph/ProtoConverters.kt
@@ -16,8 +16,10 @@
package com.android.settingslib.graph
+import android.content.ComponentName
import android.content.Context
import android.content.Intent
+import android.net.Uri
import android.os.Bundle
import com.android.settingslib.graph.proto.BundleProto
import com.android.settingslib.graph.proto.BundleProto.BundleValue
@@ -42,6 +44,20 @@
this@toProto.type?.let { mimeType = it }
}
+fun IntentProto.toIntent(): Intent? {
+ if (!hasComponent()) return null
+ val componentName = ComponentName.unflattenFromString(component) ?: return null
+ val intent = Intent()
+ intent.component = componentName
+ if (hasAction()) intent.action = action
+ if (hasData()) intent.data = Uri.parse(data)
+ if (hasPkg()) intent.`package` = pkg
+ if (hasFlags()) intent.flags = flags
+ if (hasExtras()) intent.putExtras(extras.toBundle())
+ if (hasMimeType()) intent.setType(mimeType)
+ return intent
+}
+
fun Bundle.toProto(): BundleProto = bundleProto {
fun toProto(value: Any): BundleValue = bundleValueProto {
when (value) {
@@ -61,14 +77,18 @@
}
}
-fun BundleValue.stringify(): String =
- when {
- hasBooleanValue() -> "$valueCase"
- hasBytesValue() -> "$bytesValue"
- hasIntValue() -> "$intValue"
- hasLongValue() -> "$longValue"
- hasStringValue() -> stringValue
- hasDoubleValue() -> "$doubleValue"
- hasBundleValue() -> "$bundleValue"
- else -> "Unknown"
+fun BundleProto.toBundle(): Bundle =
+ Bundle().apply {
+ for ((key, value) in valuesMap) {
+ when {
+ value.hasBooleanValue() -> putBoolean(key, value.booleanValue)
+ value.hasBytesValue() -> putByteArray(key, value.bytesValue.toByteArray())
+ value.hasIntValue() -> putInt(key, value.intValue)
+ value.hasLongValue() -> putLong(key, value.longValue)
+ value.hasStringValue() -> putString(key, value.stringValue)
+ value.hasDoubleValue() -> putDouble(key, value.doubleValue)
+ value.hasBundleValue() -> putBundle(key, value.bundleValue.toBundle())
+ else -> throw IllegalArgumentException("Unknown type: ${value.javaClass} $value")
+ }
+ }
}
diff --git a/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/ApiHandler.kt b/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/ApiHandler.kt
index 802141d..4febd89 100644
--- a/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/ApiHandler.kt
+++ b/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/ApiHandler.kt
@@ -56,6 +56,27 @@
val responseCodec: MessageCodec<Response>
}
+/** Permission checker for api. */
+fun interface ApiPermissionChecker<R> {
+ /**
+ * Returns if the request is permitted.
+ *
+ * @param application application context
+ * @param myUid uid of current process
+ * @param callingUid uid of peer process
+ * @param request API request
+ * @return `false` if permission is denied, otherwise `true`
+ */
+ fun hasPermission(application: Application, myUid: Int, callingUid: Int, request: R): Boolean
+
+ companion object {
+ private val ALWAYS_ALLOW = ApiPermissionChecker<Any> { _, _, _, _ -> true }
+
+ @Suppress("UNCHECKED_CAST")
+ fun <T> alwaysAllow(): ApiPermissionChecker<T> = ALWAYS_ALLOW as ApiPermissionChecker<T>
+ }
+}
+
/**
* Handler of API.
*
@@ -64,18 +85,8 @@
*
* The implementation must be threadsafe.
*/
-interface ApiHandler<Request, Response> : ApiDescriptor<Request, Response> {
- /**
- * Returns if the request is permitted.
- *
- * @return `false` if permission is denied, otherwise `true`
- */
- fun hasPermission(
- application: Application,
- myUid: Int,
- callingUid: Int,
- request: Request,
- ): Boolean
+interface ApiHandler<Request, Response> :
+ ApiDescriptor<Request, Response>, ApiPermissionChecker<Request> {
/**
* Invokes the API.
diff --git a/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/MessengerServiceClient.kt b/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/MessengerServiceClient.kt
index 7ffefed..ef907e1 100644
--- a/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/MessengerServiceClient.kt
+++ b/packages/SettingsLib/Ipc/src/com/android/settingslib/ipc/MessengerServiceClient.kt
@@ -320,6 +320,11 @@
}
}
+ override fun onNullBinding(name: ComponentName) {
+ Log.i(TAG, "onNullBinding $name")
+ close(ClientBindServiceException(null))
+ }
+
internal open fun drainPendingRequests() {
disposableHandle = null
if (pendingRequests.isEmpty()) {
diff --git a/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceGraphApi.kt b/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceGraphApi.kt
index 6e38df1..1823ba6 100644
--- a/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceGraphApi.kt
+++ b/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceGraphApi.kt
@@ -19,9 +19,14 @@
import android.app.Application
import com.android.settingslib.graph.GetPreferenceGraphApiHandler
import com.android.settingslib.graph.GetPreferenceGraphRequest
+import com.android.settingslib.ipc.ApiPermissionChecker
+import com.android.settingslib.preference.PreferenceScreenProvider
/** Api to get preference graph. */
-internal class PreferenceGraphApi : GetPreferenceGraphApiHandler() {
+internal class PreferenceGraphApi(
+ preferenceScreenProviders: Set<Class<out PreferenceScreenProvider>>,
+ private val permissionChecker: ApiPermissionChecker<GetPreferenceGraphRequest>,
+) : GetPreferenceGraphApiHandler(preferenceScreenProviders) {
override val id: Int
get() = API_GET_PREFERENCE_GRAPH
@@ -31,5 +36,5 @@
myUid: Int,
callingUid: Int,
request: GetPreferenceGraphRequest,
- ) = true
+ ) = permissionChecker.hasPermission(application, myUid, callingUid, request)
}
diff --git a/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceService.kt b/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceService.kt
index 8ebb145..ed748bb 100644
--- a/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceService.kt
+++ b/packages/SettingsLib/Service/src/com/android/settingslib/service/PreferenceService.kt
@@ -16,10 +16,14 @@
package com.android.settingslib.service
+import com.android.settingslib.graph.GetPreferenceGraphRequest
import com.android.settingslib.graph.PreferenceSetterApiHandler
+import com.android.settingslib.graph.PreferenceSetterRequest
import com.android.settingslib.ipc.ApiHandler
+import com.android.settingslib.ipc.ApiPermissionChecker
import com.android.settingslib.ipc.MessengerService
import com.android.settingslib.ipc.PermissionChecker
+import com.android.settingslib.preference.PreferenceScreenProvider
/**
* Preference service providing a bunch of APIs.
@@ -28,14 +32,21 @@
* [PREFERENCE_SERVICE_ACTION].
*/
open class PreferenceService(
- permissionChecker: PermissionChecker,
name: String = "PreferenceService",
+ permissionChecker: PermissionChecker = PermissionChecker { _, _, _ -> true },
+ preferenceScreenProviders: Set<Class<out PreferenceScreenProvider>> = setOf(),
+ graphPermissionChecker: ApiPermissionChecker<GetPreferenceGraphRequest>? = null,
+ setterPermissionChecker: ApiPermissionChecker<PreferenceSetterRequest>? = null,
+ vararg apiHandlers: ApiHandler<*, *>,
) :
MessengerService(
- listOf<ApiHandler<*, *>>(
- PreferenceGraphApi(),
- PreferenceSetterApiHandler(API_PREFERENCE_SETTER),
- ),
+ mutableListOf<ApiHandler<*, *>>().apply {
+ graphPermissionChecker?.let { add(PreferenceGraphApi(preferenceScreenProviders, it)) }
+ setterPermissionChecker?.let {
+ add(PreferenceSetterApiHandler(API_PREFERENCE_SETTER, it))
+ }
+ addAll(apiHandlers)
+ },
permissionChecker,
name,
)
diff --git a/packages/SettingsLib/Service/src/com/android/settingslib/service/ServiceApiConstants.kt b/packages/SettingsLib/Service/src/com/android/settingslib/service/ServiceApiConstants.kt
index 1f38a66..7655daa 100644
--- a/packages/SettingsLib/Service/src/com/android/settingslib/service/ServiceApiConstants.kt
+++ b/packages/SettingsLib/Service/src/com/android/settingslib/service/ServiceApiConstants.kt
@@ -18,5 +18,14 @@
const val PREFERENCE_SERVICE_ACTION = "com.android.settingslib.PREFERENCE_SERVICE"
+/** API id for retrieving preference graph. */
internal const val API_GET_PREFERENCE_GRAPH = 1
+
+/** API id for preference value setter. */
internal const val API_PREFERENCE_SETTER = 2
+
+/**
+ * The max API id reserved for internal preference service usages. Custom API id should start with
+ * **1000** to avoid conflict.
+ */
+internal const val API_MAX_RESERVED = 999
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/InputMediaDevice.java b/packages/SettingsLib/src/com/android/settingslib/media/InputMediaDevice.java
index 83ee975..80e5e59 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/InputMediaDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/InputMediaDevice.java
@@ -15,6 +15,7 @@
*/
package com.android.settingslib.media;
+import static android.media.AudioDeviceInfo.TYPE_BLE_HEADSET;
import static android.media.AudioDeviceInfo.TYPE_BLUETOOTH_SCO;
import static android.media.AudioDeviceInfo.TYPE_BUILTIN_MIC;
import static android.media.AudioDeviceInfo.TYPE_USB_ACCESSORY;
@@ -103,7 +104,8 @@
TYPE_USB_DEVICE,
TYPE_USB_HEADSET,
TYPE_USB_ACCESSORY,
- TYPE_BLUETOOTH_SCO ->
+ TYPE_BLUETOOTH_SCO,
+ TYPE_BLE_HEADSET ->
true;
default -> false;
};
@@ -124,7 +126,7 @@
mProductName != null
? mProductName
: mContext.getString(R.string.media_transfer_usb_device_mic_name);
- case TYPE_BLUETOOTH_SCO ->
+ case TYPE_BLUETOOTH_SCO, TYPE_BLE_HEADSET ->
mProductName != null
? mProductName
: mContext.getString(R.string.media_transfer_bt_device_mic_name);
diff --git a/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java b/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
index 5eeb49a..6842d0a 100644
--- a/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
+++ b/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
@@ -204,6 +204,13 @@
return this;
}
+ public TestModeBuilder implicitForPackage(String pkg) {
+ setPackage(pkg);
+ setId(ZenModeConfig.implicitRuleId(pkg));
+ setName("Do Not Disturb (" + pkg + ")");
+ return this;
+ }
+
public TestModeBuilder setActive(boolean active) {
if (active) {
mConfigZenRule.enabled = true;
diff --git a/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java b/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
index 34d3bd9..d5cfe55 100644
--- a/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
+++ b/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
@@ -208,6 +208,11 @@
}
@NonNull
+ public Kind getKind() {
+ return mKind;
+ }
+
+ @NonNull
public Status getStatus() {
return mStatus;
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InputMediaDeviceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InputMediaDeviceTest.java
index 7775b91..8624c4d 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InputMediaDeviceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InputMediaDeviceTest.java
@@ -38,6 +38,7 @@
private final int WIRED_HEADSET_ID = 2;
private final int USB_HEADSET_ID = 3;
private final int BT_HEADSET_ID = 4;
+ private final int BLE_HEADSET_ID = 5;
private final int MAX_VOLUME = 1;
private final int CURRENT_VOLUME = 0;
private final boolean IS_VOLUME_FIXED = true;
@@ -45,6 +46,7 @@
private static final String PRODUCT_NAME_WIRED_HEADSET = "My Wired Headset";
private static final String PRODUCT_NAME_USB_HEADSET = "My USB Headset";
private static final String PRODUCT_NAME_BT_HEADSET = "My Bluetooth Headset";
+ private static final String PRODUCT_NAME_BLE_HEADSET = "My BLE Headset";
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@@ -163,4 +165,35 @@
assertThat(btMediaDevice.getName())
.isEqualTo(mContext.getString(R.string.media_transfer_bt_device_mic_name));
}
+
+ @Test
+ public void getName_returnCorrectName_bleHeadset() {
+ InputMediaDevice bleMediaDevice =
+ InputMediaDevice.create(
+ mContext,
+ String.valueOf(BLE_HEADSET_ID),
+ AudioDeviceInfo.TYPE_BLE_HEADSET,
+ MAX_VOLUME,
+ CURRENT_VOLUME,
+ IS_VOLUME_FIXED,
+ PRODUCT_NAME_BLE_HEADSET);
+ assertThat(bleMediaDevice).isNotNull();
+ assertThat(bleMediaDevice.getName()).isEqualTo(PRODUCT_NAME_BLE_HEADSET);
+ }
+
+ @Test
+ public void getName_returnCorrectName_bleHeadset_nullProductName() {
+ InputMediaDevice bleMediaDevice =
+ InputMediaDevice.create(
+ mContext,
+ String.valueOf(BLE_HEADSET_ID),
+ AudioDeviceInfo.TYPE_BLE_HEADSET,
+ MAX_VOLUME,
+ CURRENT_VOLUME,
+ IS_VOLUME_FIXED,
+ null);
+ assertThat(bleMediaDevice).isNotNull();
+ assertThat(bleMediaDevice.getName())
+ .isEqualTo(mContext.getString(R.string.media_transfer_bt_device_mic_name));
+ }
}
diff --git a/packages/SettingsProvider/res/xml/bookmarks.xml b/packages/SettingsProvider/res/xml/bookmarks.xml
index 22d0226..645b275 100644
--- a/packages/SettingsProvider/res/xml/bookmarks.xml
+++ b/packages/SettingsProvider/res/xml/bookmarks.xml
@@ -32,6 +32,9 @@
'y': YouTube
-->
<bookmarks>
+ <!-- TODO(b/358569822): Remove this from Settings DB
+ This is legacy implementation to store bookmarks in Settings DB, which is deprecated and
+ no longer used -->
<bookmark
role="android.app.role.BROWSER"
shortcut="b" />
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 7b6321d..526320d 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -369,6 +369,9 @@
<!-- Permission needed for CTS test - UnsupportedErrorDialogTests -->
<uses-permission android:name="android.permission.RESET_APP_ERRORS" />
+ <!-- Permission needed tests -->
+ <uses-permission android:name="android.permission.OBSERVE_PICTURE_PROFILES" />
+
<!-- Permission needed for CTS test - CtsSystemUiTestCases:PipNotificationTests -->
<uses-permission android:name="android.permission.GET_INTENT_SENDER_INTENT" />
@@ -953,6 +956,13 @@
<uses-permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
android:featureFlag="android.security.aapm_api"/>
+ <!-- Permission required for CTS test - ForensicManagerTest -->
+ <uses-permission android:name="android.permission.READ_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"/>
+ <uses-permission android:name="android.permission.MANAGE_FORENSIC_STATE"
+ android:featureFlag="android.security.afl_api"/>
+
+
<!-- Permission required for CTS test - CtsAppTestCases -->
<uses-permission android:name="android.permission.KILL_UID" />
diff --git a/packages/Shell/aconfig/Android.bp b/packages/Shell/aconfig/Android.bp
new file mode 100644
index 0000000..1d797b2
--- /dev/null
+++ b/packages/Shell/aconfig/Android.bp
@@ -0,0 +1,13 @@
+aconfig_declarations {
+ name: "wear_aconfig_declarations",
+ package: "com.android.shell.flags",
+ container: "system",
+ srcs: [
+ "wear.aconfig",
+ ],
+}
+
+java_aconfig_library {
+ name: "wear_aconfig_declarations_flags_java_lib",
+ aconfig_declarations: "wear_aconfig_declarations",
+}
diff --git a/packages/Shell/aconfig/wear.aconfig b/packages/Shell/aconfig/wear.aconfig
new file mode 100644
index 0000000..e07bd96
--- /dev/null
+++ b/packages/Shell/aconfig/wear.aconfig
@@ -0,0 +1,9 @@
+package: "com.android.shell.flags"
+container: "system"
+
+flag {
+ name: "handle_bugreports_for_wear"
+ namespace: "wear_services"
+ description: "This flag enables Shell to propagate bugreport results to WearServices."
+ bug: "378060870"
+}
\ No newline at end of file
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
index 18f40c9..eee0caf 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
@@ -24,18 +24,22 @@
import android.content.ComponentName
import android.graphics.Color
import android.graphics.Matrix
+import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import android.os.Binder
import android.os.Build
import android.os.Handler
+import android.os.IBinder
import android.os.Looper
import android.os.RemoteException
+import android.util.ArrayMap
import android.util.Log
import android.view.IRemoteAnimationFinishedCallback
import android.view.IRemoteAnimationRunner
import android.view.RemoteAnimationAdapter
import android.view.RemoteAnimationTarget
+import android.view.SurfaceControl
import android.view.SyncRtSurfaceTransactionApplier
import android.view.View
import android.view.ViewGroup
@@ -45,8 +49,12 @@
import android.view.WindowManager.TRANSIT_TO_BACK
import android.view.WindowManager.TRANSIT_TO_FRONT
import android.view.animation.PathInterpolator
+import android.window.IRemoteTransition
+import android.window.IRemoteTransitionFinishedCallback
import android.window.RemoteTransition
import android.window.TransitionFilter
+import android.window.TransitionInfo
+import android.window.WindowAnimationState
import androidx.annotation.AnyThread
import androidx.annotation.BinderThread
import androidx.annotation.UiThread
@@ -55,11 +63,14 @@
import com.android.internal.policy.ScreenDecorationsUtils
import com.android.systemui.Flags.activityTransitionUseLargestWindow
import com.android.systemui.Flags.translucentOccludingActivityFix
+import com.android.systemui.animation.TransitionAnimator.Companion.assertLongLivedReturnAnimations
+import com.android.systemui.animation.TransitionAnimator.Companion.assertReturnAnimations
+import com.android.systemui.animation.TransitionAnimator.Companion.longLivedReturnAnimationsEnabled
+import com.android.systemui.animation.TransitionAnimator.Companion.returnAnimationsEnabled
import com.android.systemui.animation.TransitionAnimator.Companion.toTransitionState
-import com.android.systemui.shared.Flags.returnAnimationFrameworkLibrary
-import com.android.systemui.shared.Flags.returnAnimationFrameworkLongLived
import com.android.wm.shell.shared.IShellTransitions
import com.android.wm.shell.shared.ShellTransitions
+import com.android.wm.shell.shared.TransitionUtil
import java.util.concurrent.Executor
import kotlin.math.roundToInt
@@ -194,7 +205,13 @@
private const val LONG_TRANSITION_TIMEOUT = 5_000L
private fun defaultTransitionAnimator(mainExecutor: Executor): TransitionAnimator {
- return TransitionAnimator(mainExecutor, TIMINGS, INTERPOLATORS)
+ return TransitionAnimator(
+ mainExecutor,
+ TIMINGS,
+ INTERPOLATORS,
+ SPRING_TIMINGS,
+ SPRING_INTERPOLATORS,
+ )
}
private fun defaultDialogToAppAnimator(mainExecutor: Executor): TransitionAnimator {
@@ -275,7 +292,7 @@
"ActivityTransitionAnimator.callback must be set before using this animator"
)
val runner = createRunner(controller)
- val runnerDelegate = runner.delegate!!
+ val runnerDelegate = runner.delegate
val hideKeyguardWithAnimation = callback.isOnKeyguard() && !showOverLockscreen
// Pass the RemoteAnimationAdapter to the intent starter only if we are not hiding the
@@ -330,7 +347,11 @@
// If we expect an animation, post a timeout to cancel it in case the remote animation is
// never started.
if (willAnimate) {
- runnerDelegate.postTimeouts()
+ if (longLivedReturnAnimationsEnabled()) {
+ runner.postTimeouts()
+ } else {
+ runnerDelegate!!.postTimeouts()
+ }
// Hide the keyguard using the launch animation instead of the default unlock animation.
if (hideKeyguardWithAnimation) {
@@ -390,7 +411,7 @@
launchController: Controller,
transitionRegister: TransitionRegister?,
) {
- if (!returnAnimationFrameworkLibrary()) return
+ if (!returnAnimationsEnabled()) return
var cleanUpRunnable: Runnable? = null
val returnRunner =
@@ -413,7 +434,8 @@
private fun cleanUp() {
cleanUpRunnable?.run()
}
- }
+ },
+ initializeLazily = longLivedReturnAnimationsEnabled(),
)
// mTypeSet and mModes match back signals only, and not home. This is on purpose, because
@@ -435,7 +457,11 @@
"${launchController.transitionCookie}_returnTransition",
)
- transitionRegister?.register(filter, transition)
+ transitionRegister?.register(
+ filter,
+ transition,
+ includeTakeover = longLivedReturnAnimationsEnabled(),
+ )
cleanUpRunnable = Runnable { transitionRegister?.unregister(transition) }
}
@@ -451,7 +477,10 @@
/** Create a new animation [Runner] controlled by [controller]. */
@VisibleForTesting
- fun createRunner(controller: Controller): Runner {
+ @JvmOverloads
+ fun createRunner(controller: Controller, initializeLazily: Boolean = false): Runner {
+ if (initializeLazily) assertLongLivedReturnAnimations()
+
// Make sure we use the modified timings when animating a dialog into an app.
val transitionAnimator =
if (controller.isDialogLaunch) {
@@ -460,7 +489,13 @@
transitionAnimator
}
- return Runner(controller, callback!!, transitionAnimator, lifecycleListener)
+ return Runner(
+ controller,
+ callback!!,
+ transitionAnimator,
+ lifecycleListener,
+ initializeLazily,
+ )
}
interface PendingIntentStarter {
@@ -628,10 +663,7 @@
* this registration.
*/
fun register(controller: Controller) {
- check(returnAnimationFrameworkLongLived()) {
- "Long-lived registrations cannot be used when the returnAnimationFrameworkLongLived " +
- "flag is disabled"
- }
+ assertLongLivedReturnAnimations()
if (transitionRegister == null) {
throw IllegalStateException(
@@ -667,10 +699,10 @@
}
val launchRemoteTransition =
RemoteTransition(
- RemoteAnimationRunnerCompat.wrap(createRunner(controller)),
+ OriginTransition(createRunner(controller, initializeLazily = true)),
"${cookie}_launchTransition",
)
- transitionRegister.register(launchFilter, launchRemoteTransition)
+ transitionRegister.register(launchFilter, launchRemoteTransition, includeTakeover = true)
val returnController =
object : Controller by controller {
@@ -689,10 +721,10 @@
}
val returnRemoteTransition =
RemoteTransition(
- RemoteAnimationRunnerCompat.wrap(createRunner(returnController)),
+ OriginTransition(createRunner(returnController, initializeLazily = true)),
"${cookie}_returnTransition",
)
- transitionRegister.register(returnFilter, returnRemoteTransition)
+ transitionRegister.register(returnFilter, returnRemoteTransition, includeTakeover = true)
longLivedTransitions[cookie] = Pair(launchRemoteTransition, returnRemoteTransition)
}
@@ -738,14 +770,154 @@
}
}
+ /** [Runner] wrapper that supports animation takeovers. */
+ private inner class OriginTransition(private val runner: Runner) : IRemoteTransition {
+ private val delegate = RemoteAnimationRunnerCompat.wrap(runner)
+
+ init {
+ assertLongLivedReturnAnimations()
+ }
+
+ override fun startAnimation(
+ token: IBinder?,
+ info: TransitionInfo?,
+ t: SurfaceControl.Transaction?,
+ finishCallback: IRemoteTransitionFinishedCallback?,
+ ) {
+ delegate.startAnimation(token, info, t, finishCallback)
+ }
+
+ override fun mergeAnimation(
+ transition: IBinder?,
+ info: TransitionInfo?,
+ t: SurfaceControl.Transaction?,
+ mergeTarget: IBinder?,
+ finishCallback: IRemoteTransitionFinishedCallback?,
+ ) {
+ delegate.mergeAnimation(transition, info, t, mergeTarget, finishCallback)
+ }
+
+ override fun onTransitionConsumed(transition: IBinder?, aborted: Boolean) {
+ delegate.onTransitionConsumed(transition, aborted)
+ }
+
+ override fun takeOverAnimation(
+ token: IBinder?,
+ info: TransitionInfo?,
+ t: SurfaceControl.Transaction?,
+ finishCallback: IRemoteTransitionFinishedCallback?,
+ states: Array<WindowAnimationState>,
+ ) {
+ if (info == null || t == null) {
+ Log.e(
+ TAG,
+ "Skipping the animation takeover because the required data is missing: " +
+ "info=$info, transaction=$t",
+ )
+ return
+ }
+
+ // The following code converts the contents of the given TransitionInfo into
+ // RemoteAnimationTargets. This is necessary because we must currently support both the
+ // new (Shell, remote transitions) and old (remote animations) framework to maintain
+ // functionality for all users of the library.
+ val apps = ArrayList<RemoteAnimationTarget>()
+ val filteredStates = ArrayList<WindowAnimationState>()
+ val leashMap = ArrayMap<SurfaceControl, SurfaceControl>()
+ val leafTaskFilter = TransitionUtil.LeafTaskFilter()
+
+ // About layering: we divide up the "layer space" into 2 regions (each the size of the
+ // change count). This lets us categorize things into above and below while
+ // maintaining their relative ordering.
+ val belowLayers = info.changes.size
+ val aboveLayers = info.changes.size * 2
+ for (i in info.changes.indices) {
+ val change = info.changes[i]
+ if (change == null || change.taskInfo == null) {
+ continue
+ }
+
+ val taskInfo = change.taskInfo
+
+ if (TransitionUtil.isWallpaper(change)) {
+ val target =
+ TransitionUtil.newTarget(
+ change,
+ belowLayers - i, // wallpapers go into the "below" layer space
+ info,
+ t,
+ leashMap,
+ )
+
+ // Make all the wallpapers opaque.
+ t.setAlpha(target.leash, 1f)
+ } else if (leafTaskFilter.test(change)) {
+ // Start by putting everything into the "below" layer space.
+ val target =
+ TransitionUtil.newTarget(change, belowLayers - i, info, t, leashMap)
+ apps.add(target)
+ filteredStates.add(states[i])
+
+ // Make all the apps opaque.
+ t.setAlpha(target.leash, 1f)
+
+ if (
+ TransitionUtil.isClosingType(change.mode) &&
+ taskInfo?.topActivityType != WindowConfiguration.ACTIVITY_TYPE_HOME
+ ) {
+ // Raise closing task to "above" layer so it isn't covered.
+ t.setLayer(target.leash, aboveLayers - i)
+ }
+ } else if (TransitionInfo.isIndependent(change, info)) {
+ // Root tasks
+ if (TransitionUtil.isClosingType(change.mode)) {
+ // Raise closing task to "above" layer so it isn't covered.
+ t.setLayer(change.leash, aboveLayers - i)
+ } else if (TransitionUtil.isOpeningType(change.mode)) {
+ // Put into the "below" layer space.
+ t.setLayer(change.leash, belowLayers - i)
+ }
+ } else if (TransitionUtil.isDividerBar(change)) {
+ val target =
+ TransitionUtil.newTarget(change, belowLayers - i, info, t, leashMap)
+ apps.add(target)
+ filteredStates.add(states[i])
+ }
+ }
+
+ val wrappedCallback: IRemoteAnimationFinishedCallback =
+ object : IRemoteAnimationFinishedCallback.Stub() {
+ override fun onAnimationFinished() {
+ leashMap.clear()
+ val finishTransaction = SurfaceControl.Transaction()
+ finishCallback?.onTransitionFinished(null, finishTransaction)
+ finishTransaction.close()
+ }
+ }
+
+ runner.takeOverAnimation(
+ apps.toTypedArray(),
+ filteredStates.toTypedArray(),
+ t,
+ wrappedCallback,
+ )
+ }
+
+ override fun asBinder(): IBinder {
+ return delegate.asBinder()
+ }
+ }
+
@VisibleForTesting
inner class Runner(
- controller: Controller,
- callback: Callback,
+ private val controller: Controller,
+ private val callback: Callback,
/** The animator to use to animate the window transition. */
- transitionAnimator: TransitionAnimator,
+ private val transitionAnimator: TransitionAnimator,
/** Listener for animation lifecycle events. */
- listener: Listener? = null,
+ private val listener: Listener? = null,
+ /** Whether the internal [delegate] should be initialized lazily. */
+ private val initializeLazily: Boolean = false,
) : IRemoteAnimationRunner.Stub() {
// This is being passed across IPC boundaries and cycles (through PendingIntentRecords,
// etc.) are possible. So we need to make sure we drop any references that might
@@ -753,15 +925,14 @@
@VisibleForTesting var delegate: AnimationDelegate?
init {
- delegate =
- AnimationDelegate(
- mainExecutor,
- controller,
- callback,
- DelegatingAnimationCompletionListener(listener, this::dispose),
- transitionAnimator,
- disableWmTimeout,
- )
+ delegate = null
+ if (!initializeLazily) {
+ // Ephemeral launches bundle the runner with the launch request (instead of being
+ // registered ahead of time for later use). This means that there could be a timeout
+ // between creation and invocation, so the delegate needs to exist from the
+ // beginning in order to handle such timeout.
+ createDelegate()
+ }
}
@BinderThread
@@ -772,6 +943,36 @@
nonApps: Array<out RemoteAnimationTarget>?,
finishedCallback: IRemoteAnimationFinishedCallback?,
) {
+ initAndRun(finishedCallback) { delegate ->
+ delegate.onAnimationStart(transit, apps, wallpapers, nonApps, finishedCallback)
+ }
+ }
+
+ @VisibleForTesting
+ @BinderThread
+ fun takeOverAnimation(
+ apps: Array<RemoteAnimationTarget>?,
+ windowAnimationStates: Array<WindowAnimationState>,
+ startTransaction: SurfaceControl.Transaction,
+ finishedCallback: IRemoteAnimationFinishedCallback?,
+ ) {
+ assertLongLivedReturnAnimations()
+ initAndRun(finishedCallback) { delegate ->
+ delegate.takeOverAnimation(
+ apps,
+ windowAnimationStates,
+ startTransaction,
+ finishedCallback,
+ )
+ }
+ }
+
+ @BinderThread
+ private fun initAndRun(
+ finishedCallback: IRemoteAnimationFinishedCallback?,
+ performAnimation: (AnimationDelegate) -> Unit,
+ ) {
+ maybeSetUp()
val delegate = delegate
mainExecutor.execute {
if (delegate == null) {
@@ -780,7 +981,7 @@
// signal back that we're done with it.
finishedCallback?.onAnimationFinished()
} else {
- delegate.onAnimationStart(transit, apps, wallpapers, nonApps, finishedCallback)
+ performAnimation(delegate)
}
}
}
@@ -794,6 +995,32 @@
}
}
+ @VisibleForTesting
+ @UiThread
+ fun postTimeouts() {
+ maybeSetUp()
+ delegate?.postTimeouts()
+ }
+
+ @AnyThread
+ private fun maybeSetUp() {
+ if (!initializeLazily || delegate != null) return
+ createDelegate()
+ }
+
+ @AnyThread
+ private fun createDelegate() {
+ delegate =
+ AnimationDelegate(
+ mainExecutor,
+ controller,
+ callback,
+ DelegatingAnimationCompletionListener(listener, this::dispose),
+ transitionAnimator,
+ disableWmTimeout,
+ )
+ }
+
@AnyThread
fun dispose() {
// Drop references to animation controller once we're done with the animation
@@ -867,7 +1094,7 @@
init {
// We do this check here to cover all entry points, including Launcher which doesn't
// call startIntentWithAnimation()
- if (!controller.isLaunching) TransitionAnimator.checkReturnAnimationFrameworkFlag()
+ if (!controller.isLaunching) assertReturnAnimations()
}
@UiThread
@@ -893,19 +1120,73 @@
nonApps: Array<out RemoteAnimationTarget>?,
callback: IRemoteAnimationFinishedCallback?,
) {
+ val window = setUpAnimation(apps, callback) ?: return
+
+ if (controller.windowAnimatorState == null || !longLivedReturnAnimationsEnabled()) {
+ val navigationBar =
+ nonApps?.firstOrNull {
+ it.windowType == WindowManager.LayoutParams.TYPE_NAVIGATION_BAR
+ }
+
+ startAnimation(window, navigationBar, iCallback = callback)
+ } else {
+ // If a [controller.windowAnimatorState] exists, treat this like a takeover.
+ takeOverAnimationInternal(
+ window,
+ startWindowStates = null,
+ startTransaction = null,
+ callback,
+ )
+ }
+ }
+
+ @UiThread
+ internal fun takeOverAnimation(
+ apps: Array<out RemoteAnimationTarget>?,
+ startWindowStates: Array<WindowAnimationState>,
+ startTransaction: SurfaceControl.Transaction,
+ callback: IRemoteAnimationFinishedCallback?,
+ ) {
+ val window = setUpAnimation(apps, callback) ?: return
+ takeOverAnimationInternal(window, startWindowStates, startTransaction, callback)
+ }
+
+ private fun takeOverAnimationInternal(
+ window: RemoteAnimationTarget,
+ startWindowStates: Array<WindowAnimationState>?,
+ startTransaction: SurfaceControl.Transaction?,
+ callback: IRemoteAnimationFinishedCallback?,
+ ) {
+ val useSpring =
+ !controller.isLaunching && startWindowStates != null && startTransaction != null
+ startAnimation(
+ window,
+ navigationBar = null,
+ useSpring,
+ startWindowStates,
+ startTransaction,
+ callback,
+ )
+ }
+
+ @UiThread
+ private fun setUpAnimation(
+ apps: Array<out RemoteAnimationTarget>?,
+ callback: IRemoteAnimationFinishedCallback?,
+ ): RemoteAnimationTarget? {
removeTimeouts()
// The animation was started too late and we already notified the controller that it
// timed out.
if (timedOut) {
callback?.invoke()
- return
+ return null
}
// This should not happen, but let's make sure we don't start the animation if it was
// cancelled before and we already notified the controller.
if (cancelled) {
- return
+ return null
}
val window = findTargetWindowIfPossible(apps)
@@ -921,15 +1202,10 @@
}
controller.onTransitionAnimationCancelled()
listener?.onTransitionAnimationCancelled()
- return
+ return null
}
- val navigationBar =
- nonApps?.firstOrNull {
- it.windowType == WindowManager.LayoutParams.TYPE_NAVIGATION_BAR
- }
-
- startAnimation(window, navigationBar, callback)
+ return window
}
private fun findTargetWindowIfPossible(
@@ -950,7 +1226,7 @@
for (it in apps) {
if (it.mode == targetMode) {
if (activityTransitionUseLargestWindow()) {
- if (returnAnimationFrameworkLibrary()) {
+ if (returnAnimationsEnabled()) {
// If the controller contains a cookie, _only_ match if either the
// candidate contains the matching cookie, or a component is also
// defined and is a match.
@@ -995,8 +1271,11 @@
private fun startAnimation(
window: RemoteAnimationTarget,
- navigationBar: RemoteAnimationTarget?,
- iCallback: IRemoteAnimationFinishedCallback?,
+ navigationBar: RemoteAnimationTarget? = null,
+ useSpring: Boolean = false,
+ startingWindowStates: Array<WindowAnimationState>? = null,
+ startTransaction: SurfaceControl.Transaction? = null,
+ iCallback: IRemoteAnimationFinishedCallback? = null,
) {
if (TransitionAnimator.DEBUG) {
Log.d(TAG, "Remote animation started")
@@ -1046,18 +1325,66 @@
val controller =
object : Controller by delegate {
override fun createAnimatorState(): TransitionAnimator.State {
- if (isLaunching) return delegate.createAnimatorState()
- return delegate.windowAnimatorState?.toTransitionState()
- ?: getWindowRadius(isExpandingFullyAbove).let {
- TransitionAnimator.State(
- top = windowBounds.top,
- bottom = windowBounds.bottom,
- left = windowBounds.left,
- right = windowBounds.right,
- topCornerRadius = it,
- bottomCornerRadius = it,
- )
+ if (isLaunching) {
+ return delegate.createAnimatorState()
+ } else if (!longLivedReturnAnimationsEnabled()) {
+ return delegate.windowAnimatorState?.toTransitionState()
+ ?: getWindowRadius(isExpandingFullyAbove).let {
+ TransitionAnimator.State(
+ top = windowBounds.top,
+ bottom = windowBounds.bottom,
+ left = windowBounds.left,
+ right = windowBounds.right,
+ topCornerRadius = it,
+ bottomCornerRadius = it,
+ )
+ }
+ }
+
+ // The states are sorted matching the changes inside the transition info.
+ // Using this info, the RemoteAnimationTargets are created, with their
+ // prefixOrderIndex fields in reverse order to that of changes. To extract
+ // the right state, we need to invert again.
+ val windowState =
+ if (startingWindowStates != null) {
+ startingWindowStates[
+ startingWindowStates.size - window.prefixOrderIndex]
+ } else {
+ controller.windowAnimatorState
}
+
+ // TODO(b/323863002): use the timestamp and velocity to update the initial
+ // position.
+ val bounds = windowState?.bounds
+ val left: Int = bounds?.left?.toInt() ?: windowBounds.left
+ val top: Int = bounds?.top?.toInt() ?: windowBounds.top
+ val right: Int = bounds?.right?.toInt() ?: windowBounds.right
+ val bottom: Int = bounds?.bottom?.toInt() ?: windowBounds.bottom
+
+ val width = windowBounds.right - windowBounds.left
+ val height = windowBounds.bottom - windowBounds.top
+ // Scale the window. We use the max of (widthRatio, heightRatio) so that
+ // there is no blank space on any side.
+ val widthRatio = (right - left).toFloat() / width
+ val heightRatio = (bottom - top).toFloat() / height
+ val startScale = maxOf(widthRatio, heightRatio)
+
+ val maybeRadius = windowState?.topLeftRadius
+ val windowRadius =
+ if (maybeRadius != null) {
+ maybeRadius * startScale
+ } else {
+ getWindowRadius(isExpandingFullyAbove)
+ }
+
+ return TransitionAnimator.State(
+ top = top,
+ bottom = bottom,
+ left = left,
+ right = right,
+ topCornerRadius = windowRadius,
+ bottomCornerRadius = windowRadius,
+ )
}
override fun onTransitionAnimationStart(isExpandingFullyAbove: Boolean) {
@@ -1071,6 +1398,19 @@
"[controller=$delegate]",
)
}
+
+ if (startTransaction != null) {
+ // Calling applyStateToWindow() here avoids skipping a frame when taking
+ // over an animation.
+ applyStateToWindow(
+ window,
+ createAnimatorState(),
+ linearProgress = 0f,
+ useSpring,
+ startTransaction,
+ )
+ }
+
delegate.onTransitionAnimationStart(isExpandingFullyAbove)
}
@@ -1094,14 +1434,29 @@
progress: Float,
linearProgress: Float,
) {
- applyStateToWindow(window, state, linearProgress)
+ applyStateToWindow(window, state, linearProgress, useSpring)
navigationBar?.let { applyStateToNavigationBar(it, state, linearProgress) }
listener?.onTransitionAnimationProgress(linearProgress)
delegate.onTransitionAnimationProgress(state, progress, linearProgress)
}
}
-
+ val windowState =
+ if (startingWindowStates != null) {
+ startingWindowStates[startingWindowStates.size - window.prefixOrderIndex]
+ } else {
+ controller.windowAnimatorState
+ }
+ val velocityPxPerS =
+ if (longLivedReturnAnimationsEnabled() && windowState?.velocityPxPerMs != null) {
+ val xVelocityPxPerS = windowState.velocityPxPerMs.x * 1000
+ val yVelocityPxPerS = windowState.velocityPxPerMs.y * 1000
+ PointF(xVelocityPxPerS, yVelocityPxPerS)
+ } else if (useSpring) {
+ PointF(0f, 0f)
+ } else {
+ null
+ }
animation =
transitionAnimator.startAnimation(
controller,
@@ -1109,6 +1464,7 @@
windowBackgroundColor,
fadeWindowBackgroundLayer = !controller.isBelowAnimatingWindow,
drawHole = !controller.isBelowAnimatingWindow,
+ startVelocity = velocityPxPerS,
)
}
@@ -1128,6 +1484,8 @@
window: RemoteAnimationTarget,
state: TransitionAnimator.State,
linearProgress: Float,
+ useSpring: Boolean,
+ transaction: SurfaceControl.Transaction? = null,
) {
if (transactionApplierView.viewRootImpl == null || !window.leash.isValid) {
// Don't apply any transaction if the view root we synchronize with was detached or
@@ -1171,25 +1529,47 @@
windowCropF.bottom.roundToInt(),
)
- val windowAnimationDelay =
+ val interpolators: TransitionAnimator.Interpolators
+ val windowProgress: Float
+
+ if (useSpring) {
+ val windowAnimationDelay: Float
+ val windowAnimationDuration: Float
if (controller.isLaunching) {
- TIMINGS.contentAfterFadeInDelay
+ windowAnimationDelay = SPRING_TIMINGS.contentAfterFadeInDelay
+ windowAnimationDuration = SPRING_TIMINGS.contentAfterFadeInDuration
} else {
- TIMINGS.contentBeforeFadeOutDelay
+ windowAnimationDelay = SPRING_TIMINGS.contentBeforeFadeOutDelay
+ windowAnimationDuration = SPRING_TIMINGS.contentBeforeFadeOutDuration
}
- val windowAnimationDuration =
+
+ interpolators = SPRING_INTERPOLATORS
+ windowProgress =
+ TransitionAnimator.getProgress(
+ linearProgress,
+ windowAnimationDelay,
+ windowAnimationDuration,
+ )
+ } else {
+ val windowAnimationDelay: Long
+ val windowAnimationDuration: Long
if (controller.isLaunching) {
- TIMINGS.contentAfterFadeInDuration
+ windowAnimationDelay = TIMINGS.contentAfterFadeInDelay
+ windowAnimationDuration = TIMINGS.contentAfterFadeInDuration
} else {
- TIMINGS.contentBeforeFadeOutDuration
+ windowAnimationDelay = TIMINGS.contentBeforeFadeOutDelay
+ windowAnimationDuration = TIMINGS.contentBeforeFadeOutDuration
}
- val windowProgress =
- TransitionAnimator.getProgress(
- TIMINGS,
- linearProgress,
- windowAnimationDelay,
- windowAnimationDuration,
- )
+
+ interpolators = INTERPOLATORS
+ windowProgress =
+ TransitionAnimator.getProgress(
+ TIMINGS,
+ linearProgress,
+ windowAnimationDelay,
+ windowAnimationDuration,
+ )
+ }
// The alpha of the opening window. If it opens above the expandable, then it should
// fade in progressively. Otherwise, it should be fully opaque and will be progressively
@@ -1197,12 +1577,12 @@
val alpha =
if (controller.isBelowAnimatingWindow) {
if (controller.isLaunching) {
- INTERPOLATORS.contentAfterFadeInInterpolator.getInterpolation(
+ interpolators.contentAfterFadeInInterpolator.getInterpolation(
windowProgress
)
} else {
1 -
- INTERPOLATORS.contentBeforeFadeOutInterpolator.getInterpolation(
+ interpolators.contentBeforeFadeOutInterpolator.getInterpolation(
windowProgress
)
}
@@ -1216,6 +1596,7 @@
// especially important for lock screen animations, where the window is not clipped by
// the shade.
val cornerRadius = maxOf(state.topCornerRadius, state.bottomCornerRadius) / scale
+
val params =
SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(window.leash)
.withAlpha(alpha)
@@ -1223,11 +1604,15 @@
.withWindowCrop(windowCrop)
.withCornerRadius(cornerRadius)
.withVisibility(true)
- .build()
+ if (transaction != null) params.withMergeTransaction(transaction)
- transactionApplier.scheduleApply(params)
+ transactionApplier.scheduleApply(params.build())
}
+ // TODO(b/377643129): remote transitions have no way of identifying the navbar when
+ // converting to RemoteAnimationTargets (and in my testing it was never included in the
+ // transition at all). So this method is not used anymore. Remove or adapt once we fully
+ // convert to remote transitions.
private fun applyStateToNavigationBar(
navigationBar: RemoteAnimationTarget,
state: TransitionAnimator.State,
@@ -1362,9 +1747,17 @@
}
/** Register [remoteTransition] with WM Shell using the given [filter]. */
- internal fun register(filter: TransitionFilter, remoteTransition: RemoteTransition) {
+ internal fun register(
+ filter: TransitionFilter,
+ remoteTransition: RemoteTransition,
+ includeTakeover: Boolean,
+ ) {
shellTransitions?.registerRemote(filter, remoteTransition)
iShellTransitions?.registerRemote(filter, remoteTransition)
+ if (includeTakeover) {
+ shellTransitions?.registerRemoteForTakeover(filter, remoteTransition)
+ iShellTransitions?.registerRemoteForTakeover(filter, remoteTransition)
+ }
}
/** Unregister [remoteTransition] from WM Shell. */
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/TransitionAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/TransitionAnimator.kt
index fdb4871..de4bdbc 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/TransitionAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/TransitionAnimator.kt
@@ -38,6 +38,7 @@
import com.android.internal.dynamicanimation.animation.SpringAnimation
import com.android.internal.dynamicanimation.animation.SpringForce
import com.android.systemui.shared.Flags.returnAnimationFrameworkLibrary
+import com.android.systemui.shared.Flags.returnAnimationFrameworkLongLived
import java.util.concurrent.Executor
import kotlin.math.abs
import kotlin.math.max
@@ -113,13 +114,26 @@
)
}
- internal fun checkReturnAnimationFrameworkFlag() {
- check(returnAnimationFrameworkLibrary()) {
- "isLaunching cannot be false when the returnAnimationFrameworkLibrary flag is " +
- "disabled"
+ internal fun assertReturnAnimations() {
+ check(returnAnimationsEnabled()) {
+ "isLaunching cannot be false when the returnAnimationFrameworkLibrary flag " +
+ "is disabled"
}
}
+ internal fun returnAnimationsEnabled() = returnAnimationFrameworkLibrary()
+
+ internal fun assertLongLivedReturnAnimations() {
+ check(longLivedReturnAnimationsEnabled()) {
+ "Long-lived registrations cannot be used when the " +
+ "returnAnimationFrameworkLibrary or the " +
+ "returnAnimationFrameworkLongLived flag are disabled"
+ }
+ }
+
+ internal fun longLivedReturnAnimationsEnabled() =
+ returnAnimationFrameworkLibrary() && returnAnimationFrameworkLongLived()
+
internal fun WindowAnimationState.toTransitionState() =
State().also {
bounds?.let { b ->
@@ -467,7 +481,8 @@
drawHole: Boolean = false,
startVelocity: PointF? = null,
): Animation {
- if (!controller.isLaunching || startVelocity != null) checkReturnAnimationFrameworkFlag()
+ if (!controller.isLaunching) assertReturnAnimations()
+ if (startVelocity != null) assertLongLivedReturnAnimations()
// We add an extra layer with the same color as the dialog/app splash screen background
// color, which is usually the same color of the app background. We first fade in this layer
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContent.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContent.kt
index 96e99b1..778d7e7 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContent.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContent.kt
@@ -67,6 +67,7 @@
dialogFactory = dialogFactory,
widgetSection = widgetSection,
modifier = Modifier.element(Communal.Elements.Grid),
+ sceneScope = this@Content,
)
}
with(lockSection) {
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
index df1185c..5b1203f 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
@@ -163,6 +163,7 @@
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.window.layout.WindowMetricsCalculator
import com.android.compose.animation.Easings.Emphasized
+import com.android.compose.animation.scene.SceneScope
import com.android.compose.modifiers.thenIf
import com.android.compose.ui.graphics.painter.rememberDrawablePainter
import com.android.internal.R.dimen.system_app_widget_background_radius
@@ -186,7 +187,9 @@
import com.android.systemui.communal.widgets.SmartspaceAppWidgetHostView
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.lifecycle.rememberViewModel
+import com.android.systemui.media.controls.ui.composable.MediaCarousel
import com.android.systemui.res.R
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.statusbar.phone.SystemUIDialogFactory
import kotlin.math.max
import kotlin.math.min
@@ -205,6 +208,7 @@
widgetConfigurator: WidgetConfigurator? = null,
onOpenWidgetPicker: (() -> Unit)? = null,
onEditDone: (() -> Unit)? = null,
+ sceneScope: SceneScope? = null,
) {
val communalContent by
viewModel.communalContent.collectAsStateWithLifecycle(initialValue = emptyList())
@@ -414,6 +418,7 @@
widgetConfigurator = widgetConfigurator,
interactionHandler = interactionHandler,
widgetSection = widgetSection,
+ sceneScope = sceneScope,
)
}
}
@@ -735,6 +740,7 @@
widgetConfigurator: WidgetConfigurator?,
interactionHandler: RemoteViews.InteractionHandler?,
widgetSection: CommunalAppWidgetSection,
+ sceneScope: SceneScope?,
) {
var gridModifier =
Modifier.align(Alignment.TopStart).onGloballyPositioned { setGridCoordinates(it) }
@@ -871,6 +877,7 @@
interactionHandler = interactionHandler,
widgetSection = widgetSection,
resizeableItemFrameViewModel = resizeableItemFrameViewModel,
+ sceneScope = sceneScope,
)
}
}
@@ -1095,6 +1102,7 @@
interactionHandler: RemoteViews.InteractionHandler?,
widgetSection: CommunalAppWidgetSection,
resizeableItemFrameViewModel: ResizeableItemFrameViewModel,
+ sceneScope: SceneScope? = null,
) {
when (model) {
is CommunalContentModel.WidgetContent.Widget ->
@@ -1118,7 +1126,7 @@
is CommunalContentModel.CtaTileInViewMode -> CtaTileInViewModeContent(viewModel, modifier)
is CommunalContentModel.Smartspace -> SmartspaceContent(interactionHandler, model, modifier)
is CommunalContentModel.Tutorial -> TutorialContent(modifier)
- is CommunalContentModel.Umo -> Umo(viewModel, modifier)
+ is CommunalContentModel.Umo -> Umo(viewModel, sceneScope, modifier)
}
}
@@ -1529,7 +1537,25 @@
}
@Composable
-private fun Umo(viewModel: BaseCommunalViewModel, modifier: Modifier = Modifier) {
+private fun Umo(
+ viewModel: BaseCommunalViewModel,
+ sceneScope: SceneScope?,
+ modifier: Modifier = Modifier,
+) {
+ if (SceneContainerFlag.isEnabled && sceneScope != null) {
+ sceneScope.MediaCarousel(
+ modifier = modifier.fillMaxSize(),
+ isVisible = true,
+ mediaHost = viewModel.mediaHost,
+ carouselController = viewModel.mediaCarouselController,
+ )
+ } else {
+ UmoLegacy(viewModel, modifier)
+ }
+}
+
+@Composable
+private fun UmoLegacy(viewModel: BaseCommunalViewModel, modifier: Modifier = Modifier) {
AndroidView(
modifier =
modifier.pointerInput(Unit) {
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToSplitShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToSplitShadeTransition.kt
index 71fa6c9..ce7a85b1 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToSplitShadeTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToSplitShadeTransition.kt
@@ -19,11 +19,8 @@
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
-import androidx.compose.foundation.gestures.Orientation
-import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.TransitionBuilder
import com.android.compose.animation.scene.UserActionDistance
-import com.android.compose.animation.scene.UserActionDistanceScope
import com.android.systemui.media.controls.ui.composable.MediaCarousel
import com.android.systemui.notifications.ui.composable.Notifications
import com.android.systemui.qs.ui.composable.QuickSettings
@@ -31,24 +28,17 @@
import com.android.systemui.shade.ui.composable.ShadeHeader
import kotlin.time.Duration.Companion.milliseconds
-fun TransitionBuilder.goneToSplitShadeTransition(
- durationScale: Double = 1.0,
-) {
+fun TransitionBuilder.goneToSplitShadeTransition(durationScale: Double = 1.0) {
spec = tween(durationMillis = (DefaultDuration * durationScale).inWholeMilliseconds.toInt())
swipeSpec =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = Shade.Dimensions.ScrimVisibilityThreshold,
)
- distance =
- object : UserActionDistance {
- override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
- orientation: Orientation,
- ): Float {
- return fromSceneSize.height.toFloat() * 2 / 3f
- }
- }
+ distance = UserActionDistance { fromContent, _, _ ->
+ val fromContentSize = checkNotNull(fromContent.targetSize())
+ fromContentSize.height.toFloat() * 2 / 3f
+ }
fractionRange(end = .33f) { fade(Shade.Elements.BackgroundScrim) }
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToSplitShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToSplitShadeTransition.kt
index 1486ea7..1f7a738 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToSplitShadeTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToSplitShadeTransition.kt
@@ -19,35 +19,25 @@
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
-import androidx.compose.foundation.gestures.Orientation
-import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.TransitionBuilder
import com.android.compose.animation.scene.UserActionDistance
-import com.android.compose.animation.scene.UserActionDistanceScope
import com.android.systemui.notifications.ui.composable.Notifications
import com.android.systemui.qs.ui.composable.QuickSettings
import com.android.systemui.shade.ui.composable.Shade
import com.android.systemui.shade.ui.composable.ShadeHeader
import kotlin.time.Duration.Companion.milliseconds
-fun TransitionBuilder.lockscreenToSplitShadeTransition(
- durationScale: Double = 1.0,
-) {
+fun TransitionBuilder.lockscreenToSplitShadeTransition(durationScale: Double = 1.0) {
spec = tween(durationMillis = (DefaultDuration * durationScale).inWholeMilliseconds.toInt())
swipeSpec =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = Shade.Dimensions.ScrimVisibilityThreshold,
)
- distance =
- object : UserActionDistance {
- override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
- orientation: Orientation,
- ): Float {
- return fromSceneSize.height.toFloat() * 2 / 3f
- }
- }
+ distance = UserActionDistance { fromContent, _, _ ->
+ val fromContentSize = checkNotNull(fromContent.targetSize())
+ fromContentSize.height.toFloat() * 2 / 3f
+ }
fractionRange(end = .33f) { fade(Shade.Elements.BackgroundScrim) }
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt
index 8cd357e..ba1972f 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt
@@ -1,46 +1,36 @@
package com.android.systemui.scene.ui.composable.transitions
import androidx.compose.animation.core.tween
-import androidx.compose.foundation.gestures.Orientation
-import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.Edge
import com.android.compose.animation.scene.TransitionBuilder
import com.android.compose.animation.scene.UserActionDistance
-import com.android.compose.animation.scene.UserActionDistanceScope
import com.android.systemui.notifications.ui.composable.Notifications
import com.android.systemui.qs.ui.composable.QuickSettings
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.ui.composable.ShadeHeader
import kotlin.time.Duration.Companion.milliseconds
-fun TransitionBuilder.shadeToQuickSettingsTransition(
- durationScale: Double = 1.0,
-) {
+fun TransitionBuilder.shadeToQuickSettingsTransition(durationScale: Double = 1.0) {
spec = tween(durationMillis = (DefaultDuration * durationScale).inWholeMilliseconds.toInt())
- distance =
- object : UserActionDistance {
- override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
- orientation: Orientation,
- ): Float {
- val distance =
- Notifications.Elements.NotificationScrim.targetOffset(Scenes.Shade)?.y
- ?: return 0f
- return fromSceneSize.height - distance
- }
- }
+ distance = UserActionDistance { fromContent, _, _ ->
+ val distance =
+ Notifications.Elements.NotificationScrim.targetOffset(Scenes.Shade)?.y
+ ?: return@UserActionDistance 0f
+ val fromContentSize = checkNotNull(fromContent.targetSize())
+ fromContentSize.height - distance
+ }
translate(Notifications.Elements.NotificationScrim, Edge.Bottom)
timestampRange(endMillis = 83) { fade(QuickSettings.Elements.FooterActions) }
translate(
ShadeHeader.Elements.CollapsedContentStart,
- y = ShadeHeader.Dimensions.CollapsedHeight
+ y = ShadeHeader.Dimensions.CollapsedHeight,
)
translate(ShadeHeader.Elements.CollapsedContentEnd, y = ShadeHeader.Dimensions.CollapsedHeight)
translate(
ShadeHeader.Elements.ExpandedContent,
- y = -(ShadeHeader.Dimensions.ExpandedHeight - ShadeHeader.Dimensions.CollapsedHeight)
+ y = -(ShadeHeader.Dimensions.ExpandedHeight - ShadeHeader.Dimensions.CollapsedHeight),
)
translate(ShadeHeader.Elements.ShadeCarrierGroup, y = -ShadeHeader.Dimensions.CollapsedHeight)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToBouncerTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToBouncerTransition.kt
index de76f70..d35537a 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToBouncerTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToBouncerTransition.kt
@@ -28,8 +28,9 @@
fun TransitionBuilder.toBouncerTransition() {
spec = tween(durationMillis = 500)
- distance = UserActionDistance { fromSceneSize, _ ->
- fromSceneSize.height * TO_BOUNCER_SWIPE_DISTANCE_FRACTION
+ distance = UserActionDistance { fromContent, _, _ ->
+ val fromContentSize = checkNotNull(fromContent.targetSize())
+ fromContentSize.height * TO_BOUNCER_SWIPE_DISTANCE_FRACTION
}
translate(Bouncer.Elements.Content, y = 300.dp)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToQuickSettingsShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToQuickSettingsShadeTransition.kt
index 55fa6ad..e78bc6a 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToQuickSettingsShadeTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToQuickSettingsShadeTransition.kt
@@ -33,7 +33,10 @@
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = Shade.Dimensions.ScrimVisibilityThreshold,
)
- distance = UserActionDistance { fromSceneSize, _ -> fromSceneSize.height.toFloat() * 2 / 3f }
+ distance = UserActionDistance { fromContent, _, _ ->
+ val fromContentSize = checkNotNull(fromContent.targetSize())
+ fromContentSize.height.toFloat() * 2 / 3f
+ }
translate(OverlayShade.Elements.Panel, Edge.Top)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToShadeTransition.kt
index b677dff..bfae489 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToShadeTransition.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/ToShadeTransition.kt
@@ -19,12 +19,9 @@
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
-import androidx.compose.foundation.gestures.Orientation
-import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.Edge
import com.android.compose.animation.scene.TransitionBuilder
import com.android.compose.animation.scene.UserActionDistance
-import com.android.compose.animation.scene.UserActionDistanceScope
import com.android.systemui.media.controls.ui.composable.MediaCarousel
import com.android.systemui.notifications.ui.composable.Notifications
import com.android.systemui.qs.ui.composable.QuickSettings
@@ -33,24 +30,16 @@
import com.android.systemui.shade.ui.composable.ShadeHeader
import kotlin.time.Duration.Companion.milliseconds
-fun TransitionBuilder.toShadeTransition(
- durationScale: Double = 1.0,
-) {
+fun TransitionBuilder.toShadeTransition(durationScale: Double = 1.0) {
spec = tween(durationMillis = (DefaultDuration * durationScale).inWholeMilliseconds.toInt())
swipeSpec =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = Shade.Dimensions.ScrimVisibilityThreshold,
)
- distance =
- object : UserActionDistance {
- override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
- orientation: Orientation,
- ): Float {
- return Notifications.Elements.NotificationScrim.targetOffset(Scenes.Shade)?.y ?: 0f
- }
- }
+ distance = UserActionDistance { _, _, _ ->
+ Notifications.Elements.NotificationScrim.targetOffset(Scenes.Shade)?.y ?: 0f
+ }
fractionRange(start = .58f) {
fade(ShadeHeader.Elements.Clock)
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayout.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayout.kt
index dbf7d7b..d3ddb50 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayout.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayout.kt
@@ -637,8 +637,8 @@
fun interface UserActionDistance {
/**
- * Return the **absolute** distance of the user action given the size of the scene we are
- * animating from and the [orientation].
+ * Return the **absolute** distance of the user action when going from [fromContent] to
+ * [toContent] in the given [orientation].
*
* Note: This function will be called for each drag event until it returns a value > 0f. This
* for instance allows you to return 0f or a negative value until the first layout pass of a
@@ -646,7 +646,8 @@
* transitioning to when computing this absolute distance.
*/
fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
+ fromContent: ContentKey,
+ toContent: ContentKey,
orientation: Orientation,
): Float
}
@@ -656,7 +657,8 @@
/** The user action has a fixed [absoluteDistance]. */
class FixedDistance(private val distance: Dp) : UserActionDistance {
override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
+ fromContent: ContentKey,
+ toContent: ContentKey,
orientation: Orientation,
): Float = distance.toPx()
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutState.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutState.kt
index 7eb5a3f..3bf2ed5 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutState.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutState.kt
@@ -267,11 +267,12 @@
private set
/**
- * The flattened list of [SharedElementTransformation] within all the transitions in
+ * The flattened list of [SharedElementTransformation.Factory] within all the transitions in
* [transitionStates].
*/
- private val transformationsWithElevation: List<SharedElementTransformation> by derivedStateOf {
- transformationsWithElevation(transitionStates)
+ private val transformationFactoriesWithElevation:
+ List<SharedElementTransformation.Factory> by derivedStateOf {
+ transformationFactoriesWithElevation(transitionStates)
}
override val currentScene: SceneKey
@@ -355,6 +356,12 @@
override suspend fun startTransition(transition: TransitionState.Transition, chain: Boolean) {
checkThread()
+ // Prepare the transition before starting it. This is outside of the try/finally block on
+ // purpose because preparing a transition might throw an exception (e.g. if we find multiple
+ // specs matching this transition), in which case we want to throw that exception here
+ // before even starting the transition.
+ prepareTransitionBeforeStarting(transition)
+
try {
// Start the transition.
startTransitionInternal(transition, chain)
@@ -366,7 +373,7 @@
}
}
- private fun startTransitionInternal(transition: TransitionState.Transition, chain: Boolean) {
+ private fun prepareTransitionBeforeStarting(transition: TransitionState.Transition) {
// Set the current scene and overlays on the transition.
val currentState = transitionState
transition.currentSceneWhenTransitionStarted = currentState.currentScene
@@ -394,7 +401,9 @@
} else {
transition.updateOverscrollSpecs(fromSpec = null, toSpec = null)
}
+ }
+ private fun startTransitionInternal(transition: TransitionState.Transition, chain: Boolean) {
when (val currentState = transitionStates.last()) {
is TransitionState.Idle -> {
// Replace [Idle] by [transition].
@@ -692,22 +701,23 @@
animate()
}
- private fun transformationsWithElevation(
+ private fun transformationFactoriesWithElevation(
transitionStates: List<TransitionState>
- ): List<SharedElementTransformation> {
+ ): List<SharedElementTransformation.Factory> {
return buildList {
transitionStates.fastForEach { state ->
if (state !is TransitionState.Transition) {
return@fastForEach
}
- state.transformationSpec.transformations.fastForEach { transformationWithRange ->
- val transformation = transformationWithRange.transformation
+ state.transformationSpec.transformationMatchers.fastForEach { transformationMatcher
+ ->
+ val factory = transformationMatcher.factory
if (
- transformation is SharedElementTransformation &&
- transformation.elevateInContent != null
+ factory is SharedElementTransformation.Factory &&
+ factory.elevateInContent != null
) {
- add(transformation)
+ add(factory)
}
}
}
@@ -722,10 +732,10 @@
* necessary, for performance.
*/
internal fun isElevationPossible(content: ContentKey, element: ElementKey?): Boolean {
- if (transformationsWithElevation.isEmpty()) return false
- return transformationsWithElevation.fastAny { transformation ->
- transformation.elevateInContent == content &&
- (element == null || transformation.matcher.matches(element, content))
+ if (transformationFactoriesWithElevation.isEmpty()) return false
+ return transformationFactoriesWithElevation.fastAny { factory ->
+ factory.elevateInContent == content &&
+ (element == null || factory.matcher.matches(element, content))
}
}
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitions.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitions.kt
index 569593c..8df3f2d 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitions.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitions.kt
@@ -26,17 +26,9 @@
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.util.fastForEach
import com.android.compose.animation.scene.content.state.TransitionState
-import com.android.compose.animation.scene.transformation.CustomAlphaTransformation
-import com.android.compose.animation.scene.transformation.CustomOffsetTransformation
-import com.android.compose.animation.scene.transformation.CustomScaleTransformation
-import com.android.compose.animation.scene.transformation.CustomSizeTransformation
-import com.android.compose.animation.scene.transformation.InterpolatedAlphaTransformation
-import com.android.compose.animation.scene.transformation.InterpolatedOffsetTransformation
-import com.android.compose.animation.scene.transformation.InterpolatedScaleTransformation
-import com.android.compose.animation.scene.transformation.InterpolatedSizeTransformation
import com.android.compose.animation.scene.transformation.PropertyTransformation
import com.android.compose.animation.scene.transformation.SharedElementTransformation
-import com.android.compose.animation.scene.transformation.Transformation
+import com.android.compose.animation.scene.transformation.TransformationMatcher
import com.android.compose.animation.scene.transformation.TransformationWithRange
/** The transitions configuration of a [SceneTransitionLayout]. */
@@ -169,7 +161,7 @@
}
/** The definition of a transition between [from] and [to]. */
-interface TransitionSpec {
+internal interface TransitionSpec {
/** The key of this [TransitionSpec]. */
val key: TransitionKey?
@@ -209,7 +201,7 @@
fun previewTransformationSpec(transition: TransitionState.Transition): TransformationSpec?
}
-interface TransformationSpec {
+internal interface TransformationSpec {
/**
* The [AnimationSpec] used to animate the associated transition progress from `0` to `1` when
* the transition is triggered (i.e. it is not gesture-based).
@@ -232,8 +224,8 @@
*/
val distance: UserActionDistance?
- /** The list of [Transformation] applied to elements during this transition. */
- val transformations: List<TransformationWithRange<*>>
+ /** The list of [TransformationMatcher] applied to elements during this transformation. */
+ val transformationMatchers: List<TransformationMatcher>
companion object {
internal val Empty =
@@ -241,7 +233,7 @@
progressSpec = snap(),
swipeSpec = null,
distance = null,
- transformations = emptyList(),
+ transformationMatchers = emptyList(),
)
internal val EmptyProvider = { _: TransitionState.Transition -> Empty }
}
@@ -272,7 +264,14 @@
progressSpec = reverse.progressSpec,
swipeSpec = reverse.swipeSpec,
distance = reverse.distance,
- transformations = reverse.transformations.map { it.reversed() },
+ transformationMatchers =
+ reverse.transformationMatchers.map {
+ TransformationMatcher(
+ matcher = it.matcher,
+ factory = it.factory,
+ range = it.range?.reversed(),
+ )
+ },
)
},
)
@@ -288,7 +287,7 @@
}
/** The definition of the overscroll behavior of the [content]. */
-interface OverscrollSpec {
+internal interface OverscrollSpec {
/** The scene we are over scrolling. */
val content: ContentKey
@@ -325,7 +324,7 @@
override val progressSpec: AnimationSpec<Float>,
override val swipeSpec: SpringSpec<Float>?,
override val distance: UserActionDistance?,
- override val transformations: List<TransformationWithRange<*>>,
+ override val transformationMatchers: List<TransformationMatcher>,
) : TransformationSpec {
private val cache = mutableMapOf<ElementKey, MutableMap<ContentKey, ElementTransformations>>()
@@ -335,7 +334,7 @@
.getOrPut(content) { computeTransformations(element, content) }
}
- /** Filter [transformations] to compute the [ElementTransformations] of [element]. */
+ /** Filter [transformationMatchers] to compute the [ElementTransformations] of [element]. */
private fun computeTransformations(
element: ElementKey,
content: ContentKey,
@@ -346,46 +345,55 @@
var drawScale: TransformationWithRange<PropertyTransformation<Scale>>? = null
var alpha: TransformationWithRange<PropertyTransformation<Float>>? = null
- transformations.fastForEach { transformationWithRange ->
- val transformation = transformationWithRange.transformation
- if (!transformation.matcher.matches(element, content)) {
+ transformationMatchers.fastForEach { transformationMatcher ->
+ if (!transformationMatcher.matcher.matches(element, content)) {
return@fastForEach
}
- when (transformation) {
- is SharedElementTransformation -> {
- throwIfNotNull(shared, element, name = "shared")
- shared =
- transformationWithRange
- as TransformationWithRange<SharedElementTransformation>
+ val transformation = transformationMatcher.factory.create()
+ val property =
+ when (transformation) {
+ is SharedElementTransformation -> {
+ throwIfNotNull(shared, element, name = "shared")
+ shared =
+ TransformationWithRange(transformation, transformationMatcher.range)
+ return@fastForEach
+ }
+ is PropertyTransformation<*> -> transformation.property
}
- is InterpolatedOffsetTransformation,
- is CustomOffsetTransformation -> {
+
+ when (property) {
+ is PropertyTransformation.Property.Offset -> {
throwIfNotNull(offset, element, name = "offset")
offset =
- transformationWithRange
- as TransformationWithRange<PropertyTransformation<Offset>>
+ TransformationWithRange(
+ transformation as PropertyTransformation<Offset>,
+ transformationMatcher.range,
+ )
}
- is InterpolatedSizeTransformation,
- is CustomSizeTransformation -> {
+ is PropertyTransformation.Property.Size -> {
throwIfNotNull(size, element, name = "size")
size =
- transformationWithRange
- as TransformationWithRange<PropertyTransformation<IntSize>>
+ TransformationWithRange(
+ transformation as PropertyTransformation<IntSize>,
+ transformationMatcher.range,
+ )
}
- is InterpolatedScaleTransformation,
- is CustomScaleTransformation -> {
+ is PropertyTransformation.Property.Scale -> {
throwIfNotNull(drawScale, element, name = "drawScale")
drawScale =
- transformationWithRange
- as TransformationWithRange<PropertyTransformation<Scale>>
+ TransformationWithRange(
+ transformation as PropertyTransformation<Scale>,
+ transformationMatcher.range,
+ )
}
- is InterpolatedAlphaTransformation,
- is CustomAlphaTransformation -> {
+ is PropertyTransformation.Property.Alpha -> {
throwIfNotNull(alpha, element, name = "alpha")
alpha =
- transformationWithRange
- as TransformationWithRange<PropertyTransformation<Float>>
+ TransformationWithRange(
+ transformation as PropertyTransformation<Float>,
+ transformationMatcher.range,
+ )
}
}
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeAnimation.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeAnimation.kt
index f0043e1..dbfeb5c 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeAnimation.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeAnimation.kt
@@ -24,7 +24,6 @@
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
-import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.content.state.TransitionState
import com.android.compose.animation.scene.content.state.TransitionState.HasOverscrollProperties.Companion.DistanceUnspecified
import kotlin.math.absoluteValue
@@ -66,8 +65,9 @@
val absoluteDistance =
with(animation.contentTransition.transformationSpec.distance ?: DefaultSwipeDistance) {
layoutImpl.userActionDistanceScope.absoluteDistance(
- layoutImpl.content(animation.fromContent).targetSize,
- orientation,
+ fromContent = animation.fromContent,
+ toContent = animation.toContent,
+ orientation = orientation,
)
}
@@ -475,12 +475,14 @@
private object DefaultSwipeDistance : UserActionDistance {
override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
+ fromContent: ContentKey,
+ toContent: ContentKey,
orientation: Orientation,
): Float {
+ val fromContentSize = checkNotNull(fromContent.targetSize())
return when (orientation) {
- Orientation.Horizontal -> fromSceneSize.width
- Orientation.Vertical -> fromSceneSize.height
+ Orientation.Horizontal -> fromContentSize.width
+ Orientation.Vertical -> fromContentSize.height
}.toFloat()
}
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDsl.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDsl.kt
index 1fdfca9..48f08a7 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDsl.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDsl.kt
@@ -26,7 +26,7 @@
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.android.compose.animation.scene.content.state.TransitionState
-import com.android.compose.animation.scene.transformation.CustomPropertyTransformation
+import com.android.compose.animation.scene.transformation.Transformation
import kotlin.math.tanh
/** Define the [transitions][SceneTransitions] to be used with a [SceneTransitionLayout]. */
@@ -76,7 +76,7 @@
preview: (TransitionBuilder.() -> Unit)? = null,
reversePreview: (TransitionBuilder.() -> Unit)? = null,
builder: TransitionBuilder.() -> Unit = {},
- ): TransitionSpec
+ )
/**
* Define the animation to be played when transitioning [from] the specified content. For the
@@ -102,7 +102,7 @@
preview: (TransitionBuilder.() -> Unit)? = null,
reversePreview: (TransitionBuilder.() -> Unit)? = null,
builder: TransitionBuilder.() -> Unit = {},
- ): TransitionSpec
+ )
/**
* Define the animation to be played when the [content] is overscrolled in the given
@@ -115,13 +115,13 @@
content: ContentKey,
orientation: Orientation,
builder: OverscrollBuilder.() -> Unit,
- ): OverscrollSpec
+ )
/**
* Prevents overscroll the [content] in the given [orientation], allowing ancestors to
* eventually consume the remaining gesture.
*/
- fun overscrollDisabled(content: ContentKey, orientation: Orientation): OverscrollSpec
+ fun overscrollDisabled(content: ContentKey, orientation: Orientation)
}
interface BaseTransitionBuilder : PropertyTransformationBuilder {
@@ -529,15 +529,8 @@
anchorHeight: Boolean = true,
)
- /**
- * Apply a [CustomPropertyTransformation] to one or more elements.
- *
- * @see com.android.compose.animation.scene.transformation.CustomSizeTransformation
- * @see com.android.compose.animation.scene.transformation.CustomOffsetTransformation
- * @see com.android.compose.animation.scene.transformation.CustomAlphaTransformation
- * @see com.android.compose.animation.scene.transformation.CustomScaleTransformation
- */
- fun transformation(transformation: CustomPropertyTransformation<*>)
+ /** Apply a [transformation] to the element(s) matching [matcher]. */
+ fun transformation(matcher: ElementMatcher, transformation: Transformation.Factory)
}
/** This converter lets you change a linear progress into a function of your choice. */
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDslImpl.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDslImpl.kt
index 79f8cd4..6742b32 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDslImpl.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/TransitionDslImpl.kt
@@ -30,7 +30,6 @@
import com.android.compose.animation.scene.content.state.TransitionState
import com.android.compose.animation.scene.transformation.AnchoredSize
import com.android.compose.animation.scene.transformation.AnchoredTranslate
-import com.android.compose.animation.scene.transformation.CustomPropertyTransformation
import com.android.compose.animation.scene.transformation.DrawScale
import com.android.compose.animation.scene.transformation.EdgeTranslate
import com.android.compose.animation.scene.transformation.Fade
@@ -38,8 +37,8 @@
import com.android.compose.animation.scene.transformation.ScaleSize
import com.android.compose.animation.scene.transformation.SharedElementTransformation
import com.android.compose.animation.scene.transformation.Transformation
+import com.android.compose.animation.scene.transformation.TransformationMatcher
import com.android.compose.animation.scene.transformation.TransformationRange
-import com.android.compose.animation.scene.transformation.TransformationWithRange
import com.android.compose.animation.scene.transformation.Translate
internal fun transitionsImpl(builder: SceneTransitionsBuilder.() -> Unit): SceneTransitions {
@@ -67,8 +66,8 @@
preview: (TransitionBuilder.() -> Unit)?,
reversePreview: (TransitionBuilder.() -> Unit)?,
builder: TransitionBuilder.() -> Unit,
- ): TransitionSpec {
- return transition(from = null, to = to, key = key, preview, reversePreview, builder)
+ ) {
+ transition(from = null, to = to, key = key, preview, reversePreview, builder)
}
override fun from(
@@ -78,25 +77,25 @@
preview: (TransitionBuilder.() -> Unit)?,
reversePreview: (TransitionBuilder.() -> Unit)?,
builder: TransitionBuilder.() -> Unit,
- ): TransitionSpec {
- return transition(from = from, to = to, key = key, preview, reversePreview, builder)
+ ) {
+ transition(from = from, to = to, key = key, preview, reversePreview, builder)
}
override fun overscroll(
content: ContentKey,
orientation: Orientation,
builder: OverscrollBuilder.() -> Unit,
- ): OverscrollSpec {
+ ) {
val impl = OverscrollBuilderImpl().apply(builder)
- check(impl.transformations.isNotEmpty()) {
+ check(impl.transformationMatchers.isNotEmpty()) {
"This method does not allow empty transformations. " +
"Use overscrollDisabled($content, $orientation) instead."
}
- return overscrollSpec(content, orientation, impl)
+ overscrollSpec(content, orientation, impl)
}
- override fun overscrollDisabled(content: ContentKey, orientation: Orientation): OverscrollSpec {
- return overscrollSpec(content, orientation, OverscrollBuilderImpl())
+ override fun overscrollDisabled(content: ContentKey, orientation: Orientation) {
+ overscrollSpec(content, orientation, OverscrollBuilderImpl())
}
private fun overscrollSpec(
@@ -113,7 +112,7 @@
progressSpec = snap(),
swipeSpec = null,
distance = impl.distance,
- transformations = impl.transformations,
+ transformationMatchers = impl.transformationMatchers,
),
progressConverter = impl.progressConverter,
)
@@ -138,7 +137,7 @@
progressSpec = impl.spec,
swipeSpec = impl.swipeSpec,
distance = impl.distance,
- transformations = impl.transformations,
+ transformationMatchers = impl.transformationMatchers,
)
}
@@ -158,7 +157,7 @@
}
internal abstract class BaseTransitionBuilderImpl : BaseTransitionBuilder {
- val transformations = mutableListOf<TransformationWithRange<*>>()
+ val transformationMatchers = mutableListOf<TransformationMatcher>()
private var range: TransformationRange? = null
protected var reversed = false
override var distance: UserActionDistance? = null
@@ -174,23 +173,31 @@
range = null
}
- protected fun addTransformation(transformation: Transformation) {
- val transformationWithRange = TransformationWithRange(transformation, range)
- transformations.add(
- if (reversed) {
- transformationWithRange.reversed()
- } else {
- transformationWithRange
- }
+ protected fun addTransformation(
+ matcher: ElementMatcher,
+ transformation: Transformation.Factory,
+ ) {
+ transformationMatchers.add(
+ TransformationMatcher(
+ matcher,
+ transformation,
+ range?.let { range ->
+ if (reversed) {
+ range.reversed()
+ } else {
+ range
+ }
+ },
+ )
)
}
override fun fade(matcher: ElementMatcher) {
- addTransformation(Fade(matcher))
+ addTransformation(matcher, Fade.Factory)
}
override fun translate(matcher: ElementMatcher, x: Dp, y: Dp) {
- addTransformation(Translate(matcher, x, y))
+ addTransformation(matcher, Translate.Factory(x, y))
}
override fun translate(
@@ -198,19 +205,19 @@
edge: Edge,
startsOutsideLayoutBounds: Boolean,
) {
- addTransformation(EdgeTranslate(matcher, edge, startsOutsideLayoutBounds))
+ addTransformation(matcher, EdgeTranslate.Factory(edge, startsOutsideLayoutBounds))
}
override fun anchoredTranslate(matcher: ElementMatcher, anchor: ElementKey) {
- addTransformation(AnchoredTranslate(matcher, anchor))
+ addTransformation(matcher, AnchoredTranslate.Factory(anchor))
}
override fun scaleSize(matcher: ElementMatcher, width: Float, height: Float) {
- addTransformation(ScaleSize(matcher, width, height))
+ addTransformation(matcher, ScaleSize.Factory(width, height))
}
override fun scaleDraw(matcher: ElementMatcher, scaleX: Float, scaleY: Float, pivot: Offset) {
- addTransformation(DrawScale(matcher, scaleX, scaleY, pivot))
+ addTransformation(matcher, DrawScale.Factory(scaleX, scaleY, pivot))
}
override fun anchoredSize(
@@ -219,12 +226,12 @@
anchorWidth: Boolean,
anchorHeight: Boolean,
) {
- addTransformation(AnchoredSize(matcher, anchor, anchorWidth, anchorHeight))
+ addTransformation(matcher, AnchoredSize.Factory(anchor, anchorWidth, anchorHeight))
}
- override fun transformation(transformation: CustomPropertyTransformation<*>) {
+ override fun transformation(matcher: ElementMatcher, transformation: Transformation.Factory) {
check(range == null) { "Custom transformations can not be applied inside a range" }
- addTransformation(transformation)
+ addTransformation(matcher, transformation)
}
}
@@ -263,7 +270,10 @@
"(${transition.toContent.debugName})"
}
- addTransformation(SharedElementTransformation(matcher, enabled, elevateInContent))
+ addTransformation(
+ matcher,
+ SharedElementTransformation.Factory(matcher, enabled, elevateInContent),
+ )
}
override fun timestampRange(
@@ -294,6 +304,6 @@
x: OverscrollScope.() -> Float,
y: OverscrollScope.() -> Float,
) {
- addTransformation(OverscrollTranslate(matcher, x, y))
+ addTransformation(matcher, OverscrollTranslate.Factory(x, y))
}
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/content/state/TransitionState.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/content/state/TransitionState.kt
index 38b1aaa..33f015f 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/content/state/TransitionState.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/content/state/TransitionState.kt
@@ -401,7 +401,7 @@
else -> null
} ?: return true
- return specForCurrentScene.transformationSpec.transformations.isNotEmpty()
+ return specForCurrentScene.transformationSpec.transformationMatchers.isNotEmpty()
}
internal open fun interruptionProgress(layoutImpl: SceneTransitionLayoutImpl): Float {
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/reveal/ContainerReveal.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/reveal/ContainerReveal.kt
new file mode 100644
index 0000000..bfb5ca7
--- /dev/null
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/reveal/ContainerReveal.kt
@@ -0,0 +1,289 @@
+/*
+ * Copyright (C) 2024 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.compose.animation.scene.reveal
+
+import androidx.compose.animation.core.AnimationVector1D
+import androidx.compose.animation.core.DeferredTargetAnimation
+import androidx.compose.animation.core.ExperimentalAnimatableApi
+import androidx.compose.animation.core.FiniteAnimationSpec
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.VectorConverter
+import androidx.compose.animation.core.spring
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.util.fastCoerceAtLeast
+import androidx.compose.ui.util.fastCoerceAtMost
+import com.android.compose.animation.scene.ContentKey
+import com.android.compose.animation.scene.ElementKey
+import com.android.compose.animation.scene.OverlayKey
+import com.android.compose.animation.scene.SceneKey
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.compose.animation.scene.UserActionDistance
+import com.android.compose.animation.scene.content.state.TransitionState
+import com.android.compose.animation.scene.transformation.CustomPropertyTransformation
+import com.android.compose.animation.scene.transformation.PropertyTransformation
+import com.android.compose.animation.scene.transformation.PropertyTransformationScope
+import kotlin.math.roundToInt
+import kotlinx.coroutines.CoroutineScope
+
+interface ContainerRevealHaptics {
+ /**
+ * Called when the reveal threshold is crossed while the user was dragging on screen.
+ *
+ * Important: This callback is called during layout and its implementation should therefore be
+ * very fast or posted to a different thread.
+ *
+ * @param revealed whether we go from hidden to revealed, i.e. whether the container size is
+ * going to jump from a smaller size to a bigger size.
+ */
+ fun onRevealThresholdCrossed(revealed: Boolean)
+}
+
+/** Animate the reveal of [container] by animating its size. */
+fun TransitionBuilder.verticalContainerReveal(
+ container: ElementKey,
+ haptics: ContainerRevealHaptics,
+) {
+ // Make the swipe distance be exactly the target height of the container.
+ // TODO(b/376438969): Make sure that this works correctly when the target size of the element
+ // is changing during the transition (e.g. a notification was added). At the moment, the user
+ // action distance is only called until it returns a value > 0f, which is then cached.
+ distance = UserActionDistance { fromContent, toContent, _ ->
+ val targetSizeInFromContent = container.targetSize(fromContent)
+ val targetSizeInToContent = container.targetSize(toContent)
+ if (targetSizeInFromContent != null && targetSizeInToContent != null) {
+ error(
+ "verticalContainerReveal should not be used with shared elements, but " +
+ "${container.debugName} is in both ${fromContent.debugName} and " +
+ toContent.debugName
+ )
+ }
+
+ (targetSizeInToContent?.height ?: targetSizeInFromContent?.height)?.toFloat() ?: 0f
+ }
+
+ // TODO(b/376438969): Improve the motion of this gesture using Motion Mechanics.
+
+ // The min distance to swipe before triggering the reveal spring.
+ val distanceThreshold = 80.dp
+
+ // The minimum height of the container.
+ val minHeight = 10.dp
+
+ // The amount removed from the container width at 0% progress.
+ val widthDelta = 140.dp
+
+ // The ratio at which the distance is tracked before reaching the threshold, e.g. if the user
+ // drags 60dp then the height will be 60dp * 0.25f = 15dp.
+ val trackingRatio = 0.25f
+
+ // The max progress starting from which the container should always be visible, even if we are
+ // animating the container out. This is used so that we don't immediately fade out the container
+ // when triggering a one-off animation that hides it.
+ val alphaProgressThreshold = 0.05f
+
+ // The spring animating the size of the container.
+ val sizeSpec = spring<Float>(stiffness = 380f, dampingRatio = 0.9f)
+
+ // The spring animating the alpha of the container.
+ val alphaSpec = spring<Float>(stiffness = 1200f, dampingRatio = 0.99f)
+
+ // The spring animating the progress when releasing the finger.
+ swipeSpec =
+ spring(
+ stiffness = Spring.StiffnessMediumLow,
+ dampingRatio = Spring.DampingRatioNoBouncy,
+ visibilityThreshold = 0.5f,
+ )
+
+ // Size transformation.
+ transformation(container) {
+ VerticalContainerRevealSizeTransformation(
+ haptics,
+ distanceThreshold,
+ trackingRatio,
+ minHeight,
+ widthDelta,
+ sizeSpec,
+ )
+ }
+
+ // Alpha transformation.
+ transformation(container) {
+ ContainerRevealAlphaTransformation(alphaSpec, alphaProgressThreshold)
+ }
+}
+
+@OptIn(ExperimentalAnimatableApi::class)
+private class VerticalContainerRevealSizeTransformation(
+ private val haptics: ContainerRevealHaptics,
+ private val distanceThreshold: Dp,
+ private val trackingRatio: Float,
+ private val minHeight: Dp,
+ private val widthDelta: Dp,
+ private val spec: FiniteAnimationSpec<Float>,
+) : CustomPropertyTransformation<IntSize> {
+ override val property = PropertyTransformation.Property.Size
+
+ private val widthAnimation = DeferredTargetAnimation(Float.VectorConverter)
+ private val heightAnimation = DeferredTargetAnimation(Float.VectorConverter)
+
+ private var previousHasReachedThreshold: Boolean? = null
+
+ override fun PropertyTransformationScope.transform(
+ content: ContentKey,
+ element: ElementKey,
+ transition: TransitionState.Transition,
+ transitionScope: CoroutineScope,
+ ): IntSize {
+ // The distance to go to 100%. Note that we don't use
+ // TransitionState.HasOverscrollProperties.absoluteDistance because the transition will not
+ // implement HasOverscrollProperties if the transition is triggered and not gesture based.
+ val idleSize = checkNotNull(element.targetSize(content))
+ val userActionDistance = idleSize.height
+ val progress =
+ when ((transition as? TransitionState.HasOverscrollProperties)?.bouncingContent) {
+ null -> transition.progressTo(content)
+ content -> 1f
+ else -> 0f
+ }
+ val distance = (progress * userActionDistance).fastCoerceAtLeast(0f)
+ val threshold = distanceThreshold.toPx()
+
+ // Width.
+ val widthDelta = widthDelta.toPx()
+ val width =
+ (idleSize.width - widthDelta +
+ animateSize(
+ size = widthDelta,
+ distance = distance,
+ threshold = threshold,
+ transitionScope = transitionScope,
+ animation = widthAnimation,
+ ))
+ .roundToInt()
+
+ // Height.
+ val minHeight = minHeight.toPx()
+ val height =
+ (
+ // 1) The minimum size of the container.
+ minHeight +
+
+ // 2) The animated size between the minimum size and the threshold.
+ animateSize(
+ size = threshold - minHeight,
+ distance = distance,
+ threshold = threshold,
+ transitionScope = transitionScope,
+ animation = heightAnimation,
+ ) +
+
+ // 3) The remaining height after the threshold, tracking the finger.
+ (distance - threshold).fastCoerceAtLeast(0f))
+ .roundToInt()
+ .fastCoerceAtMost(idleSize.height)
+
+ // Haptics.
+ val hasReachedThreshold = distance >= threshold
+ if (
+ previousHasReachedThreshold != null &&
+ hasReachedThreshold != previousHasReachedThreshold &&
+ transition.isUserInputOngoing
+ ) {
+ haptics.onRevealThresholdCrossed(revealed = hasReachedThreshold)
+ }
+ previousHasReachedThreshold = hasReachedThreshold
+
+ return IntSize(width = width, height = height)
+ }
+
+ /**
+ * Animate a size up to [size], so that it is equal to 0f when distance is 0f and equal to
+ * [size] when `distance >= threshold`, taking the [trackingRatio] into account.
+ */
+ @OptIn(ExperimentalAnimatableApi::class)
+ private fun animateSize(
+ size: Float,
+ distance: Float,
+ threshold: Float,
+ transitionScope: CoroutineScope,
+ animation: DeferredTargetAnimation<Float, AnimationVector1D>,
+ ): Float {
+ val trackingSize = distance.fastCoerceAtMost(threshold) / threshold * size * trackingRatio
+ val springTarget =
+ if (distance >= threshold) {
+ size * (1f - trackingRatio)
+ } else {
+ 0f
+ }
+ val springSize = animation.updateTarget(springTarget, transitionScope, spec)
+ return trackingSize + springSize
+ }
+}
+
+@OptIn(ExperimentalAnimatableApi::class)
+private class ContainerRevealAlphaTransformation(
+ private val spec: FiniteAnimationSpec<Float>,
+ private val progressThreshold: Float,
+) : CustomPropertyTransformation<Float> {
+ override val property = PropertyTransformation.Property.Alpha
+ private val alphaAnimation = DeferredTargetAnimation(Float.VectorConverter)
+
+ override fun PropertyTransformationScope.transform(
+ content: ContentKey,
+ element: ElementKey,
+ transition: TransitionState.Transition,
+ transitionScope: CoroutineScope,
+ ): Float {
+ return alphaAnimation.updateTarget(targetAlpha(transition, content), transitionScope, spec)
+ }
+
+ private fun targetAlpha(transition: TransitionState.Transition, content: ContentKey): Float {
+ if (transition.isUserInputOngoing) {
+ if (transition !is TransitionState.HasOverscrollProperties) {
+ error(
+ "Unsupported transition driven by user input but that does not have " +
+ "overscroll properties: $transition"
+ )
+ }
+
+ val bouncingContent = transition.bouncingContent
+ return if (bouncingContent != null) {
+ if (bouncingContent == content) 1f else 0f
+ } else {
+ if (transition.progressTo(content) > 0f) 1f else 0f
+ }
+ }
+
+ // The transition was committed (the user released their finger), so the alpha depends on
+ // whether we are animating towards the content (showing the container) or away from it
+ // (hiding the container).
+ val isShowingContainer =
+ when (content) {
+ is SceneKey -> transition.currentScene == content
+ is OverlayKey -> transition.currentOverlays.contains(content)
+ }
+
+ return if (isShowingContainer || transition.progressTo(content) >= progressThreshold) {
+ 1f
+ } else {
+ 0f
+ }
+ }
+}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredSize.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredSize.kt
index 85bb533..6575068 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredSize.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredSize.kt
@@ -19,16 +19,17 @@
import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.content.state.TransitionState
/** Anchor the size of an element to the size of another element. */
-internal class AnchoredSize(
- override val matcher: ElementMatcher,
+internal class AnchoredSize
+private constructor(
private val anchor: ElementKey,
private val anchorWidth: Boolean,
private val anchorHeight: Boolean,
-) : InterpolatedSizeTransformation {
+) : InterpolatedPropertyTransformation<IntSize> {
+ override val property = PropertyTransformation.Property.Size
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -59,4 +60,12 @@
anchorSizeIn(transition.fromContent)
}
}
+
+ class Factory(
+ private val anchor: ElementKey,
+ private val anchorWidth: Boolean,
+ private val anchorHeight: Boolean,
+ ) : Transformation.Factory {
+ override fun create(): Transformation = AnchoredSize(anchor, anchorWidth, anchorHeight)
+ }
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredTranslate.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredTranslate.kt
index 04cd683..890902b 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredTranslate.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/AnchoredTranslate.kt
@@ -19,14 +19,13 @@
import androidx.compose.ui.geometry.Offset
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.content.state.TransitionState
/** Anchor the translation of an element to another element. */
-internal class AnchoredTranslate(
- override val matcher: ElementMatcher,
- private val anchor: ElementKey,
-) : InterpolatedOffsetTransformation {
+internal class AnchoredTranslate private constructor(private val anchor: ElementKey) :
+ InterpolatedPropertyTransformation<Offset> {
+ override val property = PropertyTransformation.Property.Offset
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -56,6 +55,10 @@
Offset(idleValue.x + offset.x, idleValue.y + offset.y)
}
}
+
+ class Factory(private val anchor: ElementKey) : Transformation.Factory {
+ override fun create(): Transformation = AnchoredTranslate(anchor)
+ }
}
internal fun throwMissingAnchorException(
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/DrawScale.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/DrawScale.kt
index 45d6d40..347f1c3 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/DrawScale.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/DrawScale.kt
@@ -19,7 +19,6 @@
import androidx.compose.ui.geometry.Offset
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.Scale
import com.android.compose.animation.scene.content.state.TransitionState
@@ -27,12 +26,14 @@
* Scales the draw size of an element. Note this will only scale the draw inside of an element,
* therefore it won't impact layout of elements around it.
*/
-internal class DrawScale(
- override val matcher: ElementMatcher,
+internal class DrawScale
+private constructor(
private val scaleX: Float,
private val scaleY: Float,
- private val pivot: Offset = Offset.Unspecified,
-) : InterpolatedScaleTransformation {
+ private val pivot: Offset,
+) : InterpolatedPropertyTransformation<Scale> {
+ override val property = PropertyTransformation.Property.Scale
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -41,4 +42,9 @@
): Scale {
return Scale(scaleX, scaleY, pivot)
}
+
+ class Factory(private val scaleX: Float, private val scaleY: Float, private val pivot: Offset) :
+ Transformation.Factory {
+ override fun create(): Transformation = DrawScale(scaleX, scaleY, pivot)
+ }
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/EdgeTranslate.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/EdgeTranslate.kt
index 21d66d7..f8e6dc0 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/EdgeTranslate.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/EdgeTranslate.kt
@@ -20,15 +20,14 @@
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.Edge
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.content.state.TransitionState
/** Translate an element from an edge of the layout. */
-internal class EdgeTranslate(
- override val matcher: ElementMatcher,
- private val edge: Edge,
- private val startsOutsideLayoutBounds: Boolean = true,
-) : InterpolatedOffsetTransformation {
+internal class EdgeTranslate
+private constructor(private val edge: Edge, private val startsOutsideLayoutBounds: Boolean) :
+ InterpolatedPropertyTransformation<Offset> {
+ override val property = PropertyTransformation.Property.Offset
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -67,4 +66,9 @@
}
}
}
+
+ class Factory(private val edge: Edge, private val startsOutsideLayoutBounds: Boolean) :
+ Transformation.Factory {
+ override fun create(): Transformation = EdgeTranslate(edge, startsOutsideLayoutBounds)
+ }
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Fade.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Fade.kt
index d942273..d92419e 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Fade.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Fade.kt
@@ -18,11 +18,12 @@
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.content.state.TransitionState
/** Fade an element in or out. */
-internal class Fade(override val matcher: ElementMatcher) : InterpolatedAlphaTransformation {
+internal object Fade : InterpolatedPropertyTransformation<Float> {
+ override val property = PropertyTransformation.Property.Alpha
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -33,4 +34,8 @@
// fading out, which is `0` in both cases.
return 0f
}
+
+ object Factory : Transformation.Factory {
+ override fun create(): Transformation = Fade
+ }
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/ScaleSize.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/ScaleSize.kt
index 5f3cdab..5d31fd9 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/ScaleSize.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/ScaleSize.kt
@@ -19,7 +19,6 @@
import androidx.compose.ui.unit.IntSize
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.content.state.TransitionState
import kotlin.math.roundToInt
@@ -27,11 +26,10 @@
* Scales the size of an element. Note that this makes the element resize every frame and will
* therefore impact the layout of other elements.
*/
-internal class ScaleSize(
- override val matcher: ElementMatcher,
- private val width: Float = 1f,
- private val height: Float = 1f,
-) : InterpolatedSizeTransformation {
+internal class ScaleSize private constructor(private val width: Float, private val height: Float) :
+ InterpolatedPropertyTransformation<IntSize> {
+ override val property = PropertyTransformation.Property.Size
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -43,4 +41,9 @@
height = (idleValue.height * height).roundToInt(),
)
}
+
+ class Factory(private val width: Float = 1f, private val height: Float = 1f) :
+ Transformation.Factory {
+ override fun create(): Transformation = ScaleSize(width, height)
+ }
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Transformation.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Transformation.kt
index d5143d7..e0b4218 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Transformation.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Transformation.kt
@@ -35,26 +35,59 @@
/** A transformation applied to one or more elements during a transition. */
sealed interface Transformation {
- /**
- * The matcher that should match the element(s) to which this transformation should be applied.
- */
- val matcher: ElementMatcher
+ fun interface Factory {
+ fun create(): Transformation
+ }
}
-internal class SharedElementTransformation(
- override val matcher: ElementMatcher,
+// Important: SharedElementTransformation must be a data class because we check that we don't
+// provide 2 different transformations for the same element in Element.kt
+internal data class SharedElementTransformation(
internal val enabled: Boolean,
internal val elevateInContent: ContentKey?,
-) : Transformation
+) : Transformation {
+ class Factory(
+ internal val matcher: ElementMatcher,
+ internal val enabled: Boolean,
+ internal val elevateInContent: ContentKey?,
+ ) : Transformation.Factory {
+ override fun create(): Transformation {
+ return SharedElementTransformation(enabled, elevateInContent)
+ }
+ }
+}
-/** A transformation that changes the value of an element property, like its size or offset. */
-sealed interface PropertyTransformation<T> : Transformation
+/**
+ * A transformation that changes the value of an element [Property], like its [size][Property.Size]
+ * or [offset][Property.Offset].
+ */
+sealed interface PropertyTransformation<T> : Transformation {
+ /** The property to which this transformation is applied. */
+ val property: Property<T>
+
+ sealed class Property<T> {
+ /** The size of an element. */
+ data object Size : Property<IntSize>()
+
+ /** The offset (position) of an element. */
+ data object Offset : Property<androidx.compose.ui.geometry.Offset>()
+
+ /** The alpha of an element. */
+ data object Alpha : Property<Float>()
+
+ /**
+ * The drawing scale of an element. Animating the scale does not have any effect on the
+ * layout.
+ */
+ data object Scale : Property<com.android.compose.animation.scene.Scale>()
+ }
+}
/**
* A transformation to a target/transformed value that is automatically interpolated using the
* transition progress and transformation range.
*/
-sealed interface InterpolatedPropertyTransformation<T> : PropertyTransformation<T> {
+interface InterpolatedPropertyTransformation<T> : PropertyTransformation<T> {
/**
* Return the transformed value for the given property, i.e.:
* - the value at progress = 0% for elements that are entering the layout (i.e. elements in the
@@ -73,19 +106,7 @@
): T
}
-/** An [InterpolatedPropertyTransformation] applied to the size of one or more elements. */
-interface InterpolatedSizeTransformation : InterpolatedPropertyTransformation<IntSize>
-
-/** An [InterpolatedPropertyTransformation] applied to the offset of one or more elements. */
-interface InterpolatedOffsetTransformation : InterpolatedPropertyTransformation<Offset>
-
-/** An [InterpolatedPropertyTransformation] applied to the alpha of one or more elements. */
-interface InterpolatedAlphaTransformation : InterpolatedPropertyTransformation<Float>
-
-/** An [InterpolatedPropertyTransformation] applied to the scale of one or more elements. */
-interface InterpolatedScaleTransformation : InterpolatedPropertyTransformation<Scale>
-
-sealed interface CustomPropertyTransformation<T> : PropertyTransformation<T> {
+interface CustomPropertyTransformation<T> : PropertyTransformation<T> {
/**
* Return the value that the property should have in the current frame for the given [content]
* and [element].
@@ -105,25 +126,20 @@
): T
}
-/** A [CustomPropertyTransformation] applied to the size of one or more elements. */
-interface CustomSizeTransformation : CustomPropertyTransformation<IntSize>
-
-/** A [CustomPropertyTransformation] applied to the offset of one or more elements. */
-interface CustomOffsetTransformation : CustomPropertyTransformation<Offset>
-
-/** A [CustomPropertyTransformation] applied to the alpha of one or more elements. */
-interface CustomAlphaTransformation : CustomPropertyTransformation<Float>
-
-/** A [CustomPropertyTransformation] applied to the scale of one or more elements. */
-interface CustomScaleTransformation : CustomPropertyTransformation<Scale>
-
interface PropertyTransformationScope : Density, ElementStateScope {
/** The current [direction][LayoutDirection] of the layout. */
val layoutDirection: LayoutDirection
}
+/** Defines the transformation-type to be applied to all elements matching [matcher]. */
+internal class TransformationMatcher(
+ val matcher: ElementMatcher,
+ val factory: Transformation.Factory,
+ val range: TransformationRange?,
+)
+
/** A pair consisting of a [transformation] and optional [range]. */
-class TransformationWithRange<out T : Transformation>(
+internal data class TransformationWithRange<out T : Transformation>(
val transformation: T,
val range: TransformationRange?,
) {
@@ -135,7 +151,7 @@
}
/** The progress-based range of a [PropertyTransformation]. */
-data class TransformationRange(val start: Float, val end: Float, val easing: Easing) {
+internal data class TransformationRange(val start: Float, val end: Float, val easing: Easing) {
constructor(
start: Float? = null,
end: Float? = null,
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Translate.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Translate.kt
index d756c86..2f4d5bff 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Translate.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/transformation/Translate.kt
@@ -19,18 +19,15 @@
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
-import androidx.compose.ui.unit.dp
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.OverscrollScope
import com.android.compose.animation.scene.content.state.TransitionState
-internal class Translate(
- override val matcher: ElementMatcher,
- private val x: Dp = 0.dp,
- private val y: Dp = 0.dp,
-) : InterpolatedOffsetTransformation {
+internal class Translate private constructor(private val x: Dp, private val y: Dp) :
+ InterpolatedPropertyTransformation<Offset> {
+ override val property = PropertyTransformation.Property.Offset
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -39,13 +36,19 @@
): Offset {
return Offset(idleValue.x + x.toPx(), idleValue.y + y.toPx())
}
+
+ class Factory(private val x: Dp, private val y: Dp) : Transformation.Factory {
+ override fun create(): Transformation = Translate(x, y)
+ }
}
-internal class OverscrollTranslate(
- override val matcher: ElementMatcher,
- val x: OverscrollScope.() -> Float = { 0f },
- val y: OverscrollScope.() -> Float = { 0f },
-) : InterpolatedOffsetTransformation {
+internal class OverscrollTranslate
+private constructor(
+ private val x: OverscrollScope.() -> Float,
+ private val y: OverscrollScope.() -> Float,
+) : InterpolatedPropertyTransformation<Offset> {
+ override val property = PropertyTransformation.Property.Offset
+
private val cachedOverscrollScope = CachedOverscrollScope()
override fun PropertyTransformationScope.transform(
@@ -63,6 +66,13 @@
return Offset(x = value.x + overscrollScope.x(), y = value.y + overscrollScope.y())
}
+
+ class Factory(
+ private val x: OverscrollScope.() -> Float,
+ private val y: OverscrollScope.() -> Float,
+ ) : Transformation.Factory {
+ override fun create(): Transformation = OverscrollTranslate(x, y)
+ }
}
/**
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
index 61e9bb0..10057b2 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
@@ -644,7 +644,7 @@
mutableUserActionsA = emptyMap()
mutableUserActionsB = emptyMap()
- // start accelaratedScroll and scroll over to B -> null
+ // start acceleratedScroll and scroll over to B -> null
val dragController2 = onDragStartedImmediately()
dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f), expectedConsumed = 0f)
dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f), expectedConsumed = 0f)
@@ -1530,7 +1530,7 @@
fun interceptingTransitionKeepsDistance() = runGestureTest {
var swipeDistance = 75f
layoutState.transitions = transitions {
- from(SceneA, to = SceneB) { distance = UserActionDistance { _, _ -> swipeDistance } }
+ from(SceneA, to = SceneB) { distance = UserActionDistance { _, _, _ -> swipeDistance } }
}
// Start transition.
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneTransitionLayoutStateTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneTransitionLayoutStateTest.kt
index 57ad81e..79ca891 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneTransitionLayoutStateTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneTransitionLayoutStateTest.kt
@@ -153,7 +153,7 @@
// Default transition from A to B.
assertThat(state.setTargetScene(SceneB, animationScope = this)).isNotNull()
- assertThat(state.currentTransition?.transformationSpec?.transformations).hasSize(1)
+ assertThat(state.currentTransition?.transformationSpec?.transformationMatchers).hasSize(1)
// Go back to A.
state.setTargetScene(SceneA, animationScope = this)
@@ -166,7 +166,7 @@
state.setTargetScene(SceneB, animationScope = this, transitionKey = transitionkey)
)
.isNotNull()
- assertThat(state.currentTransition?.transformationSpec?.transformations).hasSize(2)
+ assertThat(state.currentTransition?.transformationSpec?.transformationMatchers).hasSize(2)
}
@Test
@@ -686,4 +686,30 @@
assertThat(state.transitionState).isIdle()
assertThat(job.isCancelled).isTrue()
}
+
+ @Test
+ fun badTransitionSpecThrowsMeaningfulMessageWhenStartingTransition() {
+ val state =
+ MutableSceneTransitionLayoutState(
+ SceneA,
+ transitions {
+ // This transition definition is bad because they both match when transitioning
+ // from A to B.
+ from(SceneA) {}
+ to(SceneB) {}
+ },
+ )
+
+ val exception =
+ assertThrows(IllegalStateException::class.java) {
+ runBlocking { state.startTransition(transition(from = SceneA, to = SceneB)) }
+ }
+
+ assertThat(exception)
+ .hasMessageThat()
+ .isEqualTo(
+ "Found multiple transition specs for transition SceneKey(debugName=SceneA) => " +
+ "SceneKey(debugName=SceneB)"
+ )
+ }
}
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SwipeToSceneTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SwipeToSceneTest.kt
index 97a96a4..b3a3261 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SwipeToSceneTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SwipeToSceneTest.kt
@@ -55,7 +55,6 @@
import androidx.compose.ui.test.swipeUp
import androidx.compose.ui.test.swipeWithVelocity
import androidx.compose.ui.unit.Density
-import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -672,12 +671,12 @@
}
assertThat(state.isTransitioning(from = SceneA, to = SceneB)).isTrue()
- assertThat(state.currentTransition?.transformationSpec?.transformations).hasSize(1)
+ assertThat(state.currentTransition?.transformationSpec?.transformationMatchers).hasSize(1)
// Move the pointer up to swipe to scene B using the new transition.
rule.onRoot().performTouchInput { moveBy(Offset(0f, -1.dp.toPx()), delayMillis = 1_000) }
assertThat(state.isTransitioning(from = SceneA, to = SceneB)).isTrue()
- assertThat(state.currentTransition?.transformationSpec?.transformations).hasSize(2)
+ assertThat(state.currentTransition?.transformationSpec?.transformationMatchers).hasSize(2)
}
@Test
@@ -685,7 +684,8 @@
val swipeDistance =
object : UserActionDistance {
override fun UserActionDistanceScope.absoluteDistance(
- fromSceneSize: IntSize,
+ fromContent: ContentKey,
+ toContent: ContentKey,
orientation: Orientation,
): Float {
// Foo is going to have a vertical offset of 50dp. Let's make the swipe distance
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/TransitionDslTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/TransitionDslTest.kt
index 1f9ba9e..70f2ff80 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/TransitionDslTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/TransitionDslTest.kt
@@ -28,11 +28,12 @@
import com.android.compose.animation.scene.TestScenes.SceneB
import com.android.compose.animation.scene.TestScenes.SceneC
import com.android.compose.animation.scene.content.state.TransitionState
-import com.android.compose.animation.scene.transformation.CustomSizeTransformation
+import com.android.compose.animation.scene.transformation.CustomPropertyTransformation
import com.android.compose.animation.scene.transformation.OverscrollTranslate
+import com.android.compose.animation.scene.transformation.PropertyTransformation
import com.android.compose.animation.scene.transformation.PropertyTransformationScope
+import com.android.compose.animation.scene.transformation.TransformationMatcher
import com.android.compose.animation.scene.transformation.TransformationRange
-import com.android.compose.animation.scene.transformation.TransformationWithRange
import com.android.compose.test.transition
import com.google.common.truth.Correspondence
import com.google.common.truth.Truth.assertThat
@@ -103,7 +104,7 @@
val transitions = transitions { from(SceneA, to = SceneB) { fade(TestElements.Foo) } }
val transformations =
- transitions.transitionSpecs.single().transformationSpec(aToB()).transformations
+ transitions.transitionSpecs.single().transformationSpec(aToB()).transformationMatchers
assertThat(transformations.size).isEqualTo(1)
assertThat(transformations.single().range).isEqualTo(null)
}
@@ -126,7 +127,7 @@
}
val transformations =
- transitions.transitionSpecs.single().transformationSpec(aToB()).transformations
+ transitions.transitionSpecs.single().transformationSpec(aToB()).transformationMatchers
assertThat(transformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
.containsExactly(
@@ -157,7 +158,7 @@
}
val transformations =
- transitions.transitionSpecs.single().transformationSpec(aToB()).transformations
+ transitions.transitionSpecs.single().transformationSpec(aToB()).transformationMatchers
assertThat(transformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
.containsExactly(
@@ -185,7 +186,7 @@
}
val transformations =
- transitions.transitionSpecs.single().transformationSpec(aToB()).transformations
+ transitions.transitionSpecs.single().transformationSpec(aToB()).transformationMatchers
assertThat(transformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
.containsExactly(
@@ -215,7 +216,7 @@
// to B we defined.
val transitionSpec = transitions.transitionSpec(from = SceneB, to = SceneA, key = null)
- val transformations = transitionSpec.transformationSpec(aToB()).transformations
+ val transformations = transitionSpec.transformationSpec(aToB()).transformationMatchers
assertThat(transformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
@@ -225,7 +226,7 @@
)
val previewTransformations =
- transitionSpec.previewTransformationSpec(aToB())?.transformations
+ transitionSpec.previewTransformationSpec(aToB())?.transformationMatchers
assertThat(previewTransformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
@@ -255,7 +256,7 @@
key = TransitionKey.PredictiveBack,
)
- val transformations = transitionSpec.transformationSpec(aToB()).transformations
+ val transformations = transitionSpec.transformationSpec(aToB()).transformationMatchers
assertThat(transformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
@@ -265,7 +266,7 @@
)
val previewTransformations =
- transitionSpec.previewTransformationSpec(aToB())?.transformations
+ transitionSpec.previewTransformationSpec(aToB())?.transformationMatchers
assertThat(previewTransformations)
.comparingElementsUsing(TRANSFORMATION_RANGE)
@@ -316,7 +317,7 @@
val overscrollSpec = transitions.overscrollSpecs.single()
val transformation =
- overscrollSpec.transformationSpec.transformations.single().transformation
+ overscrollSpec.transformationSpec.transformationMatchers.single().factory.create()
assertThat(transformation).isInstanceOf(OverscrollTranslate::class.java)
}
@@ -324,7 +325,7 @@
fun overscrollSpec_for_overscrollDisabled() {
val transitions = transitions { overscrollDisabled(SceneA, Orientation.Vertical) }
val overscrollSpec = transitions.overscrollSpecs.single()
- assertThat(overscrollSpec.transformationSpec.transformations).isEmpty()
+ assertThat(overscrollSpec.transformationSpec.transformationMatchers).isEmpty()
}
@Test
@@ -353,9 +354,9 @@
val transitions = transitions {
from(SceneA, to = SceneB) {
fractionRange {
- transformation(
- object : CustomSizeTransformation {
- override val matcher: ElementMatcher = TestElements.Foo
+ transformation(TestElements.Foo) {
+ object : CustomPropertyTransformation<IntSize> {
+ override val property = PropertyTransformation.Property.Size
override fun PropertyTransformationScope.transform(
content: ContentKey,
@@ -364,7 +365,7 @@
transitionScope: CoroutineScope,
): IntSize = IntSize.Zero
}
- )
+ }
}
}
}
@@ -377,7 +378,7 @@
companion object {
private val TRANSFORMATION_RANGE =
- Correspondence.transforming<TransformationWithRange<*>, TransformationRange?>(
+ Correspondence.transforming<TransformationMatcher, TransformationRange?>(
{ it?.range },
"has range equal to",
)
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/subjects/TransitionStateSubject.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/subjects/TransitionStateSubject.kt
index 313379f..0adb480 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/subjects/TransitionStateSubject.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/subjects/TransitionStateSubject.kt
@@ -157,7 +157,7 @@
check("isUserInputOngoing").that(actual.isUserInputOngoing).isEqualTo(isUserInputOngoing)
}
- fun hasOverscrollSpec(): OverscrollSpec {
+ internal fun hasOverscrollSpec(): OverscrollSpec {
check("currentOverscrollSpec").that(actual.currentOverscrollSpec).isNotNull()
return actual.currentOverscrollSpec!!
}
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/transformation/CustomTransformationTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/transformation/CustomTransformationTest.kt
index 487b099..444ec4e 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/transformation/CustomTransformationTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/transformation/CustomTransformationTest.kt
@@ -30,7 +30,6 @@
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.compose.animation.scene.ContentKey
import com.android.compose.animation.scene.ElementKey
-import com.android.compose.animation.scene.ElementMatcher
import com.android.compose.animation.scene.TestElements
import com.android.compose.animation.scene.content.state.TransitionState
import com.android.compose.animation.scene.testTransition
@@ -47,8 +46,9 @@
@Test
fun customSize() {
/** A size transformation that adds [add] to the size of the transformed element(s). */
- class AddSizeTransformation(override val matcher: ElementMatcher, private val add: Dp) :
- CustomSizeTransformation {
+ class AddSizeTransformation(private val add: Dp) : CustomPropertyTransformation<IntSize> {
+ override val property = PropertyTransformation.Property.Size
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -69,7 +69,7 @@
spec = tween(16 * 4, easing = LinearEasing)
// Add 80dp to the width and height of Foo.
- transformation(AddSizeTransformation(TestElements.Foo, 80.dp))
+ transformation(TestElements.Foo) { AddSizeTransformation(80.dp) }
},
) {
before { onElement(TestElements.Foo).assertSizeIsEqualTo(40.dp, 20.dp) }
@@ -84,8 +84,9 @@
@Test
fun customOffset() {
/** An offset transformation that adds [add] to the offset of the transformed element(s). */
- class AddOffsetTransformation(override val matcher: ElementMatcher, private val add: Dp) :
- CustomOffsetTransformation {
+ class AddOffsetTransformation(private val add: Dp) : CustomPropertyTransformation<Offset> {
+ override val property = PropertyTransformation.Property.Offset
+
override fun PropertyTransformationScope.transform(
content: ContentKey,
element: ElementKey,
@@ -106,7 +107,7 @@
spec = tween(16 * 4, easing = LinearEasing)
// Add 80dp to the offset of Foo.
- transformation(AddOffsetTransformation(TestElements.Foo, 80.dp))
+ transformation(TestElements.Foo) { AddOffsetTransformation(80.dp) }
},
) {
before { onElement(TestElements.Foo).assertPositionInRootIsEqualTo(0.dp, 0.dp) }
diff --git a/packages/SystemUI/customization/res/values-sw600dp-land/dimens.xml b/packages/SystemUI/customization/res/values-sw600dp-land/dimens.xml
index 651e401..18073ad 100644
--- a/packages/SystemUI/customization/res/values-sw600dp-land/dimens.xml
+++ b/packages/SystemUI/customization/res/values-sw600dp-land/dimens.xml
@@ -16,4 +16,5 @@
<resources>
<dimen name="keyguard_smartspace_top_offset">0dp</dimen>
+ <dimen name="status_view_margin_horizontal">8dp</dimen>
</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/customization/res/values-sw600dp/dimens.xml b/packages/SystemUI/customization/res/values-sw600dp/dimens.xml
index 10e630d..37cd590 100644
--- a/packages/SystemUI/customization/res/values-sw600dp/dimens.xml
+++ b/packages/SystemUI/customization/res/values-sw600dp/dimens.xml
@@ -17,4 +17,5 @@
<resources>
<!-- For portrait direction in unfold foldable device, we don't need keyguard_smartspace_top_offset-->
<dimen name="keyguard_smartspace_top_offset">0dp</dimen>
+ <dimen name="status_view_margin_horizontal">62dp</dimen>
</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/customization/res/values-sw720dp-land/dimens.xml b/packages/SystemUI/customization/res/values-sw720dp-land/dimens.xml
new file mode 100644
index 0000000..c1cf42c
--- /dev/null
+++ b/packages/SystemUI/customization/res/values-sw720dp-land/dimens.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2024 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<resources>
+ <dimen name="status_view_margin_horizontal">24dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/customization/res/values-sw720dp-port/dimens.xml b/packages/SystemUI/customization/res/values-sw720dp-port/dimens.xml
new file mode 100644
index 0000000..54dbeaa
--- /dev/null
+++ b/packages/SystemUI/customization/res/values-sw720dp-port/dimens.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2024 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<resources>
+ <dimen name="status_view_margin_horizontal">124dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/customization/res/values/dimens.xml b/packages/SystemUI/customization/res/values/dimens.xml
index 7feea6e..041ae62 100644
--- a/packages/SystemUI/customization/res/values/dimens.xml
+++ b/packages/SystemUI/customization/res/values/dimens.xml
@@ -39,4 +39,5 @@
<!--Dimens used in both lockscreen preview and smartspace -->
<dimen name="date_weather_view_height">24dp</dimen>
<dimen name="enhanced_smartspace_height">104dp</dimen>
+ <dimen name="status_view_margin_horizontal">0dp</dimen>
</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/AssetLoader.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/AssetLoader.kt
deleted file mode 100644
index 2a2d333..0000000
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/AssetLoader.kt
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (C) 2024 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.shared.clocks
-
-import android.content.Context
-import android.content.res.Resources
-import android.graphics.Typeface
-import android.graphics.drawable.Drawable
-import android.util.TypedValue
-import com.android.internal.policy.SystemBarUtils
-import com.android.systemui.log.core.Logger
-import com.android.systemui.log.core.MessageBuffer
-import com.android.systemui.monet.Style as MonetStyle
-import java.io.IOException
-
-class AssetLoader
-private constructor(
- private val pluginCtx: Context,
- private val sysuiCtx: Context,
- private val baseDir: String,
- var seedColor: Int?,
- var overrideChroma: Float?,
- val typefaceCache: TypefaceCache,
- messageBuffer: MessageBuffer,
-) {
- val logger = Logger(messageBuffer, TAG)
- private val resources =
- listOf(
- Pair(pluginCtx.resources, pluginCtx.packageName),
- Pair(sysuiCtx.resources, sysuiCtx.packageName),
- )
-
- constructor(
- pluginCtx: Context,
- sysuiCtx: Context,
- baseDir: String,
- messageBuffer: MessageBuffer,
- ) : this(
- pluginCtx,
- sysuiCtx,
- baseDir,
- seedColor = null,
- overrideChroma = null,
- typefaceCache =
- TypefaceCache(messageBuffer) {
- // TODO(b/364680873): Move constant to config_clockFontFamily when shipping
- return@TypefaceCache Typeface.create("google-sans-flex-clock", Typeface.NORMAL)
- },
- messageBuffer = messageBuffer,
- )
-
- fun listAssets(path: String): List<String> {
- return pluginCtx.resources.assets.list("$baseDir$path")?.toList() ?: emptyList()
- }
-
- fun tryReadString(resStr: String): String? = tryRead(resStr, ::readString)
-
- fun readString(resStr: String): String {
- val resPair = resolveResourceId(resStr)
- if (resPair == null) {
- throw IOException("Failed to parse string: $resStr")
- }
-
- val (res, id) = resPair
- return res.getString(id)
- }
-
- fun readFontAsset(resStr: String): Typeface = typefaceCache.getTypeface(resStr)
-
- fun tryReadTextAsset(path: String?): String? = tryRead(path, ::readTextAsset)
-
- fun readTextAsset(path: String): String {
- return pluginCtx.resources.assets.open("$baseDir$path").use { stream ->
- val buffer = ByteArray(stream.available())
- stream.read(buffer)
- String(buffer)
- }
- }
-
- fun tryReadDrawableAsset(path: String?): Drawable? = tryRead(path, ::readDrawableAsset)
-
- fun readDrawableAsset(path: String): Drawable {
- var result: Drawable?
-
- if (path.startsWith("@")) {
- val pair = resolveResourceId(path)
- if (pair == null) {
- throw IOException("Failed to parse $path to an id")
- }
- val (res, id) = pair
- result = res.getDrawable(id)
- } else if (path.endsWith("xml")) {
- // TODO(b/248609434): Support xml files in assets
- throw IOException("Cannot load xml files from assets")
- } else {
- // Attempt to load as if it's a bitmap and directly loadable
- result =
- pluginCtx.resources.assets.open("$baseDir$path").use { stream ->
- Drawable.createFromResourceStream(
- pluginCtx.resources,
- TypedValue(),
- stream,
- null,
- )
- }
- }
-
- return result ?: throw IOException("Failed to load: $baseDir$path")
- }
-
- fun parseResourceId(resStr: String): Triple<String?, String, String> {
- if (!resStr.startsWith("@")) {
- throw IOException("Invalid resource id: $resStr; Must start with '@'")
- }
-
- // Parse out resource string
- val parts = resStr.drop(1).split('/', ':')
- return when (parts.size) {
- 2 -> Triple(null, parts[0], parts[1])
- 3 -> Triple(parts[0], parts[1], parts[2])
- else -> throw IOException("Failed to parse resource string: $resStr")
- }
- }
-
- fun resolveResourceId(resStr: String): Pair<Resources, Int>? {
- val (packageName, category, name) = parseResourceId(resStr)
- return resolveResourceId(packageName, category, name)
- }
-
- fun resolveResourceId(
- packageName: String?,
- category: String,
- name: String,
- ): Pair<Resources, Int>? {
- for ((res, ctxPkgName) in resources) {
- val result = res.getIdentifier(name, category, packageName ?: ctxPkgName)
- if (result != 0) {
- return Pair(res, result)
- }
- }
- return null
- }
-
- private fun <TArg : Any, TRes : Any> tryRead(arg: TArg?, fn: (TArg) -> TRes): TRes? {
- try {
- if (arg == null) {
- return null
- }
- return fn(arg)
- } catch (ex: IOException) {
- logger.w("Failed to read $arg", ex)
- return null
- }
- }
-
- fun assetExists(path: String): Boolean {
- try {
- if (path.startsWith("@")) {
- val pair = resolveResourceId(path)
- return pair != null
- } else {
- val stream = pluginCtx.resources.assets.open("$baseDir$path")
- if (stream == null) {
- return false
- }
-
- stream.close()
- return true
- }
- } catch (ex: IOException) {
- return false
- }
- }
-
- fun copy(messageBuffer: MessageBuffer? = null): AssetLoader =
- AssetLoader(
- pluginCtx,
- sysuiCtx,
- baseDir,
- seedColor,
- overrideChroma,
- typefaceCache,
- messageBuffer ?: logger.buffer,
- )
-
- fun setSeedColor(seedColor: Int?, style: MonetStyle?) {
- this.seedColor = seedColor
- }
-
- fun getClockPaddingStart(): Int {
- val result = resolveResourceId(null, "dimen", "clock_padding_start")
- if (result != null) {
- val (res, id) = result
- return res.getDimensionPixelSize(id)
- }
- return -1
- }
-
- fun getStatusBarHeight(): Int {
- val display = pluginCtx.getDisplayNoVerify()
- if (display != null) {
- return SystemBarUtils.getStatusBarHeight(pluginCtx.resources, display.cutout)
- }
-
- logger.w("No display available; falling back to android.R.dimen.status_bar_height")
- val statusBarHeight = resolveResourceId("android", "dimen", "status_bar_height")
- if (statusBarHeight != null) {
- val (res, resId) = statusBarHeight
- return res.getDimensionPixelSize(resId)
- }
-
- throw Exception("Could not fetch StatusBarHeight")
- }
-
- fun getResourcesId(name: String): Int = getResource("id", name) { _, id -> id }
-
- fun getDimen(name: String): Int = getResource("dimen", name, Resources::getDimensionPixelSize)
-
- fun getString(name: String): String = getResource("string", name, Resources::getString)
-
- private fun <T> getResource(
- category: String,
- name: String,
- getter: (res: Resources, id: Int) -> T,
- ): T {
- val result = resolveResourceId(null, category, name)
- if (result != null) {
- val (res, id) = result
- if (id == -1) throw Exception("Cannot find id of $id from $TAG")
- return getter(res, id)
- }
- throw Exception("Cannot find id of $name from $TAG")
- }
-
- companion object {
- private val TAG = AssetLoader::class.simpleName!!
- }
-}
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
index 4ed8fd8..d0a32dc 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
@@ -16,12 +16,9 @@
package com.android.systemui.shared.clocks
-import android.content.Context
-import android.content.res.Resources
import android.graphics.Rect
import androidx.annotation.VisibleForTesting
import com.android.systemui.log.core.Logger
-import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.AlarmData
import com.android.systemui.plugins.clocks.ClockAnimations
import com.android.systemui.plugins.clocks.ClockEvents
@@ -37,31 +34,22 @@
import java.util.TimeZone
class ComposedDigitalLayerController(
- private val ctx: Context,
- private val resources: Resources,
- private val assets: AssetLoader, // TODO(b/364680879): Remove and replace w/ resources
+ private val clockCtx: ClockContext,
private val layer: ComposedDigitalHandLayer,
- messageBuffer: MessageBuffer,
) : SimpleClockLayerController {
- private val logger = Logger(messageBuffer, ComposedDigitalLayerController::class.simpleName!!)
+ private val logger =
+ Logger(clockCtx.messageBuffer, ComposedDigitalLayerController::class.simpleName!!)
val layerControllers = mutableListOf<SimpleClockLayerController>()
val dozeState = DefaultClockController.AnimationState(1F)
- override val view = FlexClockView(ctx, assets, messageBuffer)
+ override val view = FlexClockView(clockCtx)
init {
layer.digitalLayers.forEach {
- val childView = SimpleDigitalClockTextView(ctx, messageBuffer)
+ val childView = SimpleDigitalClockTextView(clockCtx)
val controller =
- SimpleDigitalHandLayerController(
- ctx,
- resources,
- assets,
- it as DigitalHandLayer,
- childView,
- messageBuffer,
- )
+ SimpleDigitalHandLayerController(clockCtx, it as DigitalHandLayer, childView)
view.addView(childView)
layerControllers.add(controller)
@@ -156,8 +144,9 @@
val color =
when {
theme.seedColor != null -> theme.seedColor!!
- theme.isDarkTheme -> resources.getColor(android.R.color.system_accent1_100)
- else -> resources.getColor(android.R.color.system_accent2_600)
+ theme.isDarkTheme ->
+ clockCtx.resources.getColor(android.R.color.system_accent1_100)
+ else -> clockCtx.resources.getColor(android.R.color.system_accent2_600)
}
view.updateColor(color)
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
index be4ebdf..5317ac1 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
@@ -15,10 +15,10 @@
import android.content.Context
import android.content.res.Resources
+import android.graphics.Typeface
import android.view.LayoutInflater
import com.android.systemui.customization.R
-import com.android.systemui.log.core.LogLevel
-import com.android.systemui.log.core.LogcatOnlyMessageBuffer
+import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.ClockController
import com.android.systemui.plugins.clocks.ClockFontAxis
import com.android.systemui.plugins.clocks.ClockFontAxisSetting
@@ -33,6 +33,15 @@
private val TAG = DefaultClockProvider::class.simpleName
const val DEFAULT_CLOCK_ID = "DEFAULT"
+data class ClockContext(
+ val context: Context,
+ val resources: Resources,
+ val settings: ClockSettings,
+ val typefaceCache: TypefaceCache,
+ val messageBuffers: ClockMessageBuffers,
+ val messageBuffer: MessageBuffer,
+)
+
/** Provides the default system clock */
class DefaultClockProvider(
val ctx: Context,
@@ -55,18 +64,24 @@
}
return if (isClockReactiveVariantsEnabled) {
- val buffer =
- messageBuffers?.infraMessageBuffer ?: LogcatOnlyMessageBuffer(LogLevel.INFO)
- val assets = AssetLoader(ctx, ctx, "clocks/", buffer)
- assets.setSeedColor(settings.seedColor, null)
+ val buffers = messageBuffers ?: ClockMessageBuffers(LogUtil.DEFAULT_MESSAGE_BUFFER)
val fontAxes = ClockFontAxis.merge(FlexClockController.FONT_AXES, settings.axes)
+ val clockSettings = settings.copy(axes = fontAxes.map { it.toSetting() })
+ val typefaceCache =
+ TypefaceCache(buffers.infraMessageBuffer) {
+ // TODO(b/364680873): Move constant to config_clockFontFamily when shipping
+ return@TypefaceCache Typeface.create("google-sans-flex-clock", Typeface.NORMAL)
+ }
FlexClockController(
- ctx,
- resources,
- settings.copy(axes = fontAxes.map { it.toSetting() }),
- assets,
+ ClockContext(
+ ctx,
+ resources,
+ clockSettings,
+ typefaceCache,
+ buffers,
+ buffers.infraMessageBuffer,
+ ),
FLEX_DESIGN,
- messageBuffers,
)
} else {
DefaultClockController(
@@ -139,7 +154,7 @@
alignment =
DigitalAlignment(
HorizontalAlignment.CENTER,
- VerticalAlignment.CENTER,
+ VerticalAlignment.BASELINE,
),
dateTimeFormat = "hh",
),
@@ -158,7 +173,7 @@
alignment =
DigitalAlignment(
HorizontalAlignment.CENTER,
- VerticalAlignment.CENTER,
+ VerticalAlignment.BASELINE,
),
dateTimeFormat = "hh",
),
@@ -177,7 +192,7 @@
alignment =
DigitalAlignment(
HorizontalAlignment.CENTER,
- VerticalAlignment.CENTER,
+ VerticalAlignment.BASELINE,
),
dateTimeFormat = "mm",
),
@@ -196,7 +211,7 @@
alignment =
DigitalAlignment(
HorizontalAlignment.CENTER,
- VerticalAlignment.CENTER,
+ VerticalAlignment.BASELINE,
),
dateTimeFormat = "mm",
),
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
index 6c627e2..c7a3f63 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
@@ -16,8 +16,6 @@
package com.android.systemui.shared.clocks
-import android.content.Context
-import android.content.res.Resources
import com.android.systemui.customization.R
import com.android.systemui.plugins.clocks.AlarmData
import com.android.systemui.plugins.clocks.AxisType
@@ -26,8 +24,6 @@
import com.android.systemui.plugins.clocks.ClockEvents
import com.android.systemui.plugins.clocks.ClockFontAxis
import com.android.systemui.plugins.clocks.ClockFontAxisSetting
-import com.android.systemui.plugins.clocks.ClockMessageBuffers
-import com.android.systemui.plugins.clocks.ClockSettings
import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
@@ -38,42 +34,28 @@
/** Controller for the default flex clock */
class FlexClockController(
- private val ctx: Context,
- private val resources: Resources,
- private val settings: ClockSettings,
- private val assets: AssetLoader, // TODO(b/364680879): Remove and replace w/ resources
+ private val clockCtx: ClockContext,
val design: ClockDesign, // TODO(b/364680879): Remove when done inlining
- val messageBuffers: ClockMessageBuffers?,
) : ClockController {
- override val smallClock = run {
- val buffer = messageBuffers?.smallClockMessageBuffer ?: LogUtil.DEFAULT_MESSAGE_BUFFER
+ override val smallClock =
FlexClockFaceController(
- ctx,
- resources,
- assets.copy(messageBuffer = buffer),
+ clockCtx.copy(messageBuffer = clockCtx.messageBuffers.smallClockMessageBuffer),
design.small ?: design.large!!,
- false,
- buffer,
+ isLargeClock = false,
)
- }
- override val largeClock = run {
- val buffer = messageBuffers?.largeClockMessageBuffer ?: LogUtil.DEFAULT_MESSAGE_BUFFER
+ override val largeClock =
FlexClockFaceController(
- ctx,
- resources,
- assets.copy(messageBuffer = buffer),
+ clockCtx.copy(messageBuffer = clockCtx.messageBuffers.largeClockMessageBuffer),
design.large ?: design.small!!,
- true,
- buffer,
+ isLargeClock = true,
)
- }
override val config: ClockConfig by lazy {
ClockConfig(
DEFAULT_CLOCK_ID,
- resources.getString(R.string.clock_default_name),
- resources.getString(R.string.clock_default_description),
+ clockCtx.resources.getString(R.string.clock_default_name),
+ clockCtx.resources.getString(R.string.clock_default_description),
isReactiveToTone = true,
)
}
@@ -125,8 +107,8 @@
}
override fun initialize(isDarkTheme: Boolean, dozeFraction: Float, foldFraction: Float) {
- val theme = ThemeConfig(isDarkTheme, assets.seedColor)
- events.onFontAxesChanged(settings.axes)
+ val theme = ThemeConfig(isDarkTheme, clockCtx.settings.seedColor)
+ events.onFontAxesChanged(clockCtx.settings.axes)
smallClock.run {
events.onThemeChanged(theme)
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
index ee21ea6..a8890e6 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
@@ -16,15 +16,12 @@
package com.android.systemui.shared.clocks
-import android.content.Context
-import android.content.res.Resources
import android.graphics.Rect
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import com.android.systemui.customization.R
-import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.AlarmData
import com.android.systemui.plugins.clocks.ClockAnimations
import com.android.systemui.plugins.clocks.ClockEvents
@@ -45,22 +42,19 @@
// TODO(b/364680879): Merge w/ ComposedDigitalLayerController
class FlexClockFaceController(
- ctx: Context,
- private val resources: Resources,
- val assets: AssetLoader, // TODO(b/364680879): Remove and replace w/ resources
+ clockCtx: ClockContext,
face: ClockFace,
private val isLargeClock: Boolean,
- messageBuffer: MessageBuffer,
) : ClockFaceController {
override val view: View
get() = layerController.view
override val config = ClockFaceConfig(hasCustomPositionUpdatedAnimation = true)
- override var theme = ThemeConfig(true, assets.seedColor)
+ override var theme = ThemeConfig(true, clockCtx.settings.seedColor)
private val keyguardLargeClockTopMargin =
- resources.getDimensionPixelSize(R.dimen.keyguard_large_clock_top_margin)
+ clockCtx.resources.getDimensionPixelSize(R.dimen.keyguard_large_clock_top_margin)
val layerController: SimpleClockLayerController
val timespecHandler = DigitalTimespecHandler(DigitalTimespec.TIME_FULL_FORMAT, "hh:mm")
@@ -72,23 +66,10 @@
layerController =
if (isLargeClock) {
- ComposedDigitalLayerController(
- ctx,
- resources,
- assets,
- layer as ComposedDigitalHandLayer,
- messageBuffer,
- )
+ ComposedDigitalLayerController(clockCtx, layer as ComposedDigitalHandLayer)
} else {
- val childView = SimpleDigitalClockTextView(ctx, messageBuffer)
- SimpleDigitalHandLayerController(
- ctx,
- resources,
- assets,
- layer as DigitalHandLayer,
- childView,
- messageBuffer,
- )
+ val childView = SimpleDigitalClockTextView(clockCtx)
+ SimpleDigitalHandLayerController(clockCtx, layer as DigitalHandLayer, childView)
}
layerController.view.layoutParams = lp
}
@@ -97,7 +78,7 @@
private fun offsetGlyphsForStepClockAnimation(
clockStartLeft: Int,
direction: Int,
- fraction: Float
+ fraction: Float,
) {
(view as? FlexClockView)?.offsetGlyphsForStepClockAnimation(
clockStartLeft,
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
index 143b28f..ebac4b24 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
@@ -16,8 +16,6 @@
package com.android.systemui.shared.clocks
-import android.content.Context
-import android.content.res.Resources
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
@@ -25,7 +23,6 @@
import androidx.annotation.VisibleForTesting
import com.android.systemui.customization.R
import com.android.systemui.log.core.Logger
-import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.AlarmData
import com.android.systemui.plugins.clocks.ClockAnimations
import com.android.systemui.plugins.clocks.ClockEvents
@@ -42,14 +39,11 @@
private val TAG = SimpleDigitalHandLayerController::class.simpleName!!
open class SimpleDigitalHandLayerController<T>(
- private val ctx: Context,
- private val resources: Resources,
- private val assets: AssetLoader, // TODO(b/364680879): Remove and replace w/ resources
+ private val clockCtx: ClockContext,
private val layer: DigitalHandLayer,
override val view: T,
- messageBuffer: MessageBuffer,
) : SimpleClockLayerController where T : View, T : SimpleDigitalClockView {
- private val logger = Logger(messageBuffer, TAG)
+ private val logger = Logger(clockCtx.messageBuffer, TAG)
val timespec = DigitalTimespecHandler(layer.timespec, layer.dateTimeFormat)
@VisibleForTesting
@@ -75,12 +69,12 @@
layer.alignment.verticalAlignment?.let { view.verticalAlignment = it }
layer.alignment.horizontalAlignment?.let { view.horizontalAlignment = it }
}
- view.applyStyles(assets, layer.style, layer.aodStyle)
+ view.applyStyles(layer.style, layer.aodStyle)
view.id =
- ctx.resources.getIdentifier(
+ clockCtx.resources.getIdentifier(
generateDigitalLayerIdString(layer),
"id",
- ctx.getPackageName(),
+ clockCtx.context.getPackageName(),
)
}
@@ -306,8 +300,9 @@
val color =
when {
theme.seedColor != null -> theme.seedColor!!
- theme.isDarkTheme -> resources.getColor(android.R.color.system_accent1_100)
- else -> resources.getColor(android.R.color.system_accent2_600)
+ theme.isDarkTheme ->
+ clockCtx.resources.getColor(android.R.color.system_accent1_100)
+ else -> clockCtx.resources.getColor(android.R.color.system_accent2_600)
}
view.updateColor(color)
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
index b09332f..d4eb767 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
@@ -16,24 +16,23 @@
package com.android.systemui.shared.clocks.view
-import android.content.Context
import android.graphics.Canvas
import android.graphics.Point
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.VisibleForTesting
import com.android.systemui.log.core.Logger
-import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.AlarmData
import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
+import com.android.systemui.shared.clocks.ClockContext
import com.android.systemui.shared.clocks.LogUtil
import java.util.Locale
// TODO(b/364680879): Merge w/ only subclass FlexClockView
-abstract class DigitalClockFaceView(ctx: Context, messageBuffer: MessageBuffer) : FrameLayout(ctx) {
- protected val logger = Logger(messageBuffer, this::class.simpleName!!)
+abstract class DigitalClockFaceView(clockCtx: ClockContext) : FrameLayout(clockCtx.context) {
+ protected val logger = Logger(clockCtx.messageBuffer, this::class.simpleName!!)
get() = field ?: LogUtil.FALLBACK_INIT_LOGGER
abstract var digitalClockTextViewMap: MutableMap<Int, SimpleDigitalClockTextView>
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
index 593eba9..faef18c 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
@@ -16,31 +16,34 @@
package com.android.systemui.shared.clocks.view
-import android.content.Context
import android.graphics.Canvas
import android.graphics.Point
+import android.icu.text.NumberFormat
import android.util.MathUtils.constrainedMap
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.android.app.animation.Interpolators
import com.android.systemui.customization.R
-import com.android.systemui.log.core.MessageBuffer
-import com.android.systemui.shared.clocks.AssetLoader
+import com.android.systemui.shared.clocks.ClockContext
import com.android.systemui.shared.clocks.DigitTranslateAnimator
+import java.util.Locale
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun clamp(value: Float, minVal: Float, maxVal: Float): Float = max(min(value, maxVal), minVal)
-class FlexClockView(context: Context, val assets: AssetLoader, messageBuffer: MessageBuffer) :
- DigitalClockFaceView(context, messageBuffer) {
+class FlexClockView(clockCtx: ClockContext) : DigitalClockFaceView(clockCtx) {
override var digitalClockTextViewMap = mutableMapOf<Int, SimpleDigitalClockTextView>()
- val digitLeftTopMap = mutableMapOf<Int, Point>()
- var maxSingleDigitSize = Point(-1, -1)
- val lockscreenTranslate = Point(0, 0)
- var aodTranslate = Point(0, 0)
+ private val digitLeftTopMap = mutableMapOf<Int, Point>()
+
+ private var maxSingleDigitSize = Point(-1, -1)
+ private val lockscreenTranslate = Point(0, 0)
+ private var aodTranslate = Point(0, 0)
+
+ // Does the current language have mono vertical size when displaying numerals
+ private var isMonoVerticalNumericLineSpacing = true
init {
setWillNotDraw(false)
@@ -49,6 +52,7 @@
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
)
+ updateLocale(Locale.getDefault())
}
private val digitOffsets = mutableMapOf<Int, Float>()
@@ -61,12 +65,19 @@
protected override fun calculateSize(widthMeasureSpec: Int, heightMeasureSpec: Int): Point {
maxSingleDigitSize = Point(-1, -1)
+ val bottomLocation: (textView: SimpleDigitalClockTextView) -> Int = { textView ->
+ if (isMonoVerticalNumericLineSpacing) {
+ maxSingleDigitSize.y
+ } else {
+ (textView.paint.fontMetrics.descent - textView.paint.fontMetrics.ascent).toInt()
+ }
+ }
+
digitalClockTextViewMap.forEach { (_, textView) ->
textView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
maxSingleDigitSize.x = max(maxSingleDigitSize.x, textView.measuredWidth)
- maxSingleDigitSize.y = max(maxSingleDigitSize.y, textView.measuredHeight)
+ maxSingleDigitSize.y = max(bottomLocation(textView), textView.measuredHeight)
}
- val textView = digitalClockTextViewMap[R.id.HOUR_FIRST_DIGIT]!!
aodTranslate = Point(0, 0)
return Point(
((maxSingleDigitSize.x + abs(aodTranslate.x)) * 2),
@@ -106,6 +117,11 @@
}
}
+ override fun onLocaleChanged(locale: Locale) {
+ updateLocale(locale)
+ requestLayout()
+ }
+
override fun animateDoze(isDozing: Boolean, isAnimated: Boolean) {
dozeControlState.animateDoze = {
super.animateDoze(isDozing, isAnimated)
@@ -166,6 +182,18 @@
}
}
+ private fun updateLocale(locale: Locale) {
+ isMonoVerticalNumericLineSpacing =
+ !NON_MONO_VERTICAL_NUMERIC_LINE_SPACING_LANGUAGES.any {
+ val newLocaleNumberFormat =
+ NumberFormat.getInstance(locale).format(FORMAT_NUMBER.toLong())
+ val nonMonoVerticalNumericLineSpaceNumberFormat =
+ NumberFormat.getInstance(Locale.forLanguageTag(it))
+ .format(FORMAT_NUMBER.toLong())
+ newLocaleNumberFormat == nonMonoVerticalNumericLineSpaceNumberFormat
+ }
+ }
+
/**
* Offsets the textViews of the clock for the step clock animation.
*
@@ -264,10 +292,18 @@
// Constants for the animation
private val MOVE_INTERPOLATOR = Interpolators.EMPHASIZED
+ private const val FORMAT_NUMBER = 1234567890
+
// Total available transition time for each digit, taking into account the step. If step is
// 0.1, then digit 0 would animate over 0.0 - 0.7, making availableTime 0.7.
private const val AVAILABLE_ANIMATION_TIME = 1.0f - MOVE_DIGIT_STEP * (NUM_DIGITS - 1)
+ // Add language tags below that do not have vertically mono spaced numerals
+ private val NON_MONO_VERTICAL_NUMERIC_LINE_SPACING_LANGUAGES =
+ setOf(
+ "my", // Burmese
+ )
+
// Use the sign of targetTranslation to control the direction of digit translation
fun updateDirectionalTargetTranslate(id: Int, targetTranslation: Point): Point {
val outPoint = Point(targetTranslation)
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
index 5c84f2d..48761c0 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
@@ -17,7 +17,6 @@
package com.android.systemui.shared.clocks.view
import android.annotation.SuppressLint
-import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
@@ -37,13 +36,11 @@
import android.widget.TextView
import com.android.internal.annotations.VisibleForTesting
import com.android.systemui.animation.TextAnimator
-import com.android.systemui.animation.TypefaceVariantCache
import com.android.systemui.customization.R
import com.android.systemui.log.core.Logger
-import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.ClockFontAxisSetting
-import com.android.systemui.shared.clocks.AssetLoader
import com.android.systemui.shared.clocks.ClockAnimation
+import com.android.systemui.shared.clocks.ClockContext
import com.android.systemui.shared.clocks.DigitTranslateAnimator
import com.android.systemui.shared.clocks.DimensionParser
import com.android.systemui.shared.clocks.FontTextStyle
@@ -57,18 +54,15 @@
private val TAG = SimpleDigitalClockTextView::class.simpleName!!
@SuppressLint("AppCompatCustomView")
-open class SimpleDigitalClockTextView(
- ctx: Context,
- messageBuffer: MessageBuffer,
- attrs: AttributeSet? = null,
-) : TextView(ctx, attrs), SimpleDigitalClockView {
+open class SimpleDigitalClockTextView(clockCtx: ClockContext, attrs: AttributeSet? = null) :
+ TextView(clockCtx.context, attrs), SimpleDigitalClockView {
val lockScreenPaint = TextPaint()
override lateinit var textStyle: FontTextStyle
lateinit var aodStyle: FontTextStyle
private var lsFontVariation = ClockFontAxisSetting.toFVar(DEFAULT_LS_VARIATION)
private var aodFontVariation = ClockFontAxisSetting.toFVar(DEFAULT_AOD_VARIATION)
- private val parser = DimensionParser(ctx)
+ private val parser = DimensionParser(clockCtx.context)
var maxSingleDigitHeight = -1
var maxSingleDigitWidth = -1
var digitTranslateAnimator: DigitTranslateAnimator? = null
@@ -91,33 +85,23 @@
private val prevTextBounds = Rect()
// targetTextBounds holds the state we are interpolating to
private val targetTextBounds = Rect()
- protected val logger = Logger(messageBuffer, this::class.simpleName!!)
+ protected val logger = Logger(clockCtx.messageBuffer, this::class.simpleName!!)
get() = field ?: LogUtil.FALLBACK_INIT_LOGGER
private var aodDozingInterpolator: Interpolator? = null
@VisibleForTesting lateinit var textAnimator: TextAnimator
- lateinit var typefaceCache: TypefaceVariantCache
- private set
-
- private fun setTypefaceCache(value: TypefaceVariantCache) {
- typefaceCache = value
- if (this::textAnimator.isInitialized) {
- textAnimator.typefaceCache = value
- }
- }
+ private val typefaceCache = clockCtx.typefaceCache.getVariantCache("")
@VisibleForTesting
var textAnimatorFactory: (Layout, () -> Unit) -> TextAnimator = { layout, invalidateCb ->
TextAnimator(layout, ClockAnimation.NUM_CLOCK_FONT_ANIMATION_STEPS, invalidateCb).also {
- if (this::typefaceCache.isInitialized) {
- it.typefaceCache = typefaceCache
- }
+ it.typefaceCache = typefaceCache
}
}
- override var verticalAlignment: VerticalAlignment = VerticalAlignment.CENTER
+ override var verticalAlignment: VerticalAlignment = VerticalAlignment.BASELINE
override var horizontalAlignment: HorizontalAlignment = HorizontalAlignment.LEFT
override var isAnimationEnabled = true
override var dozeFraction: Float = 0F
@@ -258,7 +242,7 @@
-translation.y.toFloat(),
(-translation.x + measuredWidth).toFloat(),
(-translation.y + measuredHeight).toFloat(),
- Paint().also { it.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) },
+ PORTER_DUFF_XFER_MODE_PAINT,
)
canvas.restore()
canvas.restore()
@@ -403,7 +387,7 @@
// translation of reference point of text
// used for translation when calling textInterpolator
- fun getLocalTranslation(): Point {
+ private fun getLocalTranslation(): Point {
val viewHeight = if (isVertical) measuredWidth else measuredHeight
val interpolatedTextBounds = updateInterpolatedTextBounds()
val localTranslation = Point(0, 0)
@@ -429,17 +413,18 @@
correctedBaseline
}
VerticalAlignment.BASELINE -> {
- localTranslation.y = -lockScreenPaint.strokeWidth.toInt()
+ // account for max bottom distance of font, so clock doesn't collide with elements
+ localTranslation.y =
+ -lockScreenPaint.strokeWidth.toInt() - paint.fontMetrics.descent.toInt()
}
}
return updateXtranslation(localTranslation, interpolatedTextBounds)
}
- override fun applyStyles(assets: AssetLoader, textStyle: TextStyle, aodStyle: TextStyle?) {
+ override fun applyStyles(textStyle: TextStyle, aodStyle: TextStyle?) {
this.textStyle = textStyle as FontTextStyle
val typefaceName = "fonts/" + textStyle.fontFamily
- setTypefaceCache(assets.typefaceCache.getVariantCache(typefaceName))
lockScreenPaint.strokeJoin = Paint.Join.ROUND
lockScreenPaint.typeface = typefaceCache.getTypefaceForVariant(lsFontVariation)
textStyle.fontFeatureSettings?.let {
@@ -550,7 +535,9 @@
}
companion object {
- val AOD_STROKE_WIDTH = "2dp"
+ private val PORTER_DUFF_XFER_MODE_PAINT =
+ Paint().also { it.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) }
+
val AOD_COLOR = Color.WHITE
val OPTICAL_SIZE_AXIS = ClockFontAxisSetting("opsz", 144f)
val DEFAULT_LS_VARIATION =
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
index 3d2ed4a1..e8be28f 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
@@ -18,7 +18,6 @@
import androidx.annotation.VisibleForTesting
import com.android.systemui.plugins.clocks.ClockFontAxisSetting
-import com.android.systemui.shared.clocks.AssetLoader
import com.android.systemui.shared.clocks.TextStyle
interface SimpleDigitalClockView {
@@ -29,7 +28,7 @@
val textStyle: TextStyle
@VisibleForTesting var isAnimationEnabled: Boolean
- fun applyStyles(assets: AssetLoader, textStyle: TextStyle, aodStyle: TextStyle?)
+ fun applyStyles(textStyle: TextStyle, aodStyle: TextStyle?)
fun applyTextSize(targetFontSizePx: Float?, constrainedByHeight: Boolean = false)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/keyguard/KeyguardDisplayManagerTest.kt b/packages/SystemUI/multivalentTests/src/com/android/keyguard/KeyguardDisplayManagerTest.kt
index 57a6797..85bdf92 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/keyguard/KeyguardDisplayManagerTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/keyguard/KeyguardDisplayManagerTest.kt
@@ -28,7 +28,7 @@
import com.android.systemui.SysuiTestCase
import com.android.systemui.navigationbar.NavigationBarController
import com.android.systemui.settings.FakeDisplayTracker
-import com.android.systemui.shade.data.repository.FakeShadePositionRepository
+import com.android.systemui.shade.data.repository.FakeShadeDisplayRepository
import com.android.systemui.statusbar.policy.KeyguardStateController
import java.util.concurrent.Executor
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -62,7 +62,7 @@
mock(ConnectedDisplayKeyguardPresentation::class.java)
@Mock private val deviceStateHelper = mock(DeviceStateHelper::class.java)
@Mock private val keyguardStateController = mock(KeyguardStateController::class.java)
- private val shadePositionRepository = FakeShadePositionRepository()
+ private val shadePositionRepository = FakeShadeDisplayRepository()
private val mainExecutor = Executor { it.run() }
private val backgroundExecutor = Executor { it.run() }
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModelTest.kt
index baeb2dd..0084e18 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModelTest.kt
@@ -16,38 +16,64 @@
package com.android.systemui.communal.ui.viewmodel
-import androidx.test.ext.junit.runners.AndroidJUnit4
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
+import android.platform.test.flag.junit.FlagsParameterization
import androidx.test.filters.SmallTest
+import com.android.compose.animation.scene.ObservableTransitionState
+import com.android.compose.animation.scene.SceneKey
+import com.android.systemui.Flags.FLAG_SCENE_CONTAINER
import com.android.systemui.SysuiTestCase
import com.android.systemui.communal.data.repository.fakeCommunalSceneRepository
import com.android.systemui.communal.shared.model.CommunalScenes
import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.andSceneContainer
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.kosmos.testScope
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4
+import platform.test.runner.parameterized.Parameters
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
-@RunWith(AndroidJUnit4::class)
-class CommunalTransitionViewModelTest : SysuiTestCase() {
+@RunWith(ParameterizedAndroidJunit4::class)
+class CommunalTransitionViewModelTest(flags: FlagsParameterization) : SysuiTestCase() {
+
+ companion object {
+ @JvmStatic
+ @Parameters(name = "{0}")
+ fun getParams(): List<FlagsParameterization> {
+ return FlagsParameterization.allCombinationsOf().andSceneContainer()
+ }
+ }
+
+ init {
+ mSetFlagsRule.setFlagsParameterization(flags)
+ }
+
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
private val keyguardTransitionRepository = kosmos.fakeKeyguardTransitionRepository
private val communalSceneRepository = kosmos.fakeCommunalSceneRepository
+ private val sceneInteractor = kosmos.sceneInteractor
private val underTest: CommunalTransitionViewModel by lazy {
kosmos.communalTransitionViewModel
}
+ @DisableFlags(FLAG_SCENE_CONTAINER)
@Test
fun testIsUmoOnCommunalDuringTransitionBetweenLockscreenAndGlanceableHub() =
testScope.runTest {
@@ -61,6 +87,7 @@
assertThat(isUmoOnCommunal).isFalse()
}
+ @DisableFlags(FLAG_SCENE_CONTAINER)
@Test
fun testIsUmoOnCommunalDuringTransitionBetweenDreamingAndGlanceableHub() =
testScope.runTest {
@@ -74,6 +101,7 @@
assertThat(isUmoOnCommunal).isFalse()
}
+ @DisableFlags(FLAG_SCENE_CONTAINER)
@Test
fun testIsUmoOnCommunalDuringTransitionBetweenOccludedAndGlanceableHub() =
testScope.runTest {
@@ -87,6 +115,7 @@
assertThat(isUmoOnCommunal).isFalse()
}
+ @DisableFlags(FLAG_SCENE_CONTAINER)
@Test
fun isUmoOnCommunal_noLongerVisible_returnsFalse() =
testScope.runTest {
@@ -103,6 +132,7 @@
assertThat(isUmoOnCommunal).isFalse()
}
+ @DisableFlags(FLAG_SCENE_CONTAINER)
@Test
fun isUmoOnCommunal_idleOnCommunal_returnsTrue() =
testScope.runTest {
@@ -116,11 +146,25 @@
assertThat(isUmoOnCommunal).isTrue()
}
+ @EnableFlags(FLAG_SCENE_CONTAINER)
+ @Test
+ fun isUmoOnCommunal_sceneContainerEnabled_idleOnCommunal_returnsTrue() =
+ testScope.runTest {
+ val isUmoOnCommunal by collectLastValue(underTest.isUmoOnCommunal)
+ assertThat(isUmoOnCommunal).isFalse()
+
+ // Change to communal scene.
+ setIdleScene(Scenes.Communal)
+
+ // isUmoOnCommunal returns true, even without any keyguard transition.
+ assertThat(isUmoOnCommunal).isTrue()
+ }
+
private suspend fun TestScope.enterCommunal(from: KeyguardState) {
keyguardTransitionRepository.sendTransitionSteps(
from = from,
to = KeyguardState.GLANCEABLE_HUB,
- testScope
+ testScope,
)
communalSceneRepository.changeScene(CommunalScenes.Communal)
runCurrent()
@@ -130,9 +174,17 @@
keyguardTransitionRepository.sendTransitionSteps(
from = KeyguardState.GLANCEABLE_HUB,
to = to,
- testScope
+ testScope,
)
communalSceneRepository.changeScene(CommunalScenes.Blank)
runCurrent()
}
+
+ private fun setIdleScene(scene: SceneKey) {
+ sceneInteractor.changeScene(scene, "test")
+ val transitionState =
+ MutableStateFlow<ObservableTransitionState>(ObservableTransitionState.Idle(scene))
+ sceneInteractor.setTransitionState(transitionState)
+ testScope.runCurrent()
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalEditModeViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalEditModeViewModelTest.kt
index 6b851cb..5bbd3ff 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalEditModeViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalEditModeViewModelTest.kt
@@ -56,6 +56,7 @@
import com.android.systemui.kosmos.testDispatcher
import com.android.systemui.kosmos.testScope
import com.android.systemui.log.logcatLogBuffer
+import com.android.systemui.media.controls.ui.controller.mediaCarouselController
import com.android.systemui.media.controls.ui.view.MediaHost
import com.android.systemui.settings.fakeUserTracker
import com.android.systemui.testKosmos
@@ -133,6 +134,7 @@
accessibilityManager,
packageManager,
WIDGET_PICKER_PACKAGE_NAME,
+ kosmos.mediaCarouselController,
)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
index 09daa51..3eba8ff 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
@@ -69,6 +69,7 @@
import com.android.systemui.kosmos.testScope
import com.android.systemui.log.logcatLogBuffer
import com.android.systemui.media.controls.ui.controller.MediaHierarchyManager
+import com.android.systemui.media.controls.ui.controller.mediaCarouselController
import com.android.systemui.media.controls.ui.view.MediaHost
import com.android.systemui.power.domain.interactor.PowerInteractor.Companion.setAwakeForTest
import com.android.systemui.power.domain.interactor.powerInteractor
@@ -178,6 +179,7 @@
mediaHost,
logcatLogBuffer("CommunalViewModelTest"),
metricsLogger,
+ kosmos.mediaCarouselController,
)
}
@@ -627,10 +629,7 @@
kosmos.setTransition(
sceneTransition = Idle(Scenes.Communal),
stateTransition =
- TransitionStep(
- from = KeyguardState.DREAMING,
- to = KeyguardState.GLANCEABLE_HUB
- ),
+ TransitionStep(from = KeyguardState.DREAMING, to = KeyguardState.GLANCEABLE_HUB),
)
// Then flow is not frozen
@@ -647,10 +646,7 @@
kosmos.setTransition(
sceneTransition = Idle(Scenes.Lockscreen),
stateTransition =
- TransitionStep(
- from = KeyguardState.GLANCEABLE_HUB,
- to = KeyguardState.OCCLUDED
- ),
+ TransitionStep(from = KeyguardState.GLANCEABLE_HUB, to = KeyguardState.OCCLUDED),
)
// Then flow is not frozen
@@ -735,10 +731,7 @@
kosmos.setTransition(
sceneTransition = Idle(Scenes.Communal),
stateTransition =
- TransitionStep(
- from = KeyguardState.DREAMING,
- to = KeyguardState.GLANCEABLE_HUB
- ),
+ TransitionStep(from = KeyguardState.DREAMING, to = KeyguardState.GLANCEABLE_HUB),
)
// Widgets available
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelTest.kt
index b72668b..921a8a6 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelTest.kt
@@ -41,8 +41,8 @@
import com.android.systemui.res.R
import com.android.systemui.shade.largeScreenHeaderHelper
import com.android.systemui.statusbar.StatusBarState
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.sysuiStatusBarStateController
import com.android.systemui.util.animation.DisappearParameters
import com.google.common.truth.Truth.assertThat
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
index 01c17bd..94a19c8 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
@@ -148,7 +148,6 @@
import com.android.systemui.statusbar.StatusBarStateControllerImpl;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.disableflags.data.repository.FakeDisableFlagsRepository;
import com.android.systemui.statusbar.notification.ConversationNotificationManager;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
import com.android.systemui.statusbar.notification.HeadsUpTouchHelper;
@@ -428,7 +427,7 @@
mShadeInteractor = new ShadeInteractorImpl(
mTestScope.getBackgroundScope(),
mKosmos.getDeviceProvisioningInteractor(),
- new FakeDisableFlagsRepository(),
+ mKosmos.getDisableFlagsInteractor(),
mDozeParameters,
mFakeKeyguardRepository,
mKeyguardTransitionInteractor,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplBaseTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplBaseTest.java
index 443595d..ef132d5 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplBaseTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplBaseTest.java
@@ -149,7 +149,7 @@
@Mock protected LargeScreenHeaderHelper mLargeScreenHeaderHelper;
protected FakeDisableFlagsRepository mDisableFlagsRepository =
- new FakeDisableFlagsRepository();
+ mKosmos.getFakeDisableFlagsRepository();
protected FakeKeyguardRepository mKeyguardRepository = new FakeKeyguardRepository();
protected FakeShadeRepository mShadeRepository = new FakeShadeRepository();
@@ -185,7 +185,7 @@
mShadeInteractor = new ShadeInteractorImpl(
mTestScope.getBackgroundScope(),
mKosmos.getDeviceProvisioningInteractor(),
- mDisableFlagsRepository,
+ mKosmos.getDisableFlagsInteractor(),
mDozeParameters,
mKeyguardRepository,
keyguardTransitionInteractor,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplWithCoroutinesTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplWithCoroutinesTest.kt
index 46961d4..ee3f801 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplWithCoroutinesTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/QuickSettingsControllerImplWithCoroutinesTest.kt
@@ -19,7 +19,7 @@
import android.app.StatusBarManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelChildren
@@ -61,7 +61,7 @@
mDisableFlagsRepository.disableFlags.value =
DisableFlagsModel(
StatusBarManager.DISABLE_NONE,
- StatusBarManager.DISABLE2_QUICK_SETTINGS
+ StatusBarManager.DISABLE2_QUICK_SETTINGS,
)
runCurrent()
@@ -76,7 +76,7 @@
mDisableFlagsRepository.disableFlags.value =
DisableFlagsModel(
StatusBarManager.DISABLE_NONE,
- StatusBarManager.DISABLE2_NOTIFICATION_SHADE
+ StatusBarManager.DISABLE2_NOTIFICATION_SHADE,
)
runCurrent()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepositoryTest.kt
similarity index 95%
rename from packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepositoryTest.kt
index a9a5cac..4e7839e 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepositoryTest.kt
@@ -34,13 +34,13 @@
@SmallTest
@RunWith(AndroidJUnit4::class)
-class ShadePositionRepositoryTest : SysuiTestCase() {
+class ShadeDisplaysRepositoryTest : SysuiTestCase() {
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
private val commandRegistry = kosmos.commandRegistry
private val pw = PrintWriter(StringWriter())
- private val underTest = ShadePositionRepositoryImpl(commandRegistry)
+ private val underTest = ShadeDisplaysRepositoryImpl(commandRegistry)
@Before
fun setUp() {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorTest.kt
index f192b59..8ef1e56 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorTest.kt
@@ -28,7 +28,7 @@
import com.android.systemui.display.data.repository.FakeDisplayWindowPropertiesRepository
import com.android.systemui.display.shared.model.DisplayWindowProperties
import com.android.systemui.scene.ui.view.WindowRootView
-import com.android.systemui.shade.data.repository.FakeShadePositionRepository
+import com.android.systemui.shade.data.repository.FakeShadeDisplayRepository
import com.android.systemui.statusbar.phone.ConfigurationForwarder
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
@@ -50,7 +50,7 @@
class ShadeDisplaysInteractorTest : SysuiTestCase() {
private val shadeRootview = mock<WindowRootView>()
- private val positionRepository = FakeShadePositionRepository()
+ private val positionRepository = FakeShadeDisplayRepository()
private val defaultContext = mock<Context>()
private val secondaryContext = mock<Context>()
private val contextStore = FakeDisplayWindowPropertiesRepository()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImplTest.kt
index 19ac0cf..da652c4 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImplTest.kt
@@ -37,8 +37,8 @@
import com.android.systemui.power.shared.model.WakeSleepReason
import com.android.systemui.power.shared.model.WakefulnessState
import com.android.systemui.shade.shadeTestUtil
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.phone.dozeParameters
import com.android.systemui.statusbar.policy.data.repository.fakeDeviceProvisioningRepository
import com.android.systemui.statusbar.policy.data.repository.fakeUserSetupRepository
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepositoryTest.kt
index 907c684..cd07821 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepositoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepositoryTest.kt
@@ -32,7 +32,7 @@
import com.android.systemui.res.R
import com.android.systemui.statusbar.CommandQueue
import com.android.systemui.statusbar.disableflags.DisableFlagsLogger
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.policy.ConfigurationController
import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler
import com.android.systemui.statusbar.policy.ResourcesSplitShadeStateController
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractorTest.kt
index 79ff4be..7eac7e8 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractorTest.kt
@@ -21,8 +21,8 @@
import com.android.systemui.SysUITestModule
import com.android.systemui.SysuiTestCase
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
import com.android.systemui.statusbar.disableflags.data.repository.FakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.google.common.truth.Truth.assertThat
import dagger.BindsInstance
import dagger.Component
@@ -51,10 +51,7 @@
fun disableFlags_notifAlertsNotDisabled_notifAlertsEnabledTrue() =
with(testComponent) {
disableFlags.disableFlags.value =
- DisableFlagsModel(
- StatusBarManager.DISABLE_NONE,
- StatusBarManager.DISABLE2_NONE,
- )
+ DisableFlagsModel(StatusBarManager.DISABLE_NONE, StatusBarManager.DISABLE2_NONE)
assertThat(underTest.areNotificationAlertsEnabled()).isTrue()
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorTest.kt
index 46f822a..db24d4b 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorTest.kt
@@ -21,18 +21,18 @@
import android.app.StatusBarManager.DISABLE_NONE
import android.app.StatusBarManager.DISABLE_NOTIFICATION_ICONS
import android.app.StatusBarManager.DISABLE_SYSTEM_INFO
-import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.kosmos.testScope
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
import kotlin.test.Test
import kotlinx.coroutines.test.runTest
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/ui/viewmodel/HomeStatusBarViewModelImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/ui/viewmodel/HomeStatusBarViewModelImplTest.kt
index c4d2569..b9cdd06 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/ui/viewmodel/HomeStatusBarViewModelImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/shared/ui/viewmodel/HomeStatusBarViewModelImplTest.kt
@@ -58,8 +58,8 @@
import com.android.systemui.statusbar.data.model.StatusBarMode
import com.android.systemui.statusbar.data.repository.FakeStatusBarModeRepository.Companion.DISPLAY_ID
import com.android.systemui.statusbar.data.repository.fakeStatusBarModeRepository
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.events.data.repository.systemStatusEventAnimationRepository
import com.android.systemui.statusbar.events.shared.model.SystemEventAnimationState.AnimatingIn
import com.android.systemui.statusbar.events.shared.model.SystemEventAnimationState.AnimatingOut
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
index d823bf5..4eef308 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
@@ -27,10 +27,14 @@
import android.platform.test.annotations.EnableFlags
import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID
import android.testing.TestableLooper
+import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.Flags.FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT
import com.android.systemui.SysuiTestCase
import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.kosmos.useUnconfinedTestDispatcher
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.table.logcatTableLogBuffer
import com.android.systemui.statusbar.connectivity.WifiPickerTrackerFactory
@@ -40,9 +44,7 @@
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiScanEntry
import com.android.systemui.testKosmos
import com.android.systemui.user.data.repository.fakeUserRepository
-import com.android.systemui.user.data.repository.userRepository
import com.android.systemui.util.concurrency.FakeExecutor
-import com.android.systemui.util.mockito.argumentCaptor
import com.android.systemui.util.time.fakeSystemClock
import com.android.wifitrackerlib.HotspotNetworkEntry
import com.android.wifitrackerlib.HotspotNetworkEntry.DeviceType
@@ -53,31 +55,23 @@
import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_UNREACHABLE
import com.android.wifitrackerlib.WifiPickerTracker
import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.test.StandardTestDispatcher
-import kotlinx.coroutines.test.TestScope
-import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
+import org.junit.runner.RunWith
import org.mockito.kotlin.any
-import org.mockito.kotlin.capture
+import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
-import org.mockito.kotlin.times
+import org.mockito.kotlin.never
+import org.mockito.kotlin.reset
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
-/**
- * Note: Most of these tests are duplicates of [WifiRepositoryImplTest] tests.
- *
- * Any new tests added here may also need to be added to [WifiRepositoryImplTest].
- */
-@Suppress("EXPERIMENTAL_IS_NOT_ENABLED")
-@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
+@RunWith(AndroidJUnit4::class)
@TestableLooper.RunWithLooper(setAsMainLooper = true)
-class WifiRepositoryImplTest() : SysuiTestCase() {
- private val kosmos = testKosmos()
+class WifiRepositoryImplTest : SysuiTestCase() {
+ private val kosmos = testKosmos().useUnconfinedTestDispatcher()
private val userRepository = kosmos.fakeUserRepository
// Using lazy means that the class will only be constructed once it's fetched. Because the
@@ -108,13 +102,13 @@
private val callbackCaptor = argumentCaptor<WifiPickerTracker.WifiPickerTrackerCallback>()
- private val dispatcher = StandardTestDispatcher()
- private val testScope = TestScope(dispatcher)
+ private val dispatcher = kosmos.testDispatcher
+ private val testScope = kosmos.testScope
@Before
fun setUp() {
userRepository.setUserInfos(listOf(PRIMARY_USER, ANOTHER_USER))
- whenever(wifiPickerTrackerFactory.create(any(), any(), capture(callbackCaptor), any()))
+ whenever(wifiPickerTrackerFactory.create(any(), any(), callbackCaptor.capture(), any()))
.thenReturn(wifiPickerTracker)
}
@@ -122,7 +116,6 @@
fun wifiPickerTrackerCreation_scansDisabled() =
testScope.runTest {
collectLastValue(underTest.wifiNetwork)
- testScope.runCurrent()
verify(wifiPickerTracker).disableScanning()
}
@@ -1001,7 +994,6 @@
mock<WifiEntry>().apply { whenever(this.isPrimaryNetwork).thenReturn(false) }
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
}
@@ -1017,7 +1009,6 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
}
@@ -1034,7 +1025,6 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
}
@@ -1051,7 +1041,6 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
}
@@ -1068,7 +1057,6 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
}
@@ -1085,7 +1073,6 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isTrue()
}
@@ -1103,14 +1090,12 @@
}
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
assertThat(underTest.isWifiConnectedWithValidSsid()).isTrue()
// WHEN the network is lost
whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(null)
getCallback().onWifiEntriesChanged()
- testScope.runCurrent()
// THEN the isWifiConnected updates
assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
@@ -1216,9 +1201,6 @@
assertThat(latest).isEmpty()
}
- // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
- // this needs to
- // be updated to capture the argument instead so currentUserContext can be private.
@Test
@EnableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
fun oneUserVerifyCreatingWifiPickerTracker_multiuserFlagEnabled() =
@@ -1230,16 +1212,16 @@
)
userRepository.setSelectedUserInfo(PRIMARY_USER)
- runCurrent()
- val currentUserContext by collectLastValue(underTest.selectedUserContext)
- assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
- verify(wifiPickerTrackerFactory).create(any(), any(), any(), any())
+ collectLastValue(underTest.wifiNetwork)
+
+ val contextCaptor = argumentCaptor<Context>()
+ verify(wifiPickerTrackerFactory).create(contextCaptor.capture(), any(), any(), any())
+ // If the flag is on, verify that we use the context from #createContextAsUser and we
+ // do NOT use the top-level context
+ assertThat(contextCaptor.firstValue).isEqualTo(primaryUserMockContext)
}
- // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
- // this needs to
- // be updated to capture the argument instead so currentUserContext can be private.
@Test
@EnableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
fun changeUserVerifyCreatingWifiPickerTracker_multiuserEnabled() =
@@ -1249,32 +1231,30 @@
UserHandle.of(PRIMARY_USER_ID),
primaryUserMockContext,
)
-
- runCurrent()
userRepository.setSelectedUserInfo(PRIMARY_USER)
- runCurrent()
- val currentUserContext by collectLastValue(underTest.selectedUserContext)
- assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
+ collectLastValue(underTest.wifiNetwork)
+ val contextCaptor = argumentCaptor<Context>()
+ verify(wifiPickerTrackerFactory).create(contextCaptor.capture(), any(), any(), any())
+ assertThat(contextCaptor.firstValue).isEqualTo(primaryUserMockContext)
+
+ reset(wifiPickerTrackerFactory)
+
+ // WHEN we switch to a different user
val otherUserMockContext = mock<Context>()
mContext.prepareCreateContextAsUser(
UserHandle.of(ANOTHER_USER_ID),
otherUserMockContext,
)
-
- runCurrent()
userRepository.setSelectedUserInfo(ANOTHER_USER)
- runCurrent()
- val otherUserContext by collectLastValue(underTest.selectedUserContext)
- assertThat(otherUserContext).isEqualTo(otherUserMockContext)
- verify(wifiPickerTrackerFactory, times(2)).create(any(), any(), any(), any())
+ // THEN we use the different user's context to create WifiPickerTracker
+ val newCaptor = argumentCaptor<Context>()
+ verify(wifiPickerTrackerFactory).create(newCaptor.capture(), any(), any(), any())
+ assertThat(newCaptor.firstValue).isEqualTo(otherUserMockContext)
}
- // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
- // this needs to
- // be updated to capture the argument instead so currentUserContext can be private.
@Test
@DisableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
fun changeUserVerifyCreatingWifiPickerTracker_multiuserDisabled() =
@@ -1285,36 +1265,39 @@
primaryUserMockContext,
)
- runCurrent()
userRepository.setSelectedUserInfo(PRIMARY_USER)
- runCurrent()
- val currentUserContext by collectLastValue(underTest.selectedUserContext)
- assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
+ collectLastValue(underTest.wifiNetwork)
+ val contextCaptor = argumentCaptor<Context>()
+ verify(wifiPickerTrackerFactory).create(contextCaptor.capture(), any(), any(), any())
+ // If the flag is off, verify that we do NOT use the context from #createContextAsUser
+ // and we instead use the top-level context
+ assertThat(contextCaptor.firstValue).isNotEqualTo(primaryUserMockContext)
+ assertThat(contextCaptor.firstValue).isEqualTo(mContext)
+
+ reset(wifiPickerTrackerFactory)
+
+ // WHEN we switch to a different user
val otherUserMockContext = mock<Context>()
mContext.prepareCreateContextAsUser(
UserHandle.of(ANOTHER_USER_ID),
otherUserMockContext,
)
-
- runCurrent()
userRepository.setSelectedUserInfo(ANOTHER_USER)
- runCurrent()
- verify(wifiPickerTrackerFactory, times(1)).create(any(), any(), any(), any())
+ // THEN we do NOT re-create WifiPickerTracker because the multiuser flag is off
+ verify(wifiPickerTrackerFactory, never()).create(any(), any(), any(), any())
}
private fun getCallback(): WifiPickerTracker.WifiPickerTrackerCallback {
- testScope.runCurrent()
- return callbackCaptor.value
+ return callbackCaptor.firstValue
}
private fun getTrafficStateCallback(): WifiManager.TrafficStateCallback {
- testScope.runCurrent()
val callbackCaptor = argumentCaptor<WifiManager.TrafficStateCallback>()
verify(wifiManager).registerTrafficStateCallback(any(), callbackCaptor.capture())
- return callbackCaptor.value!!
+ return callbackCaptor.firstValue
}
private fun createHotspotWithType(@DeviceType type: Int): HotspotNetworkEntry {
@@ -1325,10 +1308,9 @@
}
private fun getScanResultsCallback(): WifiManager.ScanResultsCallback {
- testScope.runCurrent()
val callbackCaptor = argumentCaptor<WifiManager.ScanResultsCallback>()
verify(wifiManager).registerScanResultsCallback(any(), callbackCaptor.capture())
- return callbackCaptor.value!!
+ return callbackCaptor.firstValue
}
private companion object {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/ui/dialog/viewmodel/ModesDialogViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/ui/dialog/viewmodel/ModesDialogViewModelTest.kt
index 0e32c95..e686ede 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/ui/dialog/viewmodel/ModesDialogViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/ui/dialog/viewmodel/ModesDialogViewModelTest.kt
@@ -24,6 +24,7 @@
import android.provider.Settings
import android.service.notification.SystemZenRules
import android.service.notification.ZenModeConfig
+import android.service.notification.ZenModeConfig.ScheduleInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.settingslib.notification.modes.TestModeBuilder
@@ -65,6 +66,7 @@
private lateinit var underTest: ModesDialogViewModel
private lateinit var timeScheduleMode: ZenMode
+ private lateinit var timeScheduleInfo: ScheduleInfo
@Before
fun setUp() {
@@ -78,18 +80,18 @@
kosmos.mockModesDialogEventLogger,
)
- val scheduleInfo = ZenModeConfig.ScheduleInfo()
- scheduleInfo.days = intArrayOf(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY)
- scheduleInfo.startHour = 11
- scheduleInfo.endHour = 15
+ timeScheduleInfo = ZenModeConfig.ScheduleInfo()
+ timeScheduleInfo.days = intArrayOf(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY)
+ timeScheduleInfo.startHour = 11
+ timeScheduleInfo.endHour = 15
timeScheduleMode =
TestModeBuilder()
.setPackage(SystemZenRules.PACKAGE_ANDROID)
.setType(AutomaticZenRule.TYPE_SCHEDULE_TIME)
.setManualInvocationAllowed(true)
- .setConditionId(ZenModeConfig.toScheduleConditionId(scheduleInfo))
+ .setConditionId(ZenModeConfig.toScheduleConditionId(timeScheduleInfo))
.setTriggerDescription(
- SystemZenRules.getTriggerDescriptionForScheduleTime(mContext, scheduleInfo)
+ SystemZenRules.getTriggerDescriptionForScheduleTime(mContext, timeScheduleInfo)
)
.build()
}
@@ -358,7 +360,7 @@
assertThat(tiles!![3].subtext).isEqualTo("Off")
assertThat(tiles!![4].subtext).isEqualTo("On")
assertThat(tiles!![5].subtext).isEqualTo("Not set")
- assertThat(tiles!![6].subtext).isEqualTo("Mon - Wed, 11:00 AM - 3:00 PM")
+ assertThat(tiles!![6].subtext).isEqualTo(timeScheduleMode.triggerDescription)
}
@Test
@@ -437,7 +439,8 @@
with(tiles?.elementAt(6)!!) {
assertThat(this.stateDescription).isEqualTo("Off")
assertThat(this.subtextDescription)
- .isEqualTo("Monday to Wednesday, 11:00 AM - 3:00 PM")
+ .isEqualTo(SystemZenRules.getDaysOfWeekFull(context, timeScheduleInfo)
+ + ", " + SystemZenRules.getTimeSummary(context, timeScheduleInfo))
}
// All tiles have the same long click info
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/MultiDisplayStatusBarWindowControllerStoreTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/MultiDisplayStatusBarWindowControllerStoreTest.kt
new file mode 100644
index 0000000..7a9d017
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/MultiDisplayStatusBarWindowControllerStoreTest.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2024 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.window
+
+import android.platform.test.annotations.EnableFlags
+import android.view.Display.DEFAULT_DISPLAY
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.display.data.repository.displayRepository
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.statusbar.core.StatusBarConnectedDisplays
+import com.android.systemui.testKosmos
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+@EnableFlags(StatusBarConnectedDisplays.FLAG_NAME)
+class MultiDisplayStatusBarWindowControllerStoreTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val fakeDisplayRepository = kosmos.displayRepository
+ private val testScope = kosmos.testScope
+
+ private val underTest by lazy { kosmos.multiDisplayStatusBarWindowControllerStore }
+
+ @Before
+ fun start() {
+ underTest.start()
+ }
+
+ @Before fun addDisplays() = runBlocking { fakeDisplayRepository.addDisplay(DEFAULT_DISPLAY) }
+
+ @Test
+ fun beforeDisplayRemoved_doesNotStopInstances() =
+ testScope.runTest {
+ val instance = underTest.forDisplay(DEFAULT_DISPLAY)
+
+ verify(instance, never()).stop()
+ }
+
+ @Test
+ fun displayRemoved_stopsInstance() =
+ testScope.runTest {
+ val instance = underTest.forDisplay(DEFAULT_DISPLAY)
+
+ fakeDisplayRepository.removeDisplay(DEFAULT_DISPLAY)
+
+ verify(instance).stop()
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImplTest.kt
index 6e66287..61c7193 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImplTest.kt
@@ -17,12 +17,17 @@
import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
+import android.view.fakeWindowManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.concurrency.fakeExecutor
+import com.android.systemui.fragments.fragmentService
import com.android.systemui.statusbar.core.StatusBarConnectedDisplays
+import com.android.systemui.statusbar.core.StatusBarRootModernization
import com.android.systemui.statusbar.policy.statusBarConfigurationController
import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
@@ -37,6 +42,9 @@
testKosmos().also { it.statusBarWindowViewInflater = it.fakeStatusBarWindowViewInflater }
private val underTest = kosmos.statusBarWindowControllerImpl
+ private val fakeExecutor = kosmos.fakeExecutor
+ private val fakeWindowManager = kosmos.fakeWindowManager
+ private val mockFragmentService = kosmos.fragmentService
private val fakeStatusBarWindowViewInflater = kosmos.fakeStatusBarWindowViewInflater
private val statusBarConfigurationController = kosmos.statusBarConfigurationController
@@ -59,4 +67,64 @@
verify(mockWindowView, never()).setStatusBarConfigurationController(any())
}
+
+ @Test
+ @EnableFlags(StatusBarRootModernization.FLAG_NAME, StatusBarConnectedDisplays.FLAG_NAME)
+ fun stop_statusBarModernizationFlagEnabled_doesNotRemoveFragment() {
+ val windowView = fakeStatusBarWindowViewInflater.inflatedMockViews.first()
+
+ underTest.stop()
+ fakeExecutor.runAllReady()
+
+ verify(mockFragmentService, never()).removeAndDestroy(windowView)
+ }
+
+ @Test
+ @DisableFlags(StatusBarRootModernization.FLAG_NAME)
+ @EnableFlags(StatusBarConnectedDisplays.FLAG_NAME)
+ fun stop_statusBarModernizationFlagDisabled_removesFragment() {
+ val windowView = fakeStatusBarWindowViewInflater.inflatedMockViews.first()
+
+ underTest.stop()
+ fakeExecutor.runAllReady()
+
+ verify(mockFragmentService).removeAndDestroy(windowView)
+ }
+
+ @Test
+ @DisableFlags(StatusBarRootModernization.FLAG_NAME)
+ @EnableFlags(StatusBarConnectedDisplays.FLAG_NAME)
+ fun stop_statusBarModernizationFlagDisabled_removesFragmentOnExecutor() {
+ val windowView = fakeStatusBarWindowViewInflater.inflatedMockViews.first()
+
+ underTest.stop()
+
+ verify(mockFragmentService, never()).removeAndDestroy(windowView)
+ fakeExecutor.runAllReady()
+ verify(mockFragmentService).removeAndDestroy(windowView)
+ }
+
+ @Test
+ @EnableFlags(StatusBarConnectedDisplays.FLAG_NAME)
+ fun stop_removesWindowViewFromWindowManager() {
+ underTest.attach()
+ underTest.stop()
+
+ assertThat(fakeWindowManager.addedViews).isEmpty()
+ }
+
+ @Test(expected = IllegalStateException::class)
+ @DisableFlags(StatusBarConnectedDisplays.FLAG_NAME)
+ fun stop_connectedDisplaysFlagDisabled_crashes() {
+ underTest.stop()
+ }
+
+ @Test
+ fun attach_windowViewAddedToWindowManager() {
+ val windowView = fakeStatusBarWindowViewInflater.inflatedMockViews.first()
+
+ underTest.attach()
+
+ assertThat(fakeWindowManager.addedViews.keys).containsExactly(windowView)
+ }
}
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt b/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
index 89da465..fb9e96c 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
@@ -139,7 +139,9 @@
/** Message buffer for large clock rendering */
val largeClockMessageBuffer: MessageBuffer,
-)
+) {
+ constructor(buffer: MessageBuffer) : this(buffer, buffer, buffer) {}
+}
data class AodClockBurnInModel(val scale: Float, val translationX: Float, val translationY: Float)
diff --git a/packages/SystemUI/res/drawable/volume_background_top.xml b/packages/SystemUI/res/drawable/volume_background_top.xml
index 75849be..132572a 100644
--- a/packages/SystemUI/res/drawable/volume_background_top.xml
+++ b/packages/SystemUI/res/drawable/volume_background_top.xml
@@ -17,7 +17,6 @@
xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
<item>
<shape>
- <size android:width="@dimen/volume_dialog_width" />
<solid android:color="?androidprv:attr/materialColorSurface" />
<corners android:topLeftRadius="@dimen/volume_dialog_background_corner_radius"
android:topRightRadius="@dimen/volume_dialog_background_corner_radius"/>
diff --git a/packages/SystemUI/res/drawable/volume_dialog_spacer.xml b/packages/SystemUI/res/drawable/volume_dialog_spacer.xml
deleted file mode 100644
index 3c60784..0000000
--- a/packages/SystemUI/res/drawable/volume_dialog_spacer.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?><!--
- Copyright (C) 2024 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">
- <size
- android:width="@dimen/volume_dialog_spacing"
- android:height="@dimen/volume_dialog_spacing" />
- <solid android:color="@color/transparent" />
-</shape>
diff --git a/packages/SystemUI/res/layout/volume_dialog.xml b/packages/SystemUI/res/layout/volume_dialog.xml
index f187ce6..694357d 100644
--- a/packages/SystemUI/res/layout/volume_dialog.xml
+++ b/packages/SystemUI/res/layout/volume_dialog.xml
@@ -13,58 +13,70 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/volume_dialog_root"
android:layout_width="match_parent"
- android:layout_height="match_parent">
+ android:layout_height="match_parent"
+ app:layoutDescription="@xml/volume_dialog_scene">
- <LinearLayout
- android:id="@+id/volume_dialog_container"
+ <View
+ android:id="@+id/volume_dialog_background"
+ android:layout_width="@dimen/volume_dialog_width"
+ android:layout_height="0dp"
+ android:layout_marginTop="@dimen/volume_dialog_background_vertical_margin"
+ android:layout_marginBottom="@dimen/volume_dialog_background_vertical_margin"
+ android:background="@drawable/volume_dialog_background"
+ app:layout_constraintBottom_toBottomOf="@id/volume_dialog_settings"
+ app:layout_constraintEnd_toEndOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintStart_toStartOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintTop_toTopOf="@id/volume_ringer_and_drawer_container" />
+
+ <include
+ android:id="@id/volume_ringer_and_drawer_container"
+ layout="@layout/volume_ringer_drawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_gravity="center_vertical|end"
+ android:layout_marginBottom="@dimen/volume_dialog_components_spacing"
+ app:layout_constraintBottom_toTopOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintEnd_toEndOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintStart_toStartOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintVertical_bias="1" />
+
+ <include
+ android:id="@+id/volume_dialog_main_slider_container"
+ layout="@layout/volume_dialog_slider" />
+
+ <ImageButton
+ android:id="@+id/volume_dialog_settings"
+ android:layout_width="@dimen/volume_dialog_button_size"
+ android:layout_height="@dimen/volume_dialog_button_size"
+ android:layout_marginTop="@dimen/volume_dialog_components_spacing"
+ android:background="@drawable/ripple_drawable_20dp"
+ android:contentDescription="@string/accessibility_volume_settings"
+ android:soundEffectsEnabled="false"
+ android:src="@drawable/horizontal_ellipsis"
+ android:tint="?androidprv:attr/materialColorPrimary"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintStart_toStartOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintTop_toBottomOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintVertical_bias="0" />
+
+ <LinearLayout
+ android:id="@+id/volume_dialog_floating_sliders_container"
+ android:layout_width="wrap_content"
+ android:layout_height="0dp"
+ android:layout_marginTop="@dimen/volume_dialog_floating_sliders_vertical_padding_negative"
+ android:layout_marginBottom="@dimen/volume_dialog_floating_sliders_vertical_padding_negative"
android:divider="@drawable/volume_dialog_floating_sliders_spacer"
+ android:gravity="bottom"
android:orientation="horizontal"
- android:showDividers="middle|end|beginning">
+ android:showDividers="middle|beginning|end"
+ app:layout_constraintBottom_toBottomOf="@id/volume_dialog_main_slider_container"
+ app:layout_constraintEnd_toStartOf="@id/volume_dialog_background"
+ app:layout_constraintTop_toTopOf="@id/volume_dialog_main_slider_container" />
- <LinearLayout
- android:id="@+id/volume_dialog_floating_sliders_container"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:divider="@drawable/volume_dialog_floating_sliders_spacer"
- android:gravity="bottom"
- android:orientation="horizontal"
- android:paddingBottom="@dimen/volume_dialog_floating_sliders_bottom_padding"
- android:showDividers="middle" />
-
- <LinearLayout
- android:id="@+id/volume_dialog"
- android:layout_width="@dimen/volume_dialog_width"
- android:layout_height="wrap_content"
- android:background="@drawable/volume_dialog_background"
- android:clipChildren="false"
- android:clipToOutline="false"
- android:clipToPadding="false"
- android:divider="@drawable/volume_dialog_spacer"
- android:gravity="center_horizontal"
- android:orientation="vertical"
- android:paddingVertical="@dimen/volume_dialog_vertical_padding"
- android:showDividers="middle">
-
- <include layout="@layout/volume_ringer_drawer" />
-
- <include layout="@layout/volume_dialog_slider" />
-
- <ImageButton
- android:id="@+id/volume_dialog_settings"
- android:layout_width="@dimen/volume_dialog_button_size"
- android:layout_height="@dimen/volume_dialog_button_size"
- android:background="@drawable/ripple_drawable_20dp"
- android:contentDescription="@string/accessibility_volume_settings"
- android:soundEffectsEnabled="false"
- android:src="@drawable/horizontal_ellipsis"
- android:tint="?androidprv:attr/materialColorPrimary" />
- </LinearLayout>
- </LinearLayout>
-</FrameLayout>
\ No newline at end of file
+</androidx.constraintlayout.motion.widget.MotionLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/volume_ringer_drawer.xml b/packages/SystemUI/res/layout/volume_ringer_drawer.xml
index 7c266e6..b71c470 100644
--- a/packages/SystemUI/res/layout/volume_ringer_drawer.xml
+++ b/packages/SystemUI/res/layout/volume_ringer_drawer.xml
@@ -19,13 +19,10 @@
android:id="@+id/volume_ringer_and_drawer_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:gravity="center"
- android:paddingLeft="@dimen/volume_dialog_ringer_horizontal_padding"
- android:paddingRight="@dimen/volume_dialog_ringer_horizontal_padding"
- android:layoutDirection="ltr"
- android:clipToPadding="false"
android:clipChildren="false"
- android:background="@drawable/volume_background_top">
+ android:clipToPadding="false"
+ android:gravity="center"
+ android:layoutDirection="ltr">
<!-- Drawer view, invisible by default. -->
<FrameLayout
@@ -37,10 +34,10 @@
<!-- View that is animated to a tapped ringer selection, so it appears selected. -->
<FrameLayout
android:id="@+id/volume_drawer_selection_background"
- android:alpha="0.0"
android:layout_width="@dimen/volume_dialog_ringer_drawer_button_size"
android:layout_height="@dimen/volume_dialog_ringer_drawer_button_size"
android:layout_gravity="bottom|right"
+ android:alpha="0.0"
android:background="@drawable/volume_drawer_selection_bg" />
<LinearLayout
@@ -65,7 +62,6 @@
android:background="@drawable/volume_drawer_selection_bg"
android:contentDescription="@string/volume_ringer_change"
android:gravity="center"
- android:padding="@dimen/volume_dialog_ringer_horizontal_padding"
android:src="@drawable/ic_volume_media"
android:tint="?androidprv:attr/materialColorOnPrimary" />
diff --git a/packages/SystemUI/res/values-sw600dp-land/dimens.xml b/packages/SystemUI/res/values-sw600dp-land/dimens.xml
index 4a53df9..75bee9f 100644
--- a/packages/SystemUI/res/values-sw600dp-land/dimens.xml
+++ b/packages/SystemUI/res/values-sw600dp-land/dimens.xml
@@ -46,8 +46,6 @@
<dimen name="lockscreen_shade_max_over_scroll_amount">32dp</dimen>
- <dimen name="status_view_margin_horizontal">8dp</dimen>
-
<!-- Lockscreen shade transition values -->
<dimen name="lockscreen_shade_transition_by_tap_distance">200dp</dimen>
<dimen name="lockscreen_shade_full_transition_distance">200dp</dimen>
diff --git a/packages/SystemUI/res/values-sw600dp-port/dimens.xml b/packages/SystemUI/res/values-sw600dp-port/dimens.xml
index 707bc9e..f73e91a 100644
--- a/packages/SystemUI/res/values-sw600dp-port/dimens.xml
+++ b/packages/SystemUI/res/values-sw600dp-port/dimens.xml
@@ -16,8 +16,6 @@
-->
<resources>
<dimen name="notification_panel_margin_horizontal">48dp</dimen>
- <dimen name="status_view_margin_horizontal">62dp</dimen>
-
<!-- qs_tiles_page_horizontal_margin should be margin / 2, otherwise full space between two
pages is margin * 2, and that makes tiles page not appear immediately after user swipes to
the side -->
diff --git a/packages/SystemUI/res/values-sw720dp-land/dimens.xml b/packages/SystemUI/res/values-sw720dp-land/dimens.xml
index 8583f05..41bb37e 100644
--- a/packages/SystemUI/res/values-sw720dp-land/dimens.xml
+++ b/packages/SystemUI/res/values-sw720dp-land/dimens.xml
@@ -22,8 +22,6 @@
<dimen name="keyguard_split_shade_top_margin">72dp</dimen>
- <dimen name="status_view_margin_horizontal">24dp</dimen>
-
<dimen name="qs_media_session_height_expanded">184dp</dimen>
<dimen name="qs_content_horizontal_padding">40dp</dimen>
<dimen name="qs_horizontal_margin">40dp</dimen>
diff --git a/packages/SystemUI/res/values-sw720dp-port/dimens.xml b/packages/SystemUI/res/values-sw720dp-port/dimens.xml
index 9248d58..eb570b8 100644
--- a/packages/SystemUI/res/values-sw720dp-port/dimens.xml
+++ b/packages/SystemUI/res/values-sw720dp-port/dimens.xml
@@ -20,8 +20,6 @@
<!-- These resources are around just to allow their values to be customized
for different hardware and product builds. -->
<resources>
- <dimen name="status_view_margin_horizontal">124dp</dimen>
-
<dimen name="large_screen_shade_header_left_padding">24dp</dimen>
<dimen name="qqs_layout_padding_bottom">40dp</dimen>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 7af0057..4954f91 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -1955,8 +1955,6 @@
<dimen name="dream_overlay_entry_y_offset">40dp</dimen>
<dimen name="dream_overlay_exit_y_offset">40dp</dimen>
- <dimen name="status_view_margin_horizontal">0dp</dimen>
-
<!-- Media output broadcast dialog QR code picture size -->
<dimen name="media_output_qrcode_size">216dp</dimen>
<dimen name="media_output_broadcast_info">21dp</dimen>
@@ -2060,26 +2058,29 @@
<dimen name="contextual_edu_dialog_elevation">2dp</dimen>
<!-- Volume start -->
- <dimen name="volume_dialog_background_corner_radius">30dp</dimen>
<dimen name="volume_dialog_width">60dp</dimen>
- <dimen name="volume_dialog_vertical_padding">10dp</dimen>
+
+ <dimen name="volume_dialog_background_corner_radius">30dp</dimen>
+ <dimen name="volume_dialog_background_vertical_margin">-10dp</dimen>
+
<dimen name="volume_dialog_components_spacing">8dp</dimen>
<dimen name="volume_dialog_floating_sliders_spacing">8dp</dimen>
<dimen name="volume_dialog_floating_sliders_vertical_padding">10dp</dimen>
+ <dimen name="volume_dialog_floating_sliders_vertical_padding_negative">-10dp</dimen>
<dimen name="volume_dialog_floating_sliders_horizontal_padding">4dp</dimen>
- <dimen name="volume_dialog_spacing">4dp</dimen>
<dimen name="volume_dialog_button_size">48dp</dimen>
- <dimen name="volume_dialog_floating_sliders_bottom_padding">48dp</dimen>
<dimen name="volume_dialog_slider_width">52dp</dimen>
<dimen name="volume_dialog_slider_height">254dp</dimen>
- <dimen name="volume_panel_slice_vertical_padding">8dp</dimen>
- <dimen name="volume_panel_slice_horizontal_padding">24dp</dimen>
+ <fraction name="volume_dialog_half_opened_bias">0.2</fraction>
- <dimen name="volume_dialog_ringer_horizontal_padding">10dp</dimen>
+ <dimen name="volume_dialog_background_square_corner_radius">12dp</dimen>
+
<dimen name="volume_dialog_ringer_drawer_button_size">40dp</dimen>
<dimen name="volume_dialog_ringer_drawer_button_icon_radius">10dp</dimen>
- <dimen name="volume_dialog_background_square_corner_radius">12dp</dimen>
<dimen name="volume_dialog_ringer_selected_button_background_radius">20dp</dimen>
+
+ <dimen name="volume_panel_slice_vertical_padding">8dp</dimen>
+ <dimen name="volume_panel_slice_horizontal_padding">24dp</dimen>
<!-- Volume end -->
</resources>
diff --git a/packages/SystemUI/res/xml/volume_dialog_constraint_set.xml b/packages/SystemUI/res/xml/volume_dialog_constraint_set.xml
new file mode 100644
index 0000000..9018e5b
--- /dev/null
+++ b/packages/SystemUI/res/xml/volume_dialog_constraint_set.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ConstraintSet xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:id="@+id/volume_dialog_constraint_set">
+
+ <Constraint
+ android:id="@id/volume_dialog_main_slider_container"
+ android:layout_width="@dimen/volume_dialog_slider_width"
+ android:layout_height="@dimen/volume_dialog_slider_height"
+ android:layout_marginEnd="@dimen/volume_dialog_components_spacing"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintVertical_bias="0.5" />
+</ConstraintSet>
\ No newline at end of file
diff --git a/packages/SystemUI/res/xml/volume_dialog_half_folded_constraint_set.xml b/packages/SystemUI/res/xml/volume_dialog_half_folded_constraint_set.xml
new file mode 100644
index 0000000..297c388
--- /dev/null
+++ b/packages/SystemUI/res/xml/volume_dialog_half_folded_constraint_set.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ConstraintSet xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:id="@+id/volume_dialog_half_folded_constraint_set">
+
+ <Constraint
+ android:id="@id/volume_dialog_main_slider_container"
+ android:layout_width="@dimen/volume_dialog_slider_width"
+ android:layout_height="@dimen/volume_dialog_slider_height"
+ android:layout_marginEnd="@dimen/volume_dialog_components_spacing"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintVertical_bias="@fraction/volume_dialog_half_opened_bias" />
+</ConstraintSet>
\ No newline at end of file
diff --git a/packages/SystemUI/res/xml/volume_dialog_scene.xml b/packages/SystemUI/res/xml/volume_dialog_scene.xml
new file mode 100644
index 0000000..b813474
--- /dev/null
+++ b/packages/SystemUI/res/xml/volume_dialog_scene.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2024 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.
+ -->
+
+<MotionScene xmlns:motion="http://schemas.android.com/apk/res-auto">
+
+ <Transition
+ motion:autoTransition="none"
+ motion:constraintSetEnd="@id/volume_dialog_half_folded_constraint_set"
+ motion:constraintSetStart="@id/volume_dialog_constraint_set"
+ motion:duration="150" />
+
+ <Include motion:constraintSet="@xml/volume_dialog_constraint_set" />
+ <Include motion:constraintSet="@xml/volume_dialog_half_folded_constraint_set" />
+</MotionScene>
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
index 95830b5..add459b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
@@ -44,7 +44,7 @@
import com.android.systemui.navigationbar.NavigationBarController;
import com.android.systemui.navigationbar.views.NavigationBarView;
import com.android.systemui.settings.DisplayTracker;
-import com.android.systemui.shade.data.repository.ShadePositionRepository;
+import com.android.systemui.shade.data.repository.ShadeDisplaysRepository;
import com.android.systemui.shade.shared.flag.ShadeWindowGoesAround;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -66,7 +66,7 @@
private final DisplayManager mDisplayService;
private final DisplayTracker mDisplayTracker;
private final Lazy<NavigationBarController> mNavigationBarControllerLazy;
- private final Provider<ShadePositionRepository> mShadePositionRepositoryProvider;
+ private final Provider<ShadeDisplaysRepository> mShadePositionRepositoryProvider;
private final ConnectedDisplayKeyguardPresentation.Factory
mConnectedDisplayKeyguardPresentationFactory;
private final Context mContext;
@@ -112,7 +112,7 @@
KeyguardStateController keyguardStateController,
ConnectedDisplayKeyguardPresentation.Factory
connectedDisplayKeyguardPresentationFactory,
- Provider<ShadePositionRepository> shadePositionRepositoryProvider,
+ Provider<ShadeDisplaysRepository> shadePositionRepositoryProvider,
@Application CoroutineScope appScope) {
mContext = context;
mNavigationBarControllerLazy = navigationBarControllerLazy;
diff --git a/packages/SystemUI/src/com/android/systemui/ambient/touch/TouchMonitor.java b/packages/SystemUI/src/com/android/systemui/ambient/touch/TouchMonitor.java
index fb00d6e..db4d613 100644
--- a/packages/SystemUI/src/com/android/systemui/ambient/touch/TouchMonitor.java
+++ b/packages/SystemUI/src/com/android/systemui/ambient/touch/TouchMonitor.java
@@ -52,6 +52,8 @@
import com.google.common.util.concurrent.ListenableFuture;
+import kotlin.Unit;
+
import kotlinx.coroutines.Job;
import java.util.Collection;
@@ -87,7 +89,7 @@
private final ConfigurationInteractor mConfigurationInteractor;
private final Lifecycle mLifecycle;
- private Rect mExclusionRect = null;
+ private Rect mExclusionRect = new Rect();
private ISystemGestureExclusionListener mGestureExclusionListener;
@@ -298,9 +300,18 @@
public void onSystemGestureExclusionChanged(int displayId,
Region systemGestureExclusion,
Region systemGestureExclusionUnrestricted) {
- mExclusionRect = systemGestureExclusion.getBounds();
+ final Rect bounds = systemGestureExclusion.getBounds();
+ if (!mExclusionRect.equals(bounds)) {
+ mExclusionRect = bounds;
+ mLogger.i(msg -> "Exclusion rect updated to " + msg.getStr1(),
+ msg -> {
+ msg.setStr1(bounds.toString());
+ return Unit.INSTANCE;
+ });
+ }
}
};
+ mLogger.i("Registering system gesture exclusion listener");
mWindowManagerService.registerSystemGestureExclusionListener(
mGestureExclusionListener, mDisplayId);
} catch (RemoteException e) {
@@ -320,11 +331,12 @@
* Destroys any active {@link InputSession}.
*/
private void stopMonitoring(boolean force) {
- mExclusionRect = null;
+ mExclusionRect = new Rect();
if (bouncerAreaExclusion()) {
mBackgroundExecutor.execute(() -> {
try {
if (mGestureExclusionListener != null) {
+ mLogger.i("Unregistering system gesture exclusion listener");
mWindowManagerService.unregisterSystemGestureExclusionListener(
mGestureExclusionListener, mDisplayId);
mGestureExclusionListener = null;
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/BaseCommunalViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/BaseCommunalViewModel.kt
index 4e0e112..5ecf2e6b 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/BaseCommunalViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/BaseCommunalViewModel.kt
@@ -29,6 +29,7 @@
import com.android.systemui.communal.shared.model.EditModeState
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.media.controls.ui.controller.MediaCarouselController
import com.android.systemui.media.controls.ui.view.MediaHost
import com.android.systemui.util.kotlin.BooleanFlowOperators.anyOf
import com.android.systemui.util.kotlin.BooleanFlowOperators.not
@@ -43,6 +44,7 @@
val communalSceneInteractor: CommunalSceneInteractor,
private val communalInteractor: CommunalInteractor,
val mediaHost: MediaHost,
+ val mediaCarouselController: MediaCarouselController,
) {
val currentScene: Flow<SceneKey> = communalSceneInteractor.currentScene
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalEditModeViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalEditModeViewModel.kt
index ccff230..736ed5c 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalEditModeViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalEditModeViewModel.kt
@@ -46,6 +46,7 @@
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.core.Logger
import com.android.systemui.log.dagger.CommunalLog
+import com.android.systemui.media.controls.ui.controller.MediaCarouselController
import com.android.systemui.media.controls.ui.view.MediaHost
import com.android.systemui.media.dagger.MediaModule
import com.android.systemui.res.R
@@ -82,7 +83,14 @@
private val accessibilityManager: AccessibilityManager,
private val packageManager: PackageManager,
@Named(LAUNCHER_PACKAGE) private val launcherPackage: String,
-) : BaseCommunalViewModel(communalSceneInteractor, communalInteractor, mediaHost) {
+ mediaCarouselController: MediaCarouselController,
+) :
+ BaseCommunalViewModel(
+ communalSceneInteractor,
+ communalInteractor,
+ mediaHost,
+ mediaCarouselController,
+ ) {
private val logger = Logger(logBuffer, "CommunalEditModeViewModel")
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModel.kt
index 6239373..3496230 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalTransitionViewModel.kt
@@ -31,6 +31,7 @@
import com.android.systemui.keyguard.ui.viewmodel.GlanceableHubToDreamingTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.GlanceableHubToLockscreenTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.LockscreenToGlanceableHubTransitionViewModel
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.util.kotlin.BooleanFlowOperators.allOf
import com.android.systemui.util.kotlin.BooleanFlowOperators.anyOf
@@ -41,6 +42,7 @@
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onStart
@@ -60,7 +62,7 @@
glanceableHubToDreamTransitionViewModel: GlanceableHubToDreamingTransitionViewModel,
communalInteractor: CommunalInteractor,
private val communalSceneInteractor: CommunalSceneInteractor,
- keyguardTransitionInteractor: KeyguardTransitionInteractor
+ keyguardTransitionInteractor: KeyguardTransitionInteractor,
) {
/**
* Snaps to [CommunalScenes.Communal], showing the glanceable hub immediately without any
@@ -89,7 +91,7 @@
keyguardTransitionInteractor
.transition(
edge = Edge.create(from = Scenes.Communal),
- edgeWithoutSceneContainer = Edge.create(from = KeyguardState.GLANCEABLE_HUB)
+ edgeWithoutSceneContainer = Edge.create(from = KeyguardState.GLANCEABLE_HUB),
)
.filter {
it.to == KeyguardState.OCCLUDED &&
@@ -114,21 +116,24 @@
// from
// the hub, then pressing power twice to go back to the lock screen.
communalSceneInteractor.isCommunalVisible,
- merge(
- lockscreenToGlanceableHubTransitionViewModel.showUmo,
- glanceableHubToLockscreenTransitionViewModel.showUmo,
- dreamToGlanceableHubTransitionViewModel.showUmo,
- glanceableHubToDreamTransitionViewModel.showUmo,
- showUmoFromOccludedToGlanceableHub,
- showUmoFromGlanceableHubToOccluded,
- )
- .onStart { emit(false) }
- )
+ // TODO(b/378942852): polish UMO transitions when scene container is enabled
+ if (SceneContainerFlag.isEnabled) flowOf(true)
+ else
+ merge(
+ lockscreenToGlanceableHubTransitionViewModel.showUmo,
+ glanceableHubToLockscreenTransitionViewModel.showUmo,
+ dreamToGlanceableHubTransitionViewModel.showUmo,
+ glanceableHubToDreamTransitionViewModel.showUmo,
+ showUmoFromOccludedToGlanceableHub,
+ showUmoFromGlanceableHubToOccluded,
+ )
+ .onStart { emit(false) },
+ ),
)
.stateIn(
scope = applicationScope,
started = SharingStarted.WhileSubscribed(),
- initialValue = false
+ initialValue = false,
)
/** Whether to show communal when exiting the occluded state. */
@@ -145,8 +150,7 @@
val recentsBackgroundColor: Flow<Color?> =
combine(showCommunalFromOccluded, communalColors.backgroundColor) {
showCommunalFromOccluded,
- backgroundColor,
- ->
+ backgroundColor ->
if (showCommunalFromOccluded) {
backgroundColor
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
index 7990450..9cd6465 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
@@ -21,6 +21,7 @@
import android.os.Bundle
import android.view.View
import android.view.accessibility.AccessibilityNodeInfo
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.communal.domain.interactor.CommunalInteractor
import com.android.systemui.communal.domain.interactor.CommunalSceneInteractor
import com.android.systemui.communal.domain.interactor.CommunalSettingsInteractor
@@ -38,6 +39,7 @@
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.core.Logger
import com.android.systemui.log.dagger.CommunalLog
+import com.android.systemui.media.controls.ui.controller.MediaCarouselController
import com.android.systemui.media.controls.ui.controller.MediaHierarchyManager
import com.android.systemui.media.controls.ui.view.MediaHost
import com.android.systemui.media.controls.ui.view.MediaHostState
@@ -72,7 +74,6 @@
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
-import com.android.app.tracing.coroutines.launchTraced as launch
/** The default view model used for showing the communal hub. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -95,7 +96,14 @@
@Named(MediaModule.COMMUNAL_HUB) mediaHost: MediaHost,
@CommunalLog logBuffer: LogBuffer,
private val metricsLogger: CommunalMetricsLogger,
-) : BaseCommunalViewModel(communalSceneInteractor, communalInteractor, mediaHost) {
+ mediaCarouselController: MediaCarouselController,
+) :
+ BaseCommunalViewModel(
+ communalSceneInteractor,
+ communalInteractor,
+ mediaHost,
+ mediaCarouselController,
+ ) {
private val logger = Logger(logBuffer, "CommunalViewModel")
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 2ee9ddb..01ec4d0 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -2875,7 +2875,7 @@
}
if (ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS) {
- mKeyguardTransitions.startKeyguardTransition(showing, aodShowing);
+ startKeyguardTransition(showing, aodShowing);
} else {
try {
@@ -3019,7 +3019,7 @@
final int keyguardFlag = flags;
mUiBgExecutor.execute(() -> {
if (ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS) {
- mKeyguardTransitions.startKeyguardTransition(
+ startKeyguardTransition(
false /* keyguardShowing */, false /* aodShowing */);
return;
}
@@ -3035,6 +3035,10 @@
}
};
+ private void startKeyguardTransition(boolean keyguardShowing, boolean aodShowing) {
+ mKeyguardTransitions.startKeyguardTransition(keyguardShowing, aodShowing);
+ }
+
private final Runnable mHideAnimationFinishedRunnable = () -> {
Log.e(TAG, "mHideAnimationFinishedRunnable#run");
mHideAnimationRunning = false;
@@ -3490,8 +3494,7 @@
mSurfaceBehindRemoteAnimationRequested = true;
if (ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS) {
- mKeyguardTransitions.startKeyguardTransition(
- false /* keyguardShowing */, false /* aodShowing */);
+ startKeyguardTransition(false /* keyguardShowing */, false /* aodShowing */);
return;
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt b/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt
index 2914cb9..a137d6c 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt
@@ -122,10 +122,7 @@
if (visible) {
if (enableNewKeyguardShellTransitions) {
- keyguardTransitions.startKeyguardTransition(
- false /* keyguardShowing */,
- false, /* aodShowing */
- )
+ startKeyguardTransition(false, /* keyguardShowing */ false /* aodShowing */)
isKeyguardGoingAway = true
return
}
@@ -233,7 +230,7 @@
"aodVisible=$aodVisible).",
)
if (enableNewKeyguardShellTransitions) {
- keyguardTransitions.startKeyguardTransition(lockscreenShowing, aodVisible)
+ startKeyguardTransition(lockscreenShowing, aodVisible)
} else {
activityTaskManagerService.setLockScreenShown(lockscreenShowing, aodVisible)
}
@@ -241,6 +238,10 @@
this.isAodVisible = aodVisible
}
+ private fun startKeyguardTransition(keyguardShowing: Boolean, aodShowing: Boolean) {
+ keyguardTransitions.startKeyguardTransition(keyguardShowing, aodShowing)
+ }
+
private fun endKeyguardGoingAwayAnimation() {
if (!isKeyguardGoingAway) {
Log.d(
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardPreviewClockViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardPreviewClockViewBinder.kt
index 914fdd2..6c03b24 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardPreviewClockViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardPreviewClockViewBinder.kt
@@ -151,7 +151,5 @@
cs.applyTo(rootView)
}
- private const val DATE_WEATHER_VIEW_HEIGHT = "date_weather_view_height"
- private const val ENHANCED_SMARTSPACE_HEIGHT = "enhanced_smartspace_height"
private const val TAG = "KeyguardPreviewClockViewBinder"
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
index 08c3f15..4c23adf 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
@@ -29,6 +29,7 @@
import androidx.constraintlayout.widget.ConstraintSet.START
import androidx.constraintlayout.widget.ConstraintSet.TOP
import com.android.systemui.common.ui.ConfigurationState
+import com.android.systemui.customization.R as customR
import com.android.systemui.keyguard.MigrateClocksToBlueprint
import com.android.systemui.keyguard.shared.model.KeyguardSection
import com.android.systemui.keyguard.ui.viewmodel.KeyguardRootViewModel
@@ -114,14 +115,14 @@
START,
PARENT_ID,
START,
- context.resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal),
+ context.resources.getDimensionPixelSize(customR.dimen.status_view_margin_horizontal),
)
connect(
nicId,
END,
PARENT_ID,
END,
- context.resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal),
+ context.resources.getDimensionPixelSize(customR.dimen.status_view_margin_horizontal),
)
constrainHeight(
nicId,
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/ClockSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/ClockSection.kt
index c009720..6c98d5b 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/ClockSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/ClockSection.kt
@@ -221,7 +221,9 @@
PARENT_ID,
START,
context.resources.getDimensionPixelSize(customR.dimen.clock_padding_start) +
- context.resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal),
+ context.resources.getDimensionPixelSize(
+ customR.dimen.status_view_margin_horizontal
+ ),
)
val smallClockTopMargin = keyguardClockViewModel.getSmallClockTopMargin()
create(R.id.small_clock_guideline_top, ConstraintSet.HORIZONTAL_GUIDELINE)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeMediaSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeMediaSection.kt
index 0782846..f0d21f2 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeMediaSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeMediaSection.kt
@@ -28,6 +28,7 @@
import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet.START
import androidx.constraintlayout.widget.ConstraintSet.TOP
+import com.android.systemui.customization.R as customR
import com.android.systemui.keyguard.MigrateClocksToBlueprint
import com.android.systemui.keyguard.shared.model.KeyguardSection
import com.android.systemui.media.controls.ui.controller.KeyguardMediaController
@@ -42,7 +43,7 @@
constructor(
@ShadeDisplayAware private val context: Context,
private val notificationPanelView: NotificationPanelView,
- private val keyguardMediaController: KeyguardMediaController
+ private val keyguardMediaController: KeyguardMediaController,
) : KeyguardSection() {
private val mediaContainerId = R.id.status_view_media_container
@@ -62,7 +63,7 @@
val horizontalPadding =
padding +
context.resources.getDimensionPixelSize(
- R.dimen.status_view_margin_horizontal
+ customR.dimen.status_view_margin_horizontal
)
setPaddingRelative(horizontalPadding, padding, horizontalPadding, padding)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSmartspaceViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSmartspaceViewModel.kt
index e30ddc6..de0927e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSmartspaceViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSmartspaceViewModel.kt
@@ -17,6 +17,7 @@
package com.android.systemui.keyguard.ui.viewmodel
import android.content.Context
+import com.android.systemui.customization.R as customR
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.keyguard.domain.interactor.KeyguardSmartspaceInteractor
@@ -59,10 +60,9 @@
/** Whether the weather area should be visible. */
val isWeatherVisible: StateFlow<Boolean> =
- combine(
+ combine(isWeatherEnabled, keyguardClockViewModel.hasCustomWeatherDataDisplay) {
isWeatherEnabled,
- keyguardClockViewModel.hasCustomWeatherDataDisplay,
- ) { isWeatherEnabled, clockIncludesCustomWeatherDisplay ->
+ clockIncludesCustomWeatherDisplay ->
isWeatherVisible(
clockIncludesCustomWeatherDisplay = clockIncludesCustomWeatherDisplay,
isWeatherEnabled = isWeatherEnabled,
@@ -76,7 +76,7 @@
clockIncludesCustomWeatherDisplay =
keyguardClockViewModel.hasCustomWeatherDataDisplay.value,
isWeatherEnabled = smartspaceInteractor.isWeatherEnabled.value,
- )
+ ),
)
private fun isWeatherVisible(
@@ -92,12 +92,12 @@
companion object {
fun getSmartspaceStartMargin(context: Context): Int {
return context.resources.getDimensionPixelSize(R.dimen.below_clock_padding_start) +
- context.resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal)
+ context.resources.getDimensionPixelSize(customR.dimen.status_view_margin_horizontal)
}
fun getSmartspaceEndMargin(context: Context): Int {
return context.resources.getDimensionPixelSize(R.dimen.below_clock_padding_end) +
- context.resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal)
+ context.resources.getDimensionPixelSize(customR.dimen.status_view_margin_horizontal)
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModel.kt b/packages/SystemUI/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModel.kt
index 9029563..e3de6d5 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModel.kt
@@ -62,6 +62,7 @@
import com.android.systemui.statusbar.StatusBarState
import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.statusbar.disableflags.data.repository.DisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.DisableFlagsInteractor
import com.android.systemui.util.LargeScreenUtils
import com.android.systemui.util.asIndenting
import com.android.systemui.util.kotlin.emitOnStart
@@ -93,7 +94,7 @@
private val footerActionsController: FooterActionsController,
private val sysuiStatusBarStateController: SysuiStatusBarStateController,
deviceEntryInteractor: DeviceEntryInteractor,
- disableFlagsRepository: DisableFlagsRepository,
+ DisableFlagsInteractor: DisableFlagsInteractor,
keyguardTransitionInteractor: KeyguardTransitionInteractor,
private val largeScreenShadeInterpolator: LargeScreenShadeInterpolator,
@ShadeDisplayAware configurationInteractor: ConfigurationInteractor,
@@ -182,8 +183,8 @@
val isQsEnabled by
hydrator.hydratedStateOf(
traceName = "isQsEnabled",
- initialValue = disableFlagsRepository.disableFlags.value.isQuickSettingsEnabled(),
- source = disableFlagsRepository.disableFlags.map { it.isQuickSettingsEnabled() },
+ initialValue = DisableFlagsInteractor.disableFlags.value.isQuickSettingsEnabled(),
+ source = DisableFlagsInteractor.disableFlags.map { it.isQuickSettingsEnabled() },
)
var isInSplitShade by mutableStateOf(false)
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
index 0e09ad2..dbad602 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
@@ -17,6 +17,7 @@
package com.android.systemui.qs.panels.ui.compose.infinitegrid
import android.graphics.drawable.Animatable
+import android.graphics.drawable.AnimatedVectorDrawable
import android.graphics.drawable.Drawable
import android.text.TextUtils
import androidx.compose.animation.animateColorAsState
@@ -228,7 +229,14 @@
}
}
}
- is Icon.Loaded -> rememberDrawablePainter(loadedDrawable)
+ is Icon.Loaded -> {
+ LaunchedEffect(loadedDrawable) {
+ if (loadedDrawable is AnimatedVectorDrawable) {
+ loadedDrawable.forceAnimationOnUI()
+ }
+ }
+ rememberDrawablePainter(loadedDrawable)
+ }
}
Image(
diff --git a/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessSliderController.java b/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessSliderController.java
index 3a90d2b..503d0bf 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessSliderController.java
+++ b/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessSliderController.java
@@ -235,8 +235,7 @@
if (mBrightnessWarningToast.isToastActive()) {
return;
}
- mBrightnessWarningToast.show(mView.getContext(),
- R.string.quick_settings_brightness_unable_adjust_msg);
+ mBrightnessWarningToast.show(mView.getContext(), resId);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/settings/brightness/ui/BrightnessWarningToast.kt b/packages/SystemUI/src/com/android/systemui/settings/brightness/ui/BrightnessWarningToast.kt
index 9dc2cba..40260d0 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/brightness/ui/BrightnessWarningToast.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/brightness/ui/BrightnessWarningToast.kt
@@ -37,6 +37,9 @@
private var toastView: View? = null
fun show(viewContext: Context, @StringRes resId: Int) {
+ if (isToastActive()) {
+ return
+ }
val res = viewContext.resources
// Show the brightness warning toast with passing the toast inflation required context,
// userId and resId from SystemUI package.
@@ -79,13 +82,15 @@
val inAnimator = systemUIToast.inAnimation
inAnimator?.start()
- toastView!!.postDelayed({
+ toastView?.postDelayed({
val outAnimator = systemUIToast.outAnimation
if (outAnimator != null) {
outAnimator.start()
outAnimator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animator: Animator) {
- windowManager.removeViewImmediate(toastView)
+ if (isToastActive()) {
+ windowManager.removeViewImmediate(toastView)
+ }
toastView = null
}
})
@@ -94,7 +99,7 @@
}
fun isToastActive(): Boolean {
- return toastView != null && toastView!!.isAttachedToWindow
+ return toastView?.isAttachedToWindow == true
}
companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 0e82bf8..4ccd2b9 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -3109,12 +3109,18 @@
if (isTracking()) {
onTrackingStopped(true);
}
- if (isExpanded() && !mQsController.getExpanded()) {
+ if (isExpanded() && mBarState != KEYGUARD && !mQsController.getExpanded()) {
mShadeLog.d("Status Bar was long pressed. Expanding to QS.");
expandToQs();
} else {
- mShadeLog.d("Status Bar was long pressed. Expanding to Notifications.");
- expandToNotifications();
+ if (mBarState == KEYGUARD) {
+ mShadeLog.d("Lockscreen Status Bar was long pressed. Expanding to Notifications.");
+ mLockscreenShadeTransitionController.goToLockedShade(
+ /* expandedView= */null, /* needsQSAnimation= */false);
+ } else {
+ mShadeLog.d("Status Bar was long pressed. Expanding to Notifications.");
+ expandToNotifications();
+ }
}
}
@@ -5091,13 +5097,6 @@
}
boolean handled = mHeadsUpTouchHelper.onTouchEvent(event);
- if (!mHeadsUpTouchHelper.isTrackingHeadsUp() && mQsController.handleTouch(
- event, isFullyCollapsed(), isShadeOrQsHeightAnimationRunning())) {
- if (event.getActionMasked() != MotionEvent.ACTION_MOVE) {
- mShadeLog.logMotionEvent(event, "onTouch: handleQsTouch handled event");
- }
- return true;
- }
// This touch session has already resulted in shade expansion. Ignore everything else.
if (ShadeExpandsOnStatusBarLongPress.isEnabled()
&& event.getActionMasked() != MotionEvent.ACTION_DOWN
@@ -5105,6 +5104,13 @@
mShadeLog.d("Touch has same down time as Status Bar long press. Ignoring.");
return false;
}
+ if (!mHeadsUpTouchHelper.isTrackingHeadsUp() && mQsController.handleTouch(
+ event, isFullyCollapsed(), isShadeOrQsHeightAnimationRunning())) {
+ if (event.getActionMasked() != MotionEvent.ACTION_MOVE) {
+ mShadeLog.logMotionEvent(event, "onTouch: handleQsTouch handled event");
+ }
+ return true;
+ }
if (event.getActionMasked() == MotionEvent.ACTION_DOWN && isFullyCollapsed()) {
mMetricsLogger.count(COUNTER_PANEL_OPEN, 1);
handled = true;
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationsQSContainerController.kt b/packages/SystemUI/src/com/android/systemui/shade/NotificationsQSContainerController.kt
index 7a18d7c..207439e 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationsQSContainerController.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationsQSContainerController.kt
@@ -28,6 +28,7 @@
import androidx.constraintlayout.widget.ConstraintSet.TOP
import androidx.lifecycle.lifecycleScope
import com.android.app.tracing.coroutines.launchTraced as launch
+import com.android.systemui.customization.R as customR
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.fragments.FragmentService
@@ -314,7 +315,7 @@
private fun setKeyguardStatusViewConstraints(constraintSet: ConstraintSet) {
val statusViewMarginHorizontal =
- resources.getDimensionPixelSize(R.dimen.status_view_margin_horizontal)
+ resources.getDimensionPixelSize(customR.dimen.status_view_margin_horizontal)
constraintSet.apply {
setMargin(R.id.keyguard_status_view, START, statusViewMarginHorizontal)
setMargin(R.id.keyguard_status_view, END, statusViewMarginHorizontal)
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
index e15830e..fed4a26 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
@@ -30,8 +30,8 @@
import com.android.systemui.common.ui.domain.interactor.ConfigurationInteractorImpl
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.res.R
-import com.android.systemui.shade.data.repository.ShadePositionRepository
-import com.android.systemui.shade.data.repository.ShadePositionRepositoryImpl
+import com.android.systemui.shade.data.repository.ShadeDisplaysRepository
+import com.android.systemui.shade.data.repository.ShadeDisplaysRepositoryImpl
import com.android.systemui.shade.shared.flag.ShadeWindowGoesAround
import com.android.systemui.statusbar.phone.ConfigurationControllerImpl
import com.android.systemui.statusbar.phone.ConfigurationForwarder
@@ -157,16 +157,16 @@
@SysUISingleton
@Provides
- fun provideShadePositionRepository(impl: ShadePositionRepositoryImpl): ShadePositionRepository {
+ fun provideShadePositionRepository(impl: ShadeDisplaysRepositoryImpl): ShadeDisplaysRepository {
ShadeWindowGoesAround.isUnexpectedlyInLegacyMode()
return impl
}
@Provides
@IntoMap
- @ClassKey(ShadePositionRepositoryImpl::class)
+ @ClassKey(ShadeDisplaysRepositoryImpl::class)
fun provideShadePositionRepositoryAsCoreStartable(
- impl: ShadePositionRepositoryImpl
+ impl: ShadeDisplaysRepositoryImpl
): CoreStartable {
return if (ShadeWindowGoesAround.isEnabled) {
impl
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt
index 802fc0e..506b4e9 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt
@@ -17,11 +17,11 @@
package com.android.systemui.shade
import android.view.Display
-import com.android.systemui.shade.data.repository.ShadePositionRepository
+import com.android.systemui.shade.data.repository.ShadeDisplaysRepository
import com.android.systemui.statusbar.commandline.Command
import java.io.PrintWriter
-class ShadePrimaryDisplayCommand(private val positionRepository: ShadePositionRepository) :
+class ShadePrimaryDisplayCommand(private val positionRepository: ShadeDisplaysRepository) :
Command {
override fun execute(pw: PrintWriter, args: List<String>) {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/LongPressGestureDetector.kt b/packages/SystemUI/src/com/android/systemui/shade/StatusBarLongPressGestureDetector.kt
similarity index 97%
rename from packages/SystemUI/src/com/android/systemui/shade/LongPressGestureDetector.kt
rename to packages/SystemUI/src/com/android/systemui/shade/StatusBarLongPressGestureDetector.kt
index 6fb3ca5..ae36e81 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/LongPressGestureDetector.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/StatusBarLongPressGestureDetector.kt
@@ -25,7 +25,7 @@
/** Accepts touch events, detects long press, and calls ShadeViewController#onStatusBarLongPress. */
@SysUISingleton
-class LongPressGestureDetector
+class StatusBarLongPressGestureDetector
@Inject
constructor(context: Context, val shadeViewController: ShadeViewController) {
val gestureDetector =
diff --git a/packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadePositionRepository.kt b/packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadeDisplayRepository.kt
similarity index 94%
rename from packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadePositionRepository.kt
rename to packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadeDisplayRepository.kt
index 37210b9..71c5658 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadePositionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/data/repository/FakeShadeDisplayRepository.kt
@@ -20,7 +20,7 @@
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
-class FakeShadePositionRepository : ShadePositionRepository {
+class FakeShadeDisplayRepository : ShadeDisplaysRepository {
private val _displayId = MutableStateFlow(Display.DEFAULT_DISPLAY)
override fun setDisplayId(displayId: Int) {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt b/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepository.kt
similarity index 94%
rename from packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt
rename to packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepository.kt
index 24c067a..e920aba 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadeDisplaysRepository.kt
@@ -25,7 +25,7 @@
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
-interface ShadePositionRepository {
+interface ShadeDisplaysRepository {
/** ID of the display which currently hosts the shade */
val displayId: StateFlow<Int>
@@ -41,9 +41,9 @@
/** Source of truth for the display currently holding the shade. */
@SysUISingleton
-class ShadePositionRepositoryImpl
+class ShadeDisplaysRepositoryImpl
@Inject
-constructor(private val commandRegistry: CommandRegistry) : ShadePositionRepository, CoreStartable {
+constructor(private val commandRegistry: CommandRegistry) : ShadeDisplaysRepository, CoreStartable {
private val _displayId = MutableStateFlow(Display.DEFAULT_DISPLAY)
override val displayId: StateFlow<Int>
diff --git a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
index 4e7898d..1055dcb 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
@@ -30,7 +30,7 @@
import com.android.systemui.scene.ui.view.WindowRootView
import com.android.systemui.shade.ShadeDisplayAware
import com.android.systemui.shade.ShadeWindowLayoutParams
-import com.android.systemui.shade.data.repository.ShadePositionRepository
+import com.android.systemui.shade.data.repository.ShadeDisplaysRepository
import com.android.systemui.shade.shared.flag.ShadeWindowGoesAround
import com.android.systemui.statusbar.phone.ConfigurationForwarder
import javax.inject.Inject
@@ -38,13 +38,13 @@
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.withContext
-/** Handles Shade window display change when [ShadePositionRepository.displayId] changes. */
+/** Handles Shade window display change when [ShadeDisplaysRepository.displayId] changes. */
@SysUISingleton
class ShadeDisplaysInteractor
@Inject
constructor(
private val shadeRootView: WindowRootView,
- private val shadePositionRepository: ShadePositionRepository,
+ private val shadePositionRepository: ShadeDisplaysRepository,
@ShadeDisplayAware private val shadeContext: Context,
private val displayWindowPropertiesRepository: DisplayWindowPropertiesRepository,
@Background private val bgScope: CoroutineScope,
diff --git a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImpl.kt b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImpl.kt
index 460bfbb..a653ca2 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeInteractorImpl.kt
@@ -25,7 +25,7 @@
import com.android.systemui.keyguard.shared.model.Edge
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.power.domain.interactor.PowerInteractor
-import com.android.systemui.statusbar.disableflags.data.repository.DisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.DisableFlagsInteractor
import com.android.systemui.statusbar.phone.DozeParameters
import com.android.systemui.statusbar.policy.data.repository.UserSetupRepository
import com.android.systemui.statusbar.policy.domain.interactor.DeviceProvisioningInteractor
@@ -47,7 +47,7 @@
constructor(
@Application val scope: CoroutineScope,
deviceProvisioningInteractor: DeviceProvisioningInteractor,
- disableFlagsRepository: DisableFlagsRepository,
+ disableFlagsInteractor: DisableFlagsInteractor,
dozeParams: DozeParameters,
keyguardRepository: KeyguardRepository,
keyguardTransitionInteractor: KeyguardTransitionInteractor,
@@ -61,13 +61,13 @@
BaseShadeInteractor by baseShadeInteractor,
ShadeModeInteractor by shadeModeInteractor {
override val isShadeEnabled: StateFlow<Boolean> =
- disableFlagsRepository.disableFlags
+ disableFlagsInteractor.disableFlags
.map { it.isShadeEnabled() }
.flowName("isShadeEnabled")
.stateIn(scope, SharingStarted.Eagerly, initialValue = false)
override val isQsEnabled: StateFlow<Boolean> =
- disableFlagsRepository.disableFlags
+ disableFlagsInteractor.disableFlags
.map { it.isQuickSettingsEnabled() }
.flowName("isQsEnabled")
.stateIn(scope, SharingStarted.Eagerly, initialValue = false)
@@ -114,7 +114,7 @@
override val isExpandToQsEnabled: Flow<Boolean> =
combine(
- disableFlagsRepository.disableFlags,
+ disableFlagsInteractor.disableFlags,
isShadeEnabled,
keyguardRepository.isDozing,
userSetupRepository.isUserSetUp,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
index 33f0c64..6bec86a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
@@ -177,8 +177,6 @@
private float[] mMatrix;
private ColorMatrixColorFilter mMatrixColorFilter;
private Runnable mLayoutRunnable;
- private boolean mDismissed;
- private Runnable mOnDismissListener;
private boolean mIncreasedSize;
private boolean mShowsConversation;
private float mDozeAmount;
@@ -956,21 +954,6 @@
mLayoutRunnable = runnable;
}
- public void setDismissed() {
- mDismissed = true;
- if (mOnDismissListener != null) {
- mOnDismissListener.run();
- }
- }
-
- public boolean isDismissed() {
- return mDismissed;
- }
-
- public void setOnDismissListener(Runnable onDismissListener) {
- mOnDismissListener = onDismissListener;
- }
-
@Override
public void onDarkChanged(ArrayList<Rect> areas, float darkIntensity, int tint) {
int areaTint = getTint(areas, this, tint);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepository.kt
index 9004e5d..aeeb042 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/repository/DisableFlagsRepository.kt
@@ -22,7 +22,7 @@
import com.android.systemui.log.dagger.DisableFlagsRepositoryLog
import com.android.systemui.statusbar.CommandQueue
import com.android.systemui.statusbar.disableflags.DisableFlagsLogger
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractor.kt
new file mode 100644
index 0000000..4f1b978
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractor.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2024 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.disableflags.domain.interactor
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.statusbar.disableflags.data.repository.DisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
+import javax.inject.Inject
+import kotlinx.coroutines.flow.StateFlow
+
+@SysUISingleton
+class DisableFlagsInteractor @Inject constructor(repository: DisableFlagsRepository) {
+ /** A model of the disable flags last received from [IStatusBar]. */
+ val disableFlags: StateFlow<DisableFlagsModel> = repository.disableFlags
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/model/DisableFlagsModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/shared/model/DisableFlagsModel.kt
similarity index 85%
rename from packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/model/DisableFlagsModel.kt
rename to packages/SystemUI/src/com/android/systemui/statusbar/disableflags/shared/model/DisableFlagsModel.kt
index ce25cf5..6507237 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/data/model/DisableFlagsModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/disableflags/shared/model/DisableFlagsModel.kt
@@ -1,18 +1,20 @@
/*
- * Copyright (C) 2023 The Android Open Source Project
+ * Copyright (C) 2024 The Android Open Source Project
*
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software distributed under the
- * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the specific language governing
- * permissions and limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-package com.android.systemui.statusbar.disableflags.data.model
+package com.android.systemui.statusbar.disableflags.shared.model
import android.app.StatusBarManager.DISABLE2_NONE
import android.app.StatusBarManager.DISABLE2_NOTIFICATION_SHADE
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractor.kt
index 8079ce5..4ea597a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationAlertsInteractor.kt
@@ -17,17 +17,15 @@
package com.android.systemui.statusbar.notification.domain.interactor
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.disableflags.data.repository.DisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.DisableFlagsInteractor
import javax.inject.Inject
/** Interactor for notification alerting. */
@SysUISingleton
class NotificationAlertsInteractor
@Inject
-constructor(
- private val disableFlagsRepository: DisableFlagsRepository,
-) {
+constructor(private val disableFlagsInteractor: DisableFlagsInteractor) {
/** Returns true if notification alerts are allowed. */
fun areNotificationAlertsEnabled(): Boolean =
- disableFlagsRepository.disableFlags.value.areNotificationAlertsEnabled()
+ disableFlagsInteractor.disableFlags.value.areNotificationAlertsEnabled()
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 08d177f..d1de6be 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -1543,7 +1543,6 @@
setDragController(null);
mGroupParentWhenDismissed = mNotificationParent;
mChildAfterViewWhenDismissed = null;
- mEntry.getIcons().getStatusBarIcon().setDismissed();
if (isChildInGroup()) {
List<ExpandableNotificationRow> notificationChildren =
mNotificationParent.getAttachedChildren();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
index db29493..80c8e8b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
@@ -171,12 +171,14 @@
import com.android.systemui.shade.NotificationShadeWindowViewController;
import com.android.systemui.shade.QuickSettingsController;
import com.android.systemui.shade.ShadeController;
+import com.android.systemui.shade.ShadeExpandsOnStatusBarLongPress;
import com.android.systemui.shade.ShadeExpansionChangeEvent;
import com.android.systemui.shade.ShadeExpansionListener;
import com.android.systemui.shade.ShadeExpansionStateManager;
import com.android.systemui.shade.ShadeLogger;
import com.android.systemui.shade.ShadeSurface;
import com.android.systemui.shade.ShadeViewController;
+import com.android.systemui.shade.StatusBarLongPressGestureDetector;
import com.android.systemui.shared.recents.utilities.Utilities;
import com.android.systemui.shared.statusbar.phone.BarTransitions;
import com.android.systemui.statusbar.AutoHideUiElement;
@@ -366,6 +368,7 @@
private PhoneStatusBarViewController mPhoneStatusBarViewController;
private PhoneStatusBarTransitions mStatusBarTransitions;
+ private final Provider<StatusBarLongPressGestureDetector> mStatusBarLongPressGestureDetector;
private final AuthRippleController mAuthRippleController;
@WindowVisibleState private int mStatusBarWindowState = WINDOW_STATE_SHOWING;
private final NotificationShadeWindowController mNotificationShadeWindowController;
@@ -671,6 +674,7 @@
ShadeController shadeController,
WindowRootViewVisibilityInteractor windowRootViewVisibilityInteractor,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
+ Provider<StatusBarLongPressGestureDetector> statusBarLongPressGestureDetector,
ViewMediatorCallback viewMediatorCallback,
InitController initController,
@Named(TIME_TICK_HANDLER_NAME) Handler timeTickHandler,
@@ -778,6 +782,7 @@
mShadeController = shadeController;
mWindowRootViewVisibilityInteractor = windowRootViewVisibilityInteractor;
mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
+ mStatusBarLongPressGestureDetector = statusBarLongPressGestureDetector;
mKeyguardViewMediatorCallback = viewMediatorCallback;
mInitController = initController;
mPluginDependencyProvider = pluginDependencyProvider;
@@ -1527,6 +1532,11 @@
// to touch outside the customizer to close it, such as on the status or nav bar.
mShadeController.onStatusBarTouch(event);
}
+ if (ShadeExpandsOnStatusBarLongPress.isEnabled()
+ && mStatusBarStateController.getState() == StatusBarState.KEYGUARD) {
+ mStatusBarLongPressGestureDetector.get().handleTouch(event);
+ }
+
return getNotificationShadeWindowView().onTouchEvent(event);
};
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
index 91c43dd..176dd8d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -39,8 +39,8 @@
import com.android.systemui.Flags;
import com.android.systemui.Gefingerpoken;
import com.android.systemui.res.R;
-import com.android.systemui.shade.LongPressGestureDetector;
import com.android.systemui.shade.ShadeExpandsOnStatusBarLongPress;
+import com.android.systemui.shade.StatusBarLongPressGestureDetector;
import com.android.systemui.statusbar.phone.userswitcher.StatusBarUserSwitcherContainer;
import com.android.systemui.statusbar.window.StatusBarWindowControllerStore;
import com.android.systemui.user.ui.binder.StatusBarUserChipViewBinder;
@@ -69,7 +69,7 @@
private InsetsFetcher mInsetsFetcher;
private int mDensity;
private float mFontScale;
- private LongPressGestureDetector mLongPressGestureDetector;
+ private StatusBarLongPressGestureDetector mStatusBarLongPressGestureDetector;
/**
* Draw this many pixels into the left/right side of the cutout to optimally use the space
@@ -81,9 +81,10 @@
mStatusBarWindowControllerStore = Dependency.get(StatusBarWindowControllerStore.class);
}
- void setLongPressGestureDetector(LongPressGestureDetector longPressGestureDetector) {
+ void setLongPressGestureDetector(
+ StatusBarLongPressGestureDetector statusBarLongPressGestureDetector) {
if (ShadeExpandsOnStatusBarLongPress.isEnabled()) {
- mLongPressGestureDetector = longPressGestureDetector;
+ mStatusBarLongPressGestureDetector = statusBarLongPressGestureDetector;
}
}
@@ -207,8 +208,9 @@
@Override
public boolean onTouchEvent(MotionEvent event) {
- if (ShadeExpandsOnStatusBarLongPress.isEnabled() && mLongPressGestureDetector != null) {
- mLongPressGestureDetector.handleTouch(event);
+ if (ShadeExpandsOnStatusBarLongPress.isEnabled()
+ && mStatusBarLongPressGestureDetector != null) {
+ mStatusBarLongPressGestureDetector.handleTouch(event);
}
if (mTouchEventHandler == null) {
Log.w(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
index a94db49..16e023c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
@@ -34,11 +34,11 @@
import com.android.systemui.res.R
import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.scene.ui.view.WindowRootView
-import com.android.systemui.shade.LongPressGestureDetector
import com.android.systemui.shade.ShadeController
import com.android.systemui.shade.ShadeExpandsOnStatusBarLongPress
import com.android.systemui.shade.ShadeLogger
import com.android.systemui.shade.ShadeViewController
+import com.android.systemui.shade.StatusBarLongPressGestureDetector
import com.android.systemui.shade.domain.interactor.PanelExpansionInteractor
import com.android.systemui.shared.animation.UnfoldMoveFromCenterAnimator
import com.android.systemui.statusbar.data.repository.StatusBarContentInsetsProviderStore
@@ -69,7 +69,7 @@
private val shadeController: ShadeController,
private val shadeViewController: ShadeViewController,
private val panelExpansionInteractor: PanelExpansionInteractor,
- private val longPressGestureDetector: Provider<LongPressGestureDetector>,
+ private val statusBarLongPressGestureDetector: Provider<StatusBarLongPressGestureDetector>,
private val windowRootView: Provider<WindowRootView>,
private val shadeLogger: ShadeLogger,
private val moveFromCenterAnimationController: StatusBarMoveFromCenterAnimationController?,
@@ -119,7 +119,7 @@
addCursorSupportToIconContainers()
if (ShadeExpandsOnStatusBarLongPress.isEnabled) {
- mView.setLongPressGestureDetector(longPressGestureDetector.get())
+ mView.setLongPressGestureDetector(statusBarLongPressGestureDetector.get())
}
progressProvider?.setReadyToHandleTransition(true)
@@ -336,7 +336,7 @@
private val shadeController: ShadeController,
private val shadeViewController: ShadeViewController,
private val panelExpansionInteractor: PanelExpansionInteractor,
- private val longPressGestureDetector: Provider<LongPressGestureDetector>,
+ private val statusBarLongPressGestureDetector: Provider<StatusBarLongPressGestureDetector>,
private val windowRootView: Provider<WindowRootView>,
private val shadeLogger: ShadeLogger,
private val viewUtil: ViewUtil,
@@ -361,7 +361,7 @@
shadeController,
shadeViewController,
panelExpansionInteractor,
- longPressGestureDetector,
+ statusBarLongPressGestureDetector,
windowRootView,
shadeLogger,
statusBarMoveFromCenterAnimationController,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractor.kt
index 9164da7..b2a0272 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractor.kt
@@ -17,7 +17,7 @@
package com.android.systemui.statusbar.pipeline.shared.domain.interactor
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.disableflags.data.repository.DisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.DisableFlagsInteractor
import com.android.systemui.statusbar.pipeline.shared.domain.model.StatusBarDisableFlagsVisibilityModel
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
@@ -30,13 +30,13 @@
@SysUISingleton
class CollapsedStatusBarInteractor
@Inject
-constructor(disableFlagsRepository: DisableFlagsRepository) {
+constructor(DisableFlagsInteractor: DisableFlagsInteractor) {
/**
* The visibilities of various status bar child views, based only on the information we received
* from disable flags.
*/
val visibilityViaDisableFlags: Flow<StatusBarDisableFlagsVisibilityModel> =
- disableFlagsRepository.disableFlags.map {
+ DisableFlagsInteractor.disableFlags.map {
StatusBarDisableFlagsVisibilityModel(
isClockAllowed = it.isClockEnabled,
areNotificationIconsAllowed = it.areNotificationIconsEnabled,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
index a1b56d6..a72c83e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
@@ -92,8 +92,7 @@
private var wifiPickerTracker: WifiPickerTracker? = null
- @VisibleForTesting
- val selectedUserContext: Flow<Context> =
+ private val selectedUserContext: Flow<Context> =
userRepository.selectedUserInfo.map {
applicationContext.createContextAsUser(UserHandle.of(it.id), /* flags= */ 0)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowController.kt
index 584cd3b..1e043ec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowController.kt
@@ -36,6 +36,9 @@
/** Adds the status bar view to the window manager. */
fun attach()
+ /** Called when work should stop and resources should be released. */
+ fun stop()
+
/** Adds the given view to the status bar window view. */
fun addViewToWindow(view: View, layoutParams: ViewGroup.LayoutParams)
@@ -78,7 +81,7 @@
*/
fun setOngoingProcessRequiresStatusBarVisible(visible: Boolean)
- interface Factory {
+ fun interface Factory {
fun create(
context: Context,
viewCaptureAwareWindowManager: ViewCaptureAwareWindowManager,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImpl.java
index 6953bbf..811a2ec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerImpl.java
@@ -51,10 +51,12 @@
import com.android.internal.policy.SystemBarUtils;
import com.android.systemui.animation.ActivityTransitionAnimator;
import com.android.systemui.animation.DelegateTransitionAnimatorController;
+import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.fragments.FragmentHostManager;
import com.android.systemui.fragments.FragmentService;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.core.StatusBarConnectedDisplays;
+import com.android.systemui.statusbar.core.StatusBarRootModernization;
import com.android.systemui.statusbar.data.repository.StatusBarConfigurationController;
import com.android.systemui.statusbar.phone.StatusBarContentInsetsProvider;
import com.android.systemui.statusbar.window.StatusBarWindowModule.InternalWindowViewInflater;
@@ -66,6 +68,7 @@
import dagger.assisted.AssistedInject;
import java.util.Optional;
+import java.util.concurrent.Executor;
/**
* Encapsulates all logic for the status bar window state management.
@@ -79,6 +82,7 @@
private final StatusBarConfigurationController mStatusBarConfigurationController;
private final IWindowManager mIWindowManager;
private final StatusBarContentInsetsProvider mContentInsetsProvider;
+ private final Executor mMainExecutor;
private int mBarHeight = -1;
private final State mCurrentState = new State();
private boolean mIsAttached;
@@ -101,12 +105,14 @@
IWindowManager iWindowManager,
@Assisted StatusBarContentInsetsProvider contentInsetsProvider,
FragmentService fragmentService,
- Optional<UnfoldTransitionProgressProvider> unfoldTransitionProgressProvider) {
+ Optional<UnfoldTransitionProgressProvider> unfoldTransitionProgressProvider,
+ @Main Executor mainExecutor) {
mContext = context;
mWindowManager = viewCaptureAwareWindowManager;
mStatusBarConfigurationController = statusBarConfigurationController;
mIWindowManager = iWindowManager;
mContentInsetsProvider = contentInsetsProvider;
+ mMainExecutor = mainExecutor;
mStatusBarWindowView = statusBarWindowViewInflater.inflate(context);
mFragmentService = fragmentService;
mLaunchAnimationContainer = mStatusBarWindowView.findViewById(
@@ -167,6 +173,19 @@
}
@Override
+ public void stop() {
+ StatusBarConnectedDisplays.assertInNewMode();
+
+ mWindowManager.removeView(mStatusBarWindowView);
+
+ if (StatusBarRootModernization.isEnabled()) {
+ return;
+ }
+ // Fragment transactions need to happen on the main thread.
+ mMainExecutor.execute(() -> mFragmentService.removeAndDestroy(mStatusBarWindowView));
+ }
+
+ @Override
public void addViewToWindow(@NonNull View view, @NonNull ViewGroup.LayoutParams layoutParams) {
mStatusBarWindowView.addView(view, layoutParams);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStore.kt b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStore.kt
index 051d463..7403161 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStore.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStore.kt
@@ -70,6 +70,10 @@
)
}
+ override suspend fun onDisplayRemovalAction(instance: StatusBarWindowController) {
+ instance.stop()
+ }
+
override val instanceClass = StatusBarWindowController::class.java
}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dialog/ringer/ui/binder/VolumeDialogRingerViewBinder.kt b/packages/SystemUI/src/com/android/systemui/volume/dialog/ringer/ui/binder/VolumeDialogRingerViewBinder.kt
index 6816d35..c4b028d 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dialog/ringer/ui/binder/VolumeDialogRingerViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/volume/dialog/ringer/ui/binder/VolumeDialogRingerViewBinder.kt
@@ -49,7 +49,7 @@
val drawerContainer = requireViewById<View>(R.id.volume_drawer_container)
val selectedButtonView =
requireViewById<ImageButton>(R.id.volume_new_ringer_active_button)
- val volumeDialogView = requireViewById<ViewGroup>(R.id.volume_dialog)
+ val volumeDialogBackgroundView = requireViewById<View>(R.id.volume_dialog_background)
repeatWhenAttached {
viewModel(
traceName = "VolumeDialogRingerViewBinder",
@@ -71,19 +71,17 @@
is RingerDrawerState.Initial -> {
drawerContainer.visibility = View.GONE
selectedButtonView.visibility = View.VISIBLE
- volumeDialogView.setBackgroundResource(
+ volumeDialogBackgroundView.setBackgroundResource(
R.drawable.volume_dialog_background
)
}
-
is RingerDrawerState.Closed -> {
drawerContainer.visibility = View.GONE
selectedButtonView.visibility = View.VISIBLE
- volumeDialogView.setBackgroundResource(
+ volumeDialogBackgroundView.setBackgroundResource(
R.drawable.volume_dialog_background
)
}
-
is RingerDrawerState.Open -> {
drawerContainer.visibility = View.VISIBLE
selectedButtonView.visibility = View.GONE
@@ -91,17 +89,16 @@
uiModel.currentButtonIndex !=
uiModel.availableButtons.size - 1
) {
- volumeDialogView.setBackgroundResource(
+ volumeDialogBackgroundView.setBackgroundResource(
R.drawable.volume_dialog_background_small_radius
)
}
}
}
}
-
is RingerViewModelState.Unavailable -> {
drawerAndRingerContainer.visibility = View.GONE
- volumeDialogView.setBackgroundResource(
+ volumeDialogBackgroundView.setBackgroundResource(
R.drawable.volume_dialog_background
)
}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dialog/sliders/ui/VolumeDialogSlidersViewBinder.kt b/packages/SystemUI/src/com/android/systemui/volume/dialog/sliders/ui/VolumeDialogSlidersViewBinder.kt
index a17c1e5..9078f82 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dialog/sliders/ui/VolumeDialogSlidersViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/volume/dialog/sliders/ui/VolumeDialogSlidersViewBinder.kt
@@ -38,9 +38,10 @@
fun bind(view: View) {
with(view) {
- val volumeDialog: View = requireViewById(R.id.volume_dialog)
val floatingSlidersContainer: ViewGroup =
requireViewById(R.id.volume_dialog_floating_sliders_container)
+ val mainSliderContainer: View =
+ requireViewById(R.id.volume_dialog_main_slider_container)
repeatWhenAttached {
viewModel(
traceName = "VolumeDialogSlidersViewBinder",
@@ -49,7 +50,7 @@
) { viewModel ->
viewModel.sliders
.onEach { uiModel ->
- uiModel.sliderComponent.sliderViewBinder().bind(volumeDialog)
+ uiModel.sliderComponent.sliderViewBinder().bind(mainSliderContainer)
val floatingSliderViewBinders = uiModel.floatingSliderComponent
floatingSlidersContainer.ensureChildCount(
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/binder/VolumeDialogViewBinder.kt b/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/binder/VolumeDialogViewBinder.kt
index d9a945c..f6c1743 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/binder/VolumeDialogViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/binder/VolumeDialogViewBinder.kt
@@ -19,13 +19,11 @@
import android.app.Dialog
import android.graphics.Rect
import android.graphics.Region
-import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.ViewTreeObserver.InternalInsetsInfo
-import android.widget.FrameLayout
-import androidx.annotation.GravityInt
+import androidx.constraintlayout.motion.widget.MotionLayout
import com.android.internal.view.RotationPolicy
import com.android.systemui.lifecycle.WindowLifecycleState
import com.android.systemui.lifecycle.repeatWhenAttached
@@ -41,7 +39,6 @@
import com.android.systemui.volume.dialog.ui.VolumeDialogResources
import com.android.systemui.volume.dialog.ui.utils.JankListenerFactory
import com.android.systemui.volume.dialog.ui.utils.suspendAnimate
-import com.android.systemui.volume.dialog.ui.viewmodel.VolumeDialogGravityViewModel
import com.android.systemui.volume.dialog.ui.viewmodel.VolumeDialogViewModel
import com.android.systemui.volume.dialog.utils.VolumeTracer
import javax.inject.Inject
@@ -53,6 +50,7 @@
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
+import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
@@ -63,7 +61,6 @@
@Inject
constructor(
private val volumeResources: VolumeDialogResources,
- private val gravityViewModel: VolumeDialogGravityViewModel,
private val dialogViewModelFactory: VolumeDialogViewModel.Factory,
private val jankListenerFactory: JankListenerFactory,
private val tracer: VolumeTracer,
@@ -74,21 +71,23 @@
fun bind(dialog: Dialog) {
// Root view of the Volume Dialog.
- val root: ViewGroup = dialog.requireViewById(R.id.volume_dialog_root)
- // Volume Dialog container view that contains the dialog itself without the floating sliders
- val container: View = root.requireViewById(R.id.volume_dialog_container)
- container.alpha = 0f
- container.repeatWhenAttached {
+ val root: MotionLayout = dialog.requireViewById(R.id.volume_dialog_root)
+ root.alpha = 0f
+ root.repeatWhenAttached {
root.viewModel(
traceName = "VolumeDialogViewBinder",
minWindowLifecycleState = WindowLifecycleState.ATTACHED,
factory = { dialogViewModelFactory.create() },
) { viewModel ->
- animateVisibility(container, dialog, viewModel.dialogVisibilityModel)
+ animateVisibility(root, dialog, viewModel.dialogVisibilityModel)
viewModel.dialogTitle.onEach { dialog.window?.setTitle(it) }.launchIn(this)
- gravityViewModel.dialogGravity
- .onEach { container.setLayoutGravity(it) }
+ viewModel.motionState
+ .scan(0) { acc, motionState ->
+ // don't animate the initial state
+ root.transitionToState(motionState, animate = acc != 0)
+ acc + 1
+ }
.launchIn(this)
launch { root.viewTreeObserver.computeInternalInsetsListener(root) }
@@ -130,15 +129,13 @@
.launchIn(this)
}
- private suspend fun calculateTranslationX(view: View): Float? {
+ private fun calculateTranslationX(view: View): Float? {
return if (view.display.rotation == RotationPolicy.NATURAL_ROTATION) {
- val dialogGravity = gravityViewModel.dialogGravity.first()
- val isGravityLeft = (dialogGravity and Gravity.LEFT) == Gravity.LEFT
- if (isGravityLeft) {
+ if (view.isLayoutRtl) {
-1
} else {
1
- } * view.width / 2.0f
+ } * view.width / 2f
} else {
null
}
@@ -211,10 +208,11 @@
getBoundsInWindow(boundsRect, false)
}
- private fun View.setLayoutGravity(@GravityInt newGravity: Int) {
- val frameLayoutParams =
- layoutParams as? FrameLayout.LayoutParams
- ?: error("View must be a child of a FrameLayout")
- layoutParams = frameLayoutParams.apply { gravity = newGravity }
+ private fun MotionLayout.transitionToState(newState: Int, animate: Boolean) {
+ if (animate) {
+ transitionToState(newState)
+ } else {
+ jumpToState(newState)
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogGravityViewModel.kt b/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogGravityViewModel.kt
deleted file mode 100644
index 112afb1..0000000
--- a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogGravityViewModel.kt
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2024 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.volume.dialog.ui.viewmodel
-
-import android.content.Context
-import android.content.res.Configuration
-import android.view.Gravity
-import androidx.annotation.GravityInt
-import com.android.systemui.dagger.qualifiers.Application
-import com.android.systemui.dagger.qualifiers.UiBackground
-import com.android.systemui.res.R
-import com.android.systemui.statusbar.policy.ConfigurationController
-import com.android.systemui.statusbar.policy.DevicePostureController
-import com.android.systemui.statusbar.policy.devicePosture
-import com.android.systemui.statusbar.policy.onConfigChanged
-import com.android.systemui.volume.dialog.dagger.scope.VolumeDialog
-import com.android.systemui.volume.dialog.dagger.scope.VolumeDialogScope
-import javax.inject.Inject
-import kotlin.coroutines.CoroutineContext
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.SharingStarted
-import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.onEach
-import kotlinx.coroutines.flow.stateIn
-import kotlinx.coroutines.withContext
-
-/** Exposes dialog [GravityInt] for use in the UI layer. */
-@VolumeDialogScope
-class VolumeDialogGravityViewModel
-@Inject
-constructor(
- @Application private val context: Context,
- @VolumeDialog private val coroutineScope: CoroutineScope,
- @UiBackground private val uiBackgroundCoroutineContext: CoroutineContext,
- configurationController: ConfigurationController,
- private val devicePostureController: DevicePostureController,
-) {
-
- @GravityInt private var originalGravity: Int = context.getAbsoluteGravity()
-
- val dialogGravity: Flow<Int> =
- combine(
- devicePostureController.devicePosture(),
- configurationController.onConfigChanged.onEach { onConfigurationChanged() },
- ) { devicePosture, configuration ->
- context.calculateGravity(devicePosture, configuration)
- }
- .stateIn(
- scope = coroutineScope,
- started = SharingStarted.Eagerly,
- context.calculateGravity(),
- )
-
- private suspend fun onConfigurationChanged() {
- withContext(uiBackgroundCoroutineContext) { originalGravity = context.getAbsoluteGravity() }
- }
-
- @GravityInt
- private fun Context.calculateGravity(
- devicePosture: Int = devicePostureController.devicePosture,
- config: Configuration = resources.configuration,
- ): Int {
- val isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE
- val isHalfOpen = devicePosture == DevicePostureController.DEVICE_POSTURE_HALF_OPENED
- val gravity =
- if (isLandscape && isHalfOpen) {
- originalGravity or Gravity.TOP
- } else {
- originalGravity
- }
- return getAbsoluteGravity(gravity)
- }
-}
-
-@GravityInt
-private fun Context.getAbsoluteGravity(
- gravity: Int = resources.getInteger(R.integer.volume_dialog_gravity)
-): Int = with(resources) { Gravity.getAbsoluteGravity(gravity, configuration.layoutDirection) }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogViewModel.kt b/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogViewModel.kt
index 869a6a2..0352799 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/volume/dialog/ui/viewmodel/VolumeDialogViewModel.kt
@@ -17,7 +17,12 @@
package com.android.systemui.volume.dialog.ui.viewmodel
import android.content.Context
+import android.content.res.Configuration
import com.android.systemui.res.R
+import com.android.systemui.statusbar.policy.ConfigurationController
+import com.android.systemui.statusbar.policy.DevicePostureController
+import com.android.systemui.statusbar.policy.devicePosture
+import com.android.systemui.statusbar.policy.onConfigChanged
import com.android.systemui.volume.dialog.domain.interactor.VolumeDialogStateInteractor
import com.android.systemui.volume.dialog.domain.interactor.VolumeDialogVisibilityInteractor
import com.android.systemui.volume.dialog.shared.model.VolumeDialogStateModel
@@ -32,6 +37,7 @@
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
/** Provides a state for the Volume Dialog. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -42,8 +48,23 @@
dialogVisibilityInteractor: VolumeDialogVisibilityInteractor,
volumeDialogSlidersInteractor: VolumeDialogSlidersInteractor,
volumeDialogStateInteractor: VolumeDialogStateInteractor,
+ devicePostureController: DevicePostureController,
+ configurationController: ConfigurationController,
) {
+ val motionState: Flow<Int> =
+ combine(
+ devicePostureController.devicePosture(),
+ configurationController.onConfigChanged.onStart {
+ emit(context.resources.configuration)
+ },
+ ) { devicePosture, configuration ->
+ if (shouldOffsetVolumeDialog(devicePosture, configuration)) {
+ R.id.volume_dialog_half_folded_constraint_set
+ } else {
+ R.id.volume_dialog_constraint_set
+ }
+ }
val dialogVisibilityModel: Flow<VolumeDialogVisibilityModel> =
dialogVisibilityInteractor.dialogVisibility
val dialogTitle: Flow<String> =
@@ -57,6 +78,13 @@
}
.filterNotNull()
+ /** @return true when the foldable device screen curve is in the way of the volume dialog */
+ private fun shouldOffsetVolumeDialog(devicePosture: Int, config: Configuration): Boolean {
+ val isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE
+ val isHalfOpen = devicePosture == DevicePostureController.DEVICE_POSTURE_HALF_OPENED
+ return isLandscape && isHalfOpen
+ }
+
@AssistedFactory
interface Factory {
fun create(): VolumeDialogViewModel
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
index 65b6273..2aa6e7b 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
@@ -105,8 +105,7 @@
private val mainExecutor = ImmediateExecutor()
private lateinit var repository: FakeKeyguardRepository
- private val messageBuffer = LogcatOnlyMessageBuffer(LogLevel.DEBUG)
- private val clockBuffers = ClockMessageBuffers(messageBuffer, messageBuffer, messageBuffer)
+ private val clockBuffers = ClockMessageBuffers(LogcatOnlyMessageBuffer(LogLevel.DEBUG))
private lateinit var underTest: ClockEventController
@Mock private lateinit var broadcastDispatcher: BroadcastDispatcher
diff --git a/packages/SystemUI/tests/src/com/android/systemui/animation/ActivityTransitionAnimatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/animation/ActivityTransitionAnimatorTest.kt
index a940bc9..425aad2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/animation/ActivityTransitionAnimatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/animation/ActivityTransitionAnimatorTest.kt
@@ -16,10 +16,12 @@
import android.view.RemoteAnimationTarget
import android.view.SurfaceControl
import android.view.ViewGroup
+import android.view.WindowManager.TRANSIT_NONE
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.window.RemoteTransition
import android.window.TransitionFilter
+import android.window.WindowAnimationState
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
@@ -34,6 +36,10 @@
import junit.framework.AssertionFailedError
import kotlin.concurrent.thread
import kotlin.test.assertEquals
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertThrows
import org.junit.Before
@@ -258,7 +264,6 @@
@DisableFlags(Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED)
@Test
fun doesNotRegisterLongLivedTransitionIfFlagIsDisabled() {
-
val controller =
object : DelegateTransitionAnimatorController(controller) {
override val transitionCookie =
@@ -273,7 +278,6 @@
@EnableFlags(Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED)
@Test
fun doesNotRegisterLongLivedTransitionIfMissingRequiredProperties() {
-
// No TransitionCookie
val controllerWithoutCookie =
object : DelegateTransitionAnimatorController(controller) {
@@ -348,7 +352,7 @@
fun doesNotStartIfAnimationIsCancelled() {
val runner = activityTransitionAnimator.createRunner(controller)
runner.onAnimationCancelled()
- runner.onAnimationStart(0, emptyArray(), emptyArray(), emptyArray(), iCallback)
+ runner.onAnimationStart(TRANSIT_NONE, emptyArray(), emptyArray(), emptyArray(), iCallback)
waitForIdleSync()
verify(controller).onTransitionAnimationCancelled()
@@ -361,7 +365,7 @@
@Test
fun cancelsIfNoOpeningWindowIsFound() {
val runner = activityTransitionAnimator.createRunner(controller)
- runner.onAnimationStart(0, emptyArray(), emptyArray(), emptyArray(), iCallback)
+ runner.onAnimationStart(TRANSIT_NONE, emptyArray(), emptyArray(), emptyArray(), iCallback)
waitForIdleSync()
verify(controller).onTransitionAnimationCancelled()
@@ -374,7 +378,13 @@
@Test
fun startsAnimationIfWindowIsOpening() {
val runner = activityTransitionAnimator.createRunner(controller)
- runner.onAnimationStart(0, arrayOf(fakeWindow()), emptyArray(), emptyArray(), iCallback)
+ runner.onAnimationStart(
+ TRANSIT_NONE,
+ arrayOf(fakeWindow()),
+ emptyArray(),
+ emptyArray(),
+ iCallback,
+ )
waitForIdleSync()
verify(listener).onTransitionAnimationStart()
verify(controller).onTransitionAnimationStart(anyBoolean())
@@ -387,6 +397,113 @@
}
}
+ @DisableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
+ @Test
+ fun creatingRunnerWithLazyInitializationThrows_whenTheFlagsAreDisabled() {
+ assertThrows(IllegalStateException::class.java) {
+ activityTransitionAnimator.createRunner(controller, initializeLazily = true)
+ }
+ }
+
+ @EnableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
+ @Test
+ fun runnerCreatesDelegateLazily_whenPostingTimeouts() {
+ val runner = activityTransitionAnimator.createRunner(controller, initializeLazily = true)
+ assertNull(runner.delegate)
+ runner.postTimeouts()
+ assertNotNull(runner.delegate)
+ }
+
+ @EnableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
+ @Test
+ fun runnerCreatesDelegateLazily_onAnimationStart() {
+ val runner = activityTransitionAnimator.createRunner(controller, initializeLazily = true)
+ assertNull(runner.delegate)
+
+ // The delegate is cleaned up after execution (which happens in another thread), so what we
+ // do instead is check if it becomes non-null at any point with a 1 second timeout. This
+ // will tell us that takeOverWithAnimation() triggered the lazy initialization.
+ var delegateInitialized = false
+ runBlocking {
+ val initChecker = launch {
+ withTimeout(1.seconds) {
+ while (runner.delegate == null) continue
+ delegateInitialized = true
+ }
+ }
+ runner.onAnimationStart(
+ TRANSIT_NONE,
+ arrayOf(fakeWindow()),
+ emptyArray(),
+ emptyArray(),
+ iCallback,
+ )
+ initChecker.join()
+ }
+ assertTrue(delegateInitialized)
+ }
+
+ @EnableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
+ @Test
+ fun runnerCreatesDelegateLazily_onAnimationTakeover() {
+ val runner = activityTransitionAnimator.createRunner(controller, initializeLazily = true)
+ assertNull(runner.delegate)
+
+ // The delegate is cleaned up after execution (which happens in another thread), so what we
+ // do instead is check if it becomes non-null at any point with a 1 second timeout. This
+ // will tell us that takeOverWithAnimation() triggered the lazy initialization.
+ var delegateInitialized = false
+ runBlocking {
+ val initChecker = launch {
+ withTimeout(1.seconds) {
+ while (runner.delegate == null) continue
+ delegateInitialized = true
+ }
+ }
+ runner.takeOverAnimation(
+ arrayOf(fakeWindow()),
+ arrayOf(WindowAnimationState()),
+ SurfaceControl.Transaction(),
+ iCallback,
+ )
+ initChecker.join()
+ }
+ assertTrue(delegateInitialized)
+ }
+
+ @DisableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
+ @Test
+ fun animationTakeoverThrows_whenTheFlagsAreDisabled() {
+ val runner = activityTransitionAnimator.createRunner(controller, initializeLazily = false)
+ assertThrows(IllegalStateException::class.java) {
+ runner.takeOverAnimation(
+ arrayOf(fakeWindow()),
+ emptyArray(),
+ SurfaceControl.Transaction(),
+ iCallback,
+ )
+ }
+ }
+
+ @DisableFlags(
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LIBRARY,
+ Flags.FLAG_RETURN_ANIMATION_FRAMEWORK_LONG_LIVED,
+ )
@Test
fun disposeRunner_delegateDereferenced() {
val runner = activityTransitionAnimator.createRunner(controller)
@@ -409,7 +526,7 @@
false,
Rect(),
Rect(),
- 0,
+ 1,
Point(),
Rect(),
bounds,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextViewTest.kt
index 8bd8b72..2812bd3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextViewTest.kt
@@ -15,11 +15,16 @@
*/
package systemui.shared.clocks.view
+import android.graphics.Typeface
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.plugins.clocks.ClockMessageBuffers
+import com.android.systemui.plugins.clocks.ClockSettings
+import com.android.systemui.shared.clocks.ClockContext
import com.android.systemui.shared.clocks.FontTextStyle
import com.android.systemui.shared.clocks.LogUtil
+import com.android.systemui.shared.clocks.TypefaceCache
import com.android.systemui.shared.clocks.view.SimpleDigitalClockTextView
import org.junit.Assert.assertEquals
import org.junit.Before
@@ -38,7 +43,23 @@
@Before
fun setup() {
- underTest = SimpleDigitalClockTextView(context, messageBuffer)
+ underTest =
+ SimpleDigitalClockTextView(
+ ClockContext(
+ context,
+ context.resources,
+ ClockSettings(),
+ TypefaceCache(messageBuffer) {
+ // TODO(b/364680873): Move constant to config_clockFontFamily when shipping
+ return@TypefaceCache Typeface.create(
+ "google-sans-flex-clock",
+ Typeface.NORMAL,
+ )
+ },
+ ClockMessageBuffers(messageBuffer),
+ messageBuffer,
+ )
+ )
underTest.textStyle = FontTextStyle()
underTest.aodStyle = FontTextStyle()
underTest.text = "0"
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
index a8618eb..3a46d03 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
@@ -20,9 +20,8 @@
import com.android.systemui.shade.data.repository.shadeRepository
import com.android.systemui.shade.domain.interactor.ShadeLockscreenInteractor
import com.android.systemui.shade.domain.interactor.shadeInteractor
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
-import com.android.systemui.statusbar.disableflags.data.repository.disableFlagsRepository
import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
import com.android.systemui.statusbar.notification.row.NotificationTestHelper
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout
@@ -31,7 +30,6 @@
import com.android.systemui.statusbar.phone.KeyguardBypassController
import com.android.systemui.statusbar.phone.ScrimController
import com.android.systemui.statusbar.policy.ResourcesSplitShadeStateController
-import com.android.systemui.statusbar.policy.configurationController
import com.android.systemui.statusbar.policy.fakeConfigurationController
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
@@ -144,7 +142,7 @@
context = context,
configurationController = configurationController,
dumpManager = mock(),
- splitShadeStateController = ResourcesSplitShadeStateController()
+ splitShadeStateController = ResourcesSplitShadeStateController(),
),
keyguardTransitionControllerFactory = { notificationPanelController ->
LockscreenShadeKeyguardTransitionController(
@@ -153,7 +151,7 @@
context = context,
configurationController = configurationController,
dumpManager = mock(),
- splitShadeStateController = ResourcesSplitShadeStateController()
+ splitShadeStateController = ResourcesSplitShadeStateController(),
)
},
depthController = depthController,
@@ -171,7 +169,7 @@
splitShadeStateController = ResourcesSplitShadeStateController(),
shadeLockscreenInteractorLazy = { shadeLockscreenInteractor },
naturalScrollingSettingObserver = naturalScrollingSettingObserver,
- lazyQSSceneAdapter = { qsSceneAdapter }
+ lazyQSSceneAdapter = { qsSceneAdapter },
)
transitionController.addCallback(transitionControllerCallback)
@@ -229,7 +227,7 @@
verify(statusbarStateController).setState(StatusBarState.SHADE_LOCKED)
assertFalse(
"Waking to shade locked when not dozing",
- transitionController.isWakingToShadeLocked
+ transitionController.isWakingToShadeLocked,
)
}
@@ -247,9 +245,7 @@
fun testDontGoWhenShadeDisabled() =
testScope.runTest {
disableFlagsRepository.disableFlags.value =
- DisableFlagsModel(
- disable2 = DISABLE2_NOTIFICATION_SHADE,
- )
+ DisableFlagsModel(disable2 = DISABLE2_NOTIFICATION_SHADE)
testScope.runCurrent()
transitionController.goToLockedShade(null)
verify(statusbarStateController, never()).setState(anyInt())
@@ -454,7 +450,7 @@
val distance = 10
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_scrim_transition_distance,
- distance
+ distance,
)
configurationController.notifyConfigurationChanged()
@@ -463,7 +459,7 @@
verify(scrimController)
.transitionToFullShadeProgress(
progress = eq(0.5f),
- lockScreenNotificationsProgress = anyFloat()
+ lockScreenNotificationsProgress = anyFloat(),
)
}
@@ -474,11 +470,11 @@
val delay = 10
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_distance,
- distance
+ distance,
)
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_delay,
- delay
+ delay,
)
configurationController.notifyConfigurationChanged()
@@ -487,7 +483,7 @@
verify(scrimController)
.transitionToFullShadeProgress(
progress = anyFloat(),
- lockScreenNotificationsProgress = eq(0.1f)
+ lockScreenNotificationsProgress = eq(0.1f),
)
}
@@ -498,11 +494,11 @@
val delay = 50
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_distance,
- distance
+ distance,
)
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_delay,
- delay
+ delay,
)
configurationController.notifyConfigurationChanged()
@@ -511,7 +507,7 @@
verify(scrimController)
.transitionToFullShadeProgress(
progress = anyFloat(),
- lockScreenNotificationsProgress = eq(0f)
+ lockScreenNotificationsProgress = eq(0f),
)
}
@@ -522,11 +518,11 @@
val delay = 50
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_distance,
- distance
+ distance,
)
context.orCreateTestableResources.addOverride(
R.dimen.lockscreen_shade_notifications_scrim_transition_delay,
- delay
+ delay,
)
configurationController.notifyConfigurationChanged()
@@ -535,7 +531,7 @@
verify(scrimController)
.transitionToFullShadeProgress(
progress = anyFloat(),
- lockScreenNotificationsProgress = eq(1f)
+ lockScreenNotificationsProgress = eq(1f),
)
}
@@ -627,7 +623,7 @@
*/
private fun ScrimController.transitionToFullShadeProgress(
progress: Float,
- lockScreenNotificationsProgress: Float
+ lockScreenNotificationsProgress: Float,
) {
setTransitionToFullShadeProgress(progress, lockScreenNotificationsProgress)
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
index c9ada7e..b142fc2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
@@ -155,6 +155,7 @@
import com.android.systemui.shade.ShadeControllerImpl;
import com.android.systemui.shade.ShadeExpansionStateManager;
import com.android.systemui.shade.ShadeLogger;
+import com.android.systemui.shade.StatusBarLongPressGestureDetector;
import com.android.systemui.shared.notifications.domain.interactor.NotificationSettingsInteractor;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.KeyboardShortcutListSearch;
@@ -174,7 +175,6 @@
import com.android.systemui.statusbar.StatusBarStateControllerImpl;
import com.android.systemui.statusbar.core.StatusBarConnectedDisplays;
import com.android.systemui.statusbar.core.StatusBarInitializerImpl;
-import com.android.systemui.statusbar.core.StatusBarOrchestrator;
import com.android.systemui.statusbar.data.repository.FakeStatusBarModeRepository;
import com.android.systemui.statusbar.data.repository.StatusBarModePerDisplayRepository;
import com.android.systemui.statusbar.notification.NotifPipelineFlags;
@@ -372,7 +372,7 @@
@Mock private EmergencyGestureIntentFactory mEmergencyGestureIntentFactory;
@Mock private NotificationSettingsInteractor mNotificationSettingsInteractor;
@Mock private ViewCaptureAwareWindowManager mViewCaptureAwareWindowManager;
- @Mock private StatusBarOrchestrator mStatusBarOrchestrator;
+ @Mock private StatusBarLongPressGestureDetector mStatusBarLongPressGestureDetector;
private ShadeController mShadeController;
private final FakeSystemClock mFakeSystemClock = new FakeSystemClock();
private final FakeGlobalSettings mFakeGlobalSettings = new FakeGlobalSettings();
@@ -607,6 +607,7 @@
mShadeController,
mWindowRootViewVisibilityInteractor,
mStatusBarKeyguardViewManager,
+ () -> mStatusBarLongPressGestureDetector,
mViewMediatorCallback,
mInitController,
new Handler(TestableLooper.get(this).getLooper()),
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
index 638f195..69efa87 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
@@ -40,14 +40,13 @@
import com.android.systemui.plugins.fakeDarkIconDispatcher
import com.android.systemui.res.R
import com.android.systemui.scene.ui.view.WindowRootView
-import com.android.systemui.shade.LongPressGestureDetector
import com.android.systemui.shade.ShadeControllerImpl
import com.android.systemui.shade.ShadeLogger
import com.android.systemui.shade.ShadeViewController
+import com.android.systemui.shade.StatusBarLongPressGestureDetector
import com.android.systemui.shade.domain.interactor.PanelExpansionInteractor
import com.android.systemui.statusbar.CommandQueue
import com.android.systemui.statusbar.data.repository.fakeStatusBarContentInsetsProviderStore
-import com.android.systemui.statusbar.data.repository.statusBarContentInsetsProviderStore
import com.android.systemui.statusbar.policy.Clock
import com.android.systemui.statusbar.policy.ConfigurationController
import com.android.systemui.statusbar.window.StatusBarWindowStateController
@@ -98,7 +97,7 @@
@Mock private lateinit var windowRootView: Provider<WindowRootView>
@Mock private lateinit var shadeLogger: ShadeLogger
@Mock private lateinit var viewUtil: ViewUtil
- @Mock private lateinit var longPressGestureDetector: LongPressGestureDetector
+ @Mock private lateinit var mStatusBarLongPressGestureDetector: StatusBarLongPressGestureDetector
private lateinit var statusBarWindowStateController: StatusBarWindowStateController
private lateinit var view: PhoneStatusBarView
@@ -395,7 +394,7 @@
shadeControllerImpl,
shadeViewController,
panelExpansionInteractor,
- { longPressGestureDetector },
+ { mStatusBarLongPressGestureDetector },
windowRootView,
shadeLogger,
viewUtil,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
index d1303d2..3d60abf 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
@@ -71,6 +71,8 @@
import com.android.systemui.shade.ui.viewmodel.notificationShadeWindowModel
import com.android.systemui.statusbar.chips.ui.viewmodel.ongoingActivityChipsViewModel
import com.android.systemui.statusbar.data.repository.fakeStatusBarModePerDisplayRepository
+import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.disableFlagsInteractor
import com.android.systemui.statusbar.notification.collection.provider.visualStabilityProvider
import com.android.systemui.statusbar.notification.domain.interactor.activeNotificationsInteractor
import com.android.systemui.statusbar.notification.domain.interactor.seenNotificationsInteractor
@@ -183,4 +185,6 @@
val lockscreenToGlanceableHubTransitionViewModel by lazy {
kosmos.lockscreenToGlanceableHubTransitionViewModel
}
+ val disableFlagsInteractor by lazy { kosmos.disableFlagsInteractor }
+ val fakeDisableFlagsRepository by lazy { kosmos.fakeDisableFlagsRepository }
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelKosmos.kt
index 4ed49123..45d5b38 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/composefragment/viewmodel/QSFragmentComposeViewModelKosmos.kt
@@ -33,7 +33,7 @@
import com.android.systemui.qs.ui.viewmodel.quickSettingsContainerViewModelFactory
import com.android.systemui.shade.largeScreenHeaderHelper
import com.android.systemui.shade.transition.largeScreenShadeInterpolator
-import com.android.systemui.statusbar.disableflags.data.repository.disableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.disableFlagsInteractor
import com.android.systemui.statusbar.sysuiStatusBarStateController
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -51,7 +51,7 @@
footerActionsController,
sysuiStatusBarStateController,
deviceEntryInteractor,
- disableFlagsRepository,
+ disableFlagsInteractor,
keyguardTransitionInteractor,
largeScreenShadeInterpolator,
configurationInteractor,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeInteractorKosmos.kt
index 39f58ae..af6d624 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeInteractorKosmos.kt
@@ -25,7 +25,7 @@
import com.android.systemui.scene.domain.interactor.sceneInteractor
import com.android.systemui.shade.ShadeModule
import com.android.systemui.shade.data.repository.shadeRepository
-import com.android.systemui.statusbar.disableflags.data.repository.disableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.disableFlagsInteractor
import com.android.systemui.statusbar.phone.dozeParameters
import com.android.systemui.statusbar.policy.data.repository.userSetupRepository
import com.android.systemui.statusbar.policy.domain.interactor.deviceProvisioningInteractor
@@ -60,7 +60,7 @@
ShadeInteractorImpl(
scope = applicationCoroutineScope,
deviceProvisioningInteractor = deviceProvisioningInteractor,
- disableFlagsRepository = disableFlagsRepository,
+ disableFlagsInteractor = disableFlagsInteractor,
dozeParams = dozeParameters,
keyguardRepository = fakeKeyguardRepository,
keyguardTransitionInteractor = keyguardTransitionInteractor,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/data/repository/FakeDisableFlagsRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/data/repository/FakeDisableFlagsRepository.kt
index 466a3eb..9dbb547 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/data/repository/FakeDisableFlagsRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/data/repository/FakeDisableFlagsRepository.kt
@@ -15,7 +15,7 @@
package com.android.systemui.statusbar.disableflags.data.repository
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.disableflags.data.model.DisableFlagsModel
+import com.android.systemui.statusbar.disableflags.shared.model.DisableFlagsModel
import dagger.Binds
import dagger.Module
import javax.inject.Inject
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractorKosmos.kt
new file mode 100644
index 0000000..7b4b047
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/disableflags/domain/interactor/DisableFlagsInteractorKosmos.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2024 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.disableflags.domain.interactor
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.statusbar.disableflags.data.repository.disableFlagsRepository
+
+val Kosmos.disableFlagsInteractor by Fixture {
+ DisableFlagsInteractor(repository = disableFlagsRepository)
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorKosmos.kt
index 385a813..13fde96 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/shared/domain/interactor/CollapsedStatusBarInteractorKosmos.kt
@@ -17,7 +17,7 @@
package com.android.systemui.statusbar.pipeline.shared.domain.interactor
import com.android.systemui.kosmos.Kosmos
-import com.android.systemui.statusbar.disableflags.data.repository.fakeDisableFlagsRepository
+import com.android.systemui.statusbar.disableflags.domain.interactor.disableFlagsInteractor
val Kosmos.collapsedStatusBarInteractor: CollapsedStatusBarInteractor by
- Kosmos.Fixture { CollapsedStatusBarInteractor(fakeDisableFlagsRepository) }
+ Kosmos.Fixture { CollapsedStatusBarInteractor(disableFlagsInteractor) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/FakeStatusBarWindowController.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/FakeStatusBarWindowController.kt
index 528c9d9..a110a49 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/FakeStatusBarWindowController.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/FakeStatusBarWindowController.kt
@@ -27,6 +27,9 @@
var isAttached = false
private set
+ var isStopped = false
+ private set
+
override val statusBarHeight: Int = 0
override fun refreshStatusBarHeight() {}
@@ -35,6 +38,10 @@
isAttached = true
}
+ override fun stop() {
+ isStopped = true
+ }
+
override fun addViewToWindow(view: View, layoutParams: ViewGroup.LayoutParams) {}
override val backgroundView: View
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerKosmos.kt
index 173e909..23f2b42 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerKosmos.kt
@@ -18,7 +18,8 @@
import android.content.testableContext
import android.view.windowManagerService
-import com.android.app.viewcapture.viewCaptureAwareWindowManager
+import com.android.app.viewcapture.realCaptureAwareWindowManager
+import com.android.systemui.concurrency.fakeExecutor
import com.android.systemui.fragments.fragmentService
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.statusbar.phone.statusBarContentInsetsProvider
@@ -32,12 +33,13 @@
StatusBarWindowControllerImpl(
testableContext,
statusBarWindowViewInflater,
- viewCaptureAwareWindowManager,
+ realCaptureAwareWindowManager,
statusBarConfigurationController,
windowManagerService,
statusBarContentInsetsProvider,
fragmentService,
Optional.empty(),
+ fakeExecutor,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStoreKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStoreKosmos.kt
new file mode 100644
index 0000000..4941ceb
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/window/StatusBarWindowControllerStoreKosmos.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2024 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.window
+
+import android.view.WindowManager
+import com.android.app.viewcapture.ViewCaptureAwareWindowManager
+import com.android.app.viewcapture.realCaptureAwareWindowManager
+import com.android.systemui.display.data.repository.displayRepository
+import com.android.systemui.display.data.repository.displayWindowPropertiesRepository
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.applicationCoroutineScope
+import com.android.systemui.statusbar.data.repository.statusBarConfigurationControllerStore
+import com.android.systemui.statusbar.data.repository.statusBarContentInsetsProviderStore
+import org.mockito.kotlin.mock
+
+val Kosmos.multiDisplayStatusBarWindowControllerStore by
+ Kosmos.Fixture {
+ MultiDisplayStatusBarWindowControllerStore(
+ backgroundApplicationScope = applicationCoroutineScope,
+ controllerFactory = { _, _, _, _ -> mock() },
+ displayWindowPropertiesRepository = displayWindowPropertiesRepository,
+ viewCaptureAwareWindowManagerFactory =
+ object : ViewCaptureAwareWindowManager.Factory {
+ override fun create(
+ windowManager: WindowManager
+ ): ViewCaptureAwareWindowManager {
+ return realCaptureAwareWindowManager
+ }
+ },
+ statusBarConfigurationControllerStore = statusBarConfigurationControllerStore,
+ statusBarContentInsetsProviderStore = statusBarContentInsetsProviderStore,
+ displayRepository = displayRepository,
+ )
+ }
diff --git a/services/autofill/features.aconfig b/services/autofill/features.aconfig
index bd46deb..b3fe5f2 100644
--- a/services/autofill/features.aconfig
+++ b/services/autofill/features.aconfig
@@ -2,6 +2,13 @@
container: "system"
flag {
+ name: "autofill_w_metrics"
+ namespace: "autofill"
+ description: "Guards against new metrics definitions introduced in W"
+ bug: "342676602"
+}
+
+flag {
name: "autofill_credman_integration"
namespace: "autofill"
description: "Guards Autofill Framework against Autofill-Credman integration"
diff --git a/services/core/java/com/android/server/am/BroadcastFilter.java b/services/core/java/com/android/server/am/BroadcastFilter.java
index e20c46c..a32d3cb 100644
--- a/services/core/java/com/android/server/am/BroadcastFilter.java
+++ b/services/core/java/com/android/server/am/BroadcastFilter.java
@@ -16,6 +16,7 @@
package com.android.server.am;
+import android.annotation.NonNull;
import android.annotation.Nullable;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
@@ -56,11 +57,12 @@
final boolean visibleToInstantApp;
public final boolean exported;
final int initialPriority;
+ final ApplicationInfo applicationInfo;
BroadcastFilter(IntentFilter _filter, ReceiverList _receiverList,
String _packageName, String _featureId, String _receiverId, String _requiredPermission,
int _owningUid, int _userId, boolean _instantApp, boolean _visibleToInstantApp,
- boolean _exported, ApplicationInfo applicationInfo, PlatformCompat platformCompat) {
+ boolean _exported, ApplicationInfo _applicationInfo, PlatformCompat platformCompat) {
super(_filter);
receiverList = _receiverList;
packageName = _packageName;
@@ -72,6 +74,7 @@
instantApp = _instantApp;
visibleToInstantApp = _visibleToInstantApp;
exported = _exported;
+ applicationInfo = _applicationInfo;
initialPriority = getPriority();
setPriority(calculateAdjustedPriority(owningUid, initialPriority,
applicationInfo, platformCompat));
@@ -87,6 +90,10 @@
return null;
}
+ public @NonNull ApplicationInfo getApplicationInfo() {
+ return applicationInfo;
+ }
+
@NeverCompile
public void dumpDebug(ProtoOutputStream proto, long fieldId) {
long token = proto.start(fieldId);
diff --git a/services/core/java/com/android/server/am/BroadcastRecord.java b/services/core/java/com/android/server/am/BroadcastRecord.java
index e8ce173..a1ab1eea 100644
--- a/services/core/java/com/android/server/am/BroadcastRecord.java
+++ b/services/core/java/com/android/server/am/BroadcastRecord.java
@@ -49,6 +49,7 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.os.Binder;
import android.os.Bundle;
@@ -57,7 +58,6 @@
import android.util.ArrayMap;
import android.util.IntArray;
import android.util.PrintWriterPrinter;
-import android.util.SparseBooleanArray;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
@@ -865,25 +865,35 @@
@VisibleForTesting
static @NonNull boolean[] calculateChangeStateForReceivers(@NonNull List<Object> receivers,
long changeId, PlatformCompat platformCompat) {
- final SparseBooleanArray changeStateForUids = new SparseBooleanArray();
+ // TODO: b/371307720 - Remove this method as we are already avoiding the packagemanager
+ // calls by checking the changeId state using ApplicationInfos.
+ final ArrayMap<String, Boolean> changeStates = new ArrayMap<>();
final int count = receivers.size();
final boolean[] changeStateForReceivers = new boolean[count];
for (int i = 0; i < count; ++i) {
- final int receiverUid = getReceiverUid(receivers.get(i));
+ final ApplicationInfo receiverAppInfo = getReceiverAppInfo(receivers.get(i));
final boolean isChangeEnabled;
- final int idx = changeStateForUids.indexOfKey(receiverUid);
+ final int idx = changeStates.indexOfKey(receiverAppInfo.packageName);
if (idx >= 0) {
- isChangeEnabled = changeStateForUids.valueAt(idx);
+ isChangeEnabled = changeStates.valueAt(idx);
} else {
- isChangeEnabled = platformCompat.isChangeEnabledByUidInternalNoLogging(
- changeId, receiverUid);
- changeStateForUids.put(receiverUid, isChangeEnabled);
+ isChangeEnabled = platformCompat.isChangeEnabledInternalNoLogging(
+ changeId, receiverAppInfo);
+ changeStates.put(receiverAppInfo.packageName, isChangeEnabled);
}
changeStateForReceivers[i] = isChangeEnabled;
}
return changeStateForReceivers;
}
+ static ApplicationInfo getReceiverAppInfo(@NonNull Object receiver) {
+ if (receiver instanceof BroadcastFilter) {
+ return ((BroadcastFilter) receiver).getApplicationInfo();
+ } else {
+ return ((ResolveInfo) receiver).activityInfo.applicationInfo;
+ }
+ }
+
static int getReceiverUid(@NonNull Object receiver) {
if (receiver instanceof BroadcastFilter) {
return ((BroadcastFilter) receiver).owningUid;
diff --git a/services/core/java/com/android/server/biometrics/PreAuthInfo.java b/services/core/java/com/android/server/biometrics/PreAuthInfo.java
index afdc0c0..6ed1ac85 100644
--- a/services/core/java/com/android/server/biometrics/PreAuthInfo.java
+++ b/services/core/java/com/android/server/biometrics/PreAuthInfo.java
@@ -226,10 +226,6 @@
return BIOMETRIC_NO_HARDWARE;
}
- if (sensor.modality == TYPE_FACE && biometricCameraManager.isAnyCameraUnavailable()) {
- return BIOMETRIC_HARDWARE_NOT_DETECTED;
- }
-
final boolean wasStrongEnough =
Utils.isAtLeastStrength(sensor.oemStrength, requestedStrength);
final boolean isStrongEnough =
@@ -241,6 +237,10 @@
return BIOMETRIC_INSUFFICIENT_STRENGTH;
}
+ if (sensor.modality == TYPE_FACE && biometricCameraManager.isAnyCameraUnavailable()) {
+ return BIOMETRIC_HARDWARE_NOT_DETECTED;
+ }
+
try {
if (!sensor.impl.isHardwareDetected(opPackageName)) {
return BIOMETRIC_HARDWARE_NOT_DETECTED;
diff --git a/services/core/java/com/android/server/compat/PlatformCompat.java b/services/core/java/com/android/server/compat/PlatformCompat.java
index eeac260..6feae34 100644
--- a/services/core/java/com/android/server/compat/PlatformCompat.java
+++ b/services/core/java/com/android/server/compat/PlatformCompat.java
@@ -522,7 +522,7 @@
// b/282922910 - we don't want apps sharing system uid and targeting
// older target sdk to impact all system uid apps
if (Flags.systemUidTargetSystemSdk() && !mIsWear &&
- uid == Process.SYSTEM_UID) {
+ uid == Process.SYSTEM_UID && appInfo != null) {
appInfo.targetSdkVersion = Build.VERSION.SDK_INT;
}
return appInfo;
diff --git a/services/core/java/com/android/server/display/color/TintController.java b/services/core/java/com/android/server/display/color/TintController.java
index 716661d..68dc80f 100644
--- a/services/core/java/com/android/server/display/color/TintController.java
+++ b/services/core/java/com/android/server/display/color/TintController.java
@@ -19,6 +19,7 @@
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.Slog;
+import com.android.internal.annotations.GuardedBy;
import java.io.PrintWriter;
@@ -29,23 +30,33 @@
*/
private static final long TRANSITION_DURATION = 3000L;
+ private final Object mLock = new Object();
+
+ @GuardedBy("mLock")
private ValueAnimator mAnimator;
+ @GuardedBy("mLock")
private Boolean mIsActivated;
public ValueAnimator getAnimator() {
- return mAnimator;
+ synchronized (mLock) {
+ return mAnimator;
+ }
}
public void setAnimator(ValueAnimator animator) {
- mAnimator = animator;
+ synchronized (mLock) {
+ mAnimator = animator;
+ }
}
/**
* Cancel the animator if it's still running.
*/
public void cancelAnimator() {
- if (mAnimator != null) {
- mAnimator.cancel();
+ synchronized (mLock) {
+ if (mAnimator != null) {
+ mAnimator.cancel();
+ }
}
}
@@ -53,22 +64,30 @@
* End the animator if it's still running, jumping to the end state.
*/
public void endAnimator() {
- if (mAnimator != null) {
- mAnimator.end();
- mAnimator = null;
+ synchronized (mLock) {
+ if (mAnimator != null) {
+ mAnimator.end();
+ mAnimator = null;
+ }
}
}
public void setActivated(Boolean isActivated) {
- mIsActivated = isActivated;
+ synchronized (mLock) {
+ mIsActivated = isActivated;
+ }
}
public boolean isActivated() {
- return mIsActivated != null && mIsActivated;
+ synchronized (mLock) {
+ return mIsActivated != null && mIsActivated;
+ }
}
public boolean isActivatedStateNotSet() {
- return mIsActivated == null;
+ synchronized (mLock) {
+ return mIsActivated == null;
+ }
}
public long getTransitionDurationMilliseconds() {
diff --git a/services/core/java/com/android/server/input/AppLaunchShortcutManager.java b/services/core/java/com/android/server/input/AppLaunchShortcutManager.java
index aef207f..f3820e5 100644
--- a/services/core/java/com/android/server/input/AppLaunchShortcutManager.java
+++ b/services/core/java/com/android/server/input/AppLaunchShortcutManager.java
@@ -21,6 +21,7 @@
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
+import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.hardware.input.AppLaunchData;
import android.hardware.input.InputGestureData;
@@ -137,11 +138,19 @@
String categoryName = parser.getAttributeValue(null, ATTRIBUTE_CATEGORY);
String shiftName = parser.getAttributeValue(null, ATTRIBUTE_SHIFT);
String roleName = parser.getAttributeValue(null, ATTRIBUTE_ROLE);
-
- // TODO(b/358569822): Shift bookmarks to use keycode instead of shortcutChar
- int keycode = KeyEvent.KEYCODE_UNKNOWN;
String shortcut = parser.getAttributeValue(null, ATTRIBUTE_SHORTCUT);
- if (!TextUtils.isEmpty(shortcut)) {
+ int keycode;
+ int modifierState;
+ TypedArray a = mContext.getResources().obtainAttributes(parser,
+ R.styleable.Bookmark);
+ try {
+ keycode = a.getInt(R.styleable.Bookmark_keycode, KeyEvent.KEYCODE_UNKNOWN);
+ modifierState = a.getInt(R.styleable.Bookmark_modifierState, 0);
+ } finally {
+ a.recycle();
+ }
+ if (keycode == KeyEvent.KEYCODE_UNKNOWN && !TextUtils.isEmpty(shortcut)) {
+ // Fetch keycode using shortcut char
KeyEvent[] events = virtualKcm.getEvents(new char[]{shortcut.toLowerCase(
Locale.ROOT).charAt(0)});
// Single key press can generate the character
@@ -153,12 +162,17 @@
Log.w(TAG, "Keycode required for bookmark with category=" + categoryName
+ " packageName=" + packageName + " className=" + className
+ " role=" + roleName + " shiftName=" + shiftName
- + " shortcut=" + shortcut);
+ + " shortcut=" + shortcut + " modifierState=" + modifierState);
continue;
}
- final boolean isShiftShortcut = (shiftName != null && shiftName.toLowerCase(
- Locale.ROOT).equals("true"));
+ if (modifierState == 0) {
+ // Fetch modifierState using shiftName
+ boolean isShiftShortcut = shiftName != null && shiftName.toLowerCase(
+ Locale.ROOT).equals("true");
+ modifierState =
+ KeyEvent.META_META_ON | (isShiftShortcut ? KeyEvent.META_SHIFT_ON : 0);
+ }
AppLaunchData launchData = null;
if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
launchData = AppLaunchData.createLaunchDataForComponent(packageName, className);
@@ -168,11 +182,9 @@
launchData = AppLaunchData.createLaunchDataForRole(roleName);
}
if (launchData != null) {
- Log.d(TAG, "adding shortcut " + launchData + "shift="
- + isShiftShortcut + " keycode=" + keycode);
+ Log.d(TAG, "adding shortcut " + launchData + " modifierState="
+ + modifierState + " keycode=" + keycode);
// All bookmarks are based on Action key
- int modifierState =
- KeyEvent.META_META_ON | (isShiftShortcut ? KeyEvent.META_SHIFT_ON : 0);
InputGestureData bookmark = new InputGestureData.Builder()
.setTrigger(InputGestureData.createKeyTrigger(keycode, modifierState))
.setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 82449ce..edad247 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -193,7 +193,6 @@
private DisplayManagerInternal mDisplayManagerInternal;
private WindowManagerInternal mWindowManagerInternal;
- private PackageManagerInternal mPackageManagerInternal;
private final File mDoubleTouchGestureEnableFile;
@@ -573,7 +572,6 @@
mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
- mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
mSettingsObserver.registerAndUpdate();
@@ -2937,10 +2935,11 @@
private void enforceManageKeyGesturePermission() {
// TODO(b/361567988): Use @EnforcePermission to enforce permission once flag guarding the
// permission is rolled out
- if (mSystemReady) {
- String systemUIPackage = mContext.getString(R.string.config_systemUi);
- int systemUIAppId = UserHandle.getAppId(mPackageManagerInternal
- .getPackageUid(systemUIPackage, PackageManager.MATCH_SYSTEM_ONLY,
+ String systemUIPackage = mContext.getString(R.string.config_systemUi);
+ PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
+ if (pm != null) {
+ int systemUIAppId = UserHandle.getAppId(
+ pm.getPackageUid(systemUIPackage, PackageManager.MATCH_SYSTEM_ONLY,
UserHandle.USER_SYSTEM));
if (UserHandle.getCallingAppId() == systemUIAppId) {
return;
diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubHalEndpointCallback.java b/services/core/java/com/android/server/location/contexthub/ContextHubHalEndpointCallback.java
new file mode 100644
index 0000000..c05f7a0
--- /dev/null
+++ b/services/core/java/com/android/server/location/contexthub/ContextHubHalEndpointCallback.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2024 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.location.contexthub;
+
+import android.hardware.contexthub.EndpointId;
+import android.hardware.contexthub.HubEndpointInfo;
+import android.hardware.contexthub.IEndpointCallback;
+import android.hardware.contexthub.Message;
+import android.hardware.contexthub.MessageDeliveryStatus;
+import android.os.RemoteException;
+
+/** IEndpointCallback implementation. */
+public class ContextHubHalEndpointCallback
+ extends android.hardware.contexthub.IEndpointCallback.Stub {
+ private final IEndpointLifecycleCallback mEndpointLifecycleCallback;
+
+ /** Interface for listening for endpoint start and stop events. */
+ public interface IEndpointLifecycleCallback {
+ /** Called when a batch of endpoints started. */
+ void onEndpointStarted(HubEndpointInfo[] endpointInfos);
+
+ /** Called when a batch of endpoints stopped. */
+ void onEndpointStopped(HubEndpointInfo.HubEndpointIdentifier[] endpointIds, byte reason);
+ }
+
+ ContextHubHalEndpointCallback(IEndpointLifecycleCallback endpointLifecycleCallback) {
+ mEndpointLifecycleCallback = endpointLifecycleCallback;
+ }
+
+ @Override
+ public void onEndpointStarted(android.hardware.contexthub.EndpointInfo[] halEndpointInfos)
+ throws RemoteException {
+ if (halEndpointInfos.length == 0) {
+ return;
+ }
+ HubEndpointInfo[] endpointInfos = new HubEndpointInfo[halEndpointInfos.length];
+ for (int i = 0; i < halEndpointInfos.length; i++) {
+ endpointInfos[i++] = new HubEndpointInfo(halEndpointInfos[i]);
+ }
+ mEndpointLifecycleCallback.onEndpointStarted(endpointInfos);
+ }
+
+ @Override
+ public void onEndpointStopped(EndpointId[] halEndpointIds, byte reason) throws RemoteException {
+ HubEndpointInfo.HubEndpointIdentifier[] endpointIds =
+ new HubEndpointInfo.HubEndpointIdentifier[halEndpointIds.length];
+ for (int i = 0; i < halEndpointIds.length; i++) {
+ endpointIds[i] = new HubEndpointInfo.HubEndpointIdentifier(halEndpointIds[i]);
+ }
+ mEndpointLifecycleCallback.onEndpointStopped(endpointIds, reason);
+ }
+
+ @Override
+ public void onMessageReceived(int i, Message message) throws RemoteException {}
+
+ @Override
+ public void onMessageDeliveryStatusReceived(int i, MessageDeliveryStatus messageDeliveryStatus)
+ throws RemoteException {}
+
+ @Override
+ public void onEndpointSessionOpenRequest(
+ int i, EndpointId endpointId, EndpointId endpointId1, String s)
+ throws RemoteException {}
+
+ @Override
+ public void onCloseEndpointSession(int i, byte b) throws RemoteException {}
+
+ @Override
+ public void onEndpointSessionOpenComplete(int i) throws RemoteException {}
+
+ @Override
+ public int getInterfaceVersion() throws RemoteException {
+ return IEndpointCallback.VERSION;
+ }
+
+ @Override
+ public String getInterfaceHash() throws RemoteException {
+ return IEndpointCallback.HASH;
+ }
+}
diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubService.java b/services/core/java/com/android/server/location/contexthub/ContextHubService.java
index f611c57..8cf0578 100644
--- a/services/core/java/com/android/server/location/contexthub/ContextHubService.java
+++ b/services/core/java/com/android/server/location/contexthub/ContextHubService.java
@@ -31,6 +31,9 @@
import android.hardware.SensorPrivacyManager;
import android.hardware.SensorPrivacyManagerInternal;
import android.hardware.contexthub.ErrorCode;
+import android.hardware.contexthub.HubEndpointInfo;
+import android.hardware.contexthub.IContextHubEndpoint;
+import android.hardware.contexthub.IContextHubEndpointCallback;
import android.hardware.contexthub.MessageDeliveryStatus;
import android.hardware.location.ContextHubInfo;
import android.hardware.location.ContextHubMessage;
@@ -249,6 +252,7 @@
public void handleServiceRestart() {
Log.i(TAG, "Recovering from Context Hub HAL restart...");
initExistingCallbacks();
+ mHubInfoRegistry.onHalRestart();
resetSettings();
if (Flags.reconnectHostEndpointsAfterHalRestart()) {
mClientManager.forEachClientOfHub(mContextHubId,
@@ -330,6 +334,7 @@
}
initDefaultClientMap();
+ initEndpointCallback();
initLocationSettingNotifications();
initWifiSettingNotifications();
@@ -508,6 +513,18 @@
mDefaultClientMap = Collections.unmodifiableMap(defaultClientMap);
}
+ private void initEndpointCallback() {
+ if (mHubInfoRegistry == null) {
+ return;
+ }
+ try {
+ mContextHubWrapper.registerEndpointCallback(
+ new ContextHubHalEndpointCallback(mHubInfoRegistry));
+ } catch (RemoteException e) {
+ Log.e(TAG, "RemoteException while registering IEndpointCallback", e);
+ }
+ }
+
/**
* Initializes existing callbacks with the mContextHubWrapper for every context hub
*/
@@ -739,6 +756,26 @@
return mHubInfoRegistry.getHubs();
}
+ @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @Override
+ public List<HubEndpointInfo> findEndpoints(long endpointId) {
+ super.findEndpoints_enforcePermission();
+ if (mHubInfoRegistry == null) {
+ return Collections.emptyList();
+ }
+ return mHubInfoRegistry.findEndpoints(endpointId);
+ }
+
+ @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_CONTEXT_HUB)
+ @Override
+ public IContextHubEndpoint registerEndpoint(
+ HubEndpointInfo pendingHubEndpointInfo, IContextHubEndpointCallback callback)
+ throws RemoteException {
+ super.registerEndpoint_enforcePermission();
+ // TODO(b/375487784): Implement this
+ return null;
+ }
+
/**
* Creates an internal load transaction callback to be used for old API clients
*
diff --git a/services/core/java/com/android/server/location/contexthub/HubInfoRegistry.java b/services/core/java/com/android/server/location/contexthub/HubInfoRegistry.java
index 68de9db..4d1000f 100644
--- a/services/core/java/com/android/server/location/contexthub/HubInfoRegistry.java
+++ b/services/core/java/com/android/server/location/contexthub/HubInfoRegistry.java
@@ -16,45 +16,144 @@
package com.android.server.location.contexthub;
+import android.hardware.contexthub.HubEndpointInfo;
import android.hardware.location.HubInfo;
import android.os.RemoteException;
+import android.util.ArrayMap;
import android.util.IndentingPrintWriter;
import android.util.Log;
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-class HubInfoRegistry {
+class HubInfoRegistry implements ContextHubHalEndpointCallback.IEndpointLifecycleCallback {
private static final String TAG = "HubInfoRegistry";
+ private final Object mLock = new Object();
private final IContextHubWrapper mContextHubWrapper;
- private final List<HubInfo> mHubsInfo;
+ @GuardedBy("mLock")
+ private List<HubInfo> mHubsInfo;
+
+ @GuardedBy("mLock")
+ private final ArrayMap<HubEndpointInfo.HubEndpointIdentifier, HubEndpointInfo>
+ mHubEndpointInfos = new ArrayMap<>();
HubInfoRegistry(IContextHubWrapper contextHubWrapper) {
- List<HubInfo> hubInfos;
mContextHubWrapper = contextHubWrapper;
+ refreshCachedHubs();
+ refreshCachedEndpoints();
+ }
+
+ /** Retrieve the list of hubs available. */
+ List<HubInfo> getHubs() {
+ synchronized (mLock) {
+ return mHubsInfo;
+ }
+ }
+
+ private void refreshCachedHubs() {
+ List<HubInfo> hubInfos;
try {
hubInfos = mContextHubWrapper.getHubs();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException while getting Hub info", e);
hubInfos = Collections.emptyList();
}
- mHubsInfo = hubInfos;
+
+ synchronized (mLock) {
+ mHubsInfo = hubInfos;
+ }
}
- /** Retrieve the list of hubs available. */
- List<HubInfo> getHubs() {
- return mHubsInfo;
+ private void refreshCachedEndpoints() {
+ List<HubEndpointInfo> endpointInfos;
+ try {
+ endpointInfos = mContextHubWrapper.getEndpoints();
+ } catch (RemoteException e) {
+ Log.e(TAG, "RemoteException while getting Hub info", e);
+ endpointInfos = Collections.emptyList();
+ }
+
+ synchronized (mLock) {
+ mHubEndpointInfos.clear();
+ for (HubEndpointInfo endpointInfo : endpointInfos) {
+ mHubEndpointInfos.put(endpointInfo.getIdentifier(), endpointInfo);
+ }
+ }
+ }
+
+ /** Invoked when HAL restarts */
+ public void onHalRestart() {
+ synchronized (mLock) {
+ refreshCachedHubs();
+ refreshCachedEndpoints();
+ }
+ }
+
+ @Override
+ public void onEndpointStarted(HubEndpointInfo[] endpointInfos) {
+ synchronized (mLock) {
+ for (HubEndpointInfo endpointInfo : endpointInfos) {
+ mHubEndpointInfos.remove(endpointInfo.getIdentifier());
+ mHubEndpointInfos.put(endpointInfo.getIdentifier(), endpointInfo);
+ }
+ }
+ }
+
+ @Override
+ public void onEndpointStopped(
+ HubEndpointInfo.HubEndpointIdentifier[] endpointIds, byte reason) {
+ synchronized (mLock) {
+ for (HubEndpointInfo.HubEndpointIdentifier endpointId : endpointIds) {
+ mHubEndpointInfos.remove(endpointId);
+ }
+ }
+ }
+
+ /** Return a list of {@link HubEndpointInfo} that represents endpoints with the matching id. */
+ public List<HubEndpointInfo> findEndpoints(long endpointIdQuery) {
+ List<HubEndpointInfo> searchResult = new ArrayList<>();
+ synchronized (mLock) {
+ for (HubEndpointInfo.HubEndpointIdentifier endpointId : mHubEndpointInfos.keySet()) {
+ if (endpointId.getEndpoint() == endpointIdQuery) {
+ searchResult.add(mHubEndpointInfos.get(endpointId));
+ }
+ }
+ }
+ return searchResult;
}
void dump(IndentingPrintWriter ipw) {
+ synchronized (mLock) {
+ dumpLocked(ipw);
+ }
+ }
+
+ @GuardedBy("mLock")
+ private void dumpLocked(IndentingPrintWriter ipw) {
ipw.println(TAG);
ipw.increaseIndent();
+ ipw.println("Hubs");
for (HubInfo hubInfo : mHubsInfo) {
ipw.println(hubInfo);
}
ipw.decreaseIndent();
+
+ ipw.println();
+
+ ipw.increaseIndent();
+ ipw.println("Endpoints");
+ for (HubEndpointInfo endpointInfo : mHubEndpointInfos.values()) {
+ ipw.println(endpointInfo);
+ }
+ ipw.decreaseIndent();
+
+ ipw.println();
}
+
}
diff --git a/services/core/java/com/android/server/location/contexthub/IContextHubWrapper.java b/services/core/java/com/android/server/location/contexthub/IContextHubWrapper.java
index 6656a6f..9b729eb 100644
--- a/services/core/java/com/android/server/location/contexthub/IContextHubWrapper.java
+++ b/services/core/java/com/android/server/location/contexthub/IContextHubWrapper.java
@@ -19,6 +19,7 @@
import android.annotation.Nullable;
import android.chre.flags.Flags;
import android.hardware.contexthub.HostEndpointInfo;
+import android.hardware.contexthub.HubEndpointInfo;
import android.hardware.contexthub.MessageDeliveryStatus;
import android.hardware.contexthub.NanSessionRequest;
import android.hardware.contexthub.V1_0.ContextHub;
@@ -229,6 +230,15 @@
return Collections.emptyList();
}
+ /** Calls the appropriate getEndpoints function depending on the HAL version. */
+ public List<HubEndpointInfo> getEndpoints() throws RemoteException {
+ return Collections.emptyList();
+ }
+
+ /** Calls the appropriate registerEndpointCallback function depending on the HAL version. */
+ public void registerEndpointCallback(android.hardware.contexthub.IEndpointCallback cb)
+ throws RemoteException {}
+
/**
* @return True if this version of the Contexthub HAL supports Location setting notifications.
*/
@@ -622,6 +632,45 @@
return retVal;
}
+ @Override
+ public List<HubEndpointInfo> getEndpoints() throws RemoteException {
+ android.hardware.contexthub.IContextHub hub = getHub();
+ if (hub == null) {
+ return Collections.emptyList();
+ }
+
+ List<HubEndpointInfo> retVal = new ArrayList<>();
+ final List<android.hardware.contexthub.EndpointInfo> halEndpointInfos =
+ hub.getEndpoints();
+ for (android.hardware.contexthub.EndpointInfo halEndpointInfo : halEndpointInfos) {
+ /* HAL -> API Type conversion */
+ final HubEndpointInfo endpointInfo = new HubEndpointInfo(halEndpointInfo);
+ if (DEBUG) {
+ Log.i(TAG, "getEndpoints: endpointInfo=" + endpointInfo);
+ }
+ retVal.add(endpointInfo);
+ }
+
+ if (DEBUG) {
+ Log.i(TAG, "getEndpoints: total count=" + retVal.size());
+ }
+ return retVal;
+ }
+
+ @Override
+ public void registerEndpointCallback(android.hardware.contexthub.IEndpointCallback cb)
+ throws RemoteException {
+ android.hardware.contexthub.IContextHub hub = getHub();
+ if (hub == null) {
+ return;
+ }
+
+ if (DEBUG) {
+ Log.i(TAG, "registerEndpointCallback: cb=" + cb);
+ }
+ hub.registerEndpointCallback(cb);
+ }
+
public boolean supportsLocationSettingNotifications() {
return true;
}
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index 436acba..c460465 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -17,7 +17,6 @@
package com.android.server.media.projection;
import static android.Manifest.permission.MANAGE_MEDIA_PROJECTION;
-import static android.Manifest.permission.RECORD_SENSITIVE_CONTENT;
import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_CREATED;
import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED;
import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
@@ -28,7 +27,6 @@
import static android.media.projection.ReviewGrantedConsentResult.RECORD_CONTENT_DISPLAY;
import static android.media.projection.ReviewGrantedConsentResult.RECORD_CONTENT_TASK;
import static android.media.projection.ReviewGrantedConsentResult.UNKNOWN;
-import static android.provider.Settings.Global.DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.Display.INVALID_DISPLAY;
@@ -41,10 +39,7 @@
import android.app.ActivityOptions.LaunchCookie;
import android.app.AppOpsManager;
import android.app.IProcessObserver;
-import android.app.KeyguardManager;
import android.app.compat.CompatChanges;
-import android.app.role.RoleManager;
-import android.companion.AssociationRequest;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
import android.content.ComponentName;
@@ -74,7 +69,6 @@
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
-import android.provider.Settings;
import android.util.ArrayMap;
import android.util.Slog;
import android.view.ContentRecordingSession;
@@ -85,7 +79,6 @@
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.DumpUtils;
import com.android.server.LocalServices;
-import com.android.server.SystemConfig;
import com.android.server.SystemService;
import com.android.server.Watchdog;
import com.android.server.wm.WindowManagerInternal;
@@ -140,12 +133,12 @@
private final ActivityManagerInternal mActivityManagerInternal;
private final PackageManager mPackageManager;
private final WindowManagerInternal mWmInternal;
- private final KeyguardManager mKeyguardManager;
- private final RoleManager mRoleManager;
+
private final MediaRouter mMediaRouter;
private final MediaRouterCallback mMediaRouterCallback;
private final MediaProjectionMetricsLogger mMediaProjectionMetricsLogger;
+ private final MediaProjectionStopController mMediaProjectionStopController;
private MediaRouter.RouteInfo mMediaRouteInfo;
@GuardedBy("mLock")
@@ -175,72 +168,16 @@
mMediaRouter = (MediaRouter) mContext.getSystemService(Context.MEDIA_ROUTER_SERVICE);
mMediaRouterCallback = new MediaRouterCallback();
mMediaProjectionMetricsLogger = injector.mediaProjectionMetricsLogger(context);
- mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
- mKeyguardManager.addKeyguardLockedStateListener(
- mContext.getMainExecutor(), this::onKeyguardLockedStateChanged);
- mRoleManager = mContext.getSystemService(RoleManager.class);
+ mMediaProjectionStopController = new MediaProjectionStopController(context,
+ this::maybeStopMediaProjection);
Watchdog.getInstance().addMonitor(this);
}
- /**
- * In order to record the keyguard, the MediaProjection package must be either:
- * - a holder of RECORD_SENSITIVE_CONTENT permission, or
- * - be one of the bugreport allowlisted packages, or
- * - hold the OP_PROJECT_MEDIA AppOp.
- */
- @SuppressWarnings("BooleanMethodIsAlwaysInverted")
- private boolean canCaptureKeyguard() {
- if (!android.companion.virtualdevice.flags.Flags.mediaProjectionKeyguardRestrictions()) {
- return true;
- }
+ private void maybeStopMediaProjection(int reason) {
synchronized (mLock) {
- if (mProjectionGrant == null || mProjectionGrant.packageName == null) {
- return false;
- }
- boolean disableScreenShareProtections = Settings.Global.getInt(
- getContext().getContentResolver(),
- DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, 0) != 0;
- if (disableScreenShareProtections) {
- Slog.v(TAG,
- "Allowing keyguard capture as screenshare protections are disabled.");
- return true;
- }
-
- if (mPackageManager.checkPermission(RECORD_SENSITIVE_CONTENT,
- mProjectionGrant.packageName)
- == PackageManager.PERMISSION_GRANTED) {
- Slog.v(TAG,
- "Allowing keyguard capture for package with RECORD_SENSITIVE_CONTENT "
- + "permission");
- return true;
- }
- if (AppOpsManager.MODE_ALLOWED == mAppOps.noteOpNoThrow(AppOpsManager.OP_PROJECT_MEDIA,
- mProjectionGrant.uid, mProjectionGrant.packageName, /* attributionTag= */ null,
- "recording lockscreen")) {
- // Some tools use media projection by granting the OP_PROJECT_MEDIA app
- // op via a shell command. Those tools can be granted keyguard capture
- Slog.v(TAG,
- "Allowing keyguard capture for package with OP_PROJECT_MEDIA AppOp ");
- return true;
- }
- if (isProjectionAppHoldingAppStreamingRoleLocked()) {
- Slog.v(TAG,
- "Allowing keyguard capture for package holding app streaming role.");
- return true;
- }
- return SystemConfig.getInstance().getBugreportWhitelistedPackages()
- .contains(mProjectionGrant.packageName);
- }
- }
-
- @VisibleForTesting
- void onKeyguardLockedStateChanged(boolean isKeyguardLocked) {
- if (!isKeyguardLocked) return;
- synchronized (mLock) {
- if (mProjectionGrant != null && !canCaptureKeyguard()
- && mProjectionGrant.mVirtualDisplayId != INVALID_DISPLAY) {
- Slog.d(TAG, "Content Recording: Stopped MediaProjection"
- + " due to keyguard lock");
+ if (!mMediaProjectionStopController.isExemptFromStopping(mProjectionGrant)) {
+ Slog.d(TAG, "Content Recording: Stopping MediaProjection due to "
+ + MediaProjectionStopController.stopReasonToString(reason));
mProjectionGrant.stop();
}
}
@@ -310,6 +247,8 @@
}
});
}
+
+ mMediaProjectionStopController.startTrackingStopReasons(mContext);
}
@Override
@@ -736,20 +675,6 @@
}
}
- /**
- * Application holding the app streaming role
- * ({@value AssociationRequest#DEVICE_PROFILE_APP_STREAMING}) are allowed to record the
- * lockscreen.
- *
- * @return true if the is held by the recording application.
- */
- @GuardedBy("mLock")
- private boolean isProjectionAppHoldingAppStreamingRoleLocked() {
- return mRoleManager.getRoleHoldersAsUser(AssociationRequest.DEVICE_PROFILE_APP_STREAMING,
- mContext.getUser())
- .contains(mProjectionGrant.packageName);
- }
-
private void dump(final PrintWriter pw) {
pw.println("MEDIA PROJECTION MANAGER (dumpsys media_projection)");
synchronized (mLock) {
@@ -957,18 +882,19 @@
public void requestConsentForInvalidProjection(@NonNull IMediaProjection projection) {
requestConsentForInvalidProjection_enforcePermission();
- if (android.companion.virtualdevice.flags.Flags.mediaProjectionKeyguardRestrictions()
- && mKeyguardManager.isKeyguardLocked()) {
- Slog.v(TAG, "Reusing token: Won't request consent while the keyguard is locked");
- return;
- }
-
synchronized (mLock) {
if (!isCurrentProjection(projection)) {
Slog.v(TAG, "Reusing token: Won't request consent again for a token that "
+ "isn't current");
return;
}
+
+ if (mMediaProjectionStopController.isStartForbidden(mProjectionGrant)) {
+ Slog.v(TAG,
+ "Reusing token: Won't request consent while MediaProjection is "
+ + "restricted");
+ return;
+ }
}
// Remove calling app identity before performing any privileged operations.
@@ -1076,7 +1002,6 @@
}
}
- @VisibleForTesting
final class MediaProjection extends IMediaProjection.Stub {
// Host app has 5 minutes to begin using the token before it is invalid.
// Some apps show a dialog for the user to interact with (selecting recording resolution)
@@ -1381,12 +1306,15 @@
@Override
public void notifyVirtualDisplayCreated(int displayId) {
notifyVirtualDisplayCreated_enforcePermission();
- if (mKeyguardManager.isKeyguardLocked() && !canCaptureKeyguard()) {
- Slog.w(TAG, "Content Recording: Keyguard locked, aborting MediaProjection");
- stop();
- return;
- }
synchronized (mLock) {
+ if (mMediaProjectionStopController.isStartForbidden(mProjectionGrant)) {
+ Slog.w(TAG,
+ "Content Recording: MediaProjection start disallowed, aborting "
+ + "MediaProjection");
+ stop();
+ return;
+ }
+
mVirtualDisplayId = displayId;
// If prior session was does not have a valid display id, then update the display
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionStopController.java b/services/core/java/com/android/server/media/projection/MediaProjectionStopController.java
new file mode 100644
index 0000000..f5b26c4
--- /dev/null
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionStopController.java
@@ -0,0 +1,222 @@
+/*
+ * Copyright (C) 2024 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.media.projection;
+
+import static android.Manifest.permission.RECORD_SENSITIVE_CONTENT;
+import static android.provider.Settings.Global.DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS;
+
+import android.app.AppOpsManager;
+import android.app.KeyguardManager;
+import android.app.role.RoleManager;
+import android.companion.AssociationRequest;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Binder;
+import android.provider.Settings;
+import android.telecom.TelecomManager;
+import android.telephony.TelephonyCallback;
+import android.telephony.TelephonyManager;
+import android.util.Slog;
+import android.view.Display;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.SystemConfig;
+
+import java.util.function.Consumer;
+
+/**
+ * Tracks events that should cause MediaProjection to stop
+ */
+public class MediaProjectionStopController {
+
+ private static final String TAG = "MediaProjectionStopController";
+ @VisibleForTesting
+ static final int STOP_REASON_KEYGUARD = 1;
+ @VisibleForTesting
+ static final int STOP_REASON_CALL_END = 2;
+
+ private final TelephonyCallback mTelephonyCallback = new ProjectionTelephonyCallback();
+ private final Consumer<Integer> mStopReasonConsumer;
+ private final KeyguardManager mKeyguardManager;
+ private final TelecomManager mTelecomManager;
+ private final TelephonyManager mTelephonyManager;
+ private final AppOpsManager mAppOpsManager;
+ private final PackageManager mPackageManager;
+ private final RoleManager mRoleManager;
+ private final ContentResolver mContentResolver;
+
+ private boolean mIsInCall;
+
+ public MediaProjectionStopController(Context context, Consumer<Integer> stopReasonConsumer) {
+ mStopReasonConsumer = stopReasonConsumer;
+ mKeyguardManager = context.getSystemService(KeyguardManager.class);
+ mTelecomManager = context.getSystemService(TelecomManager.class);
+ mTelephonyManager = context.getSystemService(TelephonyManager.class);
+ mAppOpsManager = context.getSystemService(AppOpsManager.class);
+ mPackageManager = context.getPackageManager();
+ mRoleManager = context.getSystemService(RoleManager.class);
+ mContentResolver = context.getContentResolver();
+ }
+
+ /**
+ * Start tracking stop reasons that may interrupt a MediaProjection session.
+ */
+ public void startTrackingStopReasons(Context context) {
+ final long token = Binder.clearCallingIdentity();
+ try {
+ mKeyguardManager.addKeyguardLockedStateListener(context.getMainExecutor(),
+ this::onKeyguardLockedStateChanged);
+ if (com.android.media.projection.flags.Flags.stopMediaProjectionOnCallEnd()) {
+ callStateChanged();
+ mTelephonyManager.registerTelephonyCallback(context.getMainExecutor(),
+ mTelephonyCallback);
+ }
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ /**
+ * Checks whether the given projection grant is exempt from stopping restrictions.
+ */
+ public boolean isExemptFromStopping(
+ MediaProjectionManagerService.MediaProjection projectionGrant) {
+ return isExempt(projectionGrant, false);
+ }
+
+ /**
+ * Apps may disregard recording restrictions via MediaProjection for any stop reason if:
+ * - the "Disable Screenshare protections" developer option is enabled
+ * - the app is a holder of RECORD_SENSITIVE_CONTENT permission
+ * - the app holds the OP_PROJECT_MEDIA AppOp
+ * - the app holds the COMPANION_DEVICE_APP_STREAMING role
+ * - the app is one of the bugreport allowlisted packages
+ * - the current projection does not have an active VirtualDisplay associated with the
+ * MediaProjection session
+ */
+ private boolean isExempt(
+ MediaProjectionManagerService.MediaProjection projectionGrant, boolean forStart) {
+ if (projectionGrant == null || projectionGrant.packageName == null) {
+ return true;
+ }
+ boolean disableScreenShareProtections = Settings.Global.getInt(mContentResolver,
+ DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, 0) != 0;
+ if (disableScreenShareProtections) {
+ Slog.v(TAG, "Continuing MediaProjection as screenshare protections are disabled.");
+ return true;
+ }
+
+ if (mPackageManager.checkPermission(RECORD_SENSITIVE_CONTENT, projectionGrant.packageName)
+ == PackageManager.PERMISSION_GRANTED) {
+ Slog.v(TAG,
+ "Continuing MediaProjection for package with RECORD_SENSITIVE_CONTENT "
+ + "permission");
+ return true;
+ }
+ if (AppOpsManager.MODE_ALLOWED == mAppOpsManager.noteOpNoThrow(
+ AppOpsManager.OP_PROJECT_MEDIA, projectionGrant.uid,
+ projectionGrant.packageName, /* attributionTag= */ null, "recording lockscreen")) {
+ // Some tools use media projection by granting the OP_PROJECT_MEDIA app
+ // op via a shell command.
+ Slog.v(TAG, "Continuing MediaProjection for package with OP_PROJECT_MEDIA AppOp ");
+ return true;
+ }
+ if (mRoleManager.getRoleHoldersAsUser(AssociationRequest.DEVICE_PROFILE_APP_STREAMING,
+ projectionGrant.userHandle).contains(projectionGrant.packageName)) {
+ Slog.v(TAG, "Continuing MediaProjection for package holding app streaming role.");
+ return true;
+ }
+ if (SystemConfig.getInstance().getBugreportWhitelistedPackages().contains(
+ projectionGrant.packageName)) {
+ Slog.v(TAG, "Continuing MediaProjection for package allowlisted for bugreporting.");
+ return true;
+ }
+ if (!forStart && projectionGrant.getVirtualDisplayId() == Display.INVALID_DISPLAY) {
+ Slog.v(TAG, "Continuing MediaProjection as current projection has no VirtualDisplay.");
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @return {@code true} if a MediaProjection session is currently in a restricted state.
+ */
+ public boolean isStartForbidden(
+ MediaProjectionManagerService.MediaProjection projectionGrant) {
+ if (!android.companion.virtualdevice.flags.Flags.mediaProjectionKeyguardRestrictions()) {
+ return false;
+ }
+
+ if (!mKeyguardManager.isKeyguardLocked()) {
+ return false;
+ }
+
+ if (isExempt(projectionGrant, true)) {
+ return false;
+ }
+ return true;
+ }
+
+ @VisibleForTesting
+ void onKeyguardLockedStateChanged(boolean isKeyguardLocked) {
+ if (!isKeyguardLocked) return;
+ if (!android.companion.virtualdevice.flags.Flags.mediaProjectionKeyguardRestrictions()) {
+ return;
+ }
+ mStopReasonConsumer.accept(STOP_REASON_KEYGUARD);
+ }
+
+ @VisibleForTesting
+ void callStateChanged() {
+ if (!com.android.media.projection.flags.Flags.stopMediaProjectionOnCallEnd()) {
+ return;
+ }
+ boolean isInCall = mTelecomManager.isInCall();
+ if (isInCall == mIsInCall) {
+ return;
+ }
+ if (mIsInCall && !isInCall) {
+ mStopReasonConsumer.accept(STOP_REASON_CALL_END);
+ }
+ mIsInCall = isInCall;
+ }
+
+ /**
+ * @return a String representation of the stop reason interrupting MediaProjection.
+ */
+ public static String stopReasonToString(int stopReason) {
+ switch (stopReason) {
+ case STOP_REASON_KEYGUARD -> {
+ return "STOP_REASON_KEYGUARD";
+ }
+ case STOP_REASON_CALL_END -> {
+ return "STOP_REASON_CALL_END";
+ }
+ }
+ return "";
+ }
+
+ private final class ProjectionTelephonyCallback extends TelephonyCallback implements
+ TelephonyCallback.CallStateListener {
+ @Override
+ public void onCallStateChanged(int state) {
+ callStateChanged();
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index 7ef3582..961b4b3c 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -3606,6 +3606,13 @@
case "--force-verification":
sessionParams.setForceVerification();
break;
+ case "--disable-auto-install-dependencies":
+ if (Flags.sdkDependencyInstaller()) {
+ sessionParams.setEnableAutoInstallDependencies(false);
+ } else {
+ throw new IllegalArgumentException("Unknown option " + opt);
+ }
+ break;
default:
throw new IllegalArgumentException("Unknown option " + opt);
}
@@ -4894,6 +4901,10 @@
+ "#compiler_filters");
pw.println(" or 'skip'");
pw.println(" --force-verification: if set, enable the verification for this install");
+ if (Flags.sdkDependencyInstaller()) {
+ pw.println(" --disable-auto-install-dependencies: if set, any missing shared");
+ pw.println(" library dependencies will not be auto-installed");
+ }
pw.println("");
pw.println(" install-existing [--user USER_ID|all|current]");
pw.println(" [--instant] [--full] [--wait] [--restrict-permissions] PACKAGE");
diff --git a/services/core/java/com/android/server/policy/ModifierShortcutManager.java b/services/core/java/com/android/server/policy/ModifierShortcutManager.java
index 4f67318..c9f66eb 100644
--- a/services/core/java/com/android/server/policy/ModifierShortcutManager.java
+++ b/services/core/java/com/android/server/policy/ModifierShortcutManager.java
@@ -29,6 +29,7 @@
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
+import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Icon;
import android.hardware.input.AppLaunchData;
@@ -65,6 +66,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -84,6 +86,7 @@
private static final String ATTRIBUTE_PACKAGE = "package";
private static final String ATTRIBUTE_CLASS = "class";
private static final String ATTRIBUTE_SHORTCUT = "shortcut";
+ private static final String ATTRIBUTE_KEYCODE = "keycode";
private static final String ATTRIBUTE_CATEGORY = "category";
private static final String ATTRIBUTE_SHIFT = "shift";
private static final String ATTRIBUTE_ROLE = "role";
@@ -167,6 +170,9 @@
}, UserHandle.ALL);
mCurrentUser = currentUser;
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
+ }
+
+ void onSystemReady() {
loadShortcuts();
}
@@ -335,6 +341,7 @@
try {
XmlResourceParser parser = mContext.getResources().getXml(R.xml.bookmarks);
XmlUtils.beginDocument(parser, TAG_BOOKMARKS);
+ KeyCharacterMap virtualKcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
while (true) {
XmlUtils.nextElement(parser);
@@ -353,15 +360,36 @@
String categoryName = parser.getAttributeValue(null, ATTRIBUTE_CATEGORY);
String shiftName = parser.getAttributeValue(null, ATTRIBUTE_SHIFT);
String roleName = parser.getAttributeValue(null, ATTRIBUTE_ROLE);
+ final int keycode;
+ final int modifierState;
+ TypedArray a = mContext.getResources().obtainAttributes(parser,
+ R.styleable.Bookmark);
+ try {
+ keycode = a.getInt(R.styleable.Bookmark_keycode, KeyEvent.KEYCODE_UNKNOWN);
+ modifierState = a.getInt(R.styleable.Bookmark_modifierState, 0);
+ } finally {
+ a.recycle();
+ }
+ if (TextUtils.isEmpty(shortcutName) && keycode != KeyEvent.KEYCODE_UNKNOWN) {
+ // Try to find shortcutChar using keycode
+ shortcutName = String.valueOf(virtualKcm.getDisplayLabel(keycode)).toLowerCase(
+ Locale.ROOT);
+ }
if (TextUtils.isEmpty(shortcutName)) {
Log.w(TAG, "Shortcut required for bookmark with category=" + categoryName
+ " packageName=" + packageName + " className=" + className
- + " role=" + roleName + "shiftName=" + shiftName);
+ + " role=" + roleName + " shiftName=" + shiftName + " keycode= "
+ + keycode + " modifierState= " + modifierState);
continue;
}
- final boolean isShiftShortcut = (shiftName != null && shiftName.equals("true"));
+ final boolean isShiftShortcut;
+ if (!TextUtils.isEmpty(shiftName)) {
+ isShiftShortcut = shiftName.equals("true");
+ } else {
+ isShiftShortcut = (modifierState & KeyEvent.META_SHIFT_ON) != 0;
+ }
if (modifierShortcutManagerRefactor()) {
final char shortcutChar = shortcutName.charAt(0);
@@ -376,7 +404,7 @@
bookmark = new RoleBookmark(shortcutChar, isShiftShortcut, roleName);
}
if (bookmark != null) {
- Log.d(TAG, "adding shortcut " + bookmark + "shift="
+ Log.d(TAG, "adding shortcut " + bookmark + " shift="
+ isShiftShortcut + " char=" + shortcutChar);
mBookmarks.put(new Pair<>(shortcutChar, isShiftShortcut), bookmark);
}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index dda5bcf..85e7cfe 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -6610,6 +6610,7 @@
// In normal flow, systemReady is called before other system services are ready.
// So it is better not to bind keyguard here.
mKeyguardDelegate.onSystemReady();
+ mModifierShortcutManager.onSystemReady();
mVrManagerInternal = LocalServices.getService(VrManagerInternal.class);
if (mVrManagerInternal != null) {
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index 0acfe92..37883f5 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -2332,6 +2332,8 @@
Trace.traceBegin(Trace.TRACE_TAG_POWER, traceMethodName);
try {
// Phase 2: Handle wakefulness change and bookkeeping.
+ // Under lock, invalidate before set ensures caches won't return stale values.
+ mInjector.invalidateIsInteractiveCaches();
mWakefulnessRaw = newWakefulness;
mWakefulnessChanging = true;
mDirty |= DIRTY_WAKEFULNESS;
@@ -2429,7 +2431,6 @@
void onPowerGroupEventLocked(int event, PowerGroup powerGroup) {
mWakefulnessChanging = true;
mDirty |= DIRTY_WAKEFULNESS;
- mInjector.invalidateIsInteractiveCaches();
final int groupId = powerGroup.getGroupId();
if (event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_REMOVED) {
mPowerGroups.delete(groupId);
diff --git a/services/core/java/com/android/server/security/forensic/BackupTransportConnection.java b/services/core/java/com/android/server/security/forensic/ForensicEventTransportConnection.java
similarity index 69%
rename from services/core/java/com/android/server/security/forensic/BackupTransportConnection.java
rename to services/core/java/com/android/server/security/forensic/ForensicEventTransportConnection.java
index caca011..b85199e 100644
--- a/services/core/java/com/android/server/security/forensic/BackupTransportConnection.java
+++ b/services/core/java/com/android/server/security/forensic/ForensicEventTransportConnection.java
@@ -16,15 +16,19 @@
package com.android.server.security.forensic;
+import static android.Manifest.permission.BIND_FORENSIC_EVENT_TRANSPORT_SERVICE;
+
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
+import android.content.pm.PackageManager;
+import android.content.pm.ServiceInfo;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
import android.security.forensic.ForensicEvent;
-import android.security.forensic.IBackupTransport;
+import android.security.forensic.IForensicEventTransport;
import android.text.TextUtils;
import android.util.Slog;
@@ -36,20 +40,20 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-public class BackupTransportConnection implements ServiceConnection {
- private static final String TAG = "BackupTransportConnection";
+public class ForensicEventTransportConnection implements ServiceConnection {
+ private static final String TAG = "ForensicEventTransportConnection";
private static final long FUTURE_TIMEOUT_MILLIS = 60 * 1000; // 1 mins
private final Context mContext;
- private String mForensicBackupTransportConfig;
- volatile IBackupTransport mService;
+ private String mForensicEventTransportConfig;
+ volatile IForensicEventTransport mService;
- public BackupTransportConnection(Context context) {
+ public ForensicEventTransportConnection(Context context) {
mContext = context;
mService = null;
}
/**
- * Initialize the BackupTransport binder service.
+ * Initialize the ForensicEventTransport binder service.
* @return Whether the initialization succeed.
*/
public boolean initialize() {
@@ -74,7 +78,7 @@
}
/**
- * Add data to the BackupTransport binder service.
+ * Add data to the ForensicEventTransport binder service.
* @param data List of ForensicEvent.
* @return Whether the data is added to the binder service.
*/
@@ -109,21 +113,37 @@
return future.get(FUTURE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException
| CancellationException e) {
- Slog.w(TAG, "Failed to get result from transport:", e);
+ Slog.e(TAG, "Failed to get result from transport:", e);
return null;
}
}
private boolean bindService() {
- mForensicBackupTransportConfig = mContext.getString(
- com.android.internal.R.string.config_forensicBackupTransport);
- if (TextUtils.isEmpty(mForensicBackupTransportConfig)) {
+ mForensicEventTransportConfig = mContext.getString(
+ com.android.internal.R.string.config_forensicEventTransport);
+ if (TextUtils.isEmpty(mForensicEventTransportConfig)) {
+ Slog.e(TAG, "config_forensicEventTransport is empty");
return false;
}
ComponentName serviceComponent =
- ComponentName.unflattenFromString(mForensicBackupTransportConfig);
+ ComponentName.unflattenFromString(mForensicEventTransportConfig);
if (serviceComponent == null) {
+ Slog.e(TAG, "Can't get serviceComponent name");
+ return false;
+ }
+
+ try {
+ ServiceInfo serviceInfo = mContext.getPackageManager().getServiceInfo(serviceComponent,
+ 0 /* flags */);
+ if (!BIND_FORENSIC_EVENT_TRANSPORT_SERVICE.equals(serviceInfo.permission)) {
+ Slog.e(TAG, serviceComponent.flattenToShortString()
+ + " is not declared with the permission "
+ + "\"" + BIND_FORENSIC_EVENT_TRANSPORT_SERVICE + "\"");
+ return false;
+ }
+ } catch (PackageManager.NameNotFoundException e) {
+ Slog.e(TAG, "Unable to find serviceComponent");
return false;
}
@@ -143,7 +163,7 @@
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
- mService = IBackupTransport.Stub.asInterface(service);
+ mService = IForensicEventTransport.Stub.asInterface(service);
}
@Override
diff --git a/services/core/java/com/android/server/security/forensic/ForensicService.java b/services/core/java/com/android/server/security/forensic/ForensicService.java
index 01f630b..2be068f 100644
--- a/services/core/java/com/android/server/security/forensic/ForensicService.java
+++ b/services/core/java/com/android/server/security/forensic/ForensicService.java
@@ -16,11 +16,16 @@
package com.android.server.security.forensic;
+import static android.Manifest.permission.MANAGE_FORENSIC_STATE;
+import static android.Manifest.permission.READ_FORENSIC_STATE;
+
+import android.annotation.EnforcePermission;
import android.annotation.NonNull;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
+import android.os.PermissionEnforcer;
import android.os.RemoteException;
import android.security.forensic.ForensicEvent;
import android.security.forensic.IForensicService;
@@ -41,16 +46,15 @@
public class ForensicService extends SystemService {
private static final String TAG = "ForensicService";
- private static final int MSG_MONITOR_STATE = 0;
- private static final int MSG_MAKE_VISIBLE = 1;
- private static final int MSG_MAKE_INVISIBLE = 2;
- private static final int MSG_ENABLE = 3;
- private static final int MSG_DISABLE = 4;
- private static final int MSG_BACKUP = 5;
+ private static final int MAX_STATE_CALLBACK_NUM = 16;
+ private static final int MSG_ADD_STATE_CALLBACK = 0;
+ private static final int MSG_REMOVE_STATE_CALLBACK = 1;
+ private static final int MSG_ENABLE = 2;
+ private static final int MSG_DISABLE = 3;
+ private static final int MSG_TRANSPORT = 4;
private static final int STATE_UNKNOWN = IForensicServiceStateCallback.State.UNKNOWN;
- private static final int STATE_INVISIBLE = IForensicServiceStateCallback.State.INVISIBLE;
- private static final int STATE_VISIBLE = IForensicServiceStateCallback.State.VISIBLE;
+ private static final int STATE_DISABLED = IForensicServiceStateCallback.State.DISABLED;
private static final int STATE_ENABLED = IForensicServiceStateCallback.State.ENABLED;
private static final int ERROR_UNKNOWN = IForensicServiceCommandCallback.ErrorCode.UNKNOWN;
@@ -58,19 +62,19 @@
IForensicServiceCommandCallback.ErrorCode.PERMISSION_DENIED;
private static final int ERROR_INVALID_STATE_TRANSITION =
IForensicServiceCommandCallback.ErrorCode.INVALID_STATE_TRANSITION;
- private static final int ERROR_BACKUP_TRANSPORT_UNAVAILABLE =
- IForensicServiceCommandCallback.ErrorCode.BACKUP_TRANSPORT_UNAVAILABLE;
+ private static final int ERROR_TRANSPORT_UNAVAILABLE =
+ IForensicServiceCommandCallback.ErrorCode.TRANSPORT_UNAVAILABLE;
private static final int ERROR_DATA_SOURCE_UNAVAILABLE =
IForensicServiceCommandCallback.ErrorCode.DATA_SOURCE_UNAVAILABLE;
private final Context mContext;
private final Handler mHandler;
- private final BackupTransportConnection mBackupTransportConnection;
+ private final ForensicEventTransportConnection mForensicEventTransportConnection;
private final DataAggregator mDataAggregator;
private final BinderService mBinderService;
- private final ArrayList<IForensicServiceStateCallback> mStateMonitors = new ArrayList<>();
- private volatile int mState = STATE_INVISIBLE;
+ private final ArrayList<IForensicServiceStateCallback> mStateCallbacks = new ArrayList<>();
+ private volatile int mState = STATE_DISABLED;
public ForensicService(@NonNull Context context) {
this(new InjectorImpl(context));
@@ -81,9 +85,9 @@
super(injector.getContext());
mContext = injector.getContext();
mHandler = new EventHandler(injector.getLooper(), this);
- mBackupTransportConnection = injector.getBackupTransportConnection();
+ mForensicEventTransportConnection = injector.getForensicEventransportConnection();
mDataAggregator = injector.getDataAggregator(this);
- mBinderService = new BinderService(this);
+ mBinderService = new BinderService(this, injector.getPermissionEnforcer());
}
@VisibleForTesting
@@ -94,32 +98,36 @@
private static final class BinderService extends IForensicService.Stub {
final ForensicService mService;
- BinderService(ForensicService service) {
+ BinderService(ForensicService service, @NonNull PermissionEnforcer permissionEnforcer) {
+ super(permissionEnforcer);
mService = service;
}
@Override
- public void monitorState(IForensicServiceStateCallback callback) {
- mService.mHandler.obtainMessage(MSG_MONITOR_STATE, callback).sendToTarget();
+ @EnforcePermission(READ_FORENSIC_STATE)
+ public void addStateCallback(IForensicServiceStateCallback callback) {
+ addStateCallback_enforcePermission();
+ mService.mHandler.obtainMessage(MSG_ADD_STATE_CALLBACK, callback).sendToTarget();
}
@Override
- public void makeVisible(IForensicServiceCommandCallback callback) {
- mService.mHandler.obtainMessage(MSG_MAKE_VISIBLE, callback).sendToTarget();
+ @EnforcePermission(READ_FORENSIC_STATE)
+ public void removeStateCallback(IForensicServiceStateCallback callback) {
+ removeStateCallback_enforcePermission();
+ mService.mHandler.obtainMessage(MSG_REMOVE_STATE_CALLBACK, callback).sendToTarget();
}
@Override
- public void makeInvisible(IForensicServiceCommandCallback callback) {
- mService.mHandler.obtainMessage(MSG_MAKE_INVISIBLE, callback).sendToTarget();
- }
-
- @Override
+ @EnforcePermission(MANAGE_FORENSIC_STATE)
public void enable(IForensicServiceCommandCallback callback) {
+ enable_enforcePermission();
mService.mHandler.obtainMessage(MSG_ENABLE, callback).sendToTarget();
}
@Override
+ @EnforcePermission(MANAGE_FORENSIC_STATE)
public void disable(IForensicServiceCommandCallback callback) {
+ disable_enforcePermission();
mService.mHandler.obtainMessage(MSG_DISABLE, callback).sendToTarget();
}
}
@@ -135,24 +143,18 @@
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
- case MSG_MONITOR_STATE:
+ case MSG_ADD_STATE_CALLBACK:
try {
- mService.monitorState(
+ mService.addStateCallback(
(IForensicServiceStateCallback) msg.obj);
} catch (RemoteException e) {
Slog.e(TAG, "RemoteException", e);
}
break;
- case MSG_MAKE_VISIBLE:
+ case MSG_REMOVE_STATE_CALLBACK:
try {
- mService.makeVisible((IForensicServiceCommandCallback) msg.obj);
- } catch (RemoteException e) {
- Slog.e(TAG, "RemoteException", e);
- }
- break;
- case MSG_MAKE_INVISIBLE:
- try {
- mService.makeInvisible((IForensicServiceCommandCallback) msg.obj);
+ mService.removeStateCallback(
+ (IForensicServiceStateCallback) msg.obj);
} catch (RemoteException e) {
Slog.e(TAG, "RemoteException", e);
}
@@ -171,8 +173,8 @@
Slog.e(TAG, "RemoteException", e);
}
break;
- case MSG_BACKUP:
- mService.backup((List<ForensicEvent>) msg.obj);
+ case MSG_TRANSPORT:
+ mService.transport((List<ForensicEvent>) msg.obj);
break;
default:
Slog.w(TAG, "Unknown message: " + msg.what);
@@ -180,103 +182,83 @@
}
}
- private void monitorState(IForensicServiceStateCallback callback) throws RemoteException {
- for (int i = 0; i < mStateMonitors.size(); i++) {
- if (mStateMonitors.get(i).asBinder() == callback.asBinder()) {
+ private void addStateCallback(IForensicServiceStateCallback callback) throws RemoteException {
+ for (int i = 0; i < mStateCallbacks.size(); i++) {
+ if (mStateCallbacks.get(i).asBinder() == callback.asBinder()) {
return;
}
}
- mStateMonitors.add(callback);
+ mStateCallbacks.add(callback);
callback.onStateChange(mState);
}
- private void notifyStateMonitors() throws RemoteException {
- for (int i = 0; i < mStateMonitors.size(); i++) {
- mStateMonitors.get(i).onStateChange(mState);
+ private void removeStateCallback(IForensicServiceStateCallback callback)
+ throws RemoteException {
+ for (int i = 0; i < mStateCallbacks.size(); i++) {
+ if (mStateCallbacks.get(i).asBinder() == callback.asBinder()) {
+ mStateCallbacks.remove(i);
+ return;
+ }
}
}
- private void makeVisible(IForensicServiceCommandCallback callback) throws RemoteException {
- switch (mState) {
- case STATE_INVISIBLE:
- if (!mDataAggregator.initialize()) {
- callback.onFailure(ERROR_DATA_SOURCE_UNAVAILABLE);
- break;
- }
- mState = STATE_VISIBLE;
- notifyStateMonitors();
- callback.onSuccess();
- break;
- case STATE_VISIBLE:
- callback.onSuccess();
- break;
- default:
- callback.onFailure(ERROR_INVALID_STATE_TRANSITION);
+ private void notifyStateMonitors() {
+ if (mStateCallbacks.size() >= MAX_STATE_CALLBACK_NUM) {
+ mStateCallbacks.removeFirst();
}
- }
- private void makeInvisible(IForensicServiceCommandCallback callback) throws RemoteException {
- switch (mState) {
- case STATE_VISIBLE:
- case STATE_ENABLED:
- mState = STATE_INVISIBLE;
- notifyStateMonitors();
- callback.onSuccess();
- break;
- case STATE_INVISIBLE:
- callback.onSuccess();
- break;
- default:
- callback.onFailure(ERROR_INVALID_STATE_TRANSITION);
+ for (int i = 0; i < mStateCallbacks.size(); i++) {
+ try {
+ mStateCallbacks.get(i).onStateChange(mState);
+ } catch (RemoteException e) {
+ mStateCallbacks.remove(i);
+ }
}
}
private void enable(IForensicServiceCommandCallback callback) throws RemoteException {
- switch (mState) {
- case STATE_VISIBLE:
- if (!mBackupTransportConnection.initialize()) {
- callback.onFailure(ERROR_BACKUP_TRANSPORT_UNAVAILABLE);
- break;
- }
- mDataAggregator.enable();
- mState = STATE_ENABLED;
- notifyStateMonitors();
- callback.onSuccess();
- break;
- case STATE_ENABLED:
- callback.onSuccess();
- break;
- default:
- callback.onFailure(ERROR_INVALID_STATE_TRANSITION);
+ if (mState == STATE_ENABLED) {
+ callback.onSuccess();
+ return;
}
+
+ // TODO: temporarily disable the following for the CTS ForensicManagerTest.
+ // Enable it when the transport component is ready.
+ // if (!mForensicEventTransportConnection.initialize()) {
+ // callback.onFailure(ERROR_TRANSPORT_UNAVAILABLE);
+ // return;
+ // }
+
+ mDataAggregator.enable();
+ mState = STATE_ENABLED;
+ notifyStateMonitors();
+ callback.onSuccess();
}
private void disable(IForensicServiceCommandCallback callback) throws RemoteException {
- switch (mState) {
- case STATE_ENABLED:
- mBackupTransportConnection.release();
- mDataAggregator.disable();
- mState = STATE_VISIBLE;
- notifyStateMonitors();
- callback.onSuccess();
- break;
- case STATE_VISIBLE:
- callback.onSuccess();
- break;
- default:
- callback.onFailure(ERROR_INVALID_STATE_TRANSITION);
+ if (mState == STATE_DISABLED) {
+ callback.onSuccess();
+ return;
}
+
+ // TODO: temporarily disable the following for the CTS ForensicManagerTest.
+ // Enable it when the transport component is ready.
+ // mForensicEventTransportConnection.release();
+ mDataAggregator.disable();
+ mState = STATE_DISABLED;
+ notifyStateMonitors();
+ callback.onSuccess();
}
/**
* Add a list of ForensicEvent.
*/
public void addNewData(List<ForensicEvent> events) {
- mHandler.obtainMessage(MSG_BACKUP, events).sendToTarget();
+ mHandler.obtainMessage(MSG_TRANSPORT, events).sendToTarget();
}
- private void backup(List<ForensicEvent> events) {
- mBackupTransportConnection.addData(events);
+ private void transport(List<ForensicEvent> events) {
+ mForensicEventTransportConnection.addData(events);
}
@Override
@@ -296,9 +278,11 @@
interface Injector {
Context getContext();
+ PermissionEnforcer getPermissionEnforcer();
+
Looper getLooper();
- BackupTransportConnection getBackupTransportConnection();
+ ForensicEventTransportConnection getForensicEventransportConnection();
DataAggregator getDataAggregator(ForensicService forensicService);
}
@@ -315,6 +299,10 @@
return mContext;
}
+ @Override
+ public PermissionEnforcer getPermissionEnforcer() {
+ return PermissionEnforcer.fromContext(mContext);
+ }
@Override
public Looper getLooper() {
@@ -326,8 +314,8 @@
}
@Override
- public BackupTransportConnection getBackupTransportConnection() {
- return new BackupTransportConnection(mContext);
+ public ForensicEventTransportConnection getForensicEventransportConnection() {
+ return new ForensicEventTransportConnection(mContext);
}
@Override
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index 6707a27..f50417d 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -2856,7 +2856,10 @@
void prepareForShutdown() {
for (int i = 0; i < getChildCount(); i++) {
- createSleepToken("shutdown", getChildAt(i).mDisplayId);
+ final int displayId = getChildAt(i).mDisplayId;
+ mWindowManager.mSnapshotController.mTaskSnapshotController
+ .snapshotForShutdown(displayId);
+ createSleepToken("shutdown", displayId);
}
}
diff --git a/services/core/java/com/android/server/wm/SnapshotPersistQueue.java b/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
index 1c8c245..bd8e8f4 100644
--- a/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
+++ b/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
@@ -64,6 +64,7 @@
private boolean mStarted;
private final Object mLock = new Object();
private final UserManagerInternal mUserManagerInternal;
+ private boolean mShutdown;
SnapshotPersistQueue() {
mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
@@ -101,6 +102,16 @@
}
}
+ /**
+ * Write out everything in the queue because of shutdown.
+ */
+ void shutdown() {
+ synchronized (mLock) {
+ mShutdown = true;
+ mLock.notifyAll();
+ }
+ }
+
@VisibleForTesting
void waitForQueueEmpty() {
while (true) {
@@ -193,7 +204,9 @@
if (isReadyToWrite) {
next.write();
}
- SystemClock.sleep(DELAY_MS);
+ if (!mShutdown) {
+ SystemClock.sleep(DELAY_MS);
+ }
}
synchronized (mLock) {
final boolean writeQueueEmpty = mWriteQueue.isEmpty();
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotController.java b/services/core/java/com/android/server/wm/TaskSnapshotController.java
index 1f82cdb..9fe3f756 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotController.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotController.java
@@ -307,6 +307,28 @@
}
/**
+ * Record task snapshots before shutdown.
+ */
+ void snapshotForShutdown(int displayId) {
+ if (!com.android.window.flags.Flags.recordTaskSnapshotsBeforeShutdown()) {
+ return;
+ }
+ final DisplayContent displayContent = mService.mRoot.getDisplayContent(displayId);
+ if (displayContent == null) {
+ return;
+ }
+ displayContent.forAllLeafTasks(task -> {
+ if (task.isVisible() && !task.isActivityTypeHome()) {
+ final TaskSnapshot snapshot = captureSnapshot(task);
+ if (snapshot != null) {
+ mPersister.persistSnapshot(task.mTaskId, task.mUserId, snapshot);
+ }
+ }
+ }, true /* traverseTopToBottom */);
+ mPersister.mSnapshotPersistQueue.shutdown();
+ }
+
+ /**
* Called when screen is being turned off.
*/
void screenTurningOff(int displayId, ScreenOffListener listener) {
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 54b257c..8268cae 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -1022,12 +1022,12 @@
return;
}
- final boolean disableSecureWindows;
+ boolean disableSecureWindows;
try {
disableSecureWindows = Settings.Secure.getIntForUser(mContext.getContentResolver(),
Settings.Secure.DISABLE_SECURE_WINDOWS, 0) != 0;
} catch (Settings.SettingNotFoundException e) {
- return;
+ disableSecureWindows = false;
}
if (mDisableSecureWindows == disableSecureWindows) {
return;
diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java
index ead1282..0918965 100644
--- a/services/core/java/com/android/server/wm/WindowOrganizerController.java
+++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java
@@ -788,7 +788,9 @@
deferResume = false;
// Already calls ensureActivityConfig
mService.mRootWindowContainer.ensureActivitiesVisible();
- mService.mRootWindowContainer.resumeFocusedTasksTopActivities();
+ if (!mService.mRootWindowContainer.resumeFocusedTasksTopActivities()) {
+ mService.mTaskSupervisor.updateTopResumedActivityIfNeeded("endWCT-effects");
+ }
} else if ((effects & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
for (int i = haveConfigChanges.size() - 1; i >= 0; --i) {
haveConfigChanges.valueAt(i).forAllActivities(r -> {
@@ -886,7 +888,8 @@
if (windowingMode > -1) {
if (mService.isInLockTaskMode()
- && WindowConfiguration.inMultiWindowMode(windowingMode)) {
+ && WindowConfiguration.inMultiWindowMode(windowingMode)
+ && !container.isEmbedded()) {
Slog.w(TAG, "Dropping unsupported request to set multi-window windowing mode"
+ " during locked task mode.");
return effects;
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java
index b982098..76d16e1 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java
@@ -371,6 +371,9 @@
}
ActiveAdmin(int userId, boolean permissionBased) {
+ if (Flags.activeAdminCleanup()) {
+ throw new UnsupportedOperationException("permission based admin no longer supported");
+ }
if (permissionBased == false) {
throw new IllegalArgumentException("Can only pass true for permissionBased admin");
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
index 395ea91..c937e10 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
@@ -21,6 +21,7 @@
import android.annotation.UserIdInt;
import android.app.admin.DeviceAdminInfo;
import android.app.admin.DevicePolicyManager;
+import android.app.admin.flags.Flags;
import android.content.ComponentName;
import android.os.FileUtils;
import android.os.PersistableBundle;
@@ -124,17 +125,18 @@
final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
- // Some DevicePolicyManager APIs can be called by (1) a DPC or (2) an app with permissions that
- // isn't a DPC. For the latter, the caller won't have to provide a ComponentName and won't be
- // mapped to an ActiveAdmin. This permission-based admin should be used to persist policies
- // set by the permission-based caller. This admin should not be added to mAdminMap or mAdminList
- // since a lot of methods in DPMS assume the ActiveAdmins here have a valid ComponentName.
- // Instead, use variants of DPMS active admin getters to include the permission-based admin.
+ /**
+ * @deprecated Do not use. Policies set by permission holders must go into DevicePolicyEngine.
+ */
+ @Deprecated
ActiveAdmin mPermissionBasedAdmin;
// Create or get the permission-based admin. The permission-based admin will not have a
// DeviceAdminInfo or ComponentName.
ActiveAdmin createOrGetPermissionBasedAdmin(int userId) {
+ if (Flags.activeAdminCleanup()) {
+ throw new UnsupportedOperationException("permission based admin no longer supported");
+ }
if (mPermissionBasedAdmin == null) {
mPermissionBasedAdmin = new ActiveAdmin(userId, /* permissionBased= */ true);
}
@@ -147,7 +149,7 @@
// This is the list of component allowed to start lock task mode.
List<String> mLockTaskPackages = new ArrayList<>();
- /** @deprecated moved to {@link ActiveAdmin#protectedPackages}. */
+ /** @deprecated moved to DevicePolicyEngine. */
@Deprecated
@Nullable
List<String> mUserControlDisabledPackages;
@@ -280,7 +282,7 @@
}
}
- if (policyData.mPermissionBasedAdmin != null) {
+ if (!Flags.activeAdminCleanup() && policyData.mPermissionBasedAdmin != null) {
out.startTag(null, "permission-based-admin");
policyData.mPermissionBasedAdmin.writeToXml(out);
out.endTag(null, "permission-based-admin");
@@ -521,7 +523,8 @@
} catch (RuntimeException e) {
Slogf.w(TAG, e, "Failed loading admin %s", name);
}
- } else if ("permission-based-admin".equals(tag)) {
+ } else if (!Flags.activeAdminCleanup() && "permission-based-admin".equals(tag)) {
+
ActiveAdmin ap = new ActiveAdmin(policy.mUserId, /* permissionBased= */ true);
ap.readFromXml(parser, /* overwritePolicies= */ false);
policy.mPermissionBasedAdmin = ap;
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 28eec5c..6292cbf 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -376,6 +376,7 @@
import android.app.compat.CompatChanges;
import android.app.role.OnRoleHoldersChangedListener;
import android.app.role.RoleManager;
+import android.app.supervision.SupervisionManagerInternal;
import android.app.trust.TrustManager;
import android.app.usage.UsageStatsManagerInternal;
import android.compat.annotation.ChangeId;
@@ -504,6 +505,7 @@
import com.android.internal.app.LocalePicker;
import com.android.internal.infra.AndroidFuture;
import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.nano.MetricsProto;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.net.NetworkUtilsInternal;
import com.android.internal.notification.SystemNotificationChannels;
@@ -715,24 +717,24 @@
SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE);
GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>();
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE);
- GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.ADB_ENABLED);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.ADB_WIFI_ENABLED);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.AUTO_TIME);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.AUTO_TIME_ZONE);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.DATA_ROAMING);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.USB_MASS_STORAGE_ENABLED);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.WIFI_SLEEP_POLICY);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.STAY_ON_WHILE_PLUGGED_IN);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
+ GLOBAL_SETTINGS_ALLOWLIST.add(Global.PRIVATE_DNS_MODE);
+ GLOBAL_SETTINGS_ALLOWLIST.add(PRIVATE_DNS_SPECIFIER);
GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
- GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
- GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
- GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
- GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
- GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
+ GLOBAL_SETTINGS_DEPRECATED.add(Global.BLUETOOTH_ON);
+ GLOBAL_SETTINGS_DEPRECATED.add(Global.DEVELOPMENT_SETTINGS_ENABLED);
+ GLOBAL_SETTINGS_DEPRECATED.add(Global.MODE_RINGER);
+ GLOBAL_SETTINGS_DEPRECATED.add(Global.NETWORK_PREFERENCE);
+ GLOBAL_SETTINGS_DEPRECATED.add(Global.WIFI_ON);
SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>();
SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS);
@@ -775,7 +777,7 @@
/**
* Strings logged with {@link
- * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
+ * MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
* {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB},
* {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and
* {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}.
@@ -786,11 +788,11 @@
/**
* For admin apps targeting R+, throw when the app sets password requirement
* that is not taken into account at given quality. For example when quality is set
- * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
+ * to {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
* make sense to require certain password length. If the intent is to require a password of
* certain length having at least NUMERIC quality, the admin should first call
- * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call
- * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}.
+ * {@link DevicePolicyManager#setPasswordQuality} and only then call
+ * {@link DevicePolicyManager#setPasswordMinimumLength}.
*
* <p>Conversely when an admin app targeting R+ lowers password quality, those
* requirements that stop making sense are reset to default values.
@@ -801,9 +803,9 @@
/**
* Admin apps targeting Android R+ may not use
- * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated
- * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use
- * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}.
+ * {@link DevicePolicyManager#setSecureSetting} to change the deprecated
+ * {@link Settings.Secure#LOCATION_MODE} setting. Instead they should use
+ * {@link DevicePolicyManager#setLocationEnabled}.
*/
@ChangeId
@EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
@@ -849,7 +851,7 @@
private @interface CopyAccountStatus {}
/**
- * Mapping of {@link android.app.admin.DevicePolicyManager.ApplicationExemptionConstants} to
+ * Mapping of {@link DevicePolicyManager.ApplicationExemptionConstants} to
* corresponding app-ops.
*/
private static final Map<Integer, String> APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS =
@@ -881,11 +883,11 @@
/**
* Admin apps targeting Android S+ may not use
- * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality
+ * {@link DevicePolicyManager#setPasswordQuality} to set password quality
* on the {@code DevicePolicyManager} instance obtained by calling
- * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}.
+ * {@link DevicePolicyManager#getParentProfileInstance}.
* Instead, they should use
- * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set
+ * {@link DevicePolicyManager#setRequiredPasswordComplexity} to set
* coarse-grained password requirements device-wide.
*/
@ChangeId
@@ -894,7 +896,7 @@
/**
* For Admin Apps targeting U+
- * If {@link android.security.IKeyChainService#setGrant} is called with an alias with no
+ * If {@link IKeyChainService#setGrant} is called with an alias with no
* existing key, throw IllegalArgumentException.
*/
@ChangeId
@@ -926,6 +928,8 @@
final UsageStatsManagerInternal mUsageStatsManagerInternal;
final TelephonyManager mTelephonyManager;
final RoleManager mRoleManager;
+ final SupervisionManagerInternal mSupervisionManagerInternal;
+
private final LockPatternUtils mLockPatternUtils;
private final LockSettingsInternal mLockSettingsInternal;
private final DeviceAdminServiceController mDeviceAdminServiceController;
@@ -1474,8 +1478,8 @@
if (packageName == null || packageName.equals(adminPackage)) {
if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
|| mIPackageManager.getReceiverInfo(aa.info.getComponent(),
- PackageManager.MATCH_DIRECT_BOOT_AWARE
- | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+ MATCH_DIRECT_BOOT_AWARE
+ | MATCH_DIRECT_BOOT_UNAWARE,
userHandle) == null) {
Slogf.e(LOG_TAG, String.format(
"Admin package %s not found for user %d, removing active admin",
@@ -1693,7 +1697,7 @@
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
}
- Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
+ Context createContextAsUser(UserHandle user) throws NameNotFoundException {
final String packageName = mContext.getPackageName();
return mContext.createPackageContextAsUser(packageName, 0, user);
}
@@ -2005,25 +2009,25 @@
}
void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
- Settings.Global.putStringForUser(mContext.getContentResolver(),
+ Global.putStringForUser(mContext.getContentResolver(),
name, value, userHandle);
}
int settingsGlobalGetInt(String name, int def) {
- return Settings.Global.getInt(mContext.getContentResolver(), name, def);
+ return Global.getInt(mContext.getContentResolver(), name, def);
}
@Nullable
String settingsGlobalGetString(String name) {
- return Settings.Global.getString(mContext.getContentResolver(), name);
+ return Global.getString(mContext.getContentResolver(), name);
}
void settingsGlobalPutInt(String name, int value) {
- Settings.Global.putInt(mContext.getContentResolver(), name, value);
+ Global.putInt(mContext.getContentResolver(), name, value);
}
void settingsGlobalPutString(String name, String value) {
- Settings.Global.putString(mContext.getContentResolver(), name, value);
+ Global.putString(mContext.getContentResolver(), name, value);
}
void settingsSystemPutStringForUser(String name, String value, int userId) {
@@ -2082,6 +2086,11 @@
boolean isAdminInstalledCaCertAutoApproved() {
return false;
}
+
+ @Nullable
+ SupervisionManagerInternal getSupervisionManager() {
+ return LocalServices.getService(SupervisionManagerInternal.class);
+ }
}
/**
@@ -2113,6 +2122,11 @@
mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager());
mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager());
mRoleManager = Objects.requireNonNull(injector.getRoleManager());
+ if (Flags.secondaryLockscreenApiEnabled()) {
+ mSupervisionManagerInternal = injector.getSupervisionManager();
+ } else {
+ mSupervisionManagerInternal = null;
+ }
mLocalService = new LocalService();
mLockPatternUtils = injector.newLockPatternUtils();
@@ -2234,7 +2248,6 @@
return Collections.unmodifiableSet(packageNames);
}
-
private @Nullable String getDefaultRoleHolderPackageName(int resId) {
String packageNameAndSignature = mContext.getString(resId);
@@ -3194,8 +3207,8 @@
return mIPackageManager.getReceiverInfo(adminName,
GET_META_DATA
| PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
- | PackageManager.MATCH_DIRECT_BOOT_AWARE
- | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
+ | MATCH_DIRECT_BOOT_AWARE
+ | MATCH_DIRECT_BOOT_UNAWARE, userHandle);
} catch (RemoteException e) {
// shouldn't happen.
Slogf.wtf(LOG_TAG, "Error getting receiver info", e);
@@ -3206,9 +3219,9 @@
throw new IllegalArgumentException("Unknown admin: " + adminName);
}
- if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
+ if (!BIND_DEVICE_ADMIN.equals(ai.permission)) {
final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
- + permission.BIND_DEVICE_ADMIN;
+ + BIND_DEVICE_ADMIN;
Slogf.w(LOG_TAG, message);
if (throwForMissingPermission &&
ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
@@ -3966,7 +3979,8 @@
final int N = admins.size();
for (int i = 0; i < N; i++) {
ActiveAdmin admin = admins.get(i);
- if ((admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD))
+ if (((!Flags.activeAdminCleanup() && admin.isPermissionBased)
+ || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD))
&& admin.passwordExpirationTimeout > 0L
&& now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
&& admin.passwordExpirationDate > 0L) {
@@ -4399,8 +4413,8 @@
final ApplicationInfo ai;
try {
ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
- (PackageManager.MATCH_DIRECT_BOOT_AWARE
- | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
+ (MATCH_DIRECT_BOOT_AWARE
+ | MATCH_DIRECT_BOOT_UNAWARE), userHandle);
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
@@ -5563,13 +5577,25 @@
caller.getUserId());
Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
- ActiveAdmin activeAdmin = admin.getActiveAdmin();
+ final ActiveAdmin activeAdmin;
+ if (Flags.activeAdminCleanup()) {
+ if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
+ synchronized (getLockObject()) {
+ activeAdmin = getActiveAdminUncheckedLocked(
+ admin.getComponentName(), admin.getUserId());
+ }
+ } else {
+ activeAdmin = null;
+ }
+ } else {
+ activeAdmin = admin.getActiveAdmin();
+ }
// We require the caller to explicitly clear any password quality requirements set
// on the parent DPM instance, to avoid the case where password requirements are
// specified in the form of quality on the parent but complexity on the profile
// itself.
- if (!calledOnParent) {
+ if (activeAdmin != null && !calledOnParent) {
final boolean hasQualityRequirementsOnParent = activeAdmin.hasParentActiveAdmin()
&& activeAdmin.getParentActiveAdmin().mPasswordPolicy.quality
!= PASSWORD_QUALITY_UNSPECIFIED;
@@ -5593,20 +5619,22 @@
}
mInjector.binderWithCleanCallingIdentity(() -> {
- // Reset the password policy.
- if (calledOnParent) {
- activeAdmin.getParentActiveAdmin().mPasswordPolicy = new PasswordPolicy();
- } else {
- activeAdmin.mPasswordPolicy = new PasswordPolicy();
+ if (activeAdmin != null) {
+ // Reset the password policy.
+ if (calledOnParent) {
+ activeAdmin.getParentActiveAdmin().mPasswordPolicy = new PasswordPolicy();
+ } else {
+ activeAdmin.mPasswordPolicy = new PasswordPolicy();
+ }
+ updatePasswordQualityCacheForUserGroup(caller.getUserId());
}
+
synchronized (getLockObject()) {
updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
}
- updatePasswordQualityCacheForUserGroup(caller.getUserId());
saveSettingsLocked(caller.getUserId());
});
-
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
.setAdmin(caller.getPackageName())
@@ -5965,7 +5993,7 @@
Preconditions.checkCallAuthorization(admin != null,
"Unauthorized caller cannot call resetPassword.");
if (getTargetSdk(admin.info.getPackageName(),
- userHandle) <= android.os.Build.VERSION_CODES.M) {
+ userHandle) <= Build.VERSION_CODES.M) {
Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()");
return false;
}
@@ -6115,7 +6143,7 @@
if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
// Make sure KEEP_SCREEN_ON is disabled, since that
// would allow bypassing of the maximum time to lock.
- mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
+ mInjector.settingsGlobalPutInt(Global.STAY_ON_WHILE_PLUGGED_IN, 0);
}
getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(parentId, timeMs);
});
@@ -6287,28 +6315,33 @@
final int callingUserId = caller.getUserId();
ComponentName adminComponent = null;
synchronized (getLockObject()) {
- ActiveAdmin admin;
// Make sure the caller has any active admin with the right policy or
// the required permission.
if (Flags.lockNowCoexistence()) {
- admin = enforcePermissionsAndGetEnforcingAdmin(
+ EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
/* admin= */ null,
/* permissions= */ new String[]{MANAGE_DEVICE_POLICY_LOCK, LOCK_DEVICE},
/* deviceAdminPolicy= */ USES_POLICY_FORCE_LOCK,
caller.getPackageName(),
getAffectedUser(parent)
- ).getActiveAdmin();
+ );
+ if (Flags.activeAdminCleanup()) {
+ adminComponent = enforcingAdmin.getComponentName();
+ } else {
+ ActiveAdmin admin = enforcingAdmin.getActiveAdmin();
+ adminComponent = admin == null ? null : admin.info.getComponent();
+ }
} else {
- admin = getActiveAdminOrCheckPermissionForCallerLocked(
+ ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked(
null,
- DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
+ USES_POLICY_FORCE_LOCK,
parent,
LOCK_DEVICE);
+ adminComponent = admin == null ? null : admin.info.getComponent();
}
checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW);
final long ident = mInjector.binderClearCallingIdentity();
try {
- adminComponent = admin == null ? null : admin.info.getComponent();
if (adminComponent != null) {
// For Profile Owners only, callers with only permission not allowed.
if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
@@ -7443,7 +7476,7 @@
* privileged APIs.
* <p>
* This is done by checking that the calling package is authorized to perform the app operation
- * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}.
+ * {@link AppOpsManager#OP_MANAGE_CREDENTIALS}.
*
* @param caller the calling identity
* @return {@code true} if the calling process is the credential management app.
@@ -7453,7 +7486,7 @@
AppOpsManager appOpsManager = mInjector.getAppOpsManager();
if (appOpsManager == null) return false;
return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(),
- caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED;
+ caller.getPackageName(), null, null) == MODE_ALLOWED;
});
}
@@ -7764,7 +7797,7 @@
public void wipeDataWithReason(String callerPackageName, int flags,
@NonNull String wipeReasonForUser, boolean calledOnParentInstance,
boolean factoryReset) {
- if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
+ if (!mHasFeature && !hasCallingOrSelfPermission(MASTER_CLEAR)) {
return;
}
CallerIdentity caller = getCallerIdentity(callerPackageName);
@@ -7777,7 +7810,6 @@
USES_POLICY_WIPE_DATA,
caller.getPackageName(),
factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
- ActiveAdmin admin = enforcingAdmin.getActiveAdmin();
checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);
@@ -7786,10 +7818,20 @@
calledByProfileOwnerOnOrgOwnedDevice, calledOnParentInstance);
}
- int userId = admin != null ? admin.getUserHandle().getIdentifier()
- : caller.getUserId();
- Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
- userId);
+ int userId;
+ ActiveAdmin admin = null;
+ if (Flags.activeAdminCleanup()) {
+ userId = enforcingAdmin.getUserId();
+ Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser,
+ enforcingAdmin, userId);
+ } else {
+ admin = enforcingAdmin.getActiveAdmin();
+ userId = admin != null ? admin.getUserHandle().getIdentifier()
+ : caller.getUserId();
+ Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
+ userId);
+ }
+
if (calledByProfileOwnerOnOrgOwnedDevice) {
// When wipeData is called on the parent instance, it implies wiping the entire device.
if (calledOnParentInstance) {
@@ -7810,25 +7852,36 @@
final String adminName;
final ComponentName adminComp;
- if (admin != null) {
- if (admin.isPermissionBased) {
- adminComp = null;
- adminName = caller.getPackageName();
- event.setAdmin(adminName);
- } else {
- adminComp = admin.info.getComponent();
- adminName = adminComp.flattenToShortString();
- event.setAdmin(adminComp);
- }
+ if (Flags.activeAdminCleanup()) {
+ adminComp = enforcingAdmin.getComponentName();
+ adminName = adminComp != null
+ ? adminComp.flattenToShortString()
+ : enforcingAdmin.getPackageName();
+ event.setAdmin(enforcingAdmin.getPackageName());
+ // Not including any HSUM handling here because the "else" branch in the "flag off"
+ // case below is unreachable under normal circumstances and for permission-based
+ // callers admin won't be null.
} else {
- adminComp = null;
- adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
- Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
- event.setAdmin(adminName);
- if (mInjector.userManagerIsHeadlessSystemUserMode()) {
- // On headless system user mode, the call is meant to factory reset the whole
- // device, otherwise the caller could simply remove the current user.
- userId = UserHandle.USER_SYSTEM;
+ if (admin != null) {
+ if (admin.isPermissionBased) {
+ adminComp = null;
+ adminName = caller.getPackageName();
+ event.setAdmin(adminName);
+ } else {
+ adminComp = admin.info.getComponent();
+ adminName = adminComp.flattenToShortString();
+ event.setAdmin(adminComp);
+ }
+ } else {
+ adminComp = null;
+ adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
+ Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
+ event.setAdmin(adminName);
+ if (mInjector.userManagerIsHeadlessSystemUserMode()) {
+ // On headless system user mode, the call is meant to factory reset the whole
+ // device, otherwise the caller could simply remove the current user.
+ userId = UserHandle.USER_SYSTEM;
+ }
}
}
event.write();
@@ -8142,7 +8195,7 @@
synchronized (getLockObject()) {
if (who == null) {
Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid()
- || hasCallingPermission(permission.MASTER_CLEAR)
+ || hasCallingPermission(MASTER_CLEAR)
|| hasCallingPermission(MANAGE_DEVICE_POLICY_FACTORY_RESET),
"Must be called by the FRP management agent on device");
admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
@@ -8316,7 +8369,8 @@
List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
for (int i = 0; i < admins.size(); i++) {
ActiveAdmin admin = admins.get(i);
- if (admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
+ if ((!Flags.activeAdminCleanup() && admin.isPermissionBased)
+ || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
affectedUserIds.add(admin.getUserHandle().getIdentifier());
long timeout = admin.passwordExpirationTimeout;
admin.passwordExpirationDate =
@@ -8410,7 +8464,7 @@
*/
private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) {
final int userId = admin.getUserHandle().getIdentifier();
- if (admin.isPermissionBased) {
+ if (!Flags.activeAdminCleanup() && admin.isPermissionBased) {
return userId;
}
final ComponentName component = admin.info.getComponent();
@@ -8628,9 +8682,9 @@
Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
return;
}
- mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
- mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
- mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
+ mInjector.settingsGlobalPutString(Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
+ mInjector.settingsGlobalPutInt(Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
+ mInjector.settingsGlobalPutString(Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
exclusionList);
}
@@ -8751,7 +8805,7 @@
}
final int rawStatus = getEncryptionStatus();
- if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
+ if ((rawStatus == ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
}
return rawStatus;
@@ -8775,7 +8829,7 @@
*/
private int getEncryptionStatus() {
if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
- return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
+ return ENCRYPTION_STATUS_ACTIVE_PER_USER;
} else {
return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
}
@@ -8970,7 +9024,7 @@
// Turn AUTO_TIME on in settings if it is required
if (required) {
mInjector.binderWithCleanCallingIdentity(
- () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME,
+ () -> mInjector.settingsGlobalPutInt(Global.AUTO_TIME,
1 /* AUTO_TIME on */));
}
DevicePolicyEventLogger
@@ -10402,7 +10456,7 @@
policy.mDelegationMap.clear();
policy.mStatusBarDisabled = false;
policy.mSecondaryLockscreenEnabled = false;
- policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
+ policy.mUserProvisioningState = STATE_USER_UNMANAGED;
policy.mAffiliationIds.clear();
resetAffiliationCacheLocked();
policy.mLockTaskPackages.clear();
@@ -10437,7 +10491,7 @@
@Override
public int getUserProvisioningState(int userHandle) {
if (!mHasFeature) {
- return DevicePolicyManager.STATE_USER_UNMANAGED;
+ return STATE_USER_UNMANAGED;
}
final CallerIdentity caller = getCallerIdentity();
Preconditions.checkCallAuthorization(canManageUsers(caller)
@@ -10492,7 +10546,7 @@
// ADB shell can only move directly from un-managed to finalized as part of
// directly setting profile-owner or device-owner.
if (getUserProvisioningState(userId)
- != DevicePolicyManager.STATE_USER_UNMANAGED
+ != STATE_USER_UNMANAGED
|| newState != STATE_USER_SETUP_FINALIZED) {
throw new IllegalStateException("Not allowed to change provisioning state "
+ "unless current provisioning state is unmanaged, and new state"
@@ -10530,9 +10584,9 @@
}
// Valid transitions for normal use-cases.
switch (currentState) {
- case DevicePolicyManager.STATE_USER_UNMANAGED:
+ case STATE_USER_UNMANAGED:
// Can move to any state from unmanaged (except itself as an edge case)..
- if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
+ if (newState != STATE_USER_UNMANAGED) {
return;
}
break;
@@ -10556,7 +10610,7 @@
break;
case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED:
// Should only move to an unmanaged state after removing the work profile.
- if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
+ if (newState == STATE_USER_UNMANAGED) {
return;
}
break;
@@ -10928,7 +10982,7 @@
UserHandle userHandle = UserHandle.of(userId);
userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0,
userHandle);
- } catch (PackageManager.NameNotFoundException nnfe) {
+ } catch (NameNotFoundException nnfe) {
Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId);
return null;
}
@@ -11148,20 +11202,20 @@
}
private boolean canQueryAdminPolicy(CallerIdentity caller) {
- return hasCallingOrSelfPermission(permission.QUERY_ADMIN_POLICY);
+ return hasCallingOrSelfPermission(QUERY_ADMIN_POLICY);
}
private boolean hasPermission(String permission, int pid, int uid) {
- return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED;
+ return mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED;
}
private boolean hasCallingPermission(String permission) {
- return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
+ return mContext.checkCallingPermission(permission) == PERMISSION_GRANTED;
}
private boolean hasCallingOrSelfPermission(String permission) {
return mContext.checkCallingOrSelfPermission(permission)
- == PackageManager.PERMISSION_GRANTED;
+ == PERMISSION_GRANTED;
}
private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) {
@@ -11467,7 +11521,7 @@
private String getEncryptionStatusName(int encryptionStatus) {
switch (encryptionStatus) {
- case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
+ case ENCRYPTION_STATUS_ACTIVE_PER_USER:
return "per-user";
case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
return "unsupported";
@@ -12549,7 +12603,7 @@
if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
- Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
+ USER_SETUP_COMPLETE, 1, userHandle);
}
sendProvisioningCompletedBroadcast(
@@ -13965,8 +14019,8 @@
List<ResolveInfo> activitiesToEnable = mIPackageManager
.queryIntentActivities(intent,
intent.resolveTypeIfNeeded(mContext.getContentResolver()),
- PackageManager.MATCH_DIRECT_BOOT_AWARE
- | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+ MATCH_DIRECT_BOOT_AWARE
+ | MATCH_DIRECT_BOOT_UNAWARE,
parentUserId)
.getList();
@@ -14585,34 +14639,76 @@
}
}
+ private boolean hasActiveSupervisionTestAdminLocked(@UserIdInt int userId) {
+ ensureLocked();
+ if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
+ final DevicePolicyData policy = getUserData(userId);
+ for (ActiveAdmin admin : policy.mAdminMap.values()) {
+ if (admin != null && admin.testOnlyAdmin) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
@Override
public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled,
PersistableBundle options) {
- Objects.requireNonNull(who, "ComponentName is null");
-
- // Check can set secondary lockscreen enabled
- final CallerIdentity caller = getCallerIdentity(who);
- Preconditions.checkCallAuthorization(
- isDefaultDeviceOwner(caller) || isProfileOwner(caller));
- Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
- "User %d is not allowed to call setSecondaryLockscreenEnabled",
+ if (Flags.secondaryLockscreenApiEnabled()) {
+ final CallerIdentity caller = getCallerIdentity();
+ final boolean isRoleHolder = isCallerSystemSupervisionRoleHolder(caller);
+ synchronized (getLockObject()) {
+ // TODO(b/378102594): Remove access for test admins.
+ final boolean isTestAdmin = hasActiveSupervisionTestAdminLocked(caller.getUserId());
+ Preconditions.checkCallAuthorization(isRoleHolder || isTestAdmin,
+ "Caller (%d) is not the SYSTEM_SUPERVISION role holder",
caller.getUserId());
+ }
- synchronized (getLockObject()) {
- // Allow testOnly admins to bypass supervision config requirement.
- Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
- || isSupervisionComponentLocked(caller.getComponentName()), "Admin %s is not "
- + "the default supervision component", caller.getComponentName());
- DevicePolicyData policy = getUserData(caller.getUserId());
- policy.mSecondaryLockscreenEnabled = enabled;
- saveSettingsLocked(caller.getUserId());
+ if (mSupervisionManagerInternal != null) {
+ mSupervisionManagerInternal.setSupervisionLockscreenEnabledForUser(
+ caller.getUserId(), enabled, options);
+ } else {
+ synchronized (getLockObject()) {
+ DevicePolicyData policy = getUserData(caller.getUserId());
+ policy.mSecondaryLockscreenEnabled = enabled;
+ saveSettingsLocked(caller.getUserId());
+ }
+ }
+ } else {
+ Objects.requireNonNull(who, "ComponentName is null");
+
+ // Check can set secondary lockscreen enabled
+ final CallerIdentity caller = getCallerIdentity(who);
+ Preconditions.checkCallAuthorization(
+ isDefaultDeviceOwner(caller) || isProfileOwner(caller));
+ Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
+ "User %d is not allowed to call setSecondaryLockscreenEnabled",
+ caller.getUserId());
+
+ synchronized (getLockObject()) {
+ // Allow testOnly admins to bypass supervision config requirement.
+ Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
+ || isSupervisionComponentLocked(caller.getComponentName()),
+ "Admin %s is not the default supervision component",
+ caller.getComponentName());
+ DevicePolicyData policy = getUserData(caller.getUserId());
+ policy.mSecondaryLockscreenEnabled = enabled;
+ saveSettingsLocked(caller.getUserId());
+ }
}
}
@Override
public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
- synchronized (getLockObject()) {
- return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
+ if (Flags.secondaryLockscreenApiEnabled() && mSupervisionManagerInternal != null) {
+ return mSupervisionManagerInternal.isSupervisionLockscreenEnabledForUser(
+ userHandle.getIdentifier());
+ } else {
+ synchronized (getLockObject()) {
+ return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
+ }
}
}
@@ -14811,7 +14907,7 @@
if (policy == null) {
// We default on the power button menu, in order to be consistent with pre-P
// behaviour.
- return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
+ return LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
}
return policy.getFlags();
}
@@ -14940,7 +15036,7 @@
"Permission denial: device owners cannot update %1$s", setting));
}
- if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
+ if (Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
// ignore if it contradicts an existing policy
long timeMs = getMaximumTimeToLock(
who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
@@ -15445,7 +15541,7 @@
final int N = users.size();
for (int i = 0; i < N; i++) {
int userHandle = users.get(i).id;
- if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
+ if (mInjector.settingsSecureGetIntForUser(USER_SETUP_COMPLETE, 0,
userHandle) != 0) {
DevicePolicyData policy = getUserData(userHandle);
if (!policy.mUserSetupComplete) {
@@ -15473,7 +15569,7 @@
private class SetupContentObserver extends ContentObserver {
private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
- Settings.Secure.USER_SETUP_COMPLETE);
+ USER_SETUP_COMPLETE);
private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
Settings.Secure.DEFAULT_INPUT_METHOD);
@@ -15521,7 +15617,7 @@
private class DevicePolicyConstantsObserver extends ContentObserver {
final Uri mConstantsUri =
- Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);
+ Global.getUriFor(Global.DEVICE_POLICY_CONSTANTS);
DevicePolicyConstantsObserver(Handler handler) {
super(handler);
@@ -15814,9 +15910,9 @@
final int uid = Objects.requireNonNull(
mInjector.getPackageManager().getApplicationInfoAsUser(
Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid;
- return PackageManager.PERMISSION_GRANTED
+ return PERMISSION_GRANTED
== ActivityManager.checkComponentPermission(
- android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
+ permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
-1, /* exported= */ true);
} catch (NameNotFoundException ex) {
Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
@@ -15953,7 +16049,7 @@
private @Mode int findInteractAcrossProfilesResetMode(String packageName) {
return getDefaultCrossProfilePackages().contains(packageName)
- ? AppOpsManager.MODE_ALLOWED
+ ? MODE_ALLOWED
: AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES);
}
@@ -16272,7 +16368,8 @@
if (admin.mPasswordPolicy.quality < minPasswordQuality) {
return false;
}
- return admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
+ return (!Flags.activeAdminCleanup() && admin.isPermissionBased)
+ || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
}
@Override
@@ -16678,13 +16775,13 @@
synchronized (getLockObject()) {
long ident = mInjector.binderClearCallingIdentity();
boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
- >= android.os.Build.VERSION_CODES.Q;
+ >= Build.VERSION_CODES.Q;
try {
if (!isPostQAdmin) {
// Legacy admins assume that they cannot control pre-M apps
if (getTargetSdk(packageName, caller.getUserId())
- < android.os.Build.VERSION_CODES.M) {
+ < Build.VERSION_CODES.M) {
callback.sendResult(null);
return;
}
@@ -16695,7 +16792,7 @@
}
if (grantState == PERMISSION_GRANT_STATE_GRANTED
|| grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
- || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
+ || grantState == PERMISSION_GRANT_STATE_DEFAULT) {
AdminPermissionControlParams permissionParams =
new AdminPermissionControlParams(packageName, permission,
grantState,
@@ -16730,26 +16827,26 @@
private static final List<String> SENSOR_PERMISSIONS = new ArrayList<>();
{
- SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
- SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
- SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
- SENSOR_PERMISSIONS.add(Manifest.permission.CAMERA);
- SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
- SENSOR_PERMISSIONS.add(Manifest.permission.ACTIVITY_RECOGNITION);
- SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
- SENSOR_PERMISSIONS.add(Manifest.permission.BACKGROUND_CAMERA);
- SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_BACKGROUND_AUDIO);
- SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS_BACKGROUND);
+ SENSOR_PERMISSIONS.add(permission.ACCESS_FINE_LOCATION);
+ SENSOR_PERMISSIONS.add(permission.ACCESS_BACKGROUND_LOCATION);
+ SENSOR_PERMISSIONS.add(permission.ACCESS_COARSE_LOCATION);
+ SENSOR_PERMISSIONS.add(permission.CAMERA);
+ SENSOR_PERMISSIONS.add(permission.RECORD_AUDIO);
+ SENSOR_PERMISSIONS.add(permission.ACTIVITY_RECOGNITION);
+ SENSOR_PERMISSIONS.add(permission.BODY_SENSORS);
+ SENSOR_PERMISSIONS.add(permission.BACKGROUND_CAMERA);
+ SENSOR_PERMISSIONS.add(permission.RECORD_BACKGROUND_AUDIO);
+ SENSOR_PERMISSIONS.add(permission.BODY_SENSORS_BACKGROUND);
}
private boolean canGrantPermission(CallerIdentity caller, String permission,
String targetPackageName) {
boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
- >= android.os.Build.VERSION_CODES.Q;
+ >= Build.VERSION_CODES.Q;
if (!isPostQAdmin) {
// Legacy admins assume that they cannot control pre-M apps
if (getTargetSdk(targetPackageName, caller.getUserId())
- < android.os.Build.VERSION_CODES.M) {
+ < Build.VERSION_CODES.M) {
return false;
}
}
@@ -16796,7 +16893,7 @@
throws RemoteException {
int granted;
if (getTargetSdk(caller.getPackageName(), caller.getUserId())
- < android.os.Build.VERSION_CODES.Q) {
+ < Build.VERSION_CODES.Q) {
// The per-Q behavior was to not check the app-ops state.
granted = mIPackageManager.checkPermission(permission, packageName, userId);
} else {
@@ -16805,11 +16902,11 @@
if (packageState == null) {
Slog.w(LOG_TAG, "Can't get permission state for missing package "
+ packageName);
- return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
+ return PERMISSION_GRANT_STATE_DEFAULT;
} else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
Slog.w(LOG_TAG, "Can't get permission state for uninstalled package "
+ packageName);
- return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
+ return PERMISSION_GRANT_STATE_DEFAULT;
} else {
if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
PermissionChecker.PID_UNKNOWN,
@@ -16817,7 +16914,7 @@
!= PermissionChecker.PERMISSION_GRANTED) {
granted = PackageManager.PERMISSION_DENIED;
} else {
- granted = PackageManager.PERMISSION_GRANTED;
+ granted = PERMISSION_GRANTED;
}
}
@@ -16828,11 +16925,11 @@
if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
!= PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
// Not controlled by policy
- return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
+ return PERMISSION_GRANT_STATE_DEFAULT;
} else {
// Policy controlled so return result based on permission grant state
- return granted == PackageManager.PERMISSION_GRANTED
- ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
+ return granted == PERMISSION_GRANTED
+ ? PERMISSION_GRANT_STATE_GRANTED
: DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
}
}
@@ -16952,9 +17049,9 @@
}
if (action != null) {
switch (action) {
- case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
+ case ACTION_PROVISION_MANAGED_PROFILE:
return checkManagedProfileProvisioningPreCondition(packageName, userId);
- case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
+ case ACTION_PROVISION_MANAGED_DEVICE:
case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE:
return checkDeviceOwnerProvisioningPreCondition(componentName, userId);
}
@@ -18301,7 +18398,7 @@
hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
- Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
+ USER_SETUP_COMPLETE, 0, userId) != 0;
DevicePolicyData policy = getUserData(userId);
policy.mUserSetupComplete = isUserCompleted;
mStateCache.setDeviceProvisioned(isUserCompleted);
@@ -19932,7 +20029,7 @@
}
private boolean isDeviceAB() {
- return "true".equalsIgnoreCase(android.os.SystemProperties
+ return "true".equalsIgnoreCase(SystemProperties
.get(AB_DEVICE_KEY, ""));
}
@@ -20199,7 +20296,7 @@
return mOwners.hasDeviceOwner()
&& mInjector.getIActivityManager().getLockTaskModeState()
== ActivityManager.LOCK_TASK_MODE_LOCKED
- && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
+ && !isLockTaskFeatureEnabled(LOCK_TASK_FEATURE_SYSTEM_INFO)
&& !deviceHasKeyguard()
&& !inEphemeralUserSession();
}
@@ -20210,7 +20307,7 @@
int lockTaskFeatures = policy == null
// We default on the power button menu, in order to be consistent with pre-P
// behaviour.
- ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
+ ? LOCK_TASK_FEATURE_GLOBAL_ACTIONS
: policy.getFlags();
return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
}
@@ -20956,7 +21053,7 @@
private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) {
mInjector.binderWithCleanCallingIdentity(() -> {
- final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE);
+ final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE);
intent.setPackage(caller.getPackageName());
final List<ResolveInfo> handlers =
mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */
@@ -21165,6 +21262,17 @@
Preconditions.checkCallAuthorization(
hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
+ if (Flags.splitCreateManagedProfileEnabled()) {
+ return mInjector.binderWithCleanCallingIdentity(() -> {
+ UserHandle managedProfileUser =
+ createManagedProfileInternal(provisioningParams, caller);
+ maybeMigrateAccount(managedProfileUser.getIdentifier(), caller.getUserId(),
+ provisioningParams.getAccountToMigrate(),
+ provisioningParams.isKeepingAccountOnMigration(), callerPackage);
+ finalizeCreateManagedProfileInternal(provisioningParams, managedProfileUser);
+ return managedProfileUser;
+ });
+ }
provisioningParams.logParams(callerPackage);
UserInfo userInfo = null;
@@ -21258,6 +21366,130 @@
}
@Override
+ public UserHandle createManagedProfile(
+ @NonNull ManagedProfileProvisioningParams provisioningParams,
+ @NonNull String callerPackage) {
+ Objects.requireNonNull(provisioningParams, "provisioningParams is null");
+ Objects.requireNonNull(callerPackage, "callerPackage is null");
+ Objects.requireNonNull(provisioningParams.getProfileAdminComponentName(), "admin is null");
+ Preconditions.checkCallAuthorization(
+ hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
+ CallerIdentity caller = getCallerIdentity(callerPackage);
+
+ return mInjector.binderWithCleanCallingIdentity(() ->
+ createManagedProfileInternal(provisioningParams, caller));
+ }
+
+ private UserHandle createManagedProfileInternal(
+ @NonNull ManagedProfileProvisioningParams provisioningParams,
+ @NonNull CallerIdentity caller) {
+ provisioningParams.logParams(caller.getPackageName());
+ final ComponentName admin = provisioningParams.getProfileAdminComponentName();
+ final int callingUserId = caller.getUserId();
+ UserInfo userInfo = null;
+ try {
+ final int result = checkProvisioningPreconditionSkipPermission(
+ ACTION_PROVISION_MANAGED_PROFILE, admin, callingUserId);
+ if (result != STATUS_OK) {
+ throw new ServiceSpecificException(
+ ERROR_PRE_CONDITION_FAILED,
+ "Provisioning preconditions failed with result: " + result);
+ }
+
+ final long startTime = SystemClock.elapsedRealtime();
+
+ onCreateAndProvisionManagedProfileStarted(provisioningParams);
+
+ userInfo = createProfileForUser(provisioningParams, callingUserId);
+ if (userInfo == null) {
+ throw new ServiceSpecificException(
+ ERROR_PROFILE_CREATION_FAILED,
+ "Error creating profile, createProfileForUserEvenWhenDisallowed "
+ + "returned null.");
+ }
+ resetInteractAcrossProfilesAppOps(caller.getUserId());
+ logEventDuration(
+ DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS,
+ startTime,
+ caller.getPackageName());
+
+ maybeInstallDevicePolicyManagementRoleHolderInUser(userInfo.id);
+ installExistingAdminPackage(userInfo.id, admin.getPackageName());
+
+ if (!enableAdminAndSetProfileOwner(userInfo.id, caller.getUserId(), admin)) {
+ throw new ServiceSpecificException(
+ ERROR_SETTING_PROFILE_OWNER_FAILED,
+ "Error setting profile owner.");
+ }
+ setUserSetupComplete(userInfo.id);
+ startProfileForSetup(userInfo.id, caller.getPackageName());
+
+ if (provisioningParams.isOrganizationOwnedProvisioning()) {
+ synchronized (getLockObject()) {
+ setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id,
+ true);
+ }
+ }
+ return userInfo.getUserHandle();
+ } catch (Exception e) {
+ DevicePolicyEventLogger
+ .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
+ .setStrings(caller.getPackageName())
+ .write();
+ // In case of any errors during provisioning, remove the newly created profile.
+ if (userInfo != null) {
+ mUserManager.removeUserEvenWhenDisallowed(userInfo.id);
+ }
+ throw e;
+ }
+ }
+
+ private UserInfo createProfileForUser(ManagedProfileProvisioningParams params, int userId) {
+ final Set<String> nonRequiredApps = params.isLeaveAllSystemAppsEnabled()
+ ? Collections.emptySet()
+ : mOverlayPackagesProvider.getNonRequiredApps(params.getProfileAdminComponentName(),
+ userId, ACTION_PROVISION_MANAGED_PROFILE);
+ if (nonRequiredApps.isEmpty()) {
+ Slogf.i(LOG_TAG, "No disallowed packages for the managed profile.");
+ } else {
+ for (String packageName : nonRequiredApps) {
+ Slogf.i(LOG_TAG, "Disallowed package [" + packageName + "]");
+ }
+ }
+ return mUserManager.createProfileForUserEvenWhenDisallowed(
+ params.getProfileName(),
+ UserManager.USER_TYPE_PROFILE_MANAGED,
+ UserInfo.FLAG_DISABLED,
+ userId,
+ nonRequiredApps.toArray(new String[nonRequiredApps.size()]));
+ }
+
+ @Override
+ public void finalizeCreateManagedProfile(
+ @NonNull ManagedProfileProvisioningParams provisioningParams,
+ @NonNull UserHandle managedProfileUser) {
+ Objects.requireNonNull(provisioningParams, "provisioningParams is null");
+ Objects.requireNonNull(managedProfileUser, "managedProfileUser is null");
+ Preconditions.checkCallAuthorization(
+ hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
+
+ mInjector.binderWithCleanCallingIdentity(() -> {
+ finalizeCreateManagedProfileInternal(provisioningParams, managedProfileUser);
+ });
+ }
+
+ private void finalizeCreateManagedProfileInternal(
+ @NonNull ManagedProfileProvisioningParams provisioningParams,
+ @NonNull UserHandle managedProfileUser
+ ) {
+ onCreateAndProvisionManagedProfileCompleted(provisioningParams);
+ sendProvisioningCompletedBroadcast(
+ managedProfileUser.getIdentifier(),
+ ACTION_PROVISION_MANAGED_PROFILE,
+ provisioningParams.isLeaveAllSystemAppsEnabled());
+ }
+
+ @Override
public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser,
Account migratedAccount) {
Preconditions.checkCallAuthorization(
@@ -21427,7 +21659,7 @@
private void pregrantDefaultInteractAcrossProfilesAppOps(@UserIdInt int userId) {
final String op =
- AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES);
+ AppOpsManager.permissionToOp(permission.INTERACT_ACROSS_PROFILES);
for (String packageName : getConfigurableDefaultCrossProfilePackages(userId)) {
if (!appOpIsDefaultOrAllowed(userId, op, packageName)) {
continue;
@@ -21630,7 +21862,8 @@
Slogf.i(LOG_TAG, "Account removed from the primary user.");
} else {
// TODO(174768447): Revisit start activity logic.
- final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT, android.content.Intent.class);
+ final Intent removeIntent =
+ result.getParcelable(AccountManager.KEY_INTENT, Intent.class);
removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
if (removeIntent != null) {
Slogf.i(LOG_TAG, "Starting activity to remove account");
@@ -21926,7 +22159,7 @@
}
synchronized (getLockObject()) {
mInjector.settingsGlobalPutStringForUser(
- Settings.Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId);
+ Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId);
}
setUserProvisioningState(STATE_USER_SETUP_FINALIZED, userId);
@@ -22189,7 +22422,7 @@
@Override
public boolean isDevicePotentiallyStolen(String callerPackageName) {
final CallerIdentity caller = getCallerIdentity(callerPackageName);
- if (!android.app.admin.flags.Flags.deviceTheftImplEnabled()) {
+ if (!Flags.deviceTheftImplEnabled()) {
return false;
}
enforcePermission(QUERY_DEVICE_STOLEN_STATE, caller.getPackageName(),
@@ -22225,7 +22458,7 @@
@Override
public void setDrawables(@NonNull List<DevicePolicyDrawableResource> drawables) {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
+ permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
Objects.requireNonNull(drawables, "drawables must be provided.");
@@ -22241,7 +22474,7 @@
@Override
public void resetDrawables(@NonNull List<String> drawableIds) {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
+ permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
Objects.requireNonNull(drawableIds, "drawableIds must be provided.");
@@ -22267,7 +22500,7 @@
@Override
public void setStrings(@NonNull List<DevicePolicyStringResource> strings) {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
+ permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
Objects.requireNonNull(strings, "strings must be provided.");
@@ -22282,7 +22515,7 @@
@Override
public void resetStrings(@NonNull List<String> stringIds) {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
+ permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
mInjector.binderWithCleanCallingIdentity(() -> {
if (mDeviceManagementResourcesProvider.removeStrings(stringIds)) {
@@ -22352,7 +22585,7 @@
@Override
public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.MANAGE_ROLE_HOLDERS));
+ permission.MANAGE_ROLE_HOLDERS));
setBypassDevicePolicyManagementRoleQualificationStateInternal(
/* currentRoleHolder= */ null, /* allowBypass= */ false);
}
@@ -22360,7 +22593,7 @@
@Override
public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
- android.Manifest.permission.MANAGE_ROLE_HOLDERS));
+ permission.MANAGE_ROLE_HOLDERS));
return mInjector.binderWithCleanCallingIdentity(() -> {
if (getUserData(
UserHandle.USER_SYSTEM).mBypassDevicePolicyManagementRoleQualifications) {
@@ -23356,7 +23589,8 @@
return EnforcingAdmin.createDeviceAdminEnforcingAdmin(admin.info.getComponent(), userId,
admin);
}
- admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
+ admin = Flags.activeAdminCleanup()
+ ? null : getUserData(userId).createOrGetPermissionBasedAdmin(userId);
return EnforcingAdmin.createEnforcingAdmin(caller.getPackageName(), userId, admin);
}
@@ -23379,8 +23613,8 @@
}
}
}
-
- admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
+ admin = Flags.activeAdminCleanup()
+ ? null : getUserData(userId).createOrGetPermissionBasedAdmin(userId);
return EnforcingAdmin.createEnforcingAdmin(packageName, userId, admin);
}
@@ -23952,7 +24186,7 @@
if (!isRuntimePermission(permission)) {
continue;
}
- int grantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
+ int grantState = PERMISSION_GRANT_STATE_DEFAULT;
try {
grantState = getPermissionGrantStateForUser(
packageInfo.packageName, permission,
@@ -23965,7 +24199,7 @@
Slogf.e(LOG_TAG, e, "Error retrieving permission grant state for %s "
+ "and %s", packageInfo.packageName, permission);
}
- if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
+ if (grantState == PERMISSION_GRANT_STATE_DEFAULT) {
// Not Controlled by a policy
continue;
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/EnforcingAdmin.java b/services/devicepolicy/java/com/android/server/devicepolicy/EnforcingAdmin.java
index 58e3a7d..1fd628a 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/EnforcingAdmin.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/EnforcingAdmin.java
@@ -23,6 +23,7 @@
import android.app.admin.DpcAuthority;
import android.app.admin.RoleAuthority;
import android.app.admin.UnknownAuthority;
+import android.app.admin.flags.Flags;
import android.content.ComponentName;
import android.os.UserHandle;
@@ -295,9 +296,17 @@
@Nullable
public ActiveAdmin getActiveAdmin() {
+ if (Flags.activeAdminCleanup()) {
+ throw new UnsupportedOperationException("getActiveAdmin() no longer supported");
+ }
return mActiveAdmin;
}
+ @Nullable
+ ComponentName getComponentName() {
+ return mComponentName;
+ }
+
@NonNull
android.app.admin.EnforcingAdmin getParcelableAdmin() {
Authority authority;
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 19b0343..3e7c4ef 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -251,6 +251,7 @@
import com.android.server.security.KeyChainSystemService;
import com.android.server.security.adaptiveauthentication.AdaptiveAuthenticationService;
import com.android.server.security.advancedprotection.AdvancedProtectionService;
+import com.android.server.security.forensic.ForensicService;
import com.android.server.security.rkp.RemoteProvisioningService;
import com.android.server.selinux.SelinuxAuditLogsService;
import com.android.server.sensorprivacy.SensorPrivacyService;
@@ -1760,6 +1761,13 @@
mSystemServiceManager.startService(LogcatManagerService.class);
t.traceEnd();
+ if (!isWatch && !isTv && !isAutomotive
+ && android.security.Flags.aflApi()) {
+ t.traceBegin("StartForensicService");
+ mSystemServiceManager.startService(ForensicService.class);
+ t.traceEnd();
+ }
+
if (AppFunctionManagerConfiguration.isSupported(context)) {
t.traceBegin("StartAppFunctionManager");
mSystemServiceManager.startService(AppFunctionManagerService.class);
@@ -2761,8 +2769,9 @@
mSystemServiceManager.startService(WEAR_MODE_SERVICE_CLASS);
t.traceEnd();
- boolean enableWristOrientationService = SystemProperties.getBoolean(
- "config.enable_wristorientation", false);
+ boolean enableWristOrientationService =
+ !android.server.Flags.migrateWristOrientation()
+ && SystemProperties.getBoolean("config.enable_wristorientation", false);
if (enableWristOrientationService) {
t.traceBegin("StartWristOrientationService");
mSystemServiceManager.startService(WRIST_ORIENTATION_SERVICE_CLASS);
diff --git a/services/java/com/android/server/flags.aconfig b/services/java/com/android/server/flags.aconfig
index e2ac22d..4412968 100644
--- a/services/java/com/android/server/flags.aconfig
+++ b/services/java/com/android/server/flags.aconfig
@@ -39,6 +39,14 @@
}
flag {
+ name: "migrate_wrist_orientation"
+ namespace: "wear_frameworks"
+ description: "Migrate wrist orientation service functionality to wear settings service"
+ bug: "352725980"
+ is_fixed_read_only: true
+}
+
+flag {
name: "allow_network_time_update_service"
namespace: "wear_systems"
description: "Allow NetworkTimeUpdateService on Wear"
diff --git a/services/supervision/java/com/android/server/supervision/SupervisionService.java b/services/supervision/java/com/android/server/supervision/SupervisionService.java
index 67e2547..53a25dd 100644
--- a/services/supervision/java/com/android/server/supervision/SupervisionService.java
+++ b/services/supervision/java/com/android/server/supervision/SupervisionService.java
@@ -21,10 +21,11 @@
import android.annotation.UserIdInt;
import android.app.admin.DevicePolicyManagerInternal;
import android.app.supervision.ISupervisionManager;
+import android.app.supervision.SupervisionManagerInternal;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.UserInfo;
-import android.os.Bundle;
+import android.os.PersistableBundle;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.ShellCallback;
@@ -179,8 +180,15 @@
}
@Override
+ public boolean isSupervisionLockscreenEnabledForUser(@UserIdInt int userId) {
+ synchronized (getLockObject()) {
+ return getUserDataLocked(userId).supervisionLockScreenEnabled;
+ }
+ }
+
+ @Override
public void setSupervisionLockscreenEnabledForUser(
- @UserIdInt int userId, boolean enabled, @Nullable Bundle options) {
+ @UserIdInt int userId, boolean enabled, @Nullable PersistableBundle options) {
synchronized (getLockObject()) {
SupervisionUserData data = getUserDataLocked(userId);
data.supervisionLockScreenEnabled = enabled;
diff --git a/services/supervision/java/com/android/server/supervision/SupervisionUserData.java b/services/supervision/java/com/android/server/supervision/SupervisionUserData.java
index 5616237..1dd48f5 100644
--- a/services/supervision/java/com/android/server/supervision/SupervisionUserData.java
+++ b/services/supervision/java/com/android/server/supervision/SupervisionUserData.java
@@ -19,7 +19,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
-import android.os.Bundle;
+import android.os.PersistableBundle;
import android.util.IndentingPrintWriter;
/** User specific data, used internally by the {@link SupervisionService}. */
@@ -27,7 +27,7 @@
public final @UserIdInt int userId;
public boolean supervisionEnabled;
public boolean supervisionLockScreenEnabled;
- @Nullable public Bundle supervisionLockScreenOptions;
+ @Nullable public PersistableBundle supervisionLockScreenOptions;
public SupervisionUserData(@UserIdInt int userId) {
this.userId = userId;
diff --git a/services/tests/VpnTests/java/com/android/server/connectivity/VpnTest.java b/services/tests/VpnTests/java/com/android/server/connectivity/VpnTest.java
index 08155c7..9772ef9 100644
--- a/services/tests/VpnTests/java/com/android/server/connectivity/VpnTest.java
+++ b/services/tests/VpnTests/java/com/android/server/connectivity/VpnTest.java
@@ -2380,10 +2380,14 @@
@Test
public void doTestMigrateIkeSession_Vcn() throws Exception {
final int expectedKeepalive = 2097; // Any unlikely number will do
- final NetworkCapabilities vcnNc = new NetworkCapabilities.Builder()
- .addTransportType(TRANSPORT_CELLULAR)
- .setTransportInfo(new VcnTransportInfo(TEST_SUB_ID, expectedKeepalive))
- .build();
+ final NetworkCapabilities vcnNc =
+ new NetworkCapabilities.Builder()
+ .addTransportType(TRANSPORT_CELLULAR)
+ .setTransportInfo(
+ new VcnTransportInfo.Builder()
+ .setMinUdpPort4500NatTimeoutSeconds(expectedKeepalive)
+ .build())
+ .build();
final Ikev2VpnProfile ikev2VpnProfile = makeIkeV2VpnProfile(
true /* isAutomaticIpVersionSelectionEnabled */,
true /* isAutomaticNattKeepaliveTimerEnabled */,
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
index 1caa02a..5eb23a2 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
@@ -58,6 +58,7 @@
import com.android.server.wm.ActivityTaskManagerService;
import org.junit.Rule;
+import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -187,8 +188,8 @@
doReturn(true).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
eq(BroadcastFilter.RESTRICT_PRIORITY_VALUES), any(ApplicationInfo.class));
- doReturn(true).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), anyInt());
+ doReturn(true).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), any(ApplicationInfo.class));
}
public void tearDown() throws Exception {
@@ -308,4 +309,8 @@
app.mOptRecord.setPendingFreeze(pendingFreeze);
app.mOptRecord.setFrozen(frozen);
}
+
+ ArgumentMatcher<ApplicationInfo> appInfoEquals(int uid) {
+ return test -> (test.uid == uid);
+ }
}
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
index 88caaa6..82237bc 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
@@ -47,6 +47,7 @@
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
@@ -184,7 +185,10 @@
}
private static BroadcastFilter makeMockRegisteredReceiver() {
- return mock(BroadcastFilter.class);
+ final BroadcastFilter filter = mock(BroadcastFilter.class);
+ final ApplicationInfo info = makeApplicationInfo(PACKAGE_ORANGE);
+ doReturn(info).when(filter).getApplicationInfo();
+ return filter;
}
private BroadcastRecord makeBroadcastRecord(Intent intent) {
@@ -716,9 +720,9 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testRunnableAt_Cached_Prioritized_NonDeferrable_changeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
- eq(getUidForPackage(PACKAGE_GREEN)));
+ argThat(appInfoEquals(getUidForPackage(PACKAGE_GREEN))));
final List receivers = List.of(
withPriority(makeManifestReceiver(PACKAGE_RED, PACKAGE_RED), 10),
withPriority(makeManifestReceiver(PACKAGE_GREEN, PACKAGE_GREEN), -10));
@@ -1288,9 +1292,9 @@
@SuppressWarnings("GuardedBy")
@Test
public void testDeliveryGroupPolicy_prioritized_diffReceivers_changeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
- eq(getUidForPackage(PACKAGE_GREEN)));
+ argThat(appInfoEquals(getUidForPackage(PACKAGE_GREEN))));
final Intent screenOn = new Intent(Intent.ACTION_SCREEN_ON);
final Intent screenOff = new Intent(Intent.ACTION_SCREEN_OFF);
@@ -1823,9 +1827,9 @@
@SuppressWarnings("GuardedBy")
@Test
public void testDeliveryDeferredForCached_changeIdDisabled() throws Exception {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
- eq(getUidForPackage(PACKAGE_GREEN)));
+ argThat(appInfoEquals(getUidForPackage(PACKAGE_GREEN))));
final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
@@ -2027,9 +2031,9 @@
@Test
public void testDeliveryDeferredForCached_withInfiniteDeferred_changeIdDisabled()
throws Exception {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
- eq(getUidForPackage(PACKAGE_GREEN)));
+ argThat(appInfoEquals(getUidForPackage(PACKAGE_GREEN))));
final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
index a38ef78..ea80f28 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
@@ -1659,8 +1659,9 @@
final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
final ProcessRecord receiverYellowApp = makeActiveProcessRecord(PACKAGE_YELLOW);
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(receiverBlueApp.uid));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
+ argThat(appInfoEquals(receiverBlueApp.uid)));
// Enqueue a normal broadcast that will go to several processes, and
// then enqueue a foreground broadcast that risks reordering
@@ -2471,8 +2472,9 @@
final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(receiverBlueApp.uid));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE),
+ argThat(appInfoEquals(receiverBlueApp.uid)));
mUidObserver.onUidStateChanged(receiverGreenApp.info.uid,
ActivityManager.PROCESS_STATE_TOP, 0, ActivityManager.PROCESS_CAPABILITY_NONE);
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
index f9f3790..8482fd6 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
@@ -19,12 +19,12 @@
import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
-import static com.android.server.am.BroadcastRecord.LIMIT_PRIORITY_SCOPE;
import static com.android.server.am.BroadcastRecord.DELIVERY_DEFERRED;
import static com.android.server.am.BroadcastRecord.DELIVERY_DELIVERED;
import static com.android.server.am.BroadcastRecord.DELIVERY_PENDING;
import static com.android.server.am.BroadcastRecord.DELIVERY_SKIPPED;
import static com.android.server.am.BroadcastRecord.DELIVERY_TIMEOUT;
+import static com.android.server.am.BroadcastRecord.LIMIT_PRIORITY_SCOPE;
import static com.android.server.am.BroadcastRecord.calculateBlockedUntilBeyondCount;
import static com.android.server.am.BroadcastRecord.calculateDeferUntilActive;
import static com.android.server.am.BroadcastRecord.calculateUrgent;
@@ -35,7 +35,8 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import android.app.BackgroundStartPrivileges;
@@ -63,6 +64,7 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@@ -108,8 +110,8 @@
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- doReturn(true).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), anyInt());
+ doReturn(true).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), any(ApplicationInfo.class));
}
@Test
@@ -222,8 +224,8 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testIsPrioritized_withDifferentPriorities_withFirstUidChangeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(1))));
assertTrue(isPrioritized(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
@@ -256,8 +258,8 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testIsPrioritized_withDifferentPriorities_withLastUidChangeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(3)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(3))));
assertTrue(isPrioritized(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
@@ -294,8 +296,8 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testIsPrioritized_withDifferentPriorities_withUidChangeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(2))));
assertTrue(isPrioritized(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
@@ -328,10 +330,10 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testIsPrioritized_withDifferentPriorities_withMultipleUidChangeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(1))));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(2))));
assertTrue(isPrioritized(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
@@ -362,10 +364,10 @@
assertArrayEquals(new int[] {0, 0, 1, 1, 3},
calculateBlockedUntilBeyondCount(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 20),
- createResolveInfo(PACKAGE2, getAppId(3), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 20),
createResolveInfo(PACKAGE3, getAppId(3), 10),
createResolveInfo(PACKAGE3, getAppId(3), 0),
- createResolveInfo(PACKAGE3, getAppId(2), 0)), false, mPlatformCompat));
+ createResolveInfo(PACKAGE2, getAppId(2), 0)), false, mPlatformCompat));
}
@Test
@@ -592,8 +594,8 @@
@EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testSetDeliveryState_DeferUntilActive_changeIdDisabled() {
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(1))));
final BroadcastRecord r = createBroadcastRecord(
new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED), List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
@@ -960,8 +962,8 @@
createResolveInfo(PACKAGE2, getAppId(2)),
createResolveInfo(PACKAGE3, getAppId(3)))));
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(1))));
assertArrayEquals(new boolean[] {false, true, true}, calculateChangeState(
List.of(createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE2, getAppId(2)),
@@ -969,11 +971,11 @@
assertArrayEquals(new boolean[] {false, true, false, true}, calculateChangeState(
List.of(createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE2, getAppId(2)),
- createResolveInfo(PACKAGE2, getAppId(1)),
+ createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE3, getAppId(3)))));
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(2))));
assertArrayEquals(new boolean[] {false, false, true}, calculateChangeState(
List.of(createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE2, getAppId(2)),
@@ -987,8 +989,8 @@
createResolveInfo(PACKAGE2, getAppId(2)),
createResolveInfo(PACKAGE3, getAppId(3)))));
- doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
- eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), eq(getAppId(3)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledInternalNoLogging(
+ eq(BroadcastRecord.LIMIT_PRIORITY_SCOPE), argThat(appInfoEquals(getAppId(3))));
assertArrayEquals(new boolean[] {false, false, false}, calculateChangeState(
List.of(createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE2, getAppId(2)),
@@ -998,7 +1000,7 @@
List.of(createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE3, getAppId(3)),
createResolveInfo(PACKAGE2, getAppId(2)),
- createResolveInfo(PACKAGE2, getAppId(1)),
+ createResolveInfo(PACKAGE1, getAppId(1)),
createResolveInfo(PACKAGE2, getAppId(2)),
createResolveInfo(PACKAGE3, getAppId(3)))));
}
@@ -1185,4 +1187,8 @@
assertEquals("deferred", expectedDeferredCount, r.deferredCount);
assertEquals("beyond", expectedBeyondCount, r.beyondCount);
}
+
+ private ArgumentMatcher<ApplicationInfo> appInfoEquals(int uid) {
+ return test -> (test.uid == uid);
+ }
}
diff --git a/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java b/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
index 359cf63..b48c2d7 100644
--- a/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
+++ b/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
@@ -2705,12 +2705,11 @@
verify(mInvalidateInteractiveCachesMock).call();
listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
- verify(mInvalidateInteractiveCachesMock, times(2)).call();
mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP,
mClock.now(), 0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
- verify(mInvalidateInteractiveCachesMock, times(3)).call();
+ verify(mInvalidateInteractiveCachesMock, times(2)).call();
}
@Test
@@ -2732,12 +2731,11 @@
verify(mInvalidateInteractiveCachesMock).call();
listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
- verify(mInvalidateInteractiveCachesMock, times(2)).call();
mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP, mClock.now(),
0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
- verify(mInvalidateInteractiveCachesMock, times(3)).call();
+ verify(mInvalidateInteractiveCachesMock, times(2)).call();
}
@Test
diff --git a/services/tests/security/forensic/src/com/android/server/security/forensic/ForensicServiceTest.java b/services/tests/security/forensic/src/com/android/server/security/forensic/ForensicServiceTest.java
index 40e0034..0da6db6 100644
--- a/services/tests/security/forensic/src/com/android/server/security/forensic/ForensicServiceTest.java
+++ b/services/tests/security/forensic/src/com/android/server/security/forensic/ForensicServiceTest.java
@@ -16,9 +16,13 @@
package com.android.server.security.forensic;
+import static android.Manifest.permission.MANAGE_FORENSIC_STATE;
+import static android.Manifest.permission.READ_FORENSIC_STATE;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
@@ -29,7 +33,9 @@
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Looper;
+import android.os.PermissionEnforcer;
import android.os.RemoteException;
+import android.os.test.FakePermissionEnforcer;
import android.os.test.TestLooper;
import android.security.forensic.ForensicEvent;
import android.security.forensic.IForensicServiceCommandCallback;
@@ -41,6 +47,7 @@
import com.android.server.ServiceThread;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -50,34 +57,36 @@
public class ForensicServiceTest {
private static final int STATE_UNKNOWN = IForensicServiceStateCallback.State.UNKNOWN;
- private static final int STATE_INVISIBLE = IForensicServiceStateCallback.State.INVISIBLE;
- private static final int STATE_VISIBLE = IForensicServiceStateCallback.State.VISIBLE;
+ private static final int STATE_DISABLED = IForensicServiceStateCallback.State.DISABLED;
private static final int STATE_ENABLED = IForensicServiceStateCallback.State.ENABLED;
private static final int ERROR_UNKNOWN = IForensicServiceCommandCallback.ErrorCode.UNKNOWN;
private static final int ERROR_PERMISSION_DENIED =
IForensicServiceCommandCallback.ErrorCode.PERMISSION_DENIED;
- private static final int ERROR_INVALID_STATE_TRANSITION =
- IForensicServiceCommandCallback.ErrorCode.INVALID_STATE_TRANSITION;
- private static final int ERROR_BACKUP_TRANSPORT_UNAVAILABLE =
- IForensicServiceCommandCallback.ErrorCode.BACKUP_TRANSPORT_UNAVAILABLE;
+ private static final int ERROR_TRANSPORT_UNAVAILABLE =
+ IForensicServiceCommandCallback.ErrorCode.TRANSPORT_UNAVAILABLE;
private static final int ERROR_DATA_SOURCE_UNAVAILABLE =
IForensicServiceCommandCallback.ErrorCode.DATA_SOURCE_UNAVAILABLE;
private Context mContext;
- private BackupTransportConnection mBackupTransportConnection;
+ private ForensicEventTransportConnection mForensicEventTransportConnection;
private DataAggregator mDataAggregator;
private ForensicService mForensicService;
private TestLooper mTestLooper;
private Looper mLooper;
private TestLooper mTestLooperOfDataAggregator;
private Looper mLooperOfDataAggregator;
+ private FakePermissionEnforcer mPermissionEnforcer;
@SuppressLint("VisibleForTests")
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
+ mPermissionEnforcer = new FakePermissionEnforcer();
+ mPermissionEnforcer.grant(READ_FORENSIC_STATE);
+ mPermissionEnforcer.grant(MANAGE_FORENSIC_STATE);
+
mTestLooper = new TestLooper();
mLooper = mTestLooper.getLooper();
mTestLooperOfDataAggregator = new TestLooper();
@@ -87,217 +96,101 @@
}
@Test
- public void testMonitorState_Invisible() throws RemoteException {
+ public void testAddStateCallback_NoPermission() {
+ mPermissionEnforcer.revoke(READ_FORENSIC_STATE);
StateCallback scb = new StateCallback();
assertEquals(STATE_UNKNOWN, scb.mState);
- mForensicService.getBinderService().monitorState(scb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb.mState);
+ assertThrows(SecurityException.class,
+ () -> mForensicService.getBinderService().addStateCallback(scb));
}
@Test
- public void testMonitorState_Invisible_TwoMonitors() throws RemoteException {
+ public void testRemoveStateCallback_NoPermission() {
+ mPermissionEnforcer.revoke(READ_FORENSIC_STATE);
+ StateCallback scb = new StateCallback();
+ assertEquals(STATE_UNKNOWN, scb.mState);
+ assertThrows(SecurityException.class,
+ () -> mForensicService.getBinderService().removeStateCallback(scb));
+ }
+
+ @Test
+ public void testEnable_NoPermission() {
+ mPermissionEnforcer.revoke(MANAGE_FORENSIC_STATE);
+
+ CommandCallback ccb = new CommandCallback();
+ assertThrows(SecurityException.class,
+ () -> mForensicService.getBinderService().enable(ccb));
+ }
+
+ @Test
+ public void testDisable_NoPermission() {
+ mPermissionEnforcer.revoke(MANAGE_FORENSIC_STATE);
+
+ CommandCallback ccb = new CommandCallback();
+ assertThrows(SecurityException.class,
+ () -> mForensicService.getBinderService().disable(ccb));
+ }
+
+ @Test
+ public void testAddStateCallback_Disabled() throws RemoteException {
+ StateCallback scb = new StateCallback();
+ assertEquals(STATE_UNKNOWN, scb.mState);
+ mForensicService.getBinderService().addStateCallback(scb);
+ mTestLooper.dispatchAll();
+ assertEquals(STATE_DISABLED, scb.mState);
+ }
+
+ @Test
+ public void testAddStateCallback_Disabled_TwoStateCallbacks() throws RemoteException {
StateCallback scb1 = new StateCallback();
assertEquals(STATE_UNKNOWN, scb1.mState);
- mForensicService.getBinderService().monitorState(scb1);
+ mForensicService.getBinderService().addStateCallback(scb1);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
StateCallback scb2 = new StateCallback();
assertEquals(STATE_UNKNOWN, scb2.mState);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
}
@Test
- public void testMakeVisible_FromInvisible() throws RemoteException {
- StateCallback scb = new StateCallback();
- assertEquals(STATE_UNKNOWN, scb.mState);
- mForensicService.getBinderService().monitorState(scb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeVisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb.mState);
- assertNull(ccb.mErrorCode);
- }
-
- @Test
- public void testMakeVisible_FromInvisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_INVISIBLE);
+ public void testRemoveStateCallback() throws RemoteException {
+ mForensicService.setState(STATE_DISABLED);
StateCallback scb1 = new StateCallback();
StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
doReturn(true).when(mDataAggregator).initialize();
+ doReturn(true).when(mForensicEventTransportConnection).initialize();
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeVisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
- assertNull(ccb.mErrorCode);
- }
-
- @Test
- public void testMakeVisible_FromInvisible_TwoMonitors_DataSourceUnavailable()
- throws RemoteException {
- mForensicService.setState(STATE_INVISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
-
- doReturn(false).when(mDataAggregator).initialize();
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeVisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNotNull(ccb.mErrorCode);
- assertEquals(ERROR_DATA_SOURCE_UNAVAILABLE, ccb.mErrorCode.intValue());
- }
-
- @Test
- public void testMakeVisible_FromVisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_VISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeVisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
- assertNull(ccb.mErrorCode);
- }
-
- @Test
- public void testMakeVisible_FromEnabled_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_ENABLED);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_ENABLED, scb1.mState);
- assertEquals(STATE_ENABLED, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeVisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_ENABLED, scb1.mState);
- assertEquals(STATE_ENABLED, scb2.mState);
- assertNotNull(ccb.mErrorCode);
- assertEquals(ERROR_INVALID_STATE_TRANSITION, ccb.mErrorCode.intValue());
- }
-
- @Test
- public void testMakeInvisible_FromInvisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_INVISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeInvisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNull(ccb.mErrorCode);
- }
-
- @Test
- public void testMakeInvisible_FromVisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_VISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeInvisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNull(ccb.mErrorCode);
- }
-
- @Test
- public void testMakeInvisible_FromEnabled_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_ENABLED);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_ENABLED, scb1.mState);
- assertEquals(STATE_ENABLED, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().makeInvisible(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNull(ccb.mErrorCode);
- }
-
-
- @Test
- public void testEnable_FromInvisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_INVISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
+ mForensicService.getBinderService().removeStateCallback(scb2);
CommandCallback ccb = new CommandCallback();
mForensicService.getBinderService().enable(ccb);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNotNull(ccb.mErrorCode);
- assertEquals(ERROR_INVALID_STATE_TRANSITION, ccb.mErrorCode.intValue());
+ assertEquals(STATE_ENABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
+ assertNull(ccb.mErrorCode);
}
@Test
- public void testEnable_FromVisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_VISIBLE);
+ public void testEnable_FromDisabled_TwoStateCallbacks() throws RemoteException {
+ mForensicService.setState(STATE_DISABLED);
StateCallback scb1 = new StateCallback();
StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
- doReturn(true).when(mBackupTransportConnection).initialize();
+ doReturn(true).when(mForensicEventTransportConnection).initialize();
CommandCallback ccb = new CommandCallback();
mForensicService.getBinderService().enable(ccb);
@@ -310,35 +203,13 @@
}
@Test
- public void testEnable_FromVisible_TwoMonitors_BackupTransportUnavailable()
+ public void testEnable_FromEnabled_TwoStateCallbacks()
throws RemoteException {
- mForensicService.setState(STATE_VISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
-
- doReturn(false).when(mBackupTransportConnection).initialize();
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().enable(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
- assertNotNull(ccb.mErrorCode);
- assertEquals(ERROR_BACKUP_TRANSPORT_UNAVAILABLE, ccb.mErrorCode.intValue());
- }
-
- @Test
- public void testEnable_FromEnabled_TwoMonitors() throws RemoteException {
mForensicService.setState(STATE_ENABLED);
StateCallback scb1 = new StateCallback();
StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
assertEquals(STATE_ENABLED, scb1.mState);
assertEquals(STATE_ENABLED, scb2.mState);
@@ -346,62 +217,44 @@
CommandCallback ccb = new CommandCallback();
mForensicService.getBinderService().enable(ccb);
mTestLooper.dispatchAll();
+
assertEquals(STATE_ENABLED, scb1.mState);
assertEquals(STATE_ENABLED, scb2.mState);
assertNull(ccb.mErrorCode);
}
@Test
- public void testDisable_FromInvisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_INVISIBLE);
+ public void testDisable_FromDisabled_TwoStateCallbacks() throws RemoteException {
+ mForensicService.setState(STATE_DISABLED);
StateCallback scb1 = new StateCallback();
StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
CommandCallback ccb = new CommandCallback();
mForensicService.getBinderService().disable(ccb);
mTestLooper.dispatchAll();
- assertEquals(STATE_INVISIBLE, scb1.mState);
- assertEquals(STATE_INVISIBLE, scb2.mState);
- assertNotNull(ccb.mErrorCode);
- assertEquals(ERROR_INVALID_STATE_TRANSITION, ccb.mErrorCode.intValue());
- }
- @Test
- public void testDisable_FromVisible_TwoMonitors() throws RemoteException {
- mForensicService.setState(STATE_VISIBLE);
- StateCallback scb1 = new StateCallback();
- StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
-
- CommandCallback ccb = new CommandCallback();
- mForensicService.getBinderService().disable(ccb);
- mTestLooper.dispatchAll();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
assertNull(ccb.mErrorCode);
}
@Test
- public void testDisable_FromEnabled_TwoMonitors() throws RemoteException {
+ public void testDisable_FromEnabled_TwoStateCallbacks() throws RemoteException {
mForensicService.setState(STATE_ENABLED);
StateCallback scb1 = new StateCallback();
StateCallback scb2 = new StateCallback();
- mForensicService.getBinderService().monitorState(scb1);
- mForensicService.getBinderService().monitorState(scb2);
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
mTestLooper.dispatchAll();
assertEquals(STATE_ENABLED, scb1.mState);
assertEquals(STATE_ENABLED, scb2.mState);
- doNothing().when(mBackupTransportConnection).release();
+ doNothing().when(mForensicEventTransportConnection).release();
ServiceThread mockThread = spy(ServiceThread.class);
mDataAggregator.setHandler(mLooperOfDataAggregator, mockThread);
@@ -412,11 +265,35 @@
mTestLooperOfDataAggregator.dispatchAll();
// TODO: We can verify the data sources once we implement them.
verify(mockThread, times(1)).quitSafely();
- assertEquals(STATE_VISIBLE, scb1.mState);
- assertEquals(STATE_VISIBLE, scb2.mState);
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
assertNull(ccb.mErrorCode);
}
+ @Ignore("Enable once the ForensicEventTransportConnection is ready")
+ @Test
+ public void testEnable_FromDisable_TwoStateCallbacks_TransportUnavailable()
+ throws RemoteException {
+ mForensicService.setState(STATE_DISABLED);
+ StateCallback scb1 = new StateCallback();
+ StateCallback scb2 = new StateCallback();
+ mForensicService.getBinderService().addStateCallback(scb1);
+ mForensicService.getBinderService().addStateCallback(scb2);
+ mTestLooper.dispatchAll();
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
+
+ doReturn(false).when(mForensicEventTransportConnection).initialize();
+
+ CommandCallback ccb = new CommandCallback();
+ mForensicService.getBinderService().enable(ccb);
+ mTestLooper.dispatchAll();
+ assertEquals(STATE_DISABLED, scb1.mState);
+ assertEquals(STATE_DISABLED, scb2.mState);
+ assertNotNull(ccb.mErrorCode);
+ assertEquals(ERROR_TRANSPORT_UNAVAILABLE, ccb.mErrorCode.intValue());
+ }
+
@Test
public void testDataAggregator_AddBatchData() {
mForensicService.setState(STATE_ENABLED);
@@ -441,14 +318,14 @@
events.add(eventOne);
events.add(eventTwo);
- doReturn(true).when(mBackupTransportConnection).addData(any());
+ doReturn(true).when(mForensicEventTransportConnection).addData(any());
mDataAggregator.addBatchData(events);
mTestLooperOfDataAggregator.dispatchAll();
mTestLooper.dispatchAll();
ArgumentCaptor<List<ForensicEvent>> captor = ArgumentCaptor.forClass(List.class);
- verify(mBackupTransportConnection).addData(captor.capture());
+ verify(mForensicEventTransportConnection).addData(captor.capture());
List<ForensicEvent> receivedEvents = captor.getValue();
assertEquals(receivedEvents.size(), 2);
@@ -476,6 +353,10 @@
return mContext;
}
+ @Override
+ public PermissionEnforcer getPermissionEnforcer() {
+ return mPermissionEnforcer;
+ }
@Override
public Looper getLooper() {
@@ -483,9 +364,9 @@
}
@Override
- public BackupTransportConnection getBackupTransportConnection() {
- mBackupTransportConnection = spy(new BackupTransportConnection(mContext));
- return mBackupTransportConnection;
+ public ForensicEventTransportConnection getForensicEventransportConnection() {
+ mForensicEventTransportConnection = spy(new ForensicEventTransportConnection(mContext));
+ return mForensicEventTransportConnection;
}
@Override
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java b/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
index b81bf3c..f6f831f 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
@@ -21,6 +21,7 @@
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
import static android.hardware.biometrics.BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE;
import static android.hardware.biometrics.BiometricManager.BIOMETRIC_ERROR_NOT_ENABLED_FOR_APPS;
+import static android.hardware.biometrics.BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE;
import static com.android.server.biometrics.sensors.LockoutTracker.LOCKOUT_NONE;
@@ -354,6 +355,21 @@
assertThat(preAuthInfo.getIsMandatoryBiometricsAuthentication()).isTrue();
}
+ @Test
+ public void prioritizeStrengthErrorBeforeCameraUnavailableError() throws Exception {
+ final BiometricSensor sensor = getFaceSensorWithStrength(
+ BiometricManager.Authenticators.BIOMETRIC_WEAK);
+ final PromptInfo promptInfo = new PromptInfo();
+ promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
+ promptInfo.setNegativeButtonText(TEST_PACKAGE_NAME);
+ final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
+ mSettingObserver, List.of(sensor), USER_ID , promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
+
+ assertThat(preAuthInfo.getCanAuthenticateResult()).isEqualTo(BIOMETRIC_ERROR_NO_HARDWARE);
+ }
+
private BiometricSensor getFingerprintSensor() {
BiometricSensor sensor = new BiometricSensor(mContext, SENSOR_ID_FINGERPRINT,
TYPE_FINGERPRINT, BiometricManager.Authenticators.BIOMETRIC_STRONG,
@@ -372,9 +388,10 @@
return sensor;
}
- private BiometricSensor getFaceSensor() {
+ private BiometricSensor getFaceSensorWithStrength(
+ @BiometricManager.Authenticators.Types int sensorStrength) {
BiometricSensor sensor = new BiometricSensor(mContext, SENSOR_ID_FACE, TYPE_FACE,
- BiometricManager.Authenticators.BIOMETRIC_STRONG, mFaceAuthenticator) {
+ sensorStrength, mFaceAuthenticator) {
@Override
boolean confirmationAlwaysRequired(int userId) {
return false;
@@ -388,4 +405,8 @@
return sensor;
}
+
+ private BiometricSensor getFaceSensor() {
+ return getFaceSensorWithStrength(BiometricManager.Authenticators.BIOMETRIC_STRONG);
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
index 698bda3..4c381eb 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
@@ -24,6 +24,7 @@
import android.app.admin.DevicePolicyManagerInternal;
import android.app.admin.DevicePolicyManagerLiteInternal;
import android.app.backup.IBackupManager;
+import android.app.supervision.SupervisionManagerInternal;
import android.app.usage.UsageStatsManagerInternal;
import android.content.Context;
import android.content.Intent;
@@ -488,6 +489,11 @@
public Context createContextAsUser(UserHandle user) {
return context;
}
+
+ @Override
+ SupervisionManagerInternal getSupervisionManager() {
+ return services.supervisionManagerInternal;
+ }
}
static class TransferOwnershipMetadataManagerMockInjector extends
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 9524fb2..cf5dc4b 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -109,6 +109,7 @@
import android.app.admin.PreferentialNetworkServiceConfig;
import android.app.admin.SystemUpdatePolicy;
import android.app.admin.WifiSsidPolicy;
+import android.app.admin.flags.Flags;
import android.app.role.RoleManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -134,6 +135,10 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.platform.test.annotations.Presubmit;
+import android.platform.test.annotations.RequiresFlagsDisabled;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.provider.DeviceConfig;
import android.provider.Settings;
import android.security.KeyChain;
@@ -165,6 +170,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
+import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.collections.Sets;
@@ -207,6 +213,9 @@
public static final String INVALID_CALLING_IDENTITY_MSG = "Calling identity is not authorized";
public static final String ONGOING_CALL_MSG = "ongoing call on the device";
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+
// TODO replace all instances of this with explicit {@link #mServiceContext}.
@Deprecated
private DpmMockContext mContext;
@@ -4903,6 +4912,7 @@
}
@Test
+ @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
public void testSecondaryLockscreen_profileOwner() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_UID;
@@ -4931,6 +4941,7 @@
}
@Test
+ @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
public void testSecondaryLockscreen_deviceOwner() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
@@ -4949,6 +4960,7 @@
}
@Test
+ @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
public void testSecondaryLockscreen_nonOwner() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_UID;
@@ -4965,6 +4977,7 @@
}
@Test
+ @RequiresFlagsDisabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
public void testSecondaryLockscreen_nonSupervisionApp() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_UID;
@@ -4997,6 +5010,51 @@
}
@Test
+ @RequiresFlagsEnabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
+ public void testIsSecondaryLockscreenEnabled() throws Exception {
+ mContext.binder.callingUid = DpmMockContext.CALLER_UID;
+
+ verifyIsSecondaryLockscreenEnabled(false);
+ verifyIsSecondaryLockscreenEnabled(true);
+ }
+
+ private void verifyIsSecondaryLockscreenEnabled(boolean expected) throws Exception {
+ reset(getServices().supervisionManagerInternal);
+
+ doReturn(expected).when(getServices().supervisionManagerInternal)
+ .isSupervisionLockscreenEnabledForUser(anyInt());
+
+ final boolean enabled = dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE));
+ verify(getServices().supervisionManagerInternal)
+ .isSupervisionLockscreenEnabledForUser(CALLER_USER_HANDLE);
+
+ assertThat(enabled).isEqualTo(expected);
+ }
+
+ @Test
+ @RequiresFlagsEnabled(Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED)
+ public void testSetSecondaryLockscreenEnabled() throws Exception {
+ mContext.binder.callingUid = DpmMockContext.CALLER_UID;
+
+ verifySetSecondaryLockscreenEnabled(false);
+ verifySetSecondaryLockscreenEnabled(true);
+ }
+
+ private void verifySetSecondaryLockscreenEnabled(boolean enabled) throws Exception {
+ reset(getServices().supervisionManagerInternal);
+
+ dpm.setSecondaryLockscreenEnabled(admin1, enabled);
+ verify(getServices().supervisionManagerInternal).setSupervisionLockscreenEnabledForUser(
+ CALLER_USER_HANDLE, enabled, null);
+
+ reset(getServices().supervisionManagerInternal);
+
+ dpm.setSecondaryLockscreenEnabled(enabled, new PersistableBundle());
+ verify(getServices().supervisionManagerInternal).setSupervisionLockscreenEnabledForUser(
+ eq(CALLER_USER_HANDLE), eq(enabled), any(PersistableBundle.class));
+ }
+
+ @Test
public void testIsDeviceManaged() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
index 2e200a9..3e4448c1 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
@@ -35,6 +35,7 @@
import android.app.admin.DevicePolicyManager;
import android.app.backup.IBackupManager;
import android.app.role.RoleManager;
+import android.app.supervision.SupervisionManagerInternal;
import android.app.usage.UsageStatsManagerInternal;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -77,8 +78,8 @@
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockSettingsInternal;
import com.android.server.AlarmManagerInternal;
-import com.android.server.pdb.PersistentDataBlockManagerInternal;
import com.android.server.net.NetworkPolicyManagerInternal;
+import com.android.server.pdb.PersistentDataBlockManagerInternal;
import com.android.server.pm.PackageManagerLocal;
import com.android.server.pm.UserManagerInternal;
import com.android.server.pm.pkg.PackageState;
@@ -149,6 +150,7 @@
public final BuildMock buildMock = new BuildMock();
public final File dataDir;
public final PolicyPathProvider pathProvider;
+ public final SupervisionManagerInternal supervisionManagerInternal;
private final Map<String, PackageState> mTestPackageStates = new ArrayMap<>();
@@ -203,6 +205,7 @@
roleManager = realContext.getSystemService(RoleManager.class);
roleManagerForMock = mock(RoleManagerForMock.class);
subscriptionManager = mock(SubscriptionManager.class);
+ supervisionManagerInternal = mock(SupervisionManagerInternal.class);
// Package manager is huge, so we use a partial mock instead.
packageManager = spy(realContext.getPackageManager());
diff --git a/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionManagerServiceTest.java
index 73aec63..510c2bc 100644
--- a/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionManagerServiceTest.java
@@ -532,6 +532,8 @@
MediaProjectionManagerService.MediaProjection projection = startProjectionPreconditions();
projection.start(mIMediaProjectionCallback);
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, projection.packageName);
doReturn(true).when(mKeyguardManager).isKeyguardLocked();
MediaProjectionManagerService.BinderService mediaProjectionBinderService =
mService.new BinderService(mContext);
@@ -540,50 +542,6 @@
verify(mContext, never()).startActivityAsUser(any(), any());
}
- @EnableFlags(android.companion.virtualdevice.flags
- .Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
- @Test
- public void testKeyguardLocked_stopsActiveProjection() throws Exception {
- MediaProjectionManagerService service =
- new MediaProjectionManagerService(mContext, mMediaProjectionMetricsLoggerInjector);
- MediaProjectionManagerService.MediaProjection projection =
- startProjectionPreconditions(service);
- projection.start(mIMediaProjectionCallback);
- projection.notifyVirtualDisplayCreated(10);
-
- assertThat(service.getActiveProjectionInfo()).isNotNull();
-
- doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager)
- .checkPermission(RECORD_SENSITIVE_CONTENT, projection.packageName);
- service.onKeyguardLockedStateChanged(true);
-
- verify(mMediaProjectionMetricsLogger).logStopped(UID, TARGET_UID_UNKNOWN);
- assertThat(service.getActiveProjectionInfo()).isNull();
- assertThat(mIMediaProjectionCallback.mLatch.await(5, TimeUnit.SECONDS)).isTrue();
- }
-
- @EnableFlags(android.companion.virtualdevice.flags
- .Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
- @Test
- public void testKeyguardLocked_packageAllowlisted_doesNotStopActiveProjection()
- throws NameNotFoundException {
- MediaProjectionManagerService service =
- new MediaProjectionManagerService(mContext, mMediaProjectionMetricsLoggerInjector);
- MediaProjectionManagerService.MediaProjection projection =
- startProjectionPreconditions(service);
- projection.start(mIMediaProjectionCallback);
- projection.notifyVirtualDisplayCreated(10);
-
- assertThat(service.getActiveProjectionInfo()).isNotNull();
-
- doReturn(PackageManager.PERMISSION_GRANTED).when(mPackageManager).checkPermission(
- RECORD_SENSITIVE_CONTENT, projection.packageName);
- service.onKeyguardLockedStateChanged(true);
-
- verifyZeroInteractions(mMediaProjectionMetricsLogger);
- assertThat(service.getActiveProjectionInfo()).isNotNull();
- }
-
@Test
public void stop_noActiveProjections_doesNotLog() throws Exception {
MediaProjectionManagerService service =
diff --git a/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionStopControllerTest.java b/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionStopControllerTest.java
new file mode 100644
index 0000000..89d2d28
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/media/projection/MediaProjectionStopControllerTest.java
@@ -0,0 +1,429 @@
+/*
+ * Copyright (C) 2024 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.media.projection;
+
+
+import static android.Manifest.permission.RECORD_SENSITIVE_CONTENT;
+import static android.provider.Settings.Global.DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS;
+import static android.view.Display.INVALID_DISPLAY;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.Manifest;
+import android.annotation.SuppressLint;
+import android.app.ActivityManagerInternal;
+import android.app.AppOpsManager;
+import android.app.Instrumentation;
+import android.app.KeyguardManager;
+import android.app.role.RoleManager;
+import android.companion.AssociationRequest;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.ApplicationInfoFlags;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.media.projection.MediaProjectionManager;
+import android.os.UserHandle;
+import android.platform.test.annotations.EnableFlags;
+import android.platform.test.annotations.Presubmit;
+import android.platform.test.flag.junit.SetFlagsRule;
+import android.provider.Settings;
+import android.telecom.TelecomManager;
+import android.testing.TestableContext;
+import android.util.ArraySet;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.server.LocalServices;
+import com.android.server.SystemConfig;
+import com.android.server.wm.WindowManagerInternal;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Objects;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+/**
+ * Tests for the {@link MediaProjectionStopController} class.
+ * <p>
+ * Build/Install/Run:
+ * atest FrameworksServicesTests:MediaProjectionStopControllerTest
+ */
+@SmallTest
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+@SuppressLint({"UseCheckPermission", "VisibleForTests", "MissingPermission"})
+public class MediaProjectionStopControllerTest {
+ private static final int UID = 10;
+ private static final String PACKAGE_NAME = "test.package";
+ private final ApplicationInfo mAppInfo = new ApplicationInfo();
+ @Rule
+ public final TestableContext mContext = spy(
+ new TestableContext(InstrumentationRegistry.getInstrumentation().getContext()));
+
+ private final MediaProjectionManagerService.Injector mMediaProjectionMetricsLoggerInjector =
+ new MediaProjectionManagerService.Injector() {
+ @Override
+ MediaProjectionMetricsLogger mediaProjectionMetricsLogger(Context context) {
+ return mMediaProjectionMetricsLogger;
+ }
+ };
+
+ private MediaProjectionManagerService mService;
+
+ @Rule
+ public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
+ @Mock
+ private ActivityManagerInternal mAmInternal;
+ @Mock
+ private PackageManager mPackageManager;
+ @Mock
+ private KeyguardManager mKeyguardManager;
+ @Mock
+ private TelecomManager mTelecomManager;
+
+ private AppOpsManager mAppOpsManager;
+ @Mock
+ private MediaProjectionMetricsLogger mMediaProjectionMetricsLogger;
+ @Mock
+ private Consumer<Integer> mStopConsumer;
+
+ private MediaProjectionStopController mStopController;
+
+ @Before
+ public void setup() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ LocalServices.removeServiceForTest(ActivityManagerInternal.class);
+ LocalServices.addService(ActivityManagerInternal.class, mAmInternal);
+
+ mAppOpsManager = mockAppOpsManager();
+ mContext.addMockSystemService(AppOpsManager.class, mAppOpsManager);
+ mContext.addMockSystemService(KeyguardManager.class, mKeyguardManager);
+ mContext.addMockSystemService(TelecomManager.class, mTelecomManager);
+ mContext.setMockPackageManager(mPackageManager);
+
+ mStopController = new MediaProjectionStopController(mContext, mStopConsumer);
+ mService = new MediaProjectionManagerService(mContext,
+ mMediaProjectionMetricsLoggerInjector);
+
+ mAppInfo.targetSdkVersion = 35;
+ }
+
+ private static AppOpsManager mockAppOpsManager() {
+ return mock(AppOpsManager.class, invocationOnMock -> {
+ if (invocationOnMock.getMethod().getName().startsWith("noteOp")) {
+ // Mockito will return 0 for non-stubbed method which corresponds to MODE_ALLOWED
+ // and is not what we want.
+ return AppOpsManager.MODE_IGNORED;
+ }
+ return Answers.RETURNS_DEFAULTS.answer(invocationOnMock);
+ });
+ }
+
+ @After
+ public void tearDown() {
+ LocalServices.removeServiceForTest(ActivityManagerInternal.class);
+ LocalServices.removeServiceForTest(WindowManagerInternal.class);
+ }
+
+ @Test
+ @EnableFlags(
+ android.companion.virtualdevice.flags.Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
+ public void testMediaProjectionNotRestricted() throws Exception {
+ when(mKeyguardManager.isKeyguardLocked()).thenReturn(false);
+
+ assertThat(mStopController.isStartForbidden(
+ createMediaProjection(PACKAGE_NAME))).isFalse();
+ }
+
+ @Test
+ @EnableFlags(
+ android.companion.virtualdevice.flags.Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
+ public void testMediaProjectionRestricted() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection();
+ mediaProjection.notifyVirtualDisplayCreated(1);
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ when(mKeyguardManager.isKeyguardLocked()).thenReturn(true);
+
+ assertThat(mStopController.isStartForbidden(mediaProjection)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingNullProjection() throws Exception {
+ assertThat(mStopController.isExemptFromStopping(null)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingInvalidProjection() throws Exception {
+ assertThat(mStopController.isExemptFromStopping(createMediaProjection(null))).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingDisableScreenshareProtections() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection();
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ int value = Settings.Global.getInt(mContext.getContentResolver(),
+ DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, 0);
+ try {
+ Settings.Global.putInt(mContext.getContentResolver(),
+ DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, 1);
+
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ } finally {
+ Settings.Global.putInt(mContext.getContentResolver(),
+ DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, value);
+ }
+ }
+
+ @Test
+ public void testExemptFromStoppingHasOpProjectMedia() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection();
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
+ .noteOpNoThrow(eq(AppOpsManager.OP_PROJECT_MEDIA),
+ eq(mediaProjection.uid), eq(mediaProjection.packageName),
+ nullable(String.class),
+ nullable(String.class));
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingHasAppStreamingRole() throws Exception {
+ runWithRole(
+ AssociationRequest.DEVICE_PROFILE_APP_STREAMING,
+ () -> {
+ try {
+ MediaProjectionManagerService.MediaProjection mediaProjection =
+ createMediaProjection();
+ doReturn(PackageManager.PERMISSION_DENIED).when(
+ mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+
+ @Test
+ public void testExemptFromStoppingIsBugreportAllowlisted() throws Exception {
+ ArraySet<String> packages = SystemConfig.getInstance().getBugreportWhitelistedPackages();
+ if (packages.isEmpty()) {
+ return;
+ }
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection(
+ packages.valueAt(0));
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingHasNoDisplay() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection(
+ PACKAGE_NAME);
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingHasRecordSensitiveContentPermission() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection();
+ doReturn(PackageManager.PERMISSION_GRANTED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isTrue();
+ }
+
+ @Test
+ public void testExemptFromStoppingIsFalse() throws Exception {
+ MediaProjectionManagerService.MediaProjection mediaProjection = createMediaProjection();
+ mediaProjection.notifyVirtualDisplayCreated(1);
+ doReturn(PackageManager.PERMISSION_DENIED).when(mPackageManager).checkPermission(
+ RECORD_SENSITIVE_CONTENT, mediaProjection.packageName);
+ assertThat(mStopController.isExemptFromStopping(mediaProjection)).isFalse();
+ }
+
+ @Test
+ @EnableFlags(
+ android.companion.virtualdevice.flags.Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
+ public void testKeyguardLockedStateChanged_unlocked() {
+ mStopController.onKeyguardLockedStateChanged(false);
+
+ verify(mStopConsumer, never()).accept(anyInt());
+ }
+
+ @Test
+ @EnableFlags(
+ android.companion.virtualdevice.flags.Flags.FLAG_MEDIA_PROJECTION_KEYGUARD_RESTRICTIONS)
+ public void testKeyguardLockedStateChanged_locked() {
+ mStopController.onKeyguardLockedStateChanged(true);
+
+ verify(mStopConsumer).accept(MediaProjectionStopController.STOP_REASON_KEYGUARD);
+ }
+
+ @Test
+ @EnableFlags(com.android.media.projection.flags.Flags.FLAG_STOP_MEDIA_PROJECTION_ON_CALL_END)
+ public void testCallStateChanged_callStarts() {
+ // Setup call state to false
+ when(mTelecomManager.isInCall()).thenReturn(false);
+ mStopController.callStateChanged();
+
+ clearInvocations(mStopConsumer);
+
+ when(mTelecomManager.isInCall()).thenReturn(true);
+ mStopController.callStateChanged();
+
+ verify(mStopConsumer, never()).accept(anyInt());
+ }
+
+ @Test
+ @EnableFlags(com.android.media.projection.flags.Flags.FLAG_STOP_MEDIA_PROJECTION_ON_CALL_END)
+ public void testCallStateChanged_remainsInCall() {
+ // Setup call state to false
+ when(mTelecomManager.isInCall()).thenReturn(true);
+ mStopController.callStateChanged();
+
+ clearInvocations(mStopConsumer);
+
+ when(mTelecomManager.isInCall()).thenReturn(true);
+ mStopController.callStateChanged();
+
+ verify(mStopConsumer, never()).accept(anyInt());
+ }
+
+ @Test
+ @EnableFlags(com.android.media.projection.flags.Flags.FLAG_STOP_MEDIA_PROJECTION_ON_CALL_END)
+ public void testCallStateChanged_remainsNoCall() {
+ // Setup call state to false
+ when(mTelecomManager.isInCall()).thenReturn(false);
+ mStopController.callStateChanged();
+
+ clearInvocations(mStopConsumer);
+
+ when(mTelecomManager.isInCall()).thenReturn(false);
+ mStopController.callStateChanged();
+
+ verify(mStopConsumer, never()).accept(anyInt());
+ }
+
+ @Test
+ @EnableFlags(com.android.media.projection.flags.Flags.FLAG_STOP_MEDIA_PROJECTION_ON_CALL_END)
+ public void testCallStateChanged_callEnds() {
+ // Setup call state to false
+ when(mTelecomManager.isInCall()).thenReturn(true);
+ mStopController.callStateChanged();
+
+ clearInvocations(mStopConsumer);
+
+ when(mTelecomManager.isInCall()).thenReturn(false);
+ mStopController.callStateChanged();
+
+ verify(mStopConsumer).accept(MediaProjectionStopController.STOP_REASON_CALL_END);
+ }
+
+ private MediaProjectionManagerService.MediaProjection createMediaProjection()
+ throws NameNotFoundException {
+ return createMediaProjection(PACKAGE_NAME);
+ }
+
+ private MediaProjectionManagerService.MediaProjection createMediaProjection(String packageName)
+ throws NameNotFoundException {
+ doReturn(mAppInfo).when(mPackageManager).getApplicationInfoAsUser(anyString(),
+ any(ApplicationInfoFlags.class), any(UserHandle.class));
+ doReturn(mAppInfo).when(mPackageManager).getApplicationInfoAsUser(Mockito.isNull(),
+ any(ApplicationInfoFlags.class), any(UserHandle.class));
+ return mService.createProjectionInternal(UID, packageName,
+ MediaProjectionManager.TYPE_SCREEN_CAPTURE, false, mContext.getUser(),
+ INVALID_DISPLAY);
+ }
+
+ /**
+ * Run the provided block giving the current context's package the provided role.
+ */
+ @SuppressWarnings("SameParameterValue")
+ private void runWithRole(String role, Runnable block) {
+ Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+ String packageName = mContext.getPackageName();
+ UserHandle user = instrumentation.getTargetContext().getUser();
+ RoleManager roleManager = Objects.requireNonNull(
+ mContext.getSystemService(RoleManager.class));
+ try {
+ CountDownLatch latch = new CountDownLatch(1);
+ instrumentation.getUiAutomation().adoptShellPermissionIdentity(
+ Manifest.permission.MANAGE_ROLE_HOLDERS,
+ Manifest.permission.BYPASS_ROLE_QUALIFICATION);
+
+ roleManager.setBypassingRoleQualification(true);
+ roleManager.addRoleHolderAsUser(role, packageName,
+ /* flags= */ RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, user,
+ mContext.getMainExecutor(), success -> {
+ if (success) {
+ latch.countDown();
+ } else {
+ Assert.fail("Couldn't set role for test (failure) " + role);
+ }
+ });
+ assertWithMessage("Couldn't set role for test (timeout) : " + role)
+ .that(latch.await(1, TimeUnit.SECONDS)).isTrue();
+ block.run();
+
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ } finally {
+ roleManager.removeRoleHolderAsUser(role, packageName,
+ /* flags= */ RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, user,
+ mContext.getMainExecutor(), (aBool) -> {
+ });
+ roleManager.setBypassingRoleQualification(false);
+ instrumentation.getUiAutomation()
+ .dropShellPermissionIdentity();
+ }
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/supervision/SupervisionServiceTest.kt b/services/tests/servicestests/src/com/android/server/supervision/SupervisionServiceTest.kt
index 79b06236..8290e1c 100644
--- a/services/tests/servicestests/src/com/android/server/supervision/SupervisionServiceTest.kt
+++ b/services/tests/servicestests/src/com/android/server/supervision/SupervisionServiceTest.kt
@@ -20,7 +20,7 @@
import android.content.ComponentName
import android.content.Context
import android.content.pm.UserInfo
-import android.os.Bundle
+import android.os.PersistableBundle
import android.platform.test.annotations.RequiresFlagsEnabled
import android.platform.test.flag.junit.DeviceFlagsValueProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -139,7 +139,7 @@
assertThat(userData.supervisionLockScreenEnabled).isFalse()
assertThat(userData.supervisionLockScreenOptions).isNull()
- service.mInternal.setSupervisionLockscreenEnabledForUser(USER_ID, true, Bundle())
+ service.mInternal.setSupervisionLockscreenEnabledForUser(USER_ID, true, PersistableBundle())
userData = service.getUserDataLocked(USER_ID)
assertThat(userData.supervisionLockScreenEnabled).isTrue()
assertThat(userData.supervisionLockScreenOptions).isNotNull()
diff --git a/services/tests/wmtests/res/xml/bookmarks.xml b/services/tests/wmtests/res/xml/bookmarks.xml
index 197b366..787f4e8 100644
--- a/services/tests/wmtests/res/xml/bookmarks.xml
+++ b/services/tests/wmtests/res/xml/bookmarks.xml
@@ -13,60 +13,70 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<bookmarks>
+<bookmarks xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
<!-- the key combinations for the following shortcuts must be in sync
with the key combinations sent by the test in ModifierShortcutTests.java -->
<bookmark
role="android.app.role.BROWSER"
- shortcut="b" />
+ androidprv:keycode="KEYCODE_B"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CONTACTS"
- shortcut="c" />
+ androidprv:keycode="KEYCODE_C"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_EMAIL"
- shortcut="e" />
+ androidprv:keycode="KEYCODE_E"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALENDAR"
- shortcut="k" />
+ androidprv:keycode="KEYCODE_K"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MAPS"
- shortcut="m" />
+ androidprv:keycode="KEYCODE_M"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MUSIC"
- shortcut="p" />
+ androidprv:keycode="KEYCODE_P"
+ androidprv:modifierState="META" />
<bookmark
role="android.app.role.SMS"
- shortcut="s" />
+ androidprv:keycode="KEYCODE_S"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALCULATOR"
- shortcut="u" />
+ androidprv:keycode="KEYCODE_U"
+ androidprv:modifierState="META" />
<bookmark
role="android.app.role.BROWSER"
- shortcut="b"
- shift="true" />
+ androidprv:keycode="KEYCODE_B"
+ androidprv:modifierState="META|SHIFT" />
<bookmark
category="android.intent.category.APP_CONTACTS"
- shortcut="c"
- shift="true" />
+ androidprv:keycode="KEYCODE_C"
+ androidprv:modifierState="META|SHIFT" />
<bookmark
package="com.test"
class="com.test.BookmarkTest"
- shortcut="j"
- shift="true" />
+ androidprv:keycode="KEYCODE_J"
+ androidprv:modifierState="META|SHIFT" />
<!-- The following shortcuts will not be invoked by tests but are here to
provide test coverage of parsing the different types of shortcut. -->
<bookmark
package="com.test"
class="com.test.BookmarkTest"
- shortcut="j" />
+ androidprv:keycode="KEYCODE_J"
+ androidprv:modifierState="META" />
<bookmark
package="com.test2"
class="com.test.BookmarkTest"
- shortcut="d" />
+ androidprv:keycode="KEYCODE_D"
+ androidprv:modifierState="META" />
<!-- It's intended that this package/class will NOT resolve so we test the resolution
@@ -74,6 +84,7 @@
<bookmark
package="com.test3"
class="com.test.BookmarkTest"
- shortcut="f" />
+ androidprv:keycode="KEYCODE_F"
+ androidprv:modifierState="META" />
</bookmarks>
diff --git a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutManagerTests.java b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutManagerTests.java
index 0575d98..82a5add 100644
--- a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutManagerTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutManagerTests.java
@@ -116,6 +116,7 @@
mModifierShortcutManager = new ModifierShortcutManager(
mContext, mHandler, UserHandle.SYSTEM);
+ mModifierShortcutManager.onSystemReady();
}
@Test
diff --git a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
index a51ce995..bc03c23 100644
--- a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
+++ b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
@@ -88,6 +88,7 @@
import android.telecom.TelecomManager;
import android.view.Display;
import android.view.InputEvent;
+import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.autofill.AutofillManagerInternal;
@@ -270,11 +271,15 @@
// Return mocked services: LocalServices.getService
mMockitoSession = mockitoSession()
.mockStatic(LocalServices.class, spyStubOnly)
+ .mockStatic(KeyCharacterMap.class)
.strictness(Strictness.LENIENT)
.startMocking();
mPhoneWindowManager = spy(new PhoneWindowManager());
+ KeyCharacterMap virtualKcm = mContext.getSystemService(InputManager.class)
+ .getInputDevice(KeyCharacterMap.VIRTUAL_KEYBOARD).getKeyCharacterMap();
+ doReturn(virtualKcm).when(() -> KeyCharacterMap.load(anyInt()));
doReturn(mWindowManagerInternal).when(
() -> LocalServices.getService(eq(WindowManagerInternal.class)));
doReturn(mActivityManagerInternal).when(
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
index 69fe7c9..817c368 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
@@ -123,6 +123,8 @@
* Build/Install/Run:
* atest WmTests:WindowOrganizerTests
*/
+
+// TODO revert parts of this set to set the flag to test the behavior
@SmallTest
@Presubmit
@RunWith(WindowTestRunner.class)
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
index b737d35..50e0e18 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
@@ -71,6 +71,7 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -84,12 +85,14 @@
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
+import android.content.ContentResolver;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Region;
+import android.os.Build;
import android.os.IBinder;
import android.os.InputConfig;
import android.os.RemoteException;
@@ -97,6 +100,7 @@
import android.platform.test.annotations.EnableFlags;
import android.platform.test.annotations.Presubmit;
import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.provider.Settings;
import android.util.ArraySet;
import android.util.MergedConfiguration;
import android.view.Gravity;
@@ -1557,6 +1561,57 @@
}
@Test
+ public void testIsSecureLocked_flagSecureSet() {
+ WindowState window = createWindow(null /* parent */, TYPE_APPLICATION, "test-window",
+ 1 /* ownerId */);
+ window.mAttrs.flags |= WindowManager.LayoutParams.FLAG_SECURE;
+
+ assertTrue(window.isSecureLocked());
+ }
+
+ @Test
+ public void testIsSecureLocked_flagSecureNotSet() {
+ WindowState window = createWindow(null /* parent */, TYPE_APPLICATION, "test-window",
+ 1 /* ownerId */);
+
+ assertFalse(window.isSecureLocked());
+ }
+
+ @Test
+ public void testIsSecureLocked_disableSecureWindows() {
+ assumeTrue(Build.IS_DEBUGGABLE);
+
+ WindowState window = createWindow(null /* parent */, TYPE_APPLICATION, "test-window",
+ 1 /* ownerId */);
+ window.mAttrs.flags |= WindowManager.LayoutParams.FLAG_SECURE;
+ ContentResolver cr = useFakeSettingsProvider();
+
+ // isSecureLocked should return false when DISABLE_SECURE_WINDOWS is set to 1
+ Settings.Secure.putString(cr, Settings.Secure.DISABLE_SECURE_WINDOWS, "1");
+ mWm.mSettingsObserver.onChange(false /* selfChange */,
+ Settings.Secure.getUriFor(Settings.Secure.DISABLE_SECURE_WINDOWS));
+ assertFalse(window.isSecureLocked());
+
+ // isSecureLocked should return true if DISABLE_SECURE_WINDOWS is set to 0.
+ Settings.Secure.putString(cr, Settings.Secure.DISABLE_SECURE_WINDOWS, "0");
+ mWm.mSettingsObserver.onChange(false /* selfChange */,
+ Settings.Secure.getUriFor(Settings.Secure.DISABLE_SECURE_WINDOWS));
+ assertTrue(window.isSecureLocked());
+
+ // Disable secure windows again.
+ Settings.Secure.putString(cr, Settings.Secure.DISABLE_SECURE_WINDOWS, "1");
+ mWm.mSettingsObserver.onChange(false /* selfChange */,
+ Settings.Secure.getUriFor(Settings.Secure.DISABLE_SECURE_WINDOWS));
+ assertFalse(window.isSecureLocked());
+
+ // isSecureLocked should return true if DISABLE_SECURE_WINDOWS is deleted.
+ Settings.Secure.putString(cr, Settings.Secure.DISABLE_SECURE_WINDOWS, null);
+ mWm.mSettingsObserver.onChange(false /* selfChange */,
+ Settings.Secure.getUriFor(Settings.Secure.DISABLE_SECURE_WINDOWS));
+ assertTrue(window.isSecureLocked());
+ }
+
+ @Test
@RequiresFlagsEnabled(FLAG_SENSITIVE_NOTIFICATION_APP_PROTECTION)
public void testIsSecureLocked_sensitiveContentProtectionManagerEnabled() {
String testPackage = "test";
diff --git a/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt b/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
index 9f5e6d1..2c998c4 100644
--- a/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
+++ b/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
@@ -16,6 +16,7 @@
package com.android.server.wm.flicker.helpers
+import android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM
import android.content.Context
import android.graphics.Insets
import android.graphics.Rect
@@ -74,13 +75,28 @@
.waitForAndVerify()
}
+ /** Launch an app and ensure it's moved to Desktop if it has not. */
+ fun enterDesktopMode(
+ wmHelper: WindowManagerStateHelper,
+ device: UiDevice,
+ motionEventHelper: MotionEventHelper = MotionEventHelper(getInstrumentation(), TOUCH),
+ ) {
+ innerHelper.launchViaIntent(wmHelper)
+ if (!isInDesktopWindowingMode(wmHelper)) {
+ enterDesktopModeWithDrag(
+ wmHelper = wmHelper,
+ device = device,
+ motionEventHelper = motionEventHelper
+ )
+ }
+ }
+
/** Move an app to Desktop by dragging the app handle at the top. */
- fun enterDesktopWithDrag(
+ fun enterDesktopModeWithDrag(
wmHelper: WindowManagerStateHelper,
device: UiDevice,
motionEventHelper: MotionEventHelper = MotionEventHelper(getInstrumentation(), TOUCH)
) {
- innerHelper.launchViaIntent(wmHelper)
dragToDesktop(
wmHelper = wmHelper,
device = device,
@@ -150,6 +166,25 @@
.waitForAndVerify()
}
+ private fun getHeaderEmptyView(caption: UiObject2?): UiObject2 {
+ return caption
+ ?.children
+ ?.find { it.resourceName.endsWith(HEADER_EMPTY_VIEW) }
+ ?: error("Unable to find resource $HEADER_EMPTY_VIEW\n")
+ }
+
+ /** Click on an existing window's header to bring it to the front. */
+ fun bringToFront(wmHelper: WindowManagerStateHelper, device: UiDevice) {
+ val caption = getCaptionForTheApp(wmHelper, device)
+ val openHeaderView = getHeaderEmptyView(caption)
+ openHeaderView.click()
+ wmHelper
+ .StateSyncBuilder()
+ .withAppTransitionIdle()
+ .withTopVisibleApp(innerHelper)
+ .waitForAndVerify()
+ }
+
/** Open maximize menu and click snap resize button on the app header for the given app. */
fun snapResizeDesktopApp(
wmHelper: WindowManagerStateHelper,
@@ -415,6 +450,10 @@
return metricInsets.getInsetsIgnoringVisibility(typeMask)
}
+ // Requirement of DesktopWindowingMode is having a minimum of 1 app in WINDOWING_MODE_FREEFORM.
+ private fun isInDesktopWindowingMode(wmHelper: WindowManagerStateHelper) =
+ wmHelper.getWindow(innerHelper)?.windowingMode == WINDOWING_MODE_FREEFORM
+
private companion object {
val TIMEOUT: Duration = Duration.ofSeconds(3)
const val SNAP_RESIZE_DRAG_INSET: Int = 5 // inset to avoid dragging to display edge
@@ -427,6 +466,7 @@
const val SNAP_LEFT_BUTTON: String = "maximize_menu_snap_left_button"
const val SNAP_RIGHT_BUTTON: String = "maximize_menu_snap_right_button"
const val MINIMIZE_BUTTON_VIEW: String = "minimize_window"
+ const val HEADER_EMPTY_VIEW: String = "caption_handle"
val caption: BySelector
get() = By.res(SYSTEMUI_PACKAGE, CAPTION)
}
diff --git a/tests/Input/res/xml/bookmarks.xml b/tests/Input/res/xml/bookmarks.xml
index ba3f187..a4c898d 100644
--- a/tests/Input/res/xml/bookmarks.xml
+++ b/tests/Input/res/xml/bookmarks.xml
@@ -14,47 +14,55 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
-<bookmarks>
+<bookmarks xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
<!-- the key combinations for the following shortcuts must be in sync
with the key combinations sent by the test in KeyGestureControllerTests.java -->
<bookmark
role="android.app.role.BROWSER"
- shortcut="b" />
+ androidprv:keycode="KEYCODE_B"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CONTACTS"
- shortcut="c" />
+ androidprv:keycode="KEYCODE_C"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_EMAIL"
- shortcut="e" />
+ androidprv:keycode="KEYCODE_E"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALENDAR"
- shortcut="k" />
+ androidprv:keycode="KEYCODE_K"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MAPS"
- shortcut="m" />
+ androidprv:keycode="KEYCODE_M"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_MUSIC"
- shortcut="p" />
+ androidprv:keycode="KEYCODE_P"
+ androidprv:modifierState="META" />
<bookmark
role="android.app.role.SMS"
- shortcut="s" />
+ androidprv:keycode="KEYCODE_S"
+ androidprv:modifierState="META" />
<bookmark
category="android.intent.category.APP_CALCULATOR"
- shortcut="u" />
+ androidprv:keycode="KEYCODE_U"
+ androidprv:modifierState="META" />
<bookmark
role="android.app.role.BROWSER"
- shortcut="b"
- shift="true" />
+ androidprv:keycode="KEYCODE_B"
+ androidprv:modifierState="META|SHIFT" />
<bookmark
category="android.intent.category.APP_CONTACTS"
- shortcut="c"
+ androidprv:keycode="KEYCODE_C"
shift="true" />
<bookmark
package="com.test"
class="com.test.BookmarkTest"
- shortcut="j"
+ androidprv:keycode="KEYCODE_J"
shift="true" />
</bookmarks>
\ No newline at end of file
diff --git a/tests/Input/res/xml/bookmarks_legacy.xml b/tests/Input/res/xml/bookmarks_legacy.xml
new file mode 100644
index 0000000..8bacf49
--- /dev/null
+++ b/tests/Input/res/xml/bookmarks_legacy.xml
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright 2024 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.
+ -->
+<bookmarks>
+ <!-- The key combinations for the following shortcuts are legacy way defining bookmarks and we
+ should prefer new way of defining bookmarks as shown in {@link bookmarks.xml} -->
+ <bookmark
+ role="android.app.role.BROWSER"
+ shortcut="b" />
+ <bookmark
+ category="android.intent.category.APP_CONTACTS"
+ shortcut="c" />
+ <bookmark
+ category="android.intent.category.APP_EMAIL"
+ shortcut="e" />
+ <bookmark
+ category="android.intent.category.APP_CALENDAR"
+ shortcut="k" />
+ <bookmark
+ category="android.intent.category.APP_MAPS"
+ shortcut="m" />
+ <bookmark
+ category="android.intent.category.APP_MUSIC"
+ shortcut="p" />
+ <bookmark
+ role="android.app.role.SMS"
+ shortcut="s" />
+ <bookmark
+ category="android.intent.category.APP_CALCULATOR"
+ shortcut="u" />
+
+ <bookmark
+ role="android.app.role.BROWSER"
+ shortcut="b"
+ shift="true" />
+
+ <bookmark
+ category="android.intent.category.APP_CONTACTS"
+ shortcut="c"
+ shift="true" />
+
+ <bookmark
+ package="com.test"
+ class="com.test.BookmarkTest"
+ shortcut="j"
+ shift="true" />
+</bookmarks>
\ No newline at end of file
diff --git a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
index 09a686c..d1f8668 100644
--- a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
@@ -115,13 +115,11 @@
private lateinit var iInputManager: IInputManager
@Mock
- private lateinit var resources: Resources
-
- @Mock
private lateinit var packageManager: PackageManager
private var currentPid = 0
private lateinit var context: Context
+ private lateinit var resources: Resources
private lateinit var keyGestureController: KeyGestureController
private lateinit var inputManagerGlobalSession: InputManagerGlobal.TestSession
private lateinit var testLooper: TestLooper
@@ -130,6 +128,7 @@
@Before
fun setup() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
+ resources = Mockito.spy(context.resources)
setupInputDevices()
setupBehaviors()
testLooper = TestLooper()
@@ -146,10 +145,6 @@
private fun setupBehaviors() {
Mockito.`when`(SystemProperties.get("ro.debuggable")).thenReturn("1")
Mockito.`when`(resources.getBoolean(R.bool.config_enableScreenshotChord)).thenReturn(true)
- val testBookmarks: XmlResourceParser = context.resources.getXml(
- com.android.test.input.R.xml.bookmarks
- )
- Mockito.`when`(resources.getXml(R.xml.bookmarks)).thenReturn(testBookmarks)
Mockito.`when`(context.resources).thenReturn(resources)
Mockito.`when`(packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))
.thenReturn(true)
@@ -158,6 +153,11 @@
Mockito.`when`(context.packageManager).thenReturn(packageManager)
}
+ private fun setupBookmarks(bookmarkRes: Int) {
+ val testBookmarks: XmlResourceParser = context.resources.getXml(bookmarkRes)
+ Mockito.`when`(resources.getXml(R.xml.bookmarks)).thenReturn(testBookmarks)
+ }
+
private fun setupInputDevices() {
val correctIm = context.getSystemService(InputManager::class.java)!!
val virtualDevice = correctIm.getInputDevice(KeyCharacterMap.VIRTUAL_KEYBOARD)!!
@@ -604,45 +604,6 @@
AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
),
TestData(
- "META + SHIFT + B -> Launch Default Browser",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_B
- ),
- KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
- intArrayOf(KeyEvent.KEYCODE_B),
- KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
- ),
- TestData(
- "META + SHIFT + C -> Launch Default Contacts",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_C
- ),
- KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
- intArrayOf(KeyEvent.KEYCODE_C),
- KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
- ),
- TestData(
- "META + SHIFT + J -> Launch Target Activity",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_J
- ),
- KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
- intArrayOf(KeyEvent.KEYCODE_J),
- KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest")
- ),
- TestData(
"META + CTRL + DEL -> Trigger Bug Report",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
@@ -866,6 +827,139 @@
}
@Keep
+ private fun bookmarkArguments(): Array<TestData> {
+ return arrayOf(
+ TestData(
+ "META + B -> Launch Default Browser",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_B),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_B),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ ),
+ TestData(
+ "META + C -> Launch Default Contacts",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_C),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_C),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ ),
+ TestData(
+ "META + E -> Launch Default Email",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_E),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_E),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL)
+ ),
+ TestData(
+ "META + K -> Launch Default Calendar",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_K),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_K),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR)
+ ),
+ TestData(
+ "META + M -> Launch Default Maps",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_M),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_M),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS)
+ ),
+ TestData(
+ "META + P -> Launch Default Music",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_P),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_P),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MUSIC)
+ ),
+ TestData(
+ "META + S -> Launch Default SMS",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_S),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_S),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_SMS)
+ ),
+ TestData(
+ "META + U -> Launch Default Calculator",
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_U),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_U),
+ KeyEvent.META_META_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
+ ),
+ TestData(
+ "META + SHIFT + B -> Launch Default Browser",
+ intArrayOf(
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ KeyEvent.KEYCODE_B
+ ),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_B),
+ KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ ),
+ TestData(
+ "META + SHIFT + C -> Launch Default Contacts",
+ intArrayOf(
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ KeyEvent.KEYCODE_C
+ ),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_C),
+ KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ ),
+ TestData(
+ "META + SHIFT + J -> Launch Target Activity",
+ intArrayOf(
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ KeyEvent.KEYCODE_J
+ ),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
+ intArrayOf(KeyEvent.KEYCODE_J),
+ KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest")
+ )
+ )
+ }
+
+ @Test
+ @Parameters(method = "bookmarkArguments")
+ fun testBookmarks(test: TestData) {
+ setupBookmarks(com.android.test.input.R.xml.bookmarks)
+ setupKeyGestureController()
+ testKeyGestureInternal(test)
+ }
+
+ @Test
+ @Parameters(method = "bookmarkArguments")
+ fun testBookmarksLegacy(test: TestData) {
+ setupBookmarks(com.android.test.input.R.xml.bookmarks_legacy)
+ setupKeyGestureController()
+ testKeyGestureInternal(test)
+ }
+
+ @Keep
private fun systemKeysTestArguments(): Array<TestData> {
return arrayOf(
TestData(
diff --git a/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java b/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
index 2692e12..44641f7 100644
--- a/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
+++ b/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
@@ -24,6 +24,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -57,6 +58,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
+import org.mockito.stubbing.Answer;
import perfetto.protos.Protolog;
import perfetto.protos.ProtologCommon;
@@ -858,6 +860,39 @@
.isEqualTo("This message should also be logged 567");
}
+ @Test
+ public void enablesLogGroupAfterLoadingConfig() {
+ sProtoLog.stopLoggingToLogcat(
+ new String[] { TestProtoLogGroup.TEST_GROUP.name() }, (msg) -> {});
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isFalse();
+
+ doAnswer((Answer<Void>) invocation -> {
+ // logToLogcat is still false before we laod the viewer config
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isFalse();
+ return null;
+ }).when(sReader).unloadViewerConfig(any(), any());
+
+ sProtoLog.startLoggingToLogcat(
+ new String[] { TestProtoLogGroup.TEST_GROUP.name() }, (msg) -> {});
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isTrue();
+ }
+
+ @Test
+ public void disablesLogGroupBeforeUnloadingConfig() {
+ sProtoLog.startLoggingToLogcat(
+ new String[] { TestProtoLogGroup.TEST_GROUP.name() }, (msg) -> {});
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isTrue();
+
+ doAnswer((Answer<Void>) invocation -> {
+ // Already set logToLogcat to false by the time we unload the config
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isFalse();
+ return null;
+ }).when(sReader).unloadViewerConfig(any(), any());
+ sProtoLog.stopLoggingToLogcat(
+ new String[] { TestProtoLogGroup.TEST_GROUP.name() }, (msg) -> {});
+ Truth.assertThat(TestProtoLogGroup.TEST_GROUP.isLogToLogcat()).isFalse();
+ }
+
private enum TestProtoLogGroup implements IProtoLogGroup {
TEST_GROUP(true, true, false, "TEST_TAG");