Merge "Move multivalent test targets to multivalentTests dir" into main
diff --git a/AconfigFlags.bp b/AconfigFlags.bp
index 2047168..eed248b 100644
--- a/AconfigFlags.bp
+++ b/AconfigFlags.bp
@@ -310,6 +310,8 @@
aconfig_declarations {
name: "android.os.flags-aconfig",
package: "android.os",
+ exportable: true,
+ container: "system",
srcs: ["core/java/android/os/*.aconfig"],
}
@@ -326,6 +328,13 @@
defaults: ["framework-minus-apex-aconfig-java-defaults"],
}
+java_aconfig_library {
+ name: "android.os.flags-aconfig-java-export",
+ aconfig_declarations: "android.os.flags-aconfig",
+ defaults: ["framework-minus-apex-aconfig-java-defaults"],
+ mode: "exported",
+}
+
// VirtualDeviceManager
cc_aconfig_library {
name: "android.companion.virtualdevice.flags-aconfig-cc",
diff --git a/apex/jobscheduler/service/aconfig/alarm.aconfig b/apex/jobscheduler/service/aconfig/alarm.aconfig
index 3b9b4e7..bb0f3cb 100644
--- a/apex/jobscheduler/service/aconfig/alarm.aconfig
+++ b/apex/jobscheduler/service/aconfig/alarm.aconfig
@@ -9,3 +9,10 @@
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "start_user_before_scheduled_alarms"
+ namespace: "multiuser"
+ description: "Persist list of users with alarms scheduled and wakeup stopped users before alarms are due"
+ bug: "314907186"
+}
diff --git a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
index e728a2c..d0a1b02 100644
--- a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
+++ b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
@@ -183,6 +183,9 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.time.zone.ZoneOffsetTransition;
+import java.time.zone.ZoneRules;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
@@ -194,6 +197,7 @@
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
/**
@@ -234,8 +238,12 @@
private static final long TEMPORARY_QUOTA_DURATION = INTERVAL_DAY;
- // System property read on some device configurations to initialize time properly.
+ // System properties read on some device configurations to initialize time properly and
+ // perform DST transitions at the bootloader level.
private static final String TIMEOFFSET_PROPERTY = "persist.sys.time.offset";
+ private static final String DST_TRANSITION_PROPERTY = "persist.sys.time.dst_transition";
+ private static final String DST_OFFSET_PROPERTY = "persist.sys.time.dst_offset";
+
private final Intent mBackgroundIntent
= new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
@@ -2200,6 +2208,19 @@
final int gmtOffset = newZone.getOffset(mInjector.getCurrentTimeMillis());
SystemProperties.set(TIMEOFFSET_PROPERTY, String.valueOf(gmtOffset));
+
+ final ZoneRules rules = newZone.toZoneId().getRules();
+ final ZoneOffsetTransition transition = rules.nextTransition(Instant.now());
+ if (null != transition) {
+ // Get the offset between the time after the DST transition and before.
+ final long transitionOffset = TimeUnit.SECONDS.toMillis((
+ transition.getOffsetAfter().getTotalSeconds()
+ - transition.getOffsetBefore().getTotalSeconds()));
+ // Time when the next DST transition is programmed.
+ final long nextTransition = TimeUnit.SECONDS.toMillis(transition.toEpochSecond());
+ SystemProperties.set(DST_TRANSITION_PROPERTY, String.valueOf(nextTransition));
+ SystemProperties.set(DST_OFFSET_PROPERTY, String.valueOf(transitionOffset));
+ }
}
// Clear the default time zone in the system server process. This forces the next call
diff --git a/api/StubLibraries.bp b/api/StubLibraries.bp
index 1f5b83c..c1add03 100644
--- a/api/StubLibraries.bp
+++ b/api/StubLibraries.bp
@@ -458,13 +458,21 @@
libs: ["stub-annotations"],
}
+java_defaults {
+ name: "android-non-updatable_everything_from_text_defaults",
+ defaults: [
+ "android-non-updatable_from_text_defaults",
+ ],
+ stubs_type: "everything",
+}
+
java_api_library {
name: "android-non-updatable.stubs.from-text",
api_surface: "public",
api_contributions: [
"api-stubs-docs-non-updatable.api.contribution",
],
- defaults: ["android-non-updatable_from_text_defaults"],
+ defaults: ["android-non-updatable_everything_from_text_defaults"],
full_api_surface_stub: "android_stubs_current.from-text",
}
@@ -475,7 +483,7 @@
"api-stubs-docs-non-updatable.api.contribution",
"system-api-stubs-docs-non-updatable.api.contribution",
],
- defaults: ["android-non-updatable_from_text_defaults"],
+ defaults: ["android-non-updatable_everything_from_text_defaults"],
full_api_surface_stub: "android_system_stubs_current.from-text",
}
@@ -487,7 +495,7 @@
"system-api-stubs-docs-non-updatable.api.contribution",
"test-api-stubs-docs-non-updatable.api.contribution",
],
- defaults: ["android-non-updatable_from_text_defaults"],
+ defaults: ["android-non-updatable_everything_from_text_defaults"],
full_api_surface_stub: "android_test_stubs_current.from-text",
}
@@ -499,7 +507,7 @@
"system-api-stubs-docs-non-updatable.api.contribution",
"module-lib-api-stubs-docs-non-updatable.api.contribution",
],
- defaults: ["android-non-updatable_from_text_defaults"],
+ defaults: ["android-non-updatable_everything_from_text_defaults"],
full_api_surface_stub: "android_module_lib_stubs_current_full.from-text",
}
@@ -515,7 +523,7 @@
"test-api-stubs-docs-non-updatable.api.contribution",
"module-lib-api-stubs-docs-non-updatable.api.contribution",
],
- defaults: ["android-non-updatable_from_text_defaults"],
+ defaults: ["android-non-updatable_everything_from_text_defaults"],
full_api_surface_stub: "android_test_module_lib_stubs_current.from-text",
// This module is only used for hiddenapi, and other modules should not
@@ -836,6 +844,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -852,6 +861,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -870,6 +880,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -888,6 +899,7 @@
"system-api-stubs-docs-non-updatable.api.contribution",
],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -908,6 +920,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -922,6 +935,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -947,6 +961,7 @@
"//visibility:private",
],
enable_validation: false,
+ stubs_type: "everything",
}
java_api_library {
@@ -964,6 +979,7 @@
],
visibility: ["//visibility:public"],
enable_validation: false,
+ stubs_type: "everything",
}
////////////////////////////////////////////////////////////////////////
diff --git a/core/api/current.txt b/core/api/current.txt
index ac98a94..b4c3f44 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -691,7 +691,6 @@
field public static final int defaultHeight = 16844021; // 0x10104f5
field @FlaggedApi("android.content.res.default_locale") public static final int defaultLocale;
field public static final int defaultToDeviceProtectedStorage = 16844036; // 0x1010504
- field @FlaggedApi("android.nfc.Flags.FLAG_OBSERVE_MODE") public static final int defaultToObserveMode;
field public static final int defaultValue = 16843245; // 0x10101ed
field public static final int defaultWidth = 16844020; // 0x10104f4
field public static final int delay = 16843212; // 0x10101cc
@@ -1501,6 +1500,7 @@
field public static final int shortcutId = 16844072; // 0x1010528
field public static final int shortcutLongLabel = 16844074; // 0x101052a
field public static final int shortcutShortLabel = 16844073; // 0x1010529
+ field @FlaggedApi("android.nfc.Flags.FLAG_OBSERVE_MODE") public static final int shouldDefaultToObserveMode;
field public static final int shouldDisableView = 16843246; // 0x10101ee
field public static final int shouldUseDefaultUnfoldTransition = 16844364; // 0x101064c
field public static final int showAsAction = 16843481; // 0x10102d9
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 67ccd9d..1718452 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -10418,7 +10418,6 @@
@FlaggedApi("android.nfc.enable_nfc_mainline") public final class ApduServiceInfo implements android.os.Parcelable {
ctor @FlaggedApi("android.nfc.enable_nfc_mainline") public ApduServiceInfo(@NonNull android.content.pm.PackageManager, @NonNull android.content.pm.ResolveInfo, boolean) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
method @FlaggedApi("android.nfc.nfc_read_polling_loop") public void addPollingLoopFilter(@NonNull String, boolean);
- method @FlaggedApi("android.nfc.nfc_observe_mode") public boolean defaultToObserveMode();
method @FlaggedApi("android.nfc.enable_nfc_mainline") public int describeContents();
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dump(@NonNull android.os.ParcelFileDescriptor, @NonNull java.io.PrintWriter, @NonNull String[]);
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dumpDebug(@NonNull android.util.proto.ProtoOutputStream);
@@ -10448,9 +10447,10 @@
method @FlaggedApi("android.nfc.enable_nfc_mainline") public boolean requiresUnlock();
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void resetOffHostSecureElement();
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setCategoryOtherServiceEnabled(boolean);
- method @FlaggedApi("android.nfc.nfc_observe_mode") public void setDefaultToObserveMode(boolean);
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setDynamicAidGroup(@NonNull android.nfc.cardemulation.AidGroup);
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setOffHostSecureElement(@NonNull String);
+ method @FlaggedApi("android.nfc.nfc_observe_mode") public void setShouldDefaultToObserveMode(boolean);
+ method @FlaggedApi("android.nfc.nfc_observe_mode") public boolean shouldDefaultToObserveMode();
method @FlaggedApi("android.nfc.enable_nfc_mainline") public void writeToParcel(@NonNull android.os.Parcel, int);
field @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public static final android.os.Parcelable.Creator<android.nfc.cardemulation.ApduServiceInfo> CREATOR;
}
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index b8c32a4..af40c3d 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -317,9 +317,6 @@
}
public class ComponentOptions {
- field public static final int MODE_BACKGROUND_ACTIVITY_START_ALLOWED = 1; // 0x1
- field public static final int MODE_BACKGROUND_ACTIVITY_START_DENIED = 2; // 0x2
- field public static final int MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED = 0; // 0x0
}
public class DownloadManager {
@@ -2034,41 +2031,6 @@
method public android.media.PlaybackParams setAudioStretchMode(int);
}
- @FlaggedApi("android.os.vibrator.haptics_customization_enabled") public final class RingtoneSelection {
- method @NonNull public static android.media.RingtoneSelection fromUri(@Nullable android.net.Uri, int);
- method public int getSoundSource();
- method @Nullable public android.net.Uri getSoundUri();
- method public int getVibrationSource();
- method @Nullable public android.net.Uri getVibrationUri();
- method public static boolean isRingtoneSelectionUri(@Nullable android.net.Uri);
- method @NonNull public android.net.Uri toUri();
- field public static final String DEFAULT_SELECTION_URI_STRING = "content://media/ringtone";
- field public static final int FROM_URI_RINGTONE_SELECTION_ONLY = 3; // 0x3
- field public static final int FROM_URI_RINGTONE_SELECTION_OR_SOUND = 1; // 0x1
- field public static final int FROM_URI_RINGTONE_SELECTION_OR_VIBRATION = 2; // 0x2
- field public static final int SOUND_SOURCE_OFF = 1; // 0x1
- field public static final int SOUND_SOURCE_SYSTEM_DEFAULT = 3; // 0x3
- field public static final int SOUND_SOURCE_UNSPECIFIED = 0; // 0x0
- field public static final int SOUND_SOURCE_URI = 2; // 0x2
- field public static final int VIBRATION_SOURCE_APPLICATION_DEFAULT = 4; // 0x4
- field public static final int VIBRATION_SOURCE_AUDIO_CHANNEL = 10; // 0xa
- field public static final int VIBRATION_SOURCE_HAPTIC_GENERATOR = 11; // 0xb
- field public static final int VIBRATION_SOURCE_OFF = 1; // 0x1
- field public static final int VIBRATION_SOURCE_SYSTEM_DEFAULT = 3; // 0x3
- field public static final int VIBRATION_SOURCE_UNSPECIFIED = 0; // 0x0
- field public static final int VIBRATION_SOURCE_URI = 2; // 0x2
- }
-
- @FlaggedApi("android.os.vibrator.haptics_customization_enabled") public static final class RingtoneSelection.Builder {
- ctor public RingtoneSelection.Builder();
- ctor public RingtoneSelection.Builder(@NonNull android.media.RingtoneSelection);
- method @NonNull public android.media.RingtoneSelection build();
- method @NonNull public android.media.RingtoneSelection.Builder setSoundSource(int);
- method @NonNull public android.media.RingtoneSelection.Builder setSoundSource(@NonNull android.net.Uri);
- method @NonNull public android.media.RingtoneSelection.Builder setVibrationSource(int);
- method @NonNull public android.media.RingtoneSelection.Builder setVibrationSource(@NonNull android.net.Uri);
- }
-
public static final class VolumeShaper.Configuration.Builder {
method @NonNull public android.media.VolumeShaper.Configuration.Builder setOptionFlags(int);
}
diff --git a/core/api/test-lint-baseline.txt b/core/api/test-lint-baseline.txt
index 658ddbf..685ea63 100644
--- a/core/api/test-lint-baseline.txt
+++ b/core/api/test-lint-baseline.txt
@@ -2055,14 +2055,8 @@
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.SOUND_SOURCE_DEFAULT
UnflaggedApi: android.media.RingtoneSelection#SOUND_SOURCE_OFF:
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.SOUND_SOURCE_OFF
-UnflaggedApi: android.media.RingtoneSelection#SOUND_SOURCE_SYSTEM_DEFAULT:
- New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.SOUND_SOURCE_SYSTEM_DEFAULT
-UnflaggedApi: android.media.RingtoneSelection#SOUND_SOURCE_UNSPECIFIED:
- New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.SOUND_SOURCE_UNSPECIFIED
UnflaggedApi: android.media.RingtoneSelection#SOUND_SOURCE_URI:
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.SOUND_SOURCE_URI
-UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_APPLICATION_DEFAULT:
- New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_APPLICATION_DEFAULT
UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_APPLICATION_PROVIDED:
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_APPLICATION_PROVIDED
UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_AUDIO_CHANNEL:
@@ -2073,10 +2067,6 @@
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_HAPTIC_GENERATOR
UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_OFF:
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_OFF
-UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_SYSTEM_DEFAULT:
- New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_SYSTEM_DEFAULT
-UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_UNSPECIFIED:
- New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_UNSPECIFIED
UnflaggedApi: android.media.RingtoneSelection#VIBRATION_SOURCE_URI:
New API must be flagged with @FlaggedApi: field android.media.RingtoneSelection.VIBRATION_SOURCE_URI
UnflaggedApi: android.media.RingtoneSelection#fromUri(android.net.Uri, int):
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 57c67be..63cafdc 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -9601,9 +9601,9 @@
* Specifies whether the activities below this one in the task can also start other activities
* or finish the task.
* <p>
- * Starting from Target SDK Level {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, apps
- * are blocked from starting new activities or finishing their task unless the top activity of
- * such task belong to the same UID for security reasons.
+ * Starting from Target SDK Level {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, apps
+ * may be blocked from starting new activities or finishing their task unless the top activity
+ * of such task belong to the same UID for security reasons.
* <p>
* Setting this flag to {@code true} will allow the launching app to ignore the restriction if
* this activity is on top. Apps matching the UID of this activity are always exempt.
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index 2a2c5f0..e094ac6 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -93,15 +93,30 @@
*/
public static final String EXTRA_USAGE_TIME_REPORT_PACKAGES = "android.usage_time_packages";
- /** No explicit value chosen. The system will decide whether to grant privileges. */
- public static final int MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED =
- ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED;
- /** Allow the {@link PendingIntent} to use the background activity start privileges. */
- public static final int MODE_BACKGROUND_ACTIVITY_START_ALLOWED =
- ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED;
- /** Deny the {@link PendingIntent} to use the background activity start privileges. */
- public static final int MODE_BACKGROUND_ACTIVITY_START_DENIED =
- ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED;
+ /** Enumeration of background activity start modes.
+ *
+ * These define if an app wants to grant it's background activity start privileges to a
+ * {@link PendingIntent}.
+ * @hide
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"MODE_BACKGROUND_ACTIVITY_START_"}, value = {
+ MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED,
+ MODE_BACKGROUND_ACTIVITY_START_ALLOWED,
+ MODE_BACKGROUND_ACTIVITY_START_DENIED})
+ public @interface BackgroundActivityStartMode {}
+ /**
+ * No explicit value chosen. The system will decide whether to grant privileges.
+ */
+ public static final int MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED = 0;
+ /**
+ * Allow the {@link PendingIntent} to use the background activity start privileges.
+ */
+ public static final int MODE_BACKGROUND_ACTIVITY_START_ALLOWED = 1;
+ /**
+ * Deny the {@link PendingIntent} to use the background activity start privileges.
+ */
+ public static final int MODE_BACKGROUND_ACTIVITY_START_DENIED = 2;
/**
* The package name that created the options.
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index 6ad0313..f6ec370 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -705,7 +705,15 @@
}
/**
- * Sets the component (service or activity) that owns this rule.
+ * Sets the component name of the
+ * {@link android.service.notification.ConditionProviderService} that manages this rule
+ * (but note that {@link android.service.notification.ConditionProviderService} is
+ * deprecated in favor of using {@link NotificationManager#setAutomaticZenRuleState} to
+ * notify the system about the state of your rule).
+ *
+ * <p>This is exclusive with {@link #setConfigurationActivity}; rules where a configuration
+ * activity is set will not use the component set here to determine whether the rule
+ * should be active.
*/
public @NonNull Builder setOwner(@Nullable ComponentName owner) {
mOwner = owner;
@@ -743,6 +751,11 @@
* information about this rule and/or allows them to configure it. This is required to be
* non-null for rules that are not backed by a
* {@link android.service.notification.ConditionProviderService}.
+ *
+ * <p>This is exclusive with {@link #setOwner}; rules where a configuration
+ * activity is set will not use the
+ * {@link android.service.notification.ConditionProviderService} supplied there to determine
+ * whether the rule should be active.
*/
public @NonNull Builder setConfigurationActivity(
@Nullable ComponentName configurationActivity) {
diff --git a/core/java/android/app/BroadcastOptions.java b/core/java/android/app/BroadcastOptions.java
index 1b5b0fc..60d622d 100644
--- a/core/java/android/app/BroadcastOptions.java
+++ b/core/java/android/app/BroadcastOptions.java
@@ -16,6 +16,8 @@
package android.app;
+import static android.app.ActivityOptions.BackgroundActivityStartMode;
+
import android.annotation.CurrentTimeMillisLong;
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
@@ -1132,7 +1134,8 @@
@SystemApi
@NonNull
@Override // to narrow down the return type
- public BroadcastOptions setPendingIntentBackgroundActivityStartMode(int state) {
+ public BroadcastOptions setPendingIntentBackgroundActivityStartMode(
+ @BackgroundActivityStartMode int state) {
super.setPendingIntentBackgroundActivityStartMode(state);
return this;
}
diff --git a/core/java/android/app/ComponentOptions.java b/core/java/android/app/ComponentOptions.java
index ce16ddf..397477d 100644
--- a/core/java/android/app/ComponentOptions.java
+++ b/core/java/android/app/ComponentOptions.java
@@ -16,16 +16,17 @@
package android.app;
-import android.annotation.IntDef;
+import static android.app.ActivityOptions.BackgroundActivityStartMode;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.annotation.TestApi;
import android.os.Bundle;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
/**
* Base class for {@link ActivityOptions} and {@link BroadcastOptions}.
* @hide
@@ -56,32 +57,6 @@
private @Nullable Boolean mPendingIntentBalAllowed = null;
private boolean mPendingIntentBalAllowedByPermission = false;
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"MODE_BACKGROUND_ACTIVITY_START_"}, value = {
- MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED,
- MODE_BACKGROUND_ACTIVITY_START_ALLOWED,
- MODE_BACKGROUND_ACTIVITY_START_DENIED})
- public @interface BackgroundActivityStartMode {}
- /**
- * No explicit value chosen. The system will decide whether to grant privileges.
- * @hide
- */
- @TestApi
- public static final int MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED = 0;
- /**
- * Allow the {@link PendingIntent} to use the background activity start privileges.
- * @hide
- */
- @TestApi
- public static final int MODE_BACKGROUND_ACTIVITY_START_ALLOWED = 1;
- /**
- * Deny the {@link PendingIntent} to use the background activity start privileges.
- * @hide
- */
- @TestApi
- public static final int MODE_BACKGROUND_ACTIVITY_START_DENIED = 2;
-
ComponentOptions() {
}
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 083705b..b25ebf6 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -14071,7 +14071,7 @@
public void setAuditLogEnabled(boolean enabled) {
throwIfParentInstance("setAuditLogEnabled");
try {
- mService.setAuditLogEnabled(mContext.getPackageName(), true);
+ mService.setAuditLogEnabled(mContext.getPackageName(), enabled);
} catch (RemoteException re) {
re.rethrowFromSystemServer();
}
diff --git a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
index 48ea846..6317725 100644
--- a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
+++ b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
@@ -40,6 +40,7 @@
public class ActivityConfigurationChangeItem extends ActivityTransactionItem {
private Configuration mConfiguration;
+ private ActivityWindowInfo mActivityWindowInfo;
@Override
public void preExecute(@NonNull ClientTransactionHandler client) {
@@ -55,8 +56,7 @@
// TODO(lifecycler): detect if PIP or multi-window mode changed and report it here.
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");
client.handleActivityConfigurationChanged(r, mConfiguration, INVALID_DISPLAY,
- // TODO(b/287582673): add ActivityWindowInfo
- new ActivityWindowInfo());
+ mActivityWindowInfo);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
@@ -73,7 +73,7 @@
/** Obtain an instance initialized with provided params. */
@NonNull
public static ActivityConfigurationChangeItem obtain(@NonNull IBinder activityToken,
- @NonNull Configuration config) {
+ @NonNull Configuration config, @NonNull ActivityWindowInfo activityWindowInfo) {
ActivityConfigurationChangeItem instance =
ObjectPool.obtain(ActivityConfigurationChangeItem.class);
if (instance == null) {
@@ -81,6 +81,7 @@
}
instance.setActivityToken(activityToken);
instance.mConfiguration = new Configuration(config);
+ instance.mActivityWindowInfo = new ActivityWindowInfo(activityWindowInfo);
return instance;
}
@@ -89,6 +90,7 @@
public void recycle() {
super.recycle();
mConfiguration = null;
+ mActivityWindowInfo = null;
ObjectPool.recycle(this);
}
@@ -100,12 +102,14 @@
public void writeToParcel(@NonNull Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeTypedObject(mConfiguration, flags);
+ dest.writeTypedObject(mActivityWindowInfo, flags);
}
/** Read from Parcel. */
private ActivityConfigurationChangeItem(@NonNull Parcel in) {
super(in);
mConfiguration = in.readTypedObject(Configuration.CREATOR);
+ mActivityWindowInfo = in.readTypedObject(ActivityWindowInfo.CREATOR);
}
public static final @NonNull Creator<ActivityConfigurationChangeItem> CREATOR =
@@ -128,7 +132,8 @@
return false;
}
final ActivityConfigurationChangeItem other = (ActivityConfigurationChangeItem) o;
- return Objects.equals(mConfiguration, other.mConfiguration);
+ return Objects.equals(mConfiguration, other.mConfiguration)
+ && Objects.equals(mActivityWindowInfo, other.mActivityWindowInfo);
}
@Override
@@ -136,12 +141,14 @@
int result = 17;
result = 31 * result + super.hashCode();
result = 31 * result + Objects.hashCode(mConfiguration);
+ result = 31 * result + Objects.hashCode(mActivityWindowInfo);
return result;
}
@Override
public String toString() {
return "ActivityConfigurationChange{" + super.toString()
- + ",config=" + mConfiguration + "}";
+ + ",config=" + mConfiguration
+ + ",activityWindowInfo=" + mActivityWindowInfo + "}";
}
}
diff --git a/core/java/android/database/sqlite/SQLiteConnection.java b/core/java/android/database/sqlite/SQLiteConnection.java
index ecffe9e..faa2c70 100644
--- a/core/java/android/database/sqlite/SQLiteConnection.java
+++ b/core/java/android/database/sqlite/SQLiteConnection.java
@@ -392,8 +392,6 @@
return;
}
- Log.i(TAG, walFile.getAbsolutePath() + " " + size + " bytes: Bigger than "
- + threshold + "; truncating");
try {
executeForString("PRAGMA wal_checkpoint(TRUNCATE)", null, null);
mConfiguration.shouldTruncateWalFile = false;
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index 5dfeac7..d683d72 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -40,15 +40,12 @@
import android.os.OperationCanceledException;
import android.os.SystemProperties;
import android.text.TextUtils;
-import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.EventLog;
import android.util.Log;
import android.util.Pair;
import android.util.Printer;
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
import dalvik.annotation.optimization.NeverCompile;
@@ -106,14 +103,8 @@
// Stores reference to all databases opened in the current process.
// (The referent Object is not used at this time.)
// INVARIANT: Guarded by sActiveDatabases.
- @GuardedBy("sActiveDatabases")
private static WeakHashMap<SQLiteDatabase, Object> sActiveDatabases = new WeakHashMap<>();
- // Tracks which database files are currently open. If a database file is opened more than
- // once at any given moment, the associated databases are marked as "concurrent".
- @GuardedBy("sActiveDatabases")
- private static final OpenTracker sOpenTracker = new OpenTracker();
-
// Thread-local for database sessions that belong to this database.
// Each thread has its own database session.
// INVARIANT: Immutable.
@@ -519,7 +510,6 @@
private void dispose(boolean finalized) {
final SQLiteConnectionPool pool;
- final String path;
synchronized (mLock) {
if (mCloseGuardLocked != null) {
if (finalized) {
@@ -530,12 +520,10 @@
pool = mConnectionPoolLocked;
mConnectionPoolLocked = null;
- path = isInMemoryDatabase() ? null : getPath();
}
if (!finalized) {
synchronized (sActiveDatabases) {
- sOpenTracker.close(path);
sActiveDatabases.remove(this);
}
@@ -1144,74 +1132,6 @@
}
}
- /**
- * Track the number of times a database file has been opened. There is a primary connection
- * associated with every open database, and these can contend with each other, leading to
- * unexpected SQLiteDatabaseLockedException exceptions. The tracking here is only advisory:
- * multiply-opened databases are logged but no other action is taken.
- *
- * This class is not thread-safe.
- */
- private static class OpenTracker {
- // The list of currently-open databases. This maps the database file to the number of
- // currently-active opens.
- private final ArrayMap<String, Integer> mOpens = new ArrayMap<>();
-
- // The maximum number of concurrently open database paths that will be stored. Once this
- // many paths have been recorded, further paths are logged but not saved.
- private static final int MAX_RECORDED_PATHS = 20;
-
- // The list of databases that were ever concurrently opened.
- private final ArraySet<String> mConcurrent = new ArraySet<>();
-
- /** Return the canonical path. On error, just return the input path. */
- private static String normalize(String path) {
- try {
- return new File(path).toPath().toRealPath().toString();
- } catch (Exception e) {
- // If there is an IO or security exception, just continue, using the input path.
- return path;
- }
- }
-
- /** Return true if the path is currently open in another SQLiteDatabase instance. */
- void open(@Nullable String path) {
- if (path == null) return;
- path = normalize(path);
-
- Integer count = mOpens.get(path);
- if (count == null || count == 0) {
- mOpens.put(path, 1);
- return;
- } else {
- mOpens.put(path, count + 1);
- if (mConcurrent.size() < MAX_RECORDED_PATHS) {
- mConcurrent.add(path);
- }
- Log.w(TAG, "multiple primary connections on " + path);
- return;
- }
- }
-
- void close(@Nullable String path) {
- if (path == null) return;
- path = normalize(path);
- Integer count = mOpens.get(path);
- if (count == null || count <= 0) {
- Log.e(TAG, "open database counting failure on " + path);
- } else if (count == 1) {
- // Implicitly set the count to zero, and make mOpens smaller.
- mOpens.remove(path);
- } else {
- mOpens.put(path, count - 1);
- }
- }
-
- ArraySet<String> getConcurrentDatabasePaths() {
- return new ArraySet<>(mConcurrent);
- }
- }
-
private void open() {
try {
try {
@@ -1233,17 +1153,14 @@
}
private void openInner() {
- final String path;
synchronized (mLock) {
assert mConnectionPoolLocked == null;
mConnectionPoolLocked = SQLiteConnectionPool.open(mConfigurationLocked);
mCloseGuardLocked.open("close");
- path = isInMemoryDatabase() ? null : getPath();
}
synchronized (sActiveDatabases) {
sActiveDatabases.put(this, null);
- sOpenTracker.open(path);
}
}
@@ -2428,17 +2345,6 @@
}
/**
- * Return list of databases that have been concurrently opened.
- * @hide
- */
- @VisibleForTesting
- public static ArraySet<String> getConcurrentDatabasePaths() {
- synchronized (sActiveDatabases) {
- return sOpenTracker.getConcurrentDatabasePaths();
- }
- }
-
- /**
* Returns true if the new version code is greater than the current database version.
*
* @param newVersion The new version code.
@@ -2860,19 +2766,6 @@
dumpDatabaseDirectory(printer, new File(dir), isSystem);
}
}
-
- // Dump concurrently-opened database files, if any
- final ArraySet<String> concurrent;
- synchronized (sActiveDatabases) {
- concurrent = sOpenTracker.getConcurrentDatabasePaths();
- }
- if (concurrent.size() > 0) {
- printer.println("");
- printer.println("Concurrently opened database files");
- for (String f : concurrent) {
- printer.println(" " + f);
- }
- }
}
private static void dumpDatabaseDirectory(Printer pw, File dir, boolean isSystem) {
diff --git a/core/java/android/database/sqlite/SQLiteOpenHelper.java b/core/java/android/database/sqlite/SQLiteOpenHelper.java
index 5e523c0..78c8954 100644
--- a/core/java/android/database/sqlite/SQLiteOpenHelper.java
+++ b/core/java/android/database/sqlite/SQLiteOpenHelper.java
@@ -377,8 +377,7 @@
if (writable) {
throw ex;
}
- Log.e(TAG, "Couldn't open " + mName
- + " for writing (will try read-only):", ex);
+ Log.e(TAG, "Couldn't open database for writing (will try read-only):", ex);
params = params.toBuilder().addOpenFlags(SQLiteDatabase.OPEN_READONLY).build();
db = SQLiteDatabase.openDatabase(filePath, params);
}
@@ -425,11 +424,6 @@
}
onOpen(db);
-
- if (db.isReadOnly()) {
- Log.w(TAG, "Opened " + mName + " in read-only mode");
- }
-
mDatabase = db;
return db;
} finally {
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index 04e3dab..7119730 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -772,6 +772,16 @@
"CameraDeviceSetup is not supported for Camera ID: " + cameraId);
}
+ return getCameraDeviceSetupUnsafe(cameraId);
+
+ }
+
+ /**
+ * Creates and returns a {@link CameraDeviceSetup} instance without any error checking. To
+ * be used (carefully) by callers who are sure that CameraDeviceSetup instance can be legally
+ * created and don't want to pay the latency cost of calling {@link #getCameraDeviceSetup}.
+ */
+ private CameraDevice.CameraDeviceSetup getCameraDeviceSetupUnsafe(@NonNull String cameraId) {
return new CameraDeviceSetupImpl(cameraId, /*cameraManager=*/ this, mContext);
}
@@ -857,8 +867,9 @@
ICameraDeviceUser cameraUser = null;
CameraDevice.CameraDeviceSetup cameraDeviceSetup = null;
- if (Flags.cameraDeviceSetup() && isCameraDeviceSetupSupported(cameraId)) {
- cameraDeviceSetup = getCameraDeviceSetup(cameraId);
+ if (Flags.cameraDeviceSetup()
+ && CameraDeviceSetupImpl.isCameraDeviceSetupSupported(characteristics)) {
+ cameraDeviceSetup = getCameraDeviceSetupUnsafe(cameraId);
}
android.hardware.camera2.impl.CameraDeviceImpl deviceImpl =
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index 95526a8..8aacd5e 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -1379,7 +1379,6 @@
mSurfaceType != other.mSurfaceType ||
mIsDeferredConfig != other.mIsDeferredConfig ||
mIsShared != other.mIsShared ||
- mConfiguredFormat != other.mConfiguredFormat ||
mConfiguredDataspace != other.mConfiguredDataspace ||
mConfiguredGenerationId != other.mConfiguredGenerationId ||
!Objects.equals(mPhysicalCameraId, other.mPhysicalCameraId) ||
diff --git a/core/java/android/hardware/usb/flags/system_sw_usb_flags.aconfig b/core/java/android/hardware/usb/flags/system_sw_usb_flags.aconfig
index 63ae28f..2a11835 100644
--- a/core/java/android/hardware/usb/flags/system_sw_usb_flags.aconfig
+++ b/core/java/android/hardware/usb/flags/system_sw_usb_flags.aconfig
@@ -20,3 +20,10 @@
description: "Enable reporting USB data compliance warnings from HAL when set"
bug: "296119135"
}
+
+flag {
+ name: "enable_usb_data_signal_staking"
+ namespace: "preload_safety"
+ description: "Enables signal API with staking"
+ bug: "296119135"
+}
\ No newline at end of file
diff --git a/core/java/android/os/IVibratorManagerService.aidl b/core/java/android/os/IVibratorManagerService.aidl
index 65e498e..8b1577c 100644
--- a/core/java/android/os/IVibratorManagerService.aidl
+++ b/core/java/android/os/IVibratorManagerService.aidl
@@ -41,5 +41,5 @@
// There is no order guarantee with respect to the two-way APIs above like
// vibrate/isVibrating/cancel.
oneway void performHapticFeedback(int uid, int deviceId, String opPkg, int constant,
- boolean always, String reason);
+ boolean always, String reason, boolean fromIme);
}
diff --git a/core/java/android/os/MessageQueue.java b/core/java/android/os/MessageQueue.java
index 3950c25..2fe115f 100644
--- a/core/java/android/os/MessageQueue.java
+++ b/core/java/android/os/MessageQueue.java
@@ -623,14 +623,14 @@
// Message is to be inserted at tail or middle of queue. Usually we don't have to
// wake up the event queue unless there is a barrier at the head of the queue and
// the message is the earliest asynchronous message in the queue.
- //
+ needWake = mBlocked && p.target == null && msg.isAsynchronous();
+
// For readability, we split this portion of the function into two blocks based on
// whether tail tracking is enabled. This has a minor implication for the case
// where tail tracking is disabled. See the comment below.
if (Flags.messageQueueTailTracking()) {
- needWake = mBlocked && p.target == null && msg.isAsynchronous()
- && mAsyncMessageCount == 0;
if (when >= mLast.when) {
+ needWake = needWake && mAsyncMessageCount == 0;
msg.next = null;
mLast.next = msg;
mLast = msg;
@@ -643,6 +643,9 @@
if (p == null || when < p.when) {
break;
}
+ if (needWake && p.isAsynchronous()) {
+ needWake = false;
+ }
}
if (p == null) {
/* Inserting at tail of queue */
@@ -652,7 +655,6 @@
prev.next = msg;
}
} else {
- needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
diff --git a/core/java/android/os/SystemVibrator.java b/core/java/android/os/SystemVibrator.java
index 04c257b..2a62c24 100644
--- a/core/java/android/os/SystemVibrator.java
+++ b/core/java/android/os/SystemVibrator.java
@@ -206,12 +206,13 @@
}
@Override
- public void performHapticFeedback(int constant, boolean always, String reason) {
+ public void performHapticFeedback(
+ int constant, boolean always, String reason, boolean fromIme) {
if (mVibratorManager == null) {
Log.w(TAG, "Failed to perform haptic feedback; no vibrator manager.");
return;
}
- mVibratorManager.performHapticFeedback(constant, always, reason);
+ mVibratorManager.performHapticFeedback(constant, always, reason, fromIme);
}
@Override
diff --git a/core/java/android/os/SystemVibratorManager.java b/core/java/android/os/SystemVibratorManager.java
index 8e83923..c80bcac 100644
--- a/core/java/android/os/SystemVibratorManager.java
+++ b/core/java/android/os/SystemVibratorManager.java
@@ -147,14 +147,15 @@
}
@Override
- public void performHapticFeedback(int constant, boolean always, String reason) {
+ public void performHapticFeedback(int constant, boolean always, String reason,
+ boolean fromIme) {
if (mService == null) {
Log.w(TAG, "Failed to perform haptic feedback; no vibrator manager service.");
return;
}
try {
mService.performHapticFeedback(
- mUid, mContext.getDeviceId(), mPackageName, constant, always, reason);
+ mUid, mContext.getDeviceId(), mPackageName, constant, always, reason, fromIme);
} catch (RemoteException e) {
Log.w(TAG, "Failed to perform haptic feedback.", e);
}
@@ -244,8 +245,9 @@
}
@Override
- public void performHapticFeedback(int effectId, boolean always, String reason) {
- SystemVibratorManager.this.performHapticFeedback(effectId, always, reason);
+ public void performHapticFeedback(int effectId, boolean always, String reason,
+ boolean fromIme) {
+ SystemVibratorManager.this.performHapticFeedback(effectId, always, reason, fromIme);
}
@Override
diff --git a/core/java/android/os/Vibrator.java b/core/java/android/os/Vibrator.java
index 2fc2414..4b2d4eb 100644
--- a/core/java/android/os/Vibrator.java
+++ b/core/java/android/os/Vibrator.java
@@ -534,10 +534,12 @@
* {@code false} if the vibration for the haptic feedback should respect the applicable
* vibration intensity settings.
* @param reason the reason for this haptic feedback.
+ * @param fromIme the haptic feedback is performed from an IME.
*
* @hide
*/
- public void performHapticFeedback(int constant, boolean always, String reason) {
+ public void performHapticFeedback(int constant, boolean always, String reason,
+ boolean fromIme) {
Log.w(TAG, "performHapticFeedback is not supported");
}
diff --git a/core/java/android/os/VibratorManager.java b/core/java/android/os/VibratorManager.java
index e0b6a9f..513c4bd 100644
--- a/core/java/android/os/VibratorManager.java
+++ b/core/java/android/os/VibratorManager.java
@@ -146,9 +146,11 @@
* vibration intensity settings applicable to the corresponding vibration.
* {@code false} otherwise.
* @param reason the reason for this haptic feedback.
+ * @param fromIme the haptic feedback is performed from an IME.
* @hide
*/
- public void performHapticFeedback(int constant, boolean always, String reason) {
+ public void performHapticFeedback(int constant, boolean always, String reason,
+ boolean fromIme) {
Log.w(TAG, "performHapticFeedback is not supported");
}
diff --git a/core/java/android/os/flags.aconfig b/core/java/android/os/flags.aconfig
index abfa4e3..d9400ac 100644
--- a/core/java/android/os/flags.aconfig
+++ b/core/java/android/os/flags.aconfig
@@ -1,4 +1,5 @@
package: "android.os"
+container: "system"
flag {
name: "android_os_build_vanilla_ice_cream"
@@ -40,6 +41,7 @@
namespace: "profile_experiences"
description: "Guards a new Private Profile type in UserManager - everything from its setup to config to deletion."
bug: "299069460"
+ is_exported: true
}
flag {
diff --git a/core/java/android/permission/PermissionManager.java b/core/java/android/permission/PermissionManager.java
index 8495f37..fa9f03d 100644
--- a/core/java/android/permission/PermissionManager.java
+++ b/core/java/android/permission/PermissionManager.java
@@ -247,8 +247,6 @@
private final LegacyPermissionManager mLegacyPermissionManager;
- private final VirtualDeviceManager mVirtualDeviceManager;
-
private final ArrayMap<PackageManager.OnPermissionsChangedListener,
IOnPermissionsChangeListener> mPermissionListeners = new ArrayMap<>();
private PermissionUsageHelper mUsageHelper;
@@ -269,7 +267,6 @@
mPermissionManager = IPermissionManager.Stub.asInterface(ServiceManager.getServiceOrThrow(
"permissionmgr"));
mLegacyPermissionManager = context.getSystemService(LegacyPermissionManager.class);
- mVirtualDeviceManager = context.getSystemService(VirtualDeviceManager.class);
}
/**
@@ -1918,14 +1915,18 @@
if (deviceId == Context.DEVICE_ID_DEFAULT) {
persistentDeviceId = VirtualDeviceManager.PERSISTENT_DEVICE_ID_DEFAULT;
} else if (android.companion.virtual.flags.Flags.vdmPublicApis()) {
- VirtualDevice virtualDevice = mVirtualDeviceManager.getVirtualDevice(deviceId);
- if (virtualDevice == null) {
- Slog.e(LOG_TAG, "Virtual device is not found with device Id " + deviceId);
- return null;
- }
- persistentDeviceId = virtualDevice.getPersistentDeviceId();
- if (persistentDeviceId == null) {
- Slog.e(LOG_TAG, "Cannot find persistent device Id for " + deviceId);
+ VirtualDeviceManager virtualDeviceManager = mContext.getSystemService(
+ VirtualDeviceManager.class);
+ if (virtualDeviceManager != null) {
+ VirtualDevice virtualDevice = virtualDeviceManager.getVirtualDevice(deviceId);
+ if (virtualDevice == null) {
+ Slog.e(LOG_TAG, "Virtual device is not found with device Id " + deviceId);
+ return null;
+ }
+ persistentDeviceId = virtualDevice.getPersistentDeviceId();
+ if (persistentDeviceId == null) {
+ Slog.e(LOG_TAG, "Cannot find persistent device Id for " + deviceId);
+ }
}
} else {
Slog.e(LOG_TAG, "vdmPublicApis flag is not enabled when device Id " + deviceId
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index c13dd36..c03dc71 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -406,6 +406,7 @@
* Builder for the add-call parameters.
*/
public static final class AddCallParametersBuilder {
+ public static final int MAX_NUMBER_OF_CHARACTERS = 256;
private CallerInfo mCallerInfo;
private String mNumber;
private String mPostDialDigits;
@@ -431,7 +432,7 @@
private Uri mPictureUri;
private int mIsPhoneAccountMigrationPending;
private boolean mIsBusinessCall;
- private String mBusinessName;
+ private String mAssertedDisplayName;
/**
* @param callerInfo the CallerInfo object to get the target contact from.
@@ -659,11 +660,18 @@
}
/**
- * @param businessName should be set if the caller is a business call
+ * @param assertedDisplayName the asserted display name associated with the business
+ * call
+ * @throws IllegalArgumentException if the assertedDisplayName is over 256 characters
*/
@FlaggedApi(Flags.FLAG_BUSINESS_CALL_COMPOSER)
- public @NonNull AddCallParametersBuilder setBusinessName(String businessName) {
- mBusinessName = businessName;
+ public @NonNull AddCallParametersBuilder setAssertedDisplayName(
+ String assertedDisplayName) {
+ if (assertedDisplayName.length() > MAX_NUMBER_OF_CHARACTERS) {
+ throw new IllegalArgumentException("assertedDisplayName exceeds the character"
+ + " limit of " + MAX_NUMBER_OF_CHARACTERS + ".");
+ }
+ mAssertedDisplayName = assertedDisplayName;
return this;
}
@@ -678,7 +686,7 @@
mCallBlockReason,
mCallScreeningAppName, mCallScreeningComponentName, mMissedReason,
mPriority, mSubject, mLatitude, mLongitude, mPictureUri,
- mIsPhoneAccountMigrationPending, mIsBusinessCall, mBusinessName);
+ mIsPhoneAccountMigrationPending, mIsBusinessCall, mAssertedDisplayName);
} else {
return new AddCallParams(mCallerInfo, mNumber, mPostDialDigits, mViaNumber,
mPresentation, mCallType, mFeatures, mAccountHandle, mStart, mDuration,
@@ -716,7 +724,7 @@
private Uri mPictureUri;
private int mIsPhoneAccountMigrationPending;
private boolean mIsBusinessCall;
- private String mBusinessName;
+ private String mAssertedDisplayName;
private AddCallParams(CallerInfo callerInfo, String number, String postDialDigits,
String viaNumber, int presentation, int callType, int features,
@@ -761,7 +769,8 @@
CharSequence callScreeningAppName, String callScreeningComponentName,
long missedReason,
int priority, String subject, double latitude, double longitude, Uri pictureUri,
- int isPhoneAccountMigrationPending, boolean isBusinessCall, String businessName) {
+ int isPhoneAccountMigrationPending, boolean isBusinessCall,
+ String assertedDisplayName) {
mCallerInfo = callerInfo;
mNumber = number;
mPostDialDigits = postDialDigits;
@@ -787,7 +796,7 @@
mPictureUri = pictureUri;
mIsPhoneAccountMigrationPending = isPhoneAccountMigrationPending;
mIsBusinessCall = isBusinessCall;
- mBusinessName = businessName;
+ mAssertedDisplayName = assertedDisplayName;
}
}
@@ -1833,7 +1842,7 @@
values.put(IS_PHONE_ACCOUNT_MIGRATION_PENDING, params.mIsPhoneAccountMigrationPending);
if (Flags.businessCallComposer()) {
values.put(IS_BUSINESS_CALL, Integer.valueOf(params.mIsBusinessCall ? 1 : 0));
- values.put(ASSERTED_DISPLAY_NAME, params.mBusinessName);
+ values.put(ASSERTED_DISPLAY_NAME, params.mAssertedDisplayName);
}
if ((params.mCallerInfo != null) && (params.mCallerInfo.getContactId() > 0)) {
// Update usage information for the number associated with the contact ID.
diff --git a/core/java/android/security/ConfirmationPrompt.java b/core/java/android/security/ConfirmationPrompt.java
index d8c44ad..f626149 100644
--- a/core/java/android/security/ConfirmationPrompt.java
+++ b/core/java/android/security/ConfirmationPrompt.java
@@ -92,7 +92,6 @@
private Executor mExecutor;
private Context mContext;
- private final KeyStore mKeyStore = KeyStore.getInstance();
private AndroidProtectedConfirmation mProtectedConfirmation;
private AndroidProtectedConfirmation getService() {
diff --git a/core/java/android/security/keystore/recovery/RecoveryController.java b/core/java/android/security/keystore/recovery/RecoveryController.java
index f1054ec..c171c1b 100644
--- a/core/java/android/security/keystore/recovery/RecoveryController.java
+++ b/core/java/android/security/keystore/recovery/RecoveryController.java
@@ -26,7 +26,6 @@
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.ServiceSpecificException;
-import android.security.KeyStore;
import android.security.KeyStore2;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore2.AndroidKeyStoreProvider;
@@ -272,11 +271,9 @@
public static final int ERROR_KEY_NOT_FOUND = 30;
private final ILockSettings mBinder;
- private final KeyStore mKeyStore;
- private RecoveryController(ILockSettings binder, KeyStore keystore) {
+ private RecoveryController(ILockSettings binder) {
mBinder = binder;
- mKeyStore = keystore;
}
/**
@@ -296,7 +293,7 @@
// lockSettings may be null.
ILockSettings lockSettings =
ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings"));
- return new RecoveryController(lockSettings, KeyStore.getInstance());
+ return new RecoveryController(lockSettings);
}
/**
diff --git a/core/java/android/tracing/flags.aconfig b/core/java/android/tracing/flags.aconfig
index b1bca96..cedba85 100644
--- a/core/java/android/tracing/flags.aconfig
+++ b/core/java/android/tracing/flags.aconfig
@@ -8,7 +8,7 @@
}
flag {
- name: "perfetto_protolog"
+ name: "perfetto_protolog_tracing"
namespace: "windowing_tools"
description: "Migrate protolog to Perfetto"
bug: "276432490"
diff --git a/core/java/android/view/HandwritingInitiator.java b/core/java/android/view/HandwritingInitiator.java
index 00657ea..66655fc 100644
--- a/core/java/android/view/HandwritingInitiator.java
+++ b/core/java/android/view/HandwritingInitiator.java
@@ -188,8 +188,7 @@
// check whether the stylus we are tracking goes up.
if (mState != null) {
mState.mShouldInitHandwriting = false;
- if (!mState.mHasInitiatedHandwriting
- && !mState.mHasPreparedHandwritingDelegation) {
+ if (!mState.mHandled) {
// The user just did a click, long click or another stylus gesture,
// show hover icon again for the connected view.
mShowHoverIconForConnectedView = true;
@@ -204,16 +203,14 @@
// Either we've already tried to initiate handwriting, or the ongoing MotionEvent
// sequence is considered to be tap, long-click or other gestures.
if (!mState.mShouldInitHandwriting || mState.mExceedHandwritingSlop) {
- return mState.mHasInitiatedHandwriting
- || mState.mHasPreparedHandwritingDelegation;
+ return mState.mHandled;
}
final long timeElapsed =
motionEvent.getEventTime() - mState.mStylusDownTimeInMillis;
if (timeElapsed > mHandwritingTimeoutInMillis) {
mState.mShouldInitHandwriting = false;
- return mState.mHasInitiatedHandwriting
- || mState.mHasPreparedHandwritingDelegation;
+ return mState.mHandled;
}
final int pointerIndex = motionEvent.findPointerIndex(mState.mStylusPointerId);
@@ -223,7 +220,7 @@
mState.mExceedHandwritingSlop = true;
View candidateView = findBestCandidateView(mState.mStylusDownX,
mState.mStylusDownY, /* isHover */ false);
- if (candidateView != null) {
+ if (candidateView != null && candidateView.isEnabled()) {
if (candidateView == getConnectedOrFocusedView()) {
if (!mInitiateWithoutConnection && !candidateView.hasFocus()) {
requestFocusWithoutReveal(candidateView);
@@ -246,7 +243,7 @@
}
}
}
- return mState.mHasInitiatedHandwriting || mState.mHasPreparedHandwritingDelegation;
+ return mState.mHandled;
}
return false;
}
@@ -382,7 +379,7 @@
@VisibleForTesting
public void startHandwriting(@NonNull View view) {
mImm.startStylusHandwriting(view);
- mState.mHasInitiatedHandwriting = true;
+ mState.mHandled = true;
mState.mShouldInitHandwriting = false;
mShowHoverIconForConnectedView = false;
if (view instanceof TextView) {
@@ -402,13 +399,12 @@
mImm.startConnectionlessStylusHandwritingForDelegation(
view, getCursorAnchorInfoForConnectionless(view), delegatePackageName,
view::post, new DelegationCallback(view, delegatePackageName));
- mState.mHasInitiatedHandwriting = true;
mState.mShouldInitHandwriting = false;
} else {
mImm.prepareStylusHandwritingDelegation(view, delegatePackageName);
view.getHandwritingDelegatorCallback().run();
- mState.mHasPreparedHandwritingDelegation = true;
}
+ mState.mHandled = true;
}
/**
@@ -455,7 +451,7 @@
private void onDelegationAccepted(View view) {
if (mState != null) {
- mState.mHasInitiatedHandwriting = true;
+ mState.mHandled = true;
mState.mShouldInitHandwriting = false;
}
if (view instanceof TextView) {
@@ -795,12 +791,12 @@
* This boolean will be set to false, and it won't request to start handwriting.
*/
private boolean mShouldInitHandwriting;
- /**
- * Whether handwriting mode has already been initiated for the current MotionEvent sequence.
- */
- private boolean mHasInitiatedHandwriting;
- private boolean mHasPreparedHandwritingDelegation;
+ /**
+ * Whether the current MotionEvent sequence has been handled by the handwriting initiator,
+ * either by initiating handwriting mode, or by preparing handwriting delegation.
+ */
+ private boolean mHandled;
/**
* Whether the current ongoing stylus MotionEvent sequence already exceeds the
@@ -838,8 +834,7 @@
mStylusDownY = motionEvent.getY(actionIndex);
mShouldInitHandwriting = true;
- mHasInitiatedHandwriting = false;
- mHasPreparedHandwritingDelegation = false;
+ mHandled = false;
mExceedHandwritingSlop = false;
}
}
@@ -1052,8 +1047,6 @@
// Fall back to the old delegation flow
mImm.prepareStylusHandwritingDelegation(mView, mDelegatePackageName);
mView.getHandwritingDelegatorCallback().run();
- mState.mHasInitiatedHandwriting = false;
- mState.mHasPreparedHandwritingDelegation = true;
break;
}
}
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index d68a47c..e126836 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -148,13 +148,13 @@
int seqId);
@UnsupportedAppUsage
- boolean performHapticFeedback(int effectId, boolean always);
+ boolean performHapticFeedback(int effectId, boolean always, boolean fromIme);
/**
* Called by attached views to perform predefined haptic feedback without requiring VIBRATE
* permission.
*/
- oneway void performHapticFeedbackAsync(int effectId, boolean always);
+ oneway void performHapticFeedbackAsync(int effectId, boolean always, boolean fromIme);
/**
* Initiate the drag operation itself
diff --git a/core/java/android/view/PointerIcon.java b/core/java/android/view/PointerIcon.java
index f5f4fd9..9099f98 100644
--- a/core/java/android/view/PointerIcon.java
+++ b/core/java/android/view/PointerIcon.java
@@ -428,13 +428,11 @@
private BitmapDrawable getBitmapDrawableFromVectorDrawable(Resources resources,
VectorDrawable vectorDrawable) {
- Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
- vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
- // BitmapDrawables and Bitmap have a default density of DisplayMetrics.DENSITY_DEVICE,
- // (which is deprecated in favor of DENSITY_DEVICE_STABLE/resources.densityDpi). In
- // rare cases when device density differs from the resource density, the bitmap will
- // scale as the BitmapDrawable is created. Avoid by explicitly setting density here.
- bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
+ // Ensure we pass the display metrics into the Bitmap constructor so that it is initialized
+ // with the correct density.
+ Bitmap bitmap = Bitmap.createBitmap(resources.getDisplayMetrics(),
+ vectorDrawable.getIntrinsicWidth(),
+ vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888, true /* hasAlpha */);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 042af1f..3478286 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -25,6 +25,7 @@
import static android.view.Surface.FRAME_RATE_CATEGORY_NORMAL;
import static android.view.Surface.FRAME_RATE_CATEGORY_NO_PREFERENCE;
import static android.view.Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
+import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED;
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_INVALID_BOUNDS;
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_MISSING_WINDOW;
@@ -16815,10 +16816,15 @@
mAttachInfo.mViewRootImpl.getWindowVisibleDisplayFrame(outRect);
return;
}
- // The view is not attached to a display so we don't have a context.
- // Make a best guess about the display size.
- Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
- d.getRectSize(outRect);
+ // TODO (b/327559224): Refine the behavior to better reflect the window environment with API
+ // doc updates.
+ final WindowManager windowManager = mContext.getSystemService(WindowManager.class);
+ final WindowMetrics metrics = windowManager.getMaximumWindowMetrics();
+ final Insets insets = metrics.getWindowInsets().getInsets(
+ WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());
+ outRect.set(metrics.getBounds());
+ outRect.inset(insets);
+ outRect.offsetTo(0, 0);
}
/**
@@ -28371,15 +28377,19 @@
}
final boolean always = (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0;
+ boolean fromIme = false;
+ if (mAttachInfo.mViewRootImpl != null) {
+ fromIme = mAttachInfo.mViewRootImpl.mWindowAttributes.type == TYPE_INPUT_METHOD;
+ }
if (Flags.useVibratorHapticFeedback()) {
if (!mAttachInfo.canPerformHapticFeedback()) {
return false;
}
getSystemVibrator().performHapticFeedback(
- feedbackConstant, always, "View#performHapticFeedback");
+ feedbackConstant, always, "View#performHapticFeedback", fromIme);
return true;
}
- return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, always);
+ return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, always, fromIme);
}
private Vibrator getSystemVibrator() {
@@ -31422,7 +31432,7 @@
interface Callbacks {
void playSoundEffect(int effectId);
- boolean performHapticFeedback(int effectId, boolean always);
+ boolean performHapticFeedback(int effectId, boolean always, boolean fromIme);
}
/**
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 333cbb3..708751a 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -9201,18 +9201,18 @@
* {@inheritDoc}
*/
@Override
- public boolean performHapticFeedback(int effectId, boolean always) {
+ public boolean performHapticFeedback(int effectId, boolean always, boolean fromIme) {
if ((mDisplay.getFlags() & Display.FLAG_TOUCH_FEEDBACK_DISABLED) != 0) {
return false;
}
try {
if (USE_ASYNC_PERFORM_HAPTIC_FEEDBACK) {
- mWindowSession.performHapticFeedbackAsync(effectId, always);
+ mWindowSession.performHapticFeedbackAsync(effectId, always, fromIme);
return true;
} else {
// Original blocking binder call path.
- return mWindowSession.performHapticFeedback(effectId, always);
+ return mWindowSession.performHapticFeedback(effectId, always, fromIme);
}
} catch (RemoteException e) {
return false;
diff --git a/core/java/android/view/WindowlessWindowManager.java b/core/java/android/view/WindowlessWindowManager.java
index 2b2c507..22d8ed9 100644
--- a/core/java/android/view/WindowlessWindowManager.java
+++ b/core/java/android/view/WindowlessWindowManager.java
@@ -479,13 +479,13 @@
}
@Override
- public boolean performHapticFeedback(int effectId, boolean always) {
+ public boolean performHapticFeedback(int effectId, boolean always, boolean fromIme) {
return false;
}
@Override
- public void performHapticFeedbackAsync(int effectId, boolean always) {
- performHapticFeedback(effectId, always);
+ public void performHapticFeedbackAsync(int effectId, boolean always, boolean fromIme) {
+ performHapticFeedback(effectId, always, fromIme);
}
@Override
diff --git a/core/java/android/view/inputmethod/ImeTracker.java b/core/java/android/view/inputmethod/ImeTracker.java
index 74e1d10..b1fdaa9 100644
--- a/core/java/android/view/inputmethod/ImeTracker.java
+++ b/core/java/android/view/inputmethod/ImeTracker.java
@@ -340,15 +340,6 @@
@SoftInputShowHideReason int reason, boolean fromUser);
/**
- * Alias for {@link #onRequestShow(String, int, int, int, boolean)} with
- * {@code fromUser} set to {@code false}.
- */
- default Token onRequestShow(@Nullable String component, int uid, @Origin int origin,
- @SoftInputShowHideReason int reason) {
- return onRequestShow(component, uid, origin, reason, false /* fromUser */);
- }
-
- /**
* Creates an IME hide request tracking token.
*
* @param component the name of the component that created the IME request, or {@code null}
@@ -365,15 +356,6 @@
@SoftInputShowHideReason int reason, boolean fromUser);
/**
- * Alias for {@link #onRequestHide(String, int, int, int, boolean)} with
- * {@code fromUser} set to {@code false}.
- */
- default Token onRequestHide(@Nullable String component, int uid, @Origin int origin,
- @SoftInputShowHideReason int reason) {
- return onRequestHide(component, uid, origin, reason, false /* fromUser */);
- }
-
- /**
* Called when an IME request progresses to a further phase.
*
* @param token the token tracking the current IME request or {@code null} otherwise.
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index f349ae9..68940d6 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -1153,6 +1153,7 @@
}
final boolean startInput;
synchronized (mH) {
+ mImeDispatcher.clear();
if (getBindSequenceLocked() != sequence) {
return;
}
@@ -2328,7 +2329,7 @@
synchronized (mH) {
final ImeTracker.Token statsToken = ImeTracker.forLogging().onRequestShow(
null /* component */, Process.myUid(), ImeTracker.ORIGIN_CLIENT_SHOW_SOFT_INPUT,
- SoftInputShowHideReason.SHOW_SOFT_INPUT);
+ SoftInputShowHideReason.SHOW_SOFT_INPUT, false /* fromUser */);
Log.w(TAG, "showSoftInputUnchecked() is a hidden method, which will be"
+ " removed soon. If you are using androidx.appcompat.widget.SearchView,"
@@ -3538,7 +3539,7 @@
void closeCurrentInput() {
final ImeTracker.Token statsToken = ImeTracker.forLogging().onRequestHide(
null /* component */, Process.myUid(), ImeTracker.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
- SoftInputShowHideReason.HIDE_CLOSE_CURRENT_SESSION);
+ SoftInputShowHideReason.HIDE_CLOSE_CURRENT_SESSION, false /* fromUser */);
ImeTracker.forLatency().onRequestHide(statsToken, ImeTracker.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
SoftInputShowHideReason.HIDE_CLOSE_CURRENT_SESSION,
ActivityThread::currentApplication);
@@ -3638,7 +3639,7 @@
if (statsToken == null) {
statsToken = ImeTracker.forLogging().onRequestHide(null /* component */,
Process.myUid(), ImeTracker.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
- SoftInputShowHideReason.HIDE_SOFT_INPUT_BY_INSETS_API);
+ SoftInputShowHideReason.HIDE_SOFT_INPUT_BY_INSETS_API, false /* fromUser */);
}
ImeTracker.forLatency().onRequestHide(statsToken, ImeTracker.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
SoftInputShowHideReason.HIDE_SOFT_INPUT_BY_INSETS_API,
diff --git a/core/java/android/widget/flags/notification_widget_flags.aconfig b/core/java/android/widget/flags/notification_widget_flags.aconfig
index bfe3d05..e60fa15 100644
--- a/core/java/android/widget/flags/notification_widget_flags.aconfig
+++ b/core/java/android/widget/flags/notification_widget_flags.aconfig
@@ -15,4 +15,14 @@
metadata {
purpose: PURPOSE_BUGFIX
}
+}
+
+flag {
+ name: "conversation_style_set_avatar_async"
+ namespace: "systemui"
+ description: "Offloads conversation avatar drawable loading to the background thread"
+ bug: "305540309"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
}
\ No newline at end of file
diff --git a/core/java/android/window/flags/responsible_apis.aconfig b/core/java/android/window/flags/responsible_apis.aconfig
index 51890ec..94c72c6 100644
--- a/core/java/android/window/flags/responsible_apis.aconfig
+++ b/core/java/android/window/flags/responsible_apis.aconfig
@@ -46,5 +46,5 @@
name: "bal_respect_app_switch_state_when_check_bound_by_foreground_uid"
namespace: "responsible_apis"
description: "Prevent BAL based on it is bound by foreground Uid but the app switch is stopped."
- bug: "171459802"
+ bug: "283801068"
}
diff --git a/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java b/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
index d9ac5a9..30de546 100644
--- a/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
@@ -61,7 +61,7 @@
private static final int PER_CHUNK_SIZE = 1024;
private static final String TAG = "ProtoLog";
private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
- static final String PROTOLOG_VERSION = "1.0.0";
+ static final String PROTOLOG_VERSION = "2.0.0";
private static final int DEFAULT_PER_CHUNK_SIZE = 0;
private final File mLogFile;
diff --git a/core/java/com/android/internal/protolog/ProtoLogImpl.java b/core/java/com/android/internal/protolog/ProtoLogImpl.java
index 78bed94..8965385 100644
--- a/core/java/com/android/internal/protolog/ProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/ProtoLogImpl.java
@@ -98,7 +98,7 @@
*/
public static synchronized IProtoLog getSingleInstance() {
if (sServiceInstance == null) {
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
sServiceInstance =
new PerfettoProtoLogImpl(sViewerConfigPath);
} else {
diff --git a/core/java/com/android/internal/statusbar/IStatusBar.aidl b/core/java/com/android/internal/statusbar/IStatusBar.aidl
index d463b62..6ffc638 100644
--- a/core/java/com/android/internal/statusbar/IStatusBar.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBar.aidl
@@ -360,8 +360,12 @@
/** Shows rear display educational dialog */
void showRearDisplayDialog(int currentBaseState);
- /** Called when requested to go to fullscreen from the active split app. */
- void goToFullscreenFromSplit();
+ /**
+ * Called when requested to go to fullscreen from the focused app.
+ *
+ * @param displayId the id of the current display.
+ */
+ void moveFocusedTaskToFullscreen(int displayId);
/**
* Enters stage split from a current running app.
diff --git a/core/java/com/android/internal/widget/ConversationAvatarData.java b/core/java/com/android/internal/widget/ConversationAvatarData.java
new file mode 100644
index 0000000..e04772f
--- /dev/null
+++ b/core/java/com/android/internal/widget/ConversationAvatarData.java
@@ -0,0 +1,42 @@
+/*
+ * 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.internal.widget;
+
+import android.graphics.drawable.Drawable;
+
+/**
+ * @hide
+ */
+interface ConversationAvatarData {
+ final class OneToOneConversationAvatarData implements ConversationAvatarData {
+ final Drawable mDrawable;
+
+ OneToOneConversationAvatarData(Drawable drawable) {
+ mDrawable = drawable;
+ }
+ }
+
+ final class GroupConversationAvatarData implements ConversationAvatarData {
+ final Drawable mLastIcon;
+ final Drawable mSecondLastIcon;
+
+ GroupConversationAvatarData(Drawable lastIcon, Drawable secondLastIcon) {
+ mLastIcon = lastIcon;
+ mSecondLastIcon = secondLastIcon;
+ }
+ }
+}
diff --git a/core/java/com/android/internal/widget/ConversationHeaderData.java b/core/java/com/android/internal/widget/ConversationHeaderData.java
new file mode 100644
index 0000000..0953b39
--- /dev/null
+++ b/core/java/com/android/internal/widget/ConversationHeaderData.java
@@ -0,0 +1,44 @@
+/*
+ * 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.internal.widget;
+
+import android.annotation.Nullable;
+
+/**
+ * @hide
+ */
+final class ConversationHeaderData {
+ private final CharSequence mConversationText;
+
+ private final ConversationAvatarData mConversationAvatarData;
+
+ ConversationHeaderData(CharSequence conversationText,
+ ConversationAvatarData conversationAvatarData) {
+ mConversationText = conversationText;
+ mConversationAvatarData = conversationAvatarData;
+ }
+
+ @Nullable
+ CharSequence getConversationText() {
+ return mConversationText;
+ }
+
+ @Nullable
+ ConversationAvatarData getConversationAvatar() {
+ return mConversationAvatarData;
+ }
+}
diff --git a/core/java/com/android/internal/widget/ConversationLayout.java b/core/java/com/android/internal/widget/ConversationLayout.java
index 889434f..06835f0 100644
--- a/core/java/com/android/internal/widget/ConversationLayout.java
+++ b/core/java/com/android/internal/widget/ConversationLayout.java
@@ -34,8 +34,10 @@
import android.content.res.ColorStateList;
import android.graphics.Rect;
import android.graphics.Typeface;
+import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.Icon;
+import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Spannable;
@@ -59,8 +61,11 @@
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
+import android.widget.flags.Flags;
import com.android.internal.R;
+import com.android.internal.widget.ConversationAvatarData.GroupConversationAvatarData;
+import com.android.internal.widget.ConversationAvatarData.OneToOneConversationAvatarData;
import java.util.ArrayList;
import java.util.List;
@@ -403,11 +408,14 @@
*/
@RemotableViewMethod(asyncImpl = "setDataAsync")
public void setData(Bundle extras) {
- bind(parseMessagingData(extras, /* usePrecomputedText= */ false));
+ bind(parseMessagingData(extras,
+ /* usePrecomputedText= */ false,
+ /*includeConversationIcon= */false));
}
@NonNull
- private MessagingData parseMessagingData(Bundle extras, boolean usePrecomputedText) {
+ private MessagingData parseMessagingData(Bundle extras, boolean usePrecomputedText,
+ boolean includeConversationIcon) {
Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
List<Notification.MessagingStyle.Message> newMessages =
Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
@@ -438,8 +446,20 @@
// Lets first find the groups (populate `groups` and `senders`)
findGroups(newHistoricMessagingMessages, newMessagingMessages, user, groups, senders);
+ // load conversation header data, avatar and title.
+ final ConversationHeaderData conversationHeaderData;
+ if (includeConversationIcon && Flags.conversationStyleSetAvatarAsync()) {
+ conversationHeaderData = loadConversationHeaderData(mIsOneToOne,
+ mConversationTitle,
+ mShortcutIcon,
+ mLargeIcon, newMessagingMessages, user, groups, mLayoutColor);
+ } else {
+ conversationHeaderData = null;
+ }
+
return new MessagingData(user, showSpinner, unreadCount,
- newHistoricMessagingMessages, newMessagingMessages, groups, senders);
+ newHistoricMessagingMessages, newMessagingMessages, groups, senders,
+ conversationHeaderData);
}
/**
@@ -457,7 +477,9 @@
}
final MessagingData messagingData =
- parseMessagingData(extras, /* usePrecomputedText= */ true);
+ parseMessagingData(extras,
+ /* usePrecomputedText= */ true,
+ /*includeConversationIcon=*/true);
return () -> {
finalizeInflate(messagingData.getHistoricMessagingMessages());
@@ -536,11 +558,10 @@
mMessages = messagingData.getNewMessagingMessages();
mHistoricMessages = messagingData.getHistoricMessagingMessages();
-
updateHistoricMessageVisibility();
updateTitleAndNamesDisplay();
- updateConversationLayout();
+ updateConversationLayout(messagingData);
// Recycle everything at the end of the update, now that we know it's no longer needed.
for (MessagingLinearLayout.MessagingChild child : mToRecycle) {
@@ -552,7 +573,31 @@
/**
* Update the layout according to the data provided (i.e mIsOneToOne, expanded etc);
*/
- private void updateConversationLayout() {
+ private void updateConversationLayout(MessagingData messagingData) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ computeAndSetConversationAvatarAndName();
+ } else {
+ ConversationHeaderData conversationHeaderData =
+ messagingData.getConversationHeaderData();
+ if (conversationHeaderData == null) {
+ conversationHeaderData = loadConversationHeaderData(mIsOneToOne,
+ mConversationTitle, mShortcutIcon, mLargeIcon, mMessages, mUser,
+ messagingData.getGroups(),
+ mLayoutColor);
+ }
+ setConversationAvatarAndNameFromData(conversationHeaderData);
+ }
+
+ updateAppName();
+ updateIconPositionAndSize();
+ updateImageMessages();
+ updatePaddingsBasedOnContentAvailability();
+ updateActionListPadding();
+ updateAppNameDividerVisibility();
+ }
+
+ @Deprecated
+ private void computeAndSetConversationAvatarAndName() {
// Set avatar and name
CharSequence conversationText = mConversationTitle;
mConversationIcon = mShortcutIcon;
@@ -603,12 +648,43 @@
// Update if the groups can hide the sender if they are first (applies to 1:1 conversations)
// This needs to happen after all of the above o update all of the groups
mPeopleHelper.maybeHideFirstSenderName(mGroups, mIsOneToOne, conversationText);
- updateAppName();
- updateIconPositionAndSize();
- updateImageMessages();
- updatePaddingsBasedOnContentAvailability();
- updateActionListPadding();
- updateAppNameDividerVisibility();
+ }
+
+ private void setConversationAvatarAndNameFromData(
+ ConversationHeaderData conversationHeaderData) {
+ final OneToOneConversationAvatarData oneToOneConversationDrawable;
+ final GroupConversationAvatarData groupConversationAvatarData;
+ final ConversationAvatarData conversationAvatar =
+ conversationHeaderData.getConversationAvatar();
+ if (conversationAvatar instanceof OneToOneConversationAvatarData) {
+ oneToOneConversationDrawable =
+ ((OneToOneConversationAvatarData) conversationAvatar);
+ groupConversationAvatarData = null;
+ } else {
+ oneToOneConversationDrawable = null;
+ groupConversationAvatarData = ((GroupConversationAvatarData) conversationAvatar);
+ }
+
+ if (oneToOneConversationDrawable != null) {
+ mConversationIconView.setVisibility(VISIBLE);
+ mConversationFacePile.setVisibility(GONE);
+ mConversationIconView.setImageDrawable(oneToOneConversationDrawable.mDrawable);
+ } else {
+ mConversationIconView.setVisibility(GONE);
+ // This will also inflate it!
+ mConversationFacePile.setVisibility(VISIBLE);
+ // rebind the value to the inflated view instead of the stub
+ mConversationFacePile = findViewById(R.id.conversation_face_pile);
+ bindFacePile(groupConversationAvatarData);
+ }
+ CharSequence conversationText = conversationHeaderData.getConversationText();
+ if (TextUtils.isEmpty(conversationText)) {
+ conversationText = mIsOneToOne ? mFallbackChatName : mFallbackGroupChatName;
+ }
+ mConversationText.setText(conversationText);
+ // Update if the groups can hide the sender if they are first (applies to 1:1 conversations)
+ // This needs to happen after all of the above o update all of the groups
+ mPeopleHelper.maybeHideFirstSenderName(mGroups, mIsOneToOne, conversationText);
}
private void updateActionListPadding() {
@@ -675,7 +751,12 @@
topView.setImageIcon(secondLastIcon);
}
+ @Deprecated
private void bindFacePile() {
+ bindFacePile(null);
+ }
+
+ private void bindFacePile(@Nullable GroupConversationAvatarData groupConversationAvatarData) {
ImageView bottomBackground = mConversationFacePile.findViewById(
R.id.conversation_face_pile_bottom_background);
ImageView bottomView = mConversationFacePile.findViewById(
@@ -683,7 +764,13 @@
ImageView topView = mConversationFacePile.findViewById(
R.id.conversation_face_pile_top);
- bindFacePile(bottomBackground, bottomView, topView);
+ if (groupConversationAvatarData == null) {
+ bindFacePile(bottomBackground, bottomView, topView);
+ } else {
+ bindFacePileWithDrawable(bottomBackground, bottomView, topView,
+ groupConversationAvatarData);
+
+ }
int conversationAvatarSize;
int facepileAvatarSize;
@@ -718,6 +805,13 @@
bottomBackground.setLayoutParams(layoutParams);
}
+ private void bindFacePileWithDrawable(ImageView bottomBackground, ImageView bottomView,
+ ImageView topView, GroupConversationAvatarData groupConversationAvatarData) {
+ applyNotificationBackgroundColor(bottomBackground);
+ bottomView.setImageDrawable(groupConversationAvatarData.mLastIcon);
+ topView.setImageDrawable(groupConversationAvatarData.mSecondLastIcon);
+ }
+
private void updateAppName() {
mAppName.setVisibility(mIsCollapsed ? GONE : VISIBLE);
}
@@ -789,22 +883,62 @@
mMessagingLinearLayout.getPaddingBottom());
}
+ /**
+ * async version of {@link ConversationLayout#setLargeIcon}
+ */
@RemotableViewMethod
+ public Runnable setLargeIconAsync(Icon largeIcon) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ return () -> setLargeIcon(largeIcon);
+ }
+
+ mLargeIcon = largeIcon;
+ return NotificationRunnables.NOOP;
+ }
+
+ @RemotableViewMethod(asyncImpl = "setLargeIconAsync")
public void setLargeIcon(Icon largeIcon) {
mLargeIcon = largeIcon;
}
+ /**
+ * async version of {@link ConversationLayout#setShortcutIcon}
+ */
@RemotableViewMethod
+ public Runnable setShortcutIconAsync(Icon shortcutIcon) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ return () -> setShortcutIcon(shortcutIcon);
+ }
+
+ mShortcutIcon = shortcutIcon;
+ return NotificationRunnables.NOOP;
+ }
+
+ @RemotableViewMethod(asyncImpl = "setShortcutIconAsync")
public void setShortcutIcon(Icon shortcutIcon) {
mShortcutIcon = shortcutIcon;
}
/**
+ * async version of {@link ConversationLayout#setConversationTitle}
+ */
+ @RemotableViewMethod
+ public Runnable setConversationTitleAsync(CharSequence conversationTitle) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ return () -> setConversationTitle(conversationTitle);
+ }
+
+ // Remove formatting from the title.
+ mConversationTitle = conversationTitle != null ? conversationTitle.toString() : null;
+ return NotificationRunnables.NOOP;
+ }
+
+ /**
* Sets the conversation title of this conversation.
*
* @param conversationTitle the conversation title
*/
- @RemotableViewMethod
+ @RemotableViewMethod(asyncImpl = "setConversationTitleAsync")
public void setConversationTitle(CharSequence conversationTitle) {
// Remove formatting from the title.
mConversationTitle = conversationTitle != null ? conversationTitle.toString() : null;
@@ -888,12 +1022,37 @@
}
}
+ /**
+ * async version of {@link ConversationLayout#setLayoutColor}
+ */
@RemotableViewMethod
+ public Runnable setLayoutColorAsync(int color) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ return () -> setLayoutColor(color);
+ }
+
+ mLayoutColor = color;
+ return NotificationRunnables.NOOP;
+ }
+
+ @RemotableViewMethod(asyncImpl = "setLayoutColorAsync")
public void setLayoutColor(int color) {
mLayoutColor = color;
}
+ /**
+ * async version of {@link ConversationLayout#setIsOneToOne}
+ */
@RemotableViewMethod
+ public Runnable setIsOneToOneAsync(boolean oneToOne) {
+ if (!Flags.conversationStyleSetAvatarAsync()) {
+ return () -> setIsOneToOne(oneToOne);
+ }
+ mIsOneToOne = oneToOne;
+ return NotificationRunnables.NOOP;
+ }
+
+ @RemotableViewMethod(asyncImpl = "setIsOneToOneAsync")
public void setIsOneToOne(boolean oneToOne) {
mIsOneToOne = oneToOne;
}
@@ -1022,6 +1181,125 @@
return person == null ? null : person.getKey() == null ? person.getName() : person.getKey();
}
+ private ConversationHeaderData loadConversationHeaderData(boolean isOneToOne,
+ CharSequence conversationTitle, Icon shortcutIcon, Icon largeIcon,
+ List<MessagingMessage> messages,
+ Person user,
+ List<List<MessagingMessage>> groups, int layoutColor) {
+ Icon conversationIcon = shortcutIcon;
+ CharSequence conversationText = conversationTitle;
+ final CharSequence userKey = getKey(user);
+ if (isOneToOne) {
+ for (int i = messages.size() - 1; i >= 0; i--) {
+ final Notification.MessagingStyle.Message message = messages.get(i).getMessage();
+ final Person sender = message.getSenderPerson();
+ final CharSequence senderKey = getKey(sender);
+ if ((sender != null && senderKey != userKey) || i == 0) {
+ if (conversationText == null || conversationText.length() == 0) {
+ conversationText = sender != null ? sender.getName() : "";
+ }
+ if (conversationIcon == null) {
+ conversationIcon = sender != null ? sender.getIcon()
+ : mPeopleHelper.createAvatarSymbol(conversationText, "",
+ layoutColor);
+ }
+ break;
+ }
+ }
+ }
+
+ if (conversationIcon == null) {
+ conversationIcon = largeIcon;
+ }
+
+ if (isOneToOne || conversationIcon != null) {
+ return new ConversationHeaderData(
+ conversationText,
+ new OneToOneConversationAvatarData(
+ resolveAvatarImage(conversationIcon)));
+ }
+
+ final List<List<Notification.MessagingStyle.Message>> groupMessages = new ArrayList<>();
+ for (int i = 0; i < groups.size(); i++) {
+ final List<Notification.MessagingStyle.Message> groupMessage = new ArrayList<>();
+ for (int j = 0; j < groups.get(i).size(); j++) {
+ groupMessage.add(groups.get(i).get(j).getMessage());
+ }
+ groupMessages.add(groupMessage);
+ }
+
+ final PeopleHelper.NameToPrefixMap nameToPrefixMap =
+ mPeopleHelper.mapUniqueNamesToPrefixWithGroupList(groupMessages);
+
+ Icon lastIcon = null;
+ Icon secondLastIcon = null;
+
+ CharSequence lastKey = null;
+
+ for (int i = groups.size() - 1; i >= 0; i--) {
+ final Notification.MessagingStyle.Message message = groups.get(i).get(0).getMessage();
+ final Person sender =
+ message.getSenderPerson() != null ? message.getSenderPerson() : user;
+ final CharSequence senderKey = getKey(sender);
+ final boolean notUser = senderKey != userKey;
+ final boolean notIncluded = senderKey != lastKey;
+
+ if ((notUser && notIncluded) || (i == 0 && lastKey == null)) {
+ if (lastIcon == null) {
+ if (sender.getIcon() != null) {
+ lastIcon = sender.getIcon();
+ } else {
+ final CharSequence senderName =
+ sender.getName() != null ? sender.getName() : "";
+ lastIcon = mPeopleHelper.createAvatarSymbol(
+ senderName, nameToPrefixMap.getPrefix(senderName),
+ layoutColor);
+ }
+ lastKey = senderKey;
+ } else {
+ if (sender.getIcon() != null) {
+ secondLastIcon = sender.getIcon();
+ } else {
+ final CharSequence senderName =
+ sender.getName() != null ? sender.getName() : "";
+ secondLastIcon = mPeopleHelper.createAvatarSymbol(
+ senderName, nameToPrefixMap.getPrefix(senderName),
+ layoutColor);
+ }
+ break;
+ }
+ }
+ }
+
+ if (lastIcon == null) {
+ lastIcon = mPeopleHelper.createAvatarSymbol(
+ "", "", layoutColor);
+ }
+
+ if (secondLastIcon == null) {
+ secondLastIcon = mPeopleHelper.createAvatarSymbol(
+ "", "", layoutColor);
+ }
+
+ return new ConversationHeaderData(
+ conversationText,
+ new GroupConversationAvatarData(resolveAvatarImage(lastIcon),
+ resolveAvatarImage(secondLastIcon)));
+ }
+
+ /**
+ * {@link ImageResolver#loadImage(Uri)} accepts Uri to load images. However Conversation Avatars
+ * are received as Icon. So, we can't make use of ImageResolver.
+ */
+ @Nullable
+ private Drawable resolveAvatarImage(Icon conversationIcon) {
+ try {
+ return LocalImageResolver.resolveImage(conversationIcon, getContext());
+ } catch (Exception ex) {
+ return null;
+ }
+ }
+
/**
* Creates new messages, reusing existing ones if they are available.
*
diff --git a/core/java/com/android/internal/widget/MessagingData.java b/core/java/com/android/internal/widget/MessagingData.java
index 42de60e..fb1f28f 100644
--- a/core/java/com/android/internal/widget/MessagingData.java
+++ b/core/java/com/android/internal/widget/MessagingData.java
@@ -16,6 +16,7 @@
package com.android.internal.widget;
+import android.annotation.Nullable;
import android.app.Person;
import java.util.List;
@@ -32,6 +33,8 @@
private final List<Person> mSenders;
private final int mUnreadCount;
+ private ConversationHeaderData mConversationHeaderData;
+
MessagingData(Person user, boolean showSpinner,
List<MessagingMessage> historicMessagingMessages,
List<MessagingMessage> newMessagingMessages, List<List<MessagingMessage>> groups,
@@ -39,7 +42,7 @@
this(user, showSpinner, /* unreadCount= */0,
historicMessagingMessages, newMessagingMessages,
groups,
- senders);
+ senders, null);
}
MessagingData(Person user, boolean showSpinner,
@@ -47,7 +50,8 @@
List<MessagingMessage> historicMessagingMessages,
List<MessagingMessage> newMessagingMessages,
List<List<MessagingMessage>> groups,
- List<Person> senders) {
+ List<Person> senders,
+ @Nullable ConversationHeaderData conversationHeaderData) {
mUser = user;
mShowSpinner = showSpinner;
mUnreadCount = unreadCount;
@@ -55,6 +59,7 @@
mNewMessagingMessages = newMessagingMessages;
mGroups = groups;
mSenders = senders;
+ mConversationHeaderData = conversationHeaderData;
}
public Person getUser() {
@@ -84,4 +89,9 @@
public List<List<MessagingMessage>> getGroups() {
return mGroups;
}
+
+ @Nullable
+ public ConversationHeaderData getConversationHeaderData() {
+ return mConversationHeaderData;
+ }
}
diff --git a/core/java/com/android/internal/widget/NotificationRunnables.java b/core/java/com/android/internal/widget/NotificationRunnables.java
new file mode 100644
index 0000000..cb7ae61
--- /dev/null
+++ b/core/java/com/android/internal/widget/NotificationRunnables.java
@@ -0,0 +1,22 @@
+/*
+ * 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.internal.widget;
+
+public final class NotificationRunnables {
+ public static final Runnable NOOP = () -> {
+ };
+}
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 070d07c..5223798 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -18,6 +18,8 @@
//#define LOG_NDEBUG 0
#define LOG_TAG "AudioSystem-JNI"
+#include <android/binder_ibinder_jni.h>
+#include <android/binder_libbinder.h>
#include <android/media/AudioVibratorInfo.h>
#include <android/media/INativeSpatializerCallback.h>
#include <android/media/ISpatializer.h>
@@ -25,6 +27,7 @@
#include <android_media_audiopolicy.h>
#include <android_os_Parcel.h>
#include <audiomanager/AudioManager.h>
+#include <binder/IBinder.h>
#include <jni.h>
#include <media/AidlConversion.h>
#include <media/AudioContainers.h>
@@ -150,13 +153,14 @@
static jclass gAudioMixClass;
static jmethodID gAudioMixCstor;
static struct {
- jfieldID mRule;
- jfieldID mFormat;
- jfieldID mRouteFlags;
- jfieldID mDeviceType;
- jfieldID mDeviceAddress;
- jfieldID mMixType;
- jfieldID mCallbackFlags;
+ jfieldID mRule;
+ jfieldID mFormat;
+ jfieldID mRouteFlags;
+ jfieldID mDeviceType;
+ jfieldID mDeviceAddress;
+ jfieldID mMixType;
+ jfieldID mCallbackFlags;
+ jfieldID mToken;
} gAudioMixFields;
static jclass gAudioFormatClass;
@@ -2300,11 +2304,15 @@
if (status != AUDIO_JAVA_SUCCESS) {
return status;
}
+ std::unique_ptr<AIBinder, decltype(&AIBinder_decStrong)> aiBinder(AIBinder_fromPlatformBinder(
+ nAudioMix.mToken),
+ &AIBinder_decStrong);
+ jobject jBinderToken = AIBinder_toJavaBinder(env, aiBinder.get());
jstring deviceAddress = env->NewStringUTF(nAudioMix.mDeviceAddress.c_str());
*jAudioMix = env->NewObject(gAudioMixClass, gAudioMixCstor, jAudioMixingRule, jAudioFormat,
nAudioMix.mRouteFlags, nAudioMix.mCbFlags, nAudioMix.mDeviceType,
- deviceAddress);
+ deviceAddress, jBinderToken);
return AUDIO_JAVA_SUCCESS;
}
@@ -2333,6 +2341,12 @@
nAudioMix->mVoiceCommunicationCaptureAllowed =
env->GetBooleanField(jRule, gAudioMixingRuleFields.mVoiceCommunicationCaptureAllowed);
+ jobject jToken = env->GetObjectField(jAudioMix, gAudioMixFields.mToken);
+
+ std::unique_ptr<AIBinder, decltype(&AIBinder_decStrong)>
+ aiBinder(AIBinder_fromJavaBinder(env, jToken), &AIBinder_decStrong);
+ nAudioMix->mToken = AIBinder_toPlatformBinder(aiBinder.get());
+
jint status = convertAudioMixingRuleToNative(env, jRule, &(nAudioMix->mCriteria));
env->DeleteLocalRef(jRule);
@@ -3659,9 +3673,10 @@
jclass audioMixClass = FindClassOrDie(env, "android/media/audiopolicy/AudioMix");
gAudioMixClass = MakeGlobalRefOrDie(env, audioMixClass);
if (audio_flags::audio_mix_test_api()) {
- gAudioMixCstor = GetMethodIDOrDie(env, audioMixClass, "<init>",
- "(Landroid/media/audiopolicy/AudioMixingRule;Landroid/"
- "media/AudioFormat;IIILjava/lang/String;)V");
+ gAudioMixCstor =
+ GetMethodIDOrDie(env, audioMixClass, "<init>",
+ "(Landroid/media/audiopolicy/AudioMixingRule;Landroid/"
+ "media/AudioFormat;IIILjava/lang/String;Landroid/os/IBinder;)V");
}
gAudioMixFields.mRule = GetFieldIDOrDie(env, audioMixClass, "mRule",
"Landroid/media/audiopolicy/AudioMixingRule;");
@@ -3673,6 +3688,7 @@
"Ljava/lang/String;");
gAudioMixFields.mMixType = GetFieldIDOrDie(env, audioMixClass, "mMixType", "I");
gAudioMixFields.mCallbackFlags = GetFieldIDOrDie(env, audioMixClass, "mCallbackFlags", "I");
+ gAudioMixFields.mToken = GetFieldIDOrDie(env, audioMixClass, "mToken", "Landroid/os/IBinder;");
jclass audioFormatClass = FindClassOrDie(env, "android/media/AudioFormat");
gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass);
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index c1fd619..48cf09a 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -4409,7 +4409,7 @@
<attr name="requireDeviceScreenOn" format="boolean"/>
<!-- Whether the device should default to observe mode when this service is
default or in the foreground. -->
- <attr name="defaultToObserveMode" format="boolean"/>
+ <attr name="shouldDefaultToObserveMode" format="boolean"/>
</declare-styleable>
<!-- Use <code>offhost-apdu-service</code> as the root tag of the XML resource that
@@ -4436,7 +4436,7 @@
<attr name="requireDeviceScreenOn"/>
<!-- Whether the device should default to observe mode when this service is
default or in the foreground. -->
- <attr name="defaultToObserveMode"/>
+ <attr name="shouldDefaultToObserveMode"/>
</declare-styleable>
<!-- Specify one or more <code>aid-group</code> elements inside a
diff --git a/core/res/res/values/config_telephony.xml b/core/res/res/values/config_telephony.xml
index c87b7cd..5e3e1b0 100644
--- a/core/res/res/values/config_telephony.xml
+++ b/core/res/res/values/config_telephony.xml
@@ -84,7 +84,7 @@
CarrierConfigManager#KEY_AUTO_DATA_SWITCH_RAT_SIGNAL_SCORE_STRING_ARRAY.
If 0, the device always switch to the higher score SIM.
If < 0, the network type and signal strength based auto switch is disabled. -->
- <integer name="auto_data_switch_score_tolerance">4000</integer>
+ <integer name="auto_data_switch_score_tolerance">-1</integer>
<java-symbol type="integer" name="auto_data_switch_score_tolerance" />
<!-- Boolean indicating whether the Iwlan data service supports persistence of iwlan ipsec
diff --git a/core/res/res/values/public-staging.xml b/core/res/res/values/public-staging.xml
index 5987f6e..3303c07 100644
--- a/core/res/res/values/public-staging.xml
+++ b/core/res/res/values/public-staging.xml
@@ -160,7 +160,7 @@
<!-- @FlaggedApi("android.view.inputmethod.connectionless_handwriting") -->
<public name="supportsConnectionlessStylusHandwriting" />
<!-- @FlaggedApi("android.nfc.Flags.FLAG_OBSERVE_MODE") -->
- <public name="defaultToObserveMode"/>
+ <public name="shouldDefaultToObserveMode"/>
<!-- @FlaggedApi("android.security.asm_restrictions_enabled") -->
<public name="allowCrossUidActivitySwitchFromBelow"/>
<!-- @FlaggedApi("com.android.text.flags.use_bounds_for_width") -->
diff --git a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
index 64c17bd..d115bf3 100644
--- a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
+++ b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
@@ -247,7 +247,7 @@
newConfig.smallestScreenWidthDp++;
transaction = newTransaction(activityThread);
transaction.addTransactionItem(ActivityConfigurationChangeItem.obtain(
- activity.getActivityToken(), newConfig));
+ activity.getActivityToken(), newConfig, new ActivityWindowInfo()));
appThread.scheduleTransaction(transaction);
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
@@ -455,11 +455,11 @@
transaction = newTransaction(activityThread);
transaction.addTransactionItem(ActivityConfigurationChangeItem.obtain(
- activity.getActivityToken(), activityConfigLandscape));
+ activity.getActivityToken(), activityConfigLandscape, new ActivityWindowInfo()));
transaction.addTransactionItem(ConfigurationChangeItem.obtain(
processConfigPortrait, DEVICE_ID_INVALID));
transaction.addTransactionItem(ActivityConfigurationChangeItem.obtain(
- activity.getActivityToken(), activityConfigPortrait));
+ activity.getActivityToken(), activityConfigPortrait, new ActivityWindowInfo()));
appThread.scheduleTransaction(transaction);
activity.mTestLatch.await(TIMEOUT_SEC, TimeUnit.SECONDS);
@@ -883,7 +883,7 @@
private static ClientTransaction newActivityConfigTransaction(@NonNull Activity activity,
@NonNull Configuration config) {
final ActivityConfigurationChangeItem item = ActivityConfigurationChangeItem.obtain(
- activity.getActivityToken(), config);
+ activity.getActivityToken(), config, new ActivityWindowInfo());
final ClientTransaction transaction = newTransaction(activity);
transaction.addTransactionItem(item);
diff --git a/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java b/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
index 85a1b4e..4db5d1b 100644
--- a/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
+++ b/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
@@ -107,7 +107,7 @@
@Test
public void testActivityConfigurationChangeItem_getContextToUpdate() {
final ActivityConfigurationChangeItem item = ActivityConfigurationChangeItem
- .obtain(mActivityToken, mConfiguration);
+ .obtain(mActivityToken, mConfiguration, new ActivityWindowInfo());
final Context context = item.getContextToUpdate(mHandler);
assertEquals(mActivity, context);
diff --git a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
index 906558f..31ea675 100644
--- a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
@@ -82,7 +82,8 @@
@Test
public void testRecycleActivityConfigurationChangeItem() {
- testRecycle(() -> ActivityConfigurationChangeItem.obtain(mActivityToken, config()));
+ testRecycle(() -> ActivityConfigurationChangeItem.obtain(mActivityToken, config(),
+ new ActivityWindowInfo()));
}
@Test
diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
index dbb090f..75347bf 100644
--- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
@@ -95,8 +95,11 @@
@Test
public void testActivityConfigChange() {
// Write to parcel
+ final ActivityWindowInfo activityWindowInfo = new ActivityWindowInfo();
+ activityWindowInfo.set(true /* isEmbedded */, new Rect(0, 0, 500, 1000),
+ new Rect(0, 0, 500, 500));
ActivityConfigurationChangeItem item = ActivityConfigurationChangeItem.obtain(
- mActivityToken, config());
+ mActivityToken, config(), activityWindowInfo);
writeAndPrepareForReading(item);
// Read from parcel and assert
@@ -300,7 +303,7 @@
// Write to parcel
NewIntentItem callback1 = NewIntentItem.obtain(mActivityToken, new ArrayList<>(), true);
ActivityConfigurationChangeItem callback2 = ActivityConfigurationChangeItem.obtain(
- mActivityToken, config());
+ mActivityToken, config(), new ActivityWindowInfo());
StopActivityItem lifecycleRequest = StopActivityItem.obtain(mActivityToken,
78 /* configChanges */);
@@ -327,7 +330,7 @@
// Write to parcel
NewIntentItem callback1 = NewIntentItem.obtain(mActivityToken, new ArrayList<>(), true);
ActivityConfigurationChangeItem callback2 = ActivityConfigurationChangeItem.obtain(
- mActivityToken, config());
+ mActivityToken, config(), new ActivityWindowInfo());
ClientTransaction transaction = ClientTransaction.obtain(null /* client */);
transaction.addTransactionItem(callback1);
diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
index 3ee565f..e118c98d 100644
--- a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
+++ b/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
@@ -403,41 +403,4 @@
}
assertFalse(allowed);
}
-
- /** Return true if the path is in the list of strings. */
- private boolean isConcurrent(String path) throws Exception {
- path = new File(path).toPath().toRealPath().toString();
- return SQLiteDatabase.getConcurrentDatabasePaths().contains(path);
- }
-
- @Test
- public void testDuplicateDatabases() throws Exception {
- // The two database paths in this test are assumed not to have been opened earlier in this
- // process.
-
- // A database path that will be opened twice.
- final String dbName = "never-used-db.db";
- final File dbFile = mContext.getDatabasePath(dbName);
- final String dbPath = dbFile.getPath();
-
- // A database path that will be opened only once.
- final String okName = "never-used-ok.db";
- final File okFile = mContext.getDatabasePath(okName);
- final String okPath = okFile.getPath();
-
- SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
- assertFalse(isConcurrent(dbPath));
- SQLiteDatabase db2 = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
- assertTrue(isConcurrent(dbPath));
- db1.close();
- assertTrue(isConcurrent(dbPath));
- db2.close();
- assertTrue(isConcurrent(dbPath));
-
- SQLiteDatabase db3 = SQLiteDatabase.openOrCreateDatabase(okFile, null);
- db3.close();
- db3 = SQLiteDatabase.openOrCreateDatabase(okFile, null);
- assertFalse(isConcurrent(okPath));
- db3.close();
- }
}
diff --git a/core/tests/coretests/src/android/view/ViewRootImplTest.java b/core/tests/coretests/src/android/view/ViewRootImplTest.java
index 7c58de6..1a242ef 100644
--- a/core/tests/coretests/src/android/view/ViewRootImplTest.java
+++ b/core/tests/coretests/src/android/view/ViewRootImplTest.java
@@ -451,7 +451,7 @@
ViewRootImpl viewRootImpl = new ViewRootImpl(sContext, display);
boolean result = viewRootImpl.performHapticFeedback(
- HapticFeedbackConstants.CONTEXT_CLICK, true);
+ HapticFeedbackConstants.CONTEXT_CLICK, true, false /* fromIme */);
assertThat(result).isFalse();
}
diff --git a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
index 51eb41c..b60b806f 100644
--- a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
+++ b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
@@ -472,6 +472,26 @@
}
@Test
+ public void onTouchEvent_doesNothing_viewDisabled() {
+ mTestView1.setEnabled(false);
+
+ final int x1 = (sHwArea1.left + sHwArea1.right) / 2;
+ final int y1 = (sHwArea1.top + sHwArea1.bottom) / 2;
+ MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
+ mHandwritingInitiator.onTouchEvent(stylusEvent1);
+
+ final int x2 = x1 + mHandwritingSlop * 2;
+ final int y2 = y1;
+
+ MotionEvent stylusEvent2 = createStylusEvent(ACTION_MOVE, x2, y2, 0);
+ mHandwritingInitiator.onTouchEvent(stylusEvent2);
+
+ // HandwritingInitiator will not request focus if it is disabled.
+ verify(mTestView1, never()).requestFocus();
+ verify(mHandwritingInitiator, never()).startHandwriting(mTestView1);
+ }
+
+ @Test
public void onTouchEvent_focusView_inputConnectionAlreadyBuilt_stylusMoveOnce_withinHWArea() {
if (!mInitiateWithoutConnection) {
mHandwritingInitiator.onInputConnectionCreated(mTestView1);
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index e8c7a53..0231d3a 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.0",
+ "version": "2.0.0",
"messages": {
"7286191062634870297": {
"message": "Binding proc %s with config %s",
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java b/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
index 62fe54f..ef03d3a 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
@@ -19,9 +19,9 @@
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
-import android.security.KeyStore;
import java.io.IOException;
+import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
@@ -47,13 +47,13 @@
}
/**
- * Gets the {@link KeyStore} operation handle corresponding to the provided JCA crypto
+ * Gets the Android KeyStore operation handle corresponding to the provided JCA crypto
* primitive.
*
* <p>The following primitives are supported: {@link Cipher} and {@link Mac}.
*
- * @return KeyStore operation handle or {@code 0} if the provided primitive's KeyStore operation
- * is not in progress.
+ * @return Android KeyStore operation handle or {@code 0} if the provided primitive's Android
+ * KeyStore operation is not in progress.
*
* @throws IllegalArgumentException if the provided primitive is not supported or is not backed
* by AndroidKeyStore provider.
@@ -67,10 +67,10 @@
}
/**
- * Returns an {@code AndroidKeyStore} {@link java.security.KeyStore}} of the specified UID.
- * The {@code KeyStore} contains keys and certificates owned by that UID. Such cross-UID
- * access is permitted to a few system UIDs and only to a few other UIDs (e.g., Wi-Fi, VPN)
- * all of which are system.
+ * Returns an {@code AndroidKeyStore} {@link KeyStore} of the specified UID. The {@code
+ * KeyStore} contains keys and certificates owned by that UID. Such cross-UID access is
+ * permitted to a few system UIDs and only to a few other UIDs (e.g., Wi-Fi, VPN) all of which
+ * are system.
*
* <p>Note: the returned {@code KeyStore} is already initialized/loaded. Thus, there is
* no need to invoke {@code load} on it.
@@ -84,12 +84,12 @@
*/
@SystemApi
@NonNull
- public static java.security.KeyStore getKeyStoreForUid(int uid)
+ public static KeyStore getKeyStoreForUid(int uid)
throws KeyStoreException, NoSuchProviderException {
- final java.security.KeyStore.LoadStoreParameter loadParameter =
+ final KeyStore.LoadStoreParameter loadParameter =
new android.security.keystore2.AndroidKeyStoreLoadStoreParameter(
KeyProperties.legacyUidToNamespace(uid));
- java.security.KeyStore result = java.security.KeyStore.getInstance(PROVIDER_NAME);
+ KeyStore result = KeyStore.getInstance(PROVIDER_NAME);
try {
result.load(loadParameter);
} catch (NoSuchAlgorithmException | CertificateException | IOException e) {
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index 244fe30..7aecfd8 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -910,7 +910,7 @@
/**
* Returns whether this key is critical to the device encryption flow.
*
- * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
+ * @see Builder#setCriticalToDeviceEncryption(boolean)
* @hide
*/
public boolean isCriticalToDeviceEncryption() {
diff --git a/keystore/java/android/security/keystore/KeyProtection.java b/keystore/java/android/security/keystore/KeyProtection.java
index 2495d1a..31b4a5e 100644
--- a/keystore/java/android/security/keystore/KeyProtection.java
+++ b/keystore/java/android/security/keystore/KeyProtection.java
@@ -569,7 +569,7 @@
/**
* Return whether this key is critical to the device encryption flow.
*
- * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
+ * @see Builder#setCriticalToDeviceEncryption(boolean)
* @hide
*/
public boolean isCriticalToDeviceEncryption() {
@@ -1105,9 +1105,10 @@
* Set whether this key is critical to the device encryption flow
*
* This is a special flag only available to system servers to indicate the current key
- * is part of the device encryption flow.
+ * is part of the device encryption flow. Setting this flag causes the key to not
+ * be cryptographically bound to the LSKF even if the key is otherwise authentication
+ * bound.
*
- * @see android.security.KeyStore#FLAG_CRITICAL_TO_DEVICE_ENCRYPTION
* @hide
*/
public Builder setCriticalToDeviceEncryption(boolean critical) {
diff --git a/keystore/java/android/security/keystore/KeyStoreCryptoOperation.java b/keystore/java/android/security/keystore/KeyStoreCryptoOperation.java
index 2c709ae..c42c9e4 100644
--- a/keystore/java/android/security/keystore/KeyStoreCryptoOperation.java
+++ b/keystore/java/android/security/keystore/KeyStoreCryptoOperation.java
@@ -16,18 +16,16 @@
package android.security.keystore;
-import android.security.KeyStore;
-
/**
- * Cryptographic operation backed by {@link KeyStore}.
+ * Cryptographic operation backed by Android KeyStore.
*
* @hide
*/
public interface KeyStoreCryptoOperation {
/**
- * Gets the KeyStore operation handle of this crypto operation.
+ * Gets the Android KeyStore operation handle of this crypto operation.
*
- * @return handle or {@code 0} if the KeyStore operation is not in progress.
+ * @return handle or {@code 0} if the Android KeyStore operation is not in progress.
*/
long getOperationHandle();
}
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyFactorySpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyFactorySpi.java
index a8dd7f3..8eca67f 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyFactorySpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyFactorySpi.java
@@ -16,7 +16,6 @@
package android.security.keystore2;
-import android.security.KeyStore;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyInfo;
@@ -39,8 +38,6 @@
*/
public class AndroidKeyStoreKeyFactorySpi extends KeyFactorySpi {
- private final KeyStore mKeyStore = KeyStore.getInstance();
-
@Override
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpecClass)
throws InvalidKeySpecException {
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
index d204f13..99100de 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
@@ -17,7 +17,6 @@
package android.security.keystore2;
import android.annotation.NonNull;
-import android.security.KeyStore;
import android.security.KeyStore2;
import android.security.KeyStoreSecurityLevel;
import android.security.keymaster.KeymasterDefs;
@@ -161,13 +160,13 @@
}
/**
- * Gets the {@link KeyStore} operation handle corresponding to the provided JCA crypto
+ * Gets the Android KeyStore operation handle corresponding to the provided JCA crypto
* primitive.
*
* <p>The following primitives are supported: {@link Cipher}, {@link Signature} and {@link Mac}.
*
- * @return KeyStore operation handle or {@code 0} if the provided primitive's KeyStore operation
- * is not in progress.
+ * @return Android KeyStore operation handle or {@code 0} if the provided primitive's Android
+ * KeyStore operation is not in progress.
*
* @throws IllegalArgumentException if the provided primitive is not supported or is not backed
* by AndroidKeyStore provider.
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreSecretKeyFactorySpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreSecretKeyFactorySpi.java
index 2682eb6..2223091 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreSecretKeyFactorySpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreSecretKeyFactorySpi.java
@@ -18,7 +18,6 @@
import android.annotation.NonNull;
import android.security.GateKeeper;
-import android.security.KeyStore;
import android.security.keymaster.KeymasterArguments;
import android.security.keymaster.KeymasterDefs;
import android.security.keystore.KeyGenParameterSpec;
@@ -46,8 +45,6 @@
*/
public class AndroidKeyStoreSecretKeyFactorySpi extends SecretKeyFactorySpi {
- private final KeyStore mKeyStore = KeyStore.getInstance();
-
@Override
protected KeySpec engineGetKeySpec(SecretKey key,
@SuppressWarnings("rawtypes") Class keySpecClass) throws InvalidKeySpecException {
diff --git a/keystore/java/android/security/keystore2/KeyStoreCryptoOperationStreamer.java b/keystore/java/android/security/keystore2/KeyStoreCryptoOperationStreamer.java
index 07d6a69..5bd98bc 100644
--- a/keystore/java/android/security/keystore2/KeyStoreCryptoOperationStreamer.java
+++ b/keystore/java/android/security/keystore2/KeyStoreCryptoOperationStreamer.java
@@ -16,12 +16,11 @@
package android.security.keystore2;
-import android.security.KeyStore;
import android.security.KeyStoreException;
/**
- * Helper for streaming a crypto operation's input and output via {@link KeyStore} service's
- * {@code update} and {@code finish} operations.
+ * Helper for streaming a crypto operation's input and output via KeyStore service's {@code update}
+ * and {@code finish} operations.
*
* <p>The helper abstracts away to issues that need to be solved in most code that uses KeyStore's
* update and finish operations. Firstly, KeyStore's update operation can consume only a limited
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
index 08b7bb8..39cface 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
@@ -201,7 +201,7 @@
return null;
}
return new SplitInfo(primaryActivityStack, secondaryActivityStack,
- mCurrentSplitAttributes, mToken);
+ mCurrentSplitAttributes, SplitInfo.Token.createFromBinder(mToken));
}
static boolean shouldFinishPrimaryWithSecondary(@NonNull SplitRule splitRule) {
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
index ae3a854..038d008 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
@@ -35,6 +35,7 @@
import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED;
import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_VANISHED;
+import static androidx.window.extensions.embedding.ActivityEmbeddingOptionsProperties.KEY_ACTIVITY_STACK_TOKEN;
import static androidx.window.extensions.embedding.ActivityEmbeddingOptionsProperties.KEY_OVERLAY_TAG;
import static androidx.window.extensions.embedding.SplitContainer.getFinishPrimaryWithSecondaryBehavior;
import static androidx.window.extensions.embedding.SplitContainer.getFinishSecondaryWithPrimaryBehavior;
@@ -112,10 +113,6 @@
static final boolean ENABLE_SHELL_TRANSITIONS =
SystemProperties.getBoolean("persist.wm.debug.shell_transit", true);
- // TODO(b/295993745): remove after prebuilt library is updated.
- private static final String KEY_ACTIVITY_STACK_TOKEN =
- "androidx.window.extensions.embedding.ActivityStackToken";
-
@VisibleForTesting
@GuardedBy("mLock")
final SplitPresenter mPresenter;
@@ -554,7 +551,7 @@
}
@Override
- public void updateActivityStackAttributes(@NonNull IBinder activityStackToken,
+ public void updateActivityStackAttributes(@NonNull ActivityStack.Token activityStackToken,
@NonNull ActivityStackAttributes attributes) {
if (!Flags.activityEmbeddingOverlayPresentationFlag()) {
return;
@@ -563,7 +560,7 @@
Objects.requireNonNull(attributes);
synchronized (mLock) {
- final TaskFragmentContainer container = getContainer(activityStackToken);
+ final TaskFragmentContainer container = getContainer(activityStackToken.getRawToken());
if (container == null) {
Log.w(TAG, "Cannot find TaskFragmentContainer for token:" + activityStackToken);
return;
@@ -583,13 +580,14 @@
@Override
@Nullable
- public ParentContainerInfo getParentContainerInfo(@NonNull IBinder activityStackToken) {
+ public ParentContainerInfo getParentContainerInfo(
+ @NonNull ActivityStack.Token activityStackToken) {
if (!Flags.activityEmbeddingOverlayPresentationFlag()) {
return null;
}
Objects.requireNonNull(activityStackToken);
synchronized (mLock) {
- final TaskFragmentContainer container = getContainer(activityStackToken);
+ final TaskFragmentContainer container = getContainer(activityStackToken.getRawToken());
if (container == null) {
return null;
}
@@ -601,7 +599,7 @@
@Override
@Nullable
- public IBinder getActivityStackToken(@NonNull String tag) {
+ public ActivityStack.Token getActivityStackToken(@NonNull String tag) {
if (!Flags.activityEmbeddingOverlayPresentationFlag()) {
return null;
}
@@ -612,7 +610,8 @@
if (taskFragmentContainer == null) {
return null;
}
- return taskFragmentContainer.getTaskFragmentToken();
+ return ActivityStack.Token.createFromBinder(taskFragmentContainer
+ .getTaskFragmentToken());
}
}
@@ -2761,8 +2760,10 @@
// TODO(b/232042367): Consolidate the activity create handling so that we can handle
// cross-process the same as normal.
- IBinder activityStackToken = options.getBinder(KEY_ACTIVITY_STACK_TOKEN);
- if (activityStackToken != null) {
+ final Bundle bundle = options.getBundle(KEY_ACTIVITY_STACK_TOKEN);
+ if (bundle != null) {
+ final IBinder activityStackToken = ActivityStack.Token.readFromBundle(bundle)
+ .getRawToken();
// Put activityStack token to #KEY_LAUNCH_TASK_FRAGMENT_TOKEN to launch the activity
// into the taskFragment associated with the token.
options.putBinder(KEY_LAUNCH_TASK_FRAGMENT_TOKEN, activityStackToken);
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
index 6fe8e50..a6bf99d 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
@@ -367,7 +367,8 @@
if (activities == null) {
return null;
}
- return new ActivityStack(activities, isEmpty(), mToken, mOverlayTag);
+ return new ActivityStack(activities, isEmpty(),
+ ActivityStack.Token.createFromBinder(mToken), mOverlayTag);
}
/** Adds the activity that will be reparented to this container. */
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/OverlayPresentationTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/OverlayPresentationTest.java
index 34d43ad..28fbadb 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/OverlayPresentationTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/OverlayPresentationTest.java
@@ -399,7 +399,8 @@
new ActivityStackAttributes.Builder().build()));
assertThrows(NullPointerException.class, () ->
- mSplitController.updateActivityStackAttributes(new Binder(), null));
+ mSplitController.updateActivityStackAttributes(
+ ActivityStack.Token.createFromBinder(new Binder()), null));
verify(mSplitPresenter, never()).applyActivityStackAttributes(any(), any(), any(), any());
}
@@ -408,7 +409,8 @@
public void testUpdateActivityStackAttributes_nullContainer_earlyReturn() {
final TaskFragmentContainer container = mSplitController.newContainer(mActivity,
mActivity.getTaskId());
- mSplitController.updateActivityStackAttributes(container.getTaskFragmentToken(),
+ mSplitController.updateActivityStackAttributes(
+ ActivityStack.Token.createFromBinder(container.getTaskFragmentToken()),
new ActivityStackAttributes.Builder().build());
verify(mSplitPresenter, never()).applyActivityStackAttributes(any(), any(), any(), any());
@@ -418,7 +420,8 @@
public void testUpdateActivityStackAttributes_notOverlay_earlyReturn() {
final TaskFragmentContainer container = createMockTaskFragmentContainer(mActivity);
- mSplitController.updateActivityStackAttributes(container.getTaskFragmentToken(),
+ mSplitController.updateActivityStackAttributes(
+ ActivityStack.Token.createFromBinder(container.getTaskFragmentToken()),
new ActivityStackAttributes.Builder().build());
verify(mSplitPresenter, never()).applyActivityStackAttributes(any(), any(), any(), any());
@@ -431,7 +434,8 @@
final ActivityStackAttributes attrs = new ActivityStackAttributes.Builder().build();
final IBinder token = container.getTaskFragmentToken();
- mSplitController.updateActivityStackAttributes(token, attrs);
+ mSplitController.updateActivityStackAttributes(ActivityStack.Token.createFromBinder(token),
+ attrs);
verify(mSplitPresenter).applyActivityStackAttributes(any(), eq(container), eq(attrs),
any());
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
index b60943a..00f8b59 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
@@ -1437,7 +1437,7 @@
@Test
public void testUpdateSplitAttributes_nullParams_throwException() {
assertThrows(NullPointerException.class,
- () -> mSplitController.updateSplitAttributes(null, SPLIT_ATTRIBUTES));
+ () -> mSplitController.updateSplitAttributes((IBinder) null, SPLIT_ATTRIBUTES));
final SplitContainer splitContainer = mock(SplitContainer.class);
final IBinder token = new Binder();
diff --git a/libs/WindowManager/Shell/aconfig/multitasking.aconfig b/libs/WindowManager/Shell/aconfig/multitasking.aconfig
index 0967f4e..b61dda4 100644
--- a/libs/WindowManager/Shell/aconfig/multitasking.aconfig
+++ b/libs/WindowManager/Shell/aconfig/multitasking.aconfig
@@ -8,14 +8,6 @@
}
flag {
- name: "enable_desktop_windowing"
- namespace: "multitasking"
- description: "Enables desktop windowing"
- bug: "304778354"
- is_fixed_read_only: true
-}
-
-flag {
name: "enable_split_contextual"
namespace: "multitasking"
description: "Enables invoking split contextually"
diff --git a/libs/WindowManager/Shell/res/layout/desktop_mode_app_controls_window_decor.xml b/libs/WindowManager/Shell/res/layout/desktop_mode_app_controls_window_decor.xml
index d1b1af3..490f088 100644
--- a/libs/WindowManager/Shell/res/layout/desktop_mode_app_controls_window_decor.xml
+++ b/libs/WindowManager/Shell/res/layout/desktop_mode_app_controls_window_decor.xml
@@ -16,6 +16,7 @@
-->
<com.android.wm.shell.windowdecor.WindowDecorLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/desktop_mode_caption"
android:layout_width="match_parent"
@@ -27,6 +28,8 @@
android:id="@+id/open_menu_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
+ android:tint="?androidprv:attr/materialColorOnSurface"
+ android:background="?android:selectableItemBackground"
android:orientation="horizontal"
android:clickable="true"
android:focusable="true"
@@ -78,7 +81,9 @@
android:id="@+id/maximize_button_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_gravity="end"/>
+ android:layout_gravity="end"
+ android:clickable="true"
+ android:focusable="true" />
<ImageButton
android:id="@+id/close_window"
@@ -86,9 +91,10 @@
android:layout_height="40dp"
android:padding="4dp"
android:layout_marginEnd="8dp"
+ android:tint="?androidprv:attr/materialColorOnSurface"
+ android:background="?android:selectableItemBackgroundBorderless"
android:contentDescription="@string/close_button_text"
android:src="@drawable/decor_close_button_dark"
android:scaleType="fitCenter"
- android:gravity="end"
- android:background="@null"/>
+ android:gravity="end"/>
</com.android.wm.shell.windowdecor.WindowDecorLinearLayout>
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/res/layout/maximize_menu_button.xml b/libs/WindowManager/Shell/res/layout/maximize_menu_button.xml
index bb6efce..e0057fe 100644
--- a/libs/WindowManager/Shell/res/layout/maximize_menu_button.xml
+++ b/libs/WindowManager/Shell/res/layout/maximize_menu_button.xml
@@ -14,7 +14,8 @@
~ limitations under the License.
-->
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
+<merge xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
<ProgressBar
android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
@@ -30,7 +31,8 @@
android:layout_height="40dp"
android:padding="9dp"
android:contentDescription="@string/maximize_button_text"
+ android:tint="?androidprv:attr/materialColorOnSurface"
+ android:background="?android:selectableItemBackgroundBorderless"
android:src="@drawable/decor_desktop_mode_maximize_button_dark"
- android:scaleType="fitCenter"
- android:background="@drawable/rounded_button"/>
+ android:scaleType="fitCenter" />
</merge>
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/res/values/dimen.xml b/libs/WindowManager/Shell/res/values/dimen.xml
index cbfa74e..48e6428 100644
--- a/libs/WindowManager/Shell/res/values/dimen.xml
+++ b/libs/WindowManager/Shell/res/values/dimen.xml
@@ -101,6 +101,10 @@
<dimen name="split_divider_bar_width">10dp</dimen>
<dimen name="split_divider_corner_size">42dp</dimen>
+ <!-- The distance from the edge of the screen to invoke splitscreen when the user is dragging
+ an intent that can be launched into split. -->
+ <dimen name="drag_launchable_intent_edge_margin">48dp</dimen>
+
<!-- One-Handed Mode -->
<!-- Threshold for dragging distance to enable one-handed mode -->
<dimen name="gestures_onehanded_drag_threshold">20dp</dimen>
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/ProtoLogController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/ProtoLogController.java
index 93893e3..ef9bf00 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/ProtoLogController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/ProtoLogController.java
@@ -51,7 +51,7 @@
final ILogger logger = pw::println;
switch (args[0]) {
case "status": {
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
pw.println("(Deprecated) legacy command. Use Perfetto commands instead.");
return false;
}
@@ -59,7 +59,7 @@
return true;
}
case "start": {
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
pw.println("(Deprecated) legacy command. Use Perfetto commands instead.");
return false;
}
@@ -67,7 +67,7 @@
return true;
}
case "stop": {
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
pw.println("(Deprecated) legacy command. Use Perfetto commands instead.");
return false;
}
@@ -101,7 +101,7 @@
return mShellProtoLog.stopLoggingToLogcat(groups, logger) == 0;
}
case "save-for-bugreport": {
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
pw.println("(Deprecated) legacy command");
return false;
}
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 15350fb..96aaf02 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
@@ -1799,11 +1799,12 @@
@Override
public void removeBubble(Bubble removedBubble) {
if (mLayerView != null) {
- mLayerView.removeBubble(removedBubble);
- if (!mBubbleData.hasBubbles() && !isStackExpanded()) {
- mLayerView.setVisibility(INVISIBLE);
- removeFromWindowManagerMaybe();
- }
+ mLayerView.removeBubble(removedBubble, () -> {
+ if (!mBubbleData.hasBubbles() && !isStackExpanded()) {
+ mLayerView.setVisibility(INVISIBLE);
+ removeFromWindowManagerMaybe();
+ }
+ });
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
index 78a41f7..42799d9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
@@ -242,13 +242,17 @@
}
/** Removes the given {@code bubble}. */
- public void removeBubble(Bubble bubble) {
+ public void removeBubble(Bubble bubble, Runnable endAction) {
+ Runnable cleanUp = () -> {
+ bubble.cleanupViews();
+ endAction.run();
+ };
if (mBubbleData.getBubbles().isEmpty()) {
// we're removing the last bubble. collapse the expanded view and cleanup bubble views
// at the end.
- collapse(bubble::cleanupViews);
+ collapse(cleanUp);
} else {
- bubble.cleanupViews();
+ cleanUp.run();
}
}
@@ -264,6 +268,9 @@
*/
public void collapse(@Nullable Runnable endAction) {
if (!mIsExpanded) {
+ if (endAction != null) {
+ endAction.run();
+ }
return;
}
mIsExpanded = false;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
index f801b0d..a87116e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
@@ -75,7 +75,6 @@
private SurfaceControlViewHost mViewHost;
private DividerHandleView mHandle;
private DividerRoundedCorner mCorners;
- private View mBackground;
private int mTouchElevation;
private VelocityTracker mVelocityTracker;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
index 2b10377..194eb47 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
@@ -277,7 +277,7 @@
}
@Override
- public void onAnimationEnd(@androidx.annotation.NonNull Animator animation) {
+ public void onAnimationEnd(@NonNull Animator animation) {
mRunningAnimationCount--;
animT.remove(mScreenshot);
animT.apply();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMode.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMode.java
index 8305fa6..1071d72 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMode.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopMode.java
@@ -51,4 +51,6 @@
/** Called when requested to go to desktop mode from the current focused app. */
void enterDesktop(int displayId);
+ /** Called when requested to go to fullscreen from the current focused desktop app. */
+ void moveFocusedTaskToFullscreen(int displayId);
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java
index 88949b2a..22ba708 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java
@@ -18,21 +18,13 @@
import android.os.SystemProperties;
-import com.android.wm.shell.Flags;
+import com.android.window.flags.Flags;
/**
* Constants for desktop mode feature
*/
public class DesktopModeStatus {
- private static final boolean ENABLE_DESKTOP_WINDOWING = Flags.enableDesktopWindowing();
-
- /**
- * Flag to indicate whether desktop mode proto is available on the device
- */
- private static final boolean IS_PROTO2_ENABLED = SystemProperties.getBoolean(
- "persist.wm.debug.desktop_mode_2", false);
-
/**
* Flag to indicate whether task resizing is veiled.
*/
@@ -75,16 +67,10 @@
"persist.wm.debug.desktop_use_rounded_corners", true);
/**
- * Return {@code true} is desktop windowing proto 2 is enabled
+ * Return {@code true} if desktop windowing is enabled
*/
public static boolean isEnabled() {
- // Check for aconfig flag first
- if (ENABLE_DESKTOP_WINDOWING) {
- return true;
- }
- // Fall back to sysprop flag
- // TODO(b/304778354): remove sysprop once desktop aconfig flag supports dynamic overriding
- return IS_PROTO2_ENABLED;
+ return Flags.enableDesktopWindowingMode();
}
/**
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 dcffb2d..b9d0342 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
@@ -381,6 +381,18 @@
}
}
+ /** Enter fullscreen by moving the focused freeform task in given `displayId` to fullscreen. */
+ fun enterFullscreen(displayId: Int) {
+ if (DesktopModeStatus.isEnabled()) {
+ shellTaskOrganizer
+ .getRunningTasks(displayId)
+ .find { taskInfo ->
+ taskInfo.isFocused && taskInfo.windowingMode == WINDOWING_MODE_FREEFORM
+ }
+ ?.let { moveToFullscreenWithAnimation(it, it.positionInParent) }
+ }
+ }
+
/** Move a desktop app to split screen. */
fun moveToSplit(task: RunningTaskInfo) {
KtProtoLog.v(
@@ -1108,6 +1120,12 @@
this@DesktopTasksController.enterDesktop(displayId)
}
}
+
+ override fun moveFocusedTaskToFullscreen(displayId: Int) {
+ mainExecutor.execute {
+ this@DesktopTasksController.enterFullscreen(displayId)
+ }
+ }
}
/** The interface for calls from outside the host process. */
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
index 1afbdf9..7da1b23 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
@@ -59,7 +59,6 @@
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
-import com.android.internal.logging.InstanceId;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.protolog.common.ProtoLog;
import com.android.launcher3.icons.IconProvider;
@@ -316,12 +315,11 @@
return false;
}
// TODO(b/290391688): Also update the session data with task stack changes
- InstanceId loggerSessionId = mLogger.logStart(event);
- pd.activeDragCount++;
- pd.dragSession = new DragSession(mContext, ActivityTaskManager.getInstance(),
+ pd.dragSession = new DragSession(ActivityTaskManager.getInstance(),
mDisplayController.getDisplayLayout(displayId), event.getClipData());
pd.dragSession.update();
- pd.dragLayout.prepare(pd.dragSession, loggerSessionId);
+ pd.activeDragCount++;
+ pd.dragLayout.prepare(pd.dragSession, mLogger.logStart(pd.dragSession));
setDropTargetWindowVisibility(pd, View.VISIBLE);
notifyListeners(l -> {
l.onDragStarted();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
index 2a7dd5a..75b126c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
@@ -53,17 +53,21 @@
/**
* Logs the start of a drag.
*/
- public InstanceId logStart(DragEvent event) {
- final ClipDescription description = event.getClipDescription();
- final ClipData data = event.getClipData();
- final ClipData.Item item = data.getItemAt(0);
- mInstanceId = item.getIntent().getParcelableExtra(
- ClipDescription.EXTRA_LOGGING_INSTANCE_ID);
+ public InstanceId logStart(DragSession session) {
+ mInstanceId = session.appData != null
+ ? session.appData.getParcelableExtra(ClipDescription.EXTRA_LOGGING_INSTANCE_ID,
+ InstanceId.class)
+ : null;
if (mInstanceId == null) {
mInstanceId = mIdSequence.newInstanceId();
}
- mActivityInfo = item.getActivityInfo();
- log(getStartEnum(description), mActivityInfo);
+ mActivityInfo = session.activityInfo;
+ if (session.appData != null) {
+ log(getStartEnum(session.getClipDescription()), mActivityInfo);
+ } else {
+ // TODO(b/255649902): Update this once we have a new enum
+ log(DragAndDropUiEventEnum.GLOBAL_APP_DRAG_START_ACTIVITY, mActivityInfo);
+ }
return mInstanceId;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
index a31a773..eb82da8 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
@@ -29,6 +29,8 @@
import static android.content.Intent.EXTRA_SHORTCUT_ID;
import static android.content.Intent.EXTRA_TASK_ID;
import static android.content.Intent.EXTRA_USER;
+import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
@@ -52,9 +54,11 @@
import android.graphics.Insets;
import android.graphics.Rect;
import android.graphics.RectF;
+import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
+import android.util.Log;
import android.util.Slog;
import androidx.annotation.IntDef;
@@ -63,8 +67,10 @@
import androidx.annotation.VisibleForTesting;
import com.android.internal.logging.InstanceId;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.wm.shell.R;
import com.android.wm.shell.common.split.SplitScreenConstants.SplitPosition;
+import com.android.wm.shell.protolog.ShellProtoLogGroup;
import com.android.wm.shell.splitscreen.SplitScreenController;
import java.lang.annotation.Retention;
@@ -104,7 +110,9 @@
void start(DragSession session, InstanceId loggerSessionId) {
mLoggerSessionId = loggerSessionId;
mSession = session;
- RectF disallowHitRegion = (RectF) mSession.dragData.getExtra(EXTRA_DISALLOW_HIT_REGION);
+ RectF disallowHitRegion = mSession.appData != null
+ ? (RectF) mSession.appData.getExtra(EXTRA_DISALLOW_HIT_REGION)
+ : null;
if (disallowHitRegion == null) {
mDisallowHitRegion.setEmpty();
} else {
@@ -223,7 +231,7 @@
}
@VisibleForTesting
- void handleDrop(Target target, ClipData data) {
+ void handleDrop(Target target) {
if (target == null || !mTargets.contains(target)) {
return;
}
@@ -238,41 +246,77 @@
mSplitScreen.onDroppedToSplit(position, mLoggerSessionId);
}
- final ClipDescription description = data.getDescription();
- final Intent dragData = mSession.dragData;
- startClipDescription(description, dragData, position);
+ if (mSession.appData != null) {
+ launchApp(mSession, position);
+ } else {
+ launchIntent(mSession, position);
+ }
}
- private void startClipDescription(ClipDescription description, Intent intent,
- @SplitPosition int position) {
+ /**
+ * Launches an app provided by SysUI.
+ */
+ private void launchApp(DragSession session, @SplitPosition int position) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP, "Launching app data at position=%d",
+ position);
+ final ClipDescription description = session.getClipDescription();
final boolean isTask = description.hasMimeType(MIMETYPE_APPLICATION_TASK);
final boolean isShortcut = description.hasMimeType(MIMETYPE_APPLICATION_SHORTCUT);
final ActivityOptions baseActivityOpts = ActivityOptions.makeBasic();
baseActivityOpts.setDisallowEnterPictureInPictureWhileLaunching(true);
final Bundle opts = baseActivityOpts.toBundle();
- if (intent.hasExtra(EXTRA_ACTIVITY_OPTIONS)) {
- opts.putAll(intent.getBundleExtra(EXTRA_ACTIVITY_OPTIONS));
+ if (session.appData.hasExtra(EXTRA_ACTIVITY_OPTIONS)) {
+ opts.putAll(session.appData.getBundleExtra(EXTRA_ACTIVITY_OPTIONS));
}
// Put BAL flags to avoid activity start aborted.
opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED, true);
opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED_BY_PERMISSION, true);
- final UserHandle user = intent.getParcelableExtra(EXTRA_USER);
+ final UserHandle user = session.appData.getParcelableExtra(EXTRA_USER);
if (isTask) {
- final int taskId = intent.getIntExtra(EXTRA_TASK_ID, INVALID_TASK_ID);
+ final int taskId = session.appData.getIntExtra(EXTRA_TASK_ID, INVALID_TASK_ID);
mStarter.startTask(taskId, position, opts);
} else if (isShortcut) {
- final String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME);
- final String id = intent.getStringExtra(EXTRA_SHORTCUT_ID);
+ final String packageName = session.appData.getStringExtra(EXTRA_PACKAGE_NAME);
+ final String id = session.appData.getStringExtra(EXTRA_SHORTCUT_ID);
mStarter.startShortcut(packageName, id, position, opts, user);
} else {
- final PendingIntent launchIntent = intent.getParcelableExtra(EXTRA_PENDING_INTENT);
+ final PendingIntent launchIntent =
+ session.appData.getParcelableExtra(EXTRA_PENDING_INTENT);
+ if (Build.IS_DEBUGGABLE) {
+ if (!user.equals(launchIntent.getCreatorUserHandle())) {
+ Log.e(TAG, "Expected app intent's EXTRA_USER to match pending intent user");
+ }
+ }
mStarter.startIntent(launchIntent, user.getIdentifier(), null /* fillIntent */,
position, opts);
}
}
/**
+ * Launches an intent sender provided by an application.
+ */
+ private void launchIntent(DragSession session, @SplitPosition int position) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP, "Launching intent at position=%d",
+ position);
+ final ActivityOptions baseActivityOpts = ActivityOptions.makeBasic();
+ baseActivityOpts.setDisallowEnterPictureInPictureWhileLaunching(true);
+ // TODO(b/255649902): Rework this so that SplitScreenController can always use the options
+ // instead of a fillInIntent since it's assuming that the PendingIntent is mutable
+ baseActivityOpts.setPendingIntentLaunchFlags(FLAG_ACTIVITY_NEW_TASK
+ | FLAG_ACTIVITY_MULTIPLE_TASK);
+
+ final Bundle opts = baseActivityOpts.toBundle();
+ // Put BAL flags to avoid activity start aborted.
+ opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED, true);
+ opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED_BY_PERMISSION, true);
+
+ mStarter.startIntent(session.launchableIntent,
+ session.launchableIntent.getCreatorUserHandle().getIdentifier(),
+ null /* fillIntent */, position, opts);
+ }
+
+ /**
* Interface for actually committing the task launches.
*/
public interface Starter {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
index 619f624..ecb53dc 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
@@ -22,6 +22,8 @@
import static android.content.pm.ActivityInfo.CONFIG_ASSETS_PATHS;
import static android.content.pm.ActivityInfo.CONFIG_UI_MODE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
+import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
@@ -38,12 +40,15 @@
import android.app.StatusBarManager;
import android.content.Context;
import android.content.res.Configuration;
+import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Insets;
import android.graphics.Rect;
+import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.DragEvent;
import android.view.SurfaceControl;
+import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowInsets.Type;
import android.widget.LinearLayout;
@@ -65,7 +70,8 @@
/**
* Coordinates the visible drop targets for the current drag within a single display.
*/
-public class DragLayout extends LinearLayout {
+public class DragLayout extends LinearLayout
+ implements ViewTreeObserver.OnComputeInternalInsetsListener {
// While dragging the status bar is hidden.
private static final int HIDE_STATUS_BAR_FLAGS = StatusBarManager.DISABLE_NOTIFICATION_ICONS
@@ -90,7 +96,9 @@
private int mDisplayMargin;
private int mDividerSize;
+ private int mLaunchIntentEdgeMargin;
private Insets mInsets = Insets.NONE;
+ private Region mTouchableRegion;
private boolean mIsShowing;
private boolean mHasDropped;
@@ -106,10 +114,11 @@
mStatusBarManager = context.getSystemService(StatusBarManager.class);
mLastConfiguration.setTo(context.getResources().getConfiguration());
- mDisplayMargin = context.getResources().getDimensionPixelSize(
- R.dimen.drop_layout_display_margin);
- mDividerSize = context.getResources().getDimensionPixelSize(
- R.dimen.split_divider_bar_width);
+ final Resources res = context.getResources();
+ mDisplayMargin = res.getDimensionPixelSize(R.dimen.drop_layout_display_margin);
+ mDividerSize = res.getDimensionPixelSize(R.dimen.split_divider_bar_width);
+ mLaunchIntentEdgeMargin =
+ res.getDimensionPixelSize(R.dimen.drag_launchable_intent_edge_margin);
// Always use LTR because we assume dropZoneView1 is on the left and 2 is on the right when
// showing the highlight.
@@ -131,6 +140,66 @@
}
@Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ mTouchableRegion = Region.obtain();
+ getViewTreeObserver().addOnComputeInternalInsetsListener(this);
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
+ mTouchableRegion.recycle();
+ }
+
+ @Override
+ public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo inOutInfo) {
+ if (mSession != null && mSession.launchableIntent != null) {
+ inOutInfo.touchableRegion.set(mTouchableRegion);
+ inOutInfo.setTouchableInsets(TOUCHABLE_INSETS_REGION);
+ }
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int l, int t, int r, int b) {
+ super.onLayout(changed, l, t, r, b);
+ updateTouchableRegion();
+ }
+
+ /**
+ * Updates the touchable region, this should be called after any configuration changes have
+ * been applied.
+ */
+ private void updateTouchableRegion() {
+ mTouchableRegion.setEmpty();
+ if (mSession != null && mSession.launchableIntent != null) {
+ final int width = getMeasuredWidth();
+ final int height = getMeasuredHeight();
+ if (mIsLeftRightSplit) {
+ mTouchableRegion.union(
+ new Rect(0, 0, mInsets.left + mLaunchIntentEdgeMargin, height));
+ mTouchableRegion.union(
+ new Rect(width - mInsets.right - mLaunchIntentEdgeMargin, 0, width,
+ height));
+ } else {
+ mTouchableRegion.union(
+ new Rect(0, 0, width, mInsets.top + mLaunchIntentEdgeMargin));
+ mTouchableRegion.union(
+ new Rect(0, height - mInsets.bottom - mLaunchIntentEdgeMargin, width,
+ height));
+ }
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP,
+ "Updating drag layout width=%d height=%d touchable region=%s",
+ width, height, mTouchableRegion);
+
+ // Reapply insets to update the touchable region
+ requestApplyInsets();
+ }
+ }
+
+
+ @Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
mInsets = insets.getInsets(Type.tappableElement() | Type.displayCutout());
recomputeDropTargets();
@@ -164,6 +233,7 @@
mDropZoneView2.onThemeChange();
}
mLastConfiguration.setTo(newConfig);
+ requestLayout();
}
private void updateContainerMarginsForSingleTask() {
@@ -242,6 +312,7 @@
mSplitScreenController.getStageBounds(topOrLeftBounds, bottomOrRightBounds);
updateDropZoneSizes(topOrLeftBounds, bottomOrRightBounds);
}
+ requestLayout();
}
private void updateDropZoneSizesForSingleTask() {
@@ -392,7 +463,7 @@
mHasDropped = true;
// Process the drop
- mPolicy.handleDrop(mCurrentTarget, event.getClipData());
+ mPolicy.handleDrop(mCurrentTarget);
// Start animating the drop UI out with the drag surface
hide(event, dropCompleteCallback);
@@ -505,5 +576,7 @@
pw.println(innerPrefix + "mIsShowing=" + mIsShowing);
pw.println(innerPrefix + "mHasDropped=" + mHasDropped);
pw.println(innerPrefix + "mCurrentTarget=" + mCurrentTarget);
+ pw.println(innerPrefix + "mInsets=" + mInsets);
+ pw.println(innerPrefix + "mTouchableRegion=" + mTouchableRegion);
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
index 353d702..8f1bc59 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
@@ -21,12 +21,15 @@
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
+import android.app.PendingIntent;
import android.app.WindowConfiguration;
import android.content.ClipData;
-import android.content.Context;
+import android.content.ClipDescription;
import android.content.Intent;
import android.content.pm.ActivityInfo;
+import androidx.annotation.Nullable;
+
import com.android.wm.shell.common.DisplayLayout;
import java.util.List;
@@ -39,7 +42,18 @@
private final ClipData mInitialDragData;
final DisplayLayout displayLayout;
- Intent dragData;
+ // The activity info associated with the activity in the appData or the launchableIntent
+ @Nullable
+ ActivityInfo activityInfo;
+ // The intent bundle that includes data about an app-type drag that is started by
+ // Launcher/SysUI. Only one of appDragData OR launchableIntent will be non-null for a session.
+ @Nullable
+ Intent appData;
+ // A launchable intent that is specified in the ClipData directly.
+ // Only one of appDragData OR launchableIntent will be non-null for a session.
+ @Nullable
+ PendingIntent launchableIntent;
+ // Stores the current running task at the time that the drag was initiated
ActivityManager.RunningTaskInfo runningTaskInfo;
@WindowConfiguration.WindowingMode
int runningTaskWinMode = WINDOWING_MODE_UNDEFINED;
@@ -47,7 +61,7 @@
int runningTaskActType = ACTIVITY_TYPE_STANDARD;
boolean dragItemSupportsSplitscreen;
- DragSession(Context context, ActivityTaskManager activityTaskManager,
+ DragSession(ActivityTaskManager activityTaskManager,
DisplayLayout dispLayout, ClipData data) {
mActivityTaskManager = activityTaskManager;
mInitialDragData = data;
@@ -55,6 +69,14 @@
}
/**
+ * Returns the clip description associated with the drag.
+ * @return
+ */
+ ClipDescription getClipDescription() {
+ return mInitialDragData.getDescription();
+ }
+
+ /**
* Updates the session data based on the current state of the system.
*/
void update() {
@@ -67,9 +89,11 @@
runningTaskActType = task.getActivityType();
}
- final ActivityInfo info = mInitialDragData.getItemAt(0).getActivityInfo();
- dragItemSupportsSplitscreen = info == null
- || ActivityInfo.isResizeableMode(info.resizeMode);
- dragData = mInitialDragData.getItemAt(0).getIntent();
+ activityInfo = mInitialDragData.getItemAt(0).getActivityInfo();
+ // TODO: This should technically check & respect config_supportsNonResizableMultiWindow
+ dragItemSupportsSplitscreen = activityInfo == null
+ || ActivityInfo.isResizeableMode(activityInfo.resizeMode);
+ appData = mInitialDragData.getItemAt(0).getIntent();
+ launchableIntent = DragUtils.getLaunchIntent(mInitialDragData);
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
index f7bcc94..24f8e18 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
@@ -36,8 +36,21 @@
* Returns whether we can handle this particular drag.
*/
public static boolean canHandleDrag(DragEvent event) {
- return event.getClipData().getItemCount() > 0
- && (isAppDrag(event.getClipDescription()));
+ if (event.getClipData().getItemCount() <= 0) {
+ // No clip data, ignore this drag
+ return false;
+ }
+ if (isAppDrag(event.getClipDescription())) {
+ // Clip data contains an app drag initiated from SysUI, handle it
+ return true;
+ }
+ if (com.android.window.flags.Flags.delegateUnhandledDrags()
+ && getLaunchIntent(event) != null) {
+ // Clip data contains a launchable intent drag, handle it
+ return true;
+ }
+ // Otherwise ignore
+ return false;
}
/**
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 e421356..1c54754 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
@@ -163,14 +163,14 @@
/**
* Adds a split pair. This call does not validate the taskIds, only that they are not the same.
*/
- public void addSplitPair(int taskId1, int taskId2, SplitBounds splitBounds) {
+ public boolean addSplitPair(int taskId1, int taskId2, SplitBounds splitBounds) {
if (taskId1 == taskId2) {
- return;
+ return false;
}
if (mSplitTasks.get(taskId1, INVALID_TASK_ID) == taskId2
&& mTaskSplitBoundsMap.get(taskId1).equals(splitBounds)) {
// If the two tasks are already paired and the bounds are the same, then skip updating
- return;
+ return false;
}
// Remove any previous pairs
removeSplitPair(taskId1);
@@ -185,6 +185,7 @@
notifyRecentTasksChanged();
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENT_TASKS, "Add split pair: %d, %d, %s",
taskId1, taskId2, splitBounds);
+ return true;
}
/**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/MainStage.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/MainStage.java
index e52235f..64e26db 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/MainStage.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/MainStage.java
@@ -16,11 +16,14 @@
package com.android.wm.shell.splitscreen;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN;
+
import android.content.Context;
import android.view.SurfaceSession;
import android.window.WindowContainerToken;
import android.window.WindowContainerTransaction;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.launcher3.icons.IconProvider;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.SyncTransactionQueue;
@@ -50,6 +53,8 @@
void activate(WindowContainerTransaction wct, boolean includingTopTask) {
if (mIsActive) return;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "activate: main stage includingTopTask=%b",
+ includingTopTask);
if (includingTopTask) {
reparentTopTask(wct);
@@ -64,6 +69,8 @@
void deactivate(WindowContainerTransaction wct, boolean toTop) {
if (!mIsActive) return;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "deactivate: main stage toTop=%b rootTaskInfo=%s",
+ toTop, mRootTaskInfo);
mIsActive = false;
if (mRootTaskInfo == null) return;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SideStage.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SideStage.java
index 9903113..f5fbae5 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SideStage.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SideStage.java
@@ -16,12 +16,15 @@
package com.android.wm.shell.splitscreen;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN;
+
import android.app.ActivityManager;
import android.content.Context;
import android.view.SurfaceSession;
import android.window.WindowContainerToken;
import android.window.WindowContainerTransaction;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.launcher3.icons.IconProvider;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.SyncTransactionQueue;
@@ -47,6 +50,8 @@
}
boolean removeAllTasks(WindowContainerTransaction wct, boolean toTop) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "remove all side stage tasks: childCount=%d toTop=%b",
+ mChildrenTaskInfo.size(), toTop);
if (mChildrenTaskInfo.size() == 0) return false;
wct.reparentTasks(
mRootTaskInfo.token,
@@ -59,6 +64,8 @@
boolean removeTask(int taskId, WindowContainerToken newParent, WindowContainerTransaction wct) {
final ActivityManager.RunningTaskInfo task = mChildrenTaskInfo.get(taskId);
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "remove side stage task: task=%d exists=%b", taskId,
+ task != null);
if (task == null) return false;
wct.reparent(task.token, newParent, false /* onTop */);
return true;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
index 53dd981..952e2d4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
@@ -476,7 +476,9 @@
}
public void goToFullscreenFromSplit() {
- mStageCoordinator.goToFullscreenFromSplit();
+ if (mStageCoordinator.isSplitActive()) {
+ mStageCoordinator.goToFullscreenFromSplit();
+ }
}
/** Move the specified task to fullscreen, regardless of focus state. */
@@ -806,6 +808,9 @@
@Override
public void startIntent(PendingIntent intent, int userId1, @Nullable Intent fillInIntent,
@SplitPosition int position, @Nullable Bundle options) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ "startIntent(): intent=%s user=%d fillInIntent=%s position=%d", intent, userId1,
+ fillInIntent, position);
// Flag this as a no-user-action launch to prevent sending user leaving event to the current
// top activity since it's going to be put into another side of the split. This prevents the
// current top activity from going into pip mode due to user leaving event.
@@ -824,6 +829,8 @@
.map(recentTasks -> recentTasks.findTaskInBackground(component, userId1))
.orElse(null);
if (taskInfo != null) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ "Found suitable background task=%s", taskInfo);
if (ENABLE_SHELL_TRANSITIONS) {
mStageCoordinator.startTask(taskInfo.taskId, position, options);
} else {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
index b60e361..1d9fdeb 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
@@ -25,6 +25,8 @@
import static com.android.wm.shell.animation.Interpolators.ALPHA_OUT;
import static com.android.wm.shell.common.split.SplitScreenConstants.FADE_DURATION;
import static com.android.wm.shell.common.split.SplitScreenConstants.FLAG_IS_DIVIDER_BAR;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TRANSITIONS;
import static com.android.wm.shell.splitscreen.SplitScreen.stageTypeToString;
import static com.android.wm.shell.splitscreen.SplitScreenController.EXIT_REASON_DRAG_DIVIDER;
import static com.android.wm.shell.splitscreen.SplitScreenController.exitReasonToString;
@@ -101,6 +103,7 @@
@NonNull Transitions.TransitionFinishCallback finishCallback,
@NonNull WindowContainerToken mainRoot, @NonNull WindowContainerToken sideRoot,
@NonNull WindowContainerToken topRoot) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "playAnimation: transition=%d", info.getDebugId());
initTransition(transition, finishTransaction, finishCallback);
final TransitSession pendingTransition = getPendingTransition(transition);
@@ -123,10 +126,12 @@
playInternalAnimation(transition, info, startTransaction, mainRoot, sideRoot, topRoot);
}
- /** Internal funcation of playAnimation. */
+ /** Internal function of playAnimation. */
private void playInternalAnimation(@NonNull IBinder transition, @NonNull TransitionInfo info,
@NonNull SurfaceControl.Transaction t, @NonNull WindowContainerToken mainRoot,
@NonNull WindowContainerToken sideRoot, @NonNull WindowContainerToken topRoot) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "playInternalAnimation: transition=%d",
+ info.getDebugId());
// Play some place-holder fade animations
final boolean isEnter = isPendingEnter(transition);
for (int i = info.getChanges().size() - 1; i >= 0; --i) {
@@ -220,6 +225,8 @@
@NonNull Transitions.TransitionFinishCallback finishCallback,
@NonNull WindowContainerToken toTopRoot, @NonNull SplitDecorManager toTopDecor,
@NonNull WindowContainerToken topRoot) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "playDragDismissAnimation: transition=%d",
+ info.getDebugId());
initTransition(transition, finishTransaction, finishCallback);
for (int i = info.getChanges().size() - 1; i >= 0; --i) {
@@ -259,6 +266,7 @@
@NonNull Transitions.TransitionFinishCallback finishCallback,
@NonNull WindowContainerToken mainRoot, @NonNull WindowContainerToken sideRoot,
@NonNull SplitDecorManager mainDecor, @NonNull SplitDecorManager sideDecor) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "playResizeAnimation: transition=%d", info.getDebugId());
initTransition(transition, finishTransaction, finishCallback);
for (int i = info.getChanges().size() - 1; i >= 0; --i) {
@@ -312,13 +320,15 @@
@Nullable
private TransitSession getPendingTransition(IBinder transition) {
if (isPendingEnter(transition)) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "\tresolved enter transition");
return mPendingEnter;
} else if (isPendingDismiss(transition)) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "\tresolved dismiss transition");
return mPendingDismiss;
} else if (isPendingResize(transition)) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "\tresolved resize transition");
return mPendingResize;
}
-
return null;
}
@@ -339,7 +349,7 @@
Transitions.TransitionHandler handler,
int extraTransitType, boolean resizeAnim) {
if (mPendingEnter != null) {
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " splitTransition "
+ ProtoLog.v(WM_SHELL_TRANSITIONS, " splitTransition "
+ " skip to start enter split transition since it already exist. ");
return null;
}
@@ -355,8 +365,10 @@
mPendingEnter = new EnterSession(
transition, remoteTransition, extraTransitType, resizeAnim);
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " splitTransition "
+ ProtoLog.v(WM_SHELL_TRANSITIONS, " splitTransition "
+ " deduced Enter split screen");
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "setEnterTransition: transitType=%d resize=%b",
+ extraTransitType, resizeAnim);
}
/** Starts a transition to dismiss split. */
@@ -364,7 +376,7 @@
Transitions.TransitionHandler handler, @SplitScreen.StageType int dismissTop,
@SplitScreenController.ExitReason int reason) {
if (mPendingDismiss != null) {
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " splitTransition "
+ ProtoLog.v(WM_SHELL_TRANSITIONS, " splitTransition "
+ " skip to start dismiss split transition since it already exist. reason to "
+ " dismiss = %s", exitReasonToString(reason));
return null;
@@ -381,9 +393,11 @@
@SplitScreenController.ExitReason int reason) {
mPendingDismiss = new DismissSession(transition, reason, dismissTop);
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " splitTransition "
+ ProtoLog.v(WM_SHELL_TRANSITIONS, " splitTransition "
+ " deduced Dismiss due to %s. toTop=%s",
exitReasonToString(reason), stageTypeToString(dismissTop));
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "setDismissTransition: reason=%s dismissTop=%s",
+ exitReasonToString(reason), stageTypeToString(dismissTop));
}
IBinder startResizeTransition(WindowContainerTransaction wct,
@@ -405,8 +419,9 @@
@Nullable TransitionConsumedCallback consumedCallback,
@Nullable TransitionFinishedCallback finishCallback) {
mPendingResize = new TransitSession(transition, consumedCallback, finishCallback);
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " splitTransition "
+ ProtoLog.v(WM_SHELL_TRANSITIONS, " splitTransition "
+ " deduced Resize split screen");
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "setResizeTransition");
}
void mergeAnimation(IBinder transition, TransitionInfo info, SurfaceControl.Transaction t,
@@ -444,12 +459,15 @@
mPendingEnter.onConsumed(aborted);
mPendingEnter = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTransitionConsumed for enter transition");
} else if (isPendingDismiss(transition)) {
mPendingDismiss.onConsumed(aborted);
mPendingDismiss = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTransitionConsumed for dismiss transition");
} else if (isPendingResize(transition)) {
mPendingResize.onConsumed(aborted);
mPendingResize = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTransitionConsumed for resize transition");
}
// TODO: handle transition consumed for active remote handler
@@ -462,12 +480,15 @@
if (isPendingEnter(mAnimatingTransition)) {
mPendingEnter.onFinished(wct, mFinishTransaction);
mPendingEnter = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onFinish for enter transition");
} else if (isPendingDismiss(mAnimatingTransition)) {
mPendingDismiss.onFinished(wct, mFinishTransaction);
mPendingDismiss = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onFinish for dismiss transition");
} else if (isPendingResize(mAnimatingTransition)) {
mPendingResize.onFinished(wct, mFinishTransaction);
mPendingResize = null;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onFinish for resize transition");
}
mActiveRemoteHandler = null;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
index 2933cf4..7a1595f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
@@ -44,6 +44,7 @@
import static com.android.wm.shell.common.split.SplitScreenConstants.splitPositionToString;
import static com.android.wm.shell.common.split.SplitScreenUtils.reverseSplitPosition;
import static com.android.wm.shell.common.split.SplitScreenUtils.splitFailureMessage;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN;
import static com.android.wm.shell.shared.TransitionUtil.isClosingType;
import static com.android.wm.shell.shared.TransitionUtil.isOpeningType;
import static com.android.wm.shell.splitscreen.SplitScreen.STAGE_TYPE_MAIN;
@@ -138,6 +139,7 @@
import com.android.wm.shell.shared.TransitionUtil;
import com.android.wm.shell.splitscreen.SplitScreen.StageType;
import com.android.wm.shell.splitscreen.SplitScreenController.ExitReason;
+import com.android.wm.shell.splitscreen.SplitScreenController.SplitEnterReason;
import com.android.wm.shell.transition.DefaultMixedHandler;
import com.android.wm.shell.transition.LegacyTransitions;
import com.android.wm.shell.transition.Transitions;
@@ -313,6 +315,7 @@
taskOrganizer.createRootTask(displayId, WINDOWING_MODE_FULLSCREEN, this /* listener */);
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Creating main/side root task");
mMainStage = new MainStage(
mContext,
mTaskOrganizer,
@@ -454,6 +457,8 @@
boolean moveToStage(ActivityManager.RunningTaskInfo task, @SplitPosition int stagePosition,
WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "moveToStage: task=%d position=%d", task.taskId,
+ stagePosition);
prepareEnterSplitScreen(wct, task, stagePosition, false /* resizeAnim */);
if (ENABLE_SHELL_TRANSITIONS) {
mSplitTransitions.startEnterTransition(TRANSIT_TO_FRONT, wct,
@@ -474,6 +479,7 @@
}
boolean removeFromSideStage(int taskId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "removeFromSideStage: task=%d", taskId);
final WindowContainerTransaction wct = new WindowContainerTransaction();
/**
@@ -498,11 +504,15 @@
enteredSplitSelect |= listener.onRequestEnterSplitSelect(taskInfo, splitPosition,
taskBounds);
}
- if (enteredSplitSelect) mTaskOrganizer.applyTransaction(wct);
+ if (enteredSplitSelect) {
+ mTaskOrganizer.applyTransaction(wct);
+ }
}
void startShortcut(String packageName, String shortcutId, @SplitPosition int position,
Bundle options, UserHandle user) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startShortcut: pkg=%s id=%s position=%d user=%d",
+ packageName, shortcutId, position, user.getIdentifier());
final boolean isEnteringSplit = !isSplitActive();
IRemoteAnimationRunner wrapper = new IRemoteAnimationRunner.Stub() {
@@ -564,6 +574,7 @@
/** Use this method to launch an existing Task via a taskId */
void startTask(int taskId, @SplitPosition int position, @Nullable Bundle options) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startTask: task=%d position=%d", taskId, position);
mSplitRequest = new SplitRequest(taskId, position);
final WindowContainerTransaction wct = new WindowContainerTransaction();
options = resolveStartStage(STAGE_TYPE_UNDEFINED, position, options, null /* wct */);
@@ -595,6 +606,8 @@
/** Launches an activity into split. */
void startIntent(PendingIntent intent, Intent fillInIntent, @SplitPosition int position,
@Nullable Bundle options) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startIntent: intent=%s position=%d", intent.getIntent(),
+ position);
mSplitRequest = new SplitRequest(intent.getIntent(), position);
if (!ENABLE_SHELL_TRANSITIONS) {
startIntentLegacy(intent, fillInIntent, position, options);
@@ -690,6 +703,9 @@
void startTasks(int taskId1, @Nullable Bundle options1, int taskId2, @Nullable Bundle options2,
@SplitPosition int splitPosition, @PersistentSnapPosition int snapPosition,
@Nullable RemoteTransition remoteTransition, InstanceId instanceId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startTasks: task1=%d task2=%d position=%d snapPosition=%d",
+ taskId1, taskId2, splitPosition, snapPosition);
final WindowContainerTransaction wct = new WindowContainerTransaction();
if (taskId2 == INVALID_TASK_ID) {
if (mMainStage.containsTask(taskId1) || mSideStage.containsTask(taskId1)) {
@@ -718,6 +734,9 @@
@Nullable Bundle options1, int taskId, @Nullable Bundle options2,
@SplitPosition int splitPosition, @PersistentSnapPosition int snapPosition,
@Nullable RemoteTransition remoteTransition, InstanceId instanceId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startIntentAndTask: intent=%s task1=%d position=%d snapPosition=%d",
+ pendingIntent.getIntent(), taskId, splitPosition, snapPosition);
final WindowContainerTransaction wct = new WindowContainerTransaction();
if (taskId == INVALID_TASK_ID) {
options1 = options1 != null ? options1 : new Bundle();
@@ -740,6 +759,9 @@
int taskId, @Nullable Bundle options2, @SplitPosition int splitPosition,
@PersistentSnapPosition int snapPosition, @Nullable RemoteTransition remoteTransition,
InstanceId instanceId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startShortcutAndTask: shortcut=%s task1=%d position=%d snapPosition=%d",
+ shortcutInfo, taskId, splitPosition, snapPosition);
final WindowContainerTransaction wct = new WindowContainerTransaction();
if (taskId == INVALID_TASK_ID) {
options1 = options1 != null ? options1 : new Bundle();
@@ -801,6 +823,10 @@
@Nullable ShortcutInfo shortcutInfo2, @Nullable Bundle options2,
@SplitPosition int splitPosition, @PersistentSnapPosition int snapPosition,
@Nullable RemoteTransition remoteTransition, InstanceId instanceId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startIntents: intent1=%s intent2=%s position=%d snapPosition=%d",
+ pendingIntent1.getIntent(), pendingIntent2.getIntent(), splitPosition,
+ snapPosition);
final WindowContainerTransaction wct = new WindowContainerTransaction();
if (pendingIntent2 == null) {
options1 = options1 != null ? options1 : new Bundle();
@@ -1302,6 +1328,7 @@
}
void switchSplitPosition(String reason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "switchSplitPosition");
final SurfaceControl.Transaction t = mTransactionPool.acquire();
mTempRect1.setEmpty();
final StageTaskListener topLeftStage =
@@ -1343,7 +1370,7 @@
});
});
- ProtoLog.v(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN, "Switch split position: %s", reason);
+ ProtoLog.v(WM_SHELL_SPLIT_SCREEN, "Switch split position: %s", reason);
mLogger.logSwap(getMainStagePosition(), mMainStage.getTopChildTaskUid(),
getSideStagePosition(), mSideStage.getTopChildTaskUid(),
mSplitLayout.isLeftRightSplit());
@@ -1376,11 +1403,12 @@
if (!mMainStage.isActive()) {
return;
}
-
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onKeyguardVisibilityChanged: showing=%b", showing);
setDividerVisibility(!mKeyguardShowing, null);
}
void onFinishedWakingUp() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onFinishedWakingUp");
if (!mMainStage.isActive()) {
return;
}
@@ -1421,6 +1449,8 @@
}
void exitSplitScreen(int toTopTaskId, @ExitReason int exitReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "exitSplitScreen: topTaskId=%d reason=%s active=%b",
+ toTopTaskId, exitReasonToString(exitReason), mMainStage.isActive());
if (!mMainStage.isActive()) return;
StageTaskListener childrenToTop = null;
@@ -1439,6 +1469,8 @@
private void exitSplitScreen(@Nullable StageTaskListener childrenToTop,
@ExitReason int exitReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "exitSplitScreen: mainStageToTop=%b reason=%s active=%b",
+ childrenToTop == mMainStage, exitReasonToString(exitReason), mMainStage.isActive());
if (!mMainStage.isActive()) return;
final WindowContainerTransaction wct = new WindowContainerTransaction();
@@ -1447,6 +1479,8 @@
private void applyExitSplitScreen(@Nullable StageTaskListener childrenToTop,
WindowContainerTransaction wct, @ExitReason int exitReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "applyExitSplitScreen: reason=%s",
+ exitReasonToString(exitReason));
if (!mMainStage.isActive() || mIsExiting) return;
onSplitScreenExit();
@@ -1502,7 +1536,6 @@
}
});
- Slog.i(TAG, "applyExitSplitScreen, reason = " + exitReasonToString(exitReason));
// Log the exit
if (childrenToTop != null) {
logExitToStage(exitReason, childrenToTop == mMainStage);
@@ -1527,6 +1560,7 @@
* Exits the split screen by finishing one of the tasks.
*/
protected void exitStage(@SplitPosition int stageToClose) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "exitStage: stageToClose=%d", stageToClose);
mSplitLayout.flingDividerToDismiss(stageToClose == SPLIT_POSITION_BOTTOM_OR_RIGHT,
EXIT_REASON_APP_FINISHED);
}
@@ -1540,12 +1574,13 @@
try {
activityTaskManagerService.setFocusedTask(getTaskId(stageToFocus));
} catch (RemoteException | NullPointerException e) {
- ProtoLog.e(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ ProtoLog.e(WM_SHELL_SPLIT_SCREEN,
"Unable to update focus on the chosen stage: %s", e.getMessage());
}
}
private void clearRequestIfPresented() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "clearRequestIfPresented");
if (mSideStageListener.mVisible && mSideStageListener.mHasChildren
&& mMainStageListener.mVisible && mSideStageListener.mHasChildren) {
mSplitRequest = null;
@@ -1581,6 +1616,8 @@
void clearSplitPairedInRecents(@ExitReason int exitReason) {
if (!shouldBreakPairedTaskInRecents(exitReason) || !mShouldUpdateRecents) return;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "clearSplitPairedInRecents: reason=%s",
+ exitReasonToString(exitReason));
mRecentTasks.ifPresent(recentTasks -> {
// Notify recents if we are exiting in a way that breaks the pair, and disable further
// updates to splits in the recents until we enter split again
@@ -1597,11 +1634,13 @@
void prepareExitSplitScreen(@StageType int stageToTop,
@NonNull WindowContainerTransaction wct) {
if (!mMainStage.isActive()) return;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareExitSplitScreen: stageToTop=%d", stageToTop);
mSideStage.removeAllTasks(wct, stageToTop == STAGE_TYPE_SIDE);
mMainStage.deactivate(wct, stageToTop == STAGE_TYPE_MAIN);
}
private void prepareEnterSplitScreen(WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareEnterSplitScreen");
prepareEnterSplitScreen(wct, null /* taskInfo */, SPLIT_POSITION_UNDEFINED,
!mIsDropEntering);
}
@@ -1613,6 +1652,8 @@
void prepareEnterSplitScreen(WindowContainerTransaction wct,
@Nullable ActivityManager.RunningTaskInfo taskInfo, @SplitPosition int startPosition,
boolean resizeAnim) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareEnterSplitScreen: position=%d resize=%b",
+ startPosition, resizeAnim);
onSplitScreenEnter();
// Preemptively reset the reparenting behavior if we know that we are entering, as starting
// split tasks with activity trampolines can inadvertently trigger the task to be
@@ -1629,6 +1670,8 @@
private void prepareBringSplit(WindowContainerTransaction wct,
@Nullable ActivityManager.RunningTaskInfo taskInfo, @SplitPosition int startPosition,
boolean resizeAnim) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareBringSplit: task=%d isSplitVisible=%b",
+ taskInfo != null ? taskInfo.taskId : -1, isSplitScreenVisible());
if (taskInfo != null) {
wct.startTask(taskInfo.taskId,
resolveStartStage(STAGE_TYPE_UNDEFINED, startPosition, null, wct));
@@ -1649,6 +1692,8 @@
private void prepareActiveSplit(WindowContainerTransaction wct,
@Nullable ActivityManager.RunningTaskInfo taskInfo, @SplitPosition int startPosition,
boolean resizeAnim) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareActiveSplit: task=%d isSplitVisible=%b",
+ taskInfo != null ? taskInfo.taskId : -1, isSplitScreenVisible());
if (!ENABLE_SHELL_TRANSITIONS) {
// Legacy transition we need to create divider here, shell transition case we will
// create it on #finishEnterSplitScreen
@@ -1667,6 +1712,7 @@
}
private void prepareSplitLayout(WindowContainerTransaction wct, boolean resizeAnim) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "prepareSplitLayout: resize=%b", resizeAnim);
if (resizeAnim) {
mSplitLayout.setDividerAtBorder(mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT);
} else {
@@ -1686,6 +1732,7 @@
}
void finishEnterSplitScreen(SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "finishEnterSplitScreen");
mSplitLayout.update(finishT, true /* resetImePosition */);
mMainStage.getSplitDecorManager().inflate(mContext, mMainStage.mRootLeash,
getMainStageBounds());
@@ -1835,12 +1882,20 @@
leftTopTaskId, rightBottomTaskId, mSplitLayout.calculateCurrentSnapPosition());
if (mainStageTopTaskId != INVALID_TASK_ID && sideStageTopTaskId != INVALID_TASK_ID) {
// Update the pair for the top tasks
- recentTasks.addSplitPair(mainStageTopTaskId, sideStageTopTaskId, splitBounds);
+ boolean added = recentTasks.addSplitPair(mainStageTopTaskId, sideStageTopTaskId,
+ splitBounds);
+ if (added) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "updateRecentTasksSplitPair: adding split pair ltTask=%d rbTask=%d",
+ leftTopTaskId, rightBottomTaskId);
+ }
}
});
}
private void sendSplitVisibilityChanged() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "sendSplitVisibilityChanged: dividerVisible=%b",
+ mDividerVisible);
for (int i = mListeners.size() - 1; i >= 0; --i) {
final SplitScreen.SplitScreenListener l = mListeners.get(i);
l.onSplitVisibilityChanged(mDividerVisible);
@@ -1855,6 +1910,7 @@
throw new IllegalArgumentException(this + "\n Unknown task appeared: " + taskInfo);
}
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTaskAppeared: task=%s", taskInfo);
mRootTaskInfo = taskInfo;
mRootTaskLeash = leash;
@@ -1880,6 +1936,8 @@
if (mSplitLayout != null
&& mSplitLayout.updateConfiguration(mRootTaskInfo.configuration)
&& mMainStage.isActive()) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTaskInfoChanged: task=%d updating",
+ taskInfo.taskId);
// Clear the divider remote animating flag as the divider will be re-rendered to apply
// the new rotation config. Don't reset the IME state since those updates are not in
// sync with task info changes.
@@ -1892,6 +1950,7 @@
@Override
@CallSuper
public void onTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTaskVanished: task=%s", taskInfo);
if (mRootTaskInfo == null) {
throw new IllegalArgumentException(this + "\n Unknown task vanished: " + taskInfo);
}
@@ -1911,6 +1970,8 @@
@VisibleForTesting
void onRootTaskAppeared() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRootTaskAppeared: rootTask=%s mainRoot=%b sideRoot=%b",
+ mRootTaskInfo, mMainStageListener.mHasRootTask, mSideStageListener.mHasRootTask);
// Wait unit all root tasks appeared.
if (mRootTaskInfo == null
|| !mMainStageListener.mHasRootTask
@@ -1937,6 +1998,8 @@
* #onStageHasChildrenChanged because this would be called every time child task appeared.
* NOTICE: This only be called on legacy transition. */
private void onChildTaskAppeared(StageListenerImpl stageListener, int taskId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onChildTaskAppeared: isMainStage=%b task=%d",
+ stageListener == mMainStageListener, taskId);
// Handle entering split screen while there is a split pair running in the background.
if (stageListener == mSideStageListener && !isSplitScreenVisible() && isSplitActive()
&& mSplitRequest == null) {
@@ -1960,6 +2023,7 @@
}
private void onRootTaskVanished() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRootTaskVanished");
final WindowContainerTransaction wct = new WindowContainerTransaction();
mLaunchAdjacentController.clearLaunchAdjacentRoot();
applyExitSplitScreen(null /* childrenToTop */, wct, EXIT_REASON_ROOT_TASK_VANISHED);
@@ -1990,6 +2054,8 @@
return;
}
+ // TODO Protolog
+
// Check if it needs to dismiss split screen when both stage invisible.
if (!mainStageVisible && mExitSplitScreenOnHide) {
exitSplitScreen(null /* childrenToTop */, EXIT_REASON_RETURN_HOME);
@@ -2020,14 +2086,14 @@
return;
}
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
- "Request to %s divider bar from %s.",
- (visible ? "show" : "hide"), Debug.getCaller());
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "setDividerVisibility: visible=%b keyguardShowing=%b dividerAnimating=%b caller=%s",
+ visible, mKeyguardShowing, mIsDividerRemoteAnimating, Debug.getCaller());
// Defer showing divider bar after keyguard dismissed, so it won't interfere with keyguard
// dismissing animation.
if (visible && mKeyguardShowing) {
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
" Defer showing divider bar due to keyguard showing.");
return;
}
@@ -2036,7 +2102,7 @@
sendSplitVisibilityChanged();
if (mIsDividerRemoteAnimating) {
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
" Skip animating divider bar due to it's remote animating.");
return;
}
@@ -2050,12 +2116,12 @@
private void applyDividerVisibility(@Nullable SurfaceControl.Transaction t) {
final SurfaceControl dividerLeash = mSplitLayout.getDividerLeash();
if (dividerLeash == null) {
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
" Skip animating divider bar due to divider leash not ready.");
return;
}
if (mIsDividerRemoteAnimating) {
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
" Skip animating divider bar due to it's remote animating.");
return;
}
@@ -2119,6 +2185,8 @@
/** Callback when split roots have child or haven't under it.
* NOTICE: This only be called on legacy transition. */
private void onStageHasChildrenChanged(StageListenerImpl stageListener) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onStageHasChildrenChanged: isMainStage=%b",
+ stageListener == mMainStageListener);
final boolean hasChildren = stageListener.mHasChildren;
final boolean isSideStage = stageListener == mSideStageListener;
if (!hasChildren && !mIsExiting && mMainStage.isActive()) {
@@ -2170,13 +2238,15 @@
}
@Override
- public void onSnappedToDismiss(boolean bottomOrRight, int reason) {
+ public void onSnappedToDismiss(boolean bottomOrRight, @ExitReason int exitReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onSnappedToDismiss: bottomOrRight=%b reason=%s",
+ bottomOrRight, exitReasonToString(exitReason));
final boolean mainStageToTop =
bottomOrRight ? mSideStagePosition == SPLIT_POSITION_BOTTOM_OR_RIGHT
: mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT;
final StageTaskListener toTopStage = mainStageToTop ? mMainStage : mSideStage;
if (!ENABLE_SHELL_TRANSITIONS) {
- exitSplitScreen(toTopStage, reason);
+ exitSplitScreen(toTopStage, exitReason);
return;
}
@@ -2219,6 +2289,7 @@
@Override
public void onLayoutSizeChanged(SplitLayout layout) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onLayoutSizeChanged");
// Reset this flag every time onLayoutSizeChanged.
mShowDecorImmediately = false;
@@ -2278,8 +2349,11 @@
mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT ? mSideStage : mMainStage;
final StageTaskListener bottomRightStage =
mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT ? mMainStage : mSideStage;
- return layout.applyTaskChanges(wct, topLeftStage.mRootTaskInfo,
+ boolean updated = layout.applyTaskChanges(wct, topLeftStage.mRootTaskInfo,
bottomRightStage.mRootTaskInfo);
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "updateWindowBounds: topLeftStage=%s bottomRightStage=%s",
+ layout.getBounds1(), layout.getBounds2());
+ return updated;
}
void updateSurfaceBounds(@Nullable SplitLayout layout, @NonNull SurfaceControl.Transaction t,
@@ -2291,6 +2365,9 @@
(layout != null ? layout : mSplitLayout).applySurfaceChanges(t, topLeftStage.mRootLeash,
bottomRightStage.mRootLeash, topLeftStage.mDimLayer, bottomRightStage.mDimLayer,
applyResizingOffset);
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "updateSurfaceBounds: topLeftStage=%s bottomRightStage=%s",
+ layout.getBounds1(), layout.getBounds2());
}
@Override
@@ -2329,6 +2406,8 @@
@Override
public void setLayoutOffsetTarget(int offsetX, int offsetY, SplitLayout layout) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "setLayoutOffsetTarget: x=%d y=%d",
+ offsetX, offsetY);
final StageTaskListener topLeftStage =
mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT ? mSideStage : mMainStage;
final StageTaskListener bottomRightStage =
@@ -2343,6 +2422,7 @@
if (displayId != DEFAULT_DISPLAY) {
return;
}
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onDisplayAdded: display=%d", displayId);
mDisplayController.addDisplayChangingController(this::onDisplayChange);
}
@@ -2357,8 +2437,14 @@
private void onDisplayChange(int displayId, int fromRotation, int toRotation,
@Nullable DisplayAreaInfo newDisplayAreaInfo, WindowContainerTransaction wct) {
- if (displayId != DEFAULT_DISPLAY || !mMainStage.isActive()) return;
+ if (displayId != DEFAULT_DISPLAY || !mMainStage.isActive()) {
+ return;
+ }
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "onDisplayChange: display=%d fromRot=%d toRot=%d config=%s",
+ displayId, fromRotation, toRotation,
+ newDisplayAreaInfo != null ? newDisplayAreaInfo.configuration : null);
mSplitLayout.rotateTo(toRotation);
if (newDisplayAreaInfo != null) {
mSplitLayout.updateConfiguration(newDisplayAreaInfo.configuration);
@@ -2369,6 +2455,7 @@
@VisibleForTesting
void onFoldedStateChanged(boolean folded) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onFoldedStateChanged: folded=%b", folded);
mTopStageAfterFoldDismiss = STAGE_TYPE_UNDEFINED;
if (!folded) return;
@@ -2439,6 +2526,8 @@
final ActivityManager.RunningTaskInfo triggerTask = request.getTriggerTask();
if (triggerTask == null) {
if (isSplitActive()) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "handleRequest: transition=%d display rotation",
+ request.getDebugId());
// Check if the display is rotating.
final TransitionRequestInfo.DisplayChange displayChange =
request.getDisplayChange();
@@ -2467,6 +2556,8 @@
}
if (isSplitActive()) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "handleRequest: transition=%d split active",
+ request.getDebugId());
// Try to handle everything while in split-screen, so return a WCT even if it's empty.
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " split is active so using split"
+ "Transition to handle request. triggerTask=%d type=%s mainChildren=%d"
@@ -2541,6 +2632,8 @@
return null;
} else {
if (isOpening && getStageOfTask(triggerTask) != null) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "handleRequest: transition=%d enter split",
+ request.getDebugId());
// One task is appearing into split, prepare to enter split screen.
out = new WindowContainerTransaction();
prepareEnterSplitScreen(out);
@@ -2557,6 +2650,8 @@
*/
public void addEnterOrExitIfNeeded(@Nullable TransitionRequestInfo request,
@NonNull WindowContainerTransaction outWCT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "addEnterOrExitIfNeeded: transition=%d",
+ request.getDebugId());
final ActivityManager.RunningTaskInfo triggerTask = request.getTriggerTask();
if (triggerTask != null && triggerTask.displayId != mDisplayId) {
// Skip handling task on the other display.
@@ -2591,6 +2686,7 @@
public void mergeAnimation(IBinder transition, TransitionInfo info,
SurfaceControl.Transaction t, IBinder mergeTarget,
Transitions.TransitionFinishCallback finishCallback) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "mergeAnimation: transition=%d", info.getDebugId());
mSplitTransitions.mergeAnimation(transition, info, t, mergeTarget, finishCallback);
}
@@ -2602,6 +2698,7 @@
@Override
public void onTransitionConsumed(@NonNull IBinder transition, boolean aborted,
@Nullable SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTransitionConsumed");
mSplitTransitions.onTransitionConsumed(transition, aborted, finishT);
}
@@ -2617,6 +2714,7 @@
// If we're not in split-mode, just abort so something else can handle it.
if (!mMainStage.isActive()) return false;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startAnimation: transition=%d", info.getDebugId());
mSplitLayout.setFreezeDividerWindow(false);
final StageChangeRecord record = new StageChangeRecord();
final int transitType = info.getType();
@@ -2727,6 +2825,8 @@
if (mMixedHandler.animatePendingSplitWithDisplayChange(transition, info,
startTransaction, finishTransaction, finishCallback)) {
if (mSplitTransitions.isPendingResize(transition)) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startAnimation: transition=%d display change", info.getDebugId());
// Only need to update in resize because divider exist before transition.
mSplitLayout.update(startTransaction, true /* resetImePosition */);
startTransaction.apply();
@@ -2797,6 +2897,8 @@
@NonNull SurfaceControl.Transaction startTransaction,
@NonNull SurfaceControl.Transaction finishTransaction,
@NonNull Transitions.TransitionFinishCallback finishCallback) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startPendingAnimation: transition=%d",
+ info.getDebugId());
boolean shouldAnimate = true;
if (mSplitTransitions.isPendingEnter(transition)) {
shouldAnimate = startPendingEnterAnimation(transition,
@@ -2830,6 +2932,7 @@
/** Called to clean-up state and do house-keeping after the animation is done. */
public void onTransitionAnimationComplete() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTransitionAnimationComplete");
// If still playing, let it finish.
if (!mMainStage.isActive() && !mIsExiting) {
// Update divider state after animation so that it is still around and positioned
@@ -2842,6 +2945,8 @@
@NonNull SplitScreenTransitions.EnterSession enterTransition,
@NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction t,
@NonNull SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "startPendingEnterAnimation: enterTransition=%s",
+ enterTransition);
// First, verify that we actually have opened apps in both splits.
TransitionInfo.Change mainChild = null;
TransitionInfo.Change sideChild = null;
@@ -2959,6 +3064,7 @@
}
public void goToFullscreenFromSplit() {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "goToFullscreenFromSplit");
// If main stage is focused, toEnd = true if
// mSideStagePosition = SPLIT_POSITION_BOTTOM_OR_RIGHT. Otherwise toEnd = false
// If side stage is focused, toEnd = true if
@@ -2974,6 +3080,7 @@
/** Move the specified task to fullscreen, regardless of focus state. */
public void moveTaskToFullscreen(int taskId, int exitReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "moveTaskToFullscreen");
boolean leftOrTop;
if (mMainStage.containsTask(taskId)) {
leftOrTop = (mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT);
@@ -2994,6 +3101,7 @@
*/
public void onPipExpandToSplit(WindowContainerTransaction wct,
ActivityManager.RunningTaskInfo taskInfo) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onPipExpandToSplit: task=%s", taskInfo);
prepareEnterSplitScreen(wct, taskInfo, getActivateSplitPosition(taskInfo),
false /*resizeAnim*/);
@@ -3040,6 +3148,9 @@
public void prepareDismissAnimation(@StageType int toStage, @ExitReason int dismissReason,
@NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction t,
@NonNull SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "prepareDismissAnimation: transition=%d toStage=%d reason=%s",
+ info.getDebugId(), toStage, exitReasonToString(dismissReason));
// Make some noise if things aren't totally expected. These states shouldn't effect
// transitions locally, but remotes (like Launcher) may get confused if they were
// depending on listener callbacks. This can happen because task-organizer callbacks
@@ -3126,6 +3237,9 @@
@NonNull SplitScreenTransitions.DismissSession dismissTransition,
@NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction t,
@NonNull SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "startPendingDismissAnimation: transition=%d dismissTransition=%s",
+ info.getDebugId(), dismissTransition);
prepareDismissAnimation(dismissTransition.mDismissTop, dismissTransition.mReason, info,
t, finishT);
if (dismissTransition.mDismissTop == STAGE_TYPE_UNDEFINED) {
@@ -3146,6 +3260,8 @@
/** Call this when starting the open-recents animation while split-screen is active. */
public void onRecentsInSplitAnimationStart(TransitionInfo info) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRecentsInSplitAnimationStart: transition=%d",
+ info.getDebugId());
if (isSplitScreenVisible()) {
// Cache tasks on live tile.
for (int i = 0; i < info.getChanges().size(); ++i) {
@@ -3178,6 +3294,7 @@
/** Call this when the recents animation during split-screen finishes. */
public void onRecentsInSplitAnimationFinish(WindowContainerTransaction finishWct,
SurfaceControl.Transaction finishT) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRecentsInSplitAnimationFinish");
mPausingTasks.clear();
// Check if the recent transition is finished by returning to the current
// split, so we can restore the divider bar.
@@ -3203,6 +3320,7 @@
/** Call this when the recents animation finishes by doing pair-to-pair switch. */
public void onRecentsPairToPairAnimationFinish(WindowContainerTransaction finishWct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRecentsPairToPairAnimationFinish");
// Pair-to-pair switch happened so here should evict the live tile from its stage.
// Otherwise, the task will remain in stage, and occluding the new task when next time
// user entering recents.
@@ -3284,6 +3402,7 @@
* handled.
*/
private void setSplitsVisible(boolean visible) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "setSplitsVisible: visible=%b", visible);
mMainStageListener.mVisible = mSideStageListener.mVisible = visible;
mMainStageListener.mHasChildren = mSideStageListener.mHasChildren = visible;
}
@@ -3292,6 +3411,7 @@
* Sets drag info to be logged when splitscreen is next entered.
*/
public void onDroppedToSplit(@SplitPosition int position, InstanceId dragSessionId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onDroppedToSplit: position=%d", position);
if (!isSplitScreenVisible()) {
mIsDropEntering = true;
mSkipEvictingMainStageChildren = true;
@@ -3308,7 +3428,8 @@
/**
* Sets info to be logged when splitscreen is next entered.
*/
- public void onRequestToSplit(InstanceId sessionId, int enterReason) {
+ public void onRequestToSplit(InstanceId sessionId, @SplitEnterReason int enterReason) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onRequestToSplit: reason=%d", enterReason);
if (!isSplitScreenVisible() && !ENABLE_SHELL_TRANSITIONS) {
// If split running background, exit split first.
// Skip this on shell transition due to we could evict existing tasks on transition
@@ -3384,6 +3505,7 @@
@Override
public void onNoLongerSupportMultiWindow(ActivityManager.RunningTaskInfo taskInfo) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onNoLongerSupportMultiWindow: task=%s", taskInfo);
if (mMainStage.isActive()) {
final boolean isMainStage = mMainStageListener == this;
if (!ENABLE_SHELL_TRANSITIONS) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageTaskListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageTaskListener.java
index af7bf36..f33ab33 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageTaskListener.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageTaskListener.java
@@ -25,6 +25,7 @@
import static com.android.wm.shell.common.split.SplitScreenConstants.CONTROLLED_ACTIVITY_TYPES;
import static com.android.wm.shell.common.split.SplitScreenConstants.CONTROLLED_WINDOWING_MODES;
import static com.android.wm.shell.common.split.SplitScreenConstants.CONTROLLED_WINDOWING_MODES_WHEN_ACTIVE;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN;
import static com.android.wm.shell.transition.Transitions.ENABLE_SHELL_TRANSITIONS;
import android.annotation.CallSuper;
@@ -44,6 +45,7 @@
import androidx.annotation.NonNull;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.internal.util.ArrayUtils;
import com.android.launcher3.icons.IconProvider;
import com.android.wm.shell.ShellTaskOrganizer;
@@ -175,6 +177,9 @@
@Override
@CallSuper
public void onTaskAppeared(ActivityManager.RunningTaskInfo taskInfo, SurfaceControl leash) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTaskAppeared: task=%d taskParent=%d rootTask=%d",
+ taskInfo.taskId, taskInfo.parentTaskId,
+ mRootTaskInfo != null ? mRootTaskInfo.taskId : -1);
if (mRootTaskInfo == null) {
mRootLeash = leash;
mRootTaskInfo = taskInfo;
@@ -225,6 +230,9 @@
|| !ArrayUtils.contains(CONTROLLED_ACTIVITY_TYPES, taskInfo.getActivityType())
|| !ArrayUtils.contains(CONTROLLED_WINDOWING_MODES_WHEN_ACTIVE,
taskInfo.getWindowingMode())) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN,
+ "onTaskInfoChanged: task=%d no longer supports multiwindow",
+ taskInfo.taskId);
// Leave split screen if the task no longer supports multi window or have
// uncontrolled task.
mCallbacks.onNoLongerSupportMultiWindow(taskInfo);
@@ -251,6 +259,7 @@
@Override
@CallSuper
public void onTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "onTaskVanished: task=%d", taskInfo.taskId);
final int taskId = taskInfo.taskId;
if (mRootTaskInfo.taskId == taskId) {
mCallbacks.onRootTaskVanished();
@@ -333,6 +342,7 @@
}
void addTask(ActivityManager.RunningTaskInfo task, WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "addTask: task=%d", task.taskId);
// Clear overridden bounds and windowing mode to make sure the child task can inherit
// windowing mode and bounds from split root.
wct.setWindowingMode(task.token, WINDOWING_MODE_UNDEFINED)
@@ -342,6 +352,7 @@
}
void reorderChild(int taskId, boolean onTop, WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "reorderChild: task=%d onTop=%b", taskId, onTop);
if (!containsTask(taskId)) {
return;
}
@@ -357,6 +368,7 @@
/** Collects all the current child tasks and prepares transaction to evict them to display. */
void evictAllChildren(WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Evicting all children");
for (int i = mChildrenTaskInfo.size() - 1; i >= 0; i--) {
final ActivityManager.RunningTaskInfo taskInfo = mChildrenTaskInfo.valueAt(i);
wct.reparent(taskInfo.token, null /* parent */, false /* onTop */);
@@ -367,11 +379,13 @@
for (int i = mChildrenTaskInfo.size() - 1; i >= 0; i--) {
final ActivityManager.RunningTaskInfo taskInfo = mChildrenTaskInfo.valueAt(i);
if (taskId == taskInfo.taskId) continue;
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Evict other child: task=%d", taskId);
wct.reparent(taskInfo.token, null /* parent */, false /* onTop */);
}
}
void evictNonOpeningChildren(RemoteAnimationTarget[] apps, WindowContainerTransaction wct) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "evictNonOpeningChildren");
final SparseArray<ActivityManager.RunningTaskInfo> toBeEvict = mChildrenTaskInfo.clone();
for (int i = 0; i < apps.length; i++) {
if (apps[i].mode == MODE_OPENING) {
@@ -380,6 +394,7 @@
}
for (int i = toBeEvict.size() - 1; i >= 0; i--) {
final ActivityManager.RunningTaskInfo taskInfo = toBeEvict.valueAt(i);
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Evict non-opening child: task=%d", taskInfo.taskId);
wct.reparent(taskInfo.token, null /* parent */, false /* onTop */);
}
}
@@ -388,12 +403,15 @@
for (int i = mChildrenTaskInfo.size() - 1; i >= 0; i--) {
final ActivityManager.RunningTaskInfo taskInfo = mChildrenTaskInfo.valueAt(i);
if (!taskInfo.isVisible) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Evict invisible child: task=%d",
+ taskInfo.taskId);
wct.reparent(taskInfo.token, null /* parent */, false /* onTop */);
}
}
}
void evictChildren(WindowContainerTransaction wct, int taskId) {
+ ProtoLog.d(WM_SHELL_SPLIT_SCREEN, "Evict child: task=%d", taskId);
final ActivityManager.RunningTaskInfo taskInfo = mChildrenTaskInfo.get(taskId);
if (taskInfo != null) {
wct.reparent(taskInfo.token, null /* parent */, false /* onTop */);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
index c1406d0..caa894f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
@@ -22,8 +22,10 @@
import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.view.InputDevice.SOURCE_TOUCHSCREEN;
+import static android.view.MotionEvent.ACTION_CANCEL;
import static android.view.MotionEvent.ACTION_HOVER_ENTER;
import static android.view.MotionEvent.ACTION_HOVER_EXIT;
+import static android.view.MotionEvent.ACTION_UP;
import static android.view.WindowInsets.Type.statusBars;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
@@ -59,7 +61,6 @@
import android.view.SurfaceControl;
import android.view.SurfaceControl.Transaction;
import android.view.View;
-import android.view.ViewConfiguration;
import android.window.WindowContainerToken;
import android.window.WindowContainerTransaction;
@@ -321,8 +322,8 @@
private final GestureDetector mGestureDetector;
private boolean mIsDragging;
+ private boolean mTouchscreenInUse;
private boolean mHasLongClicked;
- private boolean mShouldClick;
private int mDragPointerId = -1;
private final Runnable mCloseMaximizeWindowRunnable;
@@ -343,6 +344,10 @@
@Override
public void onClick(View v) {
+ if (mIsDragging) {
+ mIsDragging = false;
+ return;
+ }
final DesktopModeWindowDecoration decoration = mWindowDecorByTaskId.get(mTaskId);
final int id = v.getId();
if (id == R.id.close_window) {
@@ -421,6 +426,10 @@
@Override
public boolean onTouch(View v, MotionEvent e) {
final int id = v.getId();
+ if ((e.getSource() & SOURCE_TOUCHSCREEN) == SOURCE_TOUCHSCREEN) {
+ mTouchscreenInUse = e.getActionMasked() != ACTION_UP
+ && e.getActionMasked() != ACTION_CANCEL;
+ }
if (id != R.id.caption_handle && id != R.id.desktop_mode_caption
&& id != R.id.open_menu_button && id != R.id.close_window
&& id != R.id.maximize_window) {
@@ -432,31 +441,19 @@
if (!mHasLongClicked && id != R.id.maximize_window) {
decoration.closeMaximizeMenuIfNeeded(e);
}
-
- final long eventDuration = e.getEventTime() - e.getDownTime();
- final boolean isTouchScreen =
- (e.getSource() & SOURCE_TOUCHSCREEN) == SOURCE_TOUCHSCREEN;
- final boolean shouldLongClick = isTouchScreen && id == R.id.maximize_window
- && !mIsDragging && !mHasLongClicked
- && eventDuration >= ViewConfiguration.getLongPressTimeout();
- if (shouldLongClick) {
- v.performLongClick();
- mHasLongClicked = true;
- return true;
- }
-
return mDragDetector.onMotionEvent(v, e);
}
@Override
public boolean onLongClick(View v) {
final int id = v.getId();
- if (id == R.id.maximize_window) {
+ if (id == R.id.maximize_window && mTouchscreenInUse) {
final DesktopModeWindowDecoration decoration = mWindowDecorByTaskId.get(mTaskId);
moveTaskToFront(decoration.mTaskInfo);
if (decoration.isMaximizeMenuActive()) {
decoration.closeMaximizeMenu();
} else {
+ mHasLongClicked = true;
decoration.createMaximizeMenu();
}
return true;
@@ -515,11 +512,9 @@
if (mGestureDetector.onTouchEvent(e)) {
return true;
}
- if (e.getActionMasked() == MotionEvent.ACTION_CANCEL) {
- // If a motion event is cancelled, reset mShouldClick so a click is not accidentally
- // performed.
- mShouldClick = false;
- }
+ final int id = v.getId();
+ final boolean touchingButton = (id == R.id.close_window || id == R.id.maximize_window
+ || id == R.id.open_menu_button);
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
mDragPointerId = e.getPointerId(0);
@@ -527,12 +522,12 @@
0 /* ctrlType */, e.getRawX(0),
e.getRawY(0));
mIsDragging = false;
- mShouldClick = true;
mHasLongClicked = false;
- return true;
+ // Do not consume input event if a button is touched, otherwise it would
+ // prevent the button's ripple effect from showing.
+ return !touchingButton;
}
case MotionEvent.ACTION_MOVE: {
- mShouldClick = false;
// If a decor's resize drag zone is active, don't also try to reposition it.
if (decoration.isHandlingDragResize()) break;
decoration.closeMaximizeMenu();
@@ -553,11 +548,6 @@
case MotionEvent.ACTION_CANCEL: {
final boolean wasDragging = mIsDragging;
if (!wasDragging) {
- if (mShouldClick && v != null && !mHasLongClicked) {
- v.performClick();
- mShouldClick = false;
- return true;
- }
return false;
}
if (e.findPointerIndex(mDragPointerId) == -1) {
@@ -576,8 +566,15 @@
position,
new PointF(e.getRawX(dragPointerIdx), e.getRawY(dragPointerIdx)),
newTaskBounds));
- mIsDragging = false;
- return true;
+ if (touchingButton && !mHasLongClicked) {
+ // We need the input event to not be consumed here to end the ripple
+ // effect on the touched button. We will reset drag state in the ensuing
+ // onClick call that results.
+ return false;
+ } else {
+ mIsDragging = false;
+ return true;
+ }
}
}
return true;
diff --git a/libs/WindowManager/Shell/tests/flicker/pip/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt b/libs/WindowManager/Shell/tests/flicker/pip/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
index ac7380f..9a1bd26 100644
--- a/libs/WindowManager/Shell/tests/flicker/pip/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
+++ b/libs/WindowManager/Shell/tests/flicker/pip/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
@@ -206,6 +206,18 @@
}
}
+ @Presubmit
+ @Test
+ fun pipLayerRemainInsideVisibleBounds() {
+ // during the transition we assert the center point is within the display bounds, since it
+ // might go outside of bounds as we resize from landscape fullscreen to destination bounds,
+ // and once the animation is over we assert that it's fully within the display bounds, at
+ // which point the device also performs orientation change from landscape to portrait
+ flicker.assertLayersVisibleRegion(pipApp.or(ComponentNameMatcher.PIP_CONTENT_OVERLAY)) {
+ regionsCenterPointInside(startingBounds).then().coversAtMost(endingBounds)
+ }
+ }
+
/** {@inheritDoc} */
@FlakyTest(bugId = 267424412)
@Test
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 383621b..35c803b 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
@@ -781,6 +781,23 @@
)
}
+ @Test
+ fun moveFocusedTaskToFullscreen() {
+ val task1 = setUpFreeformTask()
+ val task2 = setUpFreeformTask()
+ val task3 = setUpFreeformTask()
+
+ task1.isFocused = false
+ task2.isFocused = true
+ task3.isFocused = false
+
+ controller.enterFullscreen(DEFAULT_DISPLAY)
+
+ val wct = getLatestExitDesktopWct()
+ assertThat(wct.changes[task2.token.asBinder()]?.windowingMode)
+ .isEqualTo(WINDOWING_MODE_FULLSCREEN)
+ }
+
private fun setUpFreeformTask(displayId: Int = DEFAULT_DISPLAY): RunningTaskInfo {
val task = createFreeformTask(displayId)
whenever(shellTaskOrganizer.getRunningTaskInfo(task.taskId)).thenReturn(task)
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
index 1b347e0..5dd9d8a 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
@@ -22,9 +22,11 @@
import static android.content.ClipDescription.MIMETYPE_APPLICATION_ACTIVITY;
import static android.content.ClipDescription.MIMETYPE_APPLICATION_SHORTCUT;
import static android.content.ClipDescription.MIMETYPE_APPLICATION_TASK;
+import static android.content.ClipDescription.MIMETYPE_TEXT_INTENT;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_UNDEFINED;
@@ -46,6 +48,8 @@
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.quality.Strictness.LENIENT;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
@@ -61,6 +65,7 @@
import android.graphics.Insets;
import android.os.RemoteException;
import android.view.DisplayInfo;
+import android.view.DragEvent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
@@ -70,12 +75,15 @@
import com.android.wm.shell.common.DisplayLayout;
import com.android.wm.shell.draganddrop.DragAndDropPolicy.Target;
import com.android.wm.shell.splitscreen.SplitScreenController;
+import com.android.wm.shell.startingsurface.TaskSnapshotWindow;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoSession;
import java.util.ArrayList;
import java.util.Collections;
@@ -107,6 +115,7 @@
private DragAndDropPolicy mPolicy;
private ClipData mActivityClipData;
+ private ClipData mLaunchableIntentClipData;
private ClipData mNonResizeableActivityClipData;
private ClipData mTaskClipData;
private ClipData mShortcutClipData;
@@ -115,9 +124,16 @@
private ActivityManager.RunningTaskInfo mFullscreenAppTask;
private ActivityManager.RunningTaskInfo mNonResizeableFullscreenAppTask;
+ private MockitoSession mMockitoSession;
+
@Before
public void setUp() throws RemoteException {
MockitoAnnotations.initMocks(this);
+ mMockitoSession = mockitoSession()
+ .strictness(LENIENT)
+ .mockStatic(DragUtils.class)
+ .startMocking();
+ when(DragUtils.canHandleDrag(any())).thenReturn(true);
Resources res = mock(Resources.class);
Configuration config = new Configuration();
@@ -134,11 +150,12 @@
mInsets = Insets.of(0, 0, 0, 0);
mPolicy = spy(new DragAndDropPolicy(mContext, mSplitScreenStarter, mSplitScreenStarter));
- mActivityClipData = createClipData(MIMETYPE_APPLICATION_ACTIVITY);
- mNonResizeableActivityClipData = createClipData(MIMETYPE_APPLICATION_ACTIVITY);
+ mActivityClipData = createAppClipData(MIMETYPE_APPLICATION_ACTIVITY);
+ mLaunchableIntentClipData = createIntentClipData();
+ mNonResizeableActivityClipData = createAppClipData(MIMETYPE_APPLICATION_ACTIVITY);
setClipDataResizeable(mNonResizeableActivityClipData, false);
- mTaskClipData = createClipData(MIMETYPE_APPLICATION_TASK);
- mShortcutClipData = createClipData(MIMETYPE_APPLICATION_SHORTCUT);
+ mTaskClipData = createAppClipData(MIMETYPE_APPLICATION_TASK);
+ mShortcutClipData = createAppClipData(MIMETYPE_APPLICATION_SHORTCUT);
mHomeTask = createTaskInfo(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME);
mFullscreenAppTask = createTaskInfo(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
@@ -149,10 +166,15 @@
setRunningTask(mFullscreenAppTask);
}
+ @After
+ public void tearDown() {
+ mMockitoSession.finishMocking();
+ }
+
/**
- * Creates a clip data that is by default resizeable.
+ * Creates an app-based clip data that is by default resizeable.
*/
- private ClipData createClipData(String mimeType) {
+ private ClipData createAppClipData(String mimeType) {
ClipDescription clipDescription = new ClipDescription(mimeType, new String[] { mimeType });
Intent i = new Intent();
switch (mimeType) {
@@ -164,7 +186,9 @@
i.putExtra(Intent.EXTRA_TASK_ID, 12345);
break;
case MIMETYPE_APPLICATION_ACTIVITY:
- i.putExtra(ClipDescription.EXTRA_PENDING_INTENT, mock(PendingIntent.class));
+ final PendingIntent pi = mock(PendingIntent.class);
+ doReturn(android.os.Process.myUserHandle()).when(pi).getCreatorUserHandle();
+ i.putExtra(ClipDescription.EXTRA_PENDING_INTENT, pi);
break;
}
i.putExtra(Intent.EXTRA_USER, android.os.Process.myUserHandle());
@@ -175,6 +199,22 @@
return data;
}
+ /**
+ * Creates an intent-based clip data that is by default resizeable.
+ */
+ private ClipData createIntentClipData() {
+ ClipDescription clipDescription = new ClipDescription("Intent",
+ new String[] { MIMETYPE_TEXT_INTENT });
+ PendingIntent intent = mock(PendingIntent.class);
+ when(intent.getCreatorUserHandle()).thenReturn(android.os.Process.myUserHandle());
+ ClipData.Item item = new ClipData.Item.Builder()
+ .setIntentSender(intent.getIntentSender())
+ .build();
+ ClipData data = new ClipData(clipDescription, item);
+ when(DragUtils.getLaunchIntent((ClipData) any())).thenReturn(intent);
+ return data;
+ }
+
private ActivityManager.RunningTaskInfo createTaskInfo(int winMode, int actType) {
ActivityManager.RunningTaskInfo info = new ActivityManager.RunningTaskInfo();
info.configuration.windowConfiguration.setActivityType(actType);
@@ -204,58 +244,85 @@
@Test
public void testDragAppOverFullscreenHome_expectOnlyFullscreenTarget() {
+ dragOverFullscreenHome_expectOnlyFullscreenTarget(mActivityClipData);
+ }
+
+ @Test
+ public void testDragAppOverFullscreenApp_expectSplitScreenTargets() {
+ dragOverFullscreenApp_expectSplitScreenTargets(mActivityClipData);
+ }
+
+ @Test
+ public void testDragAppOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(mActivityClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenHome_expectOnlyFullscreenTarget() {
+ dragOverFullscreenHome_expectOnlyFullscreenTarget(mLaunchableIntentClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenApp_expectSplitScreenTargets() {
+ dragOverFullscreenApp_expectSplitScreenTargets(mLaunchableIntentClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(mLaunchableIntentClipData);
+ }
+
+ private void dragOverFullscreenHome_expectOnlyFullscreenTarget(ClipData data) {
doReturn(true).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mHomeTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mLandscapeDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mLandscapeDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_FULLSCREEN);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_FULLSCREEN), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_FULLSCREEN));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_UNDEFINED), any());
}
- @Test
- public void testDragAppOverFullscreenApp_expectSplitScreenTargets() {
+ private void dragOverFullscreenApp_expectSplitScreenTargets(ClipData data) {
doReturn(true).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mLandscapeDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mLandscapeDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_SPLIT_LEFT, TYPE_SPLIT_RIGHT);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_LEFT), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_LEFT));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_TOP_OR_LEFT), any());
reset(mSplitScreenStarter);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_RIGHT), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_RIGHT));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_BOTTOM_OR_RIGHT), any());
}
- @Test
- public void testDragAppOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ private void dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(ClipData data) {
doReturn(false).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mPortraitDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mPortraitDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_SPLIT_TOP, TYPE_SPLIT_BOTTOM);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_TOP), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_TOP));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_TOP_OR_LEFT), any());
reset(mSplitScreenStarter);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_BOTTOM), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_BOTTOM));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_BOTTOM_OR_RIGHT), any());
}
@@ -263,7 +330,7 @@
@Test
public void testTargetHitRects() {
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
+ DragSession dragSession = new DragSession(mActivityTaskManager,
mLandscapeDisplayLayout, mActivityClipData);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
diff --git a/media/java/android/media/RingtoneSelection.java b/media/java/android/media/RingtoneSelection.java
deleted file mode 100644
index b7c3721..0000000
--- a/media/java/android/media/RingtoneSelection.java
+++ /dev/null
@@ -1,742 +0,0 @@
-/*
- * Copyright (C) 2023 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;
-
-import static java.util.Objects.requireNonNull;
-
-import android.annotation.FlaggedApi;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.TestApi;
-import android.content.ContentProvider;
-import android.content.ContentResolver;
-import android.net.Uri;
-import android.os.UserHandle;
-import android.os.vibrator.Flags;
-import android.provider.MediaStore;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * Immutable representation a desired ringtone, usually originating from a user preference.
- * Unlike sound-only Uris, a "silent" setting is an explicit selection value, rather than null.
- *
- * <p>This representation can be converted into (or from) a URI form for storing within a string
- * preference or when using the ringtone picker via {@link RingtoneManager#ACTION_RINGTONE_PICKER}.
- * It does not carry any actual media data - it only references the components that make
- * up the preference. Initial selections can be built using {@link RingtoneSelection.Builder}.
- *
- * <p>A RingtoneSelection is typically played by passing into a {@link Ringtone.Builder}, and
- * supplementing with contextual defaults from the application. Bad Uris are handled by the
- * {@link Ringtone} class - the RingtoneSelection doesn't validate the target of the Uri.
- *
- * <p>When a RingtoneSelection is created/loaded, the values of its properties are modified
- * to be internally consistent and reflect effective values - with the exception of not verifying
- * the actual URI content. For example, loading a selection Uri that sets a sound source to
- * {@link #SOUND_SOURCE_URI}, but doesn't also have a sound Uri set, will result in this class
- * instead returning {@link #SOUND_SOURCE_UNSPECIFIED} from {@link #getSoundSource}.
- *
- * <h2>Storing preferences</h2>
- *
- * <p>A ringtone preference can have several states: either unset, set to a ringtone selection Uri,
- * or, from prior to the introduction of {@code RingtoneSelection}, set to a sound-only Uri or
- * explicitly set to null to indicate silent.
- *
- * @hide
- */
-@TestApi
-@FlaggedApi(Flags.FLAG_HAPTICS_CUSTOMIZATION_ENABLED)
-public final class RingtoneSelection {
-
- /**
- * The sound source was specified but its value was not recognized. This value is used
- * internally for not stripping unrecognised (possibly future) values during processing.
- * @hide
- */
- public static final int SOUND_SOURCE_UNKNOWN = -1;
-
- /**
- * The sound source is not explicitly specified, so it can follow default behavior for its
- * context.
- */
- public static final int SOUND_SOURCE_UNSPECIFIED = 0;
-
- /**
- * Sound is explicitly disabled, such as the user having selected "Silent" in the sound picker.
- */
- public static final int SOUND_SOURCE_OFF = 1;
-
- /**
- * The sound Uri should be used as the source of sound.
- */
- public static final int SOUND_SOURCE_URI = 2;
-
- /**
- * The sound should explicitly use the system default.
- *
- * <p>This value isn't valid within the system default itself.
- */
- public static final int SOUND_SOURCE_SYSTEM_DEFAULT = 3;
-
- // Note: Value 4 reserved for possibility of SOURCE_SOURCE_APPLICATION_DEFAULT.
-
- /**
- * Directive for how to make sound.
- * @hide
- */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "SOUND_SOURCE_", value = {
- SOUND_SOURCE_UNKNOWN,
- SOUND_SOURCE_UNSPECIFIED,
- SOUND_SOURCE_OFF,
- SOUND_SOURCE_URI,
- SOUND_SOURCE_SYSTEM_DEFAULT,
- })
- public @interface SoundSource {}
-
- /**
- * The vibration source was specified but its value was not recognized.
- * This value is used internally for not stripping unrecognised (possibly
- * future) values during processing.
- * @hide
- */
- public static final int VIBRATION_SOURCE_UNKNOWN = -1;
-
- /**
- * Vibration source is not explicitly specified. If vibration is enabled, this will use the
- * first available of {@link #VIBRATION_SOURCE_AUDIO_CHANNEL},
- * {@link #VIBRATION_SOURCE_APPLICATION_DEFAULT}, or {@link #VIBRATION_SOURCE_SYSTEM_DEFAULT}.
- */
- public static final int VIBRATION_SOURCE_UNSPECIFIED = 0;
-
- /** Specifies that vibration is explicitly disabled for this ringtone. */
- public static final int VIBRATION_SOURCE_OFF = 1;
-
- /** The vibration Uri should be used as the source of vibration. */
- public static final int VIBRATION_SOURCE_URI = 2;
-
- /**
- * The vibration should explicitly use the system default.
- *
- * <p>This value isn't valid within the system default itself.
- */
- public static final int VIBRATION_SOURCE_SYSTEM_DEFAULT = 3;
-
- /**
- * Specifies that vibration should use the vibration provided by the application. This is
- * typically the application's own default for the use-case, provided via
- * {@link Ringtone.Builder#setVibrationEffect}. For notification channels, this is the vibration
- * effect saved on the notification channel.
- *
- * <p>If no vibration is specified by the application, this value behaves if the source was
- * {@link #VIBRATION_SOURCE_UNSPECIFIED}.
- *
- * <p>This value isn't valid within the system default.
- */
- public static final int VIBRATION_SOURCE_APPLICATION_DEFAULT = 4;
-
- /**
- * Specifies that vibration should use haptic audio channels from the
- * sound Uri. If the sound URI doesn't have haptic channels, then reverts to the order specified
- * by {@link #VIBRATION_SOURCE_UNSPECIFIED}.
- */
- // Numeric gap from VIBRATION_SOURCE_APPLICATION_DEFAULT in case we want other common elements.
- public static final int VIBRATION_SOURCE_AUDIO_CHANNEL = 10;
-
- /**
- * Specifies that vibration should generate haptic audio channels from the
- * audio tracks of the sound Uri.
- *
- * If the sound Uri already has haptic channels, then behaves as though
- * {@link #VIBRATION_SOURCE_AUDIO_CHANNEL} was specified instead.
- */
- public static final int VIBRATION_SOURCE_HAPTIC_GENERATOR = 11;
-
- /**
- * Directive for how to vibrate.
- * @hide
- */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "VIBRATION_SOURCE_", value = {
- VIBRATION_SOURCE_UNKNOWN,
- VIBRATION_SOURCE_UNSPECIFIED,
- VIBRATION_SOURCE_OFF,
- VIBRATION_SOURCE_URI,
- VIBRATION_SOURCE_APPLICATION_DEFAULT,
- VIBRATION_SOURCE_AUDIO_CHANNEL,
- VIBRATION_SOURCE_HAPTIC_GENERATOR,
- })
- public @interface VibrationSource {}
-
- /**
- * Configures {@link #RingtoneSelection#fromUri} to treat an unrecognized Uri as the sound Uri
- * for the returned {@link RingtoneSelection}, with null meaning {@link #SOUND_SOURCE_OFF},
- * and symbolic default URIs ({@link RingtoneManager#getDefaultUri}) meaning
- * {@link #SOUND_SOURCE_SYSTEM_DEFAULT}.
- *
- * <p>This behavior is particularly suited to loading values from older settings that may
- * contain a raw sound Uri or null for silent.
- *
- * <p>An unrecognized Uri is one for which {@link #isRingtoneSelectionUri(Uri)} returns false.
- */
- public static final int FROM_URI_RINGTONE_SELECTION_OR_SOUND = 1;
-
- /**
- * Configures {@link #RingtoneSelection#fromUri} to treat an unrecognized Uri as the vibration
- * Uri for the returned {@link RingtoneSelection}, with null meaning
- * {@link #VIBRATION_SOURCE_OFF} and symbolic default URIs
- * ({@link RingtoneManager#getDefaultUri}) meaning {@link #VIBRATION_SOURCE_SYSTEM_DEFAULT}.
- *
- * <p>An unrecognized Uri is one for which {@link #isRingtoneSelectionUri(Uri)} returns false.
- */
- public static final int FROM_URI_RINGTONE_SELECTION_OR_VIBRATION = 2;
-
- /**
- * Configures {@link #RingtoneSelection#fromUri} to treat an unrecognized Uri as an invalid
- * value. Null or an invalid values will revert to default behavior correspnoding to
- * {@link #DEFAULT_SELECTION_URI_STRING}. Symbolic default URIs
- * ({@link RingtoneManager#getDefaultUri}) will set both
- * {@link #SOUND_SOURCE_SYSTEM_DEFAULT} and {@link #VIBRATION_SOURCE_SYSTEM_DEFAULT}.
- *
- * <p>An unrecognized Uri is one for which {@link #isRingtoneSelectionUri(Uri)} returns false,
- * which include {@code null}.
- */
- public static final int FROM_URI_RINGTONE_SELECTION_ONLY = 3;
-
- /**
- * How to treat values in {@link #fromUri}.
- * @hide
- */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "FROM_URI_", value = {
- FROM_URI_RINGTONE_SELECTION_OR_SOUND,
- FROM_URI_RINGTONE_SELECTION_OR_VIBRATION,
- FROM_URI_RINGTONE_SELECTION_ONLY
- })
- public @interface FromUriBehavior {}
-
- private static final String BASE_RINGTONE_URI = "content://media/ringtone";
- /**
- * String representation of a RingtoneSelection Uri that says to use defaults (equivalent
- * to {@code new RingtoneSelection.Builder().build()}).
- */
- public static final String DEFAULT_SELECTION_URI_STRING = BASE_RINGTONE_URI;
-
- private static final String MEDIA_URI_RINGTONE_PATH = "/ringtone";
-
- /* Query param keys. */
- private static final String URI_PARAM_SOUND_URI = "su";
- private static final String URI_PARAM_SOUND_SOURCE = "ss";
- private static final String URI_PARAM_VIBRATION_URI = "vu";
- private static final String URI_PARAM_VIBRATION_SOURCE = "vs";
-
- /* Common param values */
- private static final String SOURCE_OFF_STRING = "off";
- private static final String SOURCE_SYSTEM_DEFAULT_STRING = "sys";
-
- /* Vibration source param values. */
- private static final String VIBRATION_SOURCE_AUDIO_CHANNEL_STRING = "ac";
- private static final String VIBRATION_SOURCE_APPLICATION_DEFAULT_STRING = "app";
- private static final String VIBRATION_SOURCE_HAPTIC_GENERATOR_STRING = "hg";
-
- @Nullable
- private final Uri mSoundUri;
- @SoundSource
- private final int mSoundSource;
-
- @Nullable
- private final Uri mVibrationUri;
- @VibrationSource
- private final int mVibrationSource;
-
- private RingtoneSelection(@Nullable Uri soundUri, @SoundSource int soundSource,
- @Nullable Uri vibrationUri, @VibrationSource int vibrationSource) {
- // Enforce guarantees on the source values: revert to unspecified if they depend on
- // something that's not set.
- //
- // The non-public "unknown" value can't appear in a getter result, it's just a reserved
- // "null" value and should be treated the same as an unrecognized value. This can be seen
- // in Uri parsing. For this and other unrecognized values, we either revert them to the URI
- // source, if a Uri was included, or the "unspecified" source otherwise. This can be
- // seen in action in the Uri parsing.
- //
- // The "unspecified" source is a public value meaning that there is no specific
- // behavior indicated, and the defaults and fallbacks should be applied. For example, an
- // vibration source value of "system default" means to explicitly use the system default
- // vibration. However, an "unspecified" vibration source will first see if audio coupled
- // or application-default vibrations are available.
- mSoundSource = switch (soundSource) {
- // Supported explicit values that don't have a Uri.
- case SOUND_SOURCE_OFF, SOUND_SOURCE_UNSPECIFIED, SOUND_SOURCE_SYSTEM_DEFAULT ->
- soundSource;
- // Uri and unknown/unrecognized values: use a Uri if one is present, else revert to
- // unspecified.
- default ->
- soundUri != null ? SOUND_SOURCE_URI : SOUND_SOURCE_UNSPECIFIED;
- };
- mVibrationSource = switch (vibrationSource) {
- // Enforce vibration sources that require a sound Uri.
- case VIBRATION_SOURCE_AUDIO_CHANNEL, VIBRATION_SOURCE_HAPTIC_GENERATOR ->
- soundUri != null ? vibrationSource : VIBRATION_SOURCE_UNSPECIFIED;
- // Supported explicit values that don't rely on any Uri.
- case VIBRATION_SOURCE_OFF, VIBRATION_SOURCE_UNSPECIFIED,
- VIBRATION_SOURCE_SYSTEM_DEFAULT, VIBRATION_SOURCE_APPLICATION_DEFAULT ->
- vibrationSource;
- // Uri and unknown/unrecognized values: use a Uri if one is present, else revert to
- // unspecified.
- default ->
- vibrationUri != null ? VIBRATION_SOURCE_URI : VIBRATION_SOURCE_UNSPECIFIED;
- };
- // Clear Uri values if they're un-used by the source.
- mSoundUri = mSoundSource == SOUND_SOURCE_URI ? soundUri : null;
- mVibrationUri = mVibrationSource == VIBRATION_SOURCE_URI ? vibrationUri : null;
- }
-
- /**
- * Returns the stored sound behavior.
- */
- @SoundSource
- public int getSoundSource() {
- return mSoundSource;
- }
-
- /**
- * Returns the sound Uri for this selection. This is guaranteed to be non-null if
- * {@link #getSoundSource} returns {@link #SOUND_SOURCE_URI}.
- */
- @Nullable
- public Uri getSoundUri() {
- return mSoundUri;
- }
-
- /**
- * Returns the selected vibration behavior.
- */
- @VibrationSource
- public int getVibrationSource() {
- return mVibrationSource;
- }
-
- /**
- * Returns the vibration Uri for this selection. This is guaranteed to be non-null if
- * {@link #getVibrationSource} returns {@link #SOUND_SOURCE_URI}.
- */
- @Nullable
- public Uri getVibrationUri() {
- return mVibrationUri;
- }
-
- /**
- * Converts the ringtone selection into a Uri-form, suitable for storing as a user preference
- * or returning as a result.
- */
- @NonNull
- public Uri toUri() {
- Uri.Builder builder = new Uri.Builder()
- .scheme(ContentResolver.SCHEME_CONTENT)
- .authority(MediaStore.AUTHORITY)
- .path(MEDIA_URI_RINGTONE_PATH);
- if (mSoundUri != null) {
- builder.appendQueryParameter(URI_PARAM_SOUND_URI, mSoundUri.toString());
- }
- // Only off is explicit for sound sources
- String soundSourceStr = soundSourceToString(mSoundSource);
- if (soundSourceStr != null) {
- builder.appendQueryParameter(URI_PARAM_SOUND_SOURCE, soundSourceStr);
- }
- if (mVibrationUri != null) {
- builder.appendQueryParameter(URI_PARAM_VIBRATION_URI, mVibrationUri.toString());
- }
- String vibrationSourceStr = vibrationSourceToString(mVibrationSource);
- if (vibrationSourceStr != null) {
- builder.appendQueryParameter(URI_PARAM_VIBRATION_SOURCE, vibrationSourceStr);
- }
- return builder.build();
- }
-
- /**
- * Returns true if the Uri is an encoded {@link RingtoneSelection}. This method doesn't
- * validate the parameters of the selection.
- *
- * @see #fromUri
- * @see #toUri
- */
- public static boolean isRingtoneSelectionUri(@Nullable Uri uri) {
- if (uri == null) {
- return false;
- }
- // Any URI content://media/ringtone
- return ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())
- && MediaStore.AUTHORITY.equals(
- ContentProvider.getAuthorityWithoutUserId(uri.getAuthority()))
- && MEDIA_URI_RINGTONE_PATH.equals(uri.getPath());
- }
-
- /**
- * Strip the specified userId from internal Uris. Non-stripped userIds will typically be
- * for work profiles referencing system ringtones from the host user.
- *
- * This is only for use in RingtoneManager.
- * @hide
- */
- @VisibleForTesting
- public RingtoneSelection getWithoutUserId(int userIdToStrip) {
- if (mSoundSource != SOUND_SOURCE_URI && mVibrationSource != VIBRATION_SOURCE_URI) {
- return this;
- }
-
- // Ok if uri is null. We only replace explicit references to the specified (current) userId.
- int soundUserId = ContentProvider.getUserIdFromUri(mSoundUri, UserHandle.USER_NULL);
- int vibrationUserId = ContentProvider.getUserIdFromUri(mVibrationUri, UserHandle.USER_NULL);
- boolean needToChangeSound =
- soundUserId != UserHandle.USER_NULL && soundUserId == userIdToStrip;
- boolean needToChangeVibration =
- vibrationUserId != UserHandle.USER_NULL && vibrationUserId == userIdToStrip;
-
- // Anything to do?
- if (!needToChangeSound && !needToChangeVibration) {
- return this;
- }
-
- RingtoneSelection.Builder updated = new Builder(this);
- // The relevant uris can't be null, because they contain userIdToStrip.
- if (needToChangeSound) {
- // mSoundUri is not null, so the result of getUriWithoutUserId won't be null.
- updated.setSoundSource(ContentProvider.getUriWithoutUserId(mSoundUri));
- }
- if (needToChangeVibration) {
- updated.setVibrationSource(ContentProvider.getUriWithoutUserId(mVibrationUri));
- }
- return updated.build();
- }
-
- @Override
- public String toString() {
- return toUri().toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof RingtoneSelection other)) {
- return false;
- }
- return this.mSoundSource == other.mSoundSource
- && this.mVibrationSource == other.mVibrationSource
- && Objects.equals(this.mSoundUri, other.mSoundUri)
- && Objects.equals(this.mVibrationUri, other.mVibrationUri);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSoundSource, mVibrationSource, mSoundUri, mVibrationUri);
- }
-
- /**
- * Converts a Uri into a RingtoneSelection.
- *
- * <p>Null values, Uris that {@link #isRingtoneSelectionUri(Uri)} returns false (except for
- * old-style symbolic default Uris {@link RingtoneManager#getDefaultUri}) will be treated
- * according to the behaviour specified by the {@code unrecognizedValueBehavior} parameter.
- *
- * <p>Symbolic default Uris (where {@link RingtoneManager#getDefaultType(Uri)} returns -1,
- * will map sources to {@link #SOUND_SOURCE_SYSTEM_DEFAULT} and
- * {@link #VIBRATION_SOURCE_SYSTEM_DEFAULT}.
- *
- * @param uri The Uri to convert, potentially null.
- * @param unrecognizedValueBehavior indicates how to treat values for which
- * {@link #isRingtoneSelectionUri(Uri)} returns false (including null).
- * @return the RingtoneSelection represented by the given uri.
- */
- @NonNull
- public static RingtoneSelection fromUri(@Nullable Uri uri,
- @FromUriBehavior int unrecognizedValueBehavior) {
- if (isRingtoneSelectionUri(uri)) {
- return parseRingtoneSelectionUri(uri);
- }
- // Old symbolic default URIs map to the sources suggested by the unrecognized behavior.
- // It doesn't always map to both sources because the app may have its own default behavior
- // to apply, so non-primary sources are left as unspecified, which will revert to the
- // system default in the absence of an app default.
- boolean isDefaultUri = RingtoneManager.getDefaultType(uri) > 0;
- RingtoneSelection.Builder builder = new RingtoneSelection.Builder();
- switch (unrecognizedValueBehavior) {
- case FROM_URI_RINGTONE_SELECTION_ONLY:
- if (isDefaultUri) {
- builder.setSoundSource(SOUND_SOURCE_SYSTEM_DEFAULT);
- builder.setVibrationSource(VIBRATION_SOURCE_SYSTEM_DEFAULT);
- }
- // Always return unspecified (defaults) for unrecognized ringtone selection Uris.
- return builder.build();
- case FROM_URI_RINGTONE_SELECTION_OR_SOUND:
- if (uri == null) {
- return builder.setSoundSource(SOUND_SOURCE_OFF).build();
- } else if (isDefaultUri) {
- return builder.setSoundSource(SOUND_SOURCE_SYSTEM_DEFAULT).build();
- } else {
- return builder.setSoundSource(uri).build();
- }
- case FROM_URI_RINGTONE_SELECTION_OR_VIBRATION:
- if (uri == null) {
- return builder.setVibrationSource(VIBRATION_SOURCE_OFF).build();
- } else if (isDefaultUri) {
- return builder.setVibrationSource(VIBRATION_SOURCE_SYSTEM_DEFAULT).build();
- } else {
- // Unlike sound, there's no legacy settings alias uri for the default.
- return builder.setVibrationSource(uri).build();
- }
- default:
- throw new IllegalArgumentException("Unknown behavior parameter: "
- + unrecognizedValueBehavior);
- }
- }
-
- /**
- * Parses the Uri, which has already been checked for {@link #isRingtoneSelectionUri(Uri)}.
- * As a special case to be more compatible, if the RingtoneSelection has a userId specified in
- * the authority, then this is pushed down into the sound and vibration Uri, as the selection
- * itself is agnostic.
- */
- @NonNull
- private static RingtoneSelection parseRingtoneSelectionUri(@NonNull Uri uri) {
- RingtoneSelection.Builder builder = new RingtoneSelection.Builder();
- int soundSource = stringToSoundSource(uri.getQueryParameter(URI_PARAM_SOUND_SOURCE));
- int vibrationSource = stringToVibrationSource(
- uri.getQueryParameter(URI_PARAM_VIBRATION_SOURCE));
- Uri soundUri = getParamAsUri(uri, URI_PARAM_SOUND_URI);
- Uri vibrationUri = getParamAsUri(uri, URI_PARAM_VIBRATION_URI);
-
- // Add userId if necessary. This won't override an existing one in the sound/vib Uris.
- int userIdFromAuthority = ContentProvider.getUserIdFromAuthority(
- uri.getAuthority(), UserHandle.USER_NULL);
- if (userIdFromAuthority != UserHandle.USER_NULL) {
- // Won't override existing user id.
- if (soundUri != null) {
- soundUri = ContentProvider.maybeAddUserId(soundUri, userIdFromAuthority);
- }
- if (vibrationUri != null) {
- vibrationUri = ContentProvider.maybeAddUserId(vibrationUri, userIdFromAuthority);
- }
- }
-
- // Set sound uri if present, but map system default Uris to the system default source.
- if (soundUri != null) {
- if (RingtoneManager.getDefaultType(uri) >= 0) {
- builder.setSoundSource(SOUND_SOURCE_SYSTEM_DEFAULT);
- } else {
- builder.setSoundSource(soundUri);
- }
- }
- if (vibrationUri != null) {
- builder.setVibrationSource(vibrationUri);
- }
-
- // Don't set the source if there's a URI and the source is default, because that will
- // override the Uri source set above. In effect, we prioritise "explicit" sources over
- // an implicit Uri source - except for "default", which isn't really explicit.
- if (soundSource != SOUND_SOURCE_UNSPECIFIED || soundUri == null) {
- builder.setSoundSource(soundSource);
- }
- if (vibrationSource != VIBRATION_SOURCE_UNSPECIFIED || vibrationUri == null) {
- builder.setVibrationSource(vibrationSource);
- }
- return builder.build();
- }
-
- @Nullable
- private static Uri getParamAsUri(@NonNull Uri uri, String param) {
- // This returns the uri-decoded value, no need to further decode.
- String value = uri.getQueryParameter(param);
- if (value == null) {
- return null;
- }
- return Uri.parse(value);
- }
-
- /**
- * Converts the {@link SoundSource} to the uri query param value for it, or null
- * if the sound source is default, unknown, or implicit (uri).
- */
- @Nullable
- private static String soundSourceToString(@SoundSource int soundSource) {
- return switch (soundSource) {
- case SOUND_SOURCE_OFF -> SOURCE_OFF_STRING;
- case SOUND_SOURCE_SYSTEM_DEFAULT -> SOURCE_SYSTEM_DEFAULT_STRING;
- default -> null;
- };
- }
-
- /**
- * Returns the sound source int corresponding to the query string value. Returns
- * {@link #SOUND_SOURCE_UNKNOWN} if the value isn't recognised, and
- * {@link #SOUND_SOURCE_UNSPECIFIED} if the value is {@code null} (not in the Uri).
- */
- @SoundSource
- private static int stringToSoundSource(@Nullable String soundSource) {
- if (soundSource == null) {
- return SOUND_SOURCE_UNSPECIFIED;
- }
- return switch (soundSource) {
- case SOURCE_OFF_STRING -> SOUND_SOURCE_OFF;
- case SOURCE_SYSTEM_DEFAULT_STRING -> SOUND_SOURCE_SYSTEM_DEFAULT;
- default -> SOUND_SOURCE_UNKNOWN;
- };
- }
-
- /**
- * Converts the {@code vibrationSource} to the uri query param value for it, or null
- * if the vibration source is default, unknown, or implicit (uri).
- */
- @Nullable
- private static String vibrationSourceToString(@VibrationSource int vibrationSource) {
- return switch (vibrationSource) {
- case VIBRATION_SOURCE_OFF -> SOURCE_OFF_STRING;
- case VIBRATION_SOURCE_AUDIO_CHANNEL -> VIBRATION_SOURCE_AUDIO_CHANNEL_STRING;
- case VIBRATION_SOURCE_HAPTIC_GENERATOR -> VIBRATION_SOURCE_HAPTIC_GENERATOR_STRING;
- case VIBRATION_SOURCE_APPLICATION_DEFAULT ->
- VIBRATION_SOURCE_APPLICATION_DEFAULT_STRING;
- case VIBRATION_SOURCE_SYSTEM_DEFAULT -> SOURCE_SYSTEM_DEFAULT_STRING;
- default -> null;
- };
- }
-
- @VibrationSource
- private static int stringToVibrationSource(@Nullable String vibrationSource) {
- if (vibrationSource == null) {
- return VIBRATION_SOURCE_UNSPECIFIED;
- }
- return switch (vibrationSource) {
- case SOURCE_OFF_STRING -> VIBRATION_SOURCE_OFF;
- case SOURCE_SYSTEM_DEFAULT_STRING -> VIBRATION_SOURCE_SYSTEM_DEFAULT;
- case VIBRATION_SOURCE_AUDIO_CHANNEL_STRING -> VIBRATION_SOURCE_AUDIO_CHANNEL;
- case VIBRATION_SOURCE_HAPTIC_GENERATOR_STRING -> VIBRATION_SOURCE_HAPTIC_GENERATOR;
- case VIBRATION_SOURCE_APPLICATION_DEFAULT_STRING ->
- VIBRATION_SOURCE_APPLICATION_DEFAULT;
- default -> VIBRATION_SOURCE_UNKNOWN;
- };
- }
-
- /**
- * Builder for {@link RingtoneSelection}. In general, this builder will be used by interfaces
- * allowing the user to configure their selection. Once a selection is stored as a Uri, then
- * the RingtoneSelection can be loaded directly using {@link RingtoneSelection#fromUri}.
- */
- @FlaggedApi(Flags.FLAG_HAPTICS_CUSTOMIZATION_ENABLED)
- public static final class Builder {
- private Uri mSoundUri;
- private Uri mVibrationUri;
- @SoundSource private int mSoundSource = SOUND_SOURCE_UNSPECIFIED;
- @VibrationSource private int mVibrationSource = VIBRATION_SOURCE_UNSPECIFIED;
-
- /**
- * Creates a new {@link RingtoneSelection} builder. A default ringtone selection has its
- * sound and vibration source unspecified, which means they would fall back to app/system
- * defaults.
- */
- public Builder() {}
-
- /**
- * Creates a builder initialized with the given ringtone selection.
- */
- public Builder(@NonNull RingtoneSelection selection) {
- requireNonNull(selection);
- mSoundSource = selection.getSoundSource();
- mSoundUri = selection.getSoundUri();
- mVibrationSource = selection.getVibrationSource();
- mVibrationUri = selection.getVibrationUri();
- }
-
- /**
- * Sets the desired sound source.
- *
- * <p>Values other than {@link #SOUND_SOURCE_URI} will clear any previous sound Uri.
- * For {@link #SOUND_SOURCE_URI}, the {@link #setSoundSource(Uri)} method should be
- * used instead, as setting it here will have no effect unless the Uri is also set.
- */
- @NonNull
- public Builder setSoundSource(@SoundSource int soundSource) {
- mSoundSource = soundSource;
- if (soundSource != SOUND_SOURCE_URI && soundSource != SOUND_SOURCE_UNKNOWN) {
- // Note that this means the configuration of "silent sound, but use haptic
- // generator" is currently not supported. Future support could be added by either
- // using the vibration uri in that case, or by having a special
- // "setSoundUriForVibrationOnly(Uri)" method that sets sound source to off but
- // also retains the Uri.
- mSoundUri = null;
- }
- return this;
- }
-
- /**
- * Sets the sound source to {@link #SOUND_SOURCE_URI}, and the sound Uri to the
- * specified {@link Uri}.
- */
- @NonNull
- public Builder setSoundSource(@NonNull Uri soundUri) {
- // getCanonicalUri shouldn't return null. If it somehow did, then the
- // RingtoneSelection constructor will revert this to unspecified.
- mSoundUri = requireNonNull(soundUri).getCanonicalUri();
- mSoundSource = SOUND_SOURCE_URI;
- return this;
- }
-
- /**
- * Sets the vibration source to the specified value.
- *
- * <p>Values other than {@link #VIBRATION_SOURCE_URI} will clear any previous vibration Uri.
- * For {@link #VIBRATION_SOURCE_URI}, the {@link #setVibrationSource(Uri)} method should be
- * used instead, as setting it here will have no effect unless the Uri is also set.
- */
- @NonNull
- public Builder setVibrationSource(@VibrationSource int vibrationSource) {
- mVibrationSource = vibrationSource;
- if (vibrationSource != VIBRATION_SOURCE_URI
- && vibrationSource != VIBRATION_SOURCE_UNKNOWN) {
- mVibrationUri = null;
- }
- return this;
- }
-
- /**
- * Sets the vibration source to {@link #VIBRATION_SOURCE_URI}, and the vibration Uri to the
- * specified {@link Uri}.
- */
- @NonNull
- public Builder setVibrationSource(@NonNull Uri vibrationUri) {
- // getCanonicalUri shouldn't return null. If it somehow did, then the
- // RingtoneSelection constructor will revert this to unspecified.
- mVibrationUri = requireNonNull(vibrationUri).getCanonicalUri();
- mVibrationSource = VIBRATION_SOURCE_URI;
- return this;
- }
-
- /**
- * Returns the ringtone Uri that was configured.
- */
- @NonNull
- public RingtoneSelection build() {
- return new RingtoneSelection(mSoundUri, mSoundSource, mVibrationUri, mVibrationSource);
- }
- }
-}
diff --git a/media/java/android/media/audiopolicy/AudioMix.java b/media/java/android/media/audiopolicy/AudioMix.java
index 48b4766..60ab1a4 100644
--- a/media/java/android/media/audiopolicy/AudioMix.java
+++ b/media/java/android/media/audiopolicy/AudioMix.java
@@ -27,7 +27,9 @@
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioSystem;
+import android.os.Binder;
import android.os.Build;
+import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
@@ -52,6 +54,8 @@
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private int mMixType = MIX_TYPE_INVALID;
+ private final IBinder mToken;
+
// written by AudioPolicy
int mMixState = MIX_STATE_DISABLED;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
@@ -68,7 +72,7 @@
*/
private AudioMix(@NonNull AudioMixingRule rule, @NonNull AudioFormat format,
int routeFlags, int callbackFlags,
- int deviceType, @Nullable String deviceAddress) {
+ int deviceType, @Nullable String deviceAddress, IBinder token) {
mRule = Objects.requireNonNull(rule);
mFormat = Objects.requireNonNull(format);
mRouteFlags = routeFlags;
@@ -76,6 +80,7 @@
mCallbackFlags = callbackFlags;
mDeviceSystemType = deviceType;
mDeviceAddress = (deviceAddress == null) ? new String("") : deviceAddress;
+ mToken = token;
}
// CALLBACK_FLAG_* values: keep in sync with AudioMix::kCbFlag* values defined
@@ -273,13 +278,14 @@
return Objects.equals(this.mRouteFlags, that.mRouteFlags)
&& Objects.equals(this.mRule, that.mRule)
&& Objects.equals(this.mMixType, that.mMixType)
- && Objects.equals(this.mFormat, that.mFormat);
+ && Objects.equals(this.mFormat, that.mFormat)
+ && Objects.equals(this.mToken, that.mToken);
}
/** @hide */
@Override
public int hashCode() {
- return Objects.hash(mRouteFlags, mRule, mMixType, mFormat);
+ return Objects.hash(mRouteFlags, mRule, mMixType, mFormat, mToken);
}
@Override
@@ -298,6 +304,7 @@
dest.writeString8(mDeviceAddress);
mFormat.writeToParcel(dest, flags);
mRule.writeToParcel(dest, flags);
+ dest.writeStrongBinder(mToken);
}
public static final @NonNull Parcelable.Creator<AudioMix> CREATOR = new Parcelable.Creator<>() {
@@ -317,6 +324,7 @@
mixBuilder.setDevice(p.readInt(), p.readString8());
mixBuilder.setFormat(AudioFormat.CREATOR.createFromParcel(p));
mixBuilder.setMixingRule(AudioMixingRule.CREATOR.createFromParcel(p));
+ mixBuilder.setToken(p.readStrongBinder());
return mixBuilder.build();
}
@@ -339,6 +347,7 @@
private AudioFormat mFormat = null;
private int mRouteFlags = 0;
private int mCallbackFlags = 0;
+ private IBinder mToken = null;
// an AudioSystem.DEVICE_* value, not AudioDeviceInfo.TYPE_*
private int mDeviceSystemType = AudioSystem.DEVICE_NONE;
private String mDeviceAddress = null;
@@ -380,6 +389,15 @@
/**
* @hide
+ * Only used by AudioMix internally.
+ */
+ Builder setToken(IBinder token) {
+ mToken = token;
+ return this;
+ }
+
+ /**
+ * @hide
* Only used by AudioPolicyConfig, not a public API.
* @param callbackFlags which callbacks are called from native
* @return the same Builder instance.
@@ -540,8 +558,13 @@
throw new IllegalArgumentException(error);
}
}
+
+ if (mToken == null) {
+ mToken = new Binder();
+ }
+
return new AudioMix(mRule, mFormat, mRouteFlags, mCallbackFlags, mDeviceSystemType,
- mDeviceAddress);
+ mDeviceAddress, mToken);
}
private int getLoopbackDeviceSystemTypeForAudioMixingRule(AudioMixingRule rule) {
diff --git a/media/java/android/media/audiopolicy/AudioPolicy.java b/media/java/android/media/audiopolicy/AudioPolicy.java
index bbe461c..508c0a2b 100644
--- a/media/java/android/media/audiopolicy/AudioPolicy.java
+++ b/media/java/android/media/audiopolicy/AudioPolicy.java
@@ -337,7 +337,9 @@
/**
* Update the current configuration of the set of audio mixes by adding new ones, while
- * keeping the policy registered.
+ * keeping the policy registered. If any of the provided audio mixes is invalid then none of
+ * the passed mixes will be registered.
+ *
* This method can only be called on a registered policy.
* @param mixes the list of {@link AudioMix} to add
* @return {@link AudioManager#SUCCESS} if the change was successful, {@link AudioManager#ERROR}
@@ -375,12 +377,15 @@
}
/**
- * Update the current configuration of the set of audio mixes by removing some, while
- * keeping the policy registered.
- * This method can only be called on a registered policy.
+ * Update the current configuration of the set of audio mixes for this audio policy by
+ * removing some, while keeping the policy registered. Will unregister all provided audio
+ * mixes, if possible.
+ *
+ * This method can only be called on a registered policy and only affects this current policy.
* @param mixes the list of {@link AudioMix} to remove
* @return {@link AudioManager#SUCCESS} if the change was successful, {@link AudioManager#ERROR}
- * otherwise.
+ * otherwise. If only some of the provided audio mixes were detached but any one mix
+ * failed to be detached, this method returns {@link AudioManager#ERROR}.
*/
public int detachMixes(@NonNull List<AudioMix> mixes) {
if (mixes == null) {
@@ -394,7 +399,6 @@
for (AudioMix mix : mixes) {
if (mix == null) {
throw new IllegalArgumentException("Illegal null AudioMix in detachMixes");
- // TODO also check mix is currently contained in list of mixes
} else {
zeMixes.add(mix);
}
diff --git a/media/java/android/media/audiopolicy/AudioPolicyConfig.java b/media/java/android/media/audiopolicy/AudioPolicyConfig.java
index d277c7d..5e7c7c4 100644
--- a/media/java/android/media/audiopolicy/AudioPolicyConfig.java
+++ b/media/java/android/media/audiopolicy/AudioPolicyConfig.java
@@ -228,7 +228,7 @@
}
}
- private void setMixRegistration(@NonNull final AudioMix mix) {
+ protected void setMixRegistration(@NonNull final AudioMix mix) {
if (!mRegistrationId.isEmpty()) {
if ((mix.getRouteFlags() & AudioMix.ROUTE_FLAG_LOOP_BACK) ==
AudioMix.ROUTE_FLAG_LOOP_BACK) {
@@ -246,7 +246,9 @@
@GuardedBy("mMixes")
protected void add(@NonNull ArrayList<AudioMix> mixes) {
for (AudioMix mix : mixes) {
- setMixRegistration(mix);
+ if (mix.getRegistration() == null || mix.getRegistration().isEmpty()) {
+ setMixRegistration(mix);
+ }
mMixes.add(mix);
}
}
diff --git a/media/tests/projection/Android.bp b/media/tests/projection/Android.bp
index c9a8864..fd5f195 100644
--- a/media/tests/projection/Android.bp
+++ b/media/tests/projection/Android.bp
@@ -3,6 +3,7 @@
//########################################################################
package {
+ default_team: "trendy_team_lse_desktop_os_experience",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_base_license"
diff --git a/nfc/api/current.txt b/nfc/api/current.txt
index 0fb7c95..9d0221a 100644
--- a/nfc/api/current.txt
+++ b/nfc/api/current.txt
@@ -206,9 +206,9 @@
method public boolean registerAidsForService(android.content.ComponentName, String, java.util.List<java.lang.String>);
method @FlaggedApi("android.nfc.nfc_read_polling_loop") public boolean registerPollingLoopFilterForService(@NonNull android.content.ComponentName, @NonNull String, boolean);
method public boolean removeAidsForService(android.content.ComponentName, String);
- method @FlaggedApi("android.nfc.nfc_observe_mode") public boolean setDefaultToObserveModeForService(@NonNull android.content.ComponentName, boolean);
method @NonNull @RequiresPermission(android.Manifest.permission.NFC) public boolean setOffHostForService(@NonNull android.content.ComponentName, @NonNull String);
method public boolean setPreferredService(android.app.Activity, android.content.ComponentName);
+ method @FlaggedApi("android.nfc.nfc_observe_mode") public boolean setShouldDefaultToObserveModeForService(@NonNull android.content.ComponentName, boolean);
method public boolean supportsAidPrefixRegistration();
method @NonNull @RequiresPermission(android.Manifest.permission.NFC) public boolean unsetOffHostForService(@NonNull android.content.ComponentName);
method public boolean unsetPreferredService(android.app.Activity);
diff --git a/nfc/java/android/nfc/INfcCardEmulation.aidl b/nfc/java/android/nfc/INfcCardEmulation.aidl
index 64f7fa4..85a07b7 100644
--- a/nfc/java/android/nfc/INfcCardEmulation.aidl
+++ b/nfc/java/android/nfc/INfcCardEmulation.aidl
@@ -30,7 +30,7 @@
boolean isDefaultServiceForAid(int userHandle, in ComponentName service, String aid);
boolean setDefaultServiceForCategory(int userHandle, in ComponentName service, String category);
boolean setDefaultForNextTap(int userHandle, in ComponentName service);
- boolean setDefaultToObserveModeForService(int userId, in android.content.ComponentName service, boolean enable);
+ boolean setShouldDefaultToObserveModeForService(int userId, in android.content.ComponentName service, boolean enable);
boolean registerAidGroupForService(int userHandle, in ComponentName service, in AidGroup aidGroup);
boolean registerPollingLoopFilterForService(int userHandle, in ComponentName service, in String pollingLoopFilter, boolean autoTransact);
boolean setOffHostForService(int userHandle, in ComponentName service, in String offHostSecureElement);
diff --git a/nfc/java/android/nfc/cardemulation/ApduServiceInfo.java b/nfc/java/android/nfc/cardemulation/ApduServiceInfo.java
index e62e37b..2c7d61e 100644
--- a/nfc/java/android/nfc/cardemulation/ApduServiceInfo.java
+++ b/nfc/java/android/nfc/cardemulation/ApduServiceInfo.java
@@ -141,7 +141,7 @@
/**
* Whether the NFC stack should default to Observe Mode when this preferred service.
*/
- private boolean mDefaultToObserveMode;
+ private boolean mShouldDefaultToObserveMode;
/**
* @hide
@@ -275,8 +275,8 @@
com.android.internal.R.styleable.HostApduService_settingsActivity);
mOffHostName = null;
mStaticOffHostName = mOffHostName;
- mDefaultToObserveMode = sa.getBoolean(
- R.styleable.HostApduService_defaultToObserveMode,
+ mShouldDefaultToObserveMode = sa.getBoolean(
+ R.styleable.HostApduService_shouldDefaultToObserveMode,
false);
sa.recycle();
} else {
@@ -297,8 +297,8 @@
com.android.internal.R.styleable.HostApduService_settingsActivity);
mOffHostName = sa.getString(
com.android.internal.R.styleable.OffHostApduService_secureElementName);
- mDefaultToObserveMode = sa.getBoolean(
- R.styleable.HostApduService_defaultToObserveMode,
+ mShouldDefaultToObserveMode = sa.getBoolean(
+ R.styleable.HostApduService_shouldDefaultToObserveMode,
false);
if (mOffHostName != null) {
if (mOffHostName.equals("eSE")) {
@@ -633,22 +633,22 @@
}
/**
- * Returns whether the NFC stack should default to observe mode when this servise is preferred.
- * @return whether the NFC stack should default to observe mode when this servise is preferred
+ * Returns whether the NFC stack should default to observe mode when this service is preferred.
+ * @return whether the NFC stack should default to observe mode when this service is preferred
*/
@FlaggedApi(Flags.FLAG_NFC_OBSERVE_MODE)
- public boolean defaultToObserveMode() {
- return mDefaultToObserveMode;
+ public boolean shouldDefaultToObserveMode() {
+ return mShouldDefaultToObserveMode;
}
/**
- * Sets whether the NFC stack should default to observe mode when this servise is preferred.
- * @param defaultToObserveMode whether the NFC stack should default to observe mode when this
- * servise is preferred
+ * Sets whether the NFC stack should default to observe mode when this service is preferred.
+ * @param shouldDefaultToObserveMode whether the NFC stack should default to observe mode when
+ * this service is preferred
*/
@FlaggedApi(Flags.FLAG_NFC_OBSERVE_MODE)
- public void setDefaultToObserveMode(boolean defaultToObserveMode) {
- mDefaultToObserveMode = defaultToObserveMode;
+ public void setShouldDefaultToObserveMode(boolean shouldDefaultToObserveMode) {
+ mShouldDefaultToObserveMode = shouldDefaultToObserveMode;
}
/**
diff --git a/nfc/java/android/nfc/cardemulation/CardEmulation.java b/nfc/java/android/nfc/cardemulation/CardEmulation.java
index 47ddd9d..ea58504 100644
--- a/nfc/java/android/nfc/cardemulation/CardEmulation.java
+++ b/nfc/java/android/nfc/cardemulation/CardEmulation.java
@@ -348,11 +348,11 @@
* @return whether the change was successful.
*/
@FlaggedApi(Flags.FLAG_NFC_OBSERVE_MODE)
- public boolean setDefaultToObserveModeForService(@NonNull ComponentName service,
+ public boolean setShouldDefaultToObserveModeForService(@NonNull ComponentName service,
boolean enable) {
try {
- return sService.setDefaultToObserveModeForService(mContext.getUser().getIdentifier(),
- service, enable);
+ return sService.setShouldDefaultToObserveModeForService(
+ mContext.getUser().getIdentifier(), service, enable);
} catch (RemoteException e) {
Log.e(TAG, "Failed to reach CardEmulationService.");
}
diff --git a/packages/CredentialManager/res/drawable/ic_passkey_24.xml b/packages/CredentialManager/res/drawable/ic_passkey_24.xml
index a2c4f37..5298f9e 100644
--- a/packages/CredentialManager/res/drawable/ic_passkey_24.xml
+++ b/packages/CredentialManager/res/drawable/ic_passkey_24.xml
@@ -13,16 +13,14 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
-
-<vector
- android:alpha="0.8"
- android:height="24dp"
- android:viewportHeight="24"
- android:viewportWidth="24"
- android:width="24dp"
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools">
- <path android:fillColor="#4C463C" android:fillType="evenOdd" android:pathData="M22.18,14.09C22.18,15.364 21.408,16.459 20.306,16.931L21.247,17.872L20.219,18.9L21.247,19.928L19.068,22.107L18.099,21.138L18.099,17.017C16.878,16.604 16,15.45 16,14.09C16,12.383 17.383,11 19.09,11C20.796,11 22.18,12.383 22.18,14.09ZM20.692,14.091C20.692,14.976 19.975,15.693 19.09,15.693C18.205,15.693 17.488,14.976 17.488,14.091C17.488,13.206 18.205,12.488 19.09,12.488C19.975,12.488 20.692,13.206 20.692,14.091Z"/>
- <path android:fillColor="#4C463C" android:pathData="M14.978,8.476C14.978,10.865 13.041,12.802 10.652,12.802C8.263,12.802 6.326,10.865 6.326,8.476C6.326,6.087 8.263,4.15 10.652,4.15C13.041,4.15 14.978,6.087 14.978,8.476Z"/>
- <path android:fillColor="#4C463C" android:pathData="M2,19.263C2,16.39 7.762,14.937 10.652,14.937C11.782,14.937 13.353,15.16 14.845,15.602C15.177,16.491 15.804,17.236 16.607,17.717V21.454H2V19.263Z"/>
+<!--LINT.IfChange-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="960"
+ android:viewportHeight="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M120,800L120,688Q120,654 137.5,625.5Q155,597 184,582Q246,551 310,535.5Q374,520 440,520Q460,520 480,521.5Q500,523 520,526Q516,584 541,635.5Q566,687 614,720L614,800L120,800ZM760,920L700,860L700,674Q656,661 628,624.5Q600,588 600,540Q600,482 641,441Q682,400 740,400Q798,400 839,441Q880,482 880,540Q880,585 854.5,620Q829,655 790,670L840,720L780,780L840,840L760,920ZM440,480Q374,480 327,433Q280,386 280,320Q280,254 327,207Q374,160 440,160Q506,160 553,207Q600,254 600,320Q600,386 553,433Q506,480 440,480ZM740,560Q757,560 768.5,548.5Q780,537 780,520Q780,503 768.5,491.5Q757,480 740,480Q723,480 711.5,491.5Q700,503 700,520Q700,537 711.5,548.5Q723,560 740,560Z"/>
</vector>
+<!--LINT.ThenChange(/packages/CredentialManager/shared/res/drawable/ic_passkey_24.xml)-->
\ No newline at end of file
diff --git a/packages/CredentialManager/res/values/strings.xml b/packages/CredentialManager/res/values/strings.xml
index 82b47a9..527701c 100644
--- a/packages/CredentialManager/res/values/strings.xml
+++ b/packages/CredentialManager/res/values/strings.xml
@@ -63,9 +63,9 @@
<!-- This appears as the description body of the modal bottom sheet which provides all available providers for users to choose. [CHAR LIMIT=200] -->
<string name="choose_provider_body">Select a password manager to save your info and sign in faster next time</string>
<!-- This appears as the title of the modal bottom sheet for users to choose the create option inside a provider when the credential type is passkey. [CHAR LIMIT=200] -->
- <string name="choose_create_option_passkey_title">Create passkey for <xliff:g id="appName" example="Tribank">%1$s</xliff:g>?</string>
+ <string name="choose_create_option_passkey_title">Create passkey to sign in to <xliff:g id="appName" example="Tribank">%1$s</xliff:g>?</string>
<!-- This appears as the title of the modal bottom sheet for users to choose the create option inside a provider when the credential type is password. [CHAR LIMIT=200] -->
- <string name="choose_create_option_password_title">Save password for <xliff:g id="appName" example="Tribank">%1$s</xliff:g>?</string>
+ <string name="choose_create_option_password_title">Save password to sign in to <xliff:g id="appName" example="Tribank">%1$s</xliff:g>?</string>
<!-- This appears as the title of the modal bottom sheet for users to choose the create option inside a provider when the credential type is others. [CHAR LIMIT=200] -->
<string name="choose_create_option_sign_in_title">Save sign-in info for <xliff:g id="appName" example="Tribank">%1$s</xliff:g>?</string>
<!-- Types which are inserted as a placeholder as credentialTypes for other strings. [CHAR LIMIT=200] -->
diff --git a/packages/CredentialManager/shared/Android.bp b/packages/CredentialManager/shared/Android.bp
index 47ca944..f8ee96e 100644
--- a/packages/CredentialManager/shared/Android.bp
+++ b/packages/CredentialManager/shared/Android.bp
@@ -11,6 +11,7 @@
name: "CredentialManagerShared",
manifest: "AndroidManifest.xml",
srcs: ["src/**/*.kt"],
+ resource_dirs: ["res"],
static_libs: [
"androidx.activity_activity-compose",
"androidx.core_core-ktx",
diff --git a/packages/CredentialManager/shared/res/drawable/ic_passkey_24.xml b/packages/CredentialManager/shared/res/drawable/ic_passkey_24.xml
new file mode 100644
index 0000000..b81f7c5
--- /dev/null
+++ b/packages/CredentialManager/shared/res/drawable/ic_passkey_24.xml
@@ -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.
+ -->
+<!--LINT.IfChange-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="960"
+ android:viewportHeight="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M120,800L120,688Q120,654 137.5,625.5Q155,597 184,582Q246,551 310,535.5Q374,520 440,520Q460,520 480,521.5Q500,523 520,526Q516,584 541,635.5Q566,687 614,720L614,800L120,800ZM760,920L700,860L700,674Q656,661 628,624.5Q600,588 600,540Q600,482 641,441Q682,400 740,400Q798,400 839,441Q880,482 880,540Q880,585 854.5,620Q829,655 790,670L840,720L780,780L840,840L760,920ZM440,480Q374,480 327,433Q280,386 280,320Q280,254 327,207Q374,160 440,160Q506,160 553,207Q600,254 600,320Q600,386 553,433Q506,480 440,480ZM740,560Q757,560 768.5,548.5Q780,537 780,520Q780,503 768.5,491.5Q757,480 740,480Q723,480 711.5,491.5Q700,503 700,520Q700,537 711.5,548.5Q723,560 740,560Z"/>
+</vector>
+<!--LINT.ThenChange(/packages/CredentialManager/res/drawable/ic_passkey_24.xml)-->
\ No newline at end of file
diff --git a/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt b/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
index 02320a1..39d3f42 100644
--- a/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
+++ b/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
@@ -39,6 +39,7 @@
import androidx.credentials.provider.PublicKeyCredentialEntry
import androidx.credentials.provider.RemoteEntry
import com.android.credentialmanager.IS_AUTO_SELECTED_KEY
+import com.android.credentialmanager.R
import com.android.credentialmanager.model.get.ActionEntryInfo
import com.android.credentialmanager.model.get.AuthenticationEntryInfo
import com.android.credentialmanager.model.get.CredentialEntryInfo
@@ -147,7 +148,9 @@
credentialTypeDisplayName = credentialEntry.typeDisplayName.toString(),
userName = credentialEntry.username.toString(),
displayName = credentialEntry.displayName?.toString(),
- icon = credentialEntry.icon.loadDrawable(context),
+ icon = if (credentialEntry.hasDefaultIcon)
+ context.getDrawable(R.drawable.ic_passkey_24)
+ else credentialEntry.icon.loadDrawable(context),
shouldTintIcon = credentialEntry.hasDefaultIcon,
lastUsedTimeMillis = credentialEntry.lastUsedTime,
isAutoSelectable = credentialEntry.isAutoSelectAllowed &&
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt b/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt
index 5830b9f..ccf401d 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt
@@ -282,6 +282,8 @@
val appPreferredDefaultProviderId: String? =
if (!requestInfo.hasPermissionToOverrideDefault()) null
else createCredentialRequestJetpack?.displayInfo?.preferDefaultProvider
+ val typeDisplayIcon = createCredentialRequestJetpack?.displayInfo?.credentialTypeIcon
+ ?.loadDrawable(context)
return when (createCredentialRequestJetpack) {
is CreatePasswordRequest -> RequestDisplayInfo(
createCredentialRequestJetpack.id,
@@ -302,7 +304,6 @@
newRequestDisplayInfoFromPasskeyJson(
requestJson = createCredentialRequestJetpack.requestJson,
appLabel = appLabel,
- context = context,
preferImmediatelyAvailableCredentials =
createCredentialRequestJetpack.preferImmediatelyAvailableCredentials,
appPreferredDefaultProviderId = appPreferredDefaultProviderId,
@@ -311,6 +312,7 @@
// the passkey type. For now, directly parse it ourselves.
isAutoSelectRequest = createCredentialRequest.credentialData.getBoolean(
Constants.BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS, false),
+ typeIcon = context.getDrawable(R.drawable.ic_passkey_24) ?: return null,
)
}
is CreateCustomCredentialRequest -> {
@@ -323,7 +325,7 @@
subtitle = displayInfo.userDisplayName?.toString(),
type = CredentialType.UNKNOWN,
appName = appLabel,
- typeIcon = displayInfo.credentialTypeIcon?.loadDrawable(context)
+ typeIcon = typeDisplayIcon
?: context.getDrawable(R.drawable.ic_other_sign_in_24) ?: return null,
preferImmediatelyAvailableCredentials =
createCredentialRequestJetpack.preferImmediatelyAvailableCredentials,
@@ -502,7 +504,7 @@
private fun newRequestDisplayInfoFromPasskeyJson(
requestJson: String,
appLabel: String,
- context: Context,
+ typeIcon: Drawable,
preferImmediatelyAvailableCredentials: Boolean,
appPreferredDefaultProviderId: String?,
userSetDefaultProviderIds: Set<String>,
@@ -525,7 +527,7 @@
displayname,
CredentialType.PASSKEY,
appLabel,
- context.getDrawable(R.drawable.ic_passkey_24) ?: return null,
+ typeIcon,
preferImmediatelyAvailableCredentials,
appPreferredDefaultProviderId,
userSetDefaultProviderIds,
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
index 28c42fb..c118f88 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
@@ -237,11 +237,8 @@
if (providerList.isEmpty()) {
return false
}
- var totalEntryCount = 0
- providerList.forEach { provider ->
- totalEntryCount += provider.credentialEntryList.size
- }
val providerDisplayInfo: ProviderDisplayInfo = toProviderDisplayInfo(providerList)
+ var totalEntryCount = providerDisplayInfo.sortedUserNameToCredentialEntryList.size
val inlineSuggestionsRequest = filLRequest.inlineSuggestionsRequest
val inlineMaxSuggestedCount = inlineSuggestionsRequest?.maxSuggestionCount ?: 0
val inlinePresentationSpecs = inlineSuggestionsRequest?.inlinePresentationSpecs
@@ -578,7 +575,7 @@
responseClientState: Bundle
): GetCredentialRequest? {
val credentialOptions: MutableList<CredentialOption> = mutableListOf()
- traverseStructureForRequest(structure, credentialOptions, responseClientState)
+ traverseStructureForRequest(structure, credentialOptions, responseClientState, sessionId)
if (credentialOptions.isNotEmpty()) {
val dataBundle = Bundle()
@@ -594,7 +591,8 @@
private fun traverseStructureForRequest(
structure: AssistStructure,
cmRequests: MutableList<CredentialOption>,
- responseClientState: Bundle
+ responseClientState: Bundle,
+ sessionId: Int
) {
val traversedViewNodes: MutableSet<AutofillId> = mutableSetOf()
val credentialOptionsFromHints: MutableMap<String, CredentialOption> = mutableMapOf()
@@ -606,7 +604,7 @@
windowNodes.forEach { windowNode: AssistStructure.WindowNode ->
traverseNodeForRequest(
windowNode.rootViewNode, cmRequests, responseClientState, traversedViewNodes,
- credentialOptionsFromHints)
+ credentialOptionsFromHints, sessionId)
}
}
@@ -615,11 +613,12 @@
cmRequests: MutableList<CredentialOption>,
responseClientState: Bundle,
traversedViewNodes: MutableSet<AutofillId>,
- credentialOptionsFromHints: MutableMap<String, CredentialOption>
+ credentialOptionsFromHints: MutableMap<String, CredentialOption>,
+ sessionId: Int
) {
viewNode.autofillId?.let {
cmRequests.addAll(getCredentialOptionsFromViewNode(viewNode, it, responseClientState,
- traversedViewNodes, credentialOptionsFromHints))
+ traversedViewNodes, credentialOptionsFromHints, sessionId))
traversedViewNodes.add(it)
}
@@ -630,7 +629,7 @@
children.forEach { childNode: AssistStructure.ViewNode ->
traverseNodeForRequest(childNode, cmRequests, responseClientState, traversedViewNodes,
- credentialOptionsFromHints)
+ credentialOptionsFromHints, sessionId)
}
}
@@ -639,7 +638,8 @@
autofillId: AutofillId,
responseClientState: Bundle,
traversedViewNodes: MutableSet<AutofillId>,
- credentialOptionsFromHints: MutableMap<String, CredentialOption>
+ credentialOptionsFromHints: MutableMap<String, CredentialOption>,
+ sessionId: Int
): MutableList<CredentialOption> {
val credentialOptions: MutableList<CredentialOption> = mutableListOf()
if (Flags.autofillCredmanDevIntegration() && viewNode.credentialManagerRequest != null) {
@@ -650,12 +650,25 @@
.getParcelableArrayList(
CredentialProviderService.EXTRA_AUTOFILL_ID, AutofillId::class.java)
?.let { associatedAutofillIds ->
+ // Set sessionId in autofillIds. The autofillIds stored in Credential
+ // Options do not have associated session id and will result in
+ // different hashes than the ones in assistStructure.
+ associatedAutofillIds.forEach { associatedAutofillId ->
+ associatedAutofillId.sessionId = sessionId
+ }
+
// Check whether any of the associated autofill ids have already been
// traversed. If so, skip, to dedupe on duplicate credential options.
if ((traversedViewNodes intersect associatedAutofillIds.toSet())
.isEmpty()) {
credentialOptions.add(credentialOption)
}
+
+ // Set the autofillIds with session id back to credential option.
+ credentialOption.candidateQueryData.putParcelableArrayList(
+ CredentialProviderService.EXTRA_AUTOFILL_ID,
+ associatedAutofillIds
+ )
}
}
}
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
index 7277550..ccc4660 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
@@ -554,15 +554,11 @@
if (credentialEntryInfo.icon == null) painterResource(R.drawable.ic_other_sign_in_24)
else null,
entryHeadlineText = username,
- entrySecondLineText = if (
- credentialEntryInfo.credentialType == CredentialType.PASSWORD) {
- "••••••••••••"
- } else {
- val itemsToDisplay = listOf(
+ entrySecondLineText = listOf(
displayName,
credentialEntryInfo.credentialTypeDisplayName,
credentialEntryInfo.providerDisplayName
- ).filterNot(TextUtils::isEmpty)
+ ).filterNot(TextUtils::isEmpty).let { itemsToDisplay ->
if (itemsToDisplay.isEmpty()) null
else itemsToDisplay.joinToString(
separator = stringResource(R.string.get_dialog_sign_in_type_username_separator)
diff --git a/packages/PackageInstaller/res/layout/install_content_view.xml b/packages/PackageInstaller/res/layout/install_content_view.xml
index 2ecd2d5..524a88a 100644
--- a/packages/PackageInstaller/res/layout/install_content_view.xml
+++ b/packages/PackageInstaller/res/layout/install_content_view.xml
@@ -24,114 +24,116 @@
android:paddingLeft="?android:attr/dialogPreferredPadding"
android:paddingRight="?android:attr/dialogPreferredPadding">
- <LinearLayout
- android:id="@+id/staging"
+ <LinearLayout
+ android:id="@+id/staging"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:visibility="invisible">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/message_staging" />
+
+ <ProgressBar
+ android:id="@+id/progress_indeterminate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:orientation="vertical"
- android:visibility="invisible">
+ android:paddingTop="8dp"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:indeterminate="true" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/message_staging" />
+ </LinearLayout>
- <ProgressBar
- android:id="@+id/progress_indeterminate"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingTop="8dp"
- style="?android:attr/progressBarStyleHorizontal"
- android:indeterminate="true" />
+ <LinearLayout
+ android:id="@+id/installing"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:visibility="invisible">
- </LinearLayout>
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/installing" />
- <LinearLayout
- android:id="@+id/installing"
+ <ProgressBar
+ android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:orientation="vertical"
- android:visibility="invisible">
+ android:paddingTop="8dp"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:indeterminate="true" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/installing" />
+ </LinearLayout>
- <ProgressBar
- android:id="@+id/progress"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingTop="8dp"
- style="?android:attr/progressBarStyleHorizontal"
- android:indeterminate="true" />
+ <TextView
+ android:id="@+id/install_confirm_question"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_confirm_question"
+ android:visibility="invisible"
+ android:scrollbars="vertical" />
- </LinearLayout>
+ <TextView
+ android:id="@+id/install_confirm_question_update"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_confirm_question_update"
+ android:visibility="invisible"
+ android:scrollbars="vertical" />
- <TextView
- android:id="@+id/install_confirm_question"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_confirm_question"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_success"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_done"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_confirm_question_update"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_confirm_question_update"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_failed"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_failed"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_success"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_done"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_failed_blocked"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_failed_blocked"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_failed"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_failed"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_failed_conflict"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_failed_conflict"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_failed_blocked"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_failed_blocked"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_failed_incompatible"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_failed_incompatible"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_failed_conflict"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_failed_conflict"
- android:visibility="invisible" />
+ <TextView
+ android:id="@+id/install_failed_invalid_apk"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead"
+ android:text="@string/install_failed_invalid_apk"
+ android:visibility="invisible" />
- <TextView
- android:id="@+id/install_failed_incompatible"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_failed_incompatible"
- android:visibility="invisible" />
-
- <TextView
- android:id="@+id/install_failed_invalid_apk"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead"
- android:text="@string/install_failed_invalid_apk"
- android:visibility="invisible" />
-
-</FrameLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/packages/PackageInstaller/res/layout/uninstall_content_view.xml b/packages/PackageInstaller/res/layout/uninstall_content_view.xml
index 5666c0e..434e333 100644
--- a/packages/PackageInstaller/res/layout/uninstall_content_view.xml
+++ b/packages/PackageInstaller/res/layout/uninstall_content_view.xml
@@ -18,31 +18,36 @@
<!-- Check box that is displayed in the activity resolver UI for the user
to make their selection the preferred activity. -->
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:theme="?android:attr/alertDialogTheme"
- android:orientation="vertical"
- android:paddingTop="8dp"
- android:paddingStart="?android:attr/dialogPreferredPadding"
- android:paddingEnd="?android:attr/dialogPreferredPadding"
- android:clipToPadding="false">
+ android:layout_height="wrap_content">
- <TextView
- android:id="@+id/message"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- style="@android:style/TextAppearance.Material.Subhead" />
+ <LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:theme="?android:attr/alertDialogTheme"
+ android:orientation="vertical"
+ android:paddingTop="8dp"
+ android:paddingStart="?android:attr/dialogPreferredPadding"
+ android:paddingEnd="?android:attr/dialogPreferredPadding"
+ android:clipToPadding="false">
- <CheckBox
- android:id="@+id/keepData"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="8dp"
- android:layout_marginStart="-8dp"
- android:paddingLeft="8sp"
- android:visibility="gone"
- style="@android:style/TextAppearance.Material.Subhead" />
+ <TextView
+ android:id="@+id/message"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ style="@android:style/TextAppearance.Material.Subhead" />
-</LinearLayout>
\ No newline at end of file
+ <CheckBox
+ android:id="@+id/keepData"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:layout_marginStart="-8dp"
+ android:paddingLeft="8sp"
+ android:visibility="gone"
+ style="@android:style/TextAppearance.Material.Subhead" />
+
+ </LinearLayout>
+</ScrollView>
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
index cf6aab6..e95a8e6 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
@@ -51,6 +51,7 @@
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
+import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
@@ -174,6 +175,7 @@
}
viewToEnable.setVisibility(View.VISIBLE);
+ viewToEnable.setMovementMethod(new ScrollingMovementMethod());
mEnableOk = true;
mOk.setEnabled(true);
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/v2/ui/fragments/InstallConfirmationFragment.java b/packages/PackageInstaller/src/com/android/packageinstaller/v2/ui/fragments/InstallConfirmationFragment.java
index dbe32cc..0a4aa48 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/v2/ui/fragments/InstallConfirmationFragment.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/v2/ui/fragments/InstallConfirmationFragment.java
@@ -22,6 +22,7 @@
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
+import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
@@ -94,6 +95,7 @@
viewToEnable = dialogView.requireViewById(R.id.install_confirm_question);
}
viewToEnable.setVisibility(View.VISIBLE);
+ viewToEnable.setMovementMethod(new ScrollingMovementMethod());
return mDialog;
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/preference/Preference.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/preference/Preference.kt
index bb7e857..3acf075 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/preference/Preference.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/preference/Preference.kt
@@ -18,7 +18,6 @@
import androidx.compose.foundation.clickable
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import com.android.settingslib.spa.framework.common.EntryMacro
@@ -107,14 +106,9 @@
) {
val onClickWithLog = wrapOnClickWithLog(model.onClick)
val enabled = model.enabled()
- val modifier = remember(enabled) {
- if (onClickWithLog != null) {
- Modifier.clickable(
- enabled = enabled,
- onClick = onClickWithLog
- )
- } else Modifier
- }
+ val modifier = if (onClickWithLog != null) {
+ Modifier.clickable(enabled = enabled, onClick = onClickWithLog)
+ } else Modifier
EntryHighlight {
BasePreference(
title = model.title,
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar.xml
new file mode 100644
index 0000000..d9a417f
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar.xml
@@ -0,0 +1,37 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="14dp"
+ android:height="14dp"
+ android:viewportWidth="14.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M8.25,3L9.25,3A0.5,0.5 0,0 1,9.75 3.5L9.75,13.5A0.5,0.5 0,0 1,9.25 14L8.25,14A0.5,0.5 0,0 1,7.75 13.5L7.75,3.5A0.5,0.5 0,0 1,8.25 3z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11.75,0L12.75,0A0.5,0.5 0,0 1,13.25 0.5L13.25,13.5A0.5,0.5 0,0 1,12.75 14L11.75,14A0.5,0.5 0,0 1,11.25 13.5L11.25,0.5A0.5,0.5 0,0 1,11.75 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M1.25,10L2.25,10A0.5,0.5 0,0 1,2.75 10.5L2.75,13.5A0.5,0.5 0,0 1,2.25 14L1.25,14A0.5,0.5 0,0 1,0.75 13.5L0.75,10.5A0.5,0.5 0,0 1,1.25 10z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4.75,6.5L5.75,6.5A0.5,0.5 0,0 1,6.25 7L6.25,13.5A0.5,0.5 0,0 1,5.75 14L4.75,14A0.5,0.5 0,0 1,4.25 13.5L4.25,7A0.5,0.5 0,0 1,4.75 6.5z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar_error.xml
new file mode 100644
index 0000000..facc285
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_0_4_bar_error.xml
@@ -0,0 +1,28 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="15dp"
+ android:height="14dp"
+ android:viewportWidth="15.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,3.5C7,3.224 7.224,3 7.5,3H8.5C8.776,3 9,3.224 9,3.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V3.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,10.5C0,10.224 0.224,10 0.5,10H1.5C1.776,10 2,10.224 2,10.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V10.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,7C3.5,6.724 3.724,6.5 4,6.5H5C5.276,6.5 5.5,6.724 5.5,7V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V7Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,0C10.724,0 10.5,0.224 10.5,0.5V3H12.5V0.5C12.5,0.224 12.276,0 12,0H11Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,13C12.25,12.448 12.698,12 13.25,12C13.802,12 14.25,12.448 14.25,13C14.25,13.552 13.802,14 13.25,14C12.698,14 12.25,13.552 12.25,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,5C12.25,4.724 12.474,4.5 12.75,4.5H13.75C14.026,4.5 14.25,4.724 14.25,5V10C14.25,10.276 14.026,10.5 13.75,10.5H12.75C12.474,10.5 12.25,10.276 12.25,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar.xml
new file mode 100644
index 0000000..2c05a93
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar.xml
@@ -0,0 +1,41 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar_error.xml
new file mode 100644
index 0000000..328e45e
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_0_5_bar_error.xml
@@ -0,0 +1,32 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M14,0.5C14,0.224 14.224,0 14.5,0H15.5C15.776,0 16,0.224 16,0.5V3H14V0.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11C0.224,11 0,11.224 0,11.5V13.5C0,13.776 0.224,14 0.5,14H1.5C1.776,14 2,13.776 2,13.5V11.5C2,11.224 1.776,11 1.5,11H0.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8C3.724,8 3.5,8.224 3.5,8.5V13.5C3.5,13.776 3.724,14 4,14H5C5.276,14 5.5,13.776 5.5,13.5V8.5C5.5,8.224 5.276,8 5,8H4Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar.xml
new file mode 100644
index 0000000..b9054ba
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar.xml
@@ -0,0 +1,36 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="14dp"
+ android:height="14dp"
+ android:viewportWidth="14.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M8.25,3L9.25,3A0.5,0.5 0,0 1,9.75 3.5L9.75,13.5A0.5,0.5 0,0 1,9.25 14L8.25,14A0.5,0.5 0,0 1,7.75 13.5L7.75,3.5A0.5,0.5 0,0 1,8.25 3z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11.75,0L12.75,0A0.5,0.5 0,0 1,13.25 0.5L13.25,13.5A0.5,0.5 0,0 1,12.75 14L11.75,14A0.5,0.5 0,0 1,11.25 13.5L11.25,0.5A0.5,0.5 0,0 1,11.75 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M1.25,10L2.25,10A0.5,0.5 0,0 1,2.75 10.5L2.75,13.5A0.5,0.5 0,0 1,2.25 14L1.25,14A0.5,0.5 0,0 1,0.75 13.5L0.75,10.5A0.5,0.5 0,0 1,1.25 10z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4.75,6.5L5.75,6.5A0.5,0.5 0,0 1,6.25 7L6.25,13.5A0.5,0.5 0,0 1,5.75 14L4.75,14A0.5,0.5 0,0 1,4.25 13.5L4.25,7A0.5,0.5 0,0 1,4.75 6.5z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar_error.xml
new file mode 100644
index 0000000..03a9349
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_1_4_bar_error.xml
@@ -0,0 +1,27 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="15dp"
+ android:height="14dp"
+ android:viewportWidth="15.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,3.5C7,3.224 7.224,3 7.5,3H8.5C8.776,3 9,3.224 9,3.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V3.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,10.5C0,10.224 0.224,10 0.5,10H1.5C1.776,10 2,10.224 2,10.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V10.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,7C3.5,6.724 3.724,6.5 4,6.5H5C5.276,6.5 5.5,6.724 5.5,7V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V7Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,0C10.724,0 10.5,0.224 10.5,0.5V3H12.5V0.5C12.5,0.224 12.276,0 12,0H11Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,13C12.25,12.448 12.698,12 13.25,12C13.802,12 14.25,12.448 14.25,13C14.25,13.552 13.802,14 13.25,14C12.698,14 12.25,13.552 12.25,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,5C12.25,4.724 12.474,4.5 12.75,4.5H13.75C14.026,4.5 14.25,4.724 14.25,5V10C14.25,10.276 14.026,10.5 13.75,10.5H12.75C12.474,10.5 12.25,10.276 12.25,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar.xml
new file mode 100644
index 0000000..774e917
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar.xml
@@ -0,0 +1,40 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar_error.xml
new file mode 100644
index 0000000..343ec1b
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_1_5_bar_error.xml
@@ -0,0 +1,31 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,11.5C0,11.224 0.224,11 0.5,11H1.5C1.776,11 2,11.224 2,11.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V11.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,8.5C3.5,8.224 3.724,8 4,8H5C5.276,8 5.5,8.224 5.5,8.5V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V8.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0C14.224,0 14,0.224 14,0.5V3H16V0.5C16,0.224 15.776,0 15.5,0H14.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar.xml
new file mode 100644
index 0000000..b699203
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar.xml
@@ -0,0 +1,35 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="14dp"
+ android:height="14dp"
+ android:viewportWidth="14.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M8.25,3L9.25,3A0.5,0.5 0,0 1,9.75 3.5L9.75,13.5A0.5,0.5 0,0 1,9.25 14L8.25,14A0.5,0.5 0,0 1,7.75 13.5L7.75,3.5A0.5,0.5 0,0 1,8.25 3z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11.75,0L12.75,0A0.5,0.5 0,0 1,13.25 0.5L13.25,13.5A0.5,0.5 0,0 1,12.75 14L11.75,14A0.5,0.5 0,0 1,11.25 13.5L11.25,0.5A0.5,0.5 0,0 1,11.75 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M1.25,10L2.25,10A0.5,0.5 0,0 1,2.75 10.5L2.75,13.5A0.5,0.5 0,0 1,2.25 14L1.25,14A0.5,0.5 0,0 1,0.75 13.5L0.75,10.5A0.5,0.5 0,0 1,1.25 10z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4.75,6.5L5.75,6.5A0.5,0.5 0,0 1,6.25 7L6.25,13.5A0.5,0.5 0,0 1,5.75 14L4.75,14A0.5,0.5 0,0 1,4.25 13.5L4.25,7A0.5,0.5 0,0 1,4.75 6.5z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar_error.xml
new file mode 100644
index 0000000..ba8649b
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_2_4_bar_error.xml
@@ -0,0 +1,26 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="15dp"
+ android:height="14dp"
+ android:viewportWidth="15.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,3.5C7,3.224 7.224,3 7.5,3H8.5C8.776,3 9,3.224 9,3.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V3.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,10.5C0,10.224 0.224,10 0.5,10H1.5C1.776,10 2,10.224 2,10.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V10.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,7C3.5,6.724 3.724,6.5 4,6.5H5C5.276,6.5 5.5,6.724 5.5,7V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V7Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,0C10.724,0 10.5,0.224 10.5,0.5V3H12.5V0.5C12.5,0.224 12.276,0 12,0H11Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,13C12.25,12.448 12.698,12 13.25,12C13.802,12 14.25,12.448 14.25,13C14.25,13.552 13.802,14 13.25,14C12.698,14 12.25,13.552 12.25,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,5C12.25,4.724 12.474,4.5 12.75,4.5H13.75C14.026,4.5 14.25,4.724 14.25,5V10C14.25,10.276 14.026,10.5 13.75,10.5H12.75C12.474,10.5 12.25,10.276 12.25,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar.xml
new file mode 100644
index 0000000..43fa734
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar.xml
@@ -0,0 +1,39 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar_error.xml
new file mode 100644
index 0000000..6309e17
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_2_5_bar_error.xml
@@ -0,0 +1,30 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,11.5C0,11.224 0.224,11 0.5,11H1.5C1.776,11 2,11.224 2,11.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V11.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,8.5C3.5,8.224 3.724,8 4,8H5C5.276,8 5.5,8.224 5.5,8.5V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V8.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0C14.224,0 14,0.224 14,0.5V3H16V0.5C16,0.224 15.776,0 15.5,0H14.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar.xml
new file mode 100644
index 0000000..6a218b3
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar.xml
@@ -0,0 +1,34 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="14dp"
+ android:height="14dp"
+ android:viewportWidth="14.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M8.25,3L9.25,3A0.5,0.5 0,0 1,9.75 3.5L9.75,13.5A0.5,0.5 0,0 1,9.25 14L8.25,14A0.5,0.5 0,0 1,7.75 13.5L7.75,3.5A0.5,0.5 0,0 1,8.25 3z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11.75,0L12.75,0A0.5,0.5 0,0 1,13.25 0.5L13.25,13.5A0.5,0.5 0,0 1,12.75 14L11.75,14A0.5,0.5 0,0 1,11.25 13.5L11.25,0.5A0.5,0.5 0,0 1,11.75 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M1.25,10L2.25,10A0.5,0.5 0,0 1,2.75 10.5L2.75,13.5A0.5,0.5 0,0 1,2.25 14L1.25,14A0.5,0.5 0,0 1,0.75 13.5L0.75,10.5A0.5,0.5 0,0 1,1.25 10z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4.75,6.5L5.75,6.5A0.5,0.5 0,0 1,6.25 7L6.25,13.5A0.5,0.5 0,0 1,5.75 14L4.75,14A0.5,0.5 0,0 1,4.25 13.5L4.25,7A0.5,0.5 0,0 1,4.75 6.5z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar_error.xml
new file mode 100644
index 0000000..27433c7
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_3_4_bar_error.xml
@@ -0,0 +1,25 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="15dp"
+ android:height="14dp"
+ android:viewportWidth="15.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,3.5C7,3.224 7.224,3 7.5,3H8.5C8.776,3 9,3.224 9,3.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V3.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,10.5C0,10.224 0.224,10 0.5,10H1.5C1.776,10 2,10.224 2,10.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V10.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,7C3.5,6.724 3.724,6.5 4,6.5H5C5.276,6.5 5.5,6.724 5.5,7V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V7Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,0C10.724,0 10.5,0.224 10.5,0.5V3H12.5V0.5C12.5,0.224 12.276,0 12,0H11Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,13C12.25,12.448 12.698,12 13.25,12C13.802,12 14.25,12.448 14.25,13C14.25,13.552 13.802,14 13.25,14C12.698,14 12.25,13.552 12.25,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,5C12.25,4.724 12.474,4.5 12.75,4.5H13.75C14.026,4.5 14.25,4.724 14.25,5V10C14.25,10.276 14.026,10.5 13.75,10.5H12.75C12.474,10.5 12.25,10.276 12.25,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar.xml
new file mode 100644
index 0000000..158ae01
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar.xml
@@ -0,0 +1,38 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar_error.xml
new file mode 100644
index 0000000..e0517cf
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_3_5_bar_error.xml
@@ -0,0 +1,29 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,11.5C0,11.224 0.224,11 0.5,11H1.5C1.776,11 2,11.224 2,11.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V11.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,8.5C3.5,8.224 3.724,8 4,8H5C5.276,8 5.5,8.224 5.5,8.5V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V8.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0C14.224,0 14,0.224 14,0.5V3H16V0.5C16,0.224 15.776,0 15.5,0H14.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar.xml
new file mode 100644
index 0000000..1ebd396
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar.xml
@@ -0,0 +1,33 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="14dp"
+ android:height="14dp"
+ android:viewportWidth="14.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M8.25,3L9.25,3A0.5,0.5 0,0 1,9.75 3.5L9.75,13.5A0.5,0.5 0,0 1,9.25 14L8.25,14A0.5,0.5 0,0 1,7.75 13.5L7.75,3.5A0.5,0.5 0,0 1,8.25 3z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11.75,0L12.75,0A0.5,0.5 0,0 1,13.25 0.5L13.25,13.5A0.5,0.5 0,0 1,12.75 14L11.75,14A0.5,0.5 0,0 1,11.25 13.5L11.25,0.5A0.5,0.5 0,0 1,11.75 0z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M1.25,10L2.25,10A0.5,0.5 0,0 1,2.75 10.5L2.75,13.5A0.5,0.5 0,0 1,2.25 14L1.25,14A0.5,0.5 0,0 1,0.75 13.5L0.75,10.5A0.5,0.5 0,0 1,1.25 10z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4.75,6.5L5.75,6.5A0.5,0.5 0,0 1,6.25 7L6.25,13.5A0.5,0.5 0,0 1,5.75 14L4.75,14A0.5,0.5 0,0 1,4.25 13.5L4.25,7A0.5,0.5 0,0 1,4.75 6.5z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar_error.xml
new file mode 100644
index 0000000..4473c29
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_4_4_bar_error.xml
@@ -0,0 +1,24 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="15dp"
+ android:height="14dp"
+ android:viewportWidth="15.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,3.5C7,3.224 7.224,3 7.5,3H8.5C8.776,3 9,3.224 9,3.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V3.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,10.5C0,10.224 0.224,10 0.5,10H1.5C1.776,10 2,10.224 2,10.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V10.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,7C3.5,6.724 3.724,6.5 4,6.5H5C5.276,6.5 5.5,6.724 5.5,7V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V7Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,0C10.724,0 10.5,0.224 10.5,0.5V3H12.5V0.5C12.5,0.224 12.276,0 12,0H11Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,13C12.25,12.448 12.698,12 13.25,12C13.802,12 14.25,12.448 14.25,13C14.25,13.552 13.802,14 13.25,14C12.698,14 12.25,13.552 12.25,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.25,5C12.25,4.724 12.474,4.5 12.75,4.5H13.75C14.026,4.5 14.25,4.724 14.25,5V10C14.25,10.276 14.026,10.5 13.75,10.5H12.75C12.474,10.5 12.25,10.276 12.25,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar.xml
new file mode 100644
index 0000000..1ed6ac8
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar.xml
@@ -0,0 +1,37 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar_error.xml
new file mode 100644
index 0000000..703e3ac
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_4_5_bar_error.xml
@@ -0,0 +1,28 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,11.5C0,11.224 0.224,11 0.5,11H1.5C1.776,11 2,11.224 2,11.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V11.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,8.5C3.5,8.224 3.724,8 4,8H5C5.276,8 5.5,8.224 5.5,8.5V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V8.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0C14.224,0 14,0.224 14,0.5V3H16V0.5C16,0.224 15.776,0 15.5,0H14.5Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar.xml b/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar.xml
new file mode 100644
index 0000000..420ffb6
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar.xml
@@ -0,0 +1,36 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="16dp"
+ android:height="14dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7.5,5L8.5,5A0.5,0.5 0,0 1,9 5.5L9,13.5A0.5,0.5 0,0 1,8.5 14L7.5,14A0.5,0.5 0,0 1,7 13.5L7,5.5A0.5,0.5 0,0 1,7.5 5z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M11,2L12,2A0.5,0.5 0,0 1,12.5 2.5L12.5,13.5A0.5,0.5 0,0 1,12 14L11,14A0.5,0.5 0,0 1,10.5 13.5L10.5,2.5A0.5,0.5 0,0 1,11 2z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0.5,11L1.5,11A0.5,0.5 0,0 1,2 11.5L2,13.5A0.5,0.5 0,0 1,1.5 14L0.5,14A0.5,0.5 0,0 1,0 13.5L0,11.5A0.5,0.5 0,0 1,0.5 11z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0L15.5,0A0.5,0.5 0,0 1,16 0.5L16,13.5A0.5,0.5 0,0 1,15.5 14L14.5,14A0.5,0.5 0,0 1,14 13.5L14,0.5A0.5,0.5 0,0 1,14.5 0z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M4,8L5,8A0.5,0.5 0,0 1,5.5 8.5L5.5,13.5A0.5,0.5 0,0 1,5 14L4,14A0.5,0.5 0,0 1,3.5 13.5L3.5,8.5A0.5,0.5 0,0 1,4 8z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar_error.xml b/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar_error.xml
new file mode 100644
index 0000000..e63ca77
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_5_5_bar_error.xml
@@ -0,0 +1,27 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="14dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="M7,5.5C7,5.224 7.224,5 7.5,5H8.5C8.776,5 9,5.224 9,5.5V13.5C9,13.776 8.776,14 8.5,14H7.5C7.224,14 7,13.776 7,13.5V5.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.5,2.5C10.5,2.224 10.724,2 11,2H12C12.276,2 12.5,2.224 12.5,2.5V13.5C12.5,13.776 12.276,14 12,14H11C10.724,14 10.5,13.776 10.5,13.5V2.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M0,11.5C0,11.224 0.224,11 0.5,11H1.5C1.776,11 2,11.224 2,11.5V13.5C2,13.776 1.776,14 1.5,14H0.5C0.224,14 0,13.776 0,13.5V11.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M3.5,8.5C3.5,8.224 3.724,8 4,8H5C5.276,8 5.5,8.224 5.5,8.5V13.5C5.5,13.776 5.276,14 5,14H4C3.724,14 3.5,13.776 3.5,13.5V8.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.5,0C14.224,0 14,0.224 14,0.5V3H16V0.5C16,0.224 15.776,0 15.5,0H14.5Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,13C16,12.448 16.448,12 17,12C17.552,12 18,12.448 18,13C18,13.552 17.552,14 17,14C16.448,14 16,13.552 16,13Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M16,5C16,4.724 16.224,4.5 16.5,4.5H17.5C17.776,4.5 18,4.724 18,5V10C18,10.276 17.776,10.5 17.5,10.5H16.5C16.224,10.5 16,10.276 16,10V5Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_mobile_level_list.xml b/packages/SettingsLib/res/drawable/ic_mobile_level_list.xml
new file mode 100644
index 0000000..6ec6793
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_mobile_level_list.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2023 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
+ -->
+
+<!-- In order to pack the 0-4 and 0-5 ranges into a single element, we use a range offset. See
+SignalDrawable.java for usage. -->
+<level-list xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:minLevel="0" android:maxLevel="0" android:drawable="@drawable/ic_mobile_0_4_bar" />
+ <item android:minLevel="1" android:maxLevel="1" android:drawable="@drawable/ic_mobile_1_4_bar" />
+ <item android:minLevel="2" android:maxLevel="2" android:drawable="@drawable/ic_mobile_2_4_bar" />
+ <item android:minLevel="3" android:maxLevel="3" android:drawable="@drawable/ic_mobile_3_4_bar" />
+ <item android:minLevel="4" android:maxLevel="4" android:drawable="@drawable/ic_mobile_4_4_bar" />
+ <item android:minLevel="10" android:maxLevel="10" android:drawable="@drawable/ic_mobile_0_5_bar" />
+ <item android:minLevel="11" android:maxLevel="11" android:drawable="@drawable/ic_mobile_1_5_bar" />
+ <item android:minLevel="12" android:maxLevel="12" android:drawable="@drawable/ic_mobile_2_5_bar" />
+ <item android:minLevel="13" android:maxLevel="13" android:drawable="@drawable/ic_mobile_3_5_bar" />
+ <item android:minLevel="14" android:maxLevel="14" android:drawable="@drawable/ic_mobile_4_5_bar" />
+ <item android:minLevel="15" android:maxLevel="15" android:drawable="@drawable/ic_mobile_5_5_bar" />
+
+ <!-- Error states, so we don't have to draw them manually anymore -->
+ <item android:minLevel="20" android:maxLevel="20" android:drawable="@drawable/ic_mobile_0_4_bar_error" />
+ <item android:minLevel="21" android:maxLevel="21" android:drawable="@drawable/ic_mobile_1_4_bar_error" />
+ <item android:minLevel="22" android:maxLevel="22" android:drawable="@drawable/ic_mobile_2_4_bar_error" />
+ <item android:minLevel="23" android:maxLevel="23" android:drawable="@drawable/ic_mobile_3_4_bar_error" />
+ <item android:minLevel="24" android:maxLevel="24" android:drawable="@drawable/ic_mobile_4_4_bar_error" />
+
+ <item android:minLevel="30" android:maxLevel="30" android:drawable="@drawable/ic_mobile_0_5_bar_error" />
+ <item android:minLevel="31" android:maxLevel="31" android:drawable="@drawable/ic_mobile_1_5_bar_error" />
+ <item android:minLevel="32" android:maxLevel="32" android:drawable="@drawable/ic_mobile_2_5_bar_error" />
+ <item android:minLevel="33" android:maxLevel="33" android:drawable="@drawable/ic_mobile_3_5_bar_error" />
+ <item android:minLevel="34" android:maxLevel="34" android:drawable="@drawable/ic_mobile_4_5_bar_error" />
+ <item android:minLevel="35" android:maxLevel="35" android:drawable="@drawable/ic_mobile_5_5_bar_error" />
+</level-list>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_0.xml b/packages/SettingsLib/res/drawable/ic_wifi_0.xml
new file mode 100644
index 0000000..8ff6554
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_0.xml
@@ -0,0 +1,37 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="13dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.523,3.314C0.32,3.502 0.32,3.819 0.516,4.015L1.223,4.722C1.418,4.917 1.734,4.916 1.938,4.73C5.936,1.09 12.066,1.09 16.064,4.73C16.268,4.916 16.584,4.917 16.779,4.722L17.486,4.015C17.682,3.819 17.682,3.502 17.479,3.314C12.698,-1.105 5.304,-1.105 0.523,3.314Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M15.011,6.49C15.207,6.294 15.207,5.976 15.002,5.792C11.592,2.736 6.411,2.736 3,5.792C2.795,5.976 2.795,6.294 2.991,6.49L3.698,7.197C3.893,7.392 4.209,7.39 4.417,7.209C7.042,4.93 10.96,4.93 13.585,7.209C13.793,7.39 14.109,7.392 14.304,7.197L15.011,6.49Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.465,8.964C5.27,8.769 5.269,8.45 5.481,8.273C7.515,6.576 10.487,6.576 12.521,8.273C12.733,8.45 12.732,8.769 12.537,8.964L11.83,9.672C11.634,9.867 11.319,9.863 11.099,9.698C9.859,8.767 8.143,8.767 6.904,9.698C6.683,9.863 6.368,9.867 6.173,9.672L5.465,8.964Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.062,11.439C10.257,11.244 10.259,10.92 10.022,10.779C9.395,10.407 8.608,10.407 7.98,10.779C7.743,10.92 7.745,11.244 7.94,11.439L8.647,12.146C8.843,12.342 9.159,12.342 9.355,12.146L10.062,11.439Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_0_error.xml b/packages/SettingsLib/res/drawable/ic_wifi_0_error.xml
new file mode 100644
index 0000000..db31b9d
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_0_error.xml
@@ -0,0 +1,28 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="17dp"
+ android:height="13dp"
+ android:viewportWidth="17.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.146,4.015C-0.05,3.819 -0.05,3.502 0.153,3.314C4.002,-0.244 9.545,-0.937 14.055,1.234C13.339,1.449 12.792,2.053 12.66,2.801C8.998,1.281 4.65,1.924 1.568,4.73C1.364,4.916 1.048,4.917 0.853,4.722L0.146,4.015Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.63,4.435C9.406,2.836 5.424,3.288 2.63,5.792C2.424,5.976 2.425,6.294 2.621,6.49L3.328,7.197C3.523,7.392 3.839,7.39 4.047,7.209C6.484,5.094 10.033,4.942 12.63,6.753V4.435Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.095,8.964C4.9,8.769 4.899,8.45 5.111,8.273C7.145,6.576 10.117,6.576 12.151,8.273C12.363,8.45 12.362,8.769 12.166,8.964L11.459,9.672C11.264,9.867 10.949,9.863 10.728,9.698C9.489,8.767 7.773,8.767 6.533,9.698C6.313,9.863 5.998,9.867 5.802,9.672L5.095,8.964Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M9.652,10.779C9.889,10.92 9.887,11.244 9.692,11.439L8.984,12.146C8.789,12.342 8.473,12.342 8.277,12.146L7.57,11.439C7.375,11.244 7.373,10.92 7.61,10.779C8.237,10.407 9.024,10.407 9.652,10.779Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,11.15C14.63,10.598 15.078,10.15 15.63,10.15C16.182,10.15 16.63,10.598 16.63,11.15C16.63,11.703 16.182,12.15 15.63,12.15C15.078,12.15 14.63,11.703 14.63,11.15Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,3.15C14.63,2.874 14.854,2.65 15.13,2.65H16.13C16.406,2.65 16.63,2.874 16.63,3.15V8.15C16.63,8.427 16.406,8.65 16.13,8.65H15.13C14.854,8.65 14.63,8.427 14.63,8.15V3.15Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_1.xml b/packages/SettingsLib/res/drawable/ic_wifi_1.xml
new file mode 100644
index 0000000..e170f1d
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_1.xml
@@ -0,0 +1,36 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="13dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.523,3.314C0.32,3.502 0.32,3.819 0.516,4.015L1.223,4.722C1.418,4.917 1.734,4.916 1.938,4.73C5.936,1.09 12.066,1.09 16.064,4.73C16.268,4.916 16.584,4.917 16.779,4.722L17.486,4.015C17.682,3.819 17.682,3.502 17.479,3.314C12.698,-1.105 5.304,-1.105 0.523,3.314Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M15.011,6.49C15.207,6.294 15.207,5.976 15.002,5.792C11.592,2.736 6.411,2.736 3,5.792C2.795,5.976 2.795,6.294 2.991,6.49L3.698,7.197C3.893,7.392 4.209,7.39 4.417,7.209C7.042,4.93 10.96,4.93 13.585,7.209C13.793,7.39 14.109,7.392 14.304,7.197L15.011,6.49Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.465,8.964C5.27,8.769 5.269,8.45 5.481,8.273C7.515,6.576 10.487,6.576 12.521,8.273C12.733,8.45 12.732,8.769 12.537,8.964L11.83,9.672C11.634,9.867 11.319,9.863 11.099,9.698C9.859,8.767 8.143,8.767 6.904,9.698C6.683,9.863 6.368,9.867 6.173,9.672L5.465,8.964Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.062,11.439C10.257,11.244 10.259,10.92 10.022,10.779C9.395,10.407 8.608,10.407 7.98,10.779C7.743,10.92 7.745,11.244 7.94,11.439L8.647,12.146C8.843,12.342 9.159,12.342 9.355,12.146L10.062,11.439Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_1_error.xml b/packages/SettingsLib/res/drawable/ic_wifi_1_error.xml
new file mode 100644
index 0000000..a4d6a5c
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_1_error.xml
@@ -0,0 +1,27 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="17dp"
+ android:height="13dp"
+ android:viewportWidth="17.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.146,4.015C-0.05,3.819 -0.05,3.502 0.153,3.314C4.002,-0.244 9.545,-0.937 14.055,1.234C13.339,1.449 12.792,2.053 12.66,2.801C8.998,1.281 4.65,1.924 1.568,4.73C1.364,4.916 1.048,4.917 0.853,4.722L0.146,4.015Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.63,4.435C9.406,2.836 5.424,3.288 2.63,5.792C2.424,5.976 2.425,6.294 2.621,6.49L3.328,7.197C3.523,7.392 3.839,7.39 4.047,7.209C6.484,5.094 10.033,4.942 12.63,6.753V4.435Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.095,8.964C4.9,8.769 4.899,8.45 5.111,8.273C7.145,6.576 10.117,6.576 12.151,8.273C12.363,8.45 12.362,8.769 12.166,8.964L11.459,9.672C11.264,9.867 10.949,9.863 10.728,9.698C9.489,8.767 7.773,8.767 6.533,9.698C6.313,9.863 5.998,9.867 5.802,9.672L5.095,8.964Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M9.652,10.779C9.889,10.92 9.887,11.244 9.692,11.439L8.984,12.146C8.789,12.342 8.473,12.342 8.277,12.146L7.57,11.439C7.375,11.244 7.373,10.92 7.61,10.779C8.237,10.407 9.024,10.407 9.652,10.779Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,11.15C14.63,10.598 15.078,10.15 15.63,10.15C16.182,10.15 16.63,10.598 16.63,11.15C16.63,11.703 16.182,12.15 15.63,12.15C15.078,12.15 14.63,11.703 14.63,11.15Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,3.15C14.63,2.874 14.854,2.65 15.13,2.65H16.13C16.406,2.65 16.63,2.874 16.63,3.15V8.15C16.63,8.427 16.406,8.65 16.13,8.65H15.13C14.854,8.65 14.63,8.427 14.63,8.15V3.15Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_2.xml b/packages/SettingsLib/res/drawable/ic_wifi_2.xml
new file mode 100644
index 0000000..fc62267
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_2.xml
@@ -0,0 +1,35 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="13dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.523,3.314C0.32,3.502 0.32,3.819 0.516,4.015L1.223,4.722C1.418,4.917 1.734,4.916 1.938,4.73C5.936,1.09 12.066,1.09 16.064,4.73C16.268,4.916 16.584,4.917 16.779,4.722L17.486,4.015C17.682,3.819 17.682,3.502 17.479,3.314C12.698,-1.105 5.304,-1.105 0.523,3.314Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M15.011,6.49C15.207,6.294 15.207,5.976 15.002,5.792C11.592,2.736 6.411,2.736 3,5.792C2.795,5.976 2.795,6.294 2.991,6.49L3.698,7.197C3.893,7.392 4.209,7.39 4.417,7.209C7.042,4.93 10.96,4.93 13.585,7.209C13.793,7.39 14.109,7.392 14.304,7.197L15.011,6.49Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.465,8.964C5.27,8.769 5.269,8.45 5.481,8.273C7.515,6.576 10.487,6.576 12.521,8.273C12.733,8.45 12.732,8.769 12.537,8.964L11.83,9.672C11.634,9.867 11.319,9.863 11.099,9.698C9.859,8.767 8.143,8.767 6.904,9.698C6.683,9.863 6.368,9.867 6.173,9.672L5.465,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.062,11.439C10.257,11.244 10.259,10.92 10.022,10.779C9.395,10.407 8.608,10.407 7.98,10.779C7.743,10.92 7.745,11.244 7.94,11.439L8.647,12.146C8.843,12.342 9.159,12.342 9.355,12.146L10.062,11.439Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_2_error.xml b/packages/SettingsLib/res/drawable/ic_wifi_2_error.xml
new file mode 100644
index 0000000..65f40ef
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_2_error.xml
@@ -0,0 +1,26 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="17dp"
+ android:height="13dp"
+ android:viewportWidth="17.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.146,4.015C-0.05,3.819 -0.05,3.502 0.153,3.314C4.002,-0.244 9.545,-0.937 14.055,1.234C13.339,1.449 12.792,2.053 12.66,2.801C8.998,1.281 4.65,1.924 1.568,4.73C1.364,4.916 1.048,4.917 0.853,4.722L0.146,4.015Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.63,4.435C9.406,2.836 5.424,3.288 2.63,5.792C2.424,5.976 2.425,6.294 2.621,6.49L3.328,7.197C3.523,7.392 3.839,7.39 4.047,7.209C6.484,5.094 10.033,4.942 12.63,6.753V4.435Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.095,8.964C4.9,8.769 4.899,8.45 5.111,8.273C7.145,6.576 10.117,6.576 12.151,8.273C12.363,8.45 12.362,8.769 12.166,8.964L11.459,9.672C11.264,9.867 10.949,9.863 10.728,9.698C9.489,8.767 7.773,8.767 6.533,9.698C6.313,9.863 5.998,9.867 5.802,9.672L5.095,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M9.652,10.779C9.889,10.92 9.887,11.244 9.692,11.439L8.984,12.146C8.789,12.342 8.473,12.342 8.277,12.146L7.57,11.439C7.375,11.244 7.373,10.92 7.61,10.779C8.237,10.407 9.024,10.407 9.652,10.779Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,11.15C14.63,10.598 15.078,10.15 15.63,10.15C16.182,10.15 16.63,10.598 16.63,11.15C16.63,11.703 16.182,12.15 15.63,12.15C15.078,12.15 14.63,11.703 14.63,11.15Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,3.15C14.63,2.874 14.854,2.65 15.13,2.65H16.13C16.406,2.65 16.63,2.874 16.63,3.15V8.15C16.63,8.427 16.406,8.65 16.13,8.65H15.13C14.854,8.65 14.63,8.427 14.63,8.15V3.15Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_3.xml b/packages/SettingsLib/res/drawable/ic_wifi_3.xml
new file mode 100644
index 0000000..9079daf
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_3.xml
@@ -0,0 +1,34 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="13dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.523,3.314C0.32,3.502 0.32,3.819 0.516,4.015L1.223,4.722C1.418,4.917 1.734,4.916 1.938,4.73C5.936,1.09 12.066,1.09 16.064,4.73C16.268,4.916 16.584,4.917 16.779,4.722L17.486,4.015C17.682,3.819 17.682,3.502 17.479,3.314C12.698,-1.105 5.304,-1.105 0.523,3.314Z"
+ android:fillAlpha="0.24"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M15.011,6.49C15.207,6.294 15.207,5.976 15.002,5.792C11.592,2.736 6.411,2.736 3,5.792C2.795,5.976 2.795,6.294 2.991,6.49L3.698,7.197C3.893,7.392 4.209,7.39 4.417,7.209C7.042,4.93 10.96,4.93 13.585,7.209C13.793,7.39 14.109,7.392 14.304,7.197L15.011,6.49Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.465,8.964C5.27,8.769 5.269,8.45 5.481,8.273C7.515,6.576 10.487,6.576 12.521,8.273C12.733,8.45 12.732,8.769 12.537,8.964L11.83,9.672C11.634,9.867 11.319,9.863 11.099,9.698C9.859,8.767 8.143,8.767 6.904,9.698C6.683,9.863 6.368,9.867 6.173,9.672L5.465,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.062,11.439C10.257,11.244 10.259,10.92 10.022,10.779C9.395,10.407 8.608,10.407 7.98,10.779C7.743,10.92 7.745,11.244 7.94,11.439L8.647,12.146C8.843,12.342 9.159,12.342 9.355,12.146L10.062,11.439Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_3_error.xml b/packages/SettingsLib/res/drawable/ic_wifi_3_error.xml
new file mode 100644
index 0000000..940781b
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_3_error.xml
@@ -0,0 +1,25 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="17dp"
+ android:height="13dp"
+ android:viewportWidth="17.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.146,4.015C-0.05,3.819 -0.05,3.502 0.153,3.314C4.002,-0.244 9.545,-0.937 14.055,1.234C13.339,1.449 12.792,2.053 12.66,2.801C8.998,1.281 4.65,1.924 1.568,4.73C1.364,4.916 1.048,4.917 0.853,4.722L0.146,4.015Z"
+ android:fillAlpha="0.3"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.63,4.435C9.406,2.836 5.424,3.288 2.63,5.792C2.424,5.976 2.425,6.294 2.621,6.49L3.328,7.197C3.523,7.392 3.839,7.39 4.047,7.209C6.484,5.094 10.033,4.942 12.63,6.753V4.435Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.095,8.964C4.9,8.769 4.899,8.45 5.111,8.273C7.145,6.576 10.117,6.576 12.151,8.273C12.363,8.45 12.362,8.769 12.166,8.964L11.459,9.672C11.264,9.867 10.949,9.863 10.728,9.698C9.489,8.767 7.773,8.767 6.533,9.698C6.313,9.863 5.998,9.867 5.802,9.672L5.095,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M9.652,10.779C9.889,10.92 9.887,11.244 9.692,11.439L8.984,12.146C8.789,12.342 8.473,12.342 8.277,12.146L7.57,11.439C7.375,11.244 7.373,10.92 7.61,10.779C8.237,10.407 9.024,10.407 9.652,10.779Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,11.15C14.63,10.598 15.078,10.15 15.63,10.15C16.182,10.15 16.63,10.598 16.63,11.15C16.63,11.703 16.182,12.15 15.63,12.15C15.078,12.15 14.63,11.703 14.63,11.15Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,3.15C14.63,2.874 14.854,2.65 15.13,2.65H16.13C16.406,2.65 16.63,2.874 16.63,3.15V8.15C16.63,8.427 16.406,8.65 16.13,8.65H15.13C14.854,8.65 14.63,8.427 14.63,8.15V3.15Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_4.xml b/packages/SettingsLib/res/drawable/ic_wifi_4.xml
new file mode 100644
index 0000000..6185e4a
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_4.xml
@@ -0,0 +1,33 @@
+<!--
+ Copyright (C) 2023 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="18dp"
+ android:height="13dp"
+ android:viewportWidth="18.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.523,3.314C0.32,3.502 0.32,3.819 0.516,4.015L1.223,4.722C1.418,4.917 1.734,4.916 1.938,4.73C5.936,1.09 12.066,1.09 16.064,4.73C16.268,4.916 16.584,4.917 16.779,4.722L17.486,4.015C17.682,3.819 17.682,3.502 17.479,3.314C12.698,-1.105 5.304,-1.105 0.523,3.314Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M15.011,6.49C15.207,6.294 15.207,5.976 15.002,5.792C11.592,2.736 6.411,2.736 3,5.792C2.795,5.976 2.795,6.294 2.991,6.49L3.698,7.197C3.893,7.392 4.209,7.39 4.417,7.209C7.042,4.93 10.96,4.93 13.585,7.209C13.793,7.39 14.109,7.392 14.304,7.197L15.011,6.49Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.465,8.964C5.27,8.769 5.269,8.45 5.481,8.273C7.515,6.576 10.487,6.576 12.521,8.273C12.733,8.45 12.732,8.769 12.537,8.964L11.83,9.672C11.634,9.867 11.319,9.863 11.099,9.698C9.859,8.767 8.143,8.767 6.904,9.698C6.683,9.863 6.368,9.867 6.173,9.672L5.465,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M10.062,11.439C10.257,11.244 10.259,10.92 10.022,10.779C9.395,10.407 8.608,10.407 7.98,10.779C7.743,10.92 7.745,11.244 7.94,11.439L8.647,12.146C8.843,12.342 9.159,12.342 9.355,12.146L10.062,11.439Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/res/drawable/ic_wifi_4_error.xml b/packages/SettingsLib/res/drawable/ic_wifi_4_error.xml
new file mode 100644
index 0000000..715aaa0
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_wifi_4_error.xml
@@ -0,0 +1,24 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="17dp"
+ android:height="13dp"
+ android:viewportWidth="17.0"
+ android:viewportHeight="13.0">
+ <path
+ android:pathData="M0.146,4.015C-0.05,3.819 -0.05,3.502 0.153,3.314C4.002,-0.244 9.545,-0.937 14.055,1.234C13.339,1.449 12.792,2.053 12.66,2.801C8.998,1.281 4.65,1.924 1.568,4.73C1.364,4.916 1.048,4.917 0.853,4.722L0.146,4.015Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M12.63,4.435C9.406,2.836 5.424,3.288 2.63,5.792C2.424,5.976 2.425,6.294 2.621,6.49L3.328,7.197C3.523,7.392 3.839,7.39 4.047,7.209C6.484,5.094 10.033,4.942 12.63,6.753V4.435Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M5.095,8.964C4.9,8.769 4.899,8.45 5.111,8.273C7.145,6.576 10.117,6.576 12.151,8.273C12.363,8.45 12.362,8.769 12.166,8.964L11.459,9.672C11.264,9.867 10.949,9.863 10.728,9.698C9.489,8.767 7.773,8.767 6.533,9.698C6.313,9.863 5.998,9.867 5.802,9.672L5.095,8.964Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M9.652,10.779C9.889,10.92 9.887,11.244 9.692,11.439L8.984,12.146C8.789,12.342 8.473,12.342 8.277,12.146L7.57,11.439C7.375,11.244 7.373,10.92 7.61,10.779C8.237,10.407 9.024,10.407 9.652,10.779Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,11.15C14.63,10.598 15.078,10.15 15.63,10.15C16.182,10.15 16.63,10.598 16.63,11.15C16.63,11.703 16.182,12.15 15.63,12.15C15.078,12.15 14.63,11.703 14.63,11.15Z"
+ android:fillColor="#000"/>
+ <path
+ android:pathData="M14.63,3.15C14.63,2.874 14.854,2.65 15.13,2.65H16.13C16.406,2.65 16.63,2.874 16.63,3.15V8.15C16.63,8.427 16.406,8.65 16.13,8.65H15.13C14.854,8.65 14.63,8.427 14.63,8.15V3.15Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SettingsLib/src/com/android/settingslib/graph/SignalDrawable.java b/packages/SettingsLib/src/com/android/settingslib/graph/SignalDrawable.java
index 9a19f93..ef0f6cb 100644
--- a/packages/SettingsLib/src/com/android/settingslib/graph/SignalDrawable.java
+++ b/packages/SettingsLib/src/com/android/settingslib/graph/SignalDrawable.java
@@ -14,6 +14,8 @@
package com.android.settingslib.graph;
+import static com.android.settingslib.flags.Flags.newStatusBarIcons;
+
import android.animation.ArgbEvaluator;
import android.annotation.IntRange;
import android.content.Context;
@@ -67,6 +69,9 @@
private static final long DOT_DELAY = 1000;
+ // Check the config for which icon we want to use
+ private static final int ICON_RES = SignalDrawable.getIconRes();
+
private final Paint mForegroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint mTransparentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final int mDarkModeFillColor;
@@ -85,7 +90,7 @@
private int mCurrentDot;
public SignalDrawable(Context context) {
- super(context.getDrawable(com.android.internal.R.drawable.ic_signal_cellular));
+ super(context.getDrawable(ICON_RES));
final String attributionPathString = context.getString(
com.android.internal.R.string.config_signalAttributionPath);
mAttributionPath.set(PathParser.createPathFromPathData(attributionPathString));
@@ -147,9 +152,17 @@
private int unpackLevel(int packedState) {
int numBins = (packedState & NUM_LEVEL_MASK) >> NUM_LEVEL_SHIFT;
+ int cutOutOffset = 0;
int levelOffset = numBins == (CellSignalStrength.getNumSignalStrengthLevels() + 1) ? 10 : 0;
int level = (packedState & LEVEL_MASK);
- return level + levelOffset;
+
+ if (newStatusBarIcons()) {
+ if (isInState(STATE_CUT)) {
+ cutOutOffset = 20;
+ }
+ }
+
+ return level + levelOffset + cutOutOffset;
}
public void setDarkIntensity(float darkIntensity) {
@@ -214,7 +227,7 @@
drawDotAndPadding(x - dotSpacing * 2, y, dotPadding, dotSize, 0);
canvas.drawPath(mCutoutPath, mTransparentPaint);
canvas.drawPath(mForegroundPath, mForegroundPaint);
- } else if (isInState(STATE_CUT)) {
+ } else if (!newStatusBarIcons() && isInState(STATE_CUT)) {
float cutX = (mCutoutWidthFraction * width / VIEWPORT);
float cutY = (mCutoutHeightFraction * height / VIEWPORT);
mCutoutPath.moveTo(width, height);
@@ -300,4 +313,12 @@
public static int getCarrierChangeState(int numLevels) {
return (STATE_CARRIER_CHANGE << STATE_SHIFT) | (numLevels << NUM_LEVEL_SHIFT);
}
+
+ private static int getIconRes() {
+ if (newStatusBarIcons()) {
+ return R.drawable.ic_mobile_level_list;
+ } else {
+ return com.android.internal.R.drawable.ic_signal_cellular;
+ }
+ }
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
index 50e2f9c..bdb5871 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
@@ -139,7 +139,6 @@
}
}
- @Override
public void startScan() {
mMediaDevices.clear();
startScanOnRouter();
@@ -156,7 +155,6 @@
}
}
- @Override
public abstract void stopScan();
protected abstract void startScanOnRouter();
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
index dfbf23f..8bebd6e 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
@@ -54,16 +54,6 @@
}
}
- /**
- * Start scan connected MediaDevice
- */
- public abstract void startScan();
-
- /**
- * Stop scan MediaDevice
- */
- public abstract void stopScan();
-
protected MediaDevice findMediaDevice(String id) {
for (MediaDevice mediaDevice : mMediaDevices) {
if (mediaDevice.getId().equals(id)) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.java
index b9a4647..69f83a4 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.java
@@ -19,6 +19,8 @@
import static android.net.wifi.WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLED;
import static android.net.wifi.WifiConfiguration.NetworkSelectionStatus.getMaxNetworkSelectionDisableReason;
+import static com.android.settingslib.flags.Flags.newStatusBarIcons;
+
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
@@ -88,21 +90,49 @@
public static final String KEY_CHOSEN_WIFIENTRY_KEY = "key_chosen_wifientry_key";
public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
- static final int[] WIFI_PIE = {
- com.android.internal.R.drawable.ic_wifi_signal_0,
- com.android.internal.R.drawable.ic_wifi_signal_1,
- com.android.internal.R.drawable.ic_wifi_signal_2,
- com.android.internal.R.drawable.ic_wifi_signal_3,
- com.android.internal.R.drawable.ic_wifi_signal_4
- };
+ static final int[] WIFI_PIE = getIconsBasedOnFlag();
- static final int[] NO_INTERNET_WIFI_PIE = {
- R.drawable.ic_no_internet_wifi_signal_0,
- R.drawable.ic_no_internet_wifi_signal_1,
- R.drawable.ic_no_internet_wifi_signal_2,
- R.drawable.ic_no_internet_wifi_signal_3,
- R.drawable.ic_no_internet_wifi_signal_4
- };
+ private static int[] getIconsBasedOnFlag() {
+ if (newStatusBarIcons()) {
+ return new int[] {
+ R.drawable.ic_wifi_0,
+ R.drawable.ic_wifi_1,
+ R.drawable.ic_wifi_2,
+ R.drawable.ic_wifi_3,
+ R.drawable.ic_wifi_4
+ };
+ } else {
+ return new int[] {
+ com.android.internal.R.drawable.ic_wifi_signal_0,
+ com.android.internal.R.drawable.ic_wifi_signal_1,
+ com.android.internal.R.drawable.ic_wifi_signal_2,
+ com.android.internal.R.drawable.ic_wifi_signal_3,
+ com.android.internal.R.drawable.ic_wifi_signal_4
+ };
+ }
+ }
+
+ static final int[] NO_INTERNET_WIFI_PIE = getErrorIconsBasedOnFlag();
+
+ private static int [] getErrorIconsBasedOnFlag() {
+ if (newStatusBarIcons()) {
+ return new int[] {
+ R.drawable.ic_wifi_0_error,
+ R.drawable.ic_wifi_1_error,
+ R.drawable.ic_wifi_2_error,
+ R.drawable.ic_wifi_3_error,
+ R.drawable.ic_wifi_4_error
+ };
+ } else {
+ return new int[] {
+ R.drawable.ic_no_internet_wifi_signal_0,
+ R.drawable.ic_no_internet_wifi_signal_1,
+ R.drawable.ic_no_internet_wifi_signal_2,
+ R.drawable.ic_no_internet_wifi_signal_3,
+ R.drawable.ic_no_internet_wifi_signal_4
+ };
+ }
+ }
public static String buildLoggingSummary(AccessPoint accessPoint, WifiConfiguration config) {
final StringBuilder summary = new StringBuilder();
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
index 3b73192..46e724d 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
@@ -52,17 +52,7 @@
when(mDevice.getId()).thenReturn(TEST_ID);
- mMediaManager = new MediaManager(mContext, null) {
- @Override
- public void startScan() {
-
- }
-
- @Override
- public void stopScan() {
-
- }
- };
+ mMediaManager = new MediaManager(mContext, null) {};
}
@Test
diff --git a/packages/SettingsProvider/Android.bp b/packages/SettingsProvider/Android.bp
index d5814e3..94ea016 100644
--- a/packages/SettingsProvider/Android.bp
+++ b/packages/SettingsProvider/Android.bp
@@ -60,6 +60,7 @@
// because this test is not an instrumentation test. (because the target runs in the system process.)
"SettingsProviderLib",
"androidx.test.rules",
+ "device_config_service_flags_java",
"flag-junit",
"junit",
"libaconfig_java_proto_lite",
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
index 1c9e748..ce0257f 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
@@ -359,6 +359,15 @@
@VisibleForTesting
@GuardedBy("mLock")
+ public void addAconfigDefaultValuesFromMap(
+ @NonNull Map<String, Map<String, String>> defaultMap) {
+ if (mNamespaceDefaults != null) {
+ mNamespaceDefaults.putAll(defaultMap);
+ }
+ }
+
+ @VisibleForTesting
+ @GuardedBy("mLock")
public static void loadAconfigDefaultValues(byte[] fileContents,
@NonNull Map<String, Map<String, String>> defaultMap) {
try {
@@ -510,6 +519,28 @@
return false;
}
+ // Aconfig flags are always boot stable, so we anytime we write one, we staged it to be
+ // applied on reboot.
+ if (Flags.stageAllAconfigFlags() && mNamespaceDefaults != null) {
+ int slashIndex = name.indexOf("/");
+ boolean stageFlag = isConfigSettingsKey(mKey)
+ && slashIndex != -1
+ && slashIndex != 0
+ && slashIndex != name.length();
+
+ if (stageFlag) {
+ String namespace = name.substring(0, slashIndex);
+ String flag = name.substring(slashIndex + 1);
+
+ boolean isAconfig = mNamespaceDefaults.containsKey(namespace)
+ && mNamespaceDefaults.get(namespace).containsKey(name);
+
+ if (isAconfig) {
+ name = "staged/" + namespace + "*" + flag;
+ }
+ }
+ }
+
final boolean isNameTooLong = name.length() > SettingsState.MAX_LENGTH_PER_STRING;
final boolean isValueTooLong =
value != null && value.length() > SettingsState.MAX_LENGTH_PER_STRING;
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/device_config_service.aconfig b/packages/SettingsProvider/src/com/android/providers/settings/device_config_service.aconfig
index ecac5ee..e5086e8 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/device_config_service.aconfig
+++ b/packages/SettingsProvider/src/com/android/providers/settings/device_config_service.aconfig
@@ -14,3 +14,14 @@
bug: "311155098"
is_fixed_read_only: true
}
+
+flag {
+ name: "stage_all_aconfig_flags"
+ namespace: "core_experiments_team_internal"
+ description: "Stage _all_ aconfig flags on writes, even local ones."
+ bug: "326598713"
+ is_fixed_read_only: true
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
index 9ecbd50..ea30c69 100644
--- a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
@@ -15,13 +15,25 @@
*/
package com.android.providers.settings;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertNull;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+
import android.aconfig.Aconfig;
import android.aconfig.Aconfig.parsed_flag;
import android.aconfig.Aconfig.parsed_flags;
import android.os.Looper;
-import android.test.AndroidTestCase;
+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.util.Xml;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
import com.android.modules.utils.TypedXmlSerializer;
import com.google.common.base.Strings;
@@ -34,7 +46,18 @@
import java.util.List;
import java.util.Map;
-public class SettingsStateTest extends AndroidTestCase {
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class SettingsStateTest {
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule =
+ DeviceFlagsValueProvider.createCheckFlagsRule();
+
public static final String CRAZY_STRING =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\n\u000b\u000c\r" +
"\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a" +
@@ -76,25 +99,25 @@
private File mSettingsFile;
- @Override
- protected void setUp() {
- mSettingsFile = new File(getContext().getCacheDir(), "setting.xml");
+ @Before
+ public void setUp() {
+ mSettingsFile = new File(InstrumentationRegistry.getContext().getCacheDir(), "setting.xml");
mSettingsFile.delete();
}
- @Override
- protected void tearDown() throws Exception {
+ @After
+ public void tearDown() throws Exception {
if (mSettingsFile != null) {
mSettingsFile.delete();
}
- super.tearDown();
}
+ @Test
public void testLoadValidAconfigProto() {
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
Object lock = new Object();
SettingsState settingsState = new SettingsState(
- getContext(), lock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
parsed_flags flags = parsed_flags
.newBuilder()
@@ -129,11 +152,12 @@
}
}
+ @Test
public void testSkipLoadingAconfigFlagWithMissingFields() {
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
Object lock = new Object();
SettingsState settingsState = new SettingsState(
- getContext(), lock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
parsed_flags flags = parsed_flags
@@ -155,12 +179,97 @@
}
}
+ @Test
+ @RequiresFlagsEnabled(Flags.FLAG_STAGE_ALL_ACONFIG_FLAGS)
+ public void testWritingAconfigFlagStages() {
+ int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
+ Object lock = new Object();
+ SettingsState settingsState = new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ parsed_flags flags = parsed_flags
+ .newBuilder()
+ .addParsedFlag(parsed_flag
+ .newBuilder()
+ .setPackage("com.android.flags")
+ .setName("flag5")
+ .setNamespace("test_namespace")
+ .setDescription("test flag")
+ .addBug("12345678")
+ .setState(Aconfig.flag_state.DISABLED)
+ .setPermission(Aconfig.flag_permission.READ_WRITE))
+ .build();
+
+ synchronized (lock) {
+ Map<String, Map<String, String>> defaults = new HashMap<>();
+ settingsState.loadAconfigDefaultValues(flags.toByteArray(), defaults);
+ settingsState.addAconfigDefaultValuesFromMap(defaults);
+
+ settingsState.insertSettingLocked("test_namespace/com.android.flags.flag5",
+ "true", null, false, "com.android.flags");
+ settingsState.insertSettingLocked("test_namespace/com.android.flags.flag6",
+ "true", null, false, "com.android.flags");
+
+ assertEquals("true",
+ settingsState
+ .getSettingLocked("staged/test_namespace*com.android.flags.flag5")
+ .getValue());
+ assertEquals(null,
+ settingsState
+ .getSettingLocked("test_namespace/com.android.flags.flag5")
+ .getValue());
+
+ assertEquals(null,
+ settingsState
+ .getSettingLocked("staged/test_namespace*com.android.flags.flag6")
+ .getValue());
+ assertEquals("true",
+ settingsState
+ .getSettingLocked("test_namespace/com.android.flags.flag6")
+ .getValue());
+ }
+ }
+
+ @Test
+ @RequiresFlagsDisabled(Flags.FLAG_LOAD_ACONFIG_DEFAULTS)
+ public void testAddingAconfigMapOnNullIsNoOp() {
+ int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
+ Object lock = new Object();
+ SettingsState settingsState = new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+
+ parsed_flags flags = parsed_flags
+ .newBuilder()
+ .addParsedFlag(parsed_flag
+ .newBuilder()
+ .setPackage("com.android.flags")
+ .setName("flag5")
+ .setNamespace("test_namespace")
+ .setDescription("test flag")
+ .addBug("12345678")
+ .setState(Aconfig.flag_state.DISABLED)
+ .setPermission(Aconfig.flag_permission.READ_WRITE))
+ .build();
+
+ synchronized (lock) {
+ Map<String, Map<String, String>> defaults = new HashMap<>();
+ settingsState.loadAconfigDefaultValues(flags.toByteArray(), defaults);
+ settingsState.addAconfigDefaultValuesFromMap(defaults);
+
+ assertEquals(null, settingsState.getAconfigDefaultValues());
+ }
+
+ }
+
+ @Test
public void testInvalidAconfigProtoDoesNotCrash() {
Map<String, Map<String, String>> defaults = new HashMap<>();
SettingsState settingsState = getSettingStateObject();
settingsState.loadAconfigDefaultValues("invalid protobuf".getBytes(), defaults);
}
+ @Test
public void testIsBinary() {
assertFalse(SettingsState.isBinary(" abc 日本語"));
@@ -191,6 +300,7 @@
}
/** Make sure we won't pass invalid characters to XML serializer. */
+ @Test
public void testWriteReadNoCrash() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
@@ -233,12 +343,15 @@
/**
* Make sure settings can be written to a file and also can be read.
*/
+ @Test
public void testReadWrite() {
final Object lock = new Object();
assertFalse(mSettingsFile.exists());
- final SettingsState ssWriter = new SettingsState(getContext(), lock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ final SettingsState ssWriter =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
ssWriter.setVersionLocked(SettingsState.SETTINGS_VERSION_NEW_ENCODING);
ssWriter.insertSettingLocked("k1", "\u0000", null, false, "package");
@@ -250,8 +363,10 @@
}
ssWriter.waitForHandler();
assertTrue(mSettingsFile.exists());
- final SettingsState ssReader = new SettingsState(getContext(), lock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ final SettingsState ssReader =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
assertEquals("\u0000", ssReader.getSettingLocked("k1").getValue());
@@ -264,6 +379,7 @@
/**
* In version 120, value "null" meant {code NULL}.
*/
+ @Test
public void testUpgrade() throws Exception {
final Object lock = new Object();
final PrintStream os = new PrintStream(new FileOutputStream(mSettingsFile));
@@ -276,8 +392,10 @@
"</settings>");
os.close();
- final SettingsState ss = new SettingsState(getContext(), lock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ final SettingsState ss =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
SettingsState.Setting s;
s = ss.getSettingLocked("k0");
@@ -294,6 +412,7 @@
}
}
+ @Test
public void testInitializeSetting_preserveFlagNotSet() {
SettingsState settingsWriter = getSettingStateObject();
settingsWriter.insertSettingLocked(SETTING_NAME, "1", null, false, TEST_PACKAGE);
@@ -304,6 +423,7 @@
assertFalse(settingsReader.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ @Test
public void testModifySetting_preserveFlagSet() {
SettingsState settingsWriter = getSettingStateObject();
settingsWriter.insertSettingLocked(SETTING_NAME, "1", null, false, TEST_PACKAGE);
@@ -315,6 +435,7 @@
assertTrue(settingsReader.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ @Test
public void testModifySettingOverrideableByRestore_preserveFlagNotSet() {
SettingsState settingsWriter = getSettingStateObject();
settingsWriter.insertSettingLocked(SETTING_NAME, "1", null, false, TEST_PACKAGE);
@@ -327,6 +448,7 @@
assertFalse(settingsReader.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ @Test
public void testModifySettingOverrideableByRestore_preserveFlagAlreadySet_flagValueUnchanged() {
SettingsState settingsWriter = getSettingStateObject();
// Init the setting.
@@ -344,6 +466,7 @@
assertTrue(settingsReader.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ @Test
public void testResetSetting_preservedFlagIsReset() {
SettingsState settingsState = getSettingStateObject();
// Initialize the setting.
@@ -356,6 +479,7 @@
}
+ @Test
public void testModifySettingBySystemPackage_sameValue_preserveFlagNotSet() {
SettingsState settingsState = getSettingStateObject();
// Initialize the setting.
@@ -366,6 +490,7 @@
assertFalse(settingsState.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ @Test
public void testModifySettingBySystemPackage_newValue_preserveFlagSet() {
SettingsState settingsState = getSettingStateObject();
// Initialize the setting.
@@ -377,12 +502,15 @@
}
private SettingsState getSettingStateObject() {
- SettingsState settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ SettingsState settingsState =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
settingsState.setVersionLocked(SettingsState.SETTINGS_VERSION_NEW_ENCODING);
return settingsState;
}
+ @Test
public void testInsertSetting_memoryUsage() {
SettingsState settingsState = getSettingStateObject();
// No exception should be thrown when there is no cap
@@ -390,8 +518,10 @@
null, false, "p1");
settingsState.deleteSettingLocked(SETTING_NAME);
- settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
+ settingsState =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
// System package doesn't have memory usage limit
settingsState.insertSettingLocked(SETTING_NAME, Strings.repeat("A", 20001),
null, false, SYSTEM_PACKAGE);
@@ -425,9 +555,12 @@
}
}
+ @Test
public void testMemoryUsagePerPackage() {
- SettingsState settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
+ SettingsState settingsState =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
// Test inserting one key with default
final String testKey1 = SETTING_NAME;
@@ -512,9 +645,12 @@
assertEquals(expectedMemUsage, settingsState.getMemoryUsage(TEST_PACKAGE));
}
+ @Test
public void testLargeSettingKey() {
- SettingsState settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
+ SettingsState settingsState =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED, Looper.getMainLooper());
final String largeKey = Strings.repeat("A", SettingsState.MAX_LENGTH_PER_STRING + 1);
final String testValue = "testValue";
synchronized (mLock) {
@@ -535,9 +671,12 @@
}
}
+ @Test
public void testLargeSettingValue() {
- SettingsState settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
- SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+ SettingsState settingsState =
+ new SettingsState(
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, 1,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
final String testKey = "testKey";
final String largeValue = Strings.repeat("A", SettingsState.MAX_LENGTH_PER_STRING + 1);
synchronized (mLock) {
@@ -558,11 +697,12 @@
}
}
+ @Test
public void testApplyStagedConfigValues() {
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
Object lock = new Object();
SettingsState settingsState = new SettingsState(
- getContext(), lock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
@@ -578,7 +718,8 @@
assertEquals(VALUE2, settingsState.getSettingLocked(FLAG_NAME_2).getValue());
}
- settingsState = new SettingsState(getContext(), lock, mSettingsFile, configKey,
+ settingsState = new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
@@ -589,6 +730,7 @@
}
}
+ @Test
public void testStagingTransformation() {
assertEquals(INVALID_STAGED_FLAG_1,
SettingsState.createRealFlagName(INVALID_STAGED_FLAG_1));
@@ -603,11 +745,12 @@
SettingsState.createRealFlagName(VALID_STAGED_FLAG_1));
}
+ @Test
public void testInvalidStagedFlagsUnaffectedByReboot() {
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
Object lock = new Object();
SettingsState settingsState = new SettingsState(
- getContext(), lock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
@@ -620,7 +763,8 @@
assertEquals(VALUE2, settingsState.getSettingLocked(INVALID_STAGED_FLAG_1).getValue());
}
- settingsState = new SettingsState(getContext(), lock, mSettingsFile, configKey,
+ settingsState = new SettingsState(
+ InstrumentationRegistry.getContext(), lock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
synchronized (lock) {
@@ -628,6 +772,7 @@
}
}
+ @Test
public void testsetSettingsLockedKeepTrunkDefault() throws Exception {
final PrintStream os = new PrintStream(new FileOutputStream(mSettingsFile));
os.print(
@@ -648,7 +793,7 @@
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
SettingsState settingsState = new SettingsState(
- getContext(), mLock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
String prefix = "test_namespace";
@@ -705,6 +850,7 @@
}
}
+ @Test
public void testsetSettingsLockedNoTrunkDefault() throws Exception {
final PrintStream os = new PrintStream(new FileOutputStream(mSettingsFile));
os.print(
@@ -720,7 +866,7 @@
int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
SettingsState settingsState = new SettingsState(
- getContext(), mLock, mSettingsFile, configKey,
+ InstrumentationRegistry.getContext(), mLock, mSettingsFile, configKey,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
Map<String, String> keyValues =
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index f5c4843..cb6894e 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -542,6 +542,13 @@
namespace: "systemui"
description: "Binds Keyguard Media Controller Visibility to MediaContainerView"
bug: "298213983"
+}
+
+flag {
+ name: "delayed_wakelock_release_on_background_thread"
+ namespace: "systemui"
+ description: "Released delayed wakelocks on background threads to avoid janking screen transitions."
+ bug: "316128516"
metadata {
purpose: PURPOSE_BUGFIX
}
@@ -556,3 +563,10 @@
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "media_controls_refactor"
+ namespace: "systemui"
+ description: "Refactors media code to follow the recommended architecture"
+ bug: "326408371"
+}
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 609f314..078da1c86 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
@@ -17,6 +17,7 @@
package com.android.systemui.communal.ui.compose
import android.appwidget.AppWidgetHostView
+import android.graphics.drawable.Icon
import android.os.Bundle
import android.util.SizeF
import android.widget.FrameLayout
@@ -26,6 +27,7 @@
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -77,6 +79,8 @@
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ColorFilter
+import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
@@ -85,8 +89,10 @@
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalConfiguration
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
@@ -101,6 +107,8 @@
import androidx.core.view.setPadding
import com.android.compose.modifiers.thenIf
import com.android.compose.theme.LocalAndroidColorScheme
+import com.android.compose.ui.graphics.painter.rememberDrawablePainter
+import com.android.internal.R.dimen.system_app_widget_background_radius
import com.android.systemui.communal.domain.model.CommunalContentModel
import com.android.systemui.communal.shared.model.CommunalContentSize
import com.android.systemui.communal.ui.compose.Dimensions.CardOutlineWidth
@@ -178,7 +186,7 @@
// not display this button.
if (
index == null ||
- communalContent[index].isWidget() ||
+ communalContent[index].isWidgetContent() ||
communalContent[index] is CommunalContentModel.CtaTileInViewMode
) {
isButtonToEditWidgetsShowing = true
@@ -330,7 +338,7 @@
DraggableItem(
dragDropState = dragDropState,
selected = selected,
- enabled = list[index] is CommunalContentModel.Widget,
+ enabled = list[index].isWidgetContent(),
index = index,
) { isDragging ->
CommunalContent(
@@ -539,9 +547,11 @@
widgetConfigurator: WidgetConfigurator? = null,
) {
when (model) {
- is CommunalContentModel.Widget ->
+ is CommunalContentModel.WidgetContent.Widget ->
WidgetContent(viewModel, model, size, selected, widgetConfigurator, modifier)
is CommunalContentModel.WidgetPlaceholder -> HighlightedItem(modifier)
+ is CommunalContentModel.WidgetContent.DisabledWidget ->
+ DisabledWidgetPlaceholder(model, modifier)
is CommunalContentModel.CtaTileInViewMode -> CtaTileInViewModeContent(viewModel, modifier)
is CommunalContentModel.CtaTileInEditMode ->
CtaTileInEditModeContent(modifier, onOpenWidgetPicker)
@@ -672,7 +682,7 @@
@Composable
private fun WidgetContent(
viewModel: BaseCommunalViewModel,
- model: CommunalContentModel.Widget,
+ model: CommunalContentModel.WidgetContent.Widget,
size: SizeF,
selected: Boolean,
widgetConfigurator: WidgetConfigurator?,
@@ -692,8 +702,9 @@
},
update = { view ->
// Remove the extra padding applied to AppWidgetHostView to allow widgets to
- // occupy the entire box. The added padding is now adjusted to leave only sufficient
- // space for displaying the outline around the box when the widget is selected.
+ // occupy the entire box. The added padding is now adjusted to leave only
+ // sufficient space for displaying the outline around the box when the widget
+ // is selected.
view.setPadding(paddingInPx)
},
// For reusing composition in lazy lists.
@@ -717,7 +728,7 @@
@Composable
fun WidgetConfigureButton(
visible: Boolean,
- model: CommunalContentModel.Widget,
+ model: CommunalContentModel.WidgetContent.Widget,
modifier: Modifier = Modifier,
widgetConfigurator: WidgetConfigurator,
) {
@@ -752,6 +763,38 @@
}
@Composable
+fun DisabledWidgetPlaceholder(
+ model: CommunalContentModel.WidgetContent.DisabledWidget,
+ modifier: Modifier = Modifier,
+) {
+ val context = LocalContext.current
+ val appInfo = model.appInfo
+ val icon: Icon =
+ if (appInfo == null || appInfo.icon == 0) {
+ Icon.createWithResource(context, android.R.drawable.sym_def_app_icon)
+ } else {
+ Icon.createWithResource(appInfo.packageName, appInfo.icon)
+ }
+
+ Column(
+ modifier =
+ modifier.background(
+ MaterialTheme.colorScheme.surfaceVariant,
+ RoundedCornerShape(dimensionResource(system_app_widget_background_radius))
+ ),
+ verticalArrangement = Arrangement.Center,
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Image(
+ painter = rememberDrawablePainter(icon.loadDrawable(context)),
+ contentDescription = stringResource(R.string.icon_description_for_disabled_widget),
+ modifier = Modifier.size(48.dp),
+ colorFilter = ColorFilter.colorMatrix(Colors.DisabledColorFilter),
+ )
+ }
+}
+
+@Composable
private fun SmartspaceContent(
model: CommunalContentModel.Smartspace,
modifier: Modifier = Modifier,
@@ -852,7 +895,7 @@
/** Returns the key of item if it's editable at the given index. Only widget is editable. */
private fun keyAtIndexIfEditable(list: List<CommunalContentModel>, index: Int): String? =
- if (index in list.indices && list[index].isWidget()) list[index].key else null
+ if (index in list.indices && list[index].isWidgetContent()) list[index].key else null
data class ContentPaddingInPx(val start: Float, val top: Float) {
fun toOffset(): Offset = Offset(start, top)
@@ -882,5 +925,30 @@
val IconSize = 48.dp
}
+private object Colors {
+ val DisabledColorFilter by lazy { disabledColorMatrix() }
+
+ /** Returns the disabled image filter. Ported over from [DisableImageView]. */
+ private fun disabledColorMatrix(): ColorMatrix {
+ val brightnessMatrix = ColorMatrix()
+ val brightnessAmount = 0.5f
+ val brightnessRgb = (255 * brightnessAmount).toInt().toFloat()
+ // Brightness: C-new = C-old*(1-amount) + amount
+ val scale = 1f - brightnessAmount
+ val mat = brightnessMatrix.values
+ mat[0] = scale
+ mat[6] = scale
+ mat[12] = scale
+ mat[4] = brightnessRgb
+ mat[9] = brightnessRgb
+ mat[14] = brightnessRgb
+
+ return ColorMatrix().apply {
+ setToSaturation(0F)
+ timesAssign(brightnessMatrix)
+ }
+ }
+}
+
/** The resource id of communal hub accessible from UiAutomator. */
private const val COMMUNAL_HUB_TEST_TAG = "communal_hub"
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/ContentListState.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/ContentListState.kt
index 9b8c9d0..c5dab33 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/ContentListState.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/ContentListState.kt
@@ -71,8 +71,8 @@
/** Remove widget from the list and the database. */
fun onRemove(indexToRemove: Int) {
- if (list[indexToRemove] is CommunalContentModel.Widget) {
- val widget = list[indexToRemove] as CommunalContentModel.Widget
+ if (list[indexToRemove].isWidgetContent()) {
+ val widget = list[indexToRemove] as CommunalContentModel.WidgetContent
list.apply { removeAt(indexToRemove) }
onDeleteWidget(widget.appWidgetId)
}
@@ -100,7 +100,7 @@
val widgetIdToPriorityMap: Map<Int, Int> =
list
.mapIndexedNotNull { index, item ->
- if (item is CommunalContentModel.Widget) {
+ if (item is CommunalContentModel.WidgetContent) {
item.appWidgetId to list.size - index
} else {
null
@@ -115,5 +115,5 @@
}
/** Returns true if the item at given index is editable. */
- fun isItemEditable(index: Int) = list[index] is CommunalContentModel.Widget
+ fun isItemEditable(index: Int) = list[index].isWidgetContent()
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
index 452dc03..d23cd0c 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
@@ -35,11 +35,13 @@
import com.android.systemui.keyguard.ui.composable.section.BottomAreaSection
import com.android.systemui.keyguard.ui.composable.section.DefaultClockSection
import com.android.systemui.keyguard.ui.composable.section.LockSection
+import com.android.systemui.keyguard.ui.composable.section.MediaCarouselSection
import com.android.systemui.keyguard.ui.composable.section.NotificationSection
import com.android.systemui.keyguard.ui.composable.section.SettingsMenuSection
import com.android.systemui.keyguard.ui.composable.section.SmartSpaceSection
import com.android.systemui.keyguard.ui.composable.section.StatusBarSection
import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
+import com.android.systemui.media.controls.ui.composable.MediaCarousel
import com.android.systemui.res.R
import dagger.Binds
import dagger.Module
@@ -63,6 +65,7 @@
private val ambientIndicationSectionOptional: Optional<AmbientIndicationSection>,
private val bottomAreaSection: BottomAreaSection,
private val settingsMenuSection: SettingsMenuSection,
+ private val mediaCarouselSection: MediaCarouselSection,
private val clockInteractor: KeyguardClockInteractor,
) : ComposableLockscreenSceneBlueprint {
@@ -112,10 +115,16 @@
if (viewModel.isLargeClockVisible) {
Spacer(modifier = Modifier.weight(weight = 1f))
- with(clockSection) { LargeClock(modifier = Modifier.fillMaxWidth()) }
+ with(clockSection) {
+ LargeClock(
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
}
- if (viewModel.areNotificationsVisible) {
+ with(mediaCarouselSection) { MediaCarousel() }
+
+ if (viewModel.areNotificationsVisible(resources = resources)) {
with(notificationSection) {
Notifications(
modifier = Modifier.fillMaxWidth().weight(weight = 1f)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
index 71c60c7..c422c4b 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
@@ -35,6 +35,7 @@
import com.android.systemui.keyguard.ui.composable.section.BottomAreaSection
import com.android.systemui.keyguard.ui.composable.section.DefaultClockSection
import com.android.systemui.keyguard.ui.composable.section.LockSection
+import com.android.systemui.keyguard.ui.composable.section.MediaCarouselSection
import com.android.systemui.keyguard.ui.composable.section.NotificationSection
import com.android.systemui.keyguard.ui.composable.section.SettingsMenuSection
import com.android.systemui.keyguard.ui.composable.section.SmartSpaceSection
@@ -63,6 +64,7 @@
private val ambientIndicationSectionOptional: Optional<AmbientIndicationSection>,
private val bottomAreaSection: BottomAreaSection,
private val settingsMenuSection: SettingsMenuSection,
+ private val mediaCarouselSection: MediaCarouselSection,
private val clockInteractor: KeyguardClockInteractor,
) : ComposableLockscreenSceneBlueprint {
@@ -115,7 +117,9 @@
with(clockSection) { LargeClock(modifier = Modifier.fillMaxWidth()) }
}
- if (viewModel.areNotificationsVisible) {
+ with(mediaCarouselSection) { MediaCarousel() }
+
+ if (viewModel.areNotificationsVisible(resources = resources)) {
with(notificationSection) {
Notifications(
modifier = Modifier.fillMaxWidth().weight(weight = 1f)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/SplitShadeBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/SplitShadeBlueprint.kt
index af836b6..d218425 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/SplitShadeBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/SplitShadeBlueprint.kt
@@ -41,6 +41,7 @@
import com.android.systemui.keyguard.ui.composable.section.BottomAreaSection
import com.android.systemui.keyguard.ui.composable.section.DefaultClockSection
import com.android.systemui.keyguard.ui.composable.section.LockSection
+import com.android.systemui.keyguard.ui.composable.section.MediaCarouselSection
import com.android.systemui.keyguard.ui.composable.section.NotificationSection
import com.android.systemui.keyguard.ui.composable.section.SettingsMenuSection
import com.android.systemui.keyguard.ui.composable.section.SmartSpaceSection
@@ -70,6 +71,7 @@
private val ambientIndicationSectionOptional: Optional<AmbientIndicationSection>,
private val bottomAreaSection: BottomAreaSection,
private val settingsMenuSection: SettingsMenuSection,
+ private val mediaCarouselSection: MediaCarouselSection,
private val clockInteractor: KeyguardClockInteractor,
private val largeScreenHeaderHelper: LargeScreenHeaderHelper,
) : ComposableLockscreenSceneBlueprint {
@@ -100,6 +102,14 @@
modifier = Modifier.fillMaxHeight().weight(weight = 1f),
horizontalAlignment = Alignment.CenterHorizontally,
) {
+ with(clockSection) {
+ SmallClock(
+ burnInParams = burnIn.parameters,
+ onTopChanged = burnIn.onSmallClockTopChanged,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+
with(smartSpaceSection) {
SmartSpace(
burnInParams = burnIn.parameters,
@@ -121,9 +131,13 @@
)
}
- Spacer(modifier = Modifier.weight(weight = 1f))
- with(clockSection) { LargeClock() }
- Spacer(modifier = Modifier.weight(weight = 1f))
+ if (viewModel.isLargeClockVisible) {
+ Spacer(modifier = Modifier.weight(weight = 1f))
+ with(clockSection) { LargeClock() }
+ Spacer(modifier = Modifier.weight(weight = 1f))
+ }
+
+ with(mediaCarouselSection) { MediaCarousel() }
}
with(notificationSection) {
val splitShadeTopMargin: Dp =
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/WeatherClockBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/WeatherClockBlueprint.kt
index e2e7a95..f86623f 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/WeatherClockBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/WeatherClockBlueprint.kt
@@ -41,12 +41,14 @@
import com.android.systemui.keyguard.ui.composable.section.AmbientIndicationSection
import com.android.systemui.keyguard.ui.composable.section.BottomAreaSection
import com.android.systemui.keyguard.ui.composable.section.LockSection
+import com.android.systemui.keyguard.ui.composable.section.MediaCarouselSection
import com.android.systemui.keyguard.ui.composable.section.NotificationSection
import com.android.systemui.keyguard.ui.composable.section.SettingsMenuSection
import com.android.systemui.keyguard.ui.composable.section.SmartSpaceSection
import com.android.systemui.keyguard.ui.composable.section.StatusBarSection
import com.android.systemui.keyguard.ui.composable.section.WeatherClockSection
import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
+import com.android.systemui.media.controls.ui.composable.MediaCarousel
import com.android.systemui.res.R
import com.android.systemui.shade.LargeScreenHeaderHelper
import dagger.Binds
@@ -68,6 +70,7 @@
private val bottomAreaSection: BottomAreaSection,
private val settingsMenuSection: SettingsMenuSection,
private val clockInteractor: KeyguardClockInteractor,
+ private val mediaCarouselSection: MediaCarouselSection,
) : ComposableLockscreenSceneBlueprint {
override val id: String = WEATHER_CLOCK_BLUEPRINT_ID
@@ -107,7 +110,9 @@
)
}
- if (viewModel.areNotificationsVisible) {
+ with(mediaCarouselSection) { MediaCarousel() }
+
+ if (viewModel.areNotificationsVisible(resources = resources)) {
with(notificationSection) {
Notifications(
modifier = Modifier.fillMaxWidth().weight(weight = 1f)
@@ -228,6 +233,7 @@
private val clockInteractor: KeyguardClockInteractor,
private val largeScreenHeaderHelper: LargeScreenHeaderHelper,
private val weatherClockSection: WeatherClockSection,
+ private val mediaCarouselSection: MediaCarouselSection,
) : ComposableLockscreenSceneBlueprint {
override val id: String = SPLIT_SHADE_WEATHER_CLOCK_BLUEPRINT_ID
@@ -276,6 +282,8 @@
),
)
}
+
+ with(mediaCarouselSection) { MediaCarousel() }
}
with(notificationSection) {
val splitShadeTopMargin: Dp =
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/DefaultClockSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/DefaultClockSection.kt
index 335c915..152cc67 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/DefaultClockSection.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/DefaultClockSection.kt
@@ -39,7 +39,6 @@
import com.android.systemui.keyguard.ui.viewmodel.AodBurnInViewModel
import com.android.systemui.keyguard.ui.viewmodel.BurnInParameters
import com.android.systemui.keyguard.ui.viewmodel.KeyguardClockViewModel
-import com.android.systemui.statusbar.lockscreen.LockscreenSmartspaceController
import javax.inject.Inject
/** Provides small clock and large clock composables for the default clock face. */
@@ -49,7 +48,6 @@
private val viewModel: KeyguardClockViewModel,
private val clockInteractor: KeyguardClockInteractor,
private val aodBurnInViewModel: AodBurnInViewModel,
- private val lockscreenSmartspaceController: LockscreenSmartspaceController,
) {
@Composable
@@ -62,15 +60,11 @@
val currentClock by viewModel.currentClock.collectAsState()
viewModel.clock = currentClock
- if (clockSize != KeyguardClockSwitch.SMALL) {
+ if (clockSize != KeyguardClockSwitch.SMALL || currentClock?.smallClock?.view == null) {
onTopChanged(null)
return
}
- if (currentClock?.smallClock?.view == null) {
- return
- }
-
val view = LocalView.current
DisposableEffect(view) {
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/MediaCarouselSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/MediaCarouselSection.kt
new file mode 100644
index 0000000..dae120c
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/MediaCarouselSection.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.systemui.keyguard.ui.composable.section
+
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.dimensionResource
+import com.android.compose.animation.scene.SceneScope
+import com.android.systemui.keyguard.ui.viewmodel.MediaCarouselViewModel
+import com.android.systemui.media.controls.ui.composable.MediaCarousel
+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
+import com.android.systemui.util.animation.MeasurementInput
+import javax.inject.Inject
+import javax.inject.Named
+
+class MediaCarouselSection
+@Inject
+constructor(
+ private val mediaCarouselController: MediaCarouselController,
+ @param:Named(MediaModule.KEYGUARD) private val mediaHost: MediaHost,
+ private val mediaCarouselViewModel: MediaCarouselViewModel,
+) {
+
+ @Composable
+ fun SceneScope.MediaCarousel(modifier: Modifier = Modifier) {
+ if (!mediaCarouselViewModel.isMediaVisible) {
+ return
+ }
+
+ if (mediaCarouselController.mediaFrame == null) {
+ return
+ }
+
+ val mediaHeight = dimensionResource(R.dimen.qs_media_session_height_expanded)
+ // TODO(b/312714128): MediaPlayer background size is not as expected.
+ MediaCarousel(
+ modifier =
+ modifier.height(mediaHeight).fillMaxWidth().onSizeChanged { size ->
+ // Notify controller to size the carousel for the
+ // current space
+ mediaHost.measurementInput = MeasurementInput(size.width, size.height)
+ mediaCarouselController.setSceneContainerSize(size.width, size.height)
+ },
+ mediaHost = mediaHost,
+ layoutWidth = 0, // Layout width is not used.
+ layoutHeight = with(LocalDensity.current) { mediaHeight.toPx() }.toInt(),
+ carouselController = mediaCarouselController,
+ )
+ }
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/media/controls/ui/composable/MediaCarousel.kt b/packages/SystemUI/compose/features/src/com/android/systemui/media/controls/ui/composable/MediaCarousel.kt
index 61b2d4e..d3e4553 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/media/controls/ui/composable/MediaCarousel.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/media/controls/ui/composable/MediaCarousel.kt
@@ -16,9 +16,12 @@
package com.android.systemui.media.controls.ui.composable
+import android.view.ViewGroup
+import android.widget.FrameLayout
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
+import androidx.core.view.contains
import com.android.compose.animation.scene.ElementKey
import com.android.compose.animation.scene.SceneScope
import com.android.systemui.media.controls.ui.controller.MediaCarouselController
@@ -45,6 +48,20 @@
AndroidView(
modifier = modifier.element(MediaCarousel.Elements.Content),
- factory = { _ -> carouselController.mediaFrame },
+ factory = { context ->
+ FrameLayout(context).apply {
+ val mediaFrame = carouselController.mediaFrame
+ (mediaFrame.parent as? ViewGroup)?.removeView(mediaFrame)
+ addView(mediaFrame)
+ }
+ },
+ update = {
+ if (it.contains(carouselController.mediaFrame)) {
+ return@AndroidView
+ }
+ val mediaFrame = carouselController.mediaFrame
+ (mediaFrame.parent as? ViewGroup)?.removeView(mediaFrame)
+ it.addView(mediaFrame)
+ },
)
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneGestureHandler.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/DraggableHandler.kt
similarity index 79%
rename from packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneGestureHandler.kt
rename to packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/DraggableHandler.kt
index 187d82a..b94e49b 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneGestureHandler.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/DraggableHandler.kt
@@ -36,44 +36,38 @@
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
-internal class SceneGestureHandler(
+interface DraggableHandler {
+ /**
+ * Start a drag in the given [startedPosition], with the given [overSlop] and number of
+ * [pointersDown].
+ *
+ * The returned [DragController] should be used to continue or stop the drag.
+ */
+ fun onDragStarted(startedPosition: Offset?, overSlop: Float, pointersDown: Int): DragController
+}
+
+/**
+ * The [DragController] provides control over the transition between two scenes through the [onDrag]
+ * and [onStop] methods.
+ */
+interface DragController {
+ /** Drag the current scene by [delta] pixels. */
+ fun onDrag(delta: Float)
+
+ /** Starts a transition to a target scene. */
+ fun onStop(velocity: Float, canChangeScene: Boolean)
+}
+
+internal class DraggableHandlerImpl(
internal val layoutImpl: SceneTransitionLayoutImpl,
internal val orientation: Orientation,
- private val coroutineScope: CoroutineScope,
-) {
- private val layoutState = layoutImpl.state
- val draggable: DraggableHandler = SceneDraggableHandler(this)
+ internal val coroutineScope: CoroutineScope,
+) : DraggableHandler {
+ /** The [DraggableHandler] can only have one active [DragController] at a time. */
+ private var dragController: DragControllerImpl? = null
- private var _swipeTransition: SwipeTransition? = null
- private var swipeTransition: SwipeTransition
- get() = _swipeTransition ?: error("SwipeTransition needs to be initialized")
- set(value) {
- _swipeTransition = value
- }
-
- private fun updateTransition(newTransition: SwipeTransition, force: Boolean = false) {
- if (isDrivingTransition || force) {
- layoutState.startTransition(newTransition, newTransition.key)
-
- // Initialize SwipeTransition.transformationSpec and .swipeSpec. Note that this must be
- // called right after layoutState.startTransition() is called, because it computes the
- // current layoutState.transformationSpec().
- val transformationSpec = layoutState.transformationSpec
- newTransition.transformationSpec = transformationSpec
- newTransition.swipeSpec =
- transformationSpec.swipeSpec ?: layoutState.transitions.defaultSwipeSpec
- } else {
- // We were not driving the transition and we don't force the update, so the specs won't
- // be used and it doesn't matter which ones we set here.
- newTransition.transformationSpec = TransformationSpec.Empty
- newTransition.swipeSpec = SceneTransitions.DefaultSwipeSpec
- }
-
- swipeTransition = newTransition
- }
-
- internal val isDrivingTransition
- get() = layoutState.transitionState == _swipeTransition
+ internal val isDrivingTransition: Boolean
+ get() = dragController?.isDrivingTransition == true
/**
* The velocity threshold at which the intent of the user is to swipe up or down. It is the same
@@ -86,14 +80,9 @@
* The positional threshold at which the intent of the user is to swipe to the next scene. It is
* the same as SwipeableV2Defaults.PositionalThreshold.
*/
- private val positionalThreshold
+ internal val positionalThreshold
get() = with(layoutImpl.density) { 56.dp.toPx() }
- internal var currentSource: Any? = null
-
- /** The [Swipes] associated to the current gesture. */
- private var swipes: Swipes? = null
-
/**
* Whether we should immediately intercept a gesture.
*
@@ -102,35 +91,52 @@
*/
internal fun shouldImmediatelyIntercept(startedPosition: Offset?): Boolean {
// We don't intercept the touch if we are not currently driving the transition.
- if (!isDrivingTransition) {
+ val dragController = dragController
+ if (dragController?.isDrivingTransition != true) {
return false
}
// Only intercept the current transition if one of the 2 swipes results is also a transition
// between the same pair of scenes.
+ val swipeTransition = dragController.swipeTransition
val fromScene = swipeTransition._currentScene
val swipes = computeSwipes(fromScene, startedPosition, pointersDown = 1)
- val (upOrLeft, downOrRight) = computeSwipesResults(fromScene, swipes)
+ val (upOrLeft, downOrRight) = swipes.computeSwipesResults(fromScene)
return (upOrLeft != null &&
swipeTransition.isTransitioningBetween(fromScene.key, upOrLeft.toScene)) ||
(downOrRight != null &&
swipeTransition.isTransitioningBetween(fromScene.key, downOrRight.toScene))
}
- internal fun onDragStarted(pointersDown: Int, startedPosition: Offset?, overSlop: Float) {
+ override fun onDragStarted(
+ startedPosition: Offset?,
+ overSlop: Float,
+ pointersDown: Int,
+ ): DragController {
if (overSlop == 0f) {
- check(isDrivingTransition) {
- "onDragStarted() called while isDrivingTransition=false overSlop=0f"
+ val oldDragController = dragController
+ check(oldDragController != null && oldDragController.isDrivingTransition) {
+ val isActive = oldDragController?.isDrivingTransition
+ "onDragStarted(overSlop=0f) requires an active dragController, but was $isActive"
}
// This [transition] was already driving the animation: simply take over it.
// Stop animating and start from where the current offset.
- swipeTransition.cancelOffsetAnimation()
- swipes!!.updateSwipesResults(swipeTransition._fromScene)
- return
+ oldDragController.swipeTransition.cancelOffsetAnimation()
+
+ // We need to recompute the swipe results since this is a new gesture, and the
+ // fromScene.userActions may have changed.
+ val swipes = oldDragController.swipes
+ swipes.updateSwipesResults(oldDragController.swipeTransition._fromScene)
+
+ // A new gesture should always create a new SwipeTransition. This way there cannot be
+ // different gestures controlling the same transition.
+ val swipeTransition = SwipeTransition(oldDragController.swipeTransition)
+ swipes.updateSwipesResults(fromScene = swipeTransition._fromScene)
+ return updateDragController(swipes, swipeTransition)
}
- val transitionState = layoutState.transitionState
+ val transitionState = layoutImpl.state.transitionState
if (transitionState is TransitionState.Transition) {
// TODO(b/290184746): Better handle interruptions here if state != idle.
Log.w(
@@ -142,24 +148,27 @@
}
val fromScene = layoutImpl.scene(transitionState.currentScene)
- val newSwipes = computeSwipes(fromScene, startedPosition, pointersDown)
- swipes = newSwipes
- val result = newSwipes.findUserActionResult(fromScene, overSlop, true)
+ val swipes = computeSwipes(fromScene, startedPosition, pointersDown)
+ val result = swipes.findUserActionResult(fromScene, overSlop, true)
// As we were unable to locate a valid target scene, the initial SwipeTransition cannot be
- // defined.
- if (result == null) return
+ // defined. Consequently, a simple NoOp Controller will be returned.
+ if (result == null) return NoOpDragController
- val newSwipeTransition =
- SwipeTransition(
- fromScene = fromScene,
- result = result,
- swipes = newSwipes,
- layoutImpl = layoutImpl,
- orientation = orientation
- )
+ return updateDragController(
+ swipes = swipes,
+ swipeTransition = SwipeTransition(fromScene, result, swipes, layoutImpl, orientation)
+ )
+ }
- updateTransition(newSwipeTransition, force = true)
+ private fun updateDragController(
+ swipes: Swipes,
+ swipeTransition: SwipeTransition
+ ): DragController {
+ val newDragController = DragControllerImpl(this, swipes, swipeTransition)
+ newDragController.updateTransition(swipeTransition, force = true)
+ dragController = newDragController
+ return newDragController
}
private fun computeSwipes(
@@ -216,7 +225,58 @@
}
}
- internal fun onDrag(delta: Float) {
+ companion object {
+ private const val TAG = "DraggableHandlerImpl"
+ }
+}
+
+/** @param swipes The [Swipes] associated to the current gesture. */
+private class DragControllerImpl(
+ private val draggableHandler: DraggableHandlerImpl,
+ val swipes: Swipes,
+ var swipeTransition: SwipeTransition,
+) : DragController {
+ val layoutState = draggableHandler.layoutImpl.state
+
+ /**
+ * Whether this handle is active. If this returns false, calling [onDrag] and [onStop] will do
+ * nothing. We should have only one active controller at a time
+ */
+ val isDrivingTransition: Boolean
+ get() = layoutState.transitionState == swipeTransition
+
+ init {
+ check(!isDrivingTransition) { "Multiple controllers with the same SwipeTransition" }
+ }
+
+ fun updateTransition(newTransition: SwipeTransition, force: Boolean = false) {
+ if (isDrivingTransition || force) {
+ layoutState.startTransition(newTransition, newTransition.key)
+
+ // Initialize SwipeTransition.transformationSpec and .swipeSpec. Note that this must be
+ // called right after layoutState.startTransition() is called, because it computes the
+ // current layoutState.transformationSpec().
+ val transformationSpec = layoutState.transformationSpec
+ newTransition.transformationSpec = transformationSpec
+ newTransition.swipeSpec =
+ transformationSpec.swipeSpec ?: layoutState.transitions.defaultSwipeSpec
+ } else {
+ // We were not driving the transition and we don't force the update, so the specs won't
+ // be used and it doesn't matter which ones we set here.
+ newTransition.transformationSpec = TransformationSpec.Empty
+ newTransition.swipeSpec = SceneTransitions.DefaultSwipeSpec
+ }
+
+ swipeTransition = newTransition
+ }
+
+ /**
+ * We receive a [delta] that can be consumed to change the offset of the current
+ * [SwipeTransition].
+ *
+ * @return the consumed delta
+ */
+ override fun onDrag(delta: Float) {
if (delta == 0f || !isDrivingTransition) return
swipeTransition.dragOffset += delta
@@ -225,14 +285,14 @@
val isNewFromScene = fromScene.key != swipeTransition.fromScene
val result =
- swipes!!.findUserActionResult(
+ swipes.findUserActionResult(
fromScene = fromScene,
directionOffset = swipeTransition.dragOffset,
updateSwipesResults = isNewFromScene
)
if (result == null) {
- onDragStopped(velocity = delta, canChangeScene = true)
+ onStop(velocity = delta, canChangeScene = true)
return
}
@@ -243,36 +303,20 @@
result.toScene != swipeTransition.toScene ||
result.transitionKey != swipeTransition.key
) {
- val newSwipeTransition =
+ val swipeTransition =
SwipeTransition(
fromScene = fromScene,
result = result,
- swipes = swipes!!,
- layoutImpl = layoutImpl,
- orientation = orientation
+ swipes = swipes,
+ layoutImpl = draggableHandler.layoutImpl,
+ orientation = draggableHandler.orientation,
)
.apply { dragOffset = swipeTransition.dragOffset }
- updateTransition(newSwipeTransition)
+ updateTransition(swipeTransition)
}
}
- private fun computeSwipesResults(
- fromScene: Scene,
- swipes: Swipes
- ): Pair<UserActionResult?, UserActionResult?> {
- val userActions = fromScene.userActions
- fun sceneToSwipePair(swipe: Swipe?): UserActionResult? {
- return userActions[swipe ?: return null]
- }
-
- val upOrLeftResult =
- sceneToSwipePair(swipes.upOrLeft) ?: sceneToSwipePair(swipes.upOrLeftNoSource)
- val downOrRightResult =
- sceneToSwipePair(swipes.downOrRight) ?: sceneToSwipePair(swipes.downOrRightNoSource)
- return Pair(upOrLeftResult, downOrRightResult)
- }
-
/**
* Change fromScene in the case where the user quickly swiped multiple times in the same
* direction to accelerate the transition from A => B then B => C.
@@ -302,18 +346,22 @@
// to the next screen or go back to the previous one.
val offset = swipeTransition.dragOffset
val absoluteDistance = distance.absoluteValue
- return if (offset <= -absoluteDistance && swipes!!.upOrLeftResult?.toScene == toScene.key) {
+ return if (offset <= -absoluteDistance && swipes.upOrLeftResult?.toScene == toScene.key) {
toScene to absoluteDistance
- } else if (
- offset >= absoluteDistance && swipes!!.downOrRightResult?.toScene == toScene.key
- ) {
+ } else if (offset >= absoluteDistance && swipes.downOrRightResult?.toScene == toScene.key) {
toScene to -absoluteDistance
} else {
fromScene to 0f
}
}
- internal fun onDragStopped(velocity: Float, canChangeScene: Boolean) {
+ private fun snapToScene(scene: SceneKey) {
+ if (!isDrivingTransition) return
+ swipeTransition.cancelOffsetAnimation()
+ layoutState.finishTransition(swipeTransition, idleScene = scene)
+ }
+
+ override fun onStop(velocity: Float, canChangeScene: Boolean) {
// The state was changed since the drag started; don't do anything.
if (!isDrivingTransition) {
return
@@ -332,16 +380,16 @@
// immediately go back B => A.
if (targetScene != swipeTransition._currentScene) {
swipeTransition._currentScene = targetScene
- with(layoutImpl.state) { coroutineScope.onChangeScene(targetScene.key) }
+ with(draggableHandler.layoutImpl.state) {
+ draggableHandler.coroutineScope.onChangeScene(targetScene.key)
+ }
}
swipeTransition.animateOffset(
- coroutineScope = coroutineScope,
+ coroutineScope = draggableHandler.coroutineScope,
initialVelocity = velocity,
targetOffset = targetOffset,
- onAnimationCompleted = {
- layoutState.finishTransition(swipeTransition, idleScene = targetScene.key)
- }
+ onAnimationCompleted = { snapToScene(targetScene.key) }
)
}
@@ -400,10 +448,10 @@
if (startFromIdlePosition) {
// If there is a target scene, we start the overscroll animation.
- val result = swipes!!.findUserActionResultStrict(velocity)
+ val result = swipes.findUserActionResultStrict(velocity)
if (result == null) {
// We will not animate
- layoutState.finishTransition(swipeTransition, idleScene = fromScene.key)
+ snapToScene(fromScene.key)
return
}
@@ -411,9 +459,9 @@
SwipeTransition(
fromScene = fromScene,
result = result,
- swipes = swipes!!,
- layoutImpl = layoutImpl,
- orientation = orientation
+ swipes = swipes,
+ layoutImpl = draggableHandler.layoutImpl,
+ orientation = draggableHandler.orientation,
)
.apply { _currentScene = swipeTransition._currentScene }
@@ -440,6 +488,9 @@
return (offset - distance).absoluteValue < offset.absoluteValue
}
+ val velocityThreshold = draggableHandler.velocityThreshold
+ val positionalThreshold = draggableHandler.positionalThreshold
+
// Swiping up or left.
if (distance < 0f) {
return if (offset > 0f || velocity >= velocityThreshold) {
@@ -460,10 +511,6 @@
isCloserToTarget()
}
}
-
- companion object {
- private const val TAG = "SceneGestureHandler"
- }
}
private fun SwipeTransition(
@@ -492,11 +539,26 @@
)
}
+private fun SwipeTransition(old: SwipeTransition): SwipeTransition {
+ return SwipeTransition(
+ key = old.key,
+ _fromScene = old._fromScene,
+ _toScene = old._toScene,
+ userActionDistanceScope = old.userActionDistanceScope,
+ orientation = old.orientation,
+ isUpOrLeft = old.isUpOrLeft
+ )
+ .apply {
+ _currentScene = old._currentScene
+ dragOffset = old.dragOffset
+ }
+}
+
private class SwipeTransition(
val key: TransitionKey?,
val _fromScene: Scene,
val _toScene: Scene,
- private val userActionDistanceScope: UserActionDistanceScope,
+ val userActionDistanceScope: UserActionDistanceScope,
override val orientation: Orientation,
override val isUpOrLeft: Boolean,
) :
@@ -730,40 +792,16 @@
}
}
-private class SceneDraggableHandler(
- private val gestureHandler: SceneGestureHandler,
-) : DraggableHandler {
- private val source = this
-
- override fun onDragStarted(startedPosition: Offset, overSlop: Float, pointersDown: Int) {
- gestureHandler.currentSource = source
- gestureHandler.onDragStarted(pointersDown, startedPosition, overSlop)
- }
-
- override fun onDelta(pixels: Float) {
- if (gestureHandler.currentSource == source) {
- gestureHandler.onDrag(delta = pixels)
- }
- }
-
- override fun onDragStopped(velocity: Float) {
- if (gestureHandler.currentSource == source) {
- gestureHandler.currentSource = null
- gestureHandler.onDragStopped(velocity = velocity, canChangeScene = true)
- }
- }
-}
-
-internal class SceneNestedScrollHandler(
+internal class NestedScrollHandlerImpl(
private val layoutImpl: SceneTransitionLayoutImpl,
private val orientation: Orientation,
private val topOrLeftBehavior: NestedScrollBehavior,
private val bottomOrRightBehavior: NestedScrollBehavior,
-) : NestedScrollHandler {
+) {
private val layoutState = layoutImpl.state
- private val gestureHandler = layoutImpl.gestureHandler(orientation)
+ private val draggableHandler = layoutImpl.draggableHandler(orientation)
- override val connection: PriorityNestedScrollConnection = nestedScrollConnection()
+ val connection: PriorityNestedScrollConnection = nestedScrollConnection()
private fun nestedScrollConnection(): PriorityNestedScrollConnection {
// If we performed a long gesture before entering priority mode, we would have to avoid
@@ -808,7 +846,7 @@
return overscrollSpec != null
}
- val source = this
+ var dragController: DragController? = null
var isIntercepting = false
return PriorityNestedScrollConnection(
@@ -819,7 +857,7 @@
val canInterceptSwipeTransition =
canChangeScene &&
offsetAvailable != 0f &&
- gestureHandler.shouldImmediatelyIntercept(startedPosition = null)
+ draggableHandler.shouldImmediatelyIntercept(startedPosition = null)
if (!canInterceptSwipeTransition) return@PriorityNestedScrollConnection false
val threshold = layoutImpl.transitionInterceptionThreshold
@@ -893,34 +931,28 @@
canContinueScroll = { true },
canScrollOnFling = false,
onStart = { offsetAvailable ->
- gestureHandler.currentSource = source
- gestureHandler.onDragStarted(
- pointersDown = 1,
- startedPosition = null,
- overSlop = if (isIntercepting) 0f else offsetAvailable,
- )
+ dragController =
+ draggableHandler.onDragStarted(
+ pointersDown = 1,
+ startedPosition = null,
+ overSlop = if (isIntercepting) 0f else offsetAvailable,
+ )
},
onScroll = { offsetAvailable ->
- if (gestureHandler.currentSource != source) {
- return@PriorityNestedScrollConnection 0f
- }
+ val controller = dragController ?: error("Should be called after onStart")
// TODO(b/297842071) We should handle the overscroll or slow drag if the gesture is
// initiated in a nested child.
- gestureHandler.onDrag(offsetAvailable)
+ controller.onDrag(delta = offsetAvailable)
offsetAvailable
},
onStop = { velocityAvailable ->
- if (gestureHandler.currentSource != source) {
- return@PriorityNestedScrollConnection 0f
- }
+ val controller = dragController ?: error("Should be called after onStart")
- gestureHandler.onDragStopped(
- velocity = velocityAvailable,
- canChangeScene = canChangeScene
- )
+ controller.onStop(velocity = velocityAvailable, canChangeScene = canChangeScene)
+ dragController = null
// The onDragStopped animation consumes any remaining velocity.
velocityAvailable
},
@@ -935,3 +967,9 @@
// TODO(b/290184746): Have a better default visibility threshold which takes the swipe distance into
// account instead.
internal const val OffsetVisibilityThreshold = 0.5f
+
+private object NoOpDragController : DragController {
+ override fun onDrag(delta: Float) {}
+
+ override fun onStop(velocity: Float, canChangeScene: Boolean) {}
+}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/GestureHandler.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/GestureHandler.kt
deleted file mode 100644
index 58052cd..0000000
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/GestureHandler.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.android.compose.animation.scene
-
-import androidx.compose.ui.geometry.Offset
-import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
-
-interface DraggableHandler {
- fun onDragStarted(startedPosition: Offset, overSlop: Float, pointersDown: Int = 1)
- fun onDelta(pixels: Float)
- fun onDragStopped(velocity: Float)
-}
-
-interface NestedScrollHandler {
- val connection: NestedScrollConnection
-}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/MultiPointerDraggable.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/MultiPointerDraggable.kt
index 3ff869b..05dd5cc 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/MultiPointerDraggable.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/MultiPointerDraggable.kt
@@ -24,7 +24,6 @@
import androidx.compose.foundation.gestures.horizontalDrag
import androidx.compose.foundation.gestures.verticalDrag
import androidx.compose.runtime.Stable
-import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEvent
@@ -33,7 +32,6 @@
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.SuspendingPointerInputModifierNode
-import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.input.pointer.util.addPointerInputChange
@@ -69,9 +67,7 @@
orientation: Orientation,
enabled: () -> Boolean,
startDragImmediately: (startedPosition: Offset) -> Boolean,
- onDragStarted: (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> Unit,
- onDragDelta: (delta: Float) -> Unit,
- onDragStopped: (velocity: Float) -> Unit,
+ onDragStarted: (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> DragController,
): Modifier =
this.then(
MultiPointerDraggableElement(
@@ -79,8 +75,6 @@
enabled,
startDragImmediately,
onDragStarted,
- onDragDelta,
- onDragStopped,
)
)
@@ -89,9 +83,7 @@
private val enabled: () -> Boolean,
private val startDragImmediately: (startedPosition: Offset) -> Boolean,
private val onDragStarted:
- (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> Unit,
- private val onDragDelta: (Float) -> Unit,
- private val onDragStopped: (velocity: Float) -> Unit,
+ (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> DragController,
) : ModifierNodeElement<MultiPointerDraggableNode>() {
override fun create(): MultiPointerDraggableNode =
MultiPointerDraggableNode(
@@ -99,8 +91,6 @@
enabled = enabled,
startDragImmediately = startDragImmediately,
onDragStarted = onDragStarted,
- onDragDelta = onDragDelta,
- onDragStopped = onDragStopped,
)
override fun update(node: MultiPointerDraggableNode) {
@@ -108,8 +98,6 @@
node.enabled = enabled
node.startDragImmediately = startDragImmediately
node.onDragStarted = onDragStarted
- node.onDragDelta = onDragDelta
- node.onDragStopped = onDragStopped
}
}
@@ -117,9 +105,8 @@
orientation: Orientation,
enabled: () -> Boolean,
var startDragImmediately: (startedPosition: Offset) -> Boolean,
- var onDragStarted: (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> Unit,
- var onDragDelta: (Float) -> Unit,
- var onDragStopped: (velocity: Float) -> Unit,
+ var onDragStarted:
+ (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> DragController,
) :
PointerInputModifierNode,
DelegatingNode(),
@@ -176,40 +163,33 @@
return
}
- val onDragStart: (Offset, Float, Int) -> Unit = { startedPosition, overSlop, pointersDown ->
- velocityTracker.resetTracking()
- onDragStarted(startedPosition, overSlop, pointersDown)
- }
-
- val onDragCancel: () -> Unit = { onDragStopped(/* velocity= */ 0f) }
-
- val onDragEnd: () -> Unit = {
- val maxFlingVelocity =
- currentValueOf(LocalViewConfiguration).maximumFlingVelocity.let { max ->
- Velocity(max, max)
- }
-
- val velocity = velocityTracker.calculateVelocity(maxFlingVelocity)
- onDragStopped(
- when (orientation) {
- Orientation.Horizontal -> velocity.x
- Orientation.Vertical -> velocity.y
- }
- )
- }
-
- val onDrag: (change: PointerInputChange, dragAmount: Float) -> Unit = { change, amount ->
- velocityTracker.addPointerInputChange(change)
- onDragDelta(amount)
- }
-
detectDragGestures(
orientation = orientation,
startDragImmediately = startDragImmediately,
- onDragStart = onDragStart,
- onDragEnd = onDragEnd,
- onDragCancel = onDragCancel,
- onDrag = onDrag,
+ onDragStart = { startedPosition, overSlop, pointersDown ->
+ velocityTracker.resetTracking()
+ onDragStarted(startedPosition, overSlop, pointersDown)
+ },
+ onDrag = { controller, change, amount ->
+ velocityTracker.addPointerInputChange(change)
+ controller.onDrag(amount)
+ },
+ onDragEnd = { controller ->
+ val viewConfiguration = currentValueOf(LocalViewConfiguration)
+ val maxVelocity = viewConfiguration.maximumFlingVelocity.let { Velocity(it, it) }
+ val velocity = velocityTracker.calculateVelocity(maxVelocity)
+ controller.onStop(
+ velocity =
+ when (orientation) {
+ Orientation.Horizontal -> velocity.x
+ Orientation.Vertical -> velocity.y
+ },
+ canChangeScene = true,
+ )
+ },
+ onDragCancel = { controller ->
+ controller.onStop(velocity = 0f, canChangeScene = true)
+ },
)
}
}
@@ -225,10 +205,10 @@
private suspend fun PointerInputScope.detectDragGestures(
orientation: Orientation,
startDragImmediately: (startedPosition: Offset) -> Boolean,
- onDragStart: (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> Unit,
- onDragEnd: () -> Unit,
- onDragCancel: () -> Unit,
- onDrag: (change: PointerInputChange, dragAmount: Float) -> Unit,
+ onDragStart: (startedPosition: Offset, overSlop: Float, pointersDown: Int) -> DragController,
+ onDragEnd: (controller: DragController) -> Unit,
+ onDragCancel: (controller: DragController) -> Unit,
+ onDrag: (controller: DragController, change: PointerInputChange, dragAmount: Float) -> Unit,
) {
awaitEachGesture {
val initialDown = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
@@ -282,34 +262,34 @@
}
}
- onDragStart(drag.position, overSlop, pressed.size)
+ val controller = onDragStart(drag.position, overSlop, pressed.size)
val successful: Boolean
try {
- onDrag(drag, overSlop)
+ onDrag(controller, drag, overSlop)
successful =
when (orientation) {
Orientation.Horizontal ->
horizontalDrag(drag.id) {
- onDrag(it, it.positionChange().x)
+ onDrag(controller, it, it.positionChange().x)
it.consume()
}
Orientation.Vertical ->
verticalDrag(drag.id) {
- onDrag(it, it.positionChange().y)
+ onDrag(controller, it, it.positionChange().y)
it.consume()
}
}
} catch (t: Throwable) {
- onDragCancel()
+ onDragCancel(controller)
throw t
}
if (successful) {
- onDragEnd()
+ onDragEnd(controller)
} else {
- onDragCancel()
+ onDragCancel(controller)
}
}
}
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/NestedScrollToScene.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/NestedScrollToScene.kt
index e78f326..5a2f85a 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/NestedScrollToScene.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/NestedScrollToScene.kt
@@ -178,7 +178,7 @@
topOrLeftBehavior: NestedScrollBehavior,
bottomOrRightBehavior: NestedScrollBehavior,
) =
- SceneNestedScrollHandler(
+ NestedScrollHandlerImpl(
layoutImpl = layoutImpl,
orientation = orientation,
topOrLeftBehavior = topOrLeftBehavior,
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutImpl.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutImpl.kt
index 3093d47..1670e9c 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutImpl.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SceneTransitionLayoutImpl.kt
@@ -102,8 +102,8 @@
.also { _sharedValues = it }
// TODO(b/317958526): Lazily allocate scene gesture handlers the first time they are needed.
- private val horizontalGestureHandler: SceneGestureHandler
- private val verticalGestureHandler: SceneGestureHandler
+ private val horizontalDraggableHandler: DraggableHandlerImpl
+ private val verticalDraggableHandler: DraggableHandlerImpl
private var _userActionDistanceScope: UserActionDistanceScope? = null
internal val userActionDistanceScope: UserActionDistanceScope
@@ -116,27 +116,27 @@
init {
updateScenes(builder)
- // SceneGestureHandler must wait for the scenes to be initialized, in order to access the
+ // DraggableHandlerImpl must wait for the scenes to be initialized, in order to access the
// current scene (required for SwipeTransition).
- horizontalGestureHandler =
- SceneGestureHandler(
+ horizontalDraggableHandler =
+ DraggableHandlerImpl(
layoutImpl = this,
orientation = Orientation.Horizontal,
coroutineScope = coroutineScope,
)
- verticalGestureHandler =
- SceneGestureHandler(
+ verticalDraggableHandler =
+ DraggableHandlerImpl(
layoutImpl = this,
orientation = Orientation.Vertical,
coroutineScope = coroutineScope,
)
}
- internal fun gestureHandler(orientation: Orientation): SceneGestureHandler =
+ internal fun draggableHandler(orientation: Orientation): DraggableHandlerImpl =
when (orientation) {
- Orientation.Vertical -> verticalGestureHandler
- Orientation.Horizontal -> horizontalGestureHandler
+ Orientation.Vertical -> verticalDraggableHandler
+ Orientation.Horizontal -> horizontalDraggableHandler
}
internal fun scene(key: SceneKey): Scene {
@@ -192,8 +192,8 @@
// Handle horizontal and vertical swipes on this layout.
// Note: order here is important and will give a slight priority to the vertical
// swipes.
- .swipeToScene(horizontalGestureHandler)
- .swipeToScene(verticalGestureHandler)
+ .swipeToScene(horizontalDraggableHandler)
+ .swipeToScene(verticalDraggableHandler)
.then(LayoutElement(layoutImpl = this))
) {
LookaheadScope {
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeToScene.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeToScene.kt
index 61f4978..b618369 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeToScene.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/SwipeToScene.kt
@@ -31,39 +31,39 @@
* Configures the swipeable behavior of a [SceneTransitionLayout] depending on the current state.
*/
@Stable
-internal fun Modifier.swipeToScene(gestureHandler: SceneGestureHandler): Modifier {
- return this.then(SwipeToSceneElement(gestureHandler))
+internal fun Modifier.swipeToScene(draggableHandler: DraggableHandlerImpl): Modifier {
+ return this.then(SwipeToSceneElement(draggableHandler))
}
private data class SwipeToSceneElement(
- val gestureHandler: SceneGestureHandler,
+ val draggableHandler: DraggableHandlerImpl,
) : ModifierNodeElement<SwipeToSceneNode>() {
- override fun create(): SwipeToSceneNode = SwipeToSceneNode(gestureHandler)
+ override fun create(): SwipeToSceneNode = SwipeToSceneNode(draggableHandler)
override fun update(node: SwipeToSceneNode) {
- node.gestureHandler = gestureHandler
+ node.draggableHandler = draggableHandler
}
}
private class SwipeToSceneNode(
- gestureHandler: SceneGestureHandler,
+ draggableHandler: DraggableHandlerImpl,
) : DelegatingNode(), PointerInputModifierNode {
private val delegate =
delegate(
MultiPointerDraggableNode(
- orientation = gestureHandler.orientation,
+ orientation = draggableHandler.orientation,
enabled = ::enabled,
startDragImmediately = ::startDragImmediately,
- onDragStarted = gestureHandler.draggable::onDragStarted,
- onDragDelta = gestureHandler.draggable::onDelta,
- onDragStopped = gestureHandler.draggable::onDragStopped,
+ onDragStarted = draggableHandler::onDragStarted,
)
)
- var gestureHandler: SceneGestureHandler = gestureHandler
+ private var _draggableHandler = draggableHandler
+ var draggableHandler: DraggableHandlerImpl
+ get() = _draggableHandler
set(value) {
- if (value != field) {
- field = value
+ if (_draggableHandler != value) {
+ _draggableHandler = value
// Make sure to update the delegate orientation. Note that this will automatically
// reset the underlying pointer input handler, so previous gestures will be
@@ -81,12 +81,12 @@
override fun onCancelPointerInput() = delegate.onCancelPointerInput()
private fun enabled(): Boolean {
- return gestureHandler.isDrivingTransition ||
- currentScene().shouldEnableSwipes(gestureHandler.orientation)
+ return draggableHandler.isDrivingTransition ||
+ currentScene().shouldEnableSwipes(delegate.orientation)
}
private fun currentScene(): Scene {
- val layoutImpl = gestureHandler.layoutImpl
+ val layoutImpl = draggableHandler.layoutImpl
return layoutImpl.scene(layoutImpl.state.transitionState.currentScene)
}
@@ -98,12 +98,12 @@
private fun startDragImmediately(startedPosition: Offset): Boolean {
// Immediately start the drag if the user can't swipe in the other direction and the gesture
// handler can intercept it.
- return !canOppositeSwipe() && gestureHandler.shouldImmediatelyIntercept(startedPosition)
+ return !canOppositeSwipe() && draggableHandler.shouldImmediatelyIntercept(startedPosition)
}
private fun canOppositeSwipe(): Boolean {
val oppositeOrientation =
- when (gestureHandler.orientation) {
+ when (draggableHandler.orientation) {
Orientation.Vertical -> Orientation.Horizontal
Orientation.Horizontal -> Orientation.Vertical
}
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneGestureHandlerTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
similarity index 84%
rename from packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneGestureHandlerTest.kt
rename to packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
index d28ac6a..eb9b428 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/SceneGestureHandlerTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/DraggableHandlerTest.kt
@@ -47,7 +47,7 @@
private val LAYOUT_SIZE = IntSize(SCREEN_SIZE.toInt(), SCREEN_SIZE.toInt())
@RunWith(AndroidJUnit4::class)
-class SceneGestureHandlerTest {
+class DraggableHandlerTest {
private class TestGestureScope(
private val testScope: MonotonicClockTestScope,
) {
@@ -99,19 +99,19 @@
)
.apply { setScenesTargetSizeForTest(LAYOUT_SIZE) }
- val sceneGestureHandler = layoutImpl.gestureHandler(Orientation.Vertical)
- val horizontalSceneGestureHandler = layoutImpl.gestureHandler(Orientation.Horizontal)
+ val draggableHandler = layoutImpl.draggableHandler(Orientation.Vertical)
+ val horizontalDraggableHandler = layoutImpl.draggableHandler(Orientation.Horizontal)
fun nestedScrollConnection(nestedScrollBehavior: NestedScrollBehavior) =
- SceneNestedScrollHandler(
+ NestedScrollHandlerImpl(
layoutImpl = layoutImpl,
- orientation = sceneGestureHandler.orientation,
+ orientation = draggableHandler.orientation,
topOrLeftBehavior = nestedScrollBehavior,
bottomOrRightBehavior = nestedScrollBehavior,
)
.connection
- val velocityThreshold = sceneGestureHandler.velocityThreshold
+ val velocityThreshold = draggableHandler.velocityThreshold
fun down(fractionOfScreen: Float) =
if (fractionOfScreen < 0f) error("use up()") else SCREEN_SIZE * fractionOfScreen
@@ -190,20 +190,18 @@
fun onDragStarted(
startedPosition: Offset = Offset.Zero,
overSlop: Float,
- pointersDown: Int = 1
- ) {
+ pointersDown: Int = 1,
+ ): DragController {
// overSlop should be 0f only if the drag gesture starts with startDragImmediately
if (overSlop == 0f) error("Consider using onDragStartedImmediately()")
- onDragStarted(sceneGestureHandler.draggable, startedPosition, overSlop, pointersDown)
+ return onDragStarted(draggableHandler, startedPosition, overSlop, pointersDown)
}
- fun onDragStartedImmediately(startedPosition: Offset = Offset.Zero, pointersDown: Int = 1) {
- onDragStarted(
- sceneGestureHandler.draggable,
- startedPosition,
- overSlop = 0f,
- pointersDown
- )
+ fun onDragStartedImmediately(
+ startedPosition: Offset = Offset.Zero,
+ pointersDown: Int = 1,
+ ): DragController {
+ return onDragStarted(draggableHandler, startedPosition, overSlop = 0f, pointersDown)
}
fun onDragStarted(
@@ -211,24 +209,26 @@
startedPosition: Offset = Offset.Zero,
overSlop: Float = 0f,
pointersDown: Int = 1
- ) {
- draggableHandler.onDragStarted(
- startedPosition = startedPosition,
- overSlop = overSlop,
- pointersDown = pointersDown,
- )
+ ): DragController {
+ val dragController =
+ draggableHandler.onDragStarted(
+ startedPosition = startedPosition,
+ overSlop = overSlop,
+ pointersDown = pointersDown,
+ )
// MultiPointerDraggable will always call onDelta with the initial overSlop right after
- onDelta(pixels = overSlop)
+ dragController.onDragDelta(pixels = overSlop)
+
+ return dragController
}
- fun onDelta(pixels: Float) {
- sceneGestureHandler.draggable.onDelta(pixels = pixels)
+ fun DragController.onDragDelta(pixels: Float) {
+ onDrag(delta = pixels)
}
- fun onDragStopped(velocity: Float) {
- sceneGestureHandler.draggable.onDragStopped(velocity = velocity)
- runCurrent()
+ fun DragController.onDragStopped(velocity: Float, canChangeScene: Boolean = true) {
+ onStop(velocity, canChangeScene)
}
fun NestedScrollConnection.scroll(
@@ -281,20 +281,20 @@
@Test
fun afterSceneTransitionIsStarted_interceptDragEvents() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
assertTransition(currentScene = SceneA)
assertThat(progress).isEqualTo(0.1f)
- onDelta(pixels = down(fractionOfScreen = 0.1f))
+ dragController.onDragDelta(pixels = down(fractionOfScreen = 0.1f))
assertThat(progress).isEqualTo(0.2f)
}
@Test
fun onDragStoppedAfterDrag_velocityLowerThanThreshold_remainSameScene() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
assertTransition(currentScene = SceneA)
- onDragStopped(velocity = velocityThreshold - 0.01f)
+ dragController.onDragStopped(velocity = velocityThreshold - 0.01f)
assertTransition(currentScene = SceneA)
// wait for the stop animation
@@ -304,10 +304,10 @@
@Test
fun onDragStoppedAfterDrag_velocityAtLeastThreshold_goToNextScene() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
assertTransition(currentScene = SceneA)
- onDragStopped(velocity = velocityThreshold)
+ dragController.onDragStopped(velocity = velocityThreshold)
assertTransition(currentScene = SceneC)
// wait for the stop animation
@@ -317,10 +317,10 @@
@Test
fun onDragStoppedAfterStarted_returnToIdle() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
assertTransition(currentScene = SceneA)
- onDragStopped(velocity = 0f)
+ dragController.onDragStopped(velocity = 0f)
advanceUntilIdle()
assertIdle(currentScene = SceneA)
}
@@ -328,7 +328,7 @@
@Test
fun onDragReversedDirection_changeToScene() = runGestureTest {
// Drag A -> B with progress 0.6
- onDragStarted(overSlop = -60f)
+ val dragController = onDragStarted(overSlop = -60f)
assertTransition(
currentScene = SceneA,
fromScene = SceneA,
@@ -337,7 +337,7 @@
)
// Reverse direction such that A -> C now with 0.4
- onDelta(pixels = 100f)
+ dragController.onDragDelta(pixels = 100f)
assertTransition(
currentScene = SceneA,
fromScene = SceneA,
@@ -346,7 +346,7 @@
)
// After the drag stopped scene C should be committed
- onDragStopped(velocity = velocityThreshold)
+ dragController.onDragStopped(velocity = velocityThreshold)
assertTransition(currentScene = SceneC, fromScene = SceneA, toScene = SceneC)
// wait for the stop animation
@@ -356,8 +356,6 @@
@Test
fun onDragStartedWithoutActionsInBothDirections_stayIdle() = runGestureTest {
- val horizontalDraggableHandler = horizontalSceneGestureHandler.draggable
-
onDragStarted(horizontalDraggableHandler, overSlop = up(fractionOfScreen = 0.3f))
assertIdle(currentScene = SceneA)
@@ -370,7 +368,7 @@
navigateToSceneC()
// We are on SceneC which has no action in Down direction
- onDragStarted(overSlop = 10f)
+ val dragController = onDragStarted(overSlop = 10f)
assertTransition(
currentScene = SceneC,
fromScene = SceneC,
@@ -379,7 +377,7 @@
)
// Reverse drag direction, it will consume the previous drag
- onDelta(pixels = -10f)
+ dragController.onDragDelta(pixels = -10f)
assertTransition(
currentScene = SceneC,
fromScene = SceneC,
@@ -388,7 +386,7 @@
)
// Continue reverse drag direction, it should record progress to Scene B
- onDelta(pixels = -10f)
+ dragController.onDragDelta(pixels = -10f)
assertTransition(
currentScene = SceneC,
fromScene = SceneC,
@@ -416,14 +414,14 @@
@Test
fun onDragToExactlyZero_toSceneIsSet() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.3f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.3f))
assertTransition(
currentScene = SceneA,
fromScene = SceneA,
toScene = SceneC,
progress = 0.3f
)
- onDelta(pixels = up(fractionOfScreen = 0.3f))
+ dragController.onDragDelta(pixels = up(fractionOfScreen = 0.3f))
assertTransition(
currentScene = SceneA,
fromScene = SceneA,
@@ -434,8 +432,8 @@
private fun TestGestureScope.navigateToSceneC() {
assertIdle(currentScene = SceneA)
- onDragStarted(overSlop = down(fractionOfScreen = 1f))
- onDragStopped(velocity = 0f)
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 1f))
+ dragController.onDragStopped(velocity = 0f)
advanceUntilIdle()
assertIdle(currentScene = SceneC)
}
@@ -443,7 +441,7 @@
@Test
fun onAccelaratedScroll_scrollToThirdScene() = runGestureTest {
// Drag A -> B with progress 0.2
- onDragStarted(overSlop = up(fractionOfScreen = 0.2f))
+ val dragController1 = onDragStarted(overSlop = up(fractionOfScreen = 0.2f))
assertTransition(
currentScene = SceneA,
fromScene = SceneA,
@@ -452,13 +450,13 @@
)
// Start animation A -> B with progress 0.2 -> 1.0
- onDragStopped(velocity = -velocityThreshold)
+ dragController1.onDragStopped(velocity = -velocityThreshold)
assertTransition(currentScene = SceneB, fromScene = SceneA, toScene = SceneB)
// While at A -> B do a 100% screen drag (progress 1.2). This should go past B and change
// the transition to B -> C with progress 0.2
- onDragStartedImmediately()
- onDelta(pixels = up(fractionOfScreen = 1f))
+ val dragController2 = onDragStartedImmediately()
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 1f))
assertTransition(
currentScene = SceneB,
fromScene = SceneB,
@@ -467,7 +465,7 @@
)
// After the drag stopped scene C should be committed
- onDragStopped(velocity = -velocityThreshold)
+ dragController2.onDragStopped(velocity = -velocityThreshold)
assertTransition(currentScene = SceneC, fromScene = SceneB, toScene = SceneC)
// wait for the stop animation
@@ -477,9 +475,9 @@
@Test
fun onAccelaratedScrollBothTargetsBecomeNull_settlesToIdle() = runGestureTest {
- onDragStarted(overSlop = up(fractionOfScreen = 0.2f))
- onDelta(pixels = up(fractionOfScreen = 0.2f))
- onDragStopped(velocity = -velocityThreshold)
+ val dragController1 = onDragStarted(overSlop = up(fractionOfScreen = 0.2f))
+ dragController1.onDragDelta(pixels = up(fractionOfScreen = 0.2f))
+ dragController1.onDragStopped(velocity = -velocityThreshold)
assertTransition(currentScene = SceneB, fromScene = SceneA, toScene = SceneB)
mutableUserActionsA.remove(Swipe.Up)
@@ -488,34 +486,34 @@
mutableUserActionsB.remove(Swipe.Down)
// start accelaratedScroll and scroll over to B -> null
- onDragStartedImmediately()
- onDelta(pixels = up(fractionOfScreen = 0.5f))
- onDelta(pixels = up(fractionOfScreen = 0.5f))
+ val dragController2 = onDragStartedImmediately()
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f))
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f))
// here onDragStopped is already triggered, but subsequent onDelta/onDragStopped calls may
// still be called. Make sure that they don't crash or change the scene
- onDelta(pixels = up(fractionOfScreen = 0.5f))
- onDragStopped(velocity = 0f)
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f))
+ dragController2.onDragStopped(velocity = 0f)
advanceUntilIdle()
assertIdle(SceneB)
// These events can still come in after the animation has settled
- onDelta(pixels = up(fractionOfScreen = 0.5f))
- onDragStopped(velocity = 0f)
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.5f))
+ dragController2.onDragStopped(velocity = 0f)
assertIdle(SceneB)
}
@Test
fun onDragTargetsChanged_targetStaysTheSame() = runGestureTest {
- onDragStarted(overSlop = up(fractionOfScreen = 0.1f))
+ val dragController1 = onDragStarted(overSlop = up(fractionOfScreen = 0.1f))
assertTransition(fromScene = SceneA, toScene = SceneB, progress = 0.1f)
mutableUserActionsA[Swipe.Up] = UserActionResult(SceneC)
- onDelta(pixels = up(fractionOfScreen = 0.1f))
+ dragController1.onDragDelta(pixels = up(fractionOfScreen = 0.1f))
// target stays B even though UserActions changed
assertTransition(fromScene = SceneA, toScene = SceneB, progress = 0.2f)
- onDragStopped(velocity = down(fractionOfScreen = 0.1f))
+ dragController1.onDragStopped(velocity = down(fractionOfScreen = 0.1f))
advanceUntilIdle()
// now target changed to C for new drag
@@ -525,25 +523,26 @@
@Test
fun onDragTargetsChanged_targetsChangeWhenStartingNewDrag() = runGestureTest {
- onDragStarted(overSlop = up(fractionOfScreen = 0.1f))
+ val dragController1 = onDragStarted(overSlop = up(fractionOfScreen = 0.1f))
assertTransition(fromScene = SceneA, toScene = SceneB, progress = 0.1f)
mutableUserActionsA[Swipe.Up] = UserActionResult(SceneC)
- onDelta(pixels = up(fractionOfScreen = 0.1f))
- onDragStopped(velocity = down(fractionOfScreen = 0.1f))
+ dragController1.onDragDelta(pixels = up(fractionOfScreen = 0.1f))
+ dragController1.onDragStopped(velocity = down(fractionOfScreen = 0.1f))
// now target changed to C for new drag that started before previous drag settled to Idle
- onDragStartedImmediately()
- onDelta(pixels = up(fractionOfScreen = 0.1f))
+ val dragController2 = onDragStartedImmediately()
+ dragController2.onDragDelta(pixels = up(fractionOfScreen = 0.1f))
assertTransition(fromScene = SceneA, toScene = SceneC, progress = 0.3f)
}
@Test
fun startGestureDuringAnimatingOffset_shouldImmediatelyStopTheAnimation() = runGestureTest {
- onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
+ val dragController = onDragStarted(overSlop = down(fractionOfScreen = 0.1f))
assertTransition(currentScene = SceneA)
- onDragStopped(velocity = velocityThreshold)
+ dragController.onDragStopped(velocity = velocityThreshold)
+ runCurrent()
assertTransition(currentScene = SceneC)
assertThat(isUserInputOngoing).isFalse()
@@ -632,7 +631,7 @@
// stop scene transition (start the "stop animation")
nestedScroll.preFling(available = Velocity.Zero)
- // a pre scroll event, that could be intercepted by SceneGestureHandler
+ // a pre scroll event, that could be intercepted by DraggableHandlerImpl
nestedScroll.onPreScroll(
available = Offset(0f, secondScroll),
source = NestedScrollSource.Drag
@@ -801,18 +800,6 @@
}
@Test
- fun beforeDraggableStart_drag_shouldBeIgnored() = runGestureTest {
- onDelta(pixels = down(fractionOfScreen = 0.1f))
- assertIdle(currentScene = SceneA)
- }
-
- @Test
- fun beforeDraggableStart_stop_shouldBeIgnored() = runGestureTest {
- onDragStopped(velocity = velocityThreshold)
- assertIdle(currentScene = SceneA)
- }
-
- @Test
fun beforeNestedScrollStart_stop_shouldBeIgnored() = runGestureTest {
val nestedScroll = nestedScrollConnection(nestedScrollBehavior = EdgeWithPreview)
nestedScroll.preFling(available = Velocity(0f, velocityThreshold))
@@ -826,7 +813,7 @@
val offsetY10 = downOffset(fractionOfScreen = 0.1f)
// Start a drag and then stop it, given that
- onDragStarted(overSlop = up(0.1f))
+ val dragController = onDragStarted(overSlop = up(0.1f))
assertTransition(currentScene = SceneA)
assertThat(progress).isEqualTo(0.1f)
@@ -836,7 +823,7 @@
assertThat(progress).isEqualTo(0.2f)
// this should be ignored, we are scrolling now!
- onDragStopped(-velocityThreshold)
+ dragController.onDragStopped(-velocityThreshold)
assertTransition(currentScene = SceneA)
nestedScroll.scroll(available = -offsetY10)
@@ -865,6 +852,7 @@
currentScene = SceneC,
fromScene = SceneC,
toScene = SceneB,
+ progress = 0.1f,
isUserInputOngoing = true,
)
@@ -873,18 +861,25 @@
// During the current gesture, start a new gesture, still in the middle of the screen. We
// should intercept it. Because it is intercepted, the overSlop passed to onDragStarted()
// should be 0f.
- assertThat(sceneGestureHandler.shouldImmediatelyIntercept(middle)).isTrue()
+ assertThat(draggableHandler.shouldImmediatelyIntercept(middle)).isTrue()
onDragStartedImmediately(startedPosition = middle)
// We should have intercepted the transition, so the transition should be the same object.
- assertTransition(currentScene = SceneC, fromScene = SceneC, toScene = SceneB)
- assertThat(transitionState).isSameInstanceAs(firstTransition)
+ assertTransition(
+ currentScene = SceneC,
+ fromScene = SceneC,
+ toScene = SceneB,
+ progress = 0.1f,
+ isUserInputOngoing = true,
+ )
+ // We should have a new transition
+ assertThat(transitionState).isNotSameInstanceAs(firstTransition)
// Start a new gesture from the bottom of the screen. Because swiping up from the bottom of
// C leads to scene A (and not B), the previous transitions is *not* intercepted and we
// instead animate from C to A.
val bottom = Offset(SCREEN_SIZE / 2, SCREEN_SIZE)
- assertThat(sceneGestureHandler.shouldImmediatelyIntercept(bottom)).isFalse()
+ assertThat(draggableHandler.shouldImmediatelyIntercept(bottom)).isFalse()
onDragStarted(startedPosition = bottom, overSlop = up(0.1f))
assertTransition(
@@ -901,12 +896,12 @@
assertIdle(SceneA)
// Swipe up to scene B.
- onDragStarted(overSlop = up(0.1f))
+ val dragController = onDragStarted(overSlop = up(0.1f))
assertTransition(currentScene = SceneA, fromScene = SceneA, toScene = SceneB)
// Block the transition when the user release their finger.
canChangeScene = { false }
- onDragStopped(velocity = -velocityThreshold)
+ dragController.onDragStopped(velocity = -velocityThreshold)
advanceUntilIdle()
assertIdle(SceneA)
}
@@ -916,18 +911,18 @@
assertIdle(SceneA)
// Swipe up to B.
- onDragStarted(overSlop = up(0.1f))
+ val dragController1 = onDragStarted(overSlop = up(0.1f))
assertTransition(currentScene = SceneA, fromScene = SceneA, toScene = SceneB)
- onDragStopped(velocity = -velocityThreshold)
+ dragController1.onDragStopped(velocity = -velocityThreshold)
assertTransition(currentScene = SceneB, fromScene = SceneA, toScene = SceneB)
// Intercept the transition and swipe down back to scene A.
- assertThat(sceneGestureHandler.shouldImmediatelyIntercept(startedPosition = null)).isTrue()
- onDragStartedImmediately()
+ assertThat(draggableHandler.shouldImmediatelyIntercept(startedPosition = null)).isTrue()
+ val dragController2 = onDragStartedImmediately()
// Block the transition when the user release their finger.
canChangeScene = { false }
- onDragStopped(velocity = velocityThreshold)
+ dragController2.onDragStopped(velocity = velocityThreshold)
advanceUntilIdle()
assertIdle(SceneB)
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/MultiPointerDraggableTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/MultiPointerDraggableTest.kt
index cd99d05..d8cf1c1 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/MultiPointerDraggableTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/MultiPointerDraggableTest.kt
@@ -59,9 +59,18 @@
orientation = Orientation.Vertical,
enabled = { enabled },
startDragImmediately = { false },
- onDragStarted = { _, _, _ -> started = true },
- onDragDelta = { _ -> dragged = true },
- onDragStopped = { stopped = true },
+ onDragStarted = { _, _, _ ->
+ started = true
+ object : DragController {
+ override fun onDrag(delta: Float) {
+ dragged = true
+ }
+
+ override fun onStop(velocity: Float, canChangeScene: Boolean) {
+ stopped = true
+ }
+ }
+ },
)
)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
index 5034631..92eb8f8 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
@@ -30,6 +30,7 @@
import android.view.Surface
import android.view.Surface.Rotation
import android.view.View
+import android.view.ViewGroup
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -46,7 +47,12 @@
import com.android.systemui.bouncer.domain.interactor.PrimaryBouncerInteractor
import com.android.systemui.classifier.FalsingCollector
import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.domain.interactor.FromAodTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.FromLockscreenTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.FromPrimaryBouncerTransitionInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.power.data.repository.FakePowerRepository
import com.android.systemui.power.domain.interactor.PowerInteractor
@@ -127,7 +133,8 @@
@Mock private lateinit var defaultUdfpsTouchOverlayViewModel: DefaultUdfpsTouchOverlayViewModel
@Mock
private lateinit var udfpsKeyguardAccessibilityDelegate: UdfpsKeyguardAccessibilityDelegate
- @Mock private lateinit var keyguardTransitionInteractor: KeyguardTransitionInteractor
+ private lateinit var keyguardTransitionRepository: FakeKeyguardTransitionRepository
+ private lateinit var keyguardTransitionInteractor: KeyguardTransitionInteractor
@Mock private lateinit var shadeInteractor: ShadeInteractor
@Captor private lateinit var layoutParamsCaptor: ArgumentCaptor<WindowManager.LayoutParams>
@Mock private lateinit var udfpsOverlayInteractor: UdfpsOverlayInteractor
@@ -150,6 +157,19 @@
mock(ScreenOffAnimationController::class.java),
statusBarStateController,
)
+ keyguardTransitionRepository = FakeKeyguardTransitionRepository()
+ keyguardTransitionInteractor =
+ KeyguardTransitionInteractor(
+ scope = testScope.backgroundScope,
+ repository = keyguardTransitionRepository,
+ fromLockscreenTransitionInteractor = {
+ mock(FromLockscreenTransitionInteractor::class.java)
+ },
+ fromPrimaryBouncerTransitionInteractor = {
+ mock(FromPrimaryBouncerTransitionInteractor::class.java)
+ },
+ fromAodTransitionInteractor = { mock(FromAodTransitionInteractor::class.java) },
+ )
whenever(inflater.inflate(R.layout.udfps_view, null, false)).thenReturn(udfpsView)
whenever(inflater.inflate(R.layout.udfps_bp_view, null))
.thenReturn(mock(UdfpsBpView::class.java))
@@ -159,11 +179,25 @@
.thenReturn(mock(UdfpsFpmEmptyView::class.java))
}
+ private suspend fun withReasonSuspend(
+ @RequestReason reason: Int,
+ isDebuggable: Boolean = false,
+ enableDeviceEntryUdfpsRefactor: Boolean = false,
+ block: suspend () -> Unit,
+ ) {
+ withReason(
+ reason,
+ isDebuggable,
+ enableDeviceEntryUdfpsRefactor,
+ )
+ block()
+ }
+
private fun withReason(
@RequestReason reason: Int,
isDebuggable: Boolean = false,
enableDeviceEntryUdfpsRefactor: Boolean = false,
- block: () -> Unit,
+ block: () -> Unit = {},
) {
if (enableDeviceEntryUdfpsRefactor) {
mSetFlagsRule.enableFlags(Flags.FLAG_DEVICE_ENTRY_UDFPS_REFACTOR)
@@ -312,6 +346,7 @@
lastWakeReason = WakeSleepReason.POWER_BUTTON,
lastSleepReason = WakeSleepReason.OTHER,
)
+ runCurrent()
controllerOverlay.show(udfpsController, overlayParams)
runCurrent()
verify(windowManager).addView(any(), any())
@@ -321,15 +356,25 @@
@Test
fun showUdfpsOverlay_whileGoingToSleep() =
testScope.runTest {
- withReason(REASON_AUTH_KEYGUARD) {
+ withReasonSuspend(REASON_AUTH_KEYGUARD) {
mSetFlagsRule.enableFlags(Flags.FLAG_UDFPS_VIEW_PERFORMANCE)
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.OFF,
+ to = KeyguardState.GONE,
+ testScope = this,
+ )
powerRepository.updateWakefulness(
rawState = WakefulnessState.STARTING_TO_SLEEP,
lastWakeReason = WakeSleepReason.POWER_BUTTON,
lastSleepReason = WakeSleepReason.OTHER,
)
+ runCurrent()
+
+ // WHEN a request comes to show the view
controllerOverlay.show(udfpsController, overlayParams)
runCurrent()
+
+ // THEN the view does not get added immediately
verify(windowManager, never()).addView(any(), any())
// we hide to end the job that listens for the finishedGoingToSleep signal
@@ -338,25 +383,82 @@
}
@Test
- fun showUdfpsOverlay_afterFinishedGoingToSleep() =
+ fun showUdfpsOverlay_whileAsleep() =
testScope.runTest {
- withReason(REASON_AUTH_KEYGUARD) {
+ withReasonSuspend(REASON_AUTH_KEYGUARD) {
mSetFlagsRule.enableFlags(Flags.FLAG_UDFPS_VIEW_PERFORMANCE)
- powerRepository.updateWakefulness(
- rawState = WakefulnessState.STARTING_TO_SLEEP,
- lastWakeReason = WakeSleepReason.POWER_BUTTON,
- lastSleepReason = WakeSleepReason.OTHER,
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.OFF,
+ to = KeyguardState.GONE,
+ testScope = this,
)
- controllerOverlay.show(udfpsController, overlayParams)
- runCurrent()
- verify(windowManager, never()).addView(any(), any())
-
powerRepository.updateWakefulness(
rawState = WakefulnessState.ASLEEP,
lastWakeReason = WakeSleepReason.POWER_BUTTON,
lastSleepReason = WakeSleepReason.OTHER,
)
runCurrent()
+
+ // WHEN a request comes to show the view
+ controllerOverlay.show(udfpsController, overlayParams)
+ runCurrent()
+
+ // THEN view isn't added yet
+ verify(windowManager, never()).addView(any(), any())
+
+ // we hide to end the job that listens for the finishedGoingToSleep signal
+ controllerOverlay.hide()
+ }
+ }
+
+ @Test
+ fun neverRemoveViewThatHasNotBeenAdded() =
+ testScope.runTest {
+ withReasonSuspend(REASON_AUTH_KEYGUARD) {
+ mSetFlagsRule.enableFlags(Flags.FLAG_UDFPS_VIEW_PERFORMANCE)
+ controllerOverlay.show(udfpsController, overlayParams)
+ val view = controllerOverlay.getTouchOverlay()
+ view?.let {
+ // parent is null, signalling that the view was never added
+ whenever(view.parent).thenReturn(null)
+ }
+ verify(windowManager, never()).removeView(eq(view))
+ }
+ }
+
+ @Test
+ fun showUdfpsOverlay_afterFinishedTransitioningToAOD() =
+ testScope.runTest {
+ withReasonSuspend(REASON_AUTH_KEYGUARD) {
+ mSetFlagsRule.enableFlags(Flags.FLAG_UDFPS_VIEW_PERFORMANCE)
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.OFF,
+ to = KeyguardState.GONE,
+ testScope = this,
+ )
+ powerRepository.updateWakefulness(
+ rawState = WakefulnessState.STARTING_TO_SLEEP,
+ lastWakeReason = WakeSleepReason.POWER_BUTTON,
+ lastSleepReason = WakeSleepReason.OTHER,
+ )
+ runCurrent()
+
+ // WHEN a request comes to show the view
+ controllerOverlay.show(udfpsController, overlayParams)
+ runCurrent()
+
+ // THEN the view does not get added immediately
+ verify(windowManager, never()).addView(any(), any())
+
+ // WHEN the device finishes transitioning to AOD
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ testScope = this,
+ )
+ runCurrent()
+
+ // THEN the view gets added
verify(windowManager)
.addView(eq(controllerOverlay.getTouchOverlay()), layoutParamsCaptor.capture())
}
@@ -387,6 +489,7 @@
private fun hideUdfpsOverlay() {
val didShow = controllerOverlay.show(udfpsController, overlayParams)
val view = controllerOverlay.getTouchOverlay()
+ view?.let { whenever(view.parent).thenReturn(mock(ViewGroup::class.java)) }
val didHide = controllerOverlay.hide()
verify(windowManager).removeView(eq(view))
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerTest.java
index 561cdbb..9b0b5de 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/UdfpsControllerTest.java
@@ -63,6 +63,7 @@
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
+import android.view.ViewGroup;
import android.view.ViewRootImpl;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
@@ -234,6 +235,8 @@
private ArgumentCaptor<IUdfpsOverlayController> mOverlayCaptor;
private IUdfpsOverlayController mOverlayController;
@Captor
+ private ArgumentCaptor<View> mViewCaptor;
+ @Captor
private ArgumentCaptor<UdfpsView.OnTouchListener> mTouchListenerCaptor;
@Captor
private ArgumentCaptor<View.OnHoverListener> mHoverListenerCaptor;
@@ -550,8 +553,11 @@
mOpticalProps.sensorId,
BiometricRequestConstants.REASON_ENROLL_ENROLLING,
mUdfpsOverlayControllerCallback);
+
mFgExecutor.runAllReady();
- verify(mWindowManager).addView(any(), any());
+ verify(mWindowManager).addView(mViewCaptor.capture(), any());
+ when(mViewCaptor.getValue().getParent())
+ .thenReturn(mock(ViewGroup.class));
// Update overlay parameters.
reset(mWindowManager);
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt
index cd29652..6e3573b 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt
@@ -27,6 +27,7 @@
import androidx.test.filters.SmallTest
import com.android.systemui.Flags.FLAG_COMMUNAL_HUB
import com.android.systemui.SysuiTestCase
+import com.android.systemui.communal.data.repository.CommunalSettingsRepositoryImpl
import com.android.systemui.communal.data.repository.FakeCommunalMediaRepository
import com.android.systemui.communal.data.repository.FakeCommunalPrefsRepository
import com.android.systemui.communal.data.repository.FakeCommunalRepository
@@ -62,6 +63,7 @@
import com.android.systemui.user.data.repository.fakeUserRepository
import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.settings.fakeSettings
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
@@ -831,6 +833,95 @@
}
}
+ @Test
+ fun widgetContent_containsDisabledWidgets_whenCategoryNotAllowed() =
+ testScope.runTest {
+ // Communal available, and tutorial completed.
+ keyguardRepository.setKeyguardShowing(true)
+ keyguardRepository.setKeyguardOccluded(false)
+ tutorialRepository.setTutorialSettingState(HUB_MODE_TUTORIAL_COMPLETED)
+ userRepository.setSelectedUserInfo(mainUser)
+
+ val userInfos = listOf(MAIN_USER_INFO, USER_INFO_WORK)
+ userRepository.setUserInfos(userInfos)
+ userTracker.set(
+ userInfos = userInfos,
+ selectedUserIndex = 0,
+ )
+ runCurrent()
+
+ // Widgets available.
+ val widget1 =
+ createWidgetWithCategory(1, AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN)
+ val widget2 =
+ createWidgetWithCategory(2, AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD)
+ val widget3 =
+ createWidgetWithCategory(3, AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX)
+ val widgets = listOf(widget1, widget2, widget3)
+ widgetRepository.setCommunalWidgets(widgets)
+
+ val widgetContent by collectLastValue(underTest.widgetContent)
+ kosmos.fakeSettings.putIntForUser(
+ CommunalSettingsRepositoryImpl.GLANCEABLE_HUB_CONTENT_SETTING,
+ AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD,
+ mainUser.id
+ )
+ runCurrent()
+
+ // Only the keyguard widget is enabled.
+ assertThat(widgetContent).hasSize(3)
+ assertThat(widgetContent!!.get(0))
+ .isInstanceOf(CommunalContentModel.WidgetContent.DisabledWidget::class.java)
+ assertThat(widgetContent!!.get(1))
+ .isInstanceOf(CommunalContentModel.WidgetContent.Widget::class.java)
+ assertThat(widgetContent!!.get(2))
+ .isInstanceOf(CommunalContentModel.WidgetContent.DisabledWidget::class.java)
+ }
+
+ @Test
+ fun widgetContent_allEnabled_whenCategoryAllowed() =
+ testScope.runTest {
+ // Communal available, and tutorial completed.
+ keyguardRepository.setKeyguardShowing(true)
+ keyguardRepository.setKeyguardOccluded(false)
+ tutorialRepository.setTutorialSettingState(HUB_MODE_TUTORIAL_COMPLETED)
+ userRepository.setSelectedUserInfo(mainUser)
+
+ val userInfos = listOf(MAIN_USER_INFO, USER_INFO_WORK)
+ userRepository.setUserInfos(userInfos)
+ userTracker.set(
+ userInfos = userInfos,
+ selectedUserIndex = 0,
+ )
+ runCurrent()
+
+ // Widgets available.
+ val widget1 =
+ createWidgetWithCategory(1, AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN)
+ val widget2 =
+ createWidgetWithCategory(2, AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD)
+ val widget3 =
+ createWidgetWithCategory(3, AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD)
+ val widgets = listOf(widget1, widget2, widget3)
+ widgetRepository.setCommunalWidgets(widgets)
+
+ val widgetContent by collectLastValue(underTest.widgetContent)
+ kosmos.fakeSettings.putIntForUser(
+ CommunalSettingsRepositoryImpl.GLANCEABLE_HUB_CONTENT_SETTING,
+ AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD or
+ AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN,
+ mainUser.id
+ )
+ runCurrent()
+
+ // All widgets are enabled.
+ assertThat(widgetContent).hasSize(3)
+ widgetContent!!.forEach { model ->
+ assertThat(model)
+ .isInstanceOf(CommunalContentModel.WidgetContent.Widget::class.java)
+ }
+ }
+
private fun smartspaceTimer(id: String, timestamp: Long = 0L): SmartspaceTarget {
val timer = mock(SmartspaceTarget::class.java)
whenever(timer.smartspaceTargetId).thenReturn(id)
@@ -848,6 +939,17 @@
whenever(this.providerInfo).thenReturn(providerInfo)
}
+ private fun createWidgetWithCategory(
+ appWidgetId: Int,
+ category: Int
+ ): CommunalWidgetContentModel =
+ mock<CommunalWidgetContentModel> {
+ whenever(this.appWidgetId).thenReturn(appWidgetId)
+ val providerInfo = mock<AppWidgetProviderInfo>().apply { widgetCategory = category }
+ whenever(providerInfo.profile).thenReturn(UserHandle(MAIN_USER_INFO.id))
+ whenever(this.providerInfo).thenReturn(providerInfo)
+ }
+
private companion object {
val MAIN_USER_INFO = UserInfo(0, "primary", UserInfo.FLAG_MAIN)
val USER_INFO_WORK = UserInfo(10, "work", UserInfo.FLAG_PROFILE)
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 5ee88cb..8e2e947 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
@@ -135,9 +135,9 @@
// Only Widgets and CTA tile are shown.
assertThat(communalContent?.size).isEqualTo(3)
assertThat(communalContent?.get(0))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(1))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(2))
.isInstanceOf(CommunalContentModel.CtaTileInEditMode::class.java)
}
@@ -181,9 +181,9 @@
// Widgets and CTA tile are shown.
assertThat(communalContent?.size).isEqualTo(3)
assertThat(communalContent?.get(0))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(1))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(2))
.isInstanceOf(CommunalContentModel.CtaTileInEditMode::class.java)
@@ -192,7 +192,8 @@
// Only one widget and CTA tile remain.
assertThat(communalContent?.size).isEqualTo(2)
val item = communalContent?.get(0)
- val appWidgetId = if (item is CommunalContentModel.Widget) item.appWidgetId else null
+ val appWidgetId =
+ if (item is CommunalContentModel.WidgetContent) item.appWidgetId else null
assertThat(appWidgetId).isEqualTo(widgets.get(1).appWidgetId)
assertThat(communalContent?.get(1))
.isInstanceOf(CommunalContentModel.CtaTileInEditMode::class.java)
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 1e523dd..563aad1 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
@@ -184,9 +184,9 @@
.isInstanceOf(CommunalContentModel.Smartspace::class.java)
assertThat(communalContent?.get(1)).isInstanceOf(CommunalContentModel.Umo::class.java)
assertThat(communalContent?.get(2))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(3))
- .isInstanceOf(CommunalContentModel.Widget::class.java)
+ .isInstanceOf(CommunalContentModel.WidgetContent::class.java)
assertThat(communalContent?.get(4))
.isInstanceOf(CommunalContentModel.CtaTileInViewMode::class.java)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
index b611e0a..36919d0 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
@@ -1052,32 +1052,6 @@
biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(true)
faceAuthenticateIsCalled()
}
- @Test
- fun authFailedCallAfterAuthLockedOutErrorShouldBeIgnored() =
- testScope.runTest {
- initCollectors()
- allPreconditionsToRunFaceAuthAreTrue()
- runCurrent()
- assertThat(canFaceAuthRun()).isTrue()
-
- underTest.requestAuthenticate(FACE_AUTH_TRIGGERED_NOTIFICATION_PANEL_CLICKED, false)
- runCurrent()
-
- faceAuthenticateIsCalled()
- authenticationCallback.value.onAuthenticationError(
- FACE_ERROR_LOCKOUT_PERMANENT,
- "Too many attempts, face not available"
- )
-
- val lockoutError = authStatus() as ErrorFaceAuthenticationStatus
- assertThat(lockedOut()).isTrue()
- assertThat(lockoutError.isLockoutError()).isTrue()
-
- authenticationCallback.value.onAuthenticationFailed()
- runCurrent()
-
- assertThat(authStatus()).isEqualTo(lockoutError)
- }
private suspend fun TestScope.testGatingCheckForFaceAuth(
gatingCheckModifier: suspend () -> Unit
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTest.kt
index 3484025..cd4db2f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTest.kt
@@ -79,34 +79,66 @@
}
@Test
- fun dozeAmountTransitionTest() = runTest {
- val dozeAmountSteps by collectValues(underTest.dozeAmountTransition)
+ fun dozeAmountTransitionTest_AodToFromLockscreen() =
+ testScope.runTest {
+ val dozeAmountSteps by collectValues(underTest.dozeAmountTransition)
- val steps = mutableListOf<TransitionStep>()
+ val steps = mutableListOf<TransitionStep>()
- steps.add(TransitionStep(AOD, LOCKSCREEN, 0f, STARTED))
- steps.add(TransitionStep(AOD, LOCKSCREEN, 0.5f, RUNNING))
- steps.add(TransitionStep(AOD, LOCKSCREEN, 1f, FINISHED))
- steps.add(TransitionStep(LOCKSCREEN, AOD, 0f, STARTED))
- steps.add(TransitionStep(LOCKSCREEN, AOD, 0.8f, RUNNING))
- steps.add(TransitionStep(LOCKSCREEN, AOD, 0.9f, RUNNING))
- steps.add(TransitionStep(LOCKSCREEN, AOD, 1f, FINISHED))
+ steps.add(TransitionStep(AOD, LOCKSCREEN, 0f, STARTED))
+ steps.add(TransitionStep(AOD, LOCKSCREEN, 0.5f, RUNNING))
+ steps.add(TransitionStep(AOD, LOCKSCREEN, 1f, FINISHED))
+ steps.add(TransitionStep(LOCKSCREEN, AOD, 0f, STARTED))
+ steps.add(TransitionStep(LOCKSCREEN, AOD, 0.8f, RUNNING))
+ steps.add(TransitionStep(LOCKSCREEN, AOD, 0.9f, RUNNING))
+ steps.add(TransitionStep(LOCKSCREEN, AOD, 1f, FINISHED))
- steps.forEach {
- repository.sendTransitionStep(it)
- runCurrent()
+ steps.forEach {
+ repository.sendTransitionStep(it)
+ runCurrent()
+ }
+
+ assertThat(dozeAmountSteps.subList(0, 3))
+ .isEqualTo(
+ listOf(
+ steps[0].copy(value = 1f - steps[0].value),
+ steps[1].copy(value = 1f - steps[1].value),
+ steps[2].copy(value = 1f - steps[2].value),
+ )
+ )
+ assertThat(dozeAmountSteps.subList(3, 7)).isEqualTo(steps.subList(3, 7))
}
- assertThat(dozeAmountSteps.subList(0, 3))
- .isEqualTo(
- listOf(
- steps[0].copy(value = 1f - steps[0].value),
- steps[1].copy(value = 1f - steps[1].value),
- steps[2].copy(value = 1f - steps[2].value),
+ @Test
+ fun dozeAmountTransitionTest_AodToFromGone() =
+ testScope.runTest {
+ val dozeAmountSteps by collectValues(underTest.dozeAmountTransition)
+
+ val steps = mutableListOf<TransitionStep>()
+
+ steps.add(TransitionStep(AOD, GONE, 0f, STARTED))
+ steps.add(TransitionStep(AOD, GONE, 0.3f, RUNNING))
+ steps.add(TransitionStep(AOD, GONE, 1f, FINISHED))
+ steps.add(TransitionStep(GONE, AOD, 0f, STARTED))
+ steps.add(TransitionStep(GONE, AOD, 0.1f, RUNNING))
+ steps.add(TransitionStep(GONE, AOD, 0.3f, RUNNING))
+ steps.add(TransitionStep(GONE, AOD, 1f, FINISHED))
+
+ steps.forEach {
+ repository.sendTransitionStep(it)
+ runCurrent()
+ }
+
+ assertThat(dozeAmountSteps.subList(0, 3))
+ .isEqualTo(
+ listOf(
+ steps[0].copy(value = 1f - steps[0].value),
+ steps[1].copy(value = 1f - steps[1].value),
+ steps[2].copy(value = 1f - steps[2].value),
+ )
)
- )
- assertThat(dozeAmountSteps.subList(3, 7)).isEqualTo(steps.subList(3, 7))
- }
+ assertThat(dozeAmountSteps.subList(3, 7)).isEqualTo(steps.subList(3, 7))
+ }
@Test
fun finishedKeyguardStateTests() =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/AodToGoneTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/AodToGoneTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/AodToGoneTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/AodToGoneTransitionViewModelTest.kt
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/AodToOccludedTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/AodToOccludedTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/AodToOccludedTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/AodToOccludedTransitionViewModelTest.kt
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/BouncerToGoneFlowsTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/BouncerToGoneFlowsTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/BouncerToGoneFlowsTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/BouncerToGoneFlowsTest.kt
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DozingToLockscreenTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DozingToLockscreenTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DozingToLockscreenTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DozingToLockscreenTransitionViewModelTest.kt
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
index 0b80ff8..ad1cef1 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
@@ -26,6 +26,7 @@
import com.android.systemui.keyguard.data.repository.fakeKeyguardClockRepository
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.testScope
+import com.android.systemui.res.R
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.whenever
import com.google.common.truth.Truth.assertThat
@@ -36,7 +37,6 @@
@SmallTest
@RunWith(AndroidJUnit4::class)
-@android.platform.test.annotations.EnabledOnRavenwood
class LockscreenContentViewModelTest : SysuiTestCase() {
private val kosmos: Kosmos = testKosmos()
@@ -47,6 +47,7 @@
fun setup() {
with(kosmos) {
fakeFeatureFlagsClassic.set(Flags.LOCK_SCREEN_LONG_PRESS_ENABLED, true)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
underTest = lockscreenContentViewModel
}
}
@@ -88,11 +89,21 @@
}
@Test
+ fun areNotificationsVisible_splitShadeTrue_true() =
+ with(kosmos) {
+ testScope.runTest {
+ overrideResource(R.bool.config_use_split_notification_shade, true)
+ kosmos.fakeKeyguardClockRepository.setClockSize(KeyguardClockSwitch.LARGE)
+
+ assertThat(underTest.areNotificationsVisible(context.resources)).isTrue()
+ }
+ }
+ @Test
fun areNotificationsVisible_withSmallClock_true() =
with(kosmos) {
testScope.runTest {
kosmos.fakeKeyguardClockRepository.setClockSize(KeyguardClockSwitch.SMALL)
- assertThat(underTest.areNotificationsVisible).isTrue()
+ assertThat(underTest.areNotificationsVisible(context.resources)).isTrue()
}
}
@@ -101,7 +112,7 @@
with(kosmos) {
testScope.runTest {
kosmos.fakeKeyguardClockRepository.setClockSize(KeyguardClockSwitch.LARGE)
- assertThat(underTest.areNotificationsVisible).isFalse()
+ assertThat(underTest.areNotificationsVisible(context.resources)).isFalse()
}
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt
similarity index 99%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt
index e139466..bef9515 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModelTest.kt
@@ -36,10 +36,10 @@
import com.android.systemui.testKosmos
import com.google.common.collect.Range
import com.google.common.truth.Truth.assertThat
-import kotlin.test.Test
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import org.junit.Test
import org.junit.runner.RunWith
@ExperimentalCoroutinesApi
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModelTest.kt
index 28f5eba..86b3f33 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModelTest.kt
@@ -102,6 +102,24 @@
values.forEach { assertThat(it).isEqualTo(0f) }
}
+
+ @Test
+ fun lockscreenAlphaFadesOutAndFinishesVisible() =
+ testScope.runTest {
+ val alpha by collectValues(underTest.lockscreenAlpha)
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.DOZING,
+ testScope,
+ )
+
+ assertThat(alpha[0]).isEqualTo(1f)
+ // Halfway through, it will have faded out
+ assertThat(alpha[1]).isEqualTo(0f)
+ // FINISHED alpha should be visible, to support pulsing
+ assertThat(alpha[2]).isEqualTo(1f)
+ }
+
@Test
fun deviceEntryBackgroundViewDisappear() =
testScope.runTest {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt
similarity index 99%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt
index 7a564ac..43ab93a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToPrimaryBouncerTransitionViewModelTest.kt
@@ -33,10 +33,10 @@
import com.android.systemui.testKosmos
import com.google.common.collect.Range
import com.google.common.truth.Truth
-import kotlin.test.Test
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import org.junit.Test
import org.junit.runner.RunWith
@ExperimentalCoroutinesApi
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToAodTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToAodTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToAodTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToAodTransitionViewModelTest.kt
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToAodTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToAodTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToAodTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToAodTransitionViewModelTest.kt
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModelTest.kt
index 47e1ee9..db1d5d9 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModelTest.kt
@@ -149,6 +149,42 @@
values.forEach { assertThat(it).isEqualTo(1f) }
}
+ @Test
+ fun notificationAlpha() =
+ testScope.runTest {
+ val values by collectValues(underTest.notificationAlpha)
+ runCurrent()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.PRIMARY_BOUNCER,
+ to = KeyguardState.GONE,
+ testScope,
+ )
+
+ assertThat(values[0]).isEqualTo(1f)
+ // Should fade to zero between here
+ assertThat(values[1]).isEqualTo(0f)
+ }
+
+ @Test
+ fun notificationAlpha_leaveShadeOpen() =
+ testScope.runTest {
+ val values by collectValues(underTest.notificationAlpha)
+ runCurrent()
+
+ sysuiStatusBarStateController.setLeaveOpenOnKeyguardHide(true)
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.PRIMARY_BOUNCER,
+ to = KeyguardState.GONE,
+ testScope,
+ )
+
+ assertThat(values.size).isEqualTo(2)
+ // Shade stays open, and alpha should remain visible
+ values.forEach { assertThat(it).isEqualTo(1f) }
+ }
+
private fun step(
value: Float,
state: TransitionState = TransitionState.RUNNING
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToLockscreenTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToLockscreenTransitionViewModelTest.kt
similarity index 100%
rename from packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToLockscreenTransitionViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToLockscreenTransitionViewModelTest.kt
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
index fff0a31..667f516 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
@@ -615,6 +615,7 @@
private fun TestScope.emulatePendingTransitionProgress(
expectedVisible: Boolean = true,
) {
+ val isVisible by collectLastValue(sceneContainerViewModel.isVisible)
assertWithMessage("The FakeSceneDataSource has to be paused for this to do anything.")
.that(fakeSceneDataSource.isPaused)
.isTrue()
@@ -651,7 +652,7 @@
runCurrent()
assertWithMessage("Visibility mismatch after scene transition from $from to $to!")
- .that(sceneContainerViewModel.isVisible.value)
+ .that(isVisible)
.isEqualTo(expectedVisible)
assertThat(sceneContainerViewModel.currentScene.value).isEqualTo(to)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
index dd3eb68..db94c39 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
package com.android.systemui.scene.domain.interactor
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -31,6 +33,7 @@
import com.android.systemui.scene.shared.model.fakeSceneDataSource
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runCurrent
@@ -275,4 +278,18 @@
underTest.setVisible(true, "reason")
assertThat(isVisible).isTrue()
}
+
+ @Test
+ fun isVisible_duringRemoteUserInteraction_forcedVisible() =
+ testScope.runTest {
+ underTest.setVisible(false, "reason")
+ val isVisible by collectLastValue(underTest.isVisible)
+ assertThat(isVisible).isFalse()
+ underTest.onRemoteUserInteractionStarted("reason")
+ assertThat(isVisible).isTrue()
+
+ underTest.onUserInteractionFinished()
+
+ assertThat(isVisible).isFalse()
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
index ffbdafe..27ae8b6 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
@@ -14,10 +14,9 @@
* limitations under the License.
*/
-@file:OptIn(ExperimentalCoroutinesApi::class)
-
package com.android.systemui.scene.ui.viewmodel
+import android.view.MotionEvent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
@@ -35,9 +34,9 @@
import com.android.systemui.scene.shared.model.fakeSceneDataSource
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.whenever
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
-import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
@@ -50,7 +49,7 @@
private val kosmos = testKosmos()
private val testScope by lazy { kosmos.testScope }
- private val interactor by lazy { kosmos.sceneInteractor }
+ private val sceneInteractor by lazy { kosmos.sceneInteractor }
private val fakeSceneDataSource = kosmos.fakeSceneDataSource
private val sceneContainerConfig = kosmos.sceneContainerConfig
private val falsingManager = kosmos.fakeFalsingManager
@@ -62,7 +61,7 @@
kosmos.fakeSceneContainerFlags.enabled = true
underTest =
SceneContainerViewModel(
- sceneInteractor = interactor,
+ sceneInteractor = sceneInteractor,
falsingInteractor = kosmos.falsingInteractor,
powerInteractor = kosmos.powerInteractor,
)
@@ -74,10 +73,10 @@
val isVisible by collectLastValue(underTest.isVisible)
assertThat(isVisible).isTrue()
- interactor.setVisible(false, "reason")
+ sceneInteractor.setVisible(false, "reason")
assertThat(isVisible).isFalse()
- interactor.setVisible(true, "reason")
+ sceneInteractor.setVisible(true, "reason")
assertThat(isVisible).isTrue()
}
@@ -199,4 +198,20 @@
underTest.onMotionEvent(mock())
assertThat(kosmos.fakePowerRepository.userTouchRegistered).isTrue()
}
+
+ @Test
+ fun remoteUserInteraction_keepsContainerVisible() =
+ testScope.runTest {
+ sceneInteractor.setVisible(false, "reason")
+ val isVisible by collectLastValue(underTest.isVisible)
+ assertThat(isVisible).isFalse()
+ sceneInteractor.onRemoteUserInteractionStarted("reason")
+ assertThat(isVisible).isTrue()
+
+ underTest.onMotionEvent(
+ mock { whenever(actionMasked).thenReturn(MotionEvent.ACTION_UP) }
+ )
+
+ assertThat(isVisible).isFalse()
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
index 0641c61..7f5a658 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
@@ -47,8 +47,6 @@
import com.android.systemui.shade.data.repository.shadeRepository
import com.android.systemui.shade.mockLargeScreenHeaderHelper
import com.android.systemui.statusbar.notification.stack.domain.interactor.sharedNotificationContainerInteractor
-import com.android.systemui.statusbar.policy.SplitShadeStateController
-import com.android.systemui.statusbar.policy.splitShadeStateController
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.whenever
@@ -68,7 +66,6 @@
@RunWith(AndroidJUnit4::class)
class SharedNotificationContainerViewModelTest : SysuiTestCase() {
val aodBurnInViewModel = mock(AodBurnInViewModel::class.java)
- val splitShadeStateController = mock(SplitShadeStateController::class.java)
lateinit var translationYFlow: MutableStateFlow<Float>
val kosmos =
@@ -81,7 +78,6 @@
init {
kosmos.aodBurnInViewModel = aodBurnInViewModel
- kosmos.splitShadeStateController = splitShadeStateController
}
val testScope = kosmos.testScope
val configurationRepository = kosmos.fakeConfigurationRepository
@@ -98,7 +94,7 @@
@Before
fun setUp() {
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any())).thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
translationYFlow = MutableStateFlow(0f)
whenever(aodBurnInViewModel.translationY(any())).thenReturn(translationYFlow)
underTest = kosmos.sharedNotificationContainerViewModel
@@ -107,8 +103,7 @@
@Test
fun validateMarginStartInSplitShade() =
testScope.runTest {
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(true)
+ overrideResource(R.bool.config_use_split_notification_shade, true)
overrideResource(R.dimen.notification_panel_margin_horizontal, 20)
val dimens by collectLastValue(underTest.configurationBasedDimensions)
@@ -121,8 +116,7 @@
@Test
fun validateMarginStart() =
testScope.runTest {
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
overrideResource(R.dimen.notification_panel_margin_horizontal, 20)
val dimens by collectLastValue(underTest.configurationBasedDimensions)
@@ -137,8 +131,7 @@
testScope.runTest {
mSetFlagsRule.disableFlags(FLAG_CENTRALIZED_STATUS_BAR_HEIGHT_FIX)
whenever(largeScreenHeaderHelper.getLargeScreenHeaderHeight()).thenReturn(5)
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(true)
+ overrideResource(R.bool.config_use_split_notification_shade, true)
overrideResource(R.bool.config_use_large_screen_shade_header, true)
overrideResource(R.dimen.large_screen_shade_header_height, 10)
overrideResource(R.dimen.keyguard_split_shade_top_margin, 50)
@@ -156,8 +149,7 @@
testScope.runTest {
mSetFlagsRule.enableFlags(FLAG_CENTRALIZED_STATUS_BAR_HEIGHT_FIX)
whenever(largeScreenHeaderHelper.getLargeScreenHeaderHeight()).thenReturn(5)
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(true)
+ overrideResource(R.bool.config_use_split_notification_shade, true)
overrideResource(R.bool.config_use_large_screen_shade_header, true)
overrideResource(R.dimen.large_screen_shade_header_height, 10)
overrideResource(R.dimen.keyguard_split_shade_top_margin, 50)
@@ -172,8 +164,7 @@
@Test
fun validatePaddingTop() =
testScope.runTest {
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
overrideResource(R.dimen.large_screen_shade_header_height, 10)
overrideResource(R.dimen.keyguard_split_shade_top_margin, 50)
@@ -431,8 +422,7 @@
val bounds by collectLastValue(underTest.bounds)
// When not in split shade
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
configurationRepository.onAnyConfigurationChange()
runCurrent()
@@ -454,8 +444,7 @@
// When in split shade
whenever(largeScreenHeaderHelper.getLargeScreenHeaderHeight()).thenReturn(5)
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(true)
+ overrideResource(R.bool.config_use_split_notification_shade, true)
overrideResource(R.bool.config_use_large_screen_shade_header, true)
overrideResource(R.dimen.large_screen_shade_header_height, 10)
overrideResource(R.dimen.keyguard_split_shade_top_margin, 50)
@@ -483,8 +472,7 @@
// When in split shade
whenever(largeScreenHeaderHelper.getLargeScreenHeaderHeight()).thenReturn(5)
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(true)
+ overrideResource(R.bool.config_use_split_notification_shade, true)
overrideResource(R.bool.config_use_large_screen_shade_header, true)
overrideResource(R.dimen.large_screen_shade_header_height, 10)
overrideResource(R.dimen.keyguard_split_shade_top_margin, 50)
@@ -543,8 +531,7 @@
showLockscreen()
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
configurationRepository.onAnyConfigurationChange()
keyguardInteractor.setNotificationContainerBounds(
NotificationContainerBounds(top = 1f, bottom = 2f)
@@ -567,8 +554,7 @@
showLockscreen()
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
configurationRepository.onAnyConfigurationChange()
keyguardInteractor.setNotificationContainerBounds(
NotificationContainerBounds(top = 1f, bottom = 2f)
@@ -604,8 +590,7 @@
// Show lockscreen with shade expanded
showLockscreenWithShadeExpanded()
- whenever(splitShadeStateController.shouldUseSplitNotificationShade(any()))
- .thenReturn(false)
+ overrideResource(R.bool.config_use_split_notification_shade, false)
configurationRepository.onAnyConfigurationChange()
keyguardInteractor.setNotificationContainerBounds(
NotificationContainerBounds(top = 1f, bottom = 2f)
@@ -701,6 +686,32 @@
assertThat(fadeIn).isEqualTo(false)
}
+ @Test
+ fun shadeCollapseFadeIn_doesNotRunIfTransitioningToAod() =
+ testScope.runTest {
+ val fadeIn by collectLastValue(underTest.shadeCollapseFadeIn)
+
+ // Start on lockscreen without the shade
+ underTest.setShadeCollapseFadeInComplete(false)
+ showLockscreen()
+ assertThat(fadeIn).isEqualTo(false)
+
+ // ... then the shade expands
+ showLockscreenWithShadeExpanded()
+ assertThat(fadeIn).isEqualTo(false)
+
+ // ... then user hits power to go to AOD
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.AOD,
+ testScope,
+ )
+ // ... followed by a shade collapse
+ showLockscreen()
+ // ... does not trigger a fade in
+ assertThat(fadeIn).isEqualTo(false)
+ }
+
private suspend fun TestScope.showLockscreen() {
shadeRepository.setLockscreenShadeExpansion(0f)
shadeRepository.setQsExpansion(0f)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
index 6456669..db4d42f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
@@ -53,6 +53,7 @@
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
+import com.android.systemui.statusbar.notification.shared.NotificationThrottleHun;
import com.android.systemui.util.concurrency.FakeExecutor;
import com.android.systemui.util.settings.FakeGlobalSettings;
import com.android.systemui.util.time.FakeSystemClock;
@@ -71,8 +72,6 @@
@Rule
public MockitoRule rule = MockitoJUnit.rule();
- private static final String TEST_PACKAGE_NAME = "BaseHeadsUpManagerTest";
-
static final int TEST_TOUCH_ACCEPTANCE_TIME = 200;
static final int TEST_A11Y_AUTO_DISMISS_TIME = 1_000;
@@ -80,8 +79,6 @@
private final HeadsUpManagerLogger mLogger = spy(new HeadsUpManagerLogger(logcatLogBuffer()));
@Mock private AccessibilityManagerWrapper mAccessibilityMgr;
- private static final int TEST_UID = 0;
-
protected static final int TEST_MINIMUM_DISPLAY_TIME = 400;
protected static final int TEST_AUTO_DISMISS_TIME = 600;
protected static final int TEST_STICKY_AUTO_DISMISS_TIME = 800;
@@ -146,6 +143,12 @@
}
}
+ @Override
+ public void SysuiSetup() throws Exception {
+ super.SysuiSetup();
+ mSetFlagsRule.disableFlags(NotificationThrottleHun.FLAG_NAME);
+ }
+
@Test
public void testShowNotification_addsEntry() {
final BaseHeadsUpManager alm = createHeadsUpManager();
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
index ec23f76..c032d7c 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
@@ -39,6 +39,7 @@
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.provider.VisualStabilityProvider;
import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager;
+import com.android.systemui.statusbar.notification.shared.NotificationThrottleHun;
import com.android.systemui.statusbar.phone.ConfigurationControllerImpl;
import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
@@ -136,6 +137,8 @@
@Before
public void setUp() {
+ mSetFlagsRule.disableFlags(NotificationThrottleHun.FLAG_NAME);
+
when(mShadeInteractor.isAnyExpanded()).thenReturn(StateFlowKt.MutableStateFlow(false));
final AccessibilityManagerWrapper accessibilityMgr =
mDependency.injectMockDependency(AccessibilityManagerWrapper.class);
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/util/wakelock/ClientTrackingWakeLockTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/util/wakelock/ClientTrackingWakeLockTest.kt
new file mode 100644
index 0000000..fdfcdc4
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/util/wakelock/ClientTrackingWakeLockTest.kt
@@ -0,0 +1,130 @@
+/*
+ * 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.util.wakelock
+
+import android.os.Build
+import android.os.PowerManager
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import org.junit.After
+import org.junit.Assert
+import org.junit.Assume
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class ClientTrackingWakeLockTest : SysuiTestCase() {
+
+ private val WHY = "test"
+ private val WHY_2 = "test2"
+
+ lateinit var mWakeLock: ClientTrackingWakeLock
+ lateinit var mInner: PowerManager.WakeLock
+
+ @Before
+ fun setUp() {
+ mInner =
+ WakeLock.createWakeLockInner(mContext, "WakeLockTest", PowerManager.PARTIAL_WAKE_LOCK)
+ mWakeLock = ClientTrackingWakeLock(mInner, null, 20000)
+ }
+
+ @After
+ fun tearDown() {
+ mInner.setReferenceCounted(false)
+ mInner.release()
+ }
+
+ @Test
+ fun createPartialInner_notHeldYet() {
+ Assert.assertFalse(mInner.isHeld)
+ }
+
+ @Test
+ fun wakeLock_acquire() {
+ mWakeLock.acquire(WHY)
+ Assert.assertTrue(mInner.isHeld)
+ }
+
+ @Test
+ fun wakeLock_release() {
+ mWakeLock.acquire(WHY)
+ mWakeLock.release(WHY)
+ Assert.assertFalse(mInner.isHeld)
+ }
+
+ @Test
+ fun wakeLock_acquiredReleasedMultipleSources_stillHeld() {
+ mWakeLock.acquire(WHY)
+ mWakeLock.acquire(WHY_2)
+ mWakeLock.release(WHY)
+
+ Assert.assertTrue(mInner.isHeld)
+ mWakeLock.release(WHY_2)
+ Assert.assertFalse(mInner.isHeld)
+ }
+
+ @Test
+ fun wakeLock_releasedTooManyTimes_stillReleased_noThrow() {
+ Assume.assumeFalse(Build.IS_ENG)
+ mWakeLock.acquire(WHY)
+ mWakeLock.acquire(WHY_2)
+ mWakeLock.release(WHY)
+ mWakeLock.release(WHY_2)
+ mWakeLock.release(WHY)
+ Assert.assertFalse(mInner.isHeld)
+ }
+
+ @Test
+ fun wakeLock_wrap() {
+ val ran = BooleanArray(1)
+ val wrapped = mWakeLock.wrap { ran[0] = true }
+ Assert.assertTrue(mInner.isHeld)
+ Assert.assertFalse(ran[0])
+ wrapped.run()
+ Assert.assertTrue(ran[0])
+ Assert.assertFalse(mInner.isHeld)
+ }
+
+ @Test
+ fun prodBuild_wakeLock_releaseWithoutAcquire_noThrow() {
+ Assume.assumeFalse(Build.IS_ENG)
+ // shouldn't throw an exception on production builds
+ mWakeLock.release(WHY)
+ }
+
+ @Test
+ fun acquireSeveralLocks_stringReportsCorrectCount() {
+ mWakeLock.acquire(WHY)
+ mWakeLock.acquire(WHY_2)
+ mWakeLock.acquire(WHY)
+ mWakeLock.acquire(WHY)
+ mWakeLock.acquire(WHY_2)
+ Assert.assertEquals(5, mWakeLock.activeClients())
+
+ mWakeLock.release(WHY_2)
+ mWakeLock.release(WHY_2)
+ Assert.assertEquals(3, mWakeLock.activeClients())
+
+ mWakeLock.release(WHY)
+ mWakeLock.release(WHY)
+ mWakeLock.release(WHY)
+ Assert.assertEquals(0, mWakeLock.activeClients())
+ }
+}
diff --git a/packages/SystemUI/res/drawable/battery_unified_attr_charging.xml b/packages/SystemUI/res/drawable/battery_unified_attr_charging.xml
new file mode 100644
index 0000000..8e3b89b
--- /dev/null
+++ b/packages/SystemUI/res/drawable/battery_unified_attr_charging.xml
@@ -0,0 +1,26 @@
+<?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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="8dp"
+ android:height="10dp"
+ android:viewportWidth="16.0"
+ android:viewportHeight="20.0">
+ <path
+ android:pathData="M4,20L5,13H0L9,0H11L10,8H16L6,20H4Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/battery_unified_attr_defend.xml b/packages/SystemUI/res/drawable/battery_unified_attr_defend.xml
new file mode 100644
index 0000000..e7beee2
--- /dev/null
+++ b/packages/SystemUI/res/drawable/battery_unified_attr_defend.xml
@@ -0,0 +1,26 @@
+<?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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="8dp"
+ android:height="9dp"
+ android:viewportWidth="8.0"
+ android:viewportHeight="9.0">
+ <path
+ android:pathData="M3.698,9C2.629,8.765 1.746,8.181 1.048,7.247C0.349,6.306 0,5.266 0,4.126V1.422L3.698,0L7.397,1.422V4.126C7.397,5.266 7.048,6.306 6.349,7.247C5.651,8.181 4.767,8.765 3.698,9ZM3.698,7.846C4.439,7.596 5.052,7.129 5.537,6.445C6.029,5.754 6.274,4.981 6.274,4.126V2.191L3.698,1.197L1.122,2.191V4.126C1.122,4.981 1.365,5.754 1.849,6.445C2.341,7.129 2.957,7.596 3.698,7.846ZM3.698,7.183C3.1,6.99 2.605,6.616 2.213,6.061C1.828,5.505 1.635,4.888 1.635,4.211V2.651L3.698,1.86L5.761,2.651V4.211C5.761,4.888 5.565,5.505 5.173,6.061C4.789,6.616 4.297,6.99 3.698,7.183Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/battery_unified_attr_powersave.xml b/packages/SystemUI/res/drawable/battery_unified_attr_powersave.xml
new file mode 100644
index 0000000..a2c0cbae
--- /dev/null
+++ b/packages/SystemUI/res/drawable/battery_unified_attr_powersave.xml
@@ -0,0 +1,32 @@
+<?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.
+ -->
+
+<!-- This drawable is inset for now until the unified battery attrs can get their own paddings -->
+<inset xmlns:android="http://schemas.android.com/apk/res/android"
+ android:insetRight="0.5dp"
+ >
+ <vector
+ android:width="8dp"
+ android:height="8dp"
+ android:viewportWidth="8.0"
+ android:viewportHeight="8.0"
+ >
+ <path
+ android:pathData="M3.242,4.758H0V3.257H3.242V0H4.758V3.257H8V4.758H4.758V8.015H3.242V4.758Z"
+ android:fillColor="#000"/>
+ </vector>
+</inset>
diff --git a/packages/SystemUI/res/drawable/battery_unified_frame.xml b/packages/SystemUI/res/drawable/battery_unified_frame.xml
new file mode 100644
index 0000000..016b88b
--- /dev/null
+++ b/packages/SystemUI/res/drawable/battery_unified_frame.xml
@@ -0,0 +1,34 @@
+<?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.
+ -->
+
+<!-- Unified battery frame for BatteryLayersDrawable.kt -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="14dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="14.0">
+ <!-- body -->
+ <path
+ android:pathData="@string/battery_unified_frame_path_string"
+ android:strokeColor="#000"
+ android:strokeWidth="1.5"
+ />
+ <!-- cap -->
+ <path
+ android:pathData="M0,4C0,3.448 0.448,3 1,3H1.5V11H1C0.448,11 0,10.552 0,10V4Z"
+ android:fillColor="#000"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/battery_unified_frame_bg.xml b/packages/SystemUI/res/drawable/battery_unified_frame_bg.xml
new file mode 100644
index 0000000..8e04f10
--- /dev/null
+++ b/packages/SystemUI/res/drawable/battery_unified_frame_bg.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.
+ -->
+
+<!-- Vector description of the battery gutter: the background of the fill -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="14dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="14.0">
+ <path
+ android:pathData="@string/battery_unified_frame_path_string"
+ android:fillColor="#fff" />
+</vector>
diff --git a/packages/SystemUI/res/layout/internet_connectivity_dialog.xml b/packages/SystemUI/res/layout/internet_connectivity_dialog.xml
index 1365a11..22d156d 100644
--- a/packages/SystemUI/res/layout/internet_connectivity_dialog.xml
+++ b/packages/SystemUI/res/layout/internet_connectivity_dialog.xml
@@ -263,8 +263,9 @@
android:layout_gravity="center_vertical|start">
<ImageView
android:id="@+id/wifi_connected_icon"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:scaleType="fitCenter"
android:layout_gravity="center"/>
</FrameLayout>
diff --git a/packages/SystemUI/res/layout/internet_list_item.xml b/packages/SystemUI/res/layout/internet_list_item.xml
index f6a2136..0da0f2b 100644
--- a/packages/SystemUI/res/layout/internet_list_item.xml
+++ b/packages/SystemUI/res/layout/internet_list_item.xml
@@ -35,8 +35,9 @@
android:layout_gravity="center_vertical|start">
<ImageView
android:id="@+id/wifi_icon"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:scaleType="fitCenter"
android:layout_gravity="center"/>
</FrameLayout>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 32b1cad..b7eff38 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -164,6 +164,9 @@
so the width of the icon should be 13.0sp * (12.0 / 20.0) -->
<dimen name="status_bar_battery_icon_width">7.8sp</dimen>
+ <dimen name="status_bar_battery_unified_icon_width">24sp</dimen>
+ <dimen name="status_bar_battery_unified_icon_height">14sp</dimen>
+
<!-- The battery icon is 13sp tall, but the other system icons are 15sp tall (see
@*android:dimen/status_bar_system_icon_size) with some top and bottom padding embedded in
the drawables themselves. So, the battery icon may need an extra 1dp of spacing so that its
@@ -199,6 +202,7 @@
<!-- Size of the view displaying the mobile signal icon in the status bar. This value should
match the core/status_bar_system_icon_size and change to sp unit -->
<dimen name="status_bar_mobile_signal_size">15sp</dimen>
+ <dimen name="status_bar_mobile_signal_size_updated">14sp</dimen>
<!-- Size of the view displaying the mobile signal icon in the status bar. This value should
match the viewport height of mobile signal drawables such as ic_lte_mobiledata -->
<dimen name="status_bar_mobile_type_size">16sp</dimen>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index ea0e309..346bdfc 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -34,6 +34,10 @@
remaining [CHAR LIMIT=none]-->
<string name="battery_low_percent_format"><xliff:g id="percentage">%s</xliff:g> remaining</string>
+ <!-- SVG path description for the battery frame of the unified battery drawable
+ (BatteryLayersDrawable.kt). Drawn on a 24x14 canvas. Not suitable outside in any other context -->
+ <string name="battery_unified_frame_path_string" translatable="false">M2.75,3C2.75,1.757 3.757,0.75 5,0.75H20C21.795,0.75 23.25,2.205 23.25,4V10C23.25,11.795 21.795,13.25 20,13.25H5C3.757,13.25 2.75,12.243 2.75,11V3Z </string>
+
<!-- A message that appears when the battery remaining estimate is low in a dialog. This is
appended to the subtitle of the low battery alert. "percentage" is the percentage of battery
remaining. "time" is the amount of time remaining before the phone runs out of battery [CHAR LIMIT=none]-->
@@ -1114,6 +1118,8 @@
<string name="popup_on_dismiss_cta_tile_text">Long press to customize widgets</string>
<!-- Text for the button to configure widgets after long press. [CHAR LIMIT=50] -->
<string name="button_to_configure_widgets_text">Customize widgets</string>
+ <!-- Description for the App icon of disabled widget. [CHAR LIMIT=NONE] -->
+ <string name="icon_description_for_disabled_widget">App icon for disabled widget</string>
<!-- Label for the button which configures widgets [CHAR LIMIT=NONE] -->
<string name="edit_widget">Edit widget</string>
<!-- Description for the button that removes a widget on click. [CHAR LIMIT=50] -->
diff --git a/packages/SystemUI/src/com/android/keyguard/CarrierTextManager.java b/packages/SystemUI/src/com/android/keyguard/CarrierTextManager.java
index 1cfa816..75cace4 100644
--- a/packages/SystemUI/src/com/android/keyguard/CarrierTextManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/CarrierTextManager.java
@@ -17,9 +17,9 @@
package com.android.keyguard;
import static com.android.keyguard.logging.CarrierTextManagerLogger.REASON_ACTIVE_DATA_SUB_CHANGED;
-import static com.android.keyguard.logging.CarrierTextManagerLogger.REASON_ON_SIM_STATE_CHANGED;
import static com.android.keyguard.logging.CarrierTextManagerLogger.REASON_ON_TELEPHONY_CAPABLE;
import static com.android.keyguard.logging.CarrierTextManagerLogger.REASON_REFRESH_CARRIER_INFO;
+import static com.android.keyguard.logging.CarrierTextManagerLogger.REASON_SIM_ERROR_STATE_CHANGED;
import android.content.Context;
import android.content.Intent;
@@ -123,12 +123,15 @@
return;
}
- mLogger.logUpdateCarrierTextForReason(REASON_ON_SIM_STATE_CHANGED);
+
+ mLogger.logSimStateChangedCallback(subId, slotId, simState);
if (getStatusForIccState(simState) == CarrierTextManager.StatusMode.SimIoError) {
mSimErrorState[slotId] = true;
+ mLogger.logUpdateCarrierTextForReason(REASON_SIM_ERROR_STATE_CHANGED);
updateCarrierText();
} else if (mSimErrorState[slotId]) {
mSimErrorState[slotId] = false;
+ mLogger.logUpdateCarrierTextForReason(REASON_SIM_ERROR_STATE_CHANGED);
updateCarrierText();
}
}
diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
index 05e07a7..169a4e0 100644
--- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
+++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
@@ -413,7 +413,6 @@
listenForDozing(this)
if (migrateClocksToBlueprint()) {
listenForDozeAmountTransition(this)
- listenForAnyStateToAodTransition(this)
} else {
listenForDozeAmount(this)
}
@@ -522,19 +521,6 @@
}
}
- /**
- * When keyguard is displayed again after being gone, the clock must be reset to full dozing.
- */
- @VisibleForTesting
- internal fun listenForAnyStateToAodTransition(scope: CoroutineScope): Job {
- return scope.launch {
- keyguardTransitionInteractor.transitionStepsToState(AOD)
- .filter { it.transitionState == TransitionState.STARTED }
- .filter { it.from != LOCKSCREEN }
- .collect { handleDoze(1f) }
- }
- }
-
@VisibleForTesting
internal fun listenForDozing(scope: CoroutineScope): Job {
return scope.launch {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardMessageAreaController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardMessageAreaController.java
index 363dd01..f528ec8 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardMessageAreaController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardMessageAreaController.java
@@ -18,11 +18,16 @@
import android.content.res.ColorStateList;
import android.content.res.Configuration;
+import android.hardware.biometrics.BiometricSourceType;
+import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
+import android.util.Log;
+import android.util.Pair;
import android.view.View;
+import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -40,6 +45,16 @@
public class KeyguardMessageAreaController<T extends KeyguardMessageArea>
extends ViewController<T> {
/**
+ * Pair representing:
+ * first - BiometricSource the currently displayed message is associated with.
+ * second - Timestamp the biometric message came in uptimeMillis.
+ * This Pair can be null if the message is not associated with a biometric.
+ */
+ @Nullable
+ private Pair<BiometricSourceType, Long> mMessageBiometricSource = null;
+ private static final Long SKIP_SHOWING_FACE_MESSAGE_AFTER_FP_MESSAGE_MS = 3500L;
+
+ /**
* Delay before speaking an accessibility announcement. Used to prevent
* lift-to-type from interrupting itself.
*/
@@ -149,12 +164,42 @@
* Sets a message to the underlying text view.
*/
public void setMessage(CharSequence s, boolean animate) {
+ setMessage(s, animate, null);
+ }
+
+ /**
+ * Sets a message to the underlying text view.
+ */
+ public void setMessage(CharSequence s, BiometricSourceType biometricSourceType) {
+ setMessage(s, true, biometricSourceType);
+ }
+
+ private void setMessage(
+ CharSequence s,
+ boolean animate,
+ BiometricSourceType biometricSourceType) {
+ final long uptimeMillis = SystemClock.uptimeMillis();
+ if (skipShowingFaceMessage(biometricSourceType, uptimeMillis)) {
+ Log.d("KeyguardMessageAreaController", "Skip showing face message \"" + s + "\"");
+ return;
+ }
+ mMessageBiometricSource = new Pair<>(biometricSourceType, uptimeMillis);
if (mView.isDisabled()) {
return;
}
mView.setMessage(s, animate);
}
+ private boolean skipShowingFaceMessage(
+ BiometricSourceType biometricSourceType, Long currentUptimeMillis
+ ) {
+ return mMessageBiometricSource != null
+ && biometricSourceType == BiometricSourceType.FACE
+ && mMessageBiometricSource.first == BiometricSourceType.FINGERPRINT
+ && (currentUptimeMillis - mMessageBiometricSource.second)
+ < SKIP_SHOWING_FACE_MESSAGE_AFTER_FP_MESSAGE_MS;
+ }
+
public void setMessage(int resId) {
String message = resId != 0 ? mView.getResources().getString(resId) : null;
setMessage(message);
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 38c2829e..b7667a8 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -34,6 +34,7 @@
import static android.hardware.biometrics.BiometricSourceType.FINGERPRINT;
import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
import static android.os.BatteryManager.CHARGING_POLICY_DEFAULT;
+import static android.telephony.SubscriptionManager.PROFILE_CLASS_PROVISIONING;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT;
@@ -437,7 +438,8 @@
}
};
- private final OnSubscriptionsChangedListener mSubscriptionListener =
+ @VisibleForTesting
+ final OnSubscriptionsChangedListener mSubscriptionListener =
new OnSubscriptionsChangedListener() {
@Override
public void onSubscriptionsChanged() {
@@ -586,16 +588,14 @@
private void handleSimSubscriptionInfoChanged() {
Assert.isMainThread();
mLogger.v("onSubscriptionInfoChanged()");
- List<SubscriptionInfo> sil = mSubscriptionManager
- .getCompleteActiveSubscriptionInfoList();
- if (sil != null) {
- for (SubscriptionInfo subInfo : sil) {
+ List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */);
+ if (!subscriptionInfos.isEmpty()) {
+ for (SubscriptionInfo subInfo : subscriptionInfos) {
mLogger.logSubInfo(subInfo);
}
} else {
mLogger.v("onSubscriptionInfoChanged: list is null");
}
- List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */);
// Hack level over 9000: Because the subscription id is not yet valid when we see the
// first update in handleSimStateChange, we need to force refresh all SIM states
@@ -658,18 +658,18 @@
/**
* @return List of SubscriptionInfo records, maybe empty but never null.
+ *
+ * Note that this method will filter out any subscription which is PROFILE_CLASS_PROVISIONING
*/
public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) {
List<SubscriptionInfo> sil = mSubscriptionInfo;
if (sil == null || forceReload) {
- sil = mSubscriptionManager.getCompleteActiveSubscriptionInfoList();
+ mSubscriptionInfo = mSubscriptionManager.getCompleteActiveSubscriptionInfoList()
+ .stream()
+ .filter(subInfo -> subInfo.getProfileClass() != PROFILE_CLASS_PROVISIONING)
+ .toList();
}
- if (sil == null) {
- // getCompleteActiveSubscriptionInfoList was null callers expect an empty list.
- mSubscriptionInfo = new ArrayList<>();
- } else {
- mSubscriptionInfo = sil;
- }
+
return new ArrayList<>(mSubscriptionInfo);
}
diff --git a/packages/SystemUI/src/com/android/keyguard/logging/CarrierTextManagerLogger.kt b/packages/SystemUI/src/com/android/keyguard/logging/CarrierTextManagerLogger.kt
index d02b72f..cb474d3 100644
--- a/packages/SystemUI/src/com/android/keyguard/logging/CarrierTextManagerLogger.kt
+++ b/packages/SystemUI/src/com/android/keyguard/logging/CarrierTextManagerLogger.kt
@@ -94,6 +94,20 @@
)
}
+ fun logSimStateChangedCallback(subId: Int, slotId: Int, simState: Int) {
+ buffer.log(
+ TAG,
+ LogLevel.VERBOSE,
+ {
+ // subId is always a very small int, and we've run out of integers for log buffer
+ long1 = subId.toLong()
+ int1 = slotId
+ int2 = simState
+ },
+ { "onSimStateChangedCallback: subId=$long1 slotId=$int1 simState=$int2" }
+ )
+ }
+
/**
* Used to log the starting point for _why_ the carrier text is updating. In order to keep us
* from holding on to too many objects, we'll just use simple ints for reasons here
@@ -113,7 +127,7 @@
companion object {
const val REASON_REFRESH_CARRIER_INFO = 1
const val REASON_ON_TELEPHONY_CAPABLE = 2
- const val REASON_ON_SIM_STATE_CHANGED = 3
+ const val REASON_SIM_ERROR_STATE_CHANGED = 3
const val REASON_ACTIVE_DATA_SUB_CHANGED = 4
@Retention(AnnotationRetention.SOURCE)
@@ -122,7 +136,7 @@
[
REASON_REFRESH_CARRIER_INFO,
REASON_ON_TELEPHONY_CAPABLE,
- REASON_ON_SIM_STATE_CHANGED,
+ REASON_SIM_ERROR_STATE_CHANGED,
REASON_ACTIVE_DATA_SUB_CHANGED,
]
)
@@ -132,7 +146,7 @@
when (this) {
REASON_REFRESH_CARRIER_INFO -> "REFRESH_CARRIER_INFO"
REASON_ON_TELEPHONY_CAPABLE -> "ON_TELEPHONY_CAPABLE"
- REASON_ON_SIM_STATE_CHANGED -> "SIM_STATE_CHANGED"
+ REASON_SIM_ERROR_STATE_CHANGED -> "SIM_ERROR_STATE_CHANGED"
REASON_ACTIVE_DATA_SUB_CHANGED -> "ACTIVE_DATA_SUB_CHANGED"
else -> "unknown"
}
diff --git a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardLogger.kt b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardLogger.kt
index d2ad096..ce4032a 100644
--- a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardLogger.kt
+++ b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardLogger.kt
@@ -16,6 +16,7 @@
package com.android.keyguard.logging
+import android.hardware.biometrics.BiometricSourceType
import com.android.systemui.biometrics.AuthRippleController
import com.android.systemui.keyguard.KeyguardIndicationRotateTextViewController
import com.android.systemui.log.LogBuffer
@@ -117,6 +118,26 @@
)
}
+ fun logDropNonFingerprintMessage(
+ message: CharSequence,
+ followUpMessage: CharSequence?,
+ biometricSourceType: BiometricSourceType?,
+ ) {
+ buffer.log(
+ KeyguardIndicationController.TAG,
+ LogLevel.DEBUG,
+ {
+ str1 = message.toString()
+ str2 = followUpMessage?.toString()
+ str3 = biometricSourceType?.name
+ },
+ {
+ "droppingNonFingerprintMessage message=$str1 " +
+ "followUpMessage:$str2 biometricSourceType:$str3"
+ }
+ )
+ }
+
fun logUpdateBatteryIndication(
powerIndication: String,
pluggedIn: Boolean,
diff --git a/packages/SystemUI/src/com/android/systemui/DualToneHandler.kt b/packages/SystemUI/src/com/android/systemui/DualToneHandler.kt
index 22d0bc9..af810ea 100644
--- a/packages/SystemUI/src/com/android/systemui/DualToneHandler.kt
+++ b/packages/SystemUI/src/com/android/systemui/DualToneHandler.kt
@@ -20,6 +20,7 @@
import android.content.Context
import android.view.ContextThemeWrapper
import com.android.settingslib.Utils
+import com.android.settingslib.flags.Flags.newStatusBarIcons
import com.android.systemui.res.R
/**
@@ -53,14 +54,26 @@
Utils.getThemeAttr(context, R.attr.darkIconTheme))
val dualToneLightTheme = ContextThemeWrapper(context,
Utils.getThemeAttr(context, R.attr.lightIconTheme))
- darkColor = Color(
- Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.singleToneColor),
+ if (newStatusBarIcons()) {
+ darkColor = Color(
+ android.graphics.Color.BLACK,
Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.iconBackgroundColor),
Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.fillColor))
- lightColor = Color(
- Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.singleToneColor),
+
+ lightColor = Color(
+ android.graphics.Color.WHITE,
Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.iconBackgroundColor),
Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.fillColor))
+ } else {
+ darkColor = Color(
+ Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.singleToneColor),
+ Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.iconBackgroundColor),
+ Utils.getColorAttrDefaultColor(dualToneDarkTheme, R.attr.fillColor))
+ lightColor = Color(
+ Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.singleToneColor),
+ Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.iconBackgroundColor),
+ Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.fillColor))
+ }
}
private fun getColorForDarkIntensity(darkIntensity: Float, lightColor: Int, darkColor: Int) =
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
index b1a153a..31698a3 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
@@ -17,6 +17,7 @@
import static android.provider.Settings.System.SHOW_BATTERY_PERCENT;
+import static com.android.settingslib.flags.Flags.newStatusBarIcons;
import static com.android.systemui.DejankUtils.whitelistIpcs;
import static java.lang.annotation.RetentionPolicy.SOURCE;
@@ -25,6 +26,7 @@
import android.animation.ObjectAnimator;
import android.annotation.IntDef;
import android.annotation.IntRange;
+import android.annotation.Nullable;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
@@ -47,6 +49,9 @@
import com.android.app.animation.Interpolators;
import com.android.systemui.DualToneHandler;
+import com.android.systemui.battery.unified.BatteryColors;
+import com.android.systemui.battery.unified.BatteryDrawableState;
+import com.android.systemui.battery.unified.BatteryLayersDrawable;
import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver;
import com.android.systemui.res.R;
@@ -78,6 +83,7 @@
private boolean mShowPercentAvailable;
private String mEstimateText = null;
private boolean mPluggedIn;
+ private boolean mPowerSaveEnabled;
private boolean mIsBatteryDefender;
private boolean mIsIncompatibleCharging;
private boolean mDisplayShieldEnabled;
@@ -91,6 +97,12 @@
private BatteryEstimateFetcher mBatteryEstimateFetcher;
+ // for Flags.newStatusBarIcons. The unified battery icon can show percent inside
+ @Nullable private BatteryLayersDrawable mUnifiedBattery;
+ private BatteryColors mUnifiedBatteryColors = BatteryColors.LIGHT_THEME_COLORS;
+ private BatteryDrawableState mUnifiedBatteryState =
+ BatteryDrawableState.Companion.getDefaultInitialState();
+
public BatteryMeterView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@@ -106,6 +118,7 @@
final int frameColor = atts.getColor(R.styleable.BatteryMeterView_frameColor,
context.getColor(com.android.settingslib.R.color.meter_background_color));
mPercentageStyleId = atts.getResourceId(R.styleable.BatteryMeterView_textAppearance, 0);
+
mDrawable = new AccessorizedBatteryDrawable(context, frameColor);
atts.recycle();
@@ -115,13 +128,26 @@
setupLayoutTransition();
mBatteryIconView = new ImageView(context);
- mBatteryIconView.setImageDrawable(mDrawable);
- final MarginLayoutParams mlp = new MarginLayoutParams(
- getResources().getDimensionPixelSize(R.dimen.status_bar_battery_icon_width),
- getResources().getDimensionPixelSize(R.dimen.status_bar_battery_icon_height));
- mlp.setMargins(0, 0, 0,
- getResources().getDimensionPixelOffset(R.dimen.battery_margin_bottom));
- addView(mBatteryIconView, mlp);
+ if (newStatusBarIcons()) {
+ mUnifiedBattery = BatteryLayersDrawable.Companion
+ .newBatteryDrawable(context, mUnifiedBatteryState);
+ mBatteryIconView.setImageDrawable(mUnifiedBattery);
+
+ final MarginLayoutParams mlp = new MarginLayoutParams(
+ getResources().getDimensionPixelSize(
+ R.dimen.status_bar_battery_unified_icon_width),
+ getResources().getDimensionPixelSize(
+ R.dimen.status_bar_battery_unified_icon_height));
+ addView(mBatteryIconView, mlp);
+ } else {
+ mBatteryIconView.setImageDrawable(mDrawable);
+ final MarginLayoutParams mlp = new MarginLayoutParams(
+ getResources().getDimensionPixelSize(R.dimen.status_bar_battery_icon_width),
+ getResources().getDimensionPixelSize(R.dimen.status_bar_battery_icon_height));
+ mlp.setMargins(0, 0, 0,
+ getResources().getDimensionPixelOffset(R.dimen.battery_margin_bottom));
+ addView(mBatteryIconView, mlp);
+ }
updateShowPercent();
mDualToneHandler = new DualToneHandler(context);
@@ -132,6 +158,14 @@
setClipToPadding(false);
}
+
+ private void setBatteryDrawableState(BatteryDrawableState newState) {
+ if (!newStatusBarIcons()) return;
+
+ mUnifiedBatteryState = newState;
+ mUnifiedBattery.setBatteryState(mUnifiedBatteryState);
+ }
+
private void setupLayoutTransition() {
LayoutTransition transition = new LayoutTransition();
transition.setDuration(200);
@@ -200,25 +234,94 @@
* @param pluggedIn whether the device is plugged in or not
*/
public void onBatteryLevelChanged(@IntRange(from = 0, to = 100) int level, boolean pluggedIn) {
+ boolean wasCharging = isCharging();
mPluggedIn = pluggedIn;
mLevel = level;
- mDrawable.setCharging(isCharging());
+ boolean isCharging = isCharging();
+ mDrawable.setCharging(isCharging);
mDrawable.setBatteryLevel(level);
updatePercentText();
+
+ if (newStatusBarIcons()) {
+ Drawable attr = mUnifiedBatteryState.getAttribution();
+ if (isCharging != wasCharging) {
+ attr = getBatteryAttribution(isCharging);
+ }
+
+ BatteryDrawableState newState =
+ new BatteryDrawableState(
+ level,
+ mUnifiedBatteryState.getShowPercent(),
+ level <= 20,
+ attr
+ );
+
+ setBatteryDrawableState(newState);
+ }
+ }
+
+ // Potentially reloads any attribution. Should not be called if the state hasn't changed
+ private Drawable getBatteryAttribution(boolean isCharging) {
+ if (!newStatusBarIcons()) return null;
+
+ int resId = 0;
+ if (mPowerSaveEnabled) {
+ resId = R.drawable.battery_unified_attr_powersave;
+ } else if (mIsBatteryDefender && mDisplayShieldEnabled) {
+ resId = R.drawable.battery_unified_attr_defend;
+ } else if (isCharging) {
+ resId = R.drawable.battery_unified_attr_charging;
+ }
+
+ Drawable attr = null;
+ if (resId > 0) {
+ attr = mContext.getDrawable(resId);
+ }
+
+ return attr;
}
void onPowerSaveChanged(boolean isPowerSave) {
- mDrawable.setPowerSaveEnabled(isPowerSave);
+ if (isPowerSave == mPowerSaveEnabled) {
+ return;
+ }
+ mPowerSaveEnabled = isPowerSave;
+ if (!newStatusBarIcons()) {
+ mDrawable.setPowerSaveEnabled(isPowerSave);
+ } else {
+ setBatteryDrawableState(
+ new BatteryDrawableState(
+ mUnifiedBatteryState.getLevel(),
+ mUnifiedBatteryState.getShowPercent(),
+ mUnifiedBatteryState.getShowErrorState(),
+ getBatteryAttribution(isCharging())
+ )
+ );
+ }
}
void onIsBatteryDefenderChanged(boolean isBatteryDefender) {
boolean valueChanged = mIsBatteryDefender != isBatteryDefender;
mIsBatteryDefender = isBatteryDefender;
- if (valueChanged) {
- updateContentDescription();
+
+ if (!valueChanged) {
+ return;
+ }
+
+ updateContentDescription();
+ if (!newStatusBarIcons()) {
// The battery drawable is a different size depending on whether it's currently
// overheated or not, so we need to re-scale the view when overheated changes.
scaleBatteryMeterViews();
+ } else {
+ setBatteryDrawableState(
+ new BatteryDrawableState(
+ mUnifiedBatteryState.getLevel(),
+ mUnifiedBatteryState.getShowPercent(),
+ mUnifiedBatteryState.getShowErrorState(),
+ getBatteryAttribution(isCharging())
+ )
+ );
}
}
@@ -226,7 +329,18 @@
boolean valueChanged = mIsIncompatibleCharging != isIncompatibleCharging;
mIsIncompatibleCharging = isIncompatibleCharging;
if (valueChanged) {
- mDrawable.setCharging(isCharging());
+ if (newStatusBarIcons()) {
+ setBatteryDrawableState(
+ new BatteryDrawableState(
+ mUnifiedBatteryState.getLevel(),
+ mUnifiedBatteryState.getShowPercent(),
+ mUnifiedBatteryState.getShowErrorState(),
+ getBatteryAttribution(isCharging())
+ )
+ );
+ } else {
+ mDrawable.setCharging(isCharging());
+ }
updateContentDescription();
}
}
@@ -260,6 +374,38 @@
}
void updatePercentText() {
+ if (!newStatusBarIcons()) {
+ updatePercentTextLegacy();
+ return;
+ }
+
+ // The unified battery can show the percent inside, so we only need to handle
+ // the estimated time remaining case
+ if (mShowPercentMode == MODE_ESTIMATE
+ && mBatteryEstimateFetcher != null
+ && !isCharging()
+ ) {
+ mBatteryEstimateFetcher.fetchBatteryTimeRemainingEstimate(
+ (String estimate) -> {
+ if (mBatteryPercentView == null) {
+ mBatteryPercentView = loadPercentView();
+ }
+ if (estimate != null && mShowPercentMode == MODE_ESTIMATE) {
+ mEstimateText = estimate;
+ mBatteryPercentView.setText(estimate);
+ updateContentDescription();
+ } else {
+ mEstimateText = null;
+ mBatteryPercentView.setText(null);
+ updateContentDescription();
+ }
+ });
+ } else {
+ updateContentDescription();
+ }
+ }
+
+ void updatePercentTextLegacy() {
if (mBatteryStateUnknown) {
return;
}
@@ -334,6 +480,45 @@
}
void updateShowPercent() {
+ if (!newStatusBarIcons()) {
+ updateShowPercentLegacy();
+ return;
+ }
+
+ if (mUnifiedBattery == null) {
+ return;
+ }
+
+ // TODO(b/140051051)
+ final boolean systemSetting = 0 != whitelistIpcs(() -> Settings.System
+ .getIntForUser(getContext().getContentResolver(),
+ SHOW_BATTERY_PERCENT, getContext().getResources().getBoolean(
+ com.android.internal.R.bool.config_defaultBatteryPercentageSetting)
+ ? 1 : 0, UserHandle.USER_CURRENT));
+
+ boolean shouldShow =
+ (mShowPercentAvailable && systemSetting && mShowPercentMode != MODE_OFF)
+ || mShowPercentMode == MODE_ON;
+ shouldShow = shouldShow && !mBatteryStateUnknown;
+
+ setBatteryDrawableState(
+ new BatteryDrawableState(
+ mUnifiedBatteryState.getLevel(),
+ shouldShow,
+ mUnifiedBatteryState.getShowErrorState(),
+ mUnifiedBatteryState.getAttribution()
+ )
+ );
+
+ // The legacy impl used the percent view for the estimate and the percent text. The modern
+ // version only uses it for estimate. It can be safely removed here
+ if (mShowPercentMode != MODE_ESTIMATE) {
+ removeView(mBatteryPercentView);
+ mBatteryPercentView = null;
+ }
+ }
+
+ private void updateShowPercentLegacy() {
final boolean showing = mBatteryPercentView != null;
// TODO(b/140051051)
final boolean systemSetting = 0 != whitelistIpcs(() -> Settings.System
@@ -395,10 +580,39 @@
updateShowPercent();
}
+ void scaleBatteryMeterViews() {
+ if (!newStatusBarIcons()) {
+ scaleBatteryMeterViewsLegacy();
+ return;
+ }
+
+ // For simplicity's sake, copy the general pattern in the legacy method and use the new
+ // resources, excluding what we don't need
+ Resources res = getContext().getResources();
+ TypedValue typedValue = new TypedValue();
+
+ res.getValue(R.dimen.status_bar_icon_scale_factor, typedValue, true);
+ float iconScaleFactor = typedValue.getFloat();
+
+ float mainBatteryHeight =
+ res.getDimensionPixelSize(
+ R.dimen.status_bar_battery_unified_icon_height) * iconScaleFactor;
+ float mainBatteryWidth =
+ res.getDimensionPixelSize(
+ R.dimen.status_bar_battery_unified_icon_width) * iconScaleFactor;
+
+ LinearLayout.LayoutParams scaledLayoutParams = new LinearLayout.LayoutParams(
+ Math.round(mainBatteryWidth),
+ Math.round(mainBatteryHeight));
+
+ mBatteryIconView.setLayoutParams(scaledLayoutParams);
+ mBatteryIconView.invalidateDrawable(mUnifiedBattery);
+ }
+
/**
* Looks up the scale factor for status bar icons and scales the battery view by that amount.
*/
- void scaleBatteryMeterViews() {
+ void scaleBatteryMeterViewsLegacy() {
Resources res = getContext().getResources();
TypedValue typedValue = new TypedValue();
@@ -445,6 +659,32 @@
@Override
public void onDarkChanged(ArrayList<Rect> areas, float darkIntensity, int tint) {
if (mIsStaticColor) return;
+
+ if (!newStatusBarIcons()) {
+ onDarkChangedLegacy(areas, darkIntensity, tint);
+ return;
+ }
+
+ if (mUnifiedBattery == null) {
+ return;
+ }
+
+ if (DarkIconDispatcher.isInAreas(areas, this)) {
+ if (darkIntensity < 0.5) {
+ mUnifiedBatteryColors = BatteryColors.DARK_THEME_COLORS;
+ } else {
+ mUnifiedBatteryColors = BatteryColors.LIGHT_THEME_COLORS;
+ }
+
+ mUnifiedBattery.setColors(mUnifiedBatteryColors);
+ } else {
+ // Same behavior as the legacy code when not isInArea
+ mUnifiedBatteryColors = BatteryColors.DARK_THEME_COLORS;
+ mUnifiedBattery.setColors(mUnifiedBatteryColors);
+ }
+ }
+
+ private void onDarkChangedLegacy(ArrayList<Rect> areas, float darkIntensity, int tint) {
float intensity = DarkIconDispatcher.isInAreas(areas, this) ? darkIntensity : 0;
int nonAdaptedSingleToneColor = mDualToneHandler.getSingleColor(intensity);
int nonAdaptedForegroundColor = mDualToneHandler.getFillColor(intensity);
@@ -478,7 +718,16 @@
}
}
- private boolean isCharging() {
+ /** For newStatusBarIcons(), we use a BatteryColors object to declare the theme */
+ public void setUnifiedBatteryColors(BatteryColors colors) {
+ if (!newStatusBarIcons()) return;
+
+ mUnifiedBatteryColors = colors;
+ mUnifiedBattery.setColors(mUnifiedBatteryColors);
+ }
+
+ @VisibleForTesting
+ boolean isCharging() {
return mPluggedIn && !mIsIncompatibleCharging;
}
@@ -505,6 +754,16 @@
return mBatteryPercentView.getText();
}
+ @VisibleForTesting
+ TextView getBatteryPercentView() {
+ return mBatteryPercentView;
+ }
+
+ @VisibleForTesting
+ BatteryDrawableState getUnifiedBatteryState() {
+ return mUnifiedBatteryState;
+ }
+
/** An interface that will fetch the estimated time remaining for the user's battery. */
public interface BatteryEstimateFetcher {
void fetchBatteryTimeRemainingEstimate(
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt
new file mode 100644
index 0000000..1b8495a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt
@@ -0,0 +1,102 @@
+/*
+ * 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.battery.unified
+
+import android.graphics.Canvas
+import android.graphics.ColorFilter
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.graphics.drawable.Drawable
+import android.graphics.drawable.DrawableWrapper
+import android.view.Gravity
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+/**
+ * A battery attribution is defined as a drawable that can display either alongside the percent text
+ * or solely in the center of the battery frame.
+ *
+ * Attributions are given an explicit canvas of 18x8, or 6x6 depending on the display mode (centered
+ * or right-aligned). The size is configured in [BatteryLayersDrawable] by changing this drawable
+ * wrapper's bounds, and optionally setting the [gravity]
+ */
+@Suppress("RtlHardcoded")
+class BatteryAttributionDrawable(dr: Drawable?) : DrawableWrapper(dr) {
+ /** One of [CENTER, LEFT]. Note that RTL is handled in the parent */
+ var gravity = Gravity.CENTER
+ set(value) {
+ field = value
+ updateBoundsInner()
+ }
+
+ // Must be called if bounds change, gravity changes, or the wrapped drawable changes
+ private fun updateBoundsInner() {
+ val dr = drawable ?: return
+
+ val hScale = bounds.width().toFloat() / dr.intrinsicWidth.toFloat()
+ val vScale = bounds.height().toFloat() / dr.intrinsicHeight.toFloat()
+ val scale = min(hScale, vScale)
+
+ val dw = scale * dr.intrinsicWidth
+ val dh = scale * dr.intrinsicHeight
+
+ if (gravity == Gravity.CENTER) {
+ val padLeft = (bounds.width() - dw) / 2
+ val padTop = (bounds.height() - dh) / 2
+ dr.setBounds(
+ (bounds.left + padLeft).roundToInt(),
+ (bounds.top + padTop).roundToInt(),
+ (bounds.left + padLeft + dw).roundToInt(),
+ (bounds.top + padTop + dh).roundToInt()
+ )
+ } else if (gravity == Gravity.LEFT) {
+ dr.setBounds(
+ bounds.left,
+ bounds.top,
+ (bounds.left + dw).roundToInt(),
+ (bounds.top + dh).roundToInt()
+ )
+ }
+ }
+
+ override fun setDrawable(dr: Drawable?) {
+ super.setDrawable(dr)
+ updateBoundsInner()
+ }
+
+ override fun onBoundsChange(bounds: Rect) {
+ updateBoundsInner()
+ }
+
+ /**
+ * DrawableWrapper allows for a null constructor, but this method assumes that the drawable is
+ * non-null. It is called by LayerDrawable on init, so we have to handle null here specifically
+ */
+ override fun getChangingConfigurations(): Int = drawable?.changingConfigurations ?: 0
+
+ override fun draw(canvas: Canvas) {
+ drawable?.draw(canvas)
+ }
+
+ // Deprecated, but needed for Drawable implementation
+ override fun getOpacity() = PixelFormat.OPAQUE
+
+ // We don't use this
+ override fun setAlpha(alpha: Int) {}
+
+ override fun setColorFilter(colorFilter: ColorFilter?) {}
+}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryDrawableState.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryDrawableState.kt
new file mode 100644
index 0000000..b5a93b6
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryDrawableState.kt
@@ -0,0 +1,137 @@
+/*
+ * 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.battery.unified
+
+import android.graphics.Color
+import android.graphics.drawable.Drawable
+
+/**
+ * Encapsulates all drawing information needed by BatteryMeterDrawable to render properly. Rendered
+ * state will be equivalent to the most recent state passed in.
+ */
+data class BatteryDrawableState(
+ /** [0-100] description of the battery level */
+ val level: Int,
+ /** Whether or not to render the percent as a foreground text layer */
+ val showPercent: Boolean,
+ /**
+ * In an error state, the drawable will use the error colors and removes the third layer. If
+ * [showPercent] is false, then the fill will be rendered in the foreground error color. Else
+ * the fill is not rendered.
+ */
+ val showErrorState: Boolean,
+
+ /**
+ * An attribution is a drawable that shows either alongside the percent, or centered in the
+ * foreground of the overall drawable.
+ *
+ * When space sharing with the percent text, the default rect is 6x6, positioned directly next
+ * to the percent and left-aligned.
+ *
+ * When the attribution is the only foreground layer, then we use a 16x8 canvas and center this
+ * drawable.
+ *
+ * In both cases, we use a FIT_CENTER style scaling. Note that for now the attributions will
+ * have to configure their own padding inside of their vector definitions. Future versions
+ * should abstract the side- and center- canvases and allow attributions to be defined with
+ * separate designs for each case.
+ */
+ val attribution: Drawable?
+) {
+ fun hasForegroundContent() = showPercent || attribution != null
+
+ companion object {
+ val DefaultInitialState =
+ BatteryDrawableState(
+ level = 50,
+ showPercent = false,
+ showErrorState = false,
+ attribution = null,
+ )
+ }
+}
+
+sealed interface BatteryColors {
+ /** The color for the frame and any foreground attributions for the battery */
+ val fg: Int
+ /**
+ * Default color for the frame background. Configured to be a transparent white or black that
+ * matches the current mode (white for light theme, black for dark theme) and provides extra
+ * contrast for the drawable
+ */
+ val bg: Int
+
+ /** Color for the level fill when there is an attribution on top */
+ val fill: Int
+ /**
+ * When there is no attribution, [fillOnlyColor] describes an opaque color with more contrast
+ */
+ val fillOnly: Int
+
+ /** Error colors are used for low battery states typically */
+ val errorForeground: Int
+ val errorBackground: Int
+
+ /** Currently unused */
+ val warnBackground: Int
+
+ /** Color scheme appropriate for light mode (dark icons) */
+ data object LightThemeColors : BatteryColors {
+ override val fg = Color.BLACK
+ // 22% alpha white
+ override val bg: Int = Color.valueOf(1f, 1f, 1f, 0.22f).toArgb()
+
+ // 18% alpha black
+ override val fill = Color.valueOf(0f, 0f, 0f, 0.18f).toArgb()
+ // GM Gray 500
+ override val fillOnly = Color.parseColor("#9AA0A6")
+
+ // GM Red 600
+ override val errorForeground = Color.parseColor("#D93025")
+ // GM Red 100
+ override val errorBackground = Color.parseColor("#FAD2CF")
+
+ // GM Yellow 500
+ override val warnBackground = Color.parseColor("#FBBC04")
+ }
+
+ /** Color scheme appropriate for dark mode (light icons) */
+ data object DarkThemeColors : BatteryColors {
+ override val fg = Color.WHITE
+ // 18% alpha black
+ override val bg: Int = Color.valueOf(0f, 0f, 0f, 0.18f).toArgb()
+
+ // 22% alpha white
+ override val fill = Color.valueOf(1f, 1f, 1f, 0.22f).toArgb()
+ // GM Gray 600
+ override val fillOnly = Color.parseColor("#80868B")
+
+ // GM Red 600
+ override val errorForeground = Color.parseColor("#D93025")
+ // GM Red 200
+ override val errorBackground = Color.parseColor("#F6AEA9")
+ // GM Yellow
+ override val warnBackground = Color.parseColor("#FBBC04")
+ }
+
+ companion object {
+ /** For use from java */
+ @JvmField val LIGHT_THEME_COLORS = LightThemeColors
+
+ @JvmField val DARK_THEME_COLORS = DarkThemeColors
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt
new file mode 100644
index 0000000..6d32067
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt
@@ -0,0 +1,171 @@
+/*
+ * 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.battery.unified
+
+import android.graphics.BlendMode
+import android.graphics.Canvas
+import android.graphics.ColorFilter
+import android.graphics.Matrix
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.graphics.RectF
+import android.graphics.drawable.Drawable
+import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
+import kotlin.math.floor
+import kotlin.math.roundToInt
+
+/**
+ * Draws a right-to-left fill inside of the given [framePath]. This fill is designed to exactly fill
+ * the usable space inside of [framePath], given that the stroke width of the path is 1.5, and we
+ * want an extra 0.25 (canvas units) of a gap between the fill and the stroke
+ */
+class BatteryFillDrawable(private val framePath: Path) : Drawable() {
+ private var hScale = 1f
+ private val scaleMatrix = Matrix().also { it.setScale(1f, 1f) }
+ private val scaledPath = Path()
+ private val scaledFillRect = RectF()
+ private var scaledLeftOffset = 0f
+ private var scaledRightInset = 0f
+
+ // Drawable.level cannot be overloaded
+ var batteryLevel = 0
+ set(value) {
+ field = value
+ invalidateSelf()
+ }
+
+ var fillColor: Int = 0
+ set(value) {
+ field = value
+ fillPaint.color = value
+ invalidateSelf()
+ }
+
+ private val clearPaint =
+ Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+ p.style = Paint.Style.STROKE
+ p.strokeWidth = 5f
+ p.blendMode = BlendMode.CLEAR
+ }
+
+ private val fillPaint =
+ Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+ p.style = Paint.Style.FILL
+ p.color = fillColor
+ }
+
+ override fun onBoundsChange(bounds: Rect) {
+ super.onBoundsChange(bounds)
+
+ hScale = bounds.right / Metrics.ViewportWidth
+
+ if (bounds.isEmpty) {
+ scaleMatrix.setScale(1f, 1f)
+ } else {
+ scaleMatrix.setScale(
+ (bounds.right / Metrics.ViewportWidth),
+ (bounds.bottom / Metrics.ViewportHeight)
+ )
+ }
+
+ updateScale()
+ }
+
+ private fun updateScale() {
+ framePath.transform(/* matrix = */ scaleMatrix, /* dst = */ scaledPath)
+ scaleMatrix.mapRect(/* dst = */ scaledFillRect, /* src = */ FillRect)
+
+ scaledLeftOffset = LeftFillOffset * hScale
+ scaledRightInset = RightFillInset * hScale
+ }
+
+ override fun draw(canvas: Canvas) {
+ if (batteryLevel == 0) {
+ return
+ }
+
+ // saveLayer is needed here so we don't clip the other layers of our drawable
+ canvas.saveLayer(null, null)
+
+ // We need to use 3 draw commands:
+ // 1. Clip to the current level
+ // 2. Clip anything outside of the path
+ // 3. render the fill as a rect the correct size to fit the inner space
+ // 4. Clip out the padding between the frame and the fill
+
+ val fillLeft: Int =
+ if (batteryLevel == 100) {
+ 0
+ } else {
+ val fillFraction = batteryLevel / 100f
+ floor(scaledFillRect.width() * (1 - fillFraction)).roundToInt()
+ }
+
+ // Clip to the fill level
+ canvas.clipOutRect(
+ scaledLeftOffset,
+ bounds.top.toFloat(),
+ scaledLeftOffset + fillLeft,
+ bounds.height().toFloat()
+ )
+ // Clip everything outside of the path
+ canvas.clipPath(scaledPath)
+
+ // Draw the fill
+ canvas.drawRect(scaledFillRect, fillPaint)
+
+ // Clear around the fill
+ canvas.drawPath(scaledPath, clearPaint)
+
+ // Finally, restore the layer
+ canvas.restore()
+ }
+
+ override fun setColorFilter(colorFilter: ColorFilter?) {
+ clearPaint.setColorFilter(colorFilter)
+ fillPaint.setColorFilter(colorFilter)
+ }
+
+ // unused
+ override fun getOpacity(): Int = PixelFormat.OPAQUE
+
+ // unused
+ override fun setAlpha(alpha: Int) {}
+
+ companion object {
+ // 3.75f =
+ // 2.75 (left-most edge of the frame path)
+ // + 0.75 (1/2 of the stroke width)
+ // + 0.25 (padding between stroke and fill edge)
+ private const val LeftFillOffset = 3.75f
+
+ // 1.75, calculated the same way, but from the right edge (without the battery cap), which
+ // consumes 2 units of width.
+ private const val RightFillInset = 1.75f
+
+ /** Scale this to the viewport so we fill correctly! */
+ private val FillRect =
+ RectF(
+ LeftFillOffset,
+ 0f,
+ Metrics.ViewportWidth - RightFillInset,
+ Metrics.ViewportHeight
+ )
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt
new file mode 100644
index 0000000..199dd1f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt
@@ -0,0 +1,280 @@
+/*
+ * 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.battery.unified
+
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Matrix
+import android.graphics.Rect
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.graphics.drawable.Drawable
+import android.graphics.drawable.LayerDrawable
+import android.util.PathParser
+import android.view.Gravity
+import com.android.systemui.res.R
+import kotlin.math.roundToInt
+
+/**
+ * Custom [Drawable] that manages a list of other drawables which, together, achieve an appropriate
+ * view for [BatteryDrawableState].
+ *
+ * The main elements managed by this drawable are:
+ *
+ * 1. A battery frame background, which may show a solid fill color
+ * 2. The battery frame itself
+ * 3. A custom [BatteryFillDrawable], which renders a fill level, appropriately scale and
+ * clipped to the battery percent
+ * 4. Percent text
+ * 5. An attribution
+ *
+ * Layers (1) and (2) are loaded directly from xml, as they are static assets. Layer (3) contains a
+ * custom [Drawable.draw] implementation and uses the same path as the battery shape to achieve an
+ * appropriate fill shape.
+ *
+ * The text and attribution layers have the following behaviors:
+ *
+ * - When text-only or attribute-only, the foreground layer is centered and the maximum size
+ * - When sharing space between the attribute and the text:
+ * - The internal space is divided into 12x10 and 6x6 rectangles
+ * - The attribution is aligned left
+ * - The percent text is scaled based on the number of characters (1,2, or 3) in the string
+ *
+ * When [BatteryDrawableState.showErrorState] is true, we will only show either the percent text OR
+ * the battery fill, in order to maximize contrast when using the error colors.
+ */
+@Suppress("RtlHardcoded")
+class BatteryLayersDrawable(
+ private val frameBg: Drawable,
+ private val frame: Drawable,
+ private val fill: BatteryFillDrawable,
+ private val textOnly: BatteryPercentTextOnlyDrawable,
+ private val spaceSharingText: BatterySpaceSharingPercentTextDrawable,
+ private val attribution: BatteryAttributionDrawable,
+ batteryState: BatteryDrawableState,
+) : LayerDrawable(arrayOf(frameBg, frame, fill, textOnly, spaceSharingText, attribution)) {
+
+ private val scaleMatrix = Matrix().also { it.setScale(1f, 1f) }
+ private val scaledAttrFullCanvas = RectF(Metrics.AttrFullCanvas)
+ private val scaledAttrRightCanvas = RectF(Metrics.AttrRightCanvas)
+
+ var batteryState = batteryState
+ set(value) {
+ if (field != value) {
+ // Update before we set the backing field so we can diff
+ handleUpdateState(field, value)
+ field = value
+ invalidateSelf()
+ }
+ }
+
+ var colors: BatteryColors = BatteryColors.LightThemeColors
+ set(value) {
+ field = value
+ updateColors(batteryState.showErrorState, value)
+ }
+
+ private fun handleUpdateState(old: BatteryDrawableState, new: BatteryDrawableState) {
+ if (new.showErrorState != old.showErrorState) {
+ updateColors(new.showErrorState, colors)
+ }
+
+ if (new.level != old.level) {
+ fill.batteryLevel = new.level
+ textOnly.batteryLevel = new.level
+ spaceSharingText.batteryLevel = new.level
+ }
+
+ if (new.attribution != null && new.attribution != attribution.drawable) {
+ attribution.drawable = new.attribution
+ updateColors(new.showErrorState, colors)
+ }
+
+ if (new.hasForegroundContent() != old.hasForegroundContent()) {
+ setFillColor(new.hasForegroundContent(), new.showErrorState, colors)
+ }
+ }
+
+ /** In error states, we don't draw fill unless there is no foreground content (e.g., percent) */
+ private fun updateColors(showErrorState: Boolean, colorInfo: BatteryColors) {
+ frameBg.setTint(if (showErrorState) colorInfo.errorBackground else colorInfo.bg)
+ frame.setTint(colorInfo.fg)
+ attribution.setTint(if (showErrorState) colorInfo.errorForeground else colorInfo.fg)
+ textOnly.setTint(if (showErrorState) colorInfo.errorForeground else colorInfo.fg)
+ spaceSharingText.setTint(if (showErrorState) colorInfo.errorForeground else colorInfo.fg)
+ setFillColor(batteryState.hasForegroundContent(), showErrorState, colorInfo)
+ }
+
+ /**
+ * If there is a foreground layer, then we draw the fill with the low opacity
+ * [BatteryColors.fill] color. Otherwise, if there is no other foreground layer, we will use
+ * either the error or fillOnly colors for more contrast
+ */
+ private fun setFillColor(
+ hasFg: Boolean,
+ error: Boolean,
+ colorInfo: BatteryColors,
+ ) {
+ if (hasFg) {
+ fill.fillColor = colorInfo.fill
+ } else {
+ fill.fillColor = if (error) colorInfo.errorForeground else colorInfo.fillOnly
+ }
+ }
+
+ override fun onBoundsChange(bounds: Rect) {
+ super.onBoundsChange(bounds)
+
+ scaleMatrix.setScale(
+ bounds.width() / Metrics.ViewportWidth,
+ bounds.height() / Metrics.ViewportHeight
+ )
+
+ // Scale the attribution bounds
+ scaleMatrix.mapRect(scaledAttrFullCanvas, Metrics.AttrFullCanvas)
+ scaleMatrix.mapRect(scaledAttrRightCanvas, Metrics.AttrRightCanvas)
+ }
+
+ override fun draw(canvas: Canvas) {
+ // 1. Draw the frame bg
+ frameBg.draw(canvas)
+ // 2. Then the frame itself
+ frame.draw(canvas)
+
+ // 3. Fill it the appropriate amount if non-error state or error + no attribute
+ if (!batteryState.showErrorState || !batteryState.hasForegroundContent()) {
+ fill.draw(canvas)
+ }
+ // 4. Decide what goes inside
+ if (batteryState.showPercent && batteryState.attribution != null) {
+ // 4a. percent & attribution. Implies space-sharing
+
+ // Configure the attribute to draw in a smaller bounding box and align left
+ attribution.gravity = Gravity.LEFT
+ attribution.setBounds(
+ scaledAttrRightCanvas.left.roundToInt(),
+ scaledAttrRightCanvas.top.roundToInt(),
+ scaledAttrRightCanvas.right.roundToInt(),
+ scaledAttrRightCanvas.bottom.roundToInt(),
+ )
+ attribution.draw(canvas)
+
+ spaceSharingText.draw(canvas)
+ } else if (batteryState.showPercent) {
+ // 4b. Percent only
+ textOnly.draw(canvas)
+ } else if (batteryState.attribution != null) {
+ // 4c. Attribution only
+ attribution.gravity = Gravity.CENTER
+ attribution.setBounds(
+ scaledAttrFullCanvas.left.roundToInt(),
+ scaledAttrFullCanvas.top.roundToInt(),
+ scaledAttrFullCanvas.right.roundToInt(),
+ scaledAttrFullCanvas.bottom.roundToInt(),
+ )
+ attribution.draw(canvas)
+ }
+ }
+
+ /**
+ * This drawable relies on [BatteryColors] to encode all alpha in their values, so we ignore
+ * externally-set alpha
+ */
+ override fun setAlpha(alpha: Int) {}
+
+ interface M {
+ val ViewportWidth: Float
+ val ViewportHeight: Float
+
+ // Bounds, oriented in the above viewport, where we will fit-center and center-align
+ // an attribution that is the sole foreground element
+ val AttrFullCanvas: RectF
+ // Bounds, oriented in the above viewport, where we will fit-center and left-align
+ // an attribution that is sharing space with the percent text of the drawable
+ val AttrRightCanvas: RectF
+ }
+
+ companion object {
+ private val PercentFont = Typeface.create("google-sans", Typeface.BOLD)
+
+ /**
+ * Think of this like the `android:<attr>` values in a drawable.xml file. [Metrics] defines
+ * relevant canvas and size information for us to layout this cluster of drawables
+ */
+ val Metrics =
+ object : M {
+ override val ViewportWidth: Float = 24f
+ override val ViewportHeight: Float = 14f
+
+ /**
+ * Bounds, oriented in the above viewport, where we will fit-center and center-align
+ * an attribution that is the sole foreground element
+ *
+ * 18x8 point size
+ */
+ override val AttrFullCanvas: RectF = RectF(4f, 3f, 22f, 11f)
+ /**
+ * Bounds, oriented in the above viewport, where we will fit-center and left-align
+ * an attribution that is sharing space with the percent text of the drawable
+ *
+ * 6x6 point size
+ */
+ override val AttrRightCanvas: RectF = RectF(16f, 4f, 22f, 10f)
+ }
+
+ /**
+ * Create all of the layers needed by [BatteryLayersDrawable]. This class relies on the
+ * following resources to exist in order to properly render:
+ * - R.drawable.battery_unified_frame_bg
+ * - R.drawable.battery_unified_frame
+ * - R.string.battery_unified_frame_path_string
+ * - GoogleSans bold font
+ *
+ * See [BatteryDrawableState] for how to set the properties of the resulting class
+ */
+ fun newBatteryDrawable(
+ context: Context,
+ initialState: BatteryDrawableState = BatteryDrawableState.DefaultInitialState,
+ ): BatteryLayersDrawable {
+ val framePath =
+ PathParser.createPathFromPathData(
+ context.getString(R.string.battery_unified_frame_path_string)
+ )
+
+ val frameBg =
+ context.getDrawable(R.drawable.battery_unified_frame_bg)
+ ?: throw IllegalStateException("Missing battery_unified_frame_bg.xml")
+ val frame =
+ context.getDrawable(R.drawable.battery_unified_frame)
+ ?: throw IllegalStateException("Missing battery_unified_frame.xml")
+ val fill = BatteryFillDrawable(framePath)
+ val textOnly = BatteryPercentTextOnlyDrawable(PercentFont)
+ val spaceSharingText = BatterySpaceSharingPercentTextDrawable(PercentFont)
+ val attribution = BatteryAttributionDrawable(null)
+
+ return BatteryLayersDrawable(
+ frameBg = frameBg,
+ frame = frame,
+ fill = fill,
+ textOnly = textOnly,
+ spaceSharingText = spaceSharingText,
+ attribution = attribution,
+ batteryState = initialState,
+ )
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt
new file mode 100644
index 0000000..123d6ba
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt
@@ -0,0 +1,119 @@
+/*
+ * 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.battery.unified
+
+import android.graphics.Canvas
+import android.graphics.ColorFilter
+import android.graphics.Paint
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.graphics.Typeface
+import android.graphics.drawable.Drawable
+import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
+
+/**
+ * (Names are hard) this drawable calculates the percent text for inside of the
+ * [BatteryLayersDrawable], assuming that there is no other attribution in the foreground. In this
+ * case, we can use the maximum font size and center the text in the full render area inside of the
+ * frame. After accounting for the stroke width and the insets from there, our rendering area is
+ * 18x10 points.
+ *
+ * See [BatterySpaceSharingPercentTextDrawable] (names are still hard) for the space-sharing
+ * approach.
+ *
+ * Note that these drawing metrics are only tested to work with google-sans BOLD
+ */
+class BatteryPercentTextOnlyDrawable(font: Typeface) : Drawable() {
+ private var hScale = 1f
+ private var vScale = 1f
+
+ // range 0-100
+ var batteryLevel: Int = 100
+ set(value) {
+ field = value
+ percentText = "$value"
+ invalidateSelf()
+ }
+
+ private var percentText = "$batteryLevel"
+
+ private val textPaint =
+ Paint().also { p ->
+ p.textSize = 10f
+ p.typeface = font
+ }
+
+ override fun onBoundsChange(bounds: Rect) {
+ super.onBoundsChange(bounds)
+
+ vScale = bounds.bottom / Metrics.ViewportHeight
+ hScale = bounds.right / Metrics.ViewportWidth
+
+ updateScale()
+ }
+
+ private fun updateScale() {
+ textPaint.textSize = TextSize * vScale
+ }
+
+ override fun draw(canvas: Canvas) {
+ val totalAvailableHeight = CanvasHeight * vScale
+
+ // Distribute the vertical whitespace around the text. This is a simplified version of
+ // the equation ((C - T) / 2) + T - V, where C == canvas height, T == text height, and V
+ // is the vertical nudge.
+ val offsetY = (totalAvailableHeight + textPaint.textSize) / 2 - (VerticalNudge * vScale)
+
+ val totalAvailableWidth = CanvasWidth * hScale
+ val textWidth = textPaint.measureText(percentText)
+ val offsetX = (totalAvailableWidth - textWidth) / 2
+
+ // Draw the text centered in the available area
+ canvas.drawText(
+ percentText,
+ (ViewportInsetLeft * hScale) + offsetX,
+ (ViewportInsetTop * vScale) + offsetY,
+ textPaint
+ )
+ }
+
+ override fun setTint(tintColor: Int) {
+ textPaint.color = tintColor
+ super.setTint(tintColor)
+ }
+
+ override fun getOpacity() = PixelFormat.OPAQUE
+
+ override fun setAlpha(alpha: Int) {}
+
+ override fun setColorFilter(colorFilter: ColorFilter?) {}
+
+ companion object {
+ // Based on the 24x14 canvas, we can render in an 18x10 canvas, inset like so:
+ const val ViewportInsetLeft = 4f
+ const val ViewportInsetRight = 2f
+ const val ViewportInsetTop = 2f
+ const val CanvasHeight = 10f
+ const val CanvasWidth = 18f
+
+ // raise the text up by a smidgen so that it is more centered. Experimentally determined
+ const val VerticalNudge = 1.5f
+
+ // Experimentally-determined value
+ const val TextSize = 10f
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt
new file mode 100644
index 0000000..0c418b9
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt
@@ -0,0 +1,136 @@
+/*
+ * 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.battery.unified
+
+import android.graphics.Canvas
+import android.graphics.ColorFilter
+import android.graphics.Paint
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.graphics.Typeface
+import android.graphics.drawable.Drawable
+import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
+
+/**
+ * A variant of [BatteryPercentTextOnlyDrawable] with the following differences:
+ * 1. It is defined on a canvas of 12x10 (shortened by 6 points horizontally)
+ * 2. Because of this, we scale the font according to the number of characters
+ *
+ * Note that these drawing metrics are only tested to work with google-sans BOLD
+ */
+class BatterySpaceSharingPercentTextDrawable(font: Typeface) : Drawable() {
+ private var verticalNudge = 0f
+ private var hScale = 1f
+ private var vScale = 1f
+
+ // range 0-100
+ var batteryLevel: Int = 88
+ set(value) {
+ field = value
+ percentText = "$value"
+ invalidateSelf()
+ }
+
+ private var percentText = "$batteryLevel"
+ set(value) {
+ field = value
+ numberOfCharacters = percentText.length
+ }
+
+ private var numberOfCharacters = percentText.length
+ set(value) {
+ if (field != value) {
+ field = value
+ updateFontSize()
+ }
+ }
+
+ private val textPaint =
+ Paint().also { p ->
+ p.textSize = 10f
+ p.typeface = font
+ }
+
+ private fun updateFontSize() {
+ // These values are determined experimentally
+ when (numberOfCharacters) {
+ 3 -> {
+ verticalNudge = 1f
+ textPaint.textSize = 6f * hScale
+ }
+ // 1, 2
+ else -> {
+ verticalNudge = 1.25f
+ textPaint.textSize = 9f * hScale
+ }
+ }
+ }
+
+ private fun updateScale() {
+ updateFontSize()
+ }
+
+ override fun onBoundsChange(bounds: Rect) {
+ super.onBoundsChange(bounds)
+
+ hScale = bounds.right / Metrics.ViewportWidth
+ vScale = bounds.bottom / Metrics.ViewportHeight
+
+ updateScale()
+ }
+
+ override fun draw(canvas: Canvas) {
+ val totalAvailableHeight = CanvasHeight * vScale
+
+ // Distribute the vertical whitespace around the text. This is a simplified version of
+ // the equation ((C - T) / 2) + T - V, where C == canvas height, T == text height, and V
+ // is the vertical nudge.
+ val offsetY = (totalAvailableHeight + textPaint.textSize) / 2 - (verticalNudge * vScale)
+
+ val totalAvailableWidth = CanvasWidth * hScale
+ val textWidth = textPaint.measureText(percentText)
+ val offsetX = (totalAvailableWidth - textWidth) / 2
+
+ canvas.drawText(
+ percentText,
+ (ViewportInsetLeft * hScale) + offsetX,
+ (ViewportInsetTop * vScale) + offsetY,
+ textPaint
+ )
+ }
+
+ override fun setTint(tintColor: Int) {
+ textPaint.color = tintColor
+ super.setTint(tintColor)
+ }
+
+ override fun getOpacity() = PixelFormat.OPAQUE
+
+ override fun setAlpha(p0: Int) {}
+
+ override fun setColorFilter(colorFilter: ColorFilter?) {
+ textPaint.colorFilter = colorFilter
+ }
+
+ companion object {
+ private const val ViewportInsetLeft = 4f
+ private const val ViewportInsetTop = 2f
+
+ private const val CanvasWidth = 12f
+ private const val CanvasHeight = 10f
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 0bd44f0..f4cd5b9 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -17,7 +17,6 @@
package com.android.systemui.biometrics;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
-import static android.hardware.biometrics.Flags.customBiometricPrompt;
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
import static com.android.internal.jank.InteractionJankMonitor.CUJ_BIOMETRIC_PROMPT_TRANSITION;
@@ -33,6 +32,7 @@
import android.hardware.biometrics.BiometricAuthenticator.Modality;
import android.hardware.biometrics.BiometricConstants;
import android.hardware.biometrics.BiometricManager.Authenticators;
+import android.hardware.biometrics.Flags;
import android.hardware.biometrics.PromptInfo;
import android.hardware.face.FaceSensorPropertiesInternal;
import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
@@ -402,7 +402,12 @@
@Nullable FaceSensorPropertiesInternal faceProps,
@NonNull VibratorHelper vibratorHelper
) {
- if (Utils.isBiometricAllowed(config.mPromptInfo) || customBiometricPrompt()) {
+ // Set this value before showing either of the prompt.
+ mPromptSelectorInteractorProvider.get().setShouldShowBpWithoutIconForCredential(
+ config.mPromptInfo);
+
+ if (Utils.isBiometricAllowed(config.mPromptInfo)
+ || mPromptViewModel.getShowBpWithoutIconForCredential().getValue()) {
addBiometricView(config, layoutInflater, viewModel, fpProps, faceProps, vibratorHelper);
} else if (constraintBp() && Utils.isDeviceCredentialAllowed(mConfig.mPromptInfo)) {
addCredentialView(true, false);
@@ -411,7 +416,6 @@
}
}
-
private void addBiometricView(@NonNull Config config, @NonNull LayoutInflater layoutInflater,
@NonNull PromptViewModel viewModel,
@Nullable FingerprintSensorPropertiesInternal fpProps,
@@ -534,7 +538,8 @@
() -> animateAway(AuthDialogCallback.DISMISSED_USER_CANCELED));
if (constraintBp()) {
// Do nothing on attachment with constraintLayout
- } else if (Utils.isBiometricAllowed(mConfig.mPromptInfo) || customBiometricPrompt()) {
+ } else if (Utils.isBiometricAllowed(mConfig.mPromptInfo)
+ || mPromptViewModel.getShowBpWithoutIconForCredential().getValue()) {
mBiometricScrollView.addView(mBiometricView.asView());
} else if (Utils.isDeviceCredentialAllowed(mConfig.mPromptInfo)) {
addCredentialView(true /* animatePanel */, false /* animateContents */);
@@ -819,6 +824,9 @@
final Runnable endActionRunnable = () -> {
setVisibility(View.INVISIBLE);
+ if (Flags.customBiometricPrompt()) {
+ mPromptSelectorInteractorProvider.get().resetPrompt();
+ }
removeWindowIfAttached();
};
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
index 921e395..16865ca 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
@@ -31,6 +31,7 @@
import android.hardware.fingerprint.IUdfpsOverlayControllerCallback
import android.os.Build
import android.os.RemoteException
+import android.os.Trace
import android.provider.Settings
import android.util.Log
import android.util.RotationUtils
@@ -58,9 +59,9 @@
import com.android.systemui.deviceentry.shared.DeviceEntryUdfpsRefactor
import com.android.systemui.dump.DumpManager
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.power.domain.interactor.PowerInteractor
-import com.android.systemui.power.shared.model.WakefulnessState
import com.android.systemui.res.R
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.statusbar.LockscreenShadeTransitionController
@@ -125,11 +126,15 @@
private val powerInteractor: PowerInteractor,
@Application private val scope: CoroutineScope,
) {
- private val isFinishedGoingToSleep: Flow<Unit> =
- powerInteractor.detailedWakefulness
- .filter { it.internalWakefulnessState == WakefulnessState.ASLEEP }
+ private val currentStateUpdatedToOffAodOrDozing: Flow<Unit> =
+ transitionInteractor.currentKeyguardState
+ .filter {
+ it == KeyguardState.OFF ||
+ it == KeyguardState.AOD ||
+ it == KeyguardState.DOZING
+ }
.map { } // map to Unit
- private var listenForAsleepJob: Job? = null
+ private var listenForCurrentKeyguardState: Job? = null
private var addViewRunnable: Runnable? = null
private var overlayViewLegacy: UdfpsView? = null
private set
@@ -280,18 +285,19 @@
private fun addViewNowOrLater(view: View, animation: UdfpsAnimationViewController<*>?) {
if (udfpsViewPerformance()) {
addViewRunnable = kotlinx.coroutines.Runnable {
+ Trace.setCounter("UdfpsAddView", 1)
windowManager.addView(
view,
coreLayoutParams.updateDimensions(animation)
)
}
- if (powerInteractor.detailedWakefulness.value.internalWakefulnessState
- != WakefulnessState.STARTING_TO_SLEEP) {
+ if (powerInteractor.detailedWakefulness.value.isAwake()) {
+ // Device is awake, so we add the view immediately.
addViewIfPending()
} else {
- listenForAsleepJob?.cancel()
- listenForAsleepJob = scope.launch {
- isFinishedGoingToSleep.collect {
+ listenForCurrentKeyguardState?.cancel()
+ listenForCurrentKeyguardState = scope.launch {
+ currentStateUpdatedToOffAodOrDozing.collect {
addViewIfPending()
}
}
@@ -306,7 +312,7 @@
private fun addViewIfPending() {
addViewRunnable?.let {
- listenForAsleepJob?.cancel()
+ listenForCurrentKeyguardState?.cancel()
it.run()
}
addViewRunnable = null
@@ -412,7 +418,14 @@
udfpsDisplayModeProvider.disable(null)
}
getTouchOverlay()?.apply {
- windowManager.removeView(this)
+ if (udfpsViewPerformance()) {
+ if (this.parent != null) {
+ windowManager.removeView(this)
+ }
+ Trace.setCounter("UdfpsAddView", 0)
+ } else {
+ windowManager.removeView(this)
+ }
setOnTouchListener(null)
setOnHoverListener(null)
overlayTouchListener?.let {
@@ -423,7 +436,7 @@
overlayViewLegacy = null
overlayTouchView = null
overlayTouchListener = null
- listenForAsleepJob?.cancel()
+ listenForCurrentKeyguardState?.cancel()
return wasShowing
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/data/repository/PromptRepository.kt b/packages/SystemUI/src/com/android/systemui/biometrics/data/repository/PromptRepository.kt
index ad7bb0e..b87fadf 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/data/repository/PromptRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/data/repository/PromptRepository.kt
@@ -16,8 +16,11 @@
package com.android.systemui.biometrics.data.repository
+import android.hardware.biometrics.Flags
import android.hardware.biometrics.PromptInfo
import com.android.systemui.biometrics.AuthController
+import com.android.systemui.biometrics.Utils
+import com.android.systemui.biometrics.Utils.isDeviceCredentialAllowed
import com.android.systemui.biometrics.shared.model.PromptKind
import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
@@ -65,6 +68,18 @@
*/
val isConfirmationRequired: Flow<Boolean>
+ /**
+ * If biometric prompt without icon needs to show for displaying content prior to credential
+ * view.
+ */
+ val showBpWithoutIconForCredential: StateFlow<Boolean>
+
+ /**
+ * Update whether biometric prompt without icon needs to show for displaying content prior to
+ * credential view, which should be set before [setPrompt].
+ */
+ fun setShouldShowBpWithoutIconForCredential(promptInfo: PromptInfo)
+
/** Update the prompt configuration, which should be set before [isShowing]. */
fun setPrompt(
promptInfo: PromptInfo,
@@ -129,6 +144,19 @@
}
.distinctUntilChanged()
+ private val _showBpWithoutIconForCredential: MutableStateFlow<Boolean> = MutableStateFlow(false)
+ override val showBpWithoutIconForCredential = _showBpWithoutIconForCredential.asStateFlow()
+
+ override fun setShouldShowBpWithoutIconForCredential(promptInfo: PromptInfo) {
+ val hasCredentialViewShown = kind.value !is PromptKind.Biometric
+ val showBpForCredential =
+ Flags.customBiometricPrompt() &&
+ !Utils.isBiometricAllowed(promptInfo) &&
+ isDeviceCredentialAllowed(promptInfo) &&
+ promptInfo.contentView != null
+ _showBpWithoutIconForCredential.value = showBpForCredential && !hasCredentialViewShown
+ }
+
override fun setPrompt(
promptInfo: PromptInfo,
userId: Int,
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptCredentialInteractor.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptCredentialInteractor.kt
index e3facff..94cea57 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptCredentialInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptCredentialInteractor.kt
@@ -30,6 +30,7 @@
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -59,6 +60,13 @@
/** If the prompt is currently showing. */
val isShowing: Flow<Boolean> = biometricPromptRepository.isShowing
+ /**
+ * If biometric prompt without icon needs to show for displaying content prior to credential
+ * view.
+ */
+ val showBpWithoutIconForCredential: StateFlow<Boolean> =
+ biometricPromptRepository.showBpWithoutIconForCredential
+
/** Metadata about the current credential prompt, including app-supplied preferences. */
val prompt: Flow<BiometricPromptRequest.Credential?> =
combine(
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractor.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractor.kt
index b3f9574..45816c1 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractor.kt
@@ -32,6 +32,7 @@
import com.android.systemui.dagger.SysUISingleton
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@@ -70,6 +71,18 @@
/** Fingerprint sensor type */
val sensorType: Flow<FingerprintSensorType>
+ /**
+ * If biometric prompt without icon needs to show for displaying content prior to credential
+ * view.
+ */
+ val showBpWithoutIconForCredential: StateFlow<Boolean>
+
+ /**
+ * Update whether biometric prompt without icon needs to show for displaying content prior to
+ * credential view, which should be set before [PromptRepository.setPrompt].
+ */
+ fun setShouldShowBpWithoutIconForCredential(promptInfo: PromptInfo)
+
/** Use biometrics for authentication. */
fun useBiometricsForAuthentication(
promptInfo: PromptInfo,
@@ -154,6 +167,12 @@
override val sensorType: Flow<FingerprintSensorType> = fingerprintPropertyRepository.sensorType
+ override val showBpWithoutIconForCredential = promptRepository.showBpWithoutIconForCredential
+
+ override fun setShouldShowBpWithoutIconForCredential(promptInfo: PromptInfo) {
+ promptRepository.setShouldShowBpWithoutIconForCredential(promptInfo)
+ }
+
override fun useBiometricsForAuthentication(
promptInfo: PromptInfo,
userId: Int,
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
index 6133a51c..6f079e2 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
@@ -17,6 +17,7 @@
val title: String,
val subtitle: String,
val description: String,
+ val contentView: PromptContentView?,
val userInfo: BiometricUserInfo,
val operationInfo: BiometricOperationInfo,
val showEmergencyCallButton: Boolean,
@@ -33,11 +34,11 @@
title = info.title?.toString() ?: "",
subtitle = info.subtitle?.toString() ?: "",
description = info.description?.toString() ?: "",
+ contentView = info.contentView,
userInfo = userInfo,
operationInfo = operationInfo,
showEmergencyCallButton = info.isShowEmergencyCallButton
) {
- val contentView: PromptContentView? = info.contentView
val logoRes: Int = info.logoRes
val logoBitmap: Bitmap? = info.logoBitmap
val logoDescription: String? = info.logoDescription
@@ -54,6 +55,7 @@
title = (info.deviceCredentialTitle ?: info.title)?.toString() ?: "",
subtitle = (info.deviceCredentialSubtitle ?: info.subtitle)?.toString() ?: "",
description = (info.deviceCredentialDescription ?: info.description)?.toString() ?: "",
+ contentView = info.contentView,
userInfo = userInfo,
operationInfo = operationInfo,
showEmergencyCallButton = info.isShowEmergencyCallButton
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
index cd5b124..ea39247 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
@@ -22,7 +22,6 @@
import android.hardware.biometrics.BiometricAuthenticator
import android.hardware.biometrics.BiometricConstants
import android.hardware.biometrics.BiometricPrompt
-import android.hardware.biometrics.Flags.customBiometricPrompt
import android.hardware.face.FaceManager
import android.text.method.ScrollingMovementMethod
import android.util.Log
@@ -151,17 +150,6 @@
// these do not change and need to be set before any size transitions
val modalities = viewModel.modalities.first()
- // If there is no biometrics available, biometric prompt is showing just for displaying
- // content, no authentication needed.
- if (!(customBiometricPrompt() && modalities.isEmpty)) {
- PromptIconViewBinder.bind(
- iconView,
- iconOverlayView,
- iconSizeOverride,
- viewModel,
- )
- }
-
if (modalities.hasFingerprint) {
/**
* Load the given [rawResources] immediately so they are cached for use in the
@@ -233,6 +221,19 @@
)
}
+ lifecycleScope.launch {
+ viewModel.showBpWithoutIconForCredential.collect {
+ if (!it) {
+ PromptIconViewBinder.bind(
+ iconView,
+ iconOverlayView,
+ iconSizeOverride,
+ viewModel,
+ )
+ }
+ }
+ }
+
// TODO(b/251476085): migrate legacy icon controllers and remove
// The fingerprint sensor is started by the legacy
// AuthContainerView#onDialogAnimatedIn in all cases but the implicit coex flow
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
index a37d916..8336d5e 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
@@ -21,7 +21,6 @@
import android.animation.ValueAnimator
import android.graphics.Outline
import android.graphics.Rect
-import android.hardware.biometrics.Flags
import android.transition.AutoTransition
import android.transition.TransitionManager
import android.view.Surface
@@ -55,6 +54,7 @@
import com.android.systemui.biometrics.ui.viewmodel.isRight
import com.android.systemui.biometrics.ui.viewmodel.isSmall
import com.android.systemui.biometrics.ui.viewmodel.isTop
+import com.android.systemui.keyguard.ui.view.layout.sections.setVisibility
import com.android.systemui.lifecycle.repeatWhenAttached
import com.android.systemui.res.R
import kotlin.math.abs
@@ -111,14 +111,9 @@
val smallConstraintSet = ConstraintSet()
smallConstraintSet.clone(mediumConstraintSet)
- viewsToHideWhenSmall.forEach { smallConstraintSet.setVisibility(it.id, View.GONE) }
val largeConstraintSet = ConstraintSet()
largeConstraintSet.clone(mediumConstraintSet)
- viewsToHideWhenSmall.forEach { largeConstraintSet.setVisibility(it.id, View.GONE) }
- largeConstraintSet.setVisibility(iconHolderView.id, View.GONE)
- largeConstraintSet.setVisibility(R.id.biometric_icon_overlay, View.GONE)
- largeConstraintSet.setVisibility(R.id.indicator, View.GONE)
largeConstraintSet.setGuidelineBegin(leftGuideline.id, 0)
largeConstraintSet.setGuidelineEnd(rightGuideline.id, 0)
largeConstraintSet.setGuidelineEnd(bottomGuideline.id, 0)
@@ -219,13 +214,18 @@
}
}
- view.repeatWhenAttached {
- var currentSize: PromptSize? = null
- val modalities = viewModel.modalities.first()
- // TODO(b/288175072): Move all visibility settings together.
- // If there is no biometrics available, biometric prompt is showing just for
- // displaying content, no authentication needed.
- if (Flags.customBiometricPrompt() && modalities.isEmpty) {
+ fun setConstraintSetVisibility() {
+ viewsToHideWhenSmall.forEach {
+ mediumConstraintSet.setVisibility(it.id, it.showContentOrHide())
+ largeConstraintSet.setVisibility(it.id, View.GONE)
+ smallConstraintSet.setVisibility(it.id, View.GONE)
+ }
+
+ largeConstraintSet.setVisibility(iconHolderView.id, View.GONE)
+ largeConstraintSet.setVisibility(R.id.biometric_icon_overlay, View.GONE)
+ largeConstraintSet.setVisibility(R.id.indicator, View.GONE)
+
+ if (viewModel.showBpWithoutIconForCredential.value) {
smallConstraintSet.setVisibility(iconHolderView.id, View.GONE)
smallConstraintSet.setVisibility(R.id.biometric_icon_overlay, View.GONE)
smallConstraintSet.setVisibility(R.id.indicator, View.GONE)
@@ -233,12 +233,17 @@
mediumConstraintSet.setVisibility(R.id.biometric_icon_overlay, View.GONE)
mediumConstraintSet.setVisibility(R.id.indicator, View.GONE)
}
+ }
+
+ view.repeatWhenAttached {
+ var currentSize: PromptSize? = null
+
lifecycleScope.launch {
combine(viewModel.position, viewModel.size, ::Pair).collect {
(position, size) ->
view.doOnAttach {
measureBounds(position)
-
+ setConstraintSetVisibility()
when {
size.isSmall -> {
val ratio =
@@ -313,7 +318,6 @@
// TODO(b/251476085): migrate the legacy panel controller and simplify this
view.repeatWhenAttached {
var currentSize: PromptSize? = null
- val modalities = viewModel.modalities.first()
lifecycleScope.launch {
/**
* View is only set visible in BiometricViewSizeBinder once PromptSize is
@@ -331,11 +335,13 @@
// prepare for animated size transitions
for (v in viewsToHideWhenSmall) {
- v.showContentOrHide(forceHide = size.isSmall)
+ v.visibility = v.showContentOrHide(forceHide = size.isSmall)
}
- if (Flags.customBiometricPrompt() && modalities.isEmpty) {
+
+ if (viewModel.showBpWithoutIconForCredential.value) {
iconHolderView.visibility = View.GONE
}
+
if (currentSize == null && size.isSmall) {
iconHolderView.alpha = 0f
}
@@ -344,9 +350,9 @@
}
// TODO(b/302735104): Fix wrong height due to the delay of
- // PromptContentView. addOnLayoutChangeListener() will cause crash when
- // showing credential view, since |PromptIconViewModel| won't release
- // the flow.
+ // PromptContentView. addOnLayoutChangeListener() will cause crash
+ // when showing credential view, since |PromptIconViewModel| won't
+ // release the flow.
// propagate size changes to legacy panel controller and animate
// transitions
view.doOnLayout {
@@ -460,15 +466,14 @@
return r == Surface.ROTATION_90 || r == Surface.ROTATION_270
}
-private fun View.showContentOrHide(forceHide: Boolean = false) {
+private fun View.showContentOrHide(forceHide: Boolean = false): Int {
val isTextViewWithBlankText = this is TextView && this.text.isBlank()
val isImageViewWithoutImage = this is ImageView && this.drawable == null
- visibility =
- if (forceHide || isTextViewWithBlankText || isImageViewWithoutImage) {
- View.GONE
- } else {
- View.VISIBLE
- }
+ return if (forceHide || isTextViewWithBlankText || isImageViewWithoutImage) {
+ View.GONE
+ } else {
+ View.VISIBLE
+ }
}
private fun View.centerX(): Int {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
index 03c5c53..46be8c7 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
@@ -4,13 +4,13 @@
import android.graphics.drawable.Drawable
import android.text.InputType
import com.android.internal.widget.LockPatternView
-import com.android.systemui.res.R
import com.android.systemui.biometrics.Utils
import com.android.systemui.biometrics.domain.interactor.CredentialStatus
import com.android.systemui.biometrics.domain.interactor.PromptCredentialInteractor
import com.android.systemui.biometrics.domain.model.BiometricPromptRequest
import com.android.systemui.biometrics.shared.model.BiometricUserInfo
import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.res.R
import javax.inject.Inject
import kotlin.reflect.KClass
import kotlinx.coroutines.flow.Flow
@@ -32,14 +32,16 @@
/** Top level information about the prompt. */
val header: Flow<CredentialHeaderViewModel> =
- credentialInteractor.prompt.filterIsInstance<BiometricPromptRequest.Credential>().map {
- request ->
+ combine(
+ credentialInteractor.prompt.filterIsInstance<BiometricPromptRequest.Credential>(),
+ credentialInteractor.showBpWithoutIconForCredential
+ ) { request, showBpWithoutIconForCredential ->
BiometricPromptHeaderViewModelImpl(
request,
user = request.userInfo,
title = request.title,
- subtitle = request.subtitle,
- description = request.description,
+ subtitle = if (showBpWithoutIconForCredential) "" else request.subtitle,
+ description = if (showBpWithoutIconForCredential) "" else request.description,
icon = applicationContext.asLockIcon(request.userInfo.deviceCredentialOwnerId),
showEmergencyCallButton = request.showEmergencyCallButton
)
@@ -145,7 +147,7 @@
.createLaunchEmergencyDialerIntent(null)
.setFlags(
android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
- android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
+ android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
)
context.startActivity(intent)
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
index c933e0e..2c749ba 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
@@ -47,6 +47,7 @@
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
@@ -123,6 +124,9 @@
/** The kind of credential the user has. */
val credentialKind: Flow<PromptKind> = promptSelectorInteractor.credentialKind
+ val showBpWithoutIconForCredential: StateFlow<Boolean> =
+ promptSelectorInteractor.showBpWithoutIconForCredential
+
/** The label to use for the cancel button. */
val negativeButtonText: Flow<String> =
promptSelectorInteractor.prompt.map { it?.negativeButtonText ?: "" }
diff --git a/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt
index 5d52541..151e1ee 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt
@@ -24,6 +24,7 @@
import com.android.systemui.communal.data.repository.CommunalRepository
import com.android.systemui.communal.data.repository.CommunalWidgetRepository
import com.android.systemui.communal.domain.model.CommunalContentModel
+import com.android.systemui.communal.domain.model.CommunalContentModel.WidgetContent
import com.android.systemui.communal.shared.model.CommunalContentSize
import com.android.systemui.communal.shared.model.CommunalContentSize.FULL
import com.android.systemui.communal.shared.model.CommunalContentSize.HALF
@@ -278,14 +279,25 @@
}
/** A list of widget content to be displayed in the communal hub. */
- val widgetContent: Flow<List<CommunalContentModel.Widget>> =
- widgetRepository.communalWidgets.map { widgets ->
- filterWidgetsByExistingUsers(widgets).map Widget@{ widget ->
- return@Widget CommunalContentModel.Widget(
- appWidgetId = widget.appWidgetId,
- providerInfo = widget.providerInfo,
- appWidgetHost = appWidgetHost,
- )
+ val widgetContent: Flow<List<WidgetContent>> =
+ combine(
+ widgetRepository.communalWidgets.map { filterWidgetsByExistingUsers(it) },
+ communalSettingsInteractor.communalWidgetCategories
+ ) { widgets, allowedCategories ->
+ widgets.map { widget ->
+ if (widget.providerInfo.widgetCategory and allowedCategories != 0) {
+ // At least one category this widget specified is allowed, so show it
+ WidgetContent.Widget(
+ appWidgetId = widget.appWidgetId,
+ providerInfo = widget.providerInfo,
+ appWidgetHost = appWidgetHost,
+ )
+ } else {
+ WidgetContent.DisabledWidget(
+ appWidgetId = widget.appWidgetId,
+ providerInfo = widget.providerInfo,
+ )
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/domain/model/CommunalContentModel.kt b/packages/SystemUI/src/com/android/systemui/communal/domain/model/CommunalContentModel.kt
index ae019a1..c64f666 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/domain/model/CommunalContentModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/domain/model/CommunalContentModel.kt
@@ -18,6 +18,7 @@
import android.appwidget.AppWidgetProviderInfo
import android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE
+import android.content.pm.ApplicationInfo
import android.widget.RemoteViews
import com.android.systemui.communal.shared.model.CommunalContentSize
import com.android.systemui.communal.widgets.CommunalAppWidgetHost
@@ -42,20 +43,37 @@
val createdTimestampMillis: Long
}
- data class Widget(
- val appWidgetId: Int,
- val providerInfo: AppWidgetProviderInfo,
- val appWidgetHost: CommunalAppWidgetHost,
- ) : CommunalContentModel {
- override val key = KEY.widget(appWidgetId)
- // Widget size is always half.
- override val size = CommunalContentSize.HALF
+ sealed interface WidgetContent : CommunalContentModel {
+ val appWidgetId: Int
+ val providerInfo: AppWidgetProviderInfo
- /** Whether this widget can be reconfigured after it has already been added. */
- val reconfigurable: Boolean
- get() =
- (providerInfo.widgetFeatures and WIDGET_FEATURE_RECONFIGURABLE != 0) &&
- providerInfo.configure != null
+ data class Widget(
+ override val appWidgetId: Int,
+ override val providerInfo: AppWidgetProviderInfo,
+ val appWidgetHost: CommunalAppWidgetHost,
+ ) : WidgetContent {
+ override val key = KEY.widget(appWidgetId)
+ // Widget size is always half.
+ override val size = CommunalContentSize.HALF
+
+ /** Whether this widget can be reconfigured after it has already been added. */
+ val reconfigurable: Boolean
+ get() =
+ (providerInfo.widgetFeatures and WIDGET_FEATURE_RECONFIGURABLE != 0) &&
+ providerInfo.configure != null
+ }
+
+ data class DisabledWidget(
+ override val appWidgetId: Int,
+ override val providerInfo: AppWidgetProviderInfo
+ ) : WidgetContent {
+ override val key = KEY.disabledWidget(appWidgetId)
+ // Widget size is always half.
+ override val size = CommunalContentSize.HALF
+
+ val appInfo: ApplicationInfo?
+ get() = providerInfo.providerInfo?.applicationInfo
+ }
}
/** A placeholder item representing a new widget being added */
@@ -111,6 +129,10 @@
return "widget_$id"
}
+ fun disabledWidget(id: Int): String {
+ return "disabled_widget_$id"
+ }
+
fun widgetPlaceholder(): String {
return "widget_placeholder_${UUID.randomUUID()}"
}
@@ -129,5 +151,5 @@
}
}
- fun isWidget() = this is Widget
+ fun isWidgetContent() = this is WidgetContent
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
index e8a8444..7f8103e 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
@@ -18,7 +18,7 @@
import android.app.Activity
import android.app.ActivityOptions
-import android.app.ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
+import android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
import android.app.Dialog
import android.app.PendingIntent
import android.content.ComponentName
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
index 1157d97..19af371 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
@@ -51,6 +51,7 @@
import com.android.systemui.controls.dagger.ControlsModule;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.dagger.qualifiers.SystemUser;
+import com.android.systemui.dagger.qualifiers.UiBackground;
import com.android.systemui.demomode.dagger.DemoModeModule;
import com.android.systemui.deviceentry.DeviceEntryModule;
import com.android.systemui.display.DisplayModule;
@@ -365,7 +366,8 @@
SysUiState sysUiState,
FeatureFlags featureFlags,
NotifPipelineFlags notifPipelineFlags,
- @Main Executor sysuiMainExecutor) {
+ @Main Executor sysuiMainExecutor,
+ @UiBackground Executor sysuiUiBgExecutor) {
return Optional.ofNullable(BubblesManager.create(context,
bubblesOptional,
notificationShadeWindowController,
@@ -384,7 +386,8 @@
sysUiState,
featureFlags,
notifPipelineFlags,
- sysuiMainExecutor));
+ sysuiMainExecutor,
+ sysuiUiBgExecutor));
}
@Binds
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepository.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepository.kt
index cf7d601..baae986 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryFaceAuthRepository.kt
@@ -62,6 +62,10 @@
import com.android.systemui.user.data.model.SelectionStatus
import com.android.systemui.user.data.repository.UserRepository
import com.google.errorprone.annotations.CompileTimeConstant
+import java.io.PrintWriter
+import java.util.Arrays
+import java.util.stream.Collectors
+import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
@@ -83,10 +87,6 @@
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import java.io.PrintWriter
-import java.util.Arrays
-import java.util.stream.Collectors
-import javax.inject.Inject
/**
* API to run face authentication and detection for device entry / on keyguard (as opposed to the
@@ -431,11 +431,11 @@
override fun onAuthenticationFailed() {
_isAuthenticated.value = false
faceAuthLogger.authenticationFailed()
+ _authenticationStatus.value = FailedFaceAuthenticationStatus()
if (!_isLockedOut.value) {
// onAuthenticationError gets invoked before onAuthenticationFailed when the
// last auth attempt locks out face authentication.
- // Skip updating the authentication status in such a scenario.
- _authenticationStatus.value = FailedFaceAuthenticationStatus()
+ // Skip onFaceAuthRequestCompleted in such a scenario.
onFaceAuthRequestCompleted()
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
index 7a24d76..298da13 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
@@ -22,8 +22,10 @@
import com.android.server.notification.Flags.crossAppPoliteNotifications
import com.android.server.notification.Flags.politeNotifications
import com.android.server.notification.Flags.vibrateWhileUnlocked
+import com.android.systemui.Flags.FLAG_COMMUNAL_HUB
import com.android.systemui.Flags.FLAG_KEYGUARD_BOTTOM_AREA_REFACTOR
import com.android.systemui.Flags.FLAG_MIGRATE_CLOCKS_TO_BLUEPRINT
+import com.android.systemui.Flags.communalHub
import com.android.systemui.Flags.keyguardBottomAreaRefactor
import com.android.systemui.Flags.migrateClocksToBlueprint
import com.android.systemui.dagger.SysUISingleton
@@ -58,6 +60,9 @@
// ComposeLockscreen dependencies
ComposeLockscreen.token dependsOn keyguardBottomAreaRefactor
ComposeLockscreen.token dependsOn migrateClocksToBlueprint
+
+ // CommunalHub dependencies
+ communalHub dependsOn migrateClocksToBlueprint
}
private inline val politeNotifications
@@ -70,4 +75,6 @@
get() = FlagToken(FLAG_KEYGUARD_BOTTOM_AREA_REFACTOR, keyguardBottomAreaRefactor())
private inline val migrateClocksToBlueprint
get() = FlagToken(FLAG_MIGRATE_CLOCKS_TO_BLUEPRINT, migrateClocksToBlueprint())
+ private inline val communalHub
+ get() = FlagToken(FLAG_COMMUNAL_HUB, communalHub())
}
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
index 33a69bf..6bb84649 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
@@ -369,12 +369,6 @@
@Keep
val WM_BUBBLE_BAR = sysPropBooleanFlag("persist.wm.debug.bubble_bar", default = false)
- // TODO(b/260271148): Tracking bug
- @Keep
- @JvmField
- val WM_DESKTOP_WINDOWING_2 =
- sysPropBooleanFlag("persist.wm.debug.desktop_mode_2", default = false)
-
// TODO(b/254513207): Tracking Bug to delete
@Keep
@JvmField
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
index 9fc3692..6aed944 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
@@ -31,8 +31,8 @@
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.FlowPreview
-import kotlinx.coroutines.flow.sample
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@SysUISingleton
@@ -62,7 +62,6 @@
listenForTransitionToCamera(scope, keyguardInteractor)
}
- @FlowPreview
private fun listenForAlternateBouncerToLockscreenHubAodOrDozing() {
scope.launch {
keyguardInteractor.alternateBouncerShowing
@@ -71,7 +70,7 @@
// happening prematurely.
// This should eventually be removed in favor of
// [KeyguardTransitionInteractor#startDismissKeyguardTransition]
- .sample(150L)
+ .onEach { delay(150L) }
.sampleCombine(
keyguardInteractor.primaryBouncerShowing,
startedKeyguardTransitionStep,
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
index 7263ae9..cb1571e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
@@ -44,6 +44,7 @@
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
@@ -287,7 +288,7 @@
if (KeyguardWmStateRefactor.isEnabled) {
// When the refactor is enabled, we no longer use isKeyguardGoingAway.
scope.launch {
- swipeToDismissInteractor.dismissFling.collect { _ ->
+ swipeToDismissInteractor.dismissFling.filterNotNull().collect { _ ->
startTransitionTo(KeyguardState.GONE)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
index d1fd719..37b331c 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
@@ -35,6 +35,7 @@
import com.android.systemui.keyguard.shared.model.KeyguardState.PRIMARY_BOUNCER
import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.util.kotlin.pairwise
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -45,8 +46,8 @@
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
-import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.shareIn
+import kotlinx.coroutines.flow.stateIn
/** Encapsulates business-logic related to the keyguard transitions. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -177,10 +178,16 @@
* Lockscreen (0f).
*/
val dozeAmountTransition: Flow<TransitionStep> =
- merge(
- aodToLockscreenTransition.map { step -> step.copy(value = 1f - step.value) },
- lockscreenToAodTransition,
- )
+ repository.transitions
+ .filter { step -> step.from == AOD || step.to == AOD }
+ .map { step ->
+ if (step.from == AOD) {
+ step.copy(value = 1 - step.value)
+ } else {
+ step
+ }
+ }
+ .shareIn(scope, SharingStarted.Eagerly, replay = 1)
/** The last [TransitionStep] with a [TransitionState] of STARTED */
val startedKeyguardTransitionStep: Flow<TransitionStep> =
@@ -201,6 +208,21 @@
.shareIn(scope, SharingStarted.Eagerly, replay = 1)
/**
+ * A pair of the most recent STARTED step, and the transition step immediately preceding it. The
+ * transition framework enforces that the previous step is either a CANCELED or FINISHED step,
+ * and that the previous step was *to* the state the STARTED step is *from*.
+ *
+ * This flow can be used to access the previous step to determine whether it was CANCELED or
+ * FINISHED. In the case of a CANCELED step, we can also figure out which state we were coming
+ * from when we were canceled.
+ */
+ val startedStepWithPrecedingStep =
+ transitions
+ .pairwise()
+ .filter { it.newValue.transitionState == TransitionState.STARTED }
+ .stateIn(scope, SharingStarted.Eagerly, null)
+
+ /**
* The last [KeyguardState] to which we [TransitionState.FINISHED] a transition.
*
* WARNING: This will NOT emit a value if a transition is CANCELED, and will also not emit a
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt
index b81793e..cff74b3 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt
@@ -19,7 +19,9 @@
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.keyguard.shared.model.BiometricUnlockModel
import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.statusbar.notification.domain.interactor.NotificationLaunchAnimationInteractor
+import com.android.systemui.util.kotlin.sample
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
@@ -121,19 +123,27 @@
* want to know if the AOD/clock/notifs/etc. are visible.
*/
val lockscreenVisibility: Flow<Boolean> =
- combine(
- transitionInteractor.startedKeyguardTransitionStep,
- transitionInteractor.finishedKeyguardState,
- ) { startedStep, finishedState ->
- // If we finished the transition, use the finished state. If we're running a
- // transition, use the state we're transitioning FROM. This can be different from
- // the last finished state if a transition is interrupted. For example, if we were
- // transitioning from GONE to AOD and then started AOD -> LOCKSCREEN mid-transition,
- // we want to immediately use the visibility for AOD (lockscreenVisibility=true)
- // even though the lastFinishedState is still GONE (lockscreenVisibility=false).
- if (finishedState == startedStep.to) finishedState else startedStep.from
+ transitionInteractor.currentKeyguardState
+ .sample(transitionInteractor.startedStepWithPrecedingStep, ::Pair)
+ .map { (currentState, startedWithPrev) ->
+ val startedFromStep = startedWithPrev?.previousValue
+ val startedStep = startedWithPrev?.newValue
+ val returningToGoneAfterCancellation =
+ startedStep?.to == KeyguardState.GONE &&
+ startedFromStep?.transitionState == TransitionState.CANCELED &&
+ startedFromStep.from == KeyguardState.GONE
+
+ if (!returningToGoneAfterCancellation) {
+ // By default, apply the lockscreen visibility of the current state.
+ KeyguardState.lockscreenVisibleInState(currentState)
+ } else {
+ // If we're transitioning to GONE after a prior canceled transition from GONE,
+ // then this is the camera launch transition from an asleep state back to GONE.
+ // We don't want to show the lockscreen since we're aborting the lock and going
+ // back to GONE.
+ KeyguardState.lockscreenVisibleInState(KeyguardState.GONE)
+ }
}
- .map(KeyguardState::lockscreenVisibleInState)
.distinctUntilChanged()
/**
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodAlphaViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodAlphaViewModel.kt
index 8a3b57b..5741b94 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodAlphaViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodAlphaViewModel.kt
@@ -29,7 +29,6 @@
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combineTransform
-import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.onStart
/** Models UI state for the alpha of the AOD (always-on display). */
@@ -46,24 +45,23 @@
/** The alpha level for the entire lockscreen while in AOD. */
val alpha: Flow<Float> =
combineTransform(
- keyguardTransitionInteractor.transitions,
- goneToAodTransitionViewModel.enterFromTopAnimationAlpha.onStart { emit(0f) },
- goneToDozingTransitionViewModel.lockscreenAlpha.onStart { emit(0f) },
- keyguardInteractor.keyguardAlpha.onStart { emit(1f) },
- ) { step, goneToAodAlpha, goneToDozingAlpha, keyguardAlpha ->
- if (step.to == GONE) {
- // When transitioning to GONE, only emit a value when complete as other
- // transitions may be controlling the alpha fade
- if (step.value == 1f) {
- emit(0f)
- }
- } else if (step.from == GONE && step.to == AOD) {
- emit(goneToAodAlpha)
- } else if (step.from == GONE && step.to == DOZING) {
- emit(goneToDozingAlpha)
- } else if (!migrateClocksToBlueprint()) {
- emit(keyguardAlpha)
+ keyguardTransitionInteractor.transitions,
+ goneToAodTransitionViewModel.enterFromTopAnimationAlpha.onStart { emit(0f) },
+ goneToDozingTransitionViewModel.lockscreenAlpha.onStart { emit(0f) },
+ keyguardInteractor.keyguardAlpha.onStart { emit(1f) },
+ ) { step, goneToAodAlpha, goneToDozingAlpha, keyguardAlpha ->
+ if (step.to == GONE) {
+ // When transitioning to GONE, only emit a value when complete as other
+ // transitions may be controlling the alpha fade
+ if (step.value == 1f) {
+ emit(0f)
}
+ } else if (step.from == GONE && step.to == AOD) {
+ emit(goneToAodAlpha)
+ } else if (step.from == GONE && step.to == DOZING) {
+ emit(goneToDozingAlpha)
+ } else if (!migrateClocksToBlueprint()) {
+ emit(keyguardAlpha)
}
- .distinctUntilChanged()
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodBurnInViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodBurnInViewModel.kt
index 8665aab..7be390a 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodBurnInViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AodBurnInViewModel.kt
@@ -28,10 +28,6 @@
import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
import com.android.systemui.keyguard.shared.model.BurnInModel
-import com.android.systemui.keyguard.shared.model.KeyguardState.ALTERNATE_BOUNCER
-import com.android.systemui.keyguard.shared.model.KeyguardState.AOD
-import com.android.systemui.keyguard.shared.model.KeyguardState.GONE
-import com.android.systemui.keyguard.shared.model.KeyguardState.PRIMARY_BOUNCER
import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionState.RUNNING
import com.android.systemui.keyguard.shared.model.TransitionState.STARTED
@@ -47,7 +43,6 @@
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onStart
/**
@@ -127,17 +122,9 @@
params: BurnInParameters,
): Flow<BurnInModel> {
return combine(
- merge(
- keyguardTransitionInteractor.transition(GONE, AOD).map { it.value },
- keyguardTransitionInteractor.transition(AOD, PRIMARY_BOUNCER).map {
- 1f - it.value
- },
- keyguardTransitionInteractor.transition(ALTERNATE_BOUNCER, AOD).map {
- it.value
- },
- keyguardTransitionInteractor.dozeAmountTransition.map { it.value },
- )
- .map { dozeAmount -> Interpolators.FAST_OUT_SLOW_IN.getInterpolation(dozeAmount) },
+ keyguardTransitionInteractor.dozeAmountTransition.map {
+ Interpolators.FAST_OUT_SLOW_IN.getInterpolation(it.value)
+ },
burnInInteractor.keyguardBurnIn,
) { interpolated, burnIn ->
val useScaleOnly =
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
index 921eb66..bdcaf09 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
@@ -74,6 +74,10 @@
private val dozingToLockscreenTransitionViewModel: DozingToLockscreenTransitionViewModel,
private val glanceableHubToLockscreenTransitionViewModel:
GlanceableHubToLockscreenTransitionViewModel,
+ private val goneToAodTransitionViewModel: GoneToAodTransitionViewModel,
+ private val goneToDozingTransitionViewModel: GoneToDozingTransitionViewModel,
+ private val lockscreenToAodTransitionViewModel: LockscreenToAodTransitionViewModel,
+ private val lockscreenToDozingTransitionViewModel: LockscreenToDozingTransitionViewModel,
private val lockscreenToDreamingTransitionViewModel: LockscreenToDreamingTransitionViewModel,
private val lockscreenToGlanceableHubTransitionViewModel:
LockscreenToGlanceableHubTransitionViewModel,
@@ -133,17 +137,24 @@
fun alpha(viewState: ViewStateAccessor): Flow<Float> {
return combine(
communalInteractor.isIdleOnCommunal,
- keyguardTransitionInteractor.transitionValue(GONE).onStart { emit(0f) },
+ keyguardTransitionInteractor
+ .transitionValue(GONE)
+ .map { it == 1f }
+ .onStart { emit(false) }
+ .distinctUntilChanged(),
// The transitions are mutually exclusive, so they are safe to merge to get the last
// value emitted by any of them. Do not add flows that cannot make this guarantee.
merge(
- aodAlphaViewModel.alpha,
alphaOnShadeExpansion,
keyguardInteractor.dismissAlpha.filterNotNull(),
alternateBouncerToGoneTransitionViewModel.lockscreenAlpha,
aodToLockscreenTransitionViewModel.lockscreenAlpha(viewState),
dozingToLockscreenTransitionViewModel.lockscreenAlpha,
glanceableHubToLockscreenTransitionViewModel.keyguardAlpha,
+ goneToAodTransitionViewModel.enterFromTopAnimationAlpha,
+ goneToDozingTransitionViewModel.lockscreenAlpha,
+ lockscreenToAodTransitionViewModel.lockscreenAlpha(viewState),
+ lockscreenToDozingTransitionViewModel.lockscreenAlpha,
lockscreenToDreamingTransitionViewModel.lockscreenAlpha,
lockscreenToGlanceableHubTransitionViewModel.keyguardAlpha,
lockscreenToGoneTransitionViewModel.lockscreenAlpha(viewState),
@@ -156,8 +167,8 @@
primaryBouncerToLockscreenTransitionViewModel.lockscreenAlpha,
)
.onStart { emit(1f) }
- ) { isIdleOnCommunal, goneValue, alpha ->
- if (isIdleOnCommunal || goneValue == 1f) {
+ ) { isIdleOnCommunal, gone, alpha ->
+ if (isIdleOnCommunal || gone) {
// Keyguard should not show while the communal hub is fully visible. This check
// is added since at the moment, closing the notification shade will cause the
// keyguard alpha to be set back to 1. Also ensure keyguard is never visible
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
index d792889..23320be 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
@@ -23,6 +23,7 @@
import com.android.systemui.keyguard.domain.interactor.KeyguardBlueprintInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardClockInteractor
import com.android.systemui.res.R
+import com.android.systemui.statusbar.policy.SplitShadeStateController
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
@@ -39,6 +40,7 @@
private val interactor: KeyguardBlueprintInteractor,
private val authController: AuthController,
val longPress: KeyguardLongPressViewModel,
+ val splitShadeStateController: SplitShadeStateController,
) {
private val clockSize = clockInteractor.clockSize
@@ -46,8 +48,10 @@
get() = authController.isUdfpsSupported
val isLargeClockVisible: Boolean
get() = clockSize.value == KeyguardClockSwitch.LARGE
- val areNotificationsVisible: Boolean
- get() = !isLargeClockVisible
+ fun areNotificationsVisible(resources: Resources): Boolean {
+ return !isLargeClockVisible ||
+ splitShadeStateController.shouldUseSplitNotificationShade(resources)
+ }
fun getSmartSpacePaddingTop(resources: Resources): Int {
return if (isLargeClockVisible) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModel.kt
index 7bf51a7..1f9f304 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToAodTransitionViewModel.kt
@@ -16,6 +16,7 @@
package com.android.systemui.keyguard.ui.viewmodel
+import android.util.MathUtils
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.deviceentry.domain.interactor.DeviceEntryUdfpsInteractor
import com.android.systemui.keyguard.domain.interactor.FromLockscreenTransitionInteractor
@@ -67,6 +68,15 @@
onCancel = { 1f },
)
+ fun lockscreenAlpha(viewState: ViewStateAccessor): Flow<Float> {
+ var startAlpha = 1f
+ return transitionAnimation.sharedFlow(
+ duration = 500.milliseconds,
+ onStart = { startAlpha = viewState.alpha() },
+ onStep = { MathUtils.lerp(startAlpha, 1f, it) },
+ )
+ }
+
override val deviceEntryParentViewAlpha: Flow<Float> =
deviceEntryUdfpsInteractor.isUdfpsEnrolledAndEnabled.flatMapLatest {
isUdfpsEnrolledAndEnabled ->
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModel.kt
index b60c52b..c836f01 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToDozingTransitionViewModel.kt
@@ -44,6 +44,14 @@
to = KeyguardState.DOZING,
)
+ val lockscreenAlpha: Flow<Float> =
+ transitionAnimation.sharedFlow(
+ duration = 250.milliseconds,
+ onStep = { 1 - it },
+ onFinish = { 1f },
+ onCancel = { 1f },
+ )
+
val shortcutsAlpha: Flow<Float> =
transitionAnimation.sharedFlow(
duration = 250.milliseconds,
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/MediaCarouselViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/MediaCarouselViewModel.kt
new file mode 100644
index 0000000..027a739
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/MediaCarouselViewModel.kt
@@ -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 com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.systemui.media.controls.domain.pipeline.MediaDataManager
+import javax.inject.Inject
+
+class MediaCarouselViewModel @Inject constructor(mediaDataManager: MediaDataManager) {
+ val isMediaVisible: Boolean = mediaDataManager.hasActiveMediaOrRecommendation()
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModel.kt
index 378ce52..53f4488 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToGoneTransitionViewModel.kt
@@ -60,6 +60,22 @@
private var leaveShadeOpen: Boolean = false
private var willRunDismissFromKeyguard: Boolean = false
+ val notificationAlpha: Flow<Float> =
+ transitionAnimation.sharedFlow(
+ duration = 200.milliseconds,
+ onStart = {
+ leaveShadeOpen = statusBarStateController.leaveOpenOnKeyguardHide()
+ willRunDismissFromKeyguard = primaryBouncerInteractor.willRunDismissFromKeyguard()
+ },
+ onStep = {
+ if (willRunDismissFromKeyguard || leaveShadeOpen) {
+ 1f
+ } else {
+ 1f - it
+ }
+ },
+ )
+
/** Bouncer container alpha */
val bouncerAlpha: Flow<Float> =
if (featureFlags.isEnabled(Flags.REFACTOR_KEYGUARD_DISMISS_INTENT)) {
@@ -94,6 +110,7 @@
} else {
createLockscreenAlpha(primaryBouncerInteractor::willRunDismissFromKeyguard)
}
+
private fun createLockscreenAlpha(willRunAnimationOnKeyguard: () -> Boolean): Flow<Float> {
return transitionAnimation.sharedFlow(
duration = 50.milliseconds,
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/MediaDataManager.kt b/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/MediaDataManager.kt
index 6fc22ea..865c49e 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/MediaDataManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/MediaDataManager.kt
@@ -17,6 +17,7 @@
package com.android.systemui.media.controls.domain.pipeline
import android.annotation.SuppressLint
+import android.app.ActivityOptions
import android.app.BroadcastOptions
import android.app.Notification
import android.app.Notification.EXTRA_SUBSTITUTE_APP_NAME
@@ -1272,7 +1273,7 @@
val options = BroadcastOptions.makeBasic()
options.setInteractive(true)
options.setPendingIntentBackgroundActivityStartMode(
- BroadcastOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
)
intent.send(options.toBundle())
true
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaControlsRefactorFlag.kt b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaControlsRefactorFlag.kt
new file mode 100644
index 0000000..2850b4b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaControlsRefactorFlag.kt
@@ -0,0 +1,53 @@
+/*
+ * 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.media.controls.util
+
+import com.android.systemui.Flags
+import com.android.systemui.flags.FlagToken
+import com.android.systemui.flags.RefactorFlagUtils
+
+/** Helper for reading or using the media_controls_refactor flag state. */
+@Suppress("NOTHING_TO_INLINE")
+object MediaControlsRefactorFlag {
+ /** The aconfig flag name */
+ const val FLAG_NAME = Flags.FLAG_MEDIA_CONTROLS_REFACTOR
+
+ /** A token used for dependency declaration */
+ val token: FlagToken
+ get() = FlagToken(FLAG_NAME, isEnabled)
+
+ /** Is the flag enabled? */
+ @JvmStatic
+ inline val isEnabled
+ get() = Flags.mediaControlsRefactor()
+
+ /**
+ * Called to ensure code is only run when the flag is enabled. This protects users from the
+ * unintended behaviors caused by accidentally running new logic, while also crashing on an eng
+ * build to ensure that the refactor author catches issues in testing.
+ */
+ @JvmStatic
+ inline fun isUnexpectedlyInLegacyMode() =
+ RefactorFlagUtils.isUnexpectedlyInLegacyMode(isEnabled, FLAG_NAME)
+
+ /**
+ * Called to ensure code is only run when the flag is disabled. This will throw an exception if
+ * the flag is enabled to ensure that the refactor author catches issues in testing.
+ */
+ @JvmStatic
+ inline fun assertInLegacyMode() = RefactorFlagUtils.assertInLegacyMode(isEnabled, FLAG_NAME)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaFlags.kt b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaFlags.kt
index 15747b9..d4bd6da 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaFlags.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaFlags.kt
@@ -58,4 +58,7 @@
/** Check whether to use scene framework */
fun isSceneContainerEnabled() =
sceneContainerFlags.isEnabled() && MediaInSceneContainerFlag.isEnabled
+
+ /** Check whether to use media refactor code */
+ fun isMediaControlsRefactorEnabled() = MediaControlsRefactorFlag.isEnabled
}
diff --git a/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt b/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
index a811065..e1741c7 100644
--- a/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
@@ -18,7 +18,7 @@
import android.app.ActivityOptions
import android.app.ActivityOptions.LaunchCookie
-import android.app.ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
+import android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
import android.app.IActivityTaskManager
import android.graphics.Rect
import android.view.LayoutInflater
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegate.kt
similarity index 67%
rename from packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt
rename to packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegate.kt
index 6b53c7a..7ece6e0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegate.kt
@@ -37,11 +37,13 @@
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.internal.logging.UiEventLogger
-import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.res.R
import com.android.systemui.statusbar.phone.SystemUIDialog
import com.android.systemui.util.time.SystemClock
+import dagger.assisted.Assisted
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
@@ -52,19 +54,24 @@
import kotlinx.coroutines.withContext
/** Dialog for showing active, connected and saved bluetooth devices. */
-@SysUISingleton
-internal class BluetoothTileDialog
-constructor(
- private val bluetoothToggleInitialValue: Boolean,
- private val initialUiProperties: BluetoothTileDialogViewModel.UiProperties,
- private val cachedContentHeight: Int,
- private val bluetoothTileDialogCallback: BluetoothTileDialogCallback,
+class BluetoothTileDialogDelegate
+@AssistedInject
+internal constructor(
+ @Assisted private val context: Context,
+ @Assisted private val initialUiProperties: BluetoothTileDialogViewModel.UiProperties,
+ @Assisted private val cachedContentHeight: Int,
+ @Assisted private val bluetoothToggleInitialValue: Boolean,
+ @Assisted private val bluetoothTileDialogCallback: BluetoothTileDialogCallback,
+ @Assisted private val dismissListener: Runnable,
@Main private val mainDispatcher: CoroutineDispatcher,
private val systemClock: SystemClock,
private val uiEventLogger: UiEventLogger,
private val logger: BluetoothTileDialogLogger,
- context: Context,
-) : SystemUIDialog(context, DEFAULT_THEME, DEFAULT_DISMISS_ON_DEVICE_LOCK) {
+ private val systemuiDialogFactory: SystemUIDialog.Factory,
+ mainLayoutInflater: LayoutInflater,
+) : SystemUIDialog.Delegate {
+
+ private val layoutInflater = mainLayoutInflater.cloneInContext(context)
private val mutableBluetoothStateToggle: MutableStateFlow<Boolean> =
MutableStateFlow(bluetoothToggleInitialValue)
@@ -91,78 +98,72 @@
private var lastItemRow: Int = -1
- private lateinit var toggleView: Switch
- private lateinit var subtitleTextView: TextView
- private lateinit var autoOnToggle: Switch
- private lateinit var autoOnToggleView: View
- private lateinit var doneButton: View
- private lateinit var seeAllButton: View
- private lateinit var pairNewDeviceButton: View
- private lateinit var deviceListView: RecyclerView
- private lateinit var scrollViewContent: View
- private lateinit var progressBarAnimation: ProgressBar
- private lateinit var progressBarBackground: View
+ @AssistedFactory
+ internal interface Factory {
+ fun create(
+ context: Context,
+ initialUiProperties: BluetoothTileDialogViewModel.UiProperties,
+ cachedContentHeight: Int,
+ bluetoothEnabled: Boolean,
+ dialogCallback: BluetoothTileDialogCallback,
+ dimissListener: Runnable
+ ): BluetoothTileDialogDelegate
+ }
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
+ override fun createDialog(): SystemUIDialog {
+ val dialog = systemuiDialogFactory.create(this, context)
+
+ return dialog
+ }
+
+ override fun onCreate(dialog: SystemUIDialog, savedInstanceState: Bundle?) {
+ SystemUIDialog.registerDismissListener(dialog, dismissListener)
uiEventLogger.log(BluetoothTileDialogUiEvent.BLUETOOTH_TILE_DIALOG_SHOWN)
- LayoutInflater.from(context).inflate(R.layout.bluetooth_tile_dialog, null).apply {
+ layoutInflater.inflate(R.layout.bluetooth_tile_dialog, null).apply {
accessibilityPaneTitle = context.getText(R.string.accessibility_desc_quick_settings)
- setContentView(this)
+ dialog.setContentView(this)
}
- toggleView = requireViewById(R.id.bluetooth_toggle)
- subtitleTextView = requireViewById(R.id.bluetooth_tile_dialog_subtitle) as TextView
- autoOnToggle = requireViewById(R.id.bluetooth_auto_on_toggle)
- autoOnToggleView = requireViewById(R.id.bluetooth_auto_on_toggle_layout)
- doneButton = requireViewById(R.id.done_button)
- seeAllButton = requireViewById(R.id.see_all_button)
- pairNewDeviceButton = requireViewById(R.id.pair_new_device_button)
- deviceListView = requireViewById<RecyclerView>(R.id.device_list)
+ setupToggle(dialog)
+ setupRecyclerView(dialog)
- setupToggle()
- setupRecyclerView()
-
- subtitleTextView.text = context.getString(initialUiProperties.subTitleResId)
- doneButton.setOnClickListener { dismiss() }
- seeAllButton.setOnClickListener { bluetoothTileDialogCallback.onSeeAllClicked(it) }
- pairNewDeviceButton.setOnClickListener {
+ getSubtitleTextView(dialog).text = context.getString(initialUiProperties.subTitleResId)
+ dialog.requireViewById<View>(R.id.done_button).setOnClickListener { dialog.dismiss() }
+ getSeeAllButton(dialog).setOnClickListener {
+ bluetoothTileDialogCallback.onSeeAllClicked(it)
+ }
+ getPairNewDeviceButton(dialog).setOnClickListener {
bluetoothTileDialogCallback.onPairNewDeviceClicked(it)
}
- requireViewById<View>(R.id.scroll_view).apply {
- scrollViewContent = this
+ getScrollViewContent(dialog).apply {
minimumHeight =
resources.getDimensionPixelSize(initialUiProperties.scrollViewMinHeightResId)
layoutParams.height = maxOf(cachedContentHeight, minimumHeight)
}
- progressBarAnimation = requireViewById(R.id.bluetooth_tile_dialog_progress_animation)
- progressBarBackground = requireViewById(R.id.bluetooth_tile_dialog_progress_background)
}
- override fun start() {
+ override fun onStart(dialog: SystemUIDialog) {
lastUiUpdateMs = systemClock.elapsedRealtime()
}
- override fun dismiss() {
- if (::scrollViewContent.isInitialized) {
- mutableContentHeight.tryEmit(scrollViewContent.measuredHeight)
- }
- super.dismiss()
+ override fun onStop(dialog: SystemUIDialog) {
+ mutableContentHeight.tryEmit(getScrollViewContent(dialog).measuredHeight)
}
- internal suspend fun animateProgressBar(animate: Boolean) {
+ internal suspend fun animateProgressBar(dialog: SystemUIDialog, animate: Boolean) {
withContext(mainDispatcher) {
if (animate) {
- showProgressBar()
+ showProgressBar(dialog)
} else {
delay(PROGRESS_BAR_ANIMATION_DURATION_MS)
- hideProgressBar()
+ hideProgressBar(dialog)
}
}
}
internal suspend fun onDeviceItemUpdated(
+ dialog: SystemUIDialog,
deviceItem: List<DeviceItem>,
showSeeAll: Boolean,
showPairNewDevice: Boolean
@@ -176,10 +177,11 @@
}
if (isActive) {
deviceItemAdapter.refreshDeviceItemList(deviceItem) {
- seeAllButton.visibility = if (showSeeAll) VISIBLE else GONE
- pairNewDeviceButton.visibility = if (showPairNewDevice) VISIBLE else GONE
+ getSeeAllButton(dialog).visibility = if (showSeeAll) VISIBLE else GONE
+ getPairNewDeviceButton(dialog).visibility =
+ if (showPairNewDevice) VISIBLE else GONE
// Update the height after data is updated
- scrollViewContent.layoutParams.height = WRAP_CONTENT
+ getScrollViewContent(dialog).layoutParams.height = WRAP_CONTENT
lastUiUpdateMs = systemClock.elapsedRealtime()
lastItemRow = itemRow
logger.logDeviceUiUpdate(lastUiUpdateMs - start)
@@ -189,29 +191,29 @@
}
internal fun onBluetoothStateUpdated(
+ dialog: SystemUIDialog,
isEnabled: Boolean,
uiProperties: BluetoothTileDialogViewModel.UiProperties
) {
- toggleView.apply {
+ getToggleView(dialog).apply {
isChecked = isEnabled
setEnabled(true)
alpha = ENABLED_ALPHA
}
- subtitleTextView.text = context.getString(uiProperties.subTitleResId)
- autoOnToggleView.visibility = uiProperties.autoOnToggleVisibility
+ getSubtitleTextView(dialog).text = context.getString(uiProperties.subTitleResId)
+ getAutoOnToggleView(dialog).visibility = uiProperties.autoOnToggleVisibility
}
- internal fun onBluetoothAutoOnUpdated(isEnabled: Boolean) {
- if (::autoOnToggle.isInitialized) {
- autoOnToggle.apply {
- isChecked = isEnabled
- setEnabled(true)
- alpha = ENABLED_ALPHA
- }
+ internal fun onBluetoothAutoOnUpdated(dialog: SystemUIDialog, isEnabled: Boolean) {
+ getAutoOnToggle(dialog).apply {
+ isChecked = isEnabled
+ setEnabled(true)
+ alpha = ENABLED_ALPHA
}
}
- private fun setupToggle() {
+ private fun setupToggle(dialog: SystemUIDialog) {
+ val toggleView = getToggleView(dialog)
toggleView.isChecked = bluetoothToggleInitialValue
toggleView.setOnCheckedChangeListener { view, isChecked ->
mutableBluetoothStateToggle.value = isChecked
@@ -223,8 +225,8 @@
uiEventLogger.log(BluetoothTileDialogUiEvent.BLUETOOTH_TOGGLE_CLICKED)
}
- autoOnToggleView.visibility = initialUiProperties.autoOnToggleVisibility
- autoOnToggle.setOnCheckedChangeListener { view, isChecked ->
+ getAutoOnToggleView(dialog).visibility = initialUiProperties.autoOnToggleVisibility
+ getAutoOnToggle(dialog).setOnCheckedChangeListener { view, isChecked ->
mutableBluetoothAutoOnToggle.value = isChecked
view.apply {
isEnabled = false
@@ -234,30 +236,66 @@
}
}
- private fun setupRecyclerView() {
- deviceListView.apply {
+ private fun getToggleView(dialog: SystemUIDialog): Switch {
+ return dialog.requireViewById(R.id.bluetooth_toggle)
+ }
+
+ private fun getSubtitleTextView(dialog: SystemUIDialog): TextView {
+ return dialog.requireViewById(R.id.bluetooth_tile_dialog_subtitle)
+ }
+
+ private fun getSeeAllButton(dialog: SystemUIDialog): View {
+ return dialog.requireViewById(R.id.see_all_button)
+ }
+
+ private fun getPairNewDeviceButton(dialog: SystemUIDialog): View {
+ return dialog.requireViewById(R.id.pair_new_device_button)
+ }
+
+ private fun getDeviceListView(dialog: SystemUIDialog): RecyclerView {
+ return dialog.requireViewById(R.id.device_list)
+ }
+
+ private fun getAutoOnToggle(dialog: SystemUIDialog): Switch {
+ return dialog.requireViewById(R.id.bluetooth_auto_on_toggle)
+ }
+
+ private fun getAutoOnToggleView(dialog: SystemUIDialog): View {
+ return dialog.requireViewById(R.id.bluetooth_auto_on_toggle_layout)
+ }
+
+ private fun getProgressBarAnimation(dialog: SystemUIDialog): ProgressBar {
+ return dialog.requireViewById(R.id.bluetooth_tile_dialog_progress_animation)
+ }
+
+ private fun getProgressBarBackground(dialog: SystemUIDialog): View {
+ return dialog.requireViewById(R.id.bluetooth_tile_dialog_progress_animation)
+ }
+
+ private fun getScrollViewContent(dialog: SystemUIDialog): View {
+ return dialog.requireViewById(R.id.scroll_view)
+ }
+
+ private fun setupRecyclerView(dialog: SystemUIDialog) {
+ getDeviceListView(dialog).apply {
layoutManager = LinearLayoutManager(context)
adapter = deviceItemAdapter
}
}
- private fun showProgressBar() {
- if (
- ::progressBarAnimation.isInitialized &&
- ::progressBarBackground.isInitialized &&
- progressBarAnimation.visibility != VISIBLE
- ) {
+ private fun showProgressBar(dialog: SystemUIDialog) {
+ val progressBarAnimation = getProgressBarAnimation(dialog)
+ val progressBarBackground = getProgressBarBackground(dialog)
+ if (progressBarAnimation.visibility != VISIBLE) {
progressBarAnimation.visibility = VISIBLE
progressBarBackground.visibility = INVISIBLE
}
}
- private fun hideProgressBar() {
- if (
- ::progressBarAnimation.isInitialized &&
- ::progressBarBackground.isInitialized &&
- progressBarAnimation.visibility != INVISIBLE
- ) {
+ private fun hideProgressBar(dialog: SystemUIDialog) {
+ val progressBarAnimation = getProgressBarAnimation(dialog)
+ val progressBarBackground = getProgressBarBackground(dialog)
+ if (progressBarAnimation.visibility != INVISIBLE) {
progressBarAnimation.visibility = INVISIBLE
progressBarBackground.visibility = VISIBLE
}
@@ -295,9 +333,7 @@
private val asyncListDiffer = AsyncListDiffer(this, diffUtilCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceItemViewHolder {
- val view =
- LayoutInflater.from(parent.context)
- .inflate(R.layout.bluetooth_device_item, parent, false)
+ val view = layoutInflater.inflate(R.layout.bluetooth_device_item, parent, false)
return DeviceItemViewHolder(view)
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
index 5a14e5f..0486207 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
@@ -38,13 +38,11 @@
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.plugins.ActivityStarter
-import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialog.Companion.ACTION_BLUETOOTH_DEVICE_DETAILS
-import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialog.Companion.ACTION_PAIR_NEW_DEVICE
-import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialog.Companion.ACTION_PREVIOUSLY_CONNECTED_DEVICE
-import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialog.Companion.MAX_DEVICE_ITEM_ENTRY
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialogDelegate.Companion.ACTION_BLUETOOTH_DEVICE_DETAILS
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialogDelegate.Companion.ACTION_PAIR_NEW_DEVICE
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialogDelegate.Companion.ACTION_PREVIOUSLY_CONNECTED_DEVICE
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothTileDialogDelegate.Companion.MAX_DEVICE_ITEM_ENTRY
import com.android.systemui.res.R
-import com.android.systemui.statusbar.phone.SystemUIDialog
-import com.android.systemui.util.time.SystemClock
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
@@ -67,13 +65,12 @@
private val bluetoothAutoOnInteractor: BluetoothAutoOnInteractor,
private val dialogTransitionAnimator: DialogTransitionAnimator,
private val activityStarter: ActivityStarter,
- private val systemClock: SystemClock,
private val uiEventLogger: UiEventLogger,
- private val logger: BluetoothTileDialogLogger,
@Application private val coroutineScope: CoroutineScope,
@Main private val mainDispatcher: CoroutineDispatcher,
@Background private val backgroundDispatcher: CoroutineDispatcher,
@Main private val sharedPreferences: SharedPreferences,
+ private val bluetoothDialogDelegateFactory: BluetoothTileDialogDelegate.Factory,
) : BluetoothTileDialogCallback {
private var job: Job? = null
@@ -92,7 +89,8 @@
coroutineScope.launch(mainDispatcher) {
var updateDeviceItemJob: Job?
var updateDialogUiJob: Job? = null
- val dialog = createBluetoothTileDialog(context)
+ val dialogDelegate = createBluetoothTileDialog(context)
+ val dialog = dialogDelegate.createDialog()
view?.let {
dialogTransitionAnimator.showFromView(
@@ -118,13 +116,14 @@
.onEach {
updateDialogUiJob?.cancel()
updateDialogUiJob = launch {
- dialog.apply {
+ dialogDelegate.apply {
onDeviceItemUpdated(
+ dialog,
it.take(MAX_DEVICE_ITEM_ENTRY),
showSeeAll = it.size > MAX_DEVICE_ITEM_ENTRY,
showPairNewDevice = bluetoothStateInteractor.isBluetoothEnabled
)
- animateProgressBar(false)
+ animateProgressBar(dialog, false)
}
}
}
@@ -134,7 +133,7 @@
// the device item list and animiate the progress bar.
deviceItemInteractor.deviceItemUpdateRequest
.onEach {
- dialog.animateProgressBar(true)
+ dialogDelegate.animateProgressBar(dialog, true)
updateDeviceItemJob?.cancel()
updateDeviceItemJob = launch {
deviceItemInteractor.updateDeviceItems(
@@ -150,7 +149,8 @@
bluetoothStateInteractor.bluetoothStateUpdate
.filterNotNull()
.onEach {
- dialog.onBluetoothStateUpdated(
+ dialogDelegate.onBluetoothStateUpdated(
+ dialog,
it,
UiProperties.build(it, isAutoOnToggleFeatureAvailable())
)
@@ -166,20 +166,20 @@
// bluetoothStateToggle is emitted when user toggles the bluetooth state switch,
// send the new value to the bluetoothStateInteractor and animate the progress bar.
- dialog.bluetoothStateToggle
+ dialogDelegate.bluetoothStateToggle
.onEach {
- dialog.animateProgressBar(true)
+ dialogDelegate.animateProgressBar(dialog, true)
bluetoothStateInteractor.isBluetoothEnabled = it
}
.launchIn(this)
// deviceItemClick is emitted when user clicked on a device item.
- dialog.deviceItemClick
+ dialogDelegate.deviceItemClick
.onEach { deviceItemInteractor.updateDeviceItemOnClick(it) }
.launchIn(this)
// contentHeight is emitted when the dialog is dismissed.
- dialog.contentHeight
+ dialogDelegate.contentHeight
.onEach {
withContext(backgroundDispatcher) {
sharedPreferences.edit().putInt(CONTENT_HEIGHT_PREF_KEY, it).apply()
@@ -191,12 +191,12 @@
// bluetoothAutoOnUpdate is emitted when bluetooth auto on on/off state is
// changed.
bluetoothAutoOnInteractor.isEnabled
- .onEach { dialog.onBluetoothAutoOnUpdated(it) }
+ .onEach { dialogDelegate.onBluetoothAutoOnUpdated(dialog, it) }
.launchIn(this)
// bluetoothAutoOnToggle is emitted when user toggles the bluetooth auto on
// switch, send the new value to the bluetoothAutoOnInteractor.
- dialog.bluetoothAutoOnToggle
+ dialogDelegate.bluetoothAutoOnToggle
.filterNotNull()
.onEach { bluetoothAutoOnInteractor.setEnabled(it) }
.launchIn(this)
@@ -206,7 +206,7 @@
}
}
- private suspend fun createBluetoothTileDialog(context: Context): BluetoothTileDialog {
+ private suspend fun createBluetoothTileDialog(context: Context): BluetoothTileDialogDelegate {
val cachedContentHeight =
withContext(backgroundDispatcher) {
sharedPreferences.getInt(
@@ -215,21 +215,17 @@
)
}
- return BluetoothTileDialog(
+ return bluetoothDialogDelegateFactory.create(
+ context,
+ UiProperties.build(
bluetoothStateInteractor.isBluetoothEnabled,
- UiProperties.build(
- bluetoothStateInteractor.isBluetoothEnabled,
- isAutoOnToggleFeatureAvailable()
- ),
- cachedContentHeight,
- this@BluetoothTileDialogViewModel,
- mainDispatcher,
- systemClock,
- uiEventLogger,
- logger,
- context
- )
- .apply { SystemUIDialog.registerDismissListener(this) { cancelJob() } }
+ isAutoOnToggleFeatureAvailable()
+ ),
+ cachedContentHeight,
+ bluetoothStateInteractor.isBluetoothEnabled,
+ this@BluetoothTileDialogViewModel,
+ { cancelJob() }
+ )
}
override fun onDeviceItemGearClicked(deviceItem: DeviceItem, view: View) {
@@ -308,7 +304,7 @@
}
}
-internal interface BluetoothTileDialogCallback {
+interface BluetoothTileDialogCallback {
fun onDeviceItemGearClicked(deviceItem: DeviceItem, view: View)
fun onSeeAllClicked(view: View)
fun onPairNewDeviceClicked(view: View)
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index 000f3c09d..5f8b5dd 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -221,7 +221,7 @@
// If scene framework is enabled, set the scene container window to
// visible and let the touch "slip" into that window.
if (mSceneContainerFlags.isEnabled()) {
- mSceneInteractor.get().setVisible(true, "swipe down on launcher");
+ mSceneInteractor.get().onRemoteUserInteractionStarted("launcher swipe");
} else {
mShadeViewControllerLazy.get().startInputFocusTransfer();
}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt b/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
index a302194..e60dff1 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
@@ -49,6 +49,13 @@
private val _isVisible = MutableStateFlow(true)
val isVisible: StateFlow<Boolean> = _isVisible.asStateFlow()
+ /**
+ * Whether there's an ongoing remotely-initiated user interaction.
+ *
+ * For more information see the logic in `SceneInteractor` that mutates this.
+ */
+ val isRemoteUserInteractionOngoing = MutableStateFlow(false)
+
private val defaultTransitionState = ObservableTransitionState.Idle(config.initialSceneKey)
private val _transitionState = MutableStateFlow<Flow<ObservableTransitionState>?>(null)
val transitionState: StateFlow<ObservableTransitionState> =
diff --git a/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt b/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
index 0add444..6b7c672 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
@@ -31,6 +31,7 @@
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
@@ -121,7 +122,21 @@
)
/** Whether the scene container is visible. */
- val isVisible: StateFlow<Boolean> = repository.isVisible
+ val isVisible: StateFlow<Boolean> =
+ combine(
+ repository.isVisible,
+ repository.isRemoteUserInteractionOngoing,
+ ) { isVisible, isRemoteUserInteractionOngoing ->
+ isVisibleInternal(
+ raw = isVisible,
+ isRemoteUserInteractionOngoing = isRemoteUserInteractionOngoing,
+ )
+ }
+ .stateIn(
+ scope = applicationScope,
+ started = SharingStarted.WhileSubscribed(),
+ initialValue = isVisibleInternal()
+ )
/**
* Returns the keys of all scenes in the container.
@@ -164,7 +179,14 @@
repository.changeScene(toScene, transitionKey)
}
- /** Sets the visibility of the container. */
+ /**
+ * Sets the visibility of the container.
+ *
+ * Please do not call this from outside of the scene framework. If you are trying to force the
+ * visibility to visible or invisible, prefer making changes to the existing caller of this
+ * method or to upstream state used to calculate [isVisible]; for an example of the latter,
+ * please see [onRemoteUserInteractionStarted] and [onUserInteractionFinished].
+ */
fun setVisible(isVisible: Boolean, loggingReason: String) {
val wasVisible = repository.isVisible.value
if (wasVisible == isVisible) {
@@ -180,6 +202,31 @@
}
/**
+ * Notifies that a remote user interaction has begun.
+ *
+ * This is a user interaction that originates outside of the UI of the scene container and
+ * possibly outside of the System UI process itself.
+ *
+ * As an example, consider the dragging that can happen in the launcher that expands the shade.
+ * This is a user interaction that begins remotely (as it starts in the launcher process) and is
+ * then rerouted by window manager to System UI. While the user interaction definitely continues
+ * within the System UI process and code, it also originates remotely.
+ */
+ fun onRemoteUserInteractionStarted(loggingReason: String) {
+ logger.logRemoteUserInteractionStarted(loggingReason)
+ repository.isRemoteUserInteractionOngoing.value = true
+ }
+
+ /**
+ * Notifies that the current user interaction (internally or remotely started, see
+ * [onRemoteUserInteractionStarted]) has finished.
+ */
+ fun onUserInteractionFinished() {
+ logger.logUserInteractionFinished()
+ repository.isRemoteUserInteractionOngoing.value = false
+ }
+
+ /**
* Binds the given flow so the system remembers it.
*
* Note that you must call is with `null` when the UI is done or risk a memory leak.
@@ -187,4 +234,11 @@
fun setTransitionState(transitionState: Flow<ObservableTransitionState>?) {
repository.setTransitionState(transitionState)
}
+
+ private fun isVisibleInternal(
+ raw: Boolean = repository.isVisible.value,
+ isRemoteUserInteractionOngoing: Boolean = repository.isRemoteUserInteractionOngoing.value,
+ ): Boolean {
+ return raw || isRemoteUserInteractionOngoing
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
index d59fcff..cbf7b3e 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
@@ -95,6 +95,26 @@
)
}
+ fun logRemoteUserInteractionStarted(
+ reason: String,
+ ) {
+ logBuffer.log(
+ tag = TAG,
+ level = LogLevel.INFO,
+ messageInitializer = { str1 = reason },
+ messagePrinter = { "remote user interaction started, reason: $str3" },
+ )
+ }
+
+ fun logUserInteractionFinished() {
+ logBuffer.log(
+ tag = TAG,
+ level = LogLevel.INFO,
+ messageInitializer = {},
+ messagePrinter = { "user interaction finished" },
+ )
+ }
+
companion object {
private const val TAG = "SceneFramework"
}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
index 4cd3baa..91861aa 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
@@ -68,6 +68,12 @@
fun onMotionEvent(event: MotionEvent) {
powerInteractor.onUserTouch()
falsingInteractor.onTouchEvent(event)
+ if (
+ event.actionMasked == MotionEvent.ACTION_UP ||
+ event.actionMasked == MotionEvent.ACTION_CANCEL
+ ) {
+ sceneInteractor.onUserInteractionFinished()
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
index fb5339d..1f9853b 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
@@ -16,6 +16,8 @@
package com.android.systemui.screenshot
+import android.app.ActivityOptions
+import android.app.ExitTransitionCoordinator
import android.content.Context
import android.content.Intent
import android.os.Bundle
@@ -23,6 +25,7 @@
import android.os.RemoteException
import android.os.UserHandle
import android.util.Log
+import android.util.Pair
import android.view.IRemoteAnimationFinishedCallback
import android.view.IRemoteAnimationRunner
import android.view.RemoteAnimationAdapter
@@ -64,18 +67,18 @@
*/
fun launchIntentAsync(
intent: Intent,
- options: Bundle?,
+ transition: Pair<ActivityOptions, ExitTransitionCoordinator>?,
user: UserHandle,
overrideTransition: Boolean,
) {
applicationScope.launch("$TAG#launchIntentAsync") {
- launchIntent(intent, options, user, overrideTransition)
+ launchIntent(intent, transition, user, overrideTransition)
}
}
suspend fun launchIntent(
intent: Intent,
- options: Bundle?,
+ transition: Pair<ActivityOptions, ExitTransitionCoordinator>?,
user: UserHandle,
overrideTransition: Boolean,
) {
@@ -87,11 +90,14 @@
} else {
dismissKeyguard()
}
+ transition?.second?.startExit()
if (user == myUserHandle()) {
- withContext(mainDispatcher) { context.startActivity(intent, options) }
+ withContext(mainDispatcher) {
+ context.startActivity(intent, transition?.first?.toBundle())
+ }
} else {
- launchCrossProfileIntent(user, intent, options)
+ launchCrossProfileIntent(user, intent, transition?.first?.toBundle())
}
if (overrideTransition) {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/OverlayActionChip.java b/packages/SystemUI/src/com/android/systemui/screenshot/OverlayActionChip.java
index 0588fe2..30f5e8b 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/OverlayActionChip.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/OverlayActionChip.java
@@ -18,6 +18,7 @@
import static java.util.Objects.requireNonNull;
+import android.app.ActivityOptions;
import android.app.BroadcastOptions;
import android.app.PendingIntent;
import android.content.Context;
@@ -100,7 +101,7 @@
BroadcastOptions options = BroadcastOptions.makeBasic();
options.setInteractive(true);
options.setPendingIntentBackgroundActivityStartMode(
- BroadcastOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
intent.send(options.toBundle());
finisher.run();
} catch (PendingIntent.CanceledException e) {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java b/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
index 31086d8..bbf7ed5 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
@@ -16,40 +16,29 @@
package com.android.systemui.screenshot;
-import static com.android.systemui.screenshot.LogConfig.DEBUG_ACTIONS;
import static com.android.systemui.screenshot.LogConfig.DEBUG_CALLBACK;
import static com.android.systemui.screenshot.LogConfig.DEBUG_STORAGE;
import static com.android.systemui.screenshot.LogConfig.logTag;
import static com.android.systemui.screenshot.ScreenshotNotificationSmartActionsProvider.ScreenshotSmartActionType;
-import android.app.ActivityTaskManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipDescription;
-import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
-import android.content.pm.UserInfo;
-import android.content.res.Resources;
import android.graphics.Bitmap;
-import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
-import android.os.RemoteException;
import android.os.UserHandle;
-import android.os.UserManager;
import android.provider.DeviceConfig;
-import android.text.TextUtils;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
-import com.android.systemui.res.R;
import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.screenshot.ScreenshotController.SavedImageData.ActionTransition;
import com.google.common.util.concurrent.ListenableFuture;
@@ -60,7 +49,6 @@
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
-import java.util.function.Supplier;
/**
* An AsyncTask that saves an image to the media store in the background.
@@ -81,7 +69,6 @@
private final ScreenshotNotificationSmartActionsProvider mSmartActionsProvider;
private String mScreenshotId;
private final Random mRandom = new Random();
- private final Supplier<ActionTransition> mSharedElementTransition;
private final ImageExporter mImageExporter;
private long mImageTime;
@@ -91,7 +78,6 @@
ImageExporter exporter,
ScreenshotSmartActions screenshotSmartActions,
ScreenshotController.SaveImageInBackgroundData data,
- Supplier<ActionTransition> sharedElementTransition,
ScreenshotNotificationSmartActionsProvider
screenshotNotificationSmartActionsProvider
) {
@@ -100,7 +86,6 @@
mScreenshotSmartActions = screenshotSmartActions;
mImageData = new ScreenshotController.SavedImageData();
mQuickShareData = new ScreenshotController.QuickShareData();
- mSharedElementTransition = sharedElementTransition;
mImageExporter = exporter;
// Prepare all the output metadata
@@ -176,12 +161,6 @@
mImageData.uri = uri;
mImageData.owner = mParams.owner;
mImageData.smartActions = smartActions;
- mImageData.shareTransition = createShareAction(mContext, mContext.getResources(), uri,
- smartActionsEnabled);
- mImageData.editTransition = createEditAction(mContext, mContext.getResources(), uri,
- smartActionsEnabled);
- mImageData.deleteAction = createDeleteAction(mContext, mContext.getResources(), uri,
- smartActionsEnabled);
mImageData.quickShareAction = createQuickShareAction(
mQuickShareData.quickShareAction, mScreenshotId, uri, mImageTime, image,
mParams.owner);
@@ -234,164 +213,6 @@
mParams.clearImage();
}
- /**
- * Assumes that the action intent is sent immediately after being supplied.
- */
- @VisibleForTesting
- Supplier<ActionTransition> createShareAction(Context context, Resources r, Uri uri,
- boolean smartActionsEnabled) {
- return () -> {
- ActionTransition transition = mSharedElementTransition.get();
-
- // Note: Both the share and edit actions are proxied through ActionProxyReceiver in
- // order to do some common work like dismissing the keyguard and sending
- // closeSystemWindows
-
- // Create a share intent, this will always go through the chooser activity first
- // which should not trigger auto-enter PiP
- Intent sharingIntent = new Intent(Intent.ACTION_SEND);
- sharingIntent.setDataAndType(uri, "image/png");
- sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
- // Include URI in ClipData also, so that grantPermission picks it up.
- // We don't use setData here because some apps interpret this as "to:".
- ClipData clipdata = new ClipData(new ClipDescription("content",
- new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}),
- new ClipData.Item(uri));
- sharingIntent.setClipData(clipdata);
- sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getSubjectString(mImageTime));
- sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
-
-
- // Make sure pending intents for the system user are still unique across users
- // by setting the (otherwise unused) request code to the current user id.
- int requestCode = context.getUserId();
-
- Intent sharingChooserIntent = Intent.createChooser(sharingIntent, null)
- .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
- .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
-
-
- // cancel current pending intent (if any) since clipData isn't used for matching
- PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
- context, 0, sharingChooserIntent,
- PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
- transition.bundle, UserHandle.CURRENT);
-
- // Create a share action for the notification
- PendingIntent shareAction = PendingIntent.getBroadcastAsUser(context, requestCode,
- new Intent(context, ActionProxyReceiver.class)
- .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, pendingIntent)
- .putExtra(ScreenshotController.EXTRA_DISALLOW_ENTER_PIP, true)
- .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
- .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
- smartActionsEnabled)
- .setAction(Intent.ACTION_SEND)
- .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
- PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
- UserHandle.SYSTEM);
-
- Notification.Action.Builder shareActionBuilder = new Notification.Action.Builder(
- Icon.createWithResource(r, R.drawable.ic_screenshot_share),
- r.getString(com.android.internal.R.string.share), shareAction);
-
- transition.action = shareActionBuilder.build();
- return transition;
- };
- }
-
- @VisibleForTesting
- Supplier<ActionTransition> createEditAction(Context context, Resources r, Uri uri,
- boolean smartActionsEnabled) {
- return () -> {
- ActionTransition transition = mSharedElementTransition.get();
- // Note: Both the share and edit actions are proxied through ActionProxyReceiver in
- // order to do some common work like dismissing the keyguard and sending
- // closeSystemWindows
-
- // Create an edit intent, if a specific package is provided as the editor, then
- // launch that directly
- String editorPackage = context.getString(R.string.config_screenshotEditor);
- Intent editIntent = new Intent(Intent.ACTION_EDIT);
- if (!TextUtils.isEmpty(editorPackage)) {
- editIntent.setComponent(ComponentName.unflattenFromString(editorPackage));
- }
- editIntent.setDataAndType(uri, "image/png");
- editIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
- editIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
- editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
-
- PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
- context, 0, editIntent, PendingIntent.FLAG_IMMUTABLE,
- transition.bundle, UserHandle.CURRENT);
-
- // Make sure pending intents for the system user are still unique across users
- // by setting the (otherwise unused) request code to the current user id.
- int requestCode = mContext.getUserId();
-
- // Create an edit action
- PendingIntent editAction = PendingIntent.getBroadcastAsUser(context, requestCode,
- new Intent(context, ActionProxyReceiver.class)
- .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, pendingIntent)
- .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
- .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
- smartActionsEnabled)
- .putExtra(ScreenshotController.EXTRA_OVERRIDE_TRANSITION, true)
- .setAction(Intent.ACTION_EDIT)
- .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
- PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
- UserHandle.SYSTEM);
- Notification.Action.Builder editActionBuilder = new Notification.Action.Builder(
- Icon.createWithResource(r, R.drawable.ic_screenshot_edit),
- r.getString(com.android.internal.R.string.screenshot_edit), editAction);
-
- transition.action = editActionBuilder.build();
- return transition;
- };
- }
-
- @VisibleForTesting
- Notification.Action createDeleteAction(Context context, Resources r, Uri uri,
- boolean smartActionsEnabled) {
- // Make sure pending intents for the system user are still unique across users
- // by setting the (otherwise unused) request code to the current user id.
- int requestCode = mContext.getUserId();
-
- // Create a delete action for the notification
- PendingIntent deleteAction = PendingIntent.getBroadcast(context, requestCode,
- new Intent(context, DeleteScreenshotReceiver.class)
- .putExtra(ScreenshotController.SCREENSHOT_URI_ID, uri.toString())
- .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
- .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
- smartActionsEnabled)
- .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
- PendingIntent.FLAG_CANCEL_CURRENT
- | PendingIntent.FLAG_ONE_SHOT
- | PendingIntent.FLAG_IMMUTABLE);
- Notification.Action.Builder deleteActionBuilder = new Notification.Action.Builder(
- Icon.createWithResource(r, R.drawable.ic_screenshot_delete),
- r.getString(com.android.internal.R.string.delete), deleteAction);
-
- return deleteActionBuilder.build();
- }
-
- private UserHandle getUserHandleOfForegroundApplication(Context context) {
- UserManager manager = UserManager.get(context);
- int result;
- // This logic matches
- // com.android.systemui.statusbar.phone.PhoneStatusBarPolicy#updateManagedProfile
- try {
- result = ActivityTaskManager.getService().getLastResumedActivityUserId();
- } catch (RemoteException e) {
- if (DEBUG_ACTIONS) {
- Log.d(TAG, "Failed to get UserHandle of foreground app: ", e);
- }
- result = context.getUserId();
- }
- UserInfo userInfo = manager.getUserInfo(result);
- return userInfo.getUserHandle();
- }
-
private List<Notification.Action> buildSmartActions(
List<Notification.Action> actions, Context context) {
List<Notification.Action> broadcastActions = new ArrayList<>();
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
index 21a08a9..ee3e7ba 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
@@ -39,7 +39,6 @@
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.ExitTransitionCoordinator;
-import android.app.ExitTransitionCoordinator.ExitTransitionCallbacks;
import android.app.ICompatCameraControlCallback;
import android.app.Notification;
import android.app.assist.AssistContent;
@@ -54,7 +53,6 @@
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.net.Uri;
-import android.os.Bundle;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -87,13 +85,12 @@
import com.android.internal.logging.UiEventLogger;
import com.android.internal.policy.PhoneWindow;
import com.android.settingslib.applications.InterestingConfigChanges;
-import com.android.systemui.res.R;
import com.android.systemui.broadcast.BroadcastSender;
import com.android.systemui.clipboardoverlay.ClipboardOverlayController;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.flags.Flags;
-import com.android.systemui.screenshot.ScreenshotController.SavedImageData.ActionTransition;
+import com.android.systemui.res.R;
import com.android.systemui.screenshot.TakeScreenshotService.RequestCallback;
import com.android.systemui.util.Assert;
@@ -111,7 +108,6 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import javax.inject.Provider;
@@ -171,31 +167,16 @@
*/
static class SavedImageData {
public Uri uri;
- public Supplier<ActionTransition> shareTransition;
- public Supplier<ActionTransition> editTransition;
- public Notification.Action deleteAction;
public List<Notification.Action> smartActions;
public Notification.Action quickShareAction;
public UserHandle owner;
public String subject; // Title for sharing
/**
- * POD for shared element transition.
- */
- static class ActionTransition {
- public Bundle bundle;
- public Notification.Action action;
- public Runnable onCancelRunnable;
- }
-
- /**
* Used to reset the return data on error
*/
public void reset() {
uri = null;
- shareTransition = null;
- editTransition = null;
- deleteAction = null;
smartActions = null;
quickShareAction = null;
subject = null;
@@ -469,8 +450,9 @@
if (!shouldShowUi()) {
saveScreenshotInWorkerThread(
- screenshot.getUserHandle(), finisher, this::logSuccessOnActionsReady,
- (ignored) -> {});
+ screenshot.getUserHandle(), finisher, this::logSuccessOnActionsReady,
+ (ignored) -> {
+ });
return;
}
@@ -489,7 +471,7 @@
if (screenshot.getType() == WindowManager.TAKE_SCREENSHOT_PROVIDED_IMAGE) {
if (screenshot.getScreenBounds() != null
&& aspectRatiosMatch(screenshot.getBitmap(), screenshot.getInsets(),
- screenshot.getScreenBounds())) {
+ screenshot.getScreenBounds())) {
showFlash = false;
} else {
showFlash = true;
@@ -643,6 +625,12 @@
}
@Override
+ public void onAction(Intent intent, UserHandle owner, boolean overrideTransition) {
+ mActionExecutor.launchIntentAsync(
+ intent, createWindowTransition(), owner, overrideTransition);
+ }
+
+ @Override
public void onDismiss() {
finishDismiss();
}
@@ -652,7 +640,7 @@
// TODO(159460485): Remove this when focus is handled properly in the system
setWindowFocusable(false);
}
- }, mActionExecutor, mFlags);
+ }, mFlags);
mScreenshotView.setDefaultDisplay(mDisplayId);
mScreenshotView.setDefaultTimeoutMillis(mScreenshotHandler.getDefaultTimeoutMillis());
@@ -964,6 +952,35 @@
mScreenshotAnimation.start();
}
+ /**
+ * Supplies the necessary bits for the shared element transition to share sheet.
+ * Note that once called, the action intent to share must be sent immediately after.
+ */
+ private Pair<ActivityOptions, ExitTransitionCoordinator> createWindowTransition() {
+ ExitTransitionCoordinator.ExitTransitionCallbacks callbacks =
+ new ExitTransitionCoordinator.ExitTransitionCallbacks() {
+ @Override
+ public boolean isReturnTransitionAllowed() {
+ return false;
+ }
+
+ @Override
+ public void hideSharedElements() {
+ finishDismiss();
+ }
+
+ @Override
+ public void onFinish() {
+ }
+ };
+ Pair<ActivityOptions, ExitTransitionCoordinator> transition =
+ ActivityOptions.startSharedElementAnimation(mWindow, callbacks, null,
+ Pair.create(mScreenshotView.getScreenshotPreview(),
+ ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME));
+
+ return transition;
+ }
+
/** Reset screenshot view and then call onCompleteRunnable */
private void finishDismiss() {
Log.d(TAG, "finishDismiss");
@@ -1011,7 +1028,7 @@
}
mSaveInBgTask = new SaveImageInBackgroundTask(mContext, mFlags, mImageExporter,
- mScreenshotSmartActions, data, getActionTransitionSupplier(),
+ mScreenshotSmartActions, data,
mScreenshotNotificationSmartActionsProvider);
mSaveInBgTask.execute();
}
@@ -1078,26 +1095,6 @@
}
/**
- * Supplies the necessary bits for the shared element transition to share sheet.
- * Note that once supplied, the action intent to share must be sent immediately after.
- */
- private Supplier<ActionTransition> getActionTransitionSupplier() {
- return () -> {
- Pair<ActivityOptions, ExitTransitionCoordinator> transition =
- ActivityOptions.startSharedElementAnimation(
- mWindow, new ScreenshotExitTransitionCallbacksSupplier(true).get(),
- null, Pair.create(mScreenshotView.getScreenshotPreview(),
- ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME));
- transition.second.startExit();
-
- ActionTransition supply = new ActionTransition();
- supply.bundle = transition.first.toBundle();
- supply.onCancelRunnable = () -> ActivityOptions.stopSharedElementAnimation(mWindow);
- return supply;
- };
- }
-
- /**
* Logs success/failure of the screenshot saving task, and shows an error if it failed.
*/
private void logSuccessOnActionsReady(ScreenshotController.SavedImageData imageData) {
@@ -1186,36 +1183,6 @@
return matchWithinTolerance;
}
- private class ScreenshotExitTransitionCallbacksSupplier implements
- Supplier<ExitTransitionCallbacks> {
- final boolean mDismissOnHideSharedElements;
-
- ScreenshotExitTransitionCallbacksSupplier(boolean dismissOnHideSharedElements) {
- mDismissOnHideSharedElements = dismissOnHideSharedElements;
- }
-
- @Override
- public ExitTransitionCallbacks get() {
- return new ExitTransitionCallbacks() {
- @Override
- public boolean isReturnTransitionAllowed() {
- return false;
- }
-
- @Override
- public void hideSharedElements() {
- if (mDismissOnHideSharedElements) {
- finishDismiss();
- }
- }
-
- @Override
- public void onFinish() {
- }
- };
- }
- }
-
/** Injectable factory to create screenshot controller instances for a specific display. */
@AssistedFactory
public interface Factory {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
index 31c9284..be30a15 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
@@ -57,6 +57,7 @@
import android.os.Bundle;
import android.os.Looper;
import android.os.RemoteException;
+import android.os.UserHandle;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
@@ -86,9 +87,9 @@
import com.android.internal.jank.InteractionJankMonitor;
import com.android.internal.logging.UiEventLogger;
-import com.android.systemui.res.R;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.flags.Flags;
+import com.android.systemui.res.R;
import com.android.systemui.shared.system.InputChannelCompat;
import com.android.systemui.shared.system.InputMonitorCompat;
import com.android.systemui.shared.system.QuickStepContract;
@@ -104,6 +105,8 @@
interface ScreenshotViewCallback {
void onUserInteraction();
+ void onAction(Intent intent, UserHandle owner, boolean overrideTransition);
+
void onDismiss();
/** DOWN motion event was observed outside of the touchable areas of this view. */
@@ -166,7 +169,6 @@
private final InteractionJankMonitor mInteractionJankMonitor;
private long mDefaultTimeoutOfTimeoutHandler;
- private ActionIntentExecutor mActionExecutor;
private FeatureFlags mFlags;
private final Bundle mInteractiveBroadcastOption;
@@ -430,11 +432,9 @@
* Note: must be called before any other (non-constructor) method or null pointer exceptions
* may occur.
*/
- void init(UiEventLogger uiEventLogger, ScreenshotViewCallback callbacks,
- ActionIntentExecutor actionExecutor, FeatureFlags flags) {
+ void init(UiEventLogger uiEventLogger, ScreenshotViewCallback callbacks, FeatureFlags flags) {
mUiEventLogger = uiEventLogger;
mCallbacks = callbacks;
- mActionExecutor = actionExecutor;
mFlags = flags;
}
@@ -800,24 +800,21 @@
shareIntent = ActionIntentCreator.INSTANCE.createShareWithSubject(
imageData.uri, imageData.subject);
}
- mActionExecutor.launchIntentAsync(shareIntent,
- imageData.shareTransition.get().bundle,
- imageData.owner, false);
+ mCallbacks.onAction(shareIntent, imageData.owner, false);
+
});
mEditChip.setOnClickListener(v -> {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_EDIT_TAPPED, 0, mPackageName);
prepareSharedTransition();
- mActionExecutor.launchIntentAsync(
+ mCallbacks.onAction(
ActionIntentCreator.INSTANCE.createEdit(imageData.uri, mContext),
- imageData.editTransition.get().bundle,
imageData.owner, true);
});
mScreenshotPreview.setOnClickListener(v -> {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_PREVIEW_TAPPED, 0, mPackageName);
prepareSharedTransition();
- mActionExecutor.launchIntentAsync(
+ mCallbacks.onAction(
ActionIntentCreator.INSTANCE.createEdit(imageData.uri, mContext),
- imageData.editTransition.get().bundle,
imageData.owner, true);
});
if (mQuickShareChip != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index d5bbaa5..fd3c480 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -1201,7 +1201,12 @@
// Primary bouncer->Gone (ensures lockscreen content is not visible on successful auth)
if (!migrateClocksToBlueprint()) {
collectFlow(mView, mPrimaryBouncerToGoneTransitionViewModel.getLockscreenAlpha(),
- setTransitionAlpha(mNotificationStackScrollLayoutController), mMainDispatcher);
+ setTransitionAlpha(mNotificationStackScrollLayoutController,
+ /* excludeNotifications=*/ true), mMainDispatcher);
+ collectFlow(mView, mPrimaryBouncerToGoneTransitionViewModel.getNotificationAlpha(),
+ (Float alpha) -> {
+ mNotificationStackScrollLayoutController.setMaxAlphaForExpansion(alpha);
+ }, mMainDispatcher);
}
}
@@ -3069,7 +3074,9 @@
}
private void onClosingFinished() {
- mOpenCloseListener.onClosingFinished();
+ if (mOpenCloseListener != null) {
+ mOpenCloseListener.onClosingFinished();
+ }
setClosingWithAlphaFadeout(false);
mMediaHierarchyManager.closeGuts();
}
@@ -4700,7 +4707,9 @@
if (mSplitShadeEnabled && !isKeyguardShowing()) {
mQsController.setExpandImmediate(true);
}
- mOpenCloseListener.onOpenStarted();
+ if (mOpenCloseListener != null) {
+ mOpenCloseListener.onOpenStarted();
+ }
}
if (state == STATE_CLOSED) {
mQsController.setExpandImmediate(false);
@@ -4725,9 +4734,17 @@
private Consumer<Float> setTransitionAlpha(
NotificationStackScrollLayoutController stackScroller) {
+ return setTransitionAlpha(stackScroller, /* excludeNotifications= */ false);
+ }
+
+ private Consumer<Float> setTransitionAlpha(
+ NotificationStackScrollLayoutController stackScroller,
+ boolean excludeNotifications) {
return (Float alpha) -> {
mKeyguardStatusViewController.setAlpha(alpha);
- stackScroller.setMaxAlphaForExpansion(alpha);
+ if (!excludeNotifications) {
+ stackScroller.setMaxAlphaForExpansion(alpha);
+ }
if (keyguardBottomAreaRefactor()) {
mKeyguardInteractor.setAlpha(alpha);
diff --git a/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java b/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
index e7f9700..a5c0553 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
@@ -282,12 +282,6 @@
/** The duration of the notification bounds animation. */
private long mNotificationBoundsAnimationDuration;
- /** TODO(b/273591201): remove after bug resolved */
- private int mLastClippingTopBound;
- private int mLastNotificationsTopPadding;
- private int mLastNotificationsClippingTopBound;
- private int mLastNotificationsClippingTopBoundNssl;
-
private final Region mInterceptRegion = new Region();
/** The end bounds of a clipping animation. */
private final Rect mClippingAnimationEndBounds = new Rect();
@@ -2141,14 +2135,6 @@
ipw.println(mNotificationBoundsAnimationDelay);
ipw.print("mNotificationBoundsAnimationDuration=");
ipw.println(mNotificationBoundsAnimationDuration);
- ipw.print("mLastClippingTopBound=");
- ipw.println(mLastClippingTopBound);
- ipw.print("mLastNotificationsTopPadding=");
- ipw.println(mLastNotificationsTopPadding);
- ipw.print("mLastNotificationsClippingTopBound=");
- ipw.println(mLastNotificationsClippingTopBound);
- ipw.print("mLastNotificationsClippingTopBoundNssl=");
- ipw.println(mLastNotificationsClippingTopBoundNssl);
ipw.print("mInterceptRegion=");
ipw.println(mInterceptRegion);
ipw.print("mClippingAnimationEndBounds=");
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt b/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
index 8352250..a58ce41 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
@@ -22,7 +22,9 @@
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
+import com.android.settingslib.flags.Flags.newStatusBarIcons
import com.android.systemui.battery.BatteryMeterView
+import com.android.systemui.battery.unified.BatteryColors
import com.android.systemui.res.R
import com.android.systemui.statusbar.events.BackgroundAnimatableView
@@ -39,8 +41,12 @@
roundedContainer = requireViewById(R.id.rounded_container)
batteryMeterView = requireViewById(R.id.battery_meter_view)
batteryMeterView.setStaticColor(true)
- val primaryColor = context.resources.getColor(android.R.color.black, context.theme)
- batteryMeterView.updateColors(primaryColor, primaryColor, primaryColor)
+ if (newStatusBarIcons()) {
+ batteryMeterView.setUnifiedBatteryColors(BatteryColors.LightThemeColors)
+ } else {
+ val primaryColor = context.resources.getColor(android.R.color.black, context.theme)
+ batteryMeterView.updateColors(primaryColor, primaryColor, primaryColor)
+ }
updateResources()
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index ca19f71..bb81683 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -168,7 +168,7 @@
private static final int MSG_UNREGISTER_NEARBY_MEDIA_DEVICE_PROVIDER = 67 << MSG_SHIFT;
private static final int MSG_TILE_SERVICE_REQUEST_LISTENING_STATE = 68 << MSG_SHIFT;
private static final int MSG_SHOW_REAR_DISPLAY_DIALOG = 69 << MSG_SHIFT;
- private static final int MSG_GO_TO_FULLSCREEN_FROM_SPLIT = 70 << MSG_SHIFT;
+ private static final int MSG_MOVE_FOCUSED_TASK_TO_FULLSCREEN = 70 << MSG_SHIFT;
private static final int MSG_ENTER_STAGE_SPLIT_FROM_RUNNING_APP = 71 << MSG_SHIFT;
private static final int MSG_SHOW_MEDIA_OUTPUT_SWITCHER = 72 << MSG_SHIFT;
private static final int MSG_TOGGLE_TASKBAR = 73 << MSG_SHIFT;
@@ -498,9 +498,9 @@
default void showRearDisplayDialog(int currentBaseState) {}
/**
- * @see IStatusBar#goToFullscreenFromSplit
+ * @see IStatusBar#moveFocusedTaskToFullscreen
*/
- default void goToFullscreenFromSplit() {}
+ default void moveFocusedTaskToFullscreen(int displayId) {}
/**
* @see IStatusBar#enterStageSplitFromRunningApp
@@ -1422,8 +1422,10 @@
}
@Override
- public void goToFullscreenFromSplit() {
- mHandler.obtainMessage(MSG_GO_TO_FULLSCREEN_FROM_SPLIT).sendToTarget();
+ public void moveFocusedTaskToFullscreen(int displayId) {
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = displayId;
+ mHandler.obtainMessage(MSG_MOVE_FOCUSED_TASK_TO_FULLSCREEN, args).sendToTarget();
}
@Override
@@ -1897,11 +1899,14 @@
mCallbacks.get(i).showRearDisplayDialog((Integer) msg.obj);
}
break;
- case MSG_GO_TO_FULLSCREEN_FROM_SPLIT:
+ case MSG_MOVE_FOCUSED_TASK_TO_FULLSCREEN: {
+ args = (SomeArgs) msg.obj;
+ int displayId = args.argi1;
for (int i = 0; i < mCallbacks.size(); i++) {
- mCallbacks.get(i).goToFullscreenFromSplit();
+ mCallbacks.get(i).moveFocusedTaskToFullscreen(displayId);
}
break;
+ }
case MSG_ENTER_STAGE_SPLIT_FROM_RUNNING_APP:
for (int i = 0; i < mCallbacks.size(); i++) {
mCallbacks.get(i).enterStageSplitFromRunningApp((Boolean) msg.obj);
@@ -1927,13 +1932,14 @@
mCallbacks.get(i).immersiveModeChanged(rootDisplayAreaId, isImmersiveMode);
}
break;
- case MSG_ENTER_DESKTOP:
+ case MSG_ENTER_DESKTOP: {
args = (SomeArgs) msg.obj;
int displayId = args.argi1;
for (int i = 0; i < mCallbacks.size(); i++) {
mCallbacks.get(i).enterDesktop(displayId);
}
break;
+ }
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index 19fe60a..1ec86ae 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -71,6 +71,7 @@
import android.provider.DeviceConfig;
import android.text.TextUtils;
import android.text.format.Formatter;
+import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
@@ -187,6 +188,7 @@
private CharSequence mTransientIndication;
private CharSequence mBiometricMessage;
private CharSequence mBiometricMessageFollowUp;
+ private BiometricSourceType mBiometricMessageSource;
protected ColorStateList mInitialTextColorState;
private boolean mVisible;
private boolean mOrganizationOwnedDevice;
@@ -206,7 +208,7 @@
private int mBatteryLevel;
private boolean mBatteryPresent = true;
private long mChargingTimeRemaining;
- private String mBiometricErrorMessageToShowOnScreenOn;
+ private Pair<String, BiometricSourceType> mBiometricErrorMessageToShowOnScreenOn;
private final Set<Integer> mCoExFaceAcquisitionMsgIdsToShow;
private final FaceHelpMessageDeferral mFaceAcquiredMessageDeferral;
private boolean mInited;
@@ -225,15 +227,18 @@
mIsActiveDreamLockscreenHosted = isLockscreenHosted;
updateDeviceEntryIndication(false);
};
- private final ScreenLifecycle.Observer mScreenObserver =
- new ScreenLifecycle.Observer() {
+ private final ScreenLifecycle.Observer mScreenObserver = new ScreenLifecycle.Observer() {
@Override
public void onScreenTurnedOn() {
mHandler.removeMessages(MSG_RESET_ERROR_MESSAGE_ON_SCREEN_ON);
if (mBiometricErrorMessageToShowOnScreenOn != null) {
String followUpMessage = mFaceLockedOutThisAuthSession
? faceLockedOutFollowupMessage() : null;
- showBiometricMessage(mBiometricErrorMessageToShowOnScreenOn, followUpMessage);
+ showBiometricMessage(
+ mBiometricErrorMessageToShowOnScreenOn.first,
+ followUpMessage,
+ mBiometricErrorMessageToShowOnScreenOn.second
+ );
// We want to keep this message around in case the screen was off
hideBiometricMessageDelayed(DEFAULT_HIDE_DELAY_MS);
mBiometricErrorMessageToShowOnScreenOn = null;
@@ -879,8 +884,35 @@
updateTransient();
}
- private void showBiometricMessage(CharSequence biometricMessage) {
- showBiometricMessage(biometricMessage, null);
+ private void showSuccessBiometricMessage(
+ CharSequence biometricMessage,
+ @Nullable CharSequence biometricMessageFollowUp,
+ BiometricSourceType biometricSourceType
+ ) {
+ showBiometricMessage(biometricMessage, biometricMessageFollowUp, biometricSourceType, true);
+ }
+
+ private void showSuccessBiometricMessage(CharSequence biometricMessage,
+ BiometricSourceType biometricSourceType) {
+ showSuccessBiometricMessage(biometricMessage, null, biometricSourceType);
+ }
+
+ private void showBiometricMessage(CharSequence biometricMessage,
+ BiometricSourceType biometricSourceType) {
+ showBiometricMessage(biometricMessage, null, biometricSourceType, false);
+ }
+
+ private void showBiometricMessage(
+ CharSequence biometricMessage,
+ @Nullable CharSequence biometricMessageFollowUp,
+ BiometricSourceType biometricSourceType
+ ) {
+ showBiometricMessage(
+ biometricMessage,
+ biometricMessageFollowUp,
+ biometricSourceType,
+ false
+ );
}
/**
@@ -889,15 +921,33 @@
* by {@link KeyguardIndicationRotateTextViewController}, see class for rotating message
* logic.
*/
- private void showBiometricMessage(CharSequence biometricMessage,
- @Nullable CharSequence biometricMessageFollowUp) {
+ private void showBiometricMessage(
+ CharSequence biometricMessage,
+ @Nullable CharSequence biometricMessageFollowUp,
+ BiometricSourceType biometricSourceType,
+ boolean isSuccessMessage
+ ) {
if (TextUtils.equals(biometricMessage, mBiometricMessage)
+ && biometricSourceType == mBiometricMessageSource
&& TextUtils.equals(biometricMessageFollowUp, mBiometricMessageFollowUp)) {
return;
}
+ if (!isSuccessMessage
+ && mBiometricMessageSource == FINGERPRINT
+ && biometricSourceType != FINGERPRINT) {
+ // drop all non-fingerprint biometric messages if there's a fingerprint message showing
+ mKeyguardLogger.logDropNonFingerprintMessage(
+ biometricMessage,
+ biometricMessageFollowUp,
+ biometricSourceType
+ );
+ return;
+ }
+
mBiometricMessage = biometricMessage;
mBiometricMessageFollowUp = biometricMessageFollowUp;
+ mBiometricMessageSource = biometricSourceType;
mHandler.removeMessages(MSG_SHOW_ACTION_TO_UNLOCK);
hideBiometricMessageDelayed(
@@ -914,6 +964,7 @@
if (mBiometricMessage != null || mBiometricMessageFollowUp != null) {
mBiometricMessage = null;
mBiometricMessageFollowUp = null;
+ mBiometricMessageSource = null;
mHideBiometricMessageHandler.cancel();
updateBiometricMessage();
}
@@ -1085,7 +1136,8 @@
} else {
message = mContext.getString(R.string.keyguard_retry);
}
- mStatusBarKeyguardViewManager.setKeyguardMessage(message, mInitialTextColorState);
+ mStatusBarKeyguardViewManager.setKeyguardMessage(message, mInitialTextColorState,
+ null);
}
} else {
final boolean canSkipBouncer = mKeyguardUpdateMonitor.getUserCanSkipBouncer(
@@ -1097,34 +1149,40 @@
|| mAccessibilityManager.isTouchExplorationEnabled();
if (udfpsSupported && faceAuthenticated) { // co-ex
if (a11yEnabled) {
- showBiometricMessage(
+ showSuccessBiometricMessage(
mContext.getString(R.string.keyguard_face_successful_unlock),
- mContext.getString(R.string.keyguard_unlock)
+ mContext.getString(R.string.keyguard_unlock),
+ FACE
);
} else {
- showBiometricMessage(
+ showSuccessBiometricMessage(
mContext.getString(R.string.keyguard_face_successful_unlock),
- mContext.getString(R.string.keyguard_unlock_press)
+ mContext.getString(R.string.keyguard_unlock_press),
+ FACE
);
}
} else if (faceAuthenticated) { // face-only
- showBiometricMessage(
+ showSuccessBiometricMessage(
mContext.getString(R.string.keyguard_face_successful_unlock),
- mContext.getString(R.string.keyguard_unlock)
+ mContext.getString(R.string.keyguard_unlock),
+ FACE
);
} else if (udfpsSupported) { // udfps-only
if (a11yEnabled) {
- showBiometricMessage(mContext.getString(R.string.keyguard_unlock));
+ showSuccessBiometricMessage(
+ mContext.getString(R.string.keyguard_unlock),
+ null
+ );
} else {
- showBiometricMessage(mContext.getString(
- R.string.keyguard_unlock_press));
+ showSuccessBiometricMessage(mContext.getString(
+ R.string.keyguard_unlock_press), null);
}
} else { // no security or unlocked by a trust agent
- showBiometricMessage(mContext.getString(R.string.keyguard_unlock));
+ showSuccessBiometricMessage(mContext.getString(R.string.keyguard_unlock), null);
}
} else {
// suggest swiping up for the primary authentication bouncer
- showBiometricMessage(mContext.getString(R.string.keyguard_unlock));
+ showBiometricMessage(mContext.getString(R.string.keyguard_unlock), null);
}
}
}
@@ -1228,6 +1286,13 @@
&& msgId != BIOMETRIC_HELP_FACE_NOT_AVAILABLE;
final boolean faceAuthFailed = biometricSourceType == FACE
&& msgId == BIOMETRIC_HELP_FACE_NOT_RECOGNIZED; // ran through matcher & failed
+ if (faceAuthFailed && mFaceLockedOutThisAuthSession) {
+ mKeyguardLogger.logBiometricMessage(
+ "skipped showing faceAuthFailed message due to lockout",
+ msgId,
+ helpString);
+ return;
+ }
final boolean fpAuthFailed = biometricSourceType == FINGERPRINT
&& msgId == BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED; // ran matcher & failed
final boolean isUnlockWithFingerprintPossible = canUnlockWithFingerprint();
@@ -1245,49 +1310,55 @@
mBouncerMessageInteractor.setFaceAcquisitionMessage(helpString);
}
mStatusBarKeyguardViewManager.setKeyguardMessage(helpString,
- mInitialTextColorState);
+ mInitialTextColorState, biometricSourceType);
} else if (mScreenLifecycle.getScreenState() == SCREEN_ON) {
if (isCoExFaceAcquisitionMessage && msgId == FACE_ACQUIRED_TOO_DARK) {
showBiometricMessage(
helpString,
- mContext.getString(R.string.keyguard_suggest_fingerprint)
+ mContext.getString(R.string.keyguard_suggest_fingerprint),
+ biometricSourceType
);
} else if (faceAuthFailed && isUnlockWithFingerprintPossible) {
showBiometricMessage(
mContext.getString(R.string.keyguard_face_failed),
- mContext.getString(R.string.keyguard_suggest_fingerprint)
+ mContext.getString(R.string.keyguard_suggest_fingerprint),
+ biometricSourceType
);
} else if (fpAuthFailed
&& mKeyguardUpdateMonitor.isCurrentUserUnlockedWithFace()) {
// face had already previously unlocked the device, so instead of showing a
// fingerprint error, tell them they have already unlocked with face auth
// and how to enter their device
- showBiometricMessage(
+ showSuccessBiometricMessage(
mContext.getString(R.string.keyguard_face_successful_unlock),
- mContext.getString(R.string.keyguard_unlock)
+ mContext.getString(R.string.keyguard_unlock),
+ null
);
} else if (fpAuthFailed
&& mKeyguardUpdateMonitor.getUserHasTrust(getCurrentUser())) {
- showBiometricMessage(
+ showSuccessBiometricMessage(
getTrustGrantedIndication(),
- mContext.getString(R.string.keyguard_unlock)
+ mContext.getString(R.string.keyguard_unlock),
+ null
);
} else if (faceAuthUnavailable) {
showBiometricMessage(
helpString,
isUnlockWithFingerprintPossible
? mContext.getString(R.string.keyguard_suggest_fingerprint)
- : mContext.getString(R.string.keyguard_unlock)
+ : mContext.getString(R.string.keyguard_unlock),
+ biometricSourceType
);
} else {
- showBiometricMessage(helpString);
+ showBiometricMessage(helpString, biometricSourceType);
}
} else if (faceAuthFailed) {
// show action to unlock
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_ACTION_TO_UNLOCK),
TRANSIENT_BIOMETRIC_ERROR_TIMEOUT);
} else {
- mBiometricErrorMessageToShowOnScreenOn = helpString;
+ mBiometricErrorMessageToShowOnScreenOn =
+ new Pair<>(helpString, biometricSourceType);
mHandler.sendMessageDelayed(
mHandler.obtainMessage(MSG_RESET_ERROR_MESSAGE_ON_SCREEN_ON),
1000);
@@ -1333,7 +1404,7 @@
} else if (mIndicationHelper.isFaceLockoutErrorMsg(msgId)) {
handleFaceLockoutError(errString);
} else {
- showErrorMessageNowOrLater(errString, null);
+ showErrorMessageNowOrLater(errString, null, FACE);
}
}
@@ -1343,7 +1414,7 @@
msgId,
errString);
} else {
- showErrorMessageNowOrLater(errString, null);
+ showErrorMessageNowOrLater(errString, null, FINGERPRINT);
}
}
@@ -1371,7 +1442,7 @@
@Override
public void onTrustAgentErrorMessage(CharSequence message) {
- showBiometricMessage(message);
+ showBiometricMessage(message, null);
}
@Override
@@ -1459,12 +1530,13 @@
// had too many unsuccessful attempts.
if (!mFaceLockedOutThisAuthSession) {
mFaceLockedOutThisAuthSession = true;
- showErrorMessageNowOrLater(errString, followupMessage);
+ showErrorMessageNowOrLater(errString, followupMessage, FACE);
} else if (!mAuthController.isUdfpsFingerDown()) {
// On subsequent lockouts, we show a more generic locked out message.
showErrorMessageNowOrLater(
mContext.getString(R.string.keyguard_face_unlock_unavailable),
- followupMessage);
+ followupMessage,
+ FACE);
}
}
@@ -1484,7 +1556,8 @@
&& !mStatusBarKeyguardViewManager.isBouncerShowing()) {
showBiometricMessage(
deferredFaceMessage,
- mContext.getString(R.string.keyguard_suggest_fingerprint)
+ mContext.getString(R.string.keyguard_suggest_fingerprint),
+ FACE
);
} else {
// otherwise, don't show any message
@@ -1496,7 +1569,8 @@
// user to manually retry.
showBiometricMessage(
deferredFaceMessage,
- mContext.getString(R.string.keyguard_unlock)
+ mContext.getString(R.string.keyguard_unlock),
+ FACE
);
} else {
// Face-only
@@ -1510,13 +1584,15 @@
getCurrentUser()) && mKeyguardUpdateMonitor.isUnlockingWithFingerprintAllowed();
}
- private void showErrorMessageNowOrLater(String errString, @Nullable String followUpMsg) {
+ private void showErrorMessageNowOrLater(String errString, @Nullable String followUpMsg,
+ BiometricSourceType biometricSourceType) {
if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
- mStatusBarKeyguardViewManager.setKeyguardMessage(errString, mInitialTextColorState);
+ mStatusBarKeyguardViewManager.setKeyguardMessage(errString, mInitialTextColorState,
+ biometricSourceType);
} else if (mScreenLifecycle.getScreenState() == SCREEN_ON) {
- showBiometricMessage(errString, followUpMsg);
+ showBiometricMessage(errString, followUpMsg, biometricSourceType);
} else {
- mBiometricErrorMessageToShowOnScreenOn = errString;
+ mBiometricErrorMessageToShowOnScreenOn = new Pair<>(errString, biometricSourceType);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java
index e582a01..dbcda41 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.connectivity;
+import static com.android.settingslib.flags.Flags.newStatusBarIcons;
+
import com.android.settingslib.AccessibilityContentDescriptions;
import com.android.settingslib.R;
import com.android.settingslib.SignalIcon.IconGroup;
@@ -23,21 +25,52 @@
/** */
public class WifiIcons {
- public static final int[] WIFI_FULL_ICONS = {
- com.android.internal.R.drawable.ic_wifi_signal_0,
- com.android.internal.R.drawable.ic_wifi_signal_1,
- com.android.internal.R.drawable.ic_wifi_signal_2,
- com.android.internal.R.drawable.ic_wifi_signal_3,
- com.android.internal.R.drawable.ic_wifi_signal_4
- };
+ public static final int[] WIFI_FULL_ICONS = getIconsBasedOnFlag();
- public static final int[] WIFI_NO_INTERNET_ICONS = {
- R.drawable.ic_no_internet_wifi_signal_0,
- R.drawable.ic_no_internet_wifi_signal_1,
- R.drawable.ic_no_internet_wifi_signal_2,
- R.drawable.ic_no_internet_wifi_signal_3,
- R.drawable.ic_no_internet_wifi_signal_4
- };
+ /**
+ * Check the aconfig flag to decide on which icons to use. Can be removed once the flag is gone
+ */
+ private static int[] getIconsBasedOnFlag() {
+ if (newStatusBarIcons()) {
+ return new int[] {
+ R.drawable.ic_wifi_0,
+ R.drawable.ic_wifi_1,
+ R.drawable.ic_wifi_2,
+ R.drawable.ic_wifi_3,
+ R.drawable.ic_wifi_4
+ };
+ } else {
+ return new int[] {
+ com.android.internal.R.drawable.ic_wifi_signal_0,
+ com.android.internal.R.drawable.ic_wifi_signal_1,
+ com.android.internal.R.drawable.ic_wifi_signal_2,
+ com.android.internal.R.drawable.ic_wifi_signal_3,
+ com.android.internal.R.drawable.ic_wifi_signal_4
+ };
+ }
+ }
+
+ public static final int[] WIFI_NO_INTERNET_ICONS = getErrorIconsBasedOnFlag();
+
+ private static int [] getErrorIconsBasedOnFlag() {
+ if (newStatusBarIcons()) {
+ return new int[] {
+ R.drawable.ic_wifi_0_error,
+ R.drawable.ic_wifi_1_error,
+ R.drawable.ic_wifi_2_error,
+ R.drawable.ic_wifi_3_error,
+ R.drawable.ic_wifi_4_error
+ };
+ } else {
+ return new int[] {
+ R.drawable.ic_no_internet_wifi_signal_0,
+ R.drawable.ic_no_internet_wifi_signal_1,
+ R.drawable.ic_no_internet_wifi_signal_2,
+ R.drawable.ic_no_internet_wifi_signal_3,
+ R.drawable.ic_no_internet_wifi_signal_4
+ };
+ }
+ }
public static final int[][] QS_WIFI_SIGNAL_STRENGTH = {
WIFI_NO_INTERNET_ICONS,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
index 052e35c..b4c88c5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
@@ -79,6 +79,7 @@
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.flow.transformWhile
import kotlinx.coroutines.isActive
/** View-model for the shared notification container, used by both the shade and keyguard spaces */
@@ -89,7 +90,7 @@
private val interactor: SharedNotificationContainerInteractor,
@Application applicationScope: CoroutineScope,
private val keyguardInteractor: KeyguardInteractor,
- keyguardTransitionInteractor: KeyguardTransitionInteractor,
+ private val keyguardTransitionInteractor: KeyguardTransitionInteractor,
private val shadeInteractor: ShadeInteractor,
communalInteractor: CommunalInteractor,
private val alternateBouncerToGoneTransitionViewModel:
@@ -222,19 +223,60 @@
initialValue = false,
)
+ /**
+ * Fade in if the user swipes the shade back up, not if collapsed by going to AOD. This is
+ * needed due to the lack of a SHADE state with existing keyguard transitions.
+ */
+ private fun awaitCollapse(): Flow<Boolean> {
+ var aodTransitionIsComplete = true
+ return combine(
+ isOnLockscreenWithoutShade,
+ keyguardTransitionInteractor
+ .isInTransitionWhere(
+ fromStatePredicate = { it == LOCKSCREEN },
+ toStatePredicate = { it == AOD }
+ )
+ .onStart { emit(false) },
+ ::Pair
+ )
+ .transformWhile { (isOnLockscreenWithoutShade, aodTransitionIsRunning) ->
+ // Wait until the AOD transition is complete before terminating
+ if (!aodTransitionIsComplete && !aodTransitionIsRunning) {
+ aodTransitionIsComplete = true
+ emit(false) // do not fade in
+ false
+ } else if (aodTransitionIsRunning) {
+ aodTransitionIsComplete = false
+ true
+ } else if (isOnLockscreenWithoutShade) {
+ // Shade is closed, fade in and terminate
+ emit(true)
+ false
+ } else {
+ true
+ }
+ }
+ }
+
/** Fade in only for use after the shade collapses */
val shadeCollapseFadeIn: Flow<Boolean> =
flow {
while (currentCoroutineContext().isActive) {
+ // Ensure shade is collapsed
+ isShadeLocked.first { !it }
emit(false)
// Wait for shade to be fully expanded
isShadeLocked.first { it }
- // ... and then for it to be collapsed
- isOnLockscreenWithoutShade.first { it }
- emit(true)
- // ... and then for the animation to complete
- shadeCollapseFadeInComplete.first { it }
- shadeCollapseFadeInComplete.value = false
+ // ... and then for it to be collapsed OR a transition to AOD begins.
+ // If AOD, do not fade in (a fade out occurs instead).
+ awaitCollapse().collect { doFadeIn ->
+ if (doFadeIn) {
+ emit(true)
+ // ... and then for the animation to complete
+ shadeCollapseFadeInComplete.first { it }
+ shadeCollapseFadeInComplete.value = false
+ }
+ }
}
}
.stateIn(
@@ -333,7 +375,7 @@
lockscreenToPrimaryBouncerTransitionViewModel.lockscreenAlpha,
occludedToAodTransitionViewModel.lockscreenAlpha,
occludedToLockscreenTransitionViewModel.lockscreenAlpha,
- primaryBouncerToGoneTransitionViewModel.lockscreenAlpha,
+ primaryBouncerToGoneTransitionViewModel.notificationAlpha,
primaryBouncerToLockscreenTransitionViewModel.lockscreenAlpha,
)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
index 6f992ac..d513f8d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
@@ -15,10 +15,12 @@
package com.android.systemui.statusbar.phone;
import static com.android.systemui.plugins.DarkIconDispatcher.getTint;
+import static com.android.settingslib.flags.Flags.newStatusBarIcons;
import android.animation.ArgbEvaluator;
import android.content.Context;
import android.content.res.ColorStateList;
+import android.graphics.Color;
import android.graphics.Rect;
import android.util.ArrayMap;
import android.widget.ImageView;
@@ -66,10 +68,16 @@
Context context,
LightBarTransitionsController.Factory lightBarTransitionsControllerFactory,
DumpManager dumpManager) {
- mDarkModeIconColorSingleTone = context.getColor(
- com.android.settingslib.R.color.dark_mode_icon_color_single_tone);
- mLightModeIconColorSingleTone = context.getColor(
- com.android.settingslib.R.color.light_mode_icon_color_single_tone);
+
+ if (newStatusBarIcons()) {
+ mDarkModeIconColorSingleTone = Color.BLACK;
+ mLightModeIconColorSingleTone = Color.WHITE;
+ } else {
+ mDarkModeIconColorSingleTone = context.getColor(
+ com.android.settingslib.R.color.dark_mode_icon_color_single_tone);
+ mLightModeIconColorSingleTone = context.getColor(
+ com.android.settingslib.R.color.light_mode_icon_color_single_tone);
+ }
mTransitionsController = lightBarTransitionsControllerFactory.create(this);
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 d10ca3d..6b47ac1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -239,10 +239,22 @@
ViewGroup.LayoutParams layoutParams = getLayoutParams();
mStatusBarHeight = SystemBarUtils.getStatusBarHeight(mContext);
layoutParams.height = mStatusBarHeight - waterfallTopInset;
+ updateSystemIconsContainerHeight();
updatePaddings();
setLayoutParams(layoutParams);
}
+ private void updateSystemIconsContainerHeight() {
+ View systemIconsContainer = findViewById(R.id.system_icons);
+ ViewGroup.LayoutParams layoutParams = systemIconsContainer.getLayoutParams();
+ int newSystemIconsHeight =
+ getResources().getDimensionPixelSize(R.dimen.status_bar_system_icons_height);
+ if (layoutParams.height != newSystemIconsHeight) {
+ layoutParams.height = newSystemIconsHeight;
+ systemIconsContainer.setLayoutParams(layoutParams);
+ }
+ }
+
private void updatePaddings() {
int statusBarPaddingStart = getResources().getDimensionPixelSize(
R.dimen.status_bar_padding_start);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 29fd225..d1055c7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -23,7 +23,6 @@
import static com.android.systemui.plugins.ActivityStarter.OnDismissAction;
import static com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK;
import static com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK_PULSING;
-import static com.android.systemui.util.kotlin.JavaAdapterKt.collectFlow;
import static com.android.systemui.util.kotlin.JavaAdapterKt.combineFlows;
import android.content.Context;
@@ -98,6 +97,7 @@
import com.android.systemui.unfold.FoldAodAnimationController;
import com.android.systemui.unfold.SysUIUnfoldComponent;
import com.android.systemui.user.domain.interactor.SelectedUserInteractor;
+import com.android.systemui.util.kotlin.JavaAdapter;
import dagger.Lazy;
@@ -348,6 +348,8 @@
private Lazy<KeyguardSurfaceBehindInteractor> mSurfaceBehindInteractor;
private Lazy<KeyguardDismissActionInteractor> mKeyguardDismissActionInteractor;
+ private final JavaAdapter mJavaAdapter;
+
@Inject
public StatusBarKeyguardViewManager(
Context context,
@@ -378,7 +380,8 @@
Lazy<WindowManagerLockscreenVisibilityInteractor> wmLockscreenVisibilityInteractor,
Lazy<KeyguardDismissActionInteractor> keyguardDismissActionInteractorLazy,
SelectedUserInteractor selectedUserInteractor,
- Lazy<KeyguardSurfaceBehindInteractor> surfaceBehindInteractor
+ Lazy<KeyguardSurfaceBehindInteractor> surfaceBehindInteractor,
+ JavaAdapter javaAdapter
) {
mContext = context;
mViewMediatorCallback = callback;
@@ -411,6 +414,7 @@
mKeyguardDismissActionInteractor = keyguardDismissActionInteractorLazy;
mSelectedUserInteractor = selectedUserInteractor;
mSurfaceBehindInteractor = surfaceBehindInteractor;
+ mJavaAdapter = javaAdapter;
}
KeyguardTransitionInteractor mKeyguardTransitionInteractor;
@@ -481,8 +485,7 @@
if (KeyguardWmStateRefactor.isEnabled()) {
// Show the keyguard views whenever we've told WM that the lockscreen is visible.
- collectFlow(
- getViewRootImpl().getView(),
+ mJavaAdapter.alwaysCollectFlow(
combineFlows(
mWmLockscreenVisibilityInteractor.get().getLockscreenVisibility(),
mSurfaceBehindInteractor.get().isAnimatingSurface(),
@@ -781,7 +784,7 @@
}
updateAlternateBouncerShowing(mAlternateBouncerInteractor.show());
- setKeyguardMessage(message, null);
+ setKeyguardMessage(message, null, null);
return;
}
@@ -1444,11 +1447,12 @@
}
/** Display security message to relevant KeyguardMessageArea. */
- public void setKeyguardMessage(String message, ColorStateList colorState) {
+ public void setKeyguardMessage(String message, ColorStateList colorState,
+ BiometricSourceType biometricSourceType) {
if (mAlternateBouncerInteractor.isVisibleState()) {
if (mKeyguardMessageAreaController != null) {
DeviceEntryUdfpsRefactor.assertInLegacyMode();
- mKeyguardMessageAreaController.setMessage(message);
+ mKeyguardMessageAreaController.setMessage(message, biometricSourceType);
}
} else {
mPrimaryBouncerInteractor.showMessage(message, colorState);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
index a608be3..8f3b0e7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
@@ -16,6 +16,7 @@
package com.android.systemui.statusbar.pipeline.mobile.data.repository
+import android.telephony.CellSignalStrength
import android.telephony.SubscriptionInfo
import android.telephony.TelephonyManager
import com.android.systemui.log.table.TableLogBuffer
@@ -149,6 +150,6 @@
companion object {
/** The default number of levels to use for [numberOfLevels]. */
- const val DEFAULT_NUM_LEVELS = 4
+ val DEFAULT_NUM_LEVELS = CellSignalStrength.getNumSignalStrengthLevels()
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
index 6de7a00..3cb138bd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
@@ -25,6 +25,7 @@
import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType
import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository
+import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository.Companion.DEFAULT_NUM_LEVELS
import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel
import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_CARRIER_ID
import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_CARRIER_NETWORK_CHANGE
@@ -223,6 +224,9 @@
_carrierId.value = event.carrierId ?: INVALID_SUBSCRIPTION_ID
+ numberOfLevels.value =
+ if (event.inflateStrength) DEFAULT_NUM_LEVELS + 1 else DEFAULT_NUM_LEVELS
+
cdmaRoaming.value = event.roaming
_isRoaming.value = event.roaming
// TODO(b/261029387): not yet supported
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoModeMobileConnectionDataSource.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoModeMobileConnectionDataSource.kt
index 11a61a9..dbfc576 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoModeMobileConnectionDataSource.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoModeMobileConnectionDataSource.kt
@@ -71,7 +71,7 @@
val dataType = getString("datatype")?.toDataType()
val slot = getString("slot")?.toInt()
val carrierId = getString("carrierid")?.toInt()
- val inflateStrength = getString("inflate")?.toBoolean()
+ val inflateStrength = getString("inflate").toBoolean()
val activity = getString("activity")?.toActivity()
val carrierNetworkChange = getString("carriernetworkchange") == "show"
val roaming = getString("roam") == "show"
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/model/FakeNetworkEventModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/model/FakeNetworkEventModel.kt
index 4836abe..42171d0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/model/FakeNetworkEventModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/model/FakeNetworkEventModel.kt
@@ -31,7 +31,7 @@
// Null means the default (chosen by the repository)
val subId: Int?,
val carrierId: Int?,
- val inflateStrength: Boolean?,
+ val inflateStrength: Boolean = false,
@DataActivityType val activity: Int?,
val carrierNetworkChange: Boolean,
val roaming: Boolean,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
index 5e38715..adcf736 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
@@ -295,12 +295,7 @@
}
.stateIn(scope, SharingStarted.WhileSubscribed(), 0)
- private val numberOfLevels: StateFlow<Int> =
- connectionRepository.numberOfLevels.stateIn(
- scope,
- SharingStarted.WhileSubscribed(),
- connectionRepository.numberOfLevels.value,
- )
+ private val numberOfLevels: StateFlow<Int> = connectionRepository.numberOfLevels
override val isDataConnected: StateFlow<Boolean> =
connectionRepository.dataConnectionState
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
index 900a920..fd5ab13 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
@@ -19,6 +19,8 @@
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
+import android.widget.ImageView
+import com.android.settingslib.flags.Flags.newStatusBarIcons
import com.android.systemui.res.R
import com.android.systemui.statusbar.StatusBarIconView.getVisibleStateString
import com.android.systemui.statusbar.pipeline.mobile.ui.MobileViewLogger
@@ -59,6 +61,18 @@
.inflate(R.layout.status_bar_mobile_signal_group_new, null)
as ModernStatusBarMobileView)
.also {
+ // Flag-specific configuration
+ if (newStatusBarIcons()) {
+ // New icon (with no embedded whitespace) is slightly shorter
+ // (but actually taller)
+ val iconView = it.requireViewById<ImageView>(R.id.mobile_signal)
+ val lp = iconView.layoutParams
+ lp.height =
+ context.resources.getDimensionPixelSize(
+ R.dimen.status_bar_mobile_signal_size_updated
+ )
+ }
+
it.subId = viewModel.subscriptionId
it.initView(slot) {
MobileIconBinder.bind(view = it, viewModel = viewModel, logger = logger)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt
index 4cd3484..ba55aad 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt
@@ -20,6 +20,9 @@
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
+import android.view.ViewGroup
+import android.widget.ImageView
+import com.android.settingslib.flags.Flags.newStatusBarIcons
import com.android.systemui.res.R
import com.android.systemui.statusbar.StatusBarIconView
import com.android.systemui.statusbar.pipeline.shared.ui.view.ModernStatusBarView
@@ -57,7 +60,18 @@
): ModernStatusBarWifiView {
return (LayoutInflater.from(context).inflate(R.layout.new_status_bar_wifi_group, null)
as ModernStatusBarWifiView)
- .also { it.initView(slot) { WifiViewBinder.bind(it, wifiViewModel) } }
+ .also {
+ // Flag-specific configuration
+ if (newStatusBarIcons()) {
+ // The newer asset does not embed whitespace around it, and is therefore
+ // rectangular. Use wrap_content for the width in this case
+ val iconView = it.requireViewById<ImageView>(R.id.wifi_signal)
+ val lp = iconView.layoutParams
+ lp.width = ViewGroup.LayoutParams.WRAP_CONTENT
+ }
+
+ it.initView(slot) { WifiViewBinder.bind(it, wifiViewModel) }
+ }
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/util/wakelock/ClientTrackingWakeLock.kt b/packages/SystemUI/src/com/android/systemui/util/wakelock/ClientTrackingWakeLock.kt
new file mode 100644
index 0000000..db300eb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/wakelock/ClientTrackingWakeLock.kt
@@ -0,0 +1,63 @@
+/*
+ * 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.util.wakelock
+
+import android.os.PowerManager
+import android.util.Log
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * [PowerManager.WakeLock] wrapper that tracks acquire/release reasons and logs them if owning
+ * logger is enabled.
+ */
+class ClientTrackingWakeLock(
+ private val pmWakeLock: PowerManager.WakeLock,
+ private val logger: WakeLockLogger?,
+ private val maxTimeout: Long
+) : WakeLock {
+
+ private val activeClients = ConcurrentHashMap<String, AtomicInteger>()
+
+ override fun acquire(why: String) {
+ val count = activeClients.computeIfAbsent(why) { _ -> AtomicInteger(0) }.incrementAndGet()
+ logger?.logAcquire(pmWakeLock, why, count)
+ pmWakeLock.acquire(maxTimeout)
+ }
+
+ override fun release(why: String) {
+ val count = activeClients[why]?.decrementAndGet() ?: -1
+ if (count < 0) {
+ Log.wtf(WakeLock.TAG, "Releasing WakeLock with invalid reason: $why")
+ // Restore count just in case.
+ activeClients[why]?.incrementAndGet()
+ return
+ }
+
+ logger?.logRelease(pmWakeLock, why, count)
+ pmWakeLock.release()
+ }
+
+ override fun wrap(r: Runnable): Runnable = WakeLock.wrapImpl(this, r)
+
+ fun activeClients(): Int =
+ activeClients.reduceValuesToInt(Long.MAX_VALUE, AtomicInteger::get, 0, Integer::sum)
+
+ override fun toString(): String {
+ return "active clients=${activeClients()}"
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/util/wakelock/DelayedWakeLock.java b/packages/SystemUI/src/com/android/systemui/util/wakelock/DelayedWakeLock.java
index 039109e..d2ed71c 100644
--- a/packages/SystemUI/src/com/android/systemui/util/wakelock/DelayedWakeLock.java
+++ b/packages/SystemUI/src/com/android/systemui/util/wakelock/DelayedWakeLock.java
@@ -19,8 +19,11 @@
import android.content.Context;
import android.os.Handler;
+import com.android.systemui.Flags;
import com.android.systemui.dagger.qualifiers.Background;
+import com.android.systemui.dagger.qualifiers.Main;
+import dagger.Lazy;
import dagger.assisted.Assisted;
import dagger.assisted.AssistedFactory;
import dagger.assisted.AssistedInject;
@@ -37,10 +40,13 @@
private final WakeLock mInner;
@AssistedInject
- public DelayedWakeLock(@Background Handler handler, Context context, WakeLockLogger logger,
+ public DelayedWakeLock(@Background Lazy<Handler> bgHandler,
+ @Main Lazy<Handler> mainHandler,
+ Context context, WakeLockLogger logger,
@Assisted String tag) {
mInner = WakeLock.createPartial(context, logger, tag);
- mHandler = handler;
+ mHandler = Flags.delayedWakelockReleaseOnBackgroundThread() ? bgHandler.get()
+ : mainHandler.get();
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/util/wakelock/WakeLock.java b/packages/SystemUI/src/com/android/systemui/util/wakelock/WakeLock.java
index 6128fee..707751a 100644
--- a/packages/SystemUI/src/com/android/systemui/util/wakelock/WakeLock.java
+++ b/packages/SystemUI/src/com/android/systemui/util/wakelock/WakeLock.java
@@ -22,6 +22,8 @@
import androidx.annotation.VisibleForTesting;
+import com.android.systemui.Flags;
+
import java.util.HashMap;
import javax.inject.Inject;
@@ -112,6 +114,11 @@
@VisibleForTesting
static WakeLock wrap(
final PowerManager.WakeLock inner, WakeLockLogger logger, long maxTimeout) {
+ if (Flags.delayedWakelockReleaseOnBackgroundThread()) {
+ return new ClientTrackingWakeLock(inner, logger, maxTimeout);
+ }
+
+ // Non-thread safe implementation, remove when flag above is removed.
return new WakeLock() {
private final HashMap<String, Integer> mActiveClients = new HashMap<>();
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
index f498520..1a39934 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
@@ -20,6 +20,7 @@
import static com.android.systemui.wallet.ui.WalletCardCarousel.CARD_ANIM_ALPHA_DURATION;
import android.annotation.Nullable;
+import android.app.ActivityOptions;
import android.app.BroadcastOptions;
import android.app.PendingIntent;
import android.content.Context;
@@ -40,8 +41,8 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.settingslib.Utils;
-import com.android.systemui.res.R;
import com.android.systemui.classifier.FalsingCollector;
+import com.android.systemui.res.R;
import java.util.List;
@@ -308,7 +309,7 @@
BroadcastOptions options = BroadcastOptions.makeBasic();
options.setInteractive(true);
options.setPendingIntentBackgroundActivityStartMode(
- BroadcastOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
walletCard.getPendingIntent().send(options.toBundle());
} catch (PendingIntent.CanceledException e) {
Log.w(TAG, "Error sending pending intent for wallet card.");
diff --git a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
index 65dede8..cb61534 100644
--- a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
+++ b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
@@ -28,6 +28,7 @@
import static com.android.server.notification.Flags.screenshareNotificationHiding;
import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_BUBBLES;
import android.app.INotificationManager;
import android.app.Notification;
@@ -50,6 +51,7 @@
import androidx.annotation.Nullable;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.internal.statusbar.IStatusBarService;
import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.flags.FeatureFlags;
@@ -97,6 +99,7 @@
private final Context mContext;
private final Bubbles mBubbles;
private final NotificationShadeWindowController mNotificationShadeWindowController;
+ private final KeyguardStateController mKeyguardStateController;
private final ShadeController mShadeController;
private final IStatusBarService mBarService;
private final INotificationManager mNotificationManager;
@@ -109,6 +112,7 @@
private final NotifPipeline mNotifPipeline;
private final NotifPipelineFlags mNotifPipelineFlags;
private final Executor mSysuiMainExecutor;
+ private final Executor mSysuiUiBgExecutor;
private final Bubbles.SysuiProxy mSysuiProxy;
// TODO (b/145659174): allow for multiple callbacks to support the "shadow" new notif pipeline
@@ -116,6 +120,8 @@
private final StatusBarWindowCallback mStatusBarWindowCallback;
private final Runnable mSensitiveStateChangedListener;
private boolean mPanelExpanded;
+ private boolean mKeyguardShowing;
+ private boolean mDreamingOrInPreview;
/**
* Creates {@link BubblesManager}, returns {@code null} if Optional {@link Bubbles} not present
@@ -140,7 +146,8 @@
SysUiState sysUiState,
FeatureFlags featureFlags,
NotifPipelineFlags notifPipelineFlags,
- Executor sysuiMainExecutor) {
+ Executor sysuiMainExecutor,
+ Executor sysuiUiBgExecutor) {
if (bubblesOptional.isPresent()) {
return new BubblesManager(context,
bubblesOptional.get(),
@@ -160,7 +167,8 @@
sysUiState,
featureFlags,
notifPipelineFlags,
- sysuiMainExecutor);
+ sysuiMainExecutor,
+ sysuiUiBgExecutor);
} else {
return null;
}
@@ -185,10 +193,12 @@
SysUiState sysUiState,
FeatureFlags featureFlags,
NotifPipelineFlags notifPipelineFlags,
- Executor sysuiMainExecutor) {
+ Executor sysuiMainExecutor,
+ Executor sysuiUiBgExecutor) {
mContext = context;
mBubbles = bubbles;
mNotificationShadeWindowController = notificationShadeWindowController;
+ mKeyguardStateController = keyguardStateController;
mShadeController = shadeController;
mNotificationManager = notificationManager;
mDreamManager = dreamManager;
@@ -200,6 +210,7 @@
mNotifPipeline = notifPipeline;
mNotifPipelineFlags = notifPipelineFlags;
mSysuiMainExecutor = sysuiMainExecutor;
+ mSysuiUiBgExecutor = sysuiUiBgExecutor;
mBarService = statusBarService == null
? IStatusBarService.Stub.asInterface(
@@ -208,12 +219,11 @@
setupNotifPipeline();
- keyguardStateController.addCallback(new KeyguardStateController.Callback() {
+ // TODO(b/327410864): use KeyguardTransitionInteractor to listen for keyguard changes
+ mKeyguardStateController.addCallback(new KeyguardStateController.Callback() {
@Override
public void onKeyguardShowingChanged() {
- boolean isUnlockedShade = !keyguardStateController.isShowing()
- && !isDreamingOrInPreview();
- bubbles.onStatusBarStateChanged(isUnlockedShade);
+ updateKeyguardAndDreamingState();
}
});
@@ -256,6 +266,14 @@
mPanelExpanded = panelExpanded;
mBubbles.onNotificationPanelExpandedChanged(panelExpanded);
}
+ if (!mKeyguardShowing && mDreamingOrInPreview && !isDreaming) {
+ // We check for dreaming state changes when keyguard status changes.
+ // This causes us to miss events if dreaming state changes after keyguard.
+ // Add a check here for the case where keyguard is dismissed before
+ // dreaming state changes. Otherwise bubbles remain invisible.
+ // TODO(b/327410864): use KeyguardTransitionInteractor for dreaming changes
+ updateKeyguardAndDreamingState();
+ }
};
notificationShadeWindowController.registerCallback(mStatusBarWindowCallback);
@@ -395,6 +413,19 @@
mBubbles.setSysuiProxy(mSysuiProxy);
}
+ private void updateKeyguardAndDreamingState() {
+ mSysuiUiBgExecutor.execute(() -> {
+ mKeyguardShowing = mKeyguardStateController.isShowing();
+ mDreamingOrInPreview = isDreamingOrInPreview();
+ boolean isUnlockedShade = !mKeyguardShowing && !mDreamingOrInPreview;
+ ProtoLog.d(WM_SHELL_BUBBLES,
+ "handleKeyguardOrDreamChange isUnlockedShade=%b keyguardShowing=%b "
+ + "dreamingOrInPreview=%b",
+ isUnlockedShade, mKeyguardShowing, mDreamingOrInPreview);
+ mBubbles.onStatusBarStateChanged(isUnlockedShade);
+ });
+ }
+
private boolean isDreamingOrInPreview() {
try {
return mDreamManager.isDreamingOrInPreview();
diff --git a/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java b/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java
index 15e0965..324d723 100644
--- a/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java
+++ b/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java
@@ -256,7 +256,7 @@
});
mCommandQueue.addCallback(new CommandQueue.Callbacks() {
@Override
- public void goToFullscreenFromSplit() {
+ public void moveFocusedTaskToFullscreen(int displayId) {
splitScreen.goToFullscreenFromSplit();
}
});
@@ -362,6 +362,12 @@
desktopMode.enterDesktop(displayId);
}
});
+ mCommandQueue.addCallback(new CommandQueue.Callbacks() {
+ @Override
+ public void moveFocusedTaskToFullscreen(int displayId) {
+ desktopMode.moveFocusedTaskToFullscreen(displayId);
+ }
+ });
}
@VisibleForTesting
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
index 3026966..0f8a813 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
@@ -336,48 +336,6 @@
}
@Test
- fun listenForTransitionToAodFromGone_updatesClockDozeAmountToOne() =
- runBlocking(IMMEDIATE) {
- val transitionStep = MutableStateFlow(TransitionStep())
- whenever(keyguardTransitionInteractor.transitionStepsToState(KeyguardState.AOD))
- .thenReturn(transitionStep)
-
- val job = underTest.listenForAnyStateToAodTransition(this)
- transitionStep.value =
- TransitionStep(
- from = KeyguardState.GONE,
- to = KeyguardState.AOD,
- transitionState = TransitionState.STARTED,
- )
- yield()
-
- verify(animations, times(2)).doze(1f)
-
- job.cancel()
- }
-
- @Test
- fun listenForTransitionToAodFromLockscreen_neverUpdatesClockDozeAmount() =
- runBlocking(IMMEDIATE) {
- val transitionStep = MutableStateFlow(TransitionStep())
- whenever(keyguardTransitionInteractor.transitionStepsToState(KeyguardState.AOD))
- .thenReturn(transitionStep)
-
- val job = underTest.listenForAnyStateToAodTransition(this)
- transitionStep.value =
- TransitionStep(
- from = KeyguardState.LOCKSCREEN,
- to = KeyguardState.AOD,
- transitionState = TransitionState.STARTED,
- )
- yield()
-
- verify(animations, never()).doze(1f)
-
- job.cancel()
- }
-
- @Test
fun unregisterListeners_validate() =
runBlocking(IMMEDIATE) {
underTest.unregisterListeners()
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardMessageAreaControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardMessageAreaControllerTest.java
index d4522d0..93e7602 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardMessageAreaControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardMessageAreaControllerTest.java
@@ -19,11 +19,14 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.hardware.biometrics.BiometricSourceType;
import android.test.suitebuilder.annotation.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -119,4 +122,51 @@
when(mKeyguardMessageArea.getText()).thenReturn(msg);
assertThat(mMessageAreaController.getMessage()).isEqualTo(msg);
}
+
+ @Test
+ public void testFingerprintMessageUpdate() {
+ String msg = "fpMessage";
+ mMessageAreaController.setMessage(
+ msg, BiometricSourceType.FINGERPRINT
+ );
+ verify(mKeyguardMessageArea).setMessage(msg, /* animate= */ true);
+
+ String msg2 = "fpMessage2";
+ mMessageAreaController.setMessage(
+ msg2, BiometricSourceType.FINGERPRINT
+ );
+ verify(mKeyguardMessageArea).setMessage(msg2, /* animate= */ true);
+ }
+
+ @Test
+ public void testFaceMessageDroppedWhileFingerprintMessageShowing() {
+ String fpMsg = "fpMessage";
+ mMessageAreaController.setMessage(
+ fpMsg, BiometricSourceType.FINGERPRINT
+ );
+ verify(mKeyguardMessageArea).setMessage(eq(fpMsg), /* animate= */ anyBoolean());
+
+ String faceMessage = "faceMessage";
+ mMessageAreaController.setMessage(
+ faceMessage, BiometricSourceType.FACE
+ );
+ verify(mKeyguardMessageArea, never())
+ .setMessage(eq(faceMessage), /* animate= */ anyBoolean());
+ }
+
+ @Test
+ public void testGenericMessageShowsAfterFingerprintMessageShowing() {
+ String fpMsg = "fpMessage";
+ mMessageAreaController.setMessage(
+ fpMsg, BiometricSourceType.FINGERPRINT
+ );
+ verify(mKeyguardMessageArea).setMessage(eq(fpMsg), /* animate= */ anyBoolean());
+
+ String genericMessage = "genericMessage";
+ mMessageAreaController.setMessage(
+ genericMessage, null
+ );
+ verify(mKeyguardMessageArea)
+ .setMessage(eq(genericMessage), /* animate= */ anyBoolean());
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index 538daee..336a97e 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -26,6 +26,8 @@
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_UDFPS_OPTICAL;
import static android.telephony.SubscriptionManager.DATA_ROAMING_DISABLE;
import static android.telephony.SubscriptionManager.NAME_SOURCE_CARRIER_ID;
+import static android.telephony.SubscriptionManager.PROFILE_CLASS_DEFAULT;
+import static android.telephony.SubscriptionManager.PROFILE_CLASS_PROVISIONING;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
@@ -187,6 +189,11 @@
TEST_CARRIER, TEST_CARRIER_2, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", true, TEST_GROUP_UUID,
TEST_CARRIER_ID, 0);
+ private static final SubscriptionInfo TEST_SUBSCRIPTION_PROVISIONING = new SubscriptionInfo(
+ 1, "", 0,
+ TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_CARRIER_ID, 0xFFFFFF, "",
+ DATA_ROAMING_DISABLE, null, null, null, null, false, null, "", false, TEST_GROUP_UUID,
+ TEST_CARRIER_ID, PROFILE_CLASS_PROVISIONING);
private static final int FINGERPRINT_SENSOR_ID = 1;
@Mock
@@ -1204,7 +1211,8 @@
assertThat(mKeyguardUpdateMonitor.mSimDatas.get(TEST_SUBSCRIPTION.getSubscriptionId()))
.isNotNull();
- when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(null);
+ when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
+ .thenReturn(new ArrayList<>());
mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
SubscriptionManager.INVALID_SUBSCRIPTION_ID);
mTestableLooper.processAllMessages();
@@ -1216,6 +1224,37 @@
}
@Test
+ public void testActiveSubscriptionList_filtersProvisioningNetworks() {
+ List<SubscriptionInfo> list = new ArrayList<>();
+ list.add(TEST_SUBSCRIPTION_PROVISIONING);
+ when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
+ mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
+
+ assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).isEmpty();
+
+ SubscriptionInfo.Builder b = new SubscriptionInfo.Builder(TEST_SUBSCRIPTION_PROVISIONING);
+ b.setProfileClass(PROFILE_CLASS_DEFAULT);
+ SubscriptionInfo validInfo = b.build();
+
+ list.clear();
+ list.add(validInfo);
+ mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
+
+ assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).hasSize(1);
+ }
+
+ @Test
+ public void testActiveSubscriptionList_filtersProvisioningNetworks_untilValid() {
+ List<SubscriptionInfo> list = new ArrayList<>();
+ list.add(TEST_SUBSCRIPTION_PROVISIONING);
+ when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
+ mKeyguardUpdateMonitor.mSubscriptionListener.onSubscriptionsChanged();
+
+ assertThat(mKeyguardUpdateMonitor.getSubscriptionInfo(true)).isEmpty();
+
+ }
+
+ @Test
public void testIsUserUnlocked() {
// mUserManager will report the user as unlocked on @Before
assertThat(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
index 4ab7ab4..043dcaa 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
@@ -15,10 +15,13 @@
*/
package com.android.systemui.battery
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper.RunWithLooper
import android.widget.ImageView
import androidx.test.filters.SmallTest
+import com.android.settingslib.flags.Flags.FLAG_NEW_STATUS_BAR_ICONS
import com.android.systemui.res.R
import com.android.systemui.SysuiTestCase
import com.android.systemui.battery.BatteryMeterView.BatteryEstimateFetcher
@@ -141,7 +144,8 @@
}
@Test
- fun changesFromEstimateToPercent_textAndContentDescriptionChanges() {
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun changesFromEstimateToPercent_textAndContentDescriptionChanges_flagOff() {
mBatteryMeterView.onBatteryLevelChanged(15, false)
mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ESTIMATE)
mBatteryMeterView.setBatteryEstimateFetcher(Fetcher())
@@ -164,6 +168,31 @@
}
@Test
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun changesFromEstimateToPercent_textAndContentDescriptionChanges_flagOn() {
+ mBatteryMeterView.onBatteryLevelChanged(15, false)
+ mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ESTIMATE)
+ mBatteryMeterView.setBatteryEstimateFetcher(Fetcher())
+
+ mBatteryMeterView.updatePercentText()
+
+ assertThat(mBatteryMeterView.contentDescription).isEqualTo(
+ context.getString(
+ R.string.accessibility_battery_level_with_estimate, 15, ESTIMATE
+ )
+ )
+
+ // Update the show mode from estimate to percent
+ mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ON)
+
+ assertThat(mBatteryMeterView.batteryPercentView).isNull()
+ assertThat(mBatteryMeterView.contentDescription).isEqualTo(
+ context.getString(R.string.accessibility_battery_level, 15)
+ )
+ assertThat(mBatteryMeterView.unifiedBatteryState.showPercent).isTrue()
+ }
+
+ @Test
fun contentDescription_manyUpdates_alwaysUpdated() {
// BatteryDefender
mBatteryMeterView.onBatteryLevelChanged(90, false)
@@ -208,7 +237,8 @@
}
@Test
- fun isBatteryDefenderChanged_true_drawableGetsTrue() {
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_true_drawableGetsTrue_flagOff() {
mBatteryMeterView.setDisplayShieldEnabled(true)
val drawable = getBatteryDrawable()
@@ -218,7 +248,18 @@
}
@Test
- fun isBatteryDefenderChanged_false_drawableGetsFalse() {
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_true_drawableGetsTrue_flagOn() {
+ mBatteryMeterView.setDisplayShieldEnabled(true)
+
+ mBatteryMeterView.onIsBatteryDefenderChanged(true)
+
+ assertThat(mBatteryMeterView.unifiedBatteryState.attribution).isNotNull()
+ }
+
+ @Test
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_false_drawableGetsFalse_flagOff() {
mBatteryMeterView.setDisplayShieldEnabled(true)
val drawable = getBatteryDrawable()
@@ -232,7 +273,22 @@
}
@Test
- fun isBatteryDefenderChanged_true_featureflagOff_drawableGetsFalse() {
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_false_drawableGetsFalse_flagOn() {
+ mBatteryMeterView.setDisplayShieldEnabled(true)
+
+ // Start as true
+ mBatteryMeterView.onIsBatteryDefenderChanged(true)
+
+ // Update to false
+ mBatteryMeterView.onIsBatteryDefenderChanged(false)
+
+ assertThat(mBatteryMeterView.unifiedBatteryState.attribution).isNull()
+ }
+
+ @Test
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_true_featureflagOff_drawableGetsFalse_flagOff() {
mBatteryMeterView.setDisplayShieldEnabled(false)
val drawable = getBatteryDrawable()
@@ -242,17 +298,41 @@
}
@Test
- fun isIncompatibleChargingChanged_true_drawableGetsChargingFalse() {
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isBatteryDefenderChanged_true_featureflagOff_drawableGetsFalse_flagOn() {
+ mBatteryMeterView.setDisplayShieldEnabled(false)
+
+ mBatteryMeterView.onIsBatteryDefenderChanged(true)
+
+ assertThat(mBatteryMeterView.unifiedBatteryState.attribution).isNull()
+ }
+
+ @Test
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isIncompatibleChargingChanged_true_drawableGetsChargingFalse_flagOff() {
mBatteryMeterView.onBatteryLevelChanged(45, true)
val drawable = getBatteryDrawable()
mBatteryMeterView.onIsIncompatibleChargingChanged(true)
assertThat(drawable.getCharging()).isFalse()
+ assertThat(mBatteryMeterView.isCharging).isFalse()
}
@Test
- fun isIncompatibleChargingChanged_false_drawableGetsChargingTrue() {
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isIncompatibleChargingChanged_true_drawableGetsChargingFalse_flagOn() {
+ mBatteryMeterView.onBatteryLevelChanged(45, true)
+
+ mBatteryMeterView.onIsIncompatibleChargingChanged(true)
+
+ assertThat(mBatteryMeterView.unifiedBatteryState.attribution).isNull()
+ assertThat(mBatteryMeterView.isCharging).isFalse()
+ }
+
+ @Test
+ @DisableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isIncompatibleChargingChanged_false_drawableGetsChargingTrue_flagOff() {
mBatteryMeterView.onBatteryLevelChanged(45, true)
val drawable = getBatteryDrawable()
@@ -261,6 +341,17 @@
assertThat(drawable.getCharging()).isTrue()
}
+ @Test
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun isIncompatibleChargingChanged_false_drawableGetsChargingTrue_flagOn() {
+ mBatteryMeterView.onBatteryLevelChanged(45, true)
+
+ mBatteryMeterView.onIsIncompatibleChargingChanged(false)
+
+ assertThat(mBatteryMeterView.isCharging).isTrue()
+ assertThat(mBatteryMeterView.unifiedBatteryState.attribution).isNotNull()
+ }
+
private fun getBatteryDrawable(): AccessorizedBatteryDrawable {
return (mBatteryMeterView.getChildAt(0) as ImageView)
.drawable as AccessorizedBatteryDrawable
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
index 2c1a87d..10b86ea 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
@@ -21,8 +21,8 @@
import android.hardware.biometrics.BiometricConstants
import android.hardware.biometrics.BiometricManager
import android.hardware.biometrics.Flags.FLAG_CUSTOM_BIOMETRIC_PROMPT
-import android.hardware.biometrics.Flags.customBiometricPrompt
import android.hardware.biometrics.PromptInfo
+import android.hardware.biometrics.PromptVerticalListContentView
import android.hardware.face.FaceSensorPropertiesInternal
import android.hardware.fingerprint.FingerprintSensorPropertiesInternal
import android.os.Handler
@@ -40,7 +40,6 @@
import androidx.test.filters.SmallTest
import com.android.internal.jank.InteractionJankMonitor
import com.android.internal.widget.LockPatternUtils
-import com.android.systemui.Flags.FLAG_CONSTRAINT_BP
import com.android.systemui.SysuiTestCase
import com.android.systemui.biometrics.data.repository.FakeDisplayStateRepository
import com.android.systemui.biometrics.data.repository.FakeFingerprintPropertyRepository
@@ -148,8 +147,6 @@
@Before
fun setup() {
- mSetFlagsRule.disableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
- mSetFlagsRule.disableFlags(FLAG_CONSTRAINT_BP)
displayRepository = FakeDisplayRepository()
displayStateInteractor =
@@ -388,9 +385,10 @@
}
@Test
- fun testShowCredentialUI() {
+ fun testShowCredentialUI_withDescription() {
+ mSetFlagsRule.disableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
val container = initializeFingerprintContainer(
- authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL
+ authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL
)
waitForIdleSync()
@@ -399,16 +397,12 @@
}
@Test
- fun testShowBiometricUIWhenCustomBpEnabledAndNoSensors() {
- mSetFlagsRule.enableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ fun testShowCredentialUI_withCustomBp() {
val container = initializeFingerprintContainer(
- authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL
+ authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL,
+ isUsingContentView = true
)
- waitForIdleSync()
-
- assertThat(customBiometricPrompt()).isTrue()
- assertThat(container.hasBiometricPrompt()).isTrue()
- assertThat(container.hasCredentialView()).isFalse()
+ checkBpShowsForCredentialAndGoToCredential(container)
}
@Test
@@ -512,11 +506,13 @@
private fun initializeFingerprintContainer(
authenticators: Int = BiometricManager.Authenticators.BIOMETRIC_WEAK,
- addToView: Boolean = true
+ addToView: Boolean = true,
+ isUsingContentView: Boolean = false,
) = initializeContainer(
TestAuthContainerView(
authenticators = authenticators,
- fingerprintProps = fingerprintSensorPropertiesInternal()
+ fingerprintProps = fingerprintSensorPropertiesInternal(),
+ isUsingContentView = isUsingContentView,
),
addToView
)
@@ -549,7 +545,8 @@
private inner class TestAuthContainerView(
authenticators: Int = BiometricManager.Authenticators.BIOMETRIC_WEAK,
fingerprintProps: List<FingerprintSensorPropertiesInternal> = listOf(),
- faceProps: List<FaceSensorPropertiesInternal> = listOf()
+ faceProps: List<FaceSensorPropertiesInternal> = listOf(),
+ isUsingContentView: Boolean = false,
) : AuthContainerView(
Config().apply {
mContext = this@AuthContainerViewTest.context
@@ -559,6 +556,9 @@
mSkipAnimation = true
mPromptInfo = PromptInfo().apply {
this.authenticators = authenticators
+ if (isUsingContentView) {
+ this.contentView = PromptVerticalListContentView.Builder().build()
+ }
}
mOpPackageName = OP_PACKAGE_NAME
},
@@ -614,6 +614,17 @@
val layoutParams = AuthContainerView.getLayoutParams(windowToken, "")
assertThat((layoutParams.fitInsetsTypes and WindowInsets.Type.systemBars()) == 0).isTrue()
}
+
+ private fun checkBpShowsForCredentialAndGoToCredential(container: TestAuthContainerView) {
+ waitForIdleSync()
+ assertThat(container.hasBiometricPrompt()).isTrue()
+ assertThat(container.hasCredentialView()).isFalse()
+
+ container.animateToCredentialUI(false)
+ waitForIdleSync()
+ assertThat(container.hasBiometricPrompt()).isFalse()
+ assertThat(container.hasCredentialView()).isTrue()
+ }
}
private fun AuthContainerView.hasBiometricPrompt() =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/data/repository/PromptRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/data/repository/PromptRepositoryImplTest.kt
index b39e09d..7b972d3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/data/repository/PromptRepositoryImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/data/repository/PromptRepositoryImplTest.kt
@@ -16,7 +16,9 @@
package com.android.systemui.biometrics.data.repository
+import android.hardware.biometrics.BiometricManager
import android.hardware.biometrics.PromptInfo
+import android.hardware.biometrics.PromptVerticalListContentView
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.biometrics.AuthController
@@ -131,6 +133,52 @@
}
@Test
+ fun showBpWithoutIconForCredential_withCustomBp() =
+ testScope.runTest {
+ for (case in
+ listOf(
+ PromptKind.Biometric(),
+ PromptKind.Pin,
+ PromptKind.Password,
+ PromptKind.Pattern
+ )) {
+ val hasCredentialViewShown = case !is PromptKind.Biometric
+ val promptInfo =
+ PromptInfo().apply {
+ authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL
+ contentView = PromptVerticalListContentView.Builder().build()
+ }
+ repository.setPrompt(promptInfo, USER_ID, CHALLENGE, case, OP_PACKAGE_NAME)
+ repository.setShouldShowBpWithoutIconForCredential(promptInfo)
+
+ assertThat(repository.showBpWithoutIconForCredential.value)
+ .isEqualTo(!hasCredentialViewShown)
+ }
+ }
+
+ @Test
+ fun showBpWithoutIconForCredential_withDescription() =
+ testScope.runTest {
+ for (case in
+ listOf(
+ PromptKind.Biometric(),
+ PromptKind.Pin,
+ PromptKind.Password,
+ PromptKind.Pattern
+ )) {
+ val promptInfo =
+ PromptInfo().apply {
+ authenticators = BiometricManager.Authenticators.DEVICE_CREDENTIAL
+ description = "description"
+ }
+ repository.setPrompt(promptInfo, USER_ID, CHALLENGE, case, OP_PACKAGE_NAME)
+ repository.setShouldShowBpWithoutIconForCredential(promptInfo)
+
+ assertThat(repository.showBpWithoutIconForCredential.value).isFalse()
+ }
+ }
+
+ @Test
fun setsAndUnsetsPrompt() =
testScope.runTest {
val kind = PromptKind.Pin
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
index 52b4275..2817780 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
@@ -147,7 +147,7 @@
testScope.runTest { useCredentialAndReset(Utils.CREDENTIAL_PIN) }
@Test
- fun usePattermCredentialAndReset() =
+ fun usePatternCredentialAndReset() =
testScope.runTest { useCredentialAndReset(Utils.CREDENTIAL_PATTERN) }
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt
index 6d8e7aa..6aebe36 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt
@@ -126,7 +126,7 @@
keyguardRepository.setKeyguardDismissible(true)
runCurrent()
shadeRepository.setCurrentFling(
- FlingInfo(expand = true) // Not a dismiss fling (expand = true).
+ FlingInfo(expand = false) // Is a dismiss fling upward (expand = false).
)
runCurrent()
@@ -153,4 +153,22 @@
assertThatRepository(transitionRepository).noTransitionsStarted()
}
+
+ @Test
+ @DisableFlags(Flags.FLAG_KEYGUARD_WM_STATE_REFACTOR)
+ fun testDoesNotTransitionToGone_whenDismissFling_emitsNull() =
+ testScope.runTest {
+ underTest.start()
+ verify(transitionRepository, never()).startTransition(any())
+
+ keyguardRepository.setKeyguardDismissible(true)
+ runCurrent()
+
+ // The fling is null when it a) initializes b) ends and in either case we should not
+ // swipe to unlock.
+ shadeRepository.setCurrentFling(null)
+ runCurrent()
+
+ assertThatRepository(transitionRepository).noTransitionsStarted()
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt
index a4483bd..6d605a5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt
@@ -375,4 +375,323 @@
values
)
}
+
+ @Test
+ fun testLockscreenVisibility_usesFromState_ifCanceled() =
+ testScope.runTest {
+ val values by collectValues(underTest.lockscreenVisibility)
+
+ transitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.GONE,
+ testScope
+ )
+
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ // Initially should be true, as we start in LOCKSCREEN.
+ true,
+ // Then, false, since we finish in GONE.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.RUNNING,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ // Should remain false as we transition from GONE.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.CANCELED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.LOCKSCREEN,
+ )
+ )
+
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ false,
+ // If we cancel and then go from LS -> GONE, we should immediately flip to the
+ // visibility of the from state (LS).
+ true,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.FINISHED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.LOCKSCREEN,
+ )
+ )
+
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ false,
+ true,
+ ),
+ values
+ )
+ }
+
+ /**
+ * Tests the special case for insecure camera launch. CANCELING a transition from GONE and then
+ * STARTING a transition back to GONE should never show the lockscreen, even though the current
+ * state during the AOD/isAsleep -> GONE transition is AOD (where lockscreen visibility = true).
+ */
+ @Test
+ fun testLockscreenVisibility_falseDuringTransitionToGone_fromCanceledGone() =
+ testScope.runTest {
+ val values by collectValues(underTest.lockscreenVisibility)
+
+ transitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.GONE,
+ testScope
+ )
+
+ runCurrent()
+ assertEquals(
+ listOf(
+ true,
+ // Not visible since we're GONE.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.RUNNING,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.CANCELED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+ runCurrent()
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.RUNNING,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+ runCurrent()
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.FINISHED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+
+ runCurrent()
+ assertEquals(
+ listOf(
+ true,
+ // Remains not visible from GONE -> AOD (canceled) -> AOD since we never
+ // FINISHED in AOD, and special-case handling for the insecure camera launch
+ // ensures that we use the lockscreen visibility for GONE (false) if we're
+ // STARTED to GONE after a CANCELED from GONE.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionSteps(
+ from = KeyguardState.GONE,
+ to = KeyguardState.LOCKSCREEN,
+ testScope,
+ )
+
+ assertEquals(
+ listOf(
+ true,
+ false,
+ // Make sure there's no stuck overrides or something - we should make lockscreen
+ // visible again once we're finished in LOCKSCREEN.
+ true,
+ ),
+ values
+ )
+ }
+
+ /** */
+ @Test
+ fun testLockscreenVisibility_trueDuringTransitionToGone_fromNotCanceledGone() =
+ testScope.runTest {
+ val values by collectValues(underTest.lockscreenVisibility)
+
+ transitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.GONE,
+ testScope
+ )
+
+ runCurrent()
+ assertEquals(
+ listOf(
+ true,
+ // Not visible when finished in GONE.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.RUNNING,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ // Still not visible during GONE -> AOD.
+ false,
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.FINISHED,
+ from = KeyguardState.GONE,
+ to = KeyguardState.AOD,
+ )
+ )
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ false,
+ // Visible now that we're FINISHED in AOD.
+ true
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.STARTED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+ runCurrent()
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.RUNNING,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+ runCurrent()
+
+ assertEquals(
+ listOf(
+ true,
+ false,
+ // Remains visible from AOD during transition.
+ true
+ ),
+ values
+ )
+
+ transitionRepository.sendTransitionStep(
+ TransitionStep(
+ transitionState = TransitionState.FINISHED,
+ from = KeyguardState.AOD,
+ to = KeyguardState.GONE,
+ )
+ )
+
+ runCurrent()
+ assertEquals(
+ listOf(
+ true,
+ false,
+ true,
+ // Until we're finished in GONE again.
+ false
+ ),
+ values
+ )
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegateTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegateTest.kt
new file mode 100644
index 0000000..8ecb953
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogDelegateTest.kt
@@ -0,0 +1,347 @@
+/*
+ * Copyright (C) 2023 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.qs.tiles.dialog.bluetooth
+
+import android.content.Context
+import android.graphics.drawable.Drawable
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
+import android.view.LayoutInflater
+import android.view.View
+import android.view.View.GONE
+import android.view.View.VISIBLE
+import android.view.ViewGroup.LayoutParams.MATCH_PARENT
+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import androidx.test.filters.SmallTest
+import com.android.internal.logging.UiEventLogger
+import com.android.settingslib.bluetooth.CachedBluetoothDevice
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.animation.DialogTransitionAnimator
+import com.android.systemui.model.SysUiState
+import com.android.systemui.res.R
+import com.android.systemui.statusbar.phone.SystemUIDialog
+import com.android.systemui.statusbar.phone.SystemUIDialogManager
+import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.time.FakeSystemClock
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.test.TestCoroutineScheduler
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.Mock
+import org.mockito.Mockito.`when`
+import org.mockito.junit.MockitoJUnit
+import org.mockito.junit.MockitoRule
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+class BluetoothTileDialogDelegateTest : SysuiTestCase() {
+ companion object {
+ const val DEVICE_NAME = "device"
+ const val DEVICE_CONNECTION_SUMMARY = "active"
+ const val ENABLED = true
+ const val CONTENT_HEIGHT = WRAP_CONTENT
+ }
+
+ @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
+
+ @Mock private lateinit var cachedBluetoothDevice: CachedBluetoothDevice
+
+ @Mock private lateinit var bluetoothTileDialogCallback: BluetoothTileDialogCallback
+
+ @Mock private lateinit var drawable: Drawable
+
+ @Mock private lateinit var uiEventLogger: UiEventLogger
+
+ @Mock private lateinit var logger: BluetoothTileDialogLogger
+
+ private val uiProperties =
+ BluetoothTileDialogViewModel.UiProperties.build(
+ isBluetoothEnabled = ENABLED,
+ isAutoOnToggleFeatureAvailable = ENABLED
+ )
+ @Mock private lateinit var sysuiDialogFactory: SystemUIDialog.Factory
+ @Mock private lateinit var dialogManager: SystemUIDialogManager
+ @Mock private lateinit var sysuiState: SysUiState
+ @Mock private lateinit var dialogTransitionAnimator: DialogTransitionAnimator
+
+ private val fakeSystemClock = FakeSystemClock()
+
+ private lateinit var scheduler: TestCoroutineScheduler
+ private lateinit var dispatcher: CoroutineDispatcher
+ private lateinit var testScope: TestScope
+ private lateinit var icon: Pair<Drawable, String>
+ private lateinit var mBluetoothTileDialogDelegate: BluetoothTileDialogDelegate
+ private lateinit var deviceItem: DeviceItem
+
+ @Before
+ fun setUp() {
+ scheduler = TestCoroutineScheduler()
+ dispatcher = UnconfinedTestDispatcher(scheduler)
+ testScope = TestScope(dispatcher)
+
+ whenever(sysuiState.setFlag(anyInt(), anyBoolean())).thenReturn(sysuiState)
+
+ mBluetoothTileDialogDelegate =
+ BluetoothTileDialogDelegate(
+ mContext,
+ uiProperties,
+ CONTENT_HEIGHT,
+ ENABLED,
+ bluetoothTileDialogCallback,
+ {},
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ sysuiDialogFactory,
+ LayoutInflater.from(mContext)
+ )
+
+ whenever(
+ sysuiDialogFactory.create(
+ any(SystemUIDialog.Delegate::class.java),
+ any(Context::class.java)
+ )
+ )
+ .thenAnswer {
+ SystemUIDialog(
+ mContext,
+ 0,
+ SystemUIDialog.DEFAULT_DISMISS_ON_DEVICE_LOCK,
+ dialogManager,
+ sysuiState,
+ fakeBroadcastDispatcher,
+ dialogTransitionAnimator,
+ it.getArgument(0)
+ )
+ }
+
+ icon = Pair(drawable, DEVICE_NAME)
+ deviceItem =
+ DeviceItem(
+ type = DeviceItemType.AVAILABLE_MEDIA_BLUETOOTH_DEVICE,
+ cachedBluetoothDevice = cachedBluetoothDevice,
+ deviceName = DEVICE_NAME,
+ connectionSummary = DEVICE_CONNECTION_SUMMARY,
+ iconWithDescription = icon,
+ background = null
+ )
+ `when`(cachedBluetoothDevice.isBusy).thenReturn(false)
+ }
+
+ @Test
+ fun testShowDialog_createRecyclerViewWithAdapter() {
+ val dialog = mBluetoothTileDialogDelegate.createDialog()
+ dialog.show()
+
+ val recyclerView = dialog.requireViewById<RecyclerView>(R.id.device_list)
+
+ assertThat(recyclerView).isNotNull()
+ assertThat(recyclerView.visibility).isEqualTo(VISIBLE)
+ assertThat(recyclerView.adapter).isNotNull()
+ assertThat(recyclerView.layoutManager is LinearLayoutManager).isTrue()
+ }
+
+ @Test
+ fun testShowDialog_displayBluetoothDevice() {
+ testScope.runTest {
+ val dialog = mBluetoothTileDialogDelegate.createDialog()
+ dialog.show()
+ fakeSystemClock.setElapsedRealtime(Long.MAX_VALUE)
+ mBluetoothTileDialogDelegate.onDeviceItemUpdated(
+ dialog,
+ listOf(deviceItem),
+ showSeeAll = false,
+ showPairNewDevice = false
+ )
+
+ val recyclerView = dialog.requireViewById<RecyclerView>(R.id.device_list)
+ val adapter = recyclerView?.adapter as BluetoothTileDialogDelegate.Adapter
+ assertThat(adapter.itemCount).isEqualTo(1)
+ assertThat(adapter.getItem(0).deviceName).isEqualTo(DEVICE_NAME)
+ assertThat(adapter.getItem(0).connectionSummary).isEqualTo(DEVICE_CONNECTION_SUMMARY)
+ assertThat(adapter.getItem(0).iconWithDescription).isEqualTo(icon)
+ }
+ }
+
+ @Test
+ fun testDeviceItemViewHolder_cachedDeviceNotBusy() {
+ deviceItem.isEnabled = true
+
+ val view =
+ LayoutInflater.from(mContext).inflate(R.layout.bluetooth_device_item, null, false)
+ val viewHolder =
+ mBluetoothTileDialogDelegate
+ .Adapter(bluetoothTileDialogCallback)
+ .DeviceItemViewHolder(view)
+ viewHolder.bind(deviceItem, bluetoothTileDialogCallback)
+ val container = view.requireViewById<View>(R.id.bluetooth_device_row)
+
+ assertThat(container).isNotNull()
+ assertThat(container.isEnabled).isTrue()
+ assertThat(container.hasOnClickListeners()).isTrue()
+ }
+
+ @Test
+ fun testDeviceItemViewHolder_cachedDeviceBusy() {
+ deviceItem.isEnabled = false
+
+ val view =
+ LayoutInflater.from(mContext).inflate(R.layout.bluetooth_device_item, null, false)
+ val viewHolder =
+ BluetoothTileDialogDelegate(
+ mContext,
+ uiProperties,
+ CONTENT_HEIGHT,
+ ENABLED,
+ bluetoothTileDialogCallback,
+ {},
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ sysuiDialogFactory,
+ LayoutInflater.from(mContext)
+ )
+ .Adapter(bluetoothTileDialogCallback)
+ .DeviceItemViewHolder(view)
+ viewHolder.bind(deviceItem, bluetoothTileDialogCallback)
+ val container = view.requireViewById<View>(R.id.bluetooth_device_row)
+
+ assertThat(container).isNotNull()
+ assertThat(container.isEnabled).isFalse()
+ assertThat(container.hasOnClickListeners()).isTrue()
+ }
+
+ @Test
+ fun testOnDeviceUpdated_hideSeeAll_showPairNew() {
+ testScope.runTest {
+ val dialog = mBluetoothTileDialogDelegate.createDialog()
+ dialog.show()
+ fakeSystemClock.setElapsedRealtime(Long.MAX_VALUE)
+ mBluetoothTileDialogDelegate.onDeviceItemUpdated(
+ dialog,
+ listOf(deviceItem),
+ showSeeAll = false,
+ showPairNewDevice = true
+ )
+
+ val seeAllButton = dialog.requireViewById<View>(R.id.see_all_button)
+ val pairNewButton = dialog.requireViewById<View>(R.id.pair_new_device_button)
+ val recyclerView = dialog.requireViewById<RecyclerView>(R.id.device_list)
+ val adapter = recyclerView?.adapter as BluetoothTileDialogDelegate.Adapter
+ val scrollViewContent = dialog.requireViewById<View>(R.id.scroll_view)
+
+ assertThat(seeAllButton).isNotNull()
+ assertThat(seeAllButton.visibility).isEqualTo(GONE)
+ assertThat(pairNewButton).isNotNull()
+ assertThat(pairNewButton.visibility).isEqualTo(VISIBLE)
+ assertThat(adapter.itemCount).isEqualTo(1)
+ assertThat(scrollViewContent.layoutParams.height).isEqualTo(WRAP_CONTENT)
+ }
+ }
+
+ @Test
+ fun testShowDialog_cachedHeightLargerThanMinHeight_displayFromCachedHeight() {
+ testScope.runTest {
+ val cachedHeight = Int.MAX_VALUE
+ val dialog =
+ BluetoothTileDialogDelegate(
+ mContext,
+ BluetoothTileDialogViewModel.UiProperties.build(ENABLED, ENABLED),
+ cachedHeight,
+ ENABLED,
+ bluetoothTileDialogCallback,
+ {},
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ sysuiDialogFactory,
+ LayoutInflater.from(mContext)
+ )
+ .createDialog()
+ dialog.show()
+ assertThat(dialog.requireViewById<View>(R.id.scroll_view).layoutParams.height)
+ .isEqualTo(cachedHeight)
+ }
+ }
+
+ @Test
+ fun testShowDialog_cachedHeightLessThanMinHeight_displayFromUiProperties() {
+ testScope.runTest {
+ val dialog =
+ BluetoothTileDialogDelegate(
+ mContext,
+ BluetoothTileDialogViewModel.UiProperties.build(ENABLED, ENABLED),
+ MATCH_PARENT,
+ ENABLED,
+ bluetoothTileDialogCallback,
+ {},
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ sysuiDialogFactory,
+ LayoutInflater.from(mContext)
+ )
+ .createDialog()
+ dialog.show()
+ assertThat(dialog.requireViewById<View>(R.id.scroll_view).layoutParams.height)
+ .isGreaterThan(MATCH_PARENT)
+ }
+ }
+
+ @Test
+ fun testShowDialog_bluetoothEnabled_autoOnToggleGone() {
+ testScope.runTest {
+ val dialog =
+ BluetoothTileDialogDelegate(
+ mContext,
+ BluetoothTileDialogViewModel.UiProperties.build(ENABLED, ENABLED),
+ MATCH_PARENT,
+ ENABLED,
+ bluetoothTileDialogCallback,
+ {},
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ sysuiDialogFactory,
+ LayoutInflater.from(mContext)
+ )
+ .createDialog()
+ dialog.show()
+ assertThat(
+ dialog.requireViewById<View>(R.id.bluetooth_auto_on_toggle_layout).visibility
+ )
+ .isEqualTo(GONE)
+ }
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt
deleted file mode 100644
index 70b0417..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2023 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.qs.tiles.dialog.bluetooth
-
-import android.graphics.drawable.Drawable
-import android.testing.AndroidTestingRunner
-import android.testing.TestableLooper
-import android.view.LayoutInflater
-import android.view.View
-import android.view.View.GONE
-import android.view.View.VISIBLE
-import android.view.ViewGroup.LayoutParams.MATCH_PARENT
-import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
-import androidx.test.filters.SmallTest
-import com.android.internal.logging.UiEventLogger
-import com.android.settingslib.bluetooth.CachedBluetoothDevice
-import com.android.systemui.SysuiTestCase
-import com.android.systemui.res.R
-import com.android.systemui.util.time.FakeSystemClock
-import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.CoroutineDispatcher
-import kotlinx.coroutines.test.TestCoroutineScheduler
-import kotlinx.coroutines.test.TestScope
-import kotlinx.coroutines.test.UnconfinedTestDispatcher
-import kotlinx.coroutines.test.runTest
-import org.junit.Before
-import org.junit.Rule
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.mockito.Mock
-import org.mockito.Mockito.`when`
-import org.mockito.junit.MockitoJUnit
-import org.mockito.junit.MockitoRule
-
-@SmallTest
-@RunWith(AndroidTestingRunner::class)
-@TestableLooper.RunWithLooper(setAsMainLooper = true)
-class BluetoothTileDialogTest : SysuiTestCase() {
- companion object {
- const val DEVICE_NAME = "device"
- const val DEVICE_CONNECTION_SUMMARY = "active"
- const val ENABLED = true
- const val CONTENT_HEIGHT = WRAP_CONTENT
- }
-
- @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
-
- @Mock private lateinit var cachedBluetoothDevice: CachedBluetoothDevice
-
- @Mock private lateinit var bluetoothTileDialogCallback: BluetoothTileDialogCallback
-
- @Mock private lateinit var drawable: Drawable
-
- @Mock private lateinit var uiEventLogger: UiEventLogger
-
- @Mock private lateinit var logger: BluetoothTileDialogLogger
-
- private val uiProperties =
- BluetoothTileDialogViewModel.UiProperties.build(
- isBluetoothEnabled = ENABLED,
- isAutoOnToggleFeatureAvailable = ENABLED
- )
-
- private val fakeSystemClock = FakeSystemClock()
-
- private lateinit var scheduler: TestCoroutineScheduler
- private lateinit var dispatcher: CoroutineDispatcher
- private lateinit var testScope: TestScope
- private lateinit var icon: Pair<Drawable, String>
- private lateinit var bluetoothTileDialog: BluetoothTileDialog
- private lateinit var deviceItem: DeviceItem
-
- @Before
- fun setUp() {
- scheduler = TestCoroutineScheduler()
- dispatcher = UnconfinedTestDispatcher(scheduler)
- testScope = TestScope(dispatcher)
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- CONTENT_HEIGHT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- icon = Pair(drawable, DEVICE_NAME)
- deviceItem =
- DeviceItem(
- type = DeviceItemType.AVAILABLE_MEDIA_BLUETOOTH_DEVICE,
- cachedBluetoothDevice = cachedBluetoothDevice,
- deviceName = DEVICE_NAME,
- connectionSummary = DEVICE_CONNECTION_SUMMARY,
- iconWithDescription = icon,
- background = null
- )
- `when`(cachedBluetoothDevice.isBusy).thenReturn(false)
- }
-
- @Test
- fun testShowDialog_createRecyclerViewWithAdapter() {
- bluetoothTileDialog.show()
-
- val recyclerView = bluetoothTileDialog.requireViewById<RecyclerView>(R.id.device_list)
-
- assertThat(bluetoothTileDialog.isShowing).isTrue()
- assertThat(recyclerView).isNotNull()
- assertThat(recyclerView.visibility).isEqualTo(VISIBLE)
- assertThat(recyclerView.adapter).isNotNull()
- assertThat(recyclerView.layoutManager is LinearLayoutManager).isTrue()
- }
-
- @Test
- fun testShowDialog_displayBluetoothDevice() {
- testScope.runTest {
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- CONTENT_HEIGHT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- bluetoothTileDialog.show()
- fakeSystemClock.setElapsedRealtime(Long.MAX_VALUE)
- bluetoothTileDialog.onDeviceItemUpdated(
- listOf(deviceItem),
- showSeeAll = false,
- showPairNewDevice = false
- )
-
- val recyclerView = bluetoothTileDialog.requireViewById<RecyclerView>(R.id.device_list)
- val adapter = recyclerView.adapter as BluetoothTileDialog.Adapter
- assertThat(adapter.itemCount).isEqualTo(1)
- assertThat(adapter.getItem(0).deviceName).isEqualTo(DEVICE_NAME)
- assertThat(adapter.getItem(0).connectionSummary).isEqualTo(DEVICE_CONNECTION_SUMMARY)
- assertThat(adapter.getItem(0).iconWithDescription).isEqualTo(icon)
- }
- }
-
- @Test
- fun testDeviceItemViewHolder_cachedDeviceNotBusy() {
- deviceItem.isEnabled = true
-
- val view =
- LayoutInflater.from(mContext).inflate(R.layout.bluetooth_device_item, null, false)
- val viewHolder =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- CONTENT_HEIGHT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- .Adapter(bluetoothTileDialogCallback)
- .DeviceItemViewHolder(view)
- viewHolder.bind(deviceItem, bluetoothTileDialogCallback)
- val container = view.requireViewById<View>(R.id.bluetooth_device_row)
-
- assertThat(container).isNotNull()
- assertThat(container.isEnabled).isTrue()
- assertThat(container.hasOnClickListeners()).isTrue()
- }
-
- @Test
- fun testDeviceItemViewHolder_cachedDeviceBusy() {
- deviceItem.isEnabled = false
-
- val view =
- LayoutInflater.from(mContext).inflate(R.layout.bluetooth_device_item, null, false)
- val viewHolder =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- CONTENT_HEIGHT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- .Adapter(bluetoothTileDialogCallback)
- .DeviceItemViewHolder(view)
- viewHolder.bind(deviceItem, bluetoothTileDialogCallback)
- val container = view.requireViewById<View>(R.id.bluetooth_device_row)
-
- assertThat(container).isNotNull()
- assertThat(container.isEnabled).isFalse()
- assertThat(container.hasOnClickListeners()).isTrue()
- }
-
- @Test
- fun testOnDeviceUpdated_hideSeeAll_showPairNew() {
- testScope.runTest {
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- CONTENT_HEIGHT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- bluetoothTileDialog.show()
- fakeSystemClock.setElapsedRealtime(Long.MAX_VALUE)
- bluetoothTileDialog.onDeviceItemUpdated(
- listOf(deviceItem),
- showSeeAll = false,
- showPairNewDevice = true
- )
-
- val seeAllButton = bluetoothTileDialog.requireViewById<View>(R.id.see_all_button)
- val pairNewButton =
- bluetoothTileDialog.requireViewById<View>(R.id.pair_new_device_button)
- val recyclerView = bluetoothTileDialog.requireViewById<RecyclerView>(R.id.device_list)
- val adapter = recyclerView.adapter as BluetoothTileDialog.Adapter
- val scrollViewContent = bluetoothTileDialog.requireViewById<View>(R.id.scroll_view)
-
- assertThat(seeAllButton).isNotNull()
- assertThat(seeAllButton.visibility).isEqualTo(GONE)
- assertThat(pairNewButton).isNotNull()
- assertThat(pairNewButton.visibility).isEqualTo(VISIBLE)
- assertThat(adapter.itemCount).isEqualTo(1)
- assertThat(scrollViewContent.layoutParams.height).isEqualTo(WRAP_CONTENT)
- }
- }
-
- @Test
- fun testShowDialog_cachedHeightLargerThanMinHeight_displayFromCachedHeight() {
- testScope.runTest {
- val cachedHeight = Int.MAX_VALUE
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- cachedHeight,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- bluetoothTileDialog.show()
- assertThat(
- bluetoothTileDialog.requireViewById<View>(R.id.scroll_view).layoutParams.height
- )
- .isEqualTo(cachedHeight)
- }
- }
-
- @Test
- fun testShowDialog_cachedHeightLessThanMinHeight_displayFromUiProperties() {
- testScope.runTest {
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- uiProperties,
- MATCH_PARENT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- bluetoothTileDialog.show()
- assertThat(
- bluetoothTileDialog.requireViewById<View>(R.id.scroll_view).layoutParams.height
- )
- .isGreaterThan(MATCH_PARENT)
- }
- }
-
- @Test
- fun testShowDialog_bluetoothEnabled_autoOnToggleGone() {
- testScope.runTest {
- bluetoothTileDialog =
- BluetoothTileDialog(
- ENABLED,
- BluetoothTileDialogViewModel.UiProperties.build(ENABLED, ENABLED),
- MATCH_PARENT,
- bluetoothTileDialogCallback,
- dispatcher,
- fakeSystemClock,
- uiEventLogger,
- logger,
- mContext
- )
- bluetoothTileDialog.show()
- assertThat(
- bluetoothTileDialog
- .requireViewById<View>(R.id.bluetooth_auto_on_toggle_layout)
- .visibility
- )
- .isEqualTo(GONE)
- }
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
index cb9f4b4..39e2413 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
@@ -16,7 +16,6 @@
package com.android.systemui.qs.tiles.dialog.bluetooth
-import android.content.SharedPreferences
import android.content.pm.UserInfo
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper
@@ -31,10 +30,14 @@
import com.android.systemui.SysuiTestCase
import com.android.systemui.animation.DialogTransitionAnimator
import com.android.systemui.plugins.ActivityStarter
+import com.android.systemui.statusbar.phone.SystemUIDialog
import com.android.systemui.user.data.repository.FakeUserRepository
+import com.android.systemui.util.FakeSharedPreferences
import com.android.systemui.util.concurrency.FakeExecutor
+import com.android.systemui.util.kotlin.getMutableStateFlow
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.nullable
+import com.android.systemui.util.mockito.whenever
import com.android.systemui.util.settings.FakeSettings
import com.android.systemui.util.time.FakeSystemClock
import com.google.common.truth.Truth.assertThat
@@ -50,12 +53,12 @@
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mock
import org.mockito.Mockito.anyBoolean
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
@@ -84,9 +87,15 @@
@Mock private lateinit var uiEventLogger: UiEventLogger
- @Mock private lateinit var logger: BluetoothTileDialogLogger
+ @Mock
+ private lateinit var mBluetoothTileDialogDelegateDelegateFactory:
+ BluetoothTileDialogDelegate.Factory
- @Mock private lateinit var sharedPreferences: SharedPreferences
+ @Mock private lateinit var bluetoothTileDialogDelegate: BluetoothTileDialogDelegate
+
+ @Mock private lateinit var sysuiDialog: SystemUIDialog
+
+ private val sharedPreferences = FakeSharedPreferences()
private lateinit var scheduler: TestCoroutineScheduler
private lateinit var dispatcher: CoroutineDispatcher
@@ -123,20 +132,38 @@
),
mDialogTransitionAnimator,
activityStarter,
- fakeSystemClock,
uiEventLogger,
- logger,
testScope.backgroundScope,
dispatcher,
dispatcher,
sharedPreferences,
+ mBluetoothTileDialogDelegateDelegateFactory
)
- `when`(deviceItemInteractor.deviceItemUpdate).thenReturn(MutableSharedFlow())
- `when`(bluetoothStateInteractor.bluetoothStateUpdate)
+ whenever(deviceItemInteractor.deviceItemUpdate).thenReturn(MutableSharedFlow())
+ whenever(bluetoothStateInteractor.bluetoothStateUpdate)
.thenReturn(MutableStateFlow(null).asStateFlow())
- `when`(deviceItemInteractor.deviceItemUpdateRequest)
+ whenever(deviceItemInteractor.deviceItemUpdateRequest)
.thenReturn(MutableStateFlow(Unit).asStateFlow())
- `when`(bluetoothStateInteractor.isBluetoothEnabled).thenReturn(true)
+ whenever(bluetoothStateInteractor.isBluetoothEnabled).thenReturn(true)
+ whenever(
+ mBluetoothTileDialogDelegateDelegateFactory.create(
+ any(),
+ any(),
+ anyInt(),
+ ArgumentMatchers.anyBoolean(),
+ any(),
+ any()
+ )
+ )
+ .thenReturn(bluetoothTileDialogDelegate)
+ whenever(bluetoothTileDialogDelegate.createDialog()).thenReturn(sysuiDialog)
+ whenever(bluetoothTileDialogDelegate.bluetoothStateToggle)
+ .thenReturn(getMutableStateFlow(false))
+ whenever(bluetoothTileDialogDelegate.deviceItemClick)
+ .thenReturn(getMutableStateFlow(deviceItem))
+ whenever(bluetoothTileDialogDelegate.contentHeight).thenReturn(getMutableStateFlow(0))
+ whenever(bluetoothTileDialogDelegate.bluetoothAutoOnToggle)
+ .thenReturn(getMutableStateFlow(false))
}
@Test
@@ -145,7 +172,6 @@
bluetoothTileDialogViewModel.showDialog(context, null)
verify(mDialogTransitionAnimator, never()).showFromView(any(), any(), any(), any())
- verify(uiEventLogger).log(BluetoothTileDialogUiEvent.BLUETOOTH_TILE_DIALOG_SHOWN)
}
}
@@ -191,7 +217,7 @@
@Test
fun testStartSettingsActivity_activityLaunched_dialogDismissed() {
testScope.runTest {
- `when`(deviceItem.cachedBluetoothDevice).thenReturn(cachedBluetoothDevice)
+ whenever(deviceItem.cachedBluetoothDevice).thenReturn(cachedBluetoothDevice)
bluetoothTileDialogViewModel.showDialog(context, null)
val clickedView = View(context)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/SaveImageInBackgroundTaskTest.kt b/packages/SystemUI/tests/src/com/android/systemui/screenshot/SaveImageInBackgroundTaskTest.kt
index fbb77cd..25dd9fe 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/screenshot/SaveImageInBackgroundTaskTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/SaveImageInBackgroundTaskTest.kt
@@ -34,7 +34,6 @@
import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.whenever
import java.util.concurrent.CompletableFuture
-import java.util.function.Supplier
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
@@ -46,8 +45,6 @@
private val smartActions = mock<ScreenshotSmartActions>()
private val smartActionsProvider = mock<ScreenshotNotificationSmartActionsProvider>()
private val saveImageData = SaveImageInBackgroundData()
- private val sharedTransitionSupplier =
- mock<Supplier<ScreenshotController.SavedImageData.ActionTransition>>()
private val testScreenshotId: String = "testScreenshotId"
private val testBitmap = mock<Bitmap>()
private val testUser = UserHandle.getUserHandleForUid(0)
@@ -88,7 +85,6 @@
imageExporter,
smartActions,
saveImageData,
- sharedTransitionSupplier,
smartActionsProvider,
)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ScreenshotNotificationSmartActionsTest.java b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ScreenshotNotificationSmartActionsTest.java
index 85c8ba7..2a9aca7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ScreenshotNotificationSmartActionsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ScreenshotNotificationSmartActionsTest.java
@@ -20,8 +20,6 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doThrow;
@@ -32,19 +30,15 @@
import static org.mockito.Mockito.when;
import android.app.Notification;
-import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
-import android.os.Bundle;
import android.os.Handler;
-import android.os.Looper;
import android.os.UserHandle;
import android.testing.AndroidTestingRunner;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.screenshot.ScreenshotController.SavedImageData.ActionTransition;
import org.junit.Before;
import org.junit.Test;
@@ -84,7 +78,7 @@
ScreenshotNotificationSmartActionsProvider smartActionsProvider = mock(
ScreenshotNotificationSmartActionsProvider.class);
when(smartActionsProvider.getActions(any(), any(), any(), any(), any(), any()))
- .thenThrow(RuntimeException.class);
+ .thenThrow(RuntimeException.class);
CompletableFuture<List<Notification.Action>> smartActionsFuture =
mScreenshotSmartActions.getSmartActionsFuture(
"", Uri.parse("content://authority/data"), bitmap, smartActionsProvider,
@@ -166,89 +160,4 @@
List<Notification.Action> smartActions = smartActionsFuture.get(5, TimeUnit.MILLISECONDS);
assertEquals(smartActions.size(), 0);
}
-
- // Tests for share action extras
- @Test
- public void testShareActionExtras() {
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
-
- ScreenshotController.SaveImageInBackgroundData
- data = new ScreenshotController.SaveImageInBackgroundData();
- data.image = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
- data.finisher = null;
- data.mActionsReadyListener = null;
- SaveImageInBackgroundTask task =
- new SaveImageInBackgroundTask(mContext, null, null, mScreenshotSmartActions, data,
- ActionTransition::new, mSmartActionsProvider);
-
- Notification.Action shareAction = task.createShareAction(mContext, mContext.getResources(),
- Uri.parse("Screenshot_123.png"), true).get().action;
-
- Intent intent = shareAction.actionIntent.getIntent();
- assertNotNull(intent);
- Bundle bundle = intent.getExtras();
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_ID));
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED));
- assertEquals(ScreenshotController.ACTION_TYPE_SHARE, shareAction.title);
- assertEquals(Intent.ACTION_SEND, intent.getAction());
- }
-
- // Tests for edit action extras
- @Test
- public void testEditActionExtras() {
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
-
- ScreenshotController.SaveImageInBackgroundData
- data = new ScreenshotController.SaveImageInBackgroundData();
- data.image = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
- data.finisher = null;
- data.mActionsReadyListener = null;
- SaveImageInBackgroundTask task =
- new SaveImageInBackgroundTask(mContext, null, null, mScreenshotSmartActions, data,
- ActionTransition::new, mSmartActionsProvider);
-
- Notification.Action editAction = task.createEditAction(mContext, mContext.getResources(),
- Uri.parse("Screenshot_123.png"), true).get().action;
-
- Intent intent = editAction.actionIntent.getIntent();
- assertNotNull(intent);
- Bundle bundle = intent.getExtras();
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_ID));
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED));
- assertEquals(ScreenshotController.ACTION_TYPE_EDIT, editAction.title);
- assertEquals(Intent.ACTION_EDIT, intent.getAction());
- }
-
- // Tests for share action extras
- @Test
- public void testDeleteActionExtras() {
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
-
- ScreenshotController.SaveImageInBackgroundData
- data = new ScreenshotController.SaveImageInBackgroundData();
- data.image = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
- data.finisher = null;
- data.mActionsReadyListener = null;
- SaveImageInBackgroundTask task =
- new SaveImageInBackgroundTask(mContext, null, null, mScreenshotSmartActions, data,
- ActionTransition::new, mSmartActionsProvider);
-
- Notification.Action deleteAction = task.createDeleteAction(mContext,
- mContext.getResources(),
- Uri.parse("Screenshot_123.png"), true);
-
- Intent intent = deleteAction.actionIntent.getIntent();
- assertNotNull(intent);
- Bundle bundle = intent.getExtras();
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_ID));
- assertTrue(bundle.containsKey(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED));
- assertEquals(deleteAction.title, ScreenshotController.ACTION_TYPE_DELETE);
- assertNull(intent.getAction());
- }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
index 950a9db..fd7b139 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
@@ -599,6 +599,8 @@
// Primary Bouncer->Gone
when(mPrimaryBouncerToGoneTransitionViewModel.getLockscreenAlpha())
.thenReturn(emptyFlow());
+ when(mPrimaryBouncerToGoneTransitionViewModel.getNotificationAlpha())
+ .thenReturn(emptyFlow());
NotificationsKeyguardViewStateRepository notifsKeyguardViewStateRepository =
new NotificationsKeyguardViewStateRepository();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
index aa53558..1504d4c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
@@ -92,6 +92,21 @@
@TestableLooper.RunWithLooper
public class KeyguardIndicationControllerTest extends KeyguardIndicationControllerBaseTest {
@Test
+ public void afterFaceLockout_skipShowingFaceNotRecognized() {
+ createController();
+ onFaceLockoutError("lockout");
+ verifyIndicationShown(INDICATION_TYPE_BIOMETRIC_MESSAGE, "lockout");
+ clearInvocations(mRotateTextViewController);
+
+ // WHEN face sends an onBiometricHelp BIOMETRIC_HELP_FACE_NOT_RECOGNIZED (face fail)
+ mKeyguardUpdateMonitorCallback.onBiometricHelp(
+ BIOMETRIC_HELP_FACE_NOT_RECOGNIZED,
+ "Face not recognized",
+ BiometricSourceType.FACE);
+ verifyNoMessage(INDICATION_TYPE_BIOMETRIC_MESSAGE); // no updated message
+ }
+
+ @Test
public void createController_setIndicationAreaAgain_destroysPreviousRotateTextViewController() {
// GIVEN a controller with a mocked rotate text view controlller
final KeyguardIndicationRotateTextViewController mockedRotateTextViewController =
@@ -593,7 +608,7 @@
mController.getKeyguardCallback().onBiometricError(FACE_ERROR_TIMEOUT,
"A message", BiometricSourceType.FACE);
- verify(mStatusBarKeyguardViewManager).setKeyguardMessage(eq(message), any());
+ verify(mStatusBarKeyguardViewManager).setKeyguardMessage(eq(message), any(), any());
}
@Test
@@ -608,7 +623,8 @@
mController.getKeyguardCallback().onBiometricError(FACE_ERROR_TIMEOUT,
"A message", BiometricSourceType.FACE);
- verify(mStatusBarKeyguardViewManager, never()).setKeyguardMessage(eq(message), any());
+ verify(mStatusBarKeyguardViewManager, never()).setKeyguardMessage(
+ eq(message), any(), any());
}
@Test
@@ -1242,7 +1258,7 @@
public void onBiometricFailed_resetFaceHelpMessageDeferral() {
createController();
- // WHEN face sends an onBiometricHelp BIOMETRIC_HELP_FACE_NOT_RECOGNIZED
+ // WHEN face sends an onBiometricAuthFailed
mKeyguardUpdateMonitorCallback.onBiometricAuthFailed(BiometricSourceType.FACE);
// THEN face help message deferral is reset
@@ -1331,7 +1347,9 @@
verify(mStatusBarKeyguardViewManager)
.setKeyguardMessage(
eq(mContext.getString(R.string.keyguard_face_unlock_unavailable)),
- any());
+ any(),
+ any()
+ );
}
@Test
@@ -1471,6 +1489,71 @@
mContext.getString(R.string.keyguard_suggest_fingerprint));
}
+ @Test
+ public void faceErrorMessageDroppedBecauseFingerprintMessageShowing() {
+ createController();
+ mController.setVisible(true);
+ mController.getKeyguardCallback().onBiometricHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
+ "fp not recognized", BiometricSourceType.FINGERPRINT);
+ clearInvocations(mRotateTextViewController);
+
+ onFaceLockoutError("lockout");
+ verifyNoMessage(INDICATION_TYPE_BIOMETRIC_MESSAGE);
+ }
+
+ @Test
+ public void faceUnlockedMessageShowsEvenWhenFingerprintMessageShowing() {
+ createController();
+ mController.setVisible(true);
+ mController.getKeyguardCallback().onBiometricHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
+ "fp not recognized", BiometricSourceType.FINGERPRINT);
+ clearInvocations(mRotateTextViewController);
+
+ when(mKeyguardUpdateMonitor.getIsFaceAuthenticated()).thenReturn(true);
+ when(mKeyguardUpdateMonitor.getUserCanSkipBouncer(getCurrentUser()))
+ .thenReturn(true);
+ mController.getKeyguardCallback().onBiometricAuthenticated(0,
+ BiometricSourceType.FACE, false);
+ verifyIndicationMessage(
+ INDICATION_TYPE_BIOMETRIC_MESSAGE,
+ mContext.getString(R.string.keyguard_face_successful_unlock));
+ }
+
+ @Test
+ public void onTrustAgentErrorMessageDroppedBecauseFingerprintMessageShowing() {
+ createController();
+ mController.setVisible(true);
+ mController.getKeyguardCallback().onBiometricHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
+ "fp not recognized", BiometricSourceType.FINGERPRINT);
+ clearInvocations(mRotateTextViewController);
+
+ mKeyguardUpdateMonitorCallback.onTrustAgentErrorMessage("testMessage");
+ verifyNoMessage(INDICATION_TYPE_TRUST);
+ verifyNoMessage(INDICATION_TYPE_BIOMETRIC_MESSAGE);
+ }
+
+ @Test
+ public void trustGrantedMessageShowsEvenWhenFingerprintMessageShowing() {
+ createController();
+ mController.setVisible(true);
+ mController.getKeyguardCallback().onBiometricHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
+ "fp not recognized", BiometricSourceType.FINGERPRINT);
+ clearInvocations(mRotateTextViewController);
+
+ // GIVEN trust is granted
+ when(mKeyguardUpdateMonitor.getUserHasTrust(anyInt())).thenReturn(true);
+
+ // WHEN the showTrustGranted method is called
+ final String trustGrantedMsg = "testing trust granted message after fp message";
+ mController.getKeyguardCallback().onTrustGrantedForCurrentUser(
+ false, false, new TrustGrantFlags(0), trustGrantedMsg);
+
+ // THEN verify the trust granted message shows
+ verifyIndicationMessage(
+ INDICATION_TYPE_TRUST,
+ trustGrantedMsg);
+ }
+
private void screenIsTurningOn() {
when(mScreenLifecycle.getScreenState()).thenReturn(SCREEN_TURNING_ON);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
index 5e8b62e..fd2dead 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
@@ -26,6 +26,7 @@
import android.view.MotionEvent
import android.view.PrivacyIndicatorBounds
import android.view.RoundedCorners
+import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import androidx.test.filters.SmallTest
@@ -50,6 +51,8 @@
class PhoneStatusBarViewTest : SysuiTestCase() {
private lateinit var view: PhoneStatusBarView
+ private val systemIconsContainer: View
+ get() = view.requireViewById(R.id.system_icons)
private val contentInsetsProvider = mock<StatusBarContentInsetsProvider>()
private val windowController = mock<StatusBarWindowController>()
@@ -62,6 +65,7 @@
)
mDependency.injectTestDependency(DarkIconDispatcher::class.java, mock<DarkIconDispatcher>())
mDependency.injectTestDependency(StatusBarWindowController::class.java, windowController)
+ context.ensureTestableResources()
view = spy(createStatusBarView())
whenever(view.rootWindowInsets).thenReturn(emptyWindowInsets())
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
@@ -217,7 +221,7 @@
val newInsets = Insets.NONE
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
- .thenReturn(newInsets)
+ .thenReturn(newInsets)
view.onConfigurationChanged(Configuration())
assertThat(view.paddingLeft).isEqualTo(previousInsets.left)
@@ -239,7 +243,7 @@
val newInsets = Insets.NONE
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
- .thenReturn(newInsets)
+ .thenReturn(newInsets)
configuration.densityDpi = 456
view.onConfigurationChanged(configuration)
@@ -262,7 +266,7 @@
val newInsets = Insets.NONE
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
- .thenReturn(newInsets)
+ .thenReturn(newInsets)
configuration.fontScale = 2f
view.onConfigurationChanged(configuration)
@@ -273,6 +277,19 @@
}
@Test
+ fun onConfigurationChanged_systemIconsHeightChanged_containerHeightIsUpdated() {
+ val newHeight = 123456
+ context.orCreateTestableResources.addOverride(
+ R.dimen.status_bar_system_icons_height,
+ newHeight
+ )
+
+ view.onConfigurationChanged(Configuration())
+
+ assertThat(systemIconsContainer.layoutParams.height).isEqualTo(newHeight)
+ }
+
+ @Test
fun onApplyWindowInsets_updatesLeftTopRightPaddingsBasedOnInsets() {
val insets = Insets.of(/* left = */ 90, /* top = */ 10, /* right = */ 45, /* bottom = */ 50)
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
index bd7406a..3666248 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
@@ -97,6 +97,7 @@
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.unfold.SysUIUnfoldComponent;
import com.android.systemui.user.domain.interactor.SelectedUserInteractor;
+import com.android.systemui.util.kotlin.JavaAdapter;
import com.google.common.truth.Truth;
@@ -222,7 +223,8 @@
() -> mock(WindowManagerLockscreenVisibilityInteractor.class),
() -> mock(KeyguardDismissActionInteractor.class),
mSelectedUserInteractor,
- () -> mock(KeyguardSurfaceBehindInteractor.class)) {
+ () -> mock(KeyguardSurfaceBehindInteractor.class),
+ mock(JavaAdapter.class)) {
@Override
public ViewRootImpl getViewRootImpl() {
return mViewRootImpl;
@@ -730,7 +732,8 @@
() -> mock(WindowManagerLockscreenVisibilityInteractor.class),
() -> mock(KeyguardDismissActionInteractor.class),
mSelectedUserInteractor,
- () -> mock(KeyguardSurfaceBehindInteractor.class)) {
+ () -> mock(KeyguardSurfaceBehindInteractor.class),
+ mock(JavaAdapter.class)) {
@Override
public ViewRootImpl getViewRootImpl() {
return mViewRootImpl;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
index b958f35..a41bc0d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
@@ -616,7 +616,7 @@
dataType: SignalIcon.MobileIconGroup? = THREE_G,
subId: Int? = 1,
carrierId: Int? = UNKNOWN_CARRIER_ID,
- inflateStrength: Boolean? = false,
+ inflateStrength: Boolean = false,
activity: Int? = null,
carrierNetworkChange: Boolean = false,
roaming: Boolean = false,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
index 23a9207..ed07ad2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
@@ -21,21 +21,40 @@
import android.os.Build;
import android.os.PowerManager;
+import android.platform.test.flag.junit.FlagsParameterization;
+import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
+import com.android.systemui.Flags;
import com.android.systemui.SysuiTestCase;
import org.junit.After;
+import org.junit.Assume;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.List;
@SmallTest
-@RunWith(AndroidJUnit4.class)
+@RunWith(Parameterized.class)
public class WakeLockTest extends SysuiTestCase {
+ @Parameterized.Parameters(name = "{0}")
+ public static List<FlagsParameterization> getFlags() {
+ return FlagsParameterization.allCombinationsOf(
+ Flags.FLAG_DELAYED_WAKELOCK_RELEASE_ON_BACKGROUND_THREAD);
+ }
+
+ @Rule public final SetFlagsRule mSetFlagsRule;
+
+ public WakeLockTest(FlagsParameterization flags) {
+ mSetFlagsRule = new SetFlagsRule(SetFlagsRule.DefaultInitValueType.NULL_DEFAULT, flags);
+ }
+
private static final String WHY = "test";
WakeLock mWakeLock;
PowerManager.WakeLock mInner;
@@ -91,10 +110,7 @@
@Test
public void prodBuild_wakeLock_releaseWithoutAcquire_noThrow() {
- if (Build.IS_ENG) {
- return;
- }
-
+ Assume.assumeFalse(Build.IS_ENG);
// shouldn't throw an exception on production builds
mWakeLock.release(WHY);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java
index a930860..fbefb0e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java
@@ -609,6 +609,7 @@
mSysUiState,
mFeatureFlags,
mNotifPipelineFlags,
+ syncExecutor,
syncExecutor);
mBubblesManager.addNotifCallback(mNotifCallback);
@@ -651,7 +652,7 @@
}
@Test
- public void dreamingHidesBubbles() throws RemoteException {
+ public void bubblesHiddenWhileDreaming() throws RemoteException {
mBubbleController.updateBubble(mBubbleEntry);
assertTrue(mBubbleController.hasBubbles());
assertThat(mBubbleController.getStackView().getVisibility()).isEqualTo(View.VISIBLE);
@@ -662,7 +663,17 @@
mKeyguardStateControllerCallbackCaptor.getValue();
callback.onKeyguardShowingChanged();
+ // Dreaming should hide bubbles
assertThat(mBubbleController.getStackView().getVisibility()).isEqualTo(View.INVISIBLE);
+
+ // Finish dreaming should show bubbles
+ mNotificationShadeWindowController.setDreaming(false);
+ when(mIDreamManager.isDreamingOrInPreview()).thenReturn(false); // dreaming finished
+
+ // Dreaming updates come through mNotificationShadeWindowController
+ mNotificationShadeWindowController.notifyStateChangedCallbacks();
+
+ assertThat(mBubbleController.getStackView().getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
diff --git a/packages/SystemUI/tests/utils/src/android/content/ContextKosmos.kt b/packages/SystemUI/tests/utils/src/android/content/ContextKosmos.kt
index f6ddfcc..185deea 100644
--- a/packages/SystemUI/tests/utils/src/android/content/ContextKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/android/content/ContextKosmos.kt
@@ -20,5 +20,6 @@
import com.android.systemui.kosmos.testCase
import com.android.systemui.util.mockito.mock
-var Kosmos.applicationContext: Context by Kosmos.Fixture { testCase.context }
+var Kosmos.applicationContext: Context by
+ Kosmos.Fixture { testCase.context.apply { ensureTestableResources() } }
val Kosmos.mockedContext: Context by Kosmos.Fixture { mock<Context>() }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/data/repository/FakePromptRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/data/repository/FakePromptRepository.kt
index f192de2..c3af437 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/data/repository/FakePromptRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/data/repository/FakePromptRepository.kt
@@ -1,6 +1,8 @@
package com.android.systemui.biometrics.data.repository
+import android.hardware.biometrics.Flags
import android.hardware.biometrics.PromptInfo
+import com.android.systemui.biometrics.Utils
import com.android.systemui.biometrics.shared.model.PromptKind
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -26,6 +28,9 @@
private val _isConfirmationRequired = MutableStateFlow(false)
override val isConfirmationRequired = _isConfirmationRequired.asStateFlow()
+ private val _showBpWithoutIconForCredential = MutableStateFlow(false)
+ override val showBpWithoutIconForCredential = _showBpWithoutIconForCredential.asStateFlow()
+
private val _opPackageName: MutableStateFlow<String?> = MutableStateFlow(null)
override val opPackageName = _opPackageName.asStateFlow()
@@ -69,6 +74,16 @@
_isConfirmationRequired.value = false
}
+ override fun setShouldShowBpWithoutIconForCredential(promptInfo: PromptInfo) {
+ val hasCredentialViewShown = kind.value !is PromptKind.Biometric
+ val showBpForCredential =
+ Flags.customBiometricPrompt() &&
+ !Utils.isBiometricAllowed(promptInfo) &&
+ Utils.isDeviceCredentialAllowed(promptInfo) &&
+ promptInfo.contentView != null
+ _showBpWithoutIconForCredential.value = showBpForCredential && !hasCredentialViewShown
+ }
+
fun setIsShowing(showing: Boolean) {
_isShowing.value = showing
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelKosmos.kt
index ecf66a2..8ca53e6 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelKosmos.kt
@@ -42,6 +42,10 @@
aodToLockscreenTransitionViewModel = aodToLockscreenTransitionViewModel,
dozingToLockscreenTransitionViewModel = dozingToLockscreenTransitionViewModel,
glanceableHubToLockscreenTransitionViewModel = glanceableHubToLockscreenTransitionViewModel,
+ goneToAodTransitionViewModel = goneToAodTransitionViewModel,
+ goneToDozingTransitionViewModel = goneToDozingTransitionViewModel,
+ lockscreenToAodTransitionViewModel = lockscreenToAodTransitionViewModel,
+ lockscreenToDozingTransitionViewModel = lockscreenToDozingTransitionViewModel,
lockscreenToDreamingTransitionViewModel = lockscreenToDreamingTransitionViewModel,
lockscreenToGlanceableHubTransitionViewModel = lockscreenToGlanceableHubTransitionViewModel,
lockscreenToGoneTransitionViewModel = lockscreenToGoneTransitionViewModel,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
index 96de4ba..8da5dd4 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
@@ -20,6 +20,7 @@
import com.android.systemui.keyguard.domain.interactor.keyguardBlueprintInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardClockInteractor
import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.statusbar.policy.splitShadeStateController
val Kosmos.lockscreenContentViewModel by
Kosmos.Fixture {
@@ -28,5 +29,6 @@
interactor = keyguardBlueprintInteractor,
authController = authController,
longPress = keyguardLongPressViewModel,
+ splitShadeStateController = splitShadeStateController,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/util/settings/FakeGlobalSettingsKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/util/settings/FakeGlobalSettingsKosmos.kt
new file mode 100644
index 0000000..df6fc41
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/util/settings/FakeGlobalSettingsKosmos.kt
@@ -0,0 +1,22 @@
+/*
+ * 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.util.settings
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+
+val Kosmos.fakeGlobalSettings: FakeGlobalSettings by Fixture { FakeGlobalSettings() }
diff --git a/proto/src/criticalevents/critical_event_log.proto b/proto/src/criticalevents/critical_event_log.proto
index cffcd09..71d291a 100644
--- a/proto/src/criticalevents/critical_event_log.proto
+++ b/proto/src/criticalevents/critical_event_log.proto
@@ -61,6 +61,12 @@
NativeCrash native_crash = 6;
SystemServerStarted system_server_started = 7;
InstallPackages install_packages = 8;
+ ExcessiveBinderCalls excessive_binder_calls = 9;
+ }
+
+ message ExcessiveBinderCalls {
+ // The uid sending many calls.
+ optional int32 uid = 1;
}
message InstallPackages {}
diff --git a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
index d0eb59d..1dab40e 100644
--- a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
+++ b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
@@ -25,12 +25,12 @@
import static android.content.pm.PackageManager.FEATURE_WATCH;
import static com.android.server.companion.CompanionDeviceManagerService.DEBUG;
-import static com.android.server.companion.MetricUtils.logCreateAssociation;
-import static com.android.server.companion.PackageUtils.enforceUsesCompanionDeviceFeature;
-import static com.android.server.companion.PermissionsUtils.enforcePermissionsForAssociation;
-import static com.android.server.companion.RolesUtils.addRoleHolderForAssociation;
-import static com.android.server.companion.RolesUtils.isRoleHolder;
-import static com.android.server.companion.Utils.prepareForIpc;
+import static com.android.server.companion.utils.MetricUtils.logCreateAssociation;
+import static com.android.server.companion.utils.PackageUtils.enforceUsesCompanionDeviceFeature;
+import static com.android.server.companion.utils.PermissionsUtils.enforcePermissionForCreatingAssociation;
+import static com.android.server.companion.utils.RolesUtils.addRoleHolderForAssociation;
+import static com.android.server.companion.utils.RolesUtils.isRoleHolder;
+import static com.android.server.companion.utils.Utils.prepareForIpc;
import static java.util.Objects.requireNonNull;
@@ -59,6 +59,7 @@
import android.util.Slog;
import com.android.internal.R;
+import com.android.server.companion.utils.PackageUtils;
import java.util.List;
@@ -167,7 +168,7 @@
}
// 1. Enforce permissions and other requirements.
- enforcePermissionsForAssociation(mContext, request, packageUid);
+ enforcePermissionForCreatingAssociation(mContext, request, packageUid);
enforceUsesCompanionDeviceFeature(mContext, userId, packageName);
// 2a. Check if association can be created without launching UI (i.e. CDM needs NEITHER
@@ -257,7 +258,7 @@
// 1. Need to check permissions again in case something changed, since we first received
// this request.
try {
- enforcePermissionsForAssociation(mContext, request, packageUid);
+ enforcePermissionForCreatingAssociation(mContext, request, packageUid);
} catch (SecurityException e) {
// Since, at this point the caller is our own UI, we need to catch the exception on
// forward it back to the application via the callback.
@@ -316,6 +317,9 @@
// If it is null, then the operation will succeed without granting any role.
addRoleHolderForAssociation(mService.getContext(), association, success -> {
if (success) {
+ Slog.i(TAG, "Added " + association.getDeviceProfile() + " role to userId="
+ + association.getUserId() + ", packageName="
+ + association.getPackageName());
addAssociationToStore(association);
sendCallbackAndFinish(association, callback, resultReceiver);
} else {
diff --git a/services/companion/java/com/android/server/companion/AssociationRevokeProcessor.java b/services/companion/java/com/android/server/companion/AssociationRevokeProcessor.java
index de6382e..10963ea 100644
--- a/services/companion/java/com/android/server/companion/AssociationRevokeProcessor.java
+++ b/services/companion/java/com/android/server/companion/AssociationRevokeProcessor.java
@@ -20,8 +20,8 @@
import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PROJECTION;
import static com.android.internal.util.CollectionUtils.any;
-import static com.android.server.companion.MetricUtils.logRemoveAssociation;
-import static com.android.server.companion.RolesUtils.removeRoleHolderForAssociation;
+import static com.android.server.companion.utils.MetricUtils.logRemoveAssociation;
+import static com.android.server.companion.utils.RolesUtils.removeRoleHolderForAssociation;
import static com.android.server.companion.CompanionDeviceManagerService.PerUserAssociationSet;
import android.annotation.NonNull;
@@ -203,7 +203,8 @@
return false;
}
- removeRoleHolderForAssociation(mContext, association);
+ removeRoleHolderForAssociation(mContext, association.getUserId(),
+ association.getPackageName(), association.getDeviceProfile());
return true;
}
diff --git a/services/companion/java/com/android/server/companion/CompanionApplicationController.java b/services/companion/java/com/android/server/companion/CompanionApplicationController.java
index af0777c..559ebbc 100644
--- a/services/companion/java/com/android/server/companion/CompanionApplicationController.java
+++ b/services/companion/java/com/android/server/companion/CompanionApplicationController.java
@@ -38,6 +38,9 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.infra.PerUser;
import com.android.server.companion.presence.CompanionDevicePresenceMonitor;
+import com.android.server.companion.presence.ObservableUuid;
+import com.android.server.companion.presence.ObservableUuidStore;
+import com.android.server.companion.utils.PackageUtils;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -61,7 +64,7 @@
* <ul>
* <li> {@link #bindCompanionApplication(int, String, boolean)}
* <li> {@link #unbindCompanionApplication(int, String)}
- * <li> {@link #notifyCompanionApplicationDevicePresenceEvent(AssociationInfo, int)}
+ * <li> {@link #notifyCompanionDevicePresenceEvent(AssociationInfo, int)}
* <li> {@link #isCompanionApplicationBound(int, String)}
* <li> {@link #isRebindingCompanionApplicationScheduled(int, String)}
* </ul>
@@ -251,7 +254,13 @@
serviceConnector.connect();
}
- void notifyCompanionApplicationDeviceAppeared(AssociationInfo association) {
+ /**
+ * Notify the app that the device appeared.
+ *
+ * @deprecated use {@link #notifyCompanionDevicePresenceEvent(AssociationInfo, int)} instead
+ */
+ @Deprecated
+ public void notifyCompanionApplicationDeviceAppeared(AssociationInfo association) {
final int userId = association.getUserId();
final String packageName = association.getPackageName();
@@ -273,7 +282,13 @@
primaryServiceConnector.postOnDeviceAppeared(association);
}
- void notifyCompanionApplicationDeviceDisappeared(AssociationInfo association) {
+ /**
+ * Notify the app that the device disappeared.
+ *
+ * @deprecated use {@link #notifyCompanionDevicePresenceEvent(AssociationInfo, int)} instead
+ */
+ @Deprecated
+ public void notifyCompanionApplicationDeviceDisappeared(AssociationInfo association) {
final int userId = association.getUserId();
final String packageName = association.getPackageName();
@@ -295,7 +310,10 @@
primaryServiceConnector.postOnDeviceDisappeared(association);
}
- void notifyCompanionApplicationDevicePresenceEvent(AssociationInfo association, int event) {
+ /**
+ * Notify the app that the device appeared.
+ */
+ public void notifyCompanionDevicePresenceEvent(AssociationInfo association, int event) {
final int userId = association.getUserId();
final String packageName = association.getPackageName();
final CompanionDeviceServiceConnector primaryServiceConnector =
@@ -318,7 +336,10 @@
primaryServiceConnector.postOnDevicePresenceEvent(devicePresenceEvent);
}
- void notifyApplicationDevicePresenceEvent(ObservableUuid uuid, int event) {
+ /**
+ * Notify the app that the device disappeared.
+ */
+ public void notifyUuidDevicePresenceEvent(ObservableUuid uuid, int event) {
final int userId = uuid.getUserId();
final ParcelUuid parcelUuid = uuid.getUuid();
final String packageName = uuid.getPackageName();
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
index 09c7793..a478a3d 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
@@ -38,15 +38,15 @@
import static com.android.internal.util.Preconditions.checkState;
import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import static com.android.server.companion.AssociationStore.CHANGE_TYPE_UPDATED_ADDRESS_UNCHANGED;
-import static com.android.server.companion.PackageUtils.isRestrictedSettingsAllowed;
-import static com.android.server.companion.PackageUtils.enforceUsesCompanionDeviceFeature;
-import static com.android.server.companion.PackageUtils.getPackageInfo;
-import static com.android.server.companion.PermissionsUtils.checkCallerCanManageCompanionDevice;
-import static com.android.server.companion.PermissionsUtils.enforceCallerCanManageAssociationsForPackage;
-import static com.android.server.companion.PermissionsUtils.enforceCallerCanObservingDevicePresenceByUuid;
-import static com.android.server.companion.PermissionsUtils.enforceCallerIsSystemOr;
-import static com.android.server.companion.PermissionsUtils.enforceCallerIsSystemOrCanInteractWithUserId;
-import static com.android.server.companion.PermissionsUtils.sanitizeWithCallerChecks;
+import static com.android.server.companion.utils.PackageUtils.isRestrictedSettingsAllowed;
+import static com.android.server.companion.utils.PackageUtils.enforceUsesCompanionDeviceFeature;
+import static com.android.server.companion.utils.PackageUtils.getPackageInfo;
+import static com.android.server.companion.utils.PermissionsUtils.checkCallerCanManageCompanionDevice;
+import static com.android.server.companion.utils.PermissionsUtils.enforceCallerCanManageAssociationsForPackage;
+import static com.android.server.companion.utils.PermissionsUtils.enforceCallerCanObservingDevicePresenceByUuid;
+import static com.android.server.companion.utils.PermissionsUtils.enforceCallerIsSystemOr;
+import static com.android.server.companion.utils.PermissionsUtils.enforceCallerIsSystemOrCanInteractWithUserId;
+import static com.android.server.companion.utils.PermissionsUtils.sanitizeWithCallerChecks;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.DAYS;
@@ -123,6 +123,8 @@
import com.android.server.companion.datatransfer.contextsync.CrossDeviceSyncController;
import com.android.server.companion.datatransfer.contextsync.CrossDeviceSyncControllerCallback;
import com.android.server.companion.presence.CompanionDevicePresenceMonitor;
+import com.android.server.companion.presence.ObservableUuid;
+import com.android.server.companion.presence.ObservableUuidStore;
import com.android.server.companion.transport.CompanionTransportManager;
import com.android.server.pm.UserManagerInternal;
import com.android.server.wm.ActivityTaskManagerInternal;
@@ -435,7 +437,7 @@
bindApplicationIfNeeded(association);
- mCompanionAppController.notifyCompanionApplicationDevicePresenceEvent(
+ mCompanionAppController.notifyCompanionDevicePresenceEvent(
association, event);
break;
case EVENT_BLE_DISAPPEARED:
@@ -446,7 +448,7 @@
return;
}
if (association.shouldBindWhenPresent()) {
- mCompanionAppController.notifyCompanionApplicationDevicePresenceEvent(
+ mCompanionAppController.notifyCompanionDevicePresenceEvent(
association, event);
}
// Check if there are other devices associated to the app that are present.
@@ -475,7 +477,7 @@
Log.i(TAG, "u" + userId + "\\" + packageName + " is already bound");
}
- mCompanionAppController.notifyApplicationDevicePresenceEvent(uuid, event);
+ mCompanionAppController.notifyUuidDevicePresenceEvent(uuid, event);
break;
case EVENT_BT_DISCONNECTED:
@@ -484,7 +486,7 @@
return;
}
- mCompanionAppController.notifyApplicationDevicePresenceEvent(uuid, event);
+ mCompanionAppController.notifyUuidDevicePresenceEvent(uuid, event);
// Check if there are other devices associated to the app or the UUID to be
// observed are present.
if (shouldBindPackage(userId, packageName)) return;
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java b/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
index de4f2b6..74b4cab 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
@@ -18,7 +18,7 @@
import static android.companion.CompanionDeviceManager.MESSAGE_REQUEST_CONTEXT_SYNC;
-import static com.android.server.companion.PermissionsUtils.sanitizeWithCallerChecks;
+import static com.android.server.companion.utils.PermissionsUtils.sanitizeWithCallerChecks;
import android.companion.AssociationInfo;
import android.companion.ContextSyncMessage;
@@ -36,6 +36,7 @@
import com.android.server.companion.datatransfer.contextsync.BitmapUtils;
import com.android.server.companion.datatransfer.contextsync.CrossDeviceSyncController;
import com.android.server.companion.presence.CompanionDevicePresenceMonitor;
+import com.android.server.companion.presence.ObservableUuid;
import com.android.server.companion.transport.CompanionTransportManager;
import java.io.PrintWriter;
diff --git a/services/companion/java/com/android/server/companion/PersistentDataStore.java b/services/companion/java/com/android/server/companion/PersistentDataStore.java
index 1ebe65c..7527efb 100644
--- a/services/companion/java/com/android/server/companion/PersistentDataStore.java
+++ b/services/companion/java/com/android/server/companion/PersistentDataStore.java
@@ -27,11 +27,11 @@
import static com.android.internal.util.XmlUtils.writeStringAttribute;
import static com.android.server.companion.CompanionDeviceManagerService.getFirstAssociationIdForUser;
import static com.android.server.companion.CompanionDeviceManagerService.getLastAssociationIdForUser;
-import static com.android.server.companion.DataStoreUtils.createStorageFileForUser;
-import static com.android.server.companion.DataStoreUtils.fileToByteArray;
-import static com.android.server.companion.DataStoreUtils.isEndOfTag;
-import static com.android.server.companion.DataStoreUtils.isStartOfTag;
-import static com.android.server.companion.DataStoreUtils.writeToFileSafely;
+import static com.android.server.companion.utils.DataStoreUtils.createStorageFileForUser;
+import static com.android.server.companion.utils.DataStoreUtils.fileToByteArray;
+import static com.android.server.companion.utils.DataStoreUtils.isEndOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.isStartOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.writeToFileSafely;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -51,6 +51,7 @@
import com.android.internal.util.XmlUtils;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
+import com.android.server.companion.utils.DataStoreUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
diff --git a/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferProcessor.java b/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferProcessor.java
index 260b21f..74236a4 100644
--- a/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferProcessor.java
+++ b/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferProcessor.java
@@ -23,7 +23,7 @@
import static android.content.ComponentName.createRelative;
import static android.content.pm.PackageManager.FEATURE_WATCH;
-import static com.android.server.companion.Utils.prepareForIpc;
+import static com.android.server.companion.utils.Utils.prepareForIpc;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -54,9 +54,9 @@
import com.android.internal.R;
import com.android.server.companion.AssociationStore;
import com.android.server.companion.CompanionDeviceManagerService;
-import com.android.server.companion.PackageUtils;
-import com.android.server.companion.PermissionsUtils;
import com.android.server.companion.transport.CompanionTransportManager;
+import com.android.server.companion.utils.PackageUtils;
+import com.android.server.companion.utils.PermissionsUtils;
import java.util.List;
import java.util.concurrent.ExecutorService;
diff --git a/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferRequestStore.java b/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferRequestStore.java
index c4c80f9..ee816a0 100644
--- a/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferRequestStore.java
+++ b/services/companion/java/com/android/server/companion/datatransfer/SystemDataTransferRequestStore.java
@@ -22,11 +22,11 @@
import static com.android.internal.util.XmlUtils.readIntAttribute;
import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
import static com.android.internal.util.XmlUtils.writeIntAttribute;
-import static com.android.server.companion.DataStoreUtils.createStorageFileForUser;
-import static com.android.server.companion.DataStoreUtils.fileToByteArray;
-import static com.android.server.companion.DataStoreUtils.isEndOfTag;
-import static com.android.server.companion.DataStoreUtils.isStartOfTag;
-import static com.android.server.companion.DataStoreUtils.writeToFileSafely;
+import static com.android.server.companion.utils.DataStoreUtils.createStorageFileForUser;
+import static com.android.server.companion.utils.DataStoreUtils.fileToByteArray;
+import static com.android.server.companion.utils.DataStoreUtils.isEndOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.isStartOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.writeToFileSafely;
import android.annotation.NonNull;
import android.annotation.Nullable;
diff --git a/services/companion/java/com/android/server/companion/presence/BleCompanionDeviceScanner.java b/services/companion/java/com/android/server/companion/presence/BleCompanionDeviceScanner.java
index 7e30790..6792434 100644
--- a/services/companion/java/com/android/server/companion/presence/BleCompanionDeviceScanner.java
+++ b/services/companion/java/com/android/server/companion/presence/BleCompanionDeviceScanner.java
@@ -34,7 +34,7 @@
import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_POWER;
import static com.android.server.companion.presence.CompanionDevicePresenceMonitor.DEBUG;
-import static com.android.server.companion.presence.Utils.btDeviceToString;
+import static com.android.server.companion.utils.Utils.btDeviceToString;
import static java.util.Objects.requireNonNull;
diff --git a/services/companion/java/com/android/server/companion/presence/BluetoothCompanionDeviceConnectionListener.java b/services/companion/java/com/android/server/companion/presence/BluetoothCompanionDeviceConnectionListener.java
index c514f3e..0287f62 100644
--- a/services/companion/java/com/android/server/companion/presence/BluetoothCompanionDeviceConnectionListener.java
+++ b/services/companion/java/com/android/server/companion/presence/BluetoothCompanionDeviceConnectionListener.java
@@ -20,7 +20,7 @@
import static android.companion.DevicePresenceEvent.EVENT_BT_DISCONNECTED;
import static com.android.server.companion.presence.CompanionDevicePresenceMonitor.DEBUG;
-import static com.android.server.companion.presence.Utils.btDeviceToString;
+import static com.android.server.companion.utils.Utils.btDeviceToString;
import android.annotation.NonNull;
import android.annotation.SuppressLint;
@@ -40,8 +40,6 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.ArrayUtils;
import com.android.server.companion.AssociationStore;
-import com.android.server.companion.ObservableUuid;
-import com.android.server.companion.ObservableUuidStore;
import java.util.Arrays;
import java.util.Collections;
diff --git a/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java b/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
index 54a4692..caca48d 100644
--- a/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
+++ b/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
@@ -43,8 +43,6 @@
import android.util.SparseArray;
import com.android.server.companion.AssociationStore;
-import com.android.server.companion.ObservableUuid;
-import com.android.server.companion.ObservableUuidStore;
import java.io.PrintWriter;
import java.util.HashSet;
diff --git a/services/companion/java/com/android/server/companion/ObservableUuid.java b/services/companion/java/com/android/server/companion/presence/ObservableUuid.java
similarity index 96%
rename from services/companion/java/com/android/server/companion/ObservableUuid.java
rename to services/companion/java/com/android/server/companion/presence/ObservableUuid.java
index 6ab3188..9cfa270 100644
--- a/services/companion/java/com/android/server/companion/ObservableUuid.java
+++ b/services/companion/java/com/android/server/companion/presence/ObservableUuid.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.presence;
import android.annotation.NonNull;
import android.annotation.UserIdInt;
diff --git a/services/companion/java/com/android/server/companion/ObservableUuidStore.java b/services/companion/java/com/android/server/companion/presence/ObservableUuidStore.java
similarity index 93%
rename from services/companion/java/com/android/server/companion/ObservableUuidStore.java
rename to services/companion/java/com/android/server/companion/presence/ObservableUuidStore.java
index 94be22a..ee8b106 100644
--- a/services/companion/java/com/android/server/companion/ObservableUuidStore.java
+++ b/services/companion/java/com/android/server/companion/presence/ObservableUuidStore.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.presence;
import static com.android.internal.util.XmlUtils.readIntAttribute;
import static com.android.internal.util.XmlUtils.readLongAttribute;
@@ -22,10 +22,10 @@
import static com.android.internal.util.XmlUtils.writeIntAttribute;
import static com.android.internal.util.XmlUtils.writeLongAttribute;
import static com.android.internal.util.XmlUtils.writeStringAttribute;
-import static com.android.server.companion.DataStoreUtils.createStorageFileForUser;
-import static com.android.server.companion.DataStoreUtils.isEndOfTag;
-import static com.android.server.companion.DataStoreUtils.isStartOfTag;
-import static com.android.server.companion.DataStoreUtils.writeToFileSafely;
+import static com.android.server.companion.utils.DataStoreUtils.createStorageFileForUser;
+import static com.android.server.companion.utils.DataStoreUtils.isEndOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.isStartOfTag;
+import static com.android.server.companion.utils.DataStoreUtils.writeToFileSafely;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -57,6 +57,9 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+/**
+ * This store manages the cache and disk data for observable uuids.
+ */
public class ObservableUuidStore {
private static final String TAG = "CDM_ObservableUuidStore";
private static final String FILE_NAME = "observing_uuids_presence.xml";
@@ -84,9 +87,9 @@
}
/**
- * Remove the observable uuid from the disk.
+ * Remove the observable uuid.
*/
- void removeObservableUuid(@UserIdInt int userId, ParcelUuid uuid, String packageName) {
+ public void removeObservableUuid(@UserIdInt int userId, ParcelUuid uuid, String packageName) {
List<ObservableUuid> cachedObservableUuids;
synchronized (mLock) {
@@ -101,7 +104,10 @@
mExecutor.execute(() -> writeObservableUuidToStore(userId, cachedObservableUuids));
}
- void writeObservableUuid(@UserIdInt int userId, ObservableUuid uuid) {
+ /**
+ * Write the observable uuid.
+ */
+ public void writeObservableUuid(@UserIdInt int userId, ObservableUuid uuid) {
Slog.i(TAG, "Writing uuid=" + uuid.getUuid() + " to store.");
List<ObservableUuid> cachedObservableUuids;
diff --git a/services/companion/java/com/android/server/companion/presence/Utils.java b/services/companion/java/com/android/server/companion/presence/Utils.java
deleted file mode 100644
index 583b443..0000000
--- a/services/companion/java/com/android/server/companion/presence/Utils.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2022 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.companion.presence;
-
-import android.annotation.NonNull;
-import android.bluetooth.BluetoothDevice;
-
-/** Utilities for working with Bluetooth and BLE devices. */
-class Utils {
-
- /**
- * @return short String representation of {@link BluetoothDevice}.
- */
- static String btDeviceToString(@NonNull BluetoothDevice btDevice) {
- final StringBuilder sb = new StringBuilder(btDevice.getAddress());
-
- sb.append(" [name=");
- final String name = btDevice.getName();
- if (name != null) {
- sb.append('\'').append(name).append('\'');
- } else {
- sb.append("null");
- }
-
- final String alias = btDevice.getAlias();
- if (alias != null) {
- sb.append(", alias='").append(alias).append("'");
- }
-
- return sb.append(']').toString();
- }
-
- private Utils() {
- }
-}
diff --git a/services/companion/java/com/android/server/companion/DataStoreUtils.java b/services/companion/java/com/android/server/companion/utils/DataStoreUtils.java
similarity index 97%
rename from services/companion/java/com/android/server/companion/DataStoreUtils.java
rename to services/companion/java/com/android/server/companion/utils/DataStoreUtils.java
index 04ce1f6..c75b1a5 100644
--- a/services/companion/java/com/android/server/companion/DataStoreUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/DataStoreUtils.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
import static org.xmlpull.v1.XmlPullParser.END_TAG;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
@@ -80,7 +80,7 @@
/**
* Writing to file could fail, for example, if the user has been recently removed and so was
- * their DE (/data/system_de/<user-id>/) directory.
+ * their DE (/data/system_de/[user-id]/) directory.
*/
public static void writeToFileSafely(
@NonNull AtomicFile file, @NonNull ThrowingConsumer<FileOutputStream> consumer) {
diff --git a/services/companion/java/com/android/server/companion/MetricUtils.java b/services/companion/java/com/android/server/companion/utils/MetricUtils.java
similarity index 92%
rename from services/companion/java/com/android/server/companion/MetricUtils.java
rename to services/companion/java/com/android/server/companion/utils/MetricUtils.java
index cf867b6..8ea5c89 100644
--- a/services/companion/java/com/android/server/companion/MetricUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/MetricUtils.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
import static android.companion.AssociationRequest.DEVICE_PROFILE_APP_STREAMING;
import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PROJECTION;
@@ -41,7 +41,7 @@
import java.util.Map;
-final class MetricUtils {
+public final class MetricUtils {
private static final Map<String, Integer> METRIC_DEVICE_PROFILE;
static {
@@ -75,13 +75,19 @@
METRIC_DEVICE_PROFILE = unmodifiableMap(map);
}
- static void logCreateAssociation(String profile) {
+ /**
+ * Log association creation
+ */
+ public static void logCreateAssociation(String profile) {
write(CDM_ASSOCIATION_ACTION,
CDM_ASSOCIATION_ACTION__ACTION__CREATED,
METRIC_DEVICE_PROFILE.get(profile));
}
- static void logRemoveAssociation(String profile) {
+ /**
+ * Log association removal
+ */
+ public static void logRemoveAssociation(String profile) {
write(CDM_ASSOCIATION_ACTION,
CDM_ASSOCIATION_ACTION__ACTION__REMOVED,
METRIC_DEVICE_PROFILE.get(profile));
diff --git a/services/companion/java/com/android/server/companion/PackageUtils.java b/services/companion/java/com/android/server/companion/utils/PackageUtils.java
similarity index 86%
rename from services/companion/java/com/android/server/companion/PackageUtils.java
rename to services/companion/java/com/android/server/companion/utils/PackageUtils.java
index 3aae1ec..d38590e 100644
--- a/services/companion/java/com/android/server/companion/PackageUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/PackageUtils.java
@@ -14,16 +14,13 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
import static android.content.pm.PackageManager.FEATURE_COMPANION_DEVICE_SETUP;
import static android.content.pm.PackageManager.GET_CONFIGURATIONS;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
import static android.os.Binder.getCallingUid;
-import static com.android.server.companion.CompanionDeviceManagerService.DEBUG;
-import static com.android.server.companion.CompanionDeviceManagerService.TAG;
-
import android.Manifest;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -44,13 +41,11 @@
import android.content.pm.Signature;
import android.os.Binder;
import android.os.Process;
-import android.util.Log;
import android.util.Slog;
import com.android.internal.util.ArrayUtils;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -58,16 +53,22 @@
import java.util.Set;
/**
- * Utility methods for working with {@link PackageInfo}-s.
+ * Utility methods for working with {@link PackageInfo}.
*/
public final class PackageUtils {
+
+ private static final String TAG = "CDM_PackageUtils";
+
private static final Intent COMPANION_SERVICE_INTENT =
new Intent(CompanionDeviceService.SERVICE_INTERFACE);
private static final String PROPERTY_PRIMARY_TAG =
"android.companion.PROPERTY_PRIMARY_COMPANION_DEVICE_SERVICE";
+ /**
+ * Get package info
+ */
@Nullable
- static PackageInfo getPackageInfo(@NonNull Context context,
+ public static PackageInfo getPackageInfo(@NonNull Context context,
@UserIdInt int userId, @NonNull String packageName) {
final PackageManager pm = context.getPackageManager();
final PackageInfoFlags flags = PackageInfoFlags.of(GET_PERMISSIONS | GET_CONFIGURATIONS);
@@ -81,26 +82,32 @@
});
}
- static void enforceUsesCompanionDeviceFeature(@NonNull Context context,
+ /**
+ * Require the app to declare the companion device feature.
+ */
+ public static void enforceUsesCompanionDeviceFeature(@NonNull Context context,
@UserIdInt int userId, @NonNull String packageName) {
// Allow system server to create CDM associations without FEATURE_COMPANION_DEVICE_SETUP
if (getCallingUid() == Process.SYSTEM_UID) {
return;
}
- String requiredFeature = FEATURE_COMPANION_DEVICE_SETUP;
+ PackageInfo packageInfo = getPackageInfo(context, userId, packageName);
+ if (packageInfo == null) {
+ throw new IllegalArgumentException("Package " + packageName + " doesn't exist.");
+ }
- FeatureInfo[] requestedFeatures = getPackageInfo(context, userId, packageName).reqFeatures;
+ FeatureInfo[] requestedFeatures = packageInfo.reqFeatures;
if (requestedFeatures != null) {
- for (int i = 0; i < requestedFeatures.length; i++) {
- if (requiredFeature.equals(requestedFeatures[i].name)) {
+ for (FeatureInfo requestedFeature : requestedFeatures) {
+ if (FEATURE_COMPANION_DEVICE_SETUP.equals(requestedFeature.name)) {
return;
}
}
}
throw new IllegalStateException("Must declare uses-feature "
- + requiredFeature
+ + FEATURE_COMPANION_DEVICE_SETUP
+ " in manifest to use this API");
}
@@ -109,7 +116,7 @@
* Services marked as "primary" would always appear at the head of the lists, *before*
* all non-primary services.
*/
- static @NonNull Map<String, List<ComponentName>> getCompanionServicesForUser(
+ public static @NonNull Map<String, List<ComponentName>> getCompanionServicesForUser(
@NonNull Context context, @UserIdInt int userId) {
final PackageManager pm = context.getPackageManager();
final List<ResolveInfo> companionServices = pm.queryIntentServicesAsUser(
@@ -179,9 +186,7 @@
final String[] allowlistedPackages = context.getResources()
.getStringArray(com.android.internal.R.array.config_companionDevicePackages);
if (!ArrayUtils.contains(allowlistedPackages, packageName)) {
- if (DEBUG) {
- Log.d(TAG, packageName + " is not allowlisted.");
- }
+ Slog.d(TAG, packageName + " is not allowlisted.");
return false;
}
@@ -212,13 +217,6 @@
if (!requestingPackageSignatureAllowlisted) {
Slog.w(TAG, "Certificate mismatch for allowlisted package " + packageName);
- if (DEBUG) {
- Log.d(TAG, " > allowlisted signatures for " + packageName + ": ["
- + String.join(", ", allowlistedSignatureDigestsForRequestingPackage)
- + "]");
- Log.d(TAG, " > actual signatures for " + packageName + ": "
- + Arrays.toString(requestingPackageSignatureDigests));
- }
}
return requestingPackageSignatureAllowlisted;
diff --git a/services/companion/java/com/android/server/companion/PermissionsUtils.java b/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
similarity index 80%
rename from services/companion/java/com/android/server/companion/PermissionsUtils.java
rename to services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
index 15bebba..2cf1f46 100644
--- a/services/companion/java/com/android/server/companion/PermissionsUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
import static android.Manifest.permission.INTERACT_ACROSS_USERS;
import static android.Manifest.permission.MANAGE_COMPANION_DEVICES;
@@ -75,16 +75,22 @@
DEVICE_PROFILE_TO_PERMISSION = unmodifiableMap(map);
}
- static void enforcePermissionsForAssociation(@NonNull Context context,
+ /**
+ * Require the app to declare necessary permission for creating association.
+ */
+ public static void enforcePermissionForCreatingAssociation(@NonNull Context context,
@NonNull AssociationRequest request, int packageUid) {
- enforceRequestDeviceProfilePermissions(context, request.getDeviceProfile(), packageUid);
+ enforcePermissionForRequestingProfile(context, request.getDeviceProfile(), packageUid);
if (request.isSelfManaged()) {
- enforceRequestSelfManagedPermission(context, packageUid);
+ enforcePermissionForRequestingSelfManaged(context, packageUid);
}
}
- static void enforceRequestDeviceProfilePermissions(
+ /**
+ * Require the app to declare necessary permission for creating association with profile.
+ */
+ public static void enforcePermissionForRequestingProfile(
@NonNull Context context, @Nullable String deviceProfile, int packageUid) {
// Device profile can be null.
if (deviceProfile == null) return;
@@ -101,7 +107,11 @@
}
}
- static void enforceRequestSelfManagedPermission(@NonNull Context context, int packageUid) {
+ /**
+ * Require the app to declare necessary permission for creating self-managed association.
+ */
+ public static void enforcePermissionForRequestingSelfManaged(@NonNull Context context,
+ int packageUid) {
if (context.checkPermission(REQUEST_COMPANION_SELF_MANAGED, getCallingPid(), packageUid)
!= PERMISSION_GRANTED) {
throw new SecurityException("Application does not hold "
@@ -109,25 +119,39 @@
}
}
- static boolean checkCallerCanInteractWithUserId(@NonNull Context context, int userId) {
+ /**
+ * Check if the caller can interact with the user.
+ */
+ public static boolean checkCallerCanInteractWithUserId(@NonNull Context context, int userId) {
if (getCallingUserId() == userId) return true;
return context.checkCallingPermission(INTERACT_ACROSS_USERS) == PERMISSION_GRANTED;
}
- static void enforceCallerCanInteractWithUserId(@NonNull Context context, int userId) {
+ /**
+ * Require the caller to be able to interact with the user.
+ */
+ public static void enforceCallerCanInteractWithUserId(@NonNull Context context, int userId) {
if (getCallingUserId() == userId) return;
context.enforceCallingPermission(INTERACT_ACROSS_USERS, null);
}
- static void enforceCallerIsSystemOrCanInteractWithUserId(@NonNull Context context, int userId) {
+ /**
+ * Require the caller to be system UID or to be able to interact with the user.
+ */
+ public static void enforceCallerIsSystemOrCanInteractWithUserId(@NonNull Context context,
+ int userId) {
if (getCallingUid() == SYSTEM_UID) return;
enforceCallerCanInteractWithUserId(context, userId);
}
- static boolean checkCallerIsSystemOr(@UserIdInt int userId, @NonNull String packageName) {
+ /**
+ * Check if the caller is system UID or the provided user.
+ */
+ public static boolean checkCallerIsSystemOr(@UserIdInt int userId,
+ @NonNull String packageName) {
final int callingUid = getCallingUid();
if (callingUid == SYSTEM_UID) return true;
@@ -158,13 +182,19 @@
}
}
- static boolean checkCallerCanManageCompanionDevice(@NonNull Context context) {
+ /**
+ * Check if the caller holds the necessary permission to manage companion devices.
+ */
+ public static boolean checkCallerCanManageCompanionDevice(@NonNull Context context) {
if (getCallingUid() == SYSTEM_UID) return true;
return context.checkCallingPermission(MANAGE_COMPANION_DEVICES) == PERMISSION_GRANTED;
}
- static void enforceCallerCanManageAssociationsForPackage(@NonNull Context context,
+ /**
+ * Require the caller to be able to manage the associations for the package.
+ */
+ public static void enforceCallerCanManageAssociationsForPackage(@NonNull Context context,
@UserIdInt int userId, @NonNull String packageName,
@Nullable String actionDescription) {
if (checkCallerCanManageAssociationsForPackage(context, userId, packageName)) return;
@@ -175,7 +205,10 @@
+ " for u" + userId + "/" + packageName);
}
- static void enforceCallerCanObservingDevicePresenceByUuid(@NonNull Context context) {
+ /**
+ * Require the caller to hold necessary permission to observe device presence by UUID.
+ */
+ public static void enforceCallerCanObservingDevicePresenceByUuid(@NonNull Context context) {
if (context.checkCallingPermission(REQUEST_OBSERVE_DEVICE_UUID_PRESENCE)
!= PERMISSION_GRANTED) {
throw new SecurityException("Caller (uid=" + getCallingUid() + ") does not have "
@@ -193,7 +226,7 @@
* </ul>
* @return whether the caller is one of the above.
*/
- static boolean checkCallerCanManageAssociationsForPackage(@NonNull Context context,
+ public static boolean checkCallerCanManageAssociationsForPackage(@NonNull Context context,
@UserIdInt int userId, @NonNull String packageName) {
if (checkCallerIsSystemOr(userId, packageName)) return true;
diff --git a/services/companion/java/com/android/server/companion/RolesUtils.java b/services/companion/java/com/android/server/companion/utils/RolesUtils.java
similarity index 70%
rename from services/companion/java/com/android/server/companion/RolesUtils.java
rename to services/companion/java/com/android/server/companion/utils/RolesUtils.java
index af9d2d7..f798e21 100644
--- a/services/companion/java/com/android/server/companion/RolesUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/RolesUtils.java
@@ -14,13 +14,10 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
import static android.app.role.RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP;
-import static com.android.server.companion.CompanionDeviceManagerService.DEBUG;
-import static com.android.server.companion.CompanionDeviceManagerService.TAG;
-
import android.annotation.NonNull;
import android.annotation.SuppressLint;
import android.annotation.UserIdInt;
@@ -29,7 +26,6 @@
import android.content.Context;
import android.os.Binder;
import android.os.UserHandle;
-import android.util.Log;
import android.util.Slog;
import java.util.List;
@@ -37,9 +33,14 @@
/** Utility methods for accessing {@link RoleManager} APIs. */
@SuppressLint("LongLogTag")
-final class RolesUtils {
+public final class RolesUtils {
- static boolean isRoleHolder(@NonNull Context context, @UserIdInt int userId,
+ private static final String TAG = "CDM_RolesUtils";
+
+ /**
+ * Check if the package holds the role.
+ */
+ public static boolean isRoleHolder(@NonNull Context context, @UserIdInt int userId,
@NonNull String packageName, @NonNull String role) {
final RoleManager roleManager = context.getSystemService(RoleManager.class);
final List<String> roleHolders = roleManager.getRoleHoldersAsUser(
@@ -58,13 +59,9 @@
* false if failed. If the association does not have any device profile
* specified, then the operation will always be successful as a no-op.
*/
- static void addRoleHolderForAssociation(
+ public static void addRoleHolderForAssociation(
@NonNull Context context, @NonNull AssociationInfo associationInfo,
@NonNull Consumer<Boolean> roleGrantResult) {
- if (DEBUG) {
- Log.d(TAG, "addRoleHolderForAssociation() associationInfo=" + associationInfo);
- }
-
final String deviceProfile = associationInfo.getDeviceProfile();
if (deviceProfile == null) {
// If no device profile is specified, then no-op and resolve callback with success.
@@ -83,33 +80,30 @@
roleGrantResult);
}
- static void removeRoleHolderForAssociation(
- @NonNull Context context, @NonNull AssociationInfo associationInfo) {
- if (DEBUG) {
- Log.d(TAG, "removeRoleHolderForAssociation() associationInfo=" + associationInfo);
- }
-
- final String deviceProfile = associationInfo.getDeviceProfile();
+ /**
+ * Remove the role for the package association.
+ */
+ public static void removeRoleHolderForAssociation(
+ @NonNull Context context, int userId, String packageName, String deviceProfile) {
if (deviceProfile == null) return;
final RoleManager roleManager = context.getSystemService(RoleManager.class);
- final String packageName = associationInfo.getPackageName();
- final int userId = associationInfo.getUserId();
final UserHandle userHandle = UserHandle.of(userId);
- Slog.i(TAG, "Removing CDM role holder, role=" + deviceProfile
- + ", package=u" + userId + "\\" + packageName);
+ Slog.i(TAG, "Removing CDM role=" + deviceProfile
+ + " for userId=" + userId + ", packageName=" + packageName);
final long identity = Binder.clearCallingIdentity();
try {
roleManager.removeRoleHolderAsUser(deviceProfile, packageName,
- MANAGE_HOLDERS_FLAG_DONT_KILL_APP, userHandle, context.getMainExecutor(),
- success -> {
- if (!success) {
- Slog.e(TAG, "Failed to remove u" + userId + "\\" + packageName
- + " from the list of " + deviceProfile + " holders.");
- }
- });
+ MANAGE_HOLDERS_FLAG_DONT_KILL_APP, userHandle, context.getMainExecutor(),
+ success -> {
+ if (!success) {
+ Slog.e(TAG, "Failed to remove userId=" + userId + ", packageName="
+ + packageName + " from the list of " + deviceProfile
+ + " holders.");
+ }
+ });
} finally {
Binder.restoreCallingIdentity(identity);
}
diff --git a/services/companion/java/com/android/server/companion/Utils.java b/services/companion/java/com/android/server/companion/utils/Utils.java
similarity index 64%
rename from services/companion/java/com/android/server/companion/Utils.java
rename to services/companion/java/com/android/server/companion/utils/Utils.java
index b9f61ec..8302997 100644
--- a/services/companion/java/com/android/server/companion/Utils.java
+++ b/services/companion/java/com/android/server/companion/utils/Utils.java
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-package com.android.server.companion;
+package com.android.server.companion.utils;
+import android.annotation.NonNull;
+import android.bluetooth.BluetoothDevice;
import android.os.Parcel;
import android.os.ResultReceiver;
@@ -43,5 +45,27 @@
return ipcFriendly;
}
+ /**
+ * Return a human-readable string for the BluetoothDevice.
+ */
+ public static String btDeviceToString(@NonNull BluetoothDevice btDevice) {
+ final StringBuilder sb = new StringBuilder(btDevice.getAddress());
+
+ sb.append(" [name=");
+ final String name = btDevice.getName();
+ if (name != null) {
+ sb.append('\'').append(name).append('\'');
+ } else {
+ sb.append("null");
+ }
+
+ final String alias = btDevice.getAlias();
+ if (alias != null) {
+ sb.append(", alias='").append(alias).append("'");
+ }
+
+ return sb.append(']').toString();
+ }
+
private Utils() {}
}
diff --git a/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java b/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java
index 3312be2..96fee929 100644
--- a/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java
+++ b/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java
@@ -32,8 +32,10 @@
import android.util.Log;
import android.util.Slog;
import android.util.SparseIntArray;
+import android.util.SparseLongArray;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.FrameworkStatsLog;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockSettingsInternal;
import com.android.internal.widget.LockSettingsStateListener;
@@ -57,6 +59,8 @@
private static final int MSG_REPORT_BIOMETRIC_AUTH_ATTEMPT = 2;
private static final int AUTH_SUCCESS = 1;
private static final int AUTH_FAILURE = 0;
+ private static final int TYPE_PRIMARY_AUTH = 0;
+ private static final int TYPE_BIOMETRIC_AUTH = 1;
private final LockPatternUtils mLockPatternUtils;
private final LockSettingsInternal mLockSettings;
@@ -67,6 +71,7 @@
private final UserManagerInternal mUserManager;
@VisibleForTesting
final SparseIntArray mFailedAttemptsForUser = new SparseIntArray();
+ private final SparseLongArray mLastLockedTimestamp = new SparseLongArray();
public AdaptiveAuthService(Context context) {
this(context, new LockPatternUtils(context));
@@ -170,7 +175,7 @@
Slog.d(TAG, "handleReportPrimaryAuthAttempt: success=" + success
+ ", userId=" + userId);
}
- reportAuthAttempt(success, userId);
+ reportAuthAttempt(TYPE_PRIMARY_AUTH, success, userId);
}
private void handleReportBiometricAuthAttempt(boolean success, int userId) {
@@ -178,13 +183,24 @@
Slog.d(TAG, "handleReportBiometricAuthAttempt: success=" + success
+ ", userId=" + userId);
}
- reportAuthAttempt(success, userId);
+ reportAuthAttempt(TYPE_BIOMETRIC_AUTH, success, userId);
}
- private void reportAuthAttempt(boolean success, int userId) {
+ private void reportAuthAttempt(int authType, boolean success, int userId) {
if (success) {
// Deleting the entry effectively resets the counter of failed attempts for the user
mFailedAttemptsForUser.delete(userId);
+
+ // Collect metrics if the device was locked by adaptive auth before
+ if (mLastLockedTimestamp.indexOfKey(userId) >= 0) {
+ final long lastLockedTime = mLastLockedTimestamp.get(userId);
+ collectTimeElapsedSinceLastLocked(
+ lastLockedTime, SystemClock.elapsedRealtime(), authType);
+
+ // Remove the entry for the last locked time because a successful auth just happened
+ // and metrics have been collected
+ mLastLockedTimestamp.delete(userId);
+ }
return;
}
@@ -210,6 +226,34 @@
lockDevice(userId);
}
+ private static void collectTimeElapsedSinceLastLocked(long lastLockedTime, long authTime,
+ int authType) {
+ final int unlockType = switch (authType) {
+ case TYPE_PRIMARY_AUTH -> FrameworkStatsLog
+ .ADAPTIVE_AUTH_UNLOCK_AFTER_LOCK_REPORTED__UNLOCK_TYPE__PRIMARY_AUTH;
+ case TYPE_BIOMETRIC_AUTH -> FrameworkStatsLog
+ .ADAPTIVE_AUTH_UNLOCK_AFTER_LOCK_REPORTED__UNLOCK_TYPE__BIOMETRIC_AUTH;
+ default -> FrameworkStatsLog
+ .ADAPTIVE_AUTH_UNLOCK_AFTER_LOCK_REPORTED__UNLOCK_TYPE__UNKNOWN;
+ };
+
+ if (DEBUG) {
+ Slog.d(TAG, "collectTimeElapsedSinceLastLockedForUser: "
+ + "lastLockedTime=" + lastLockedTime
+ + ", authTime=" + authTime
+ + ", unlockType=" + unlockType);
+ }
+
+ // This usually shouldn't happen, and just check out of an abundance of caution
+ if (lastLockedTime > authTime) {
+ return;
+ }
+
+ // Log to statsd
+ FrameworkStatsLog.write(FrameworkStatsLog.ADAPTIVE_AUTH_UNLOCK_AFTER_LOCK_REPORTED,
+ lastLockedTime, authTime, unlockType);
+ }
+
/**
* Locks the device and requires primary auth or biometric auth for unlocking
*/
@@ -234,5 +278,9 @@
// Lock the device
mWindowManager.lockNow();
+
+ // Record the time that the device is locked by adaptive auth to collect metrics when the
+ // next successful primary or biometric auth happens
+ mLastLockedTimestamp.put(userId, SystemClock.elapsedRealtime());
}
}
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index b8f6b3f..b8e09cc 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -4133,7 +4133,7 @@
|| (callerApp.mState.getCurProcState() <= PROCESS_STATE_TOP
&& c.hasFlag(Context.BIND_TREAT_LIKE_ACTIVITY)),
b.client);
- if ((serviceBindingOomAdjPolicy
+ if (!s.mOomAdjBumpedInExec && (serviceBindingOomAdjPolicy
& SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT) == 0) {
needOomAdj = true;
mAm.enqueueOomAdjTargetLocked(s.app);
@@ -4277,7 +4277,7 @@
}
serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false, false,
- !Flags.serviceBindingOomAdjPolicy() || b == null || !b.mSkippedOomAdj
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec
? OOM_ADJ_REASON_EXECUTING_SERVICE : OOM_ADJ_REASON_NONE);
}
} finally {
@@ -4398,7 +4398,6 @@
+ (b != null ? b.apps.size() : 0));
boolean inDestroying = mDestroyingServices.contains(r);
- boolean skipOomAdj = false;
if (b != null) {
if (b.apps.size() > 0 && !inDestroying) {
// Applications have already bound since the last
@@ -4423,11 +4422,11 @@
// a new client.
b.doRebind = true;
}
- skipOomAdj = Flags.serviceBindingOomAdjPolicy() && b.mSkippedOomAdj;
}
serviceDoneExecutingLocked(r, inDestroying, false, false,
- skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE);
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec
+ ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
}
} finally {
mAm.mInjector.restoreCallingIdentity(origId);
@@ -4905,9 +4904,8 @@
* Bump the given service record into executing state.
* @param oomAdjReason The caller requests it to perform the oomAdjUpdate not {@link
* ActivityManagerInternal#OOM_ADJ_REASON_NONE}.
- * @return {@code true} if it performed oomAdjUpdate.
*/
- private boolean bumpServiceExecutingLocked(
+ private void bumpServiceExecutingLocked(
ServiceRecord r, boolean fg, String why, @OomAdjReason int oomAdjReason,
boolean skipTimeoutIfPossible) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
@@ -4972,19 +4970,17 @@
}
}
}
- boolean oomAdjusted = false;
if (oomAdjReason != OOM_ADJ_REASON_NONE && r.app != null
&& r.app.mState.getCurProcState() > ActivityManager.PROCESS_STATE_SERVICE) {
// Force an immediate oomAdjUpdate, so the client app could be in the correct process
// state before doing any service related transactions
mAm.enqueueOomAdjTargetLocked(r.app);
mAm.updateOomAdjPendingTargetsLocked(oomAdjReason);
- oomAdjusted = true;
+ r.mOomAdjBumpedInExec = true;
}
r.executeFg |= fg;
r.executeNesting++;
r.executingStart = SystemClock.uptimeMillis();
- return oomAdjusted;
}
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
@@ -5001,7 +4997,7 @@
& SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND) != 0;
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
- i.mSkippedOomAdj = !bumpServiceExecutingLocked(r, execInFg, "bind",
+ bumpServiceExecutingLocked(r, execInFg, "bind",
skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_BIND_SERVICE,
skipOomAdj /* skipTimeoutIfPossible */);
if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
@@ -5020,14 +5016,16 @@
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
- skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE);
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec
+ ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
throw e;
} catch (RemoteException e) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
// Keep the executeNesting count accurate.
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
- skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE);
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec
+ ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
return false;
}
}
@@ -5823,6 +5821,7 @@
// process state before doing any service related transactions
mAm.enqueueOomAdjTargetLocked(app);
mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
+ r.mOomAdjBumpedInExec = true;
} else {
// Since we skipped the oom adj update, the Service#onCreate() might be running in
// the cached state, if the service process drops into the cached state after the call.
@@ -5863,7 +5862,8 @@
// Keep the executeNesting count accurate.
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
- skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_STOP_SERVICE);
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec
+ ? OOM_ADJ_REASON_STOP_SERVICE : OOM_ADJ_REASON_NONE);
// Cleanup.
if (newService) {
@@ -5898,7 +5898,7 @@
null, null, 0, null, null, ActivityManager.PROCESS_STATE_UNKNOWN));
}
- sendServiceArgsLocked(r, execInFg, true);
+ sendServiceArgsLocked(r, execInFg, r.mOomAdjBumpedInExec);
if (r.delayed) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
@@ -6085,7 +6085,8 @@
}
}
- boolean oomAdjusted = false;
+ boolean oomAdjusted = Flags.serviceBindingOomAdjPolicy() && r.mOomAdjBumpedInExec;
+
// Tell the service that it has been unbound.
if (r.app != null && r.app.isThreadReady()) {
for (int i = r.bindings.size() - 1; i >= 0; i--) {
@@ -6094,9 +6095,10 @@
+ ": hasBound=" + ibr.hasBound);
if (ibr.hasBound) {
try {
- oomAdjusted |= bumpServiceExecutingLocked(r, false, "bring down unbind",
- OOM_ADJ_REASON_UNBIND_SERVICE,
- false /* skipTimeoutIfPossible */);
+ bumpServiceExecutingLocked(r, false, "bring down unbind",
+ oomAdjusted ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
+ oomAdjusted /* skipTimeoutIfPossible */);
+ oomAdjusted |= r.mOomAdjBumpedInExec;
ibr.hasBound = false;
ibr.requested = false;
r.app.getThread().scheduleUnbindService(r,
@@ -6252,10 +6254,11 @@
}
} else {
try {
- oomAdjusted |= bumpServiceExecutingLocked(r, false, "destroy",
- oomAdjusted ? 0 : OOM_ADJ_REASON_STOP_SERVICE,
- false /* skipTimeoutIfPossible */);
+ bumpServiceExecutingLocked(r, false, "destroy",
+ oomAdjusted ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
+ oomAdjusted /* skipTimeoutIfPossible */);
mDestroyingServices.add(r);
+ oomAdjusted |= r.mOomAdjBumpedInExec;
r.destroying = true;
r.app.getThread().scheduleStopService(r);
} catch (Exception e) {
@@ -6411,7 +6414,7 @@
final boolean skipOomAdj = (serviceBindingOomAdjPolicy
& SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT) != 0;
try {
- b.intent.mSkippedOomAdj = !bumpServiceExecutingLocked(s, false, "unbind",
+ bumpServiceExecutingLocked(s, false, "unbind",
skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
skipOomAdj /* skipTimeoutIfPossible */);
if (b.client != s.app && c.notHasFlag(Context.BIND_WAIVE_PRIORITY)
@@ -6461,6 +6464,7 @@
boolean inDestroying = mDestroyingServices.contains(r);
if (r != null) {
boolean skipOomAdj = false;
+ boolean needOomAdj = false;
if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
// This is a call from a service start... take care of
// book-keeping.
@@ -6536,15 +6540,13 @@
// Fake it to keep from ANR due to orphaned entry.
r.executeNesting = 1;
}
- } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_REBIND
- || type == ActivityThread.SERVICE_DONE_EXECUTING_UNBIND) {
- final Intent.FilterComparison filter = new Intent.FilterComparison(intent);
- final IntentBindRecord b = r.bindings.get(filter);
- skipOomAdj = Flags.serviceBindingOomAdjPolicy() && b != null && b.mSkippedOomAdj;
+ // The service is done, force an oom adj update.
+ needOomAdj = true;
}
final long origId = mAm.mInjector.clearCallingIdentity();
serviceDoneExecutingLocked(r, inDestroying, inDestroying, enqueueOomAdj,
- skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_EXECUTING_SERVICE);
+ !Flags.serviceBindingOomAdjPolicy() || r.mOomAdjBumpedInExec || needOomAdj
+ ? OOM_ADJ_REASON_EXECUTING_SERVICE : OOM_ADJ_REASON_NONE);
mAm.mInjector.restoreCallingIdentity(origId);
} else {
Slog.w(TAG, "Done executing unknown service from pid "
@@ -6600,18 +6602,16 @@
mDestroyingServices.remove(r);
r.bindings.clear();
}
- boolean oomAdjusted = false;
if (oomAdjReason != OOM_ADJ_REASON_NONE) {
if (enqueueOomAdj) {
mAm.enqueueOomAdjTargetLocked(r.app);
} else {
mAm.updateOomAdjLocked(r.app, oomAdjReason);
}
- oomAdjusted = true;
} else {
// Skip oom adj if it wasn't bumped during the bumpServiceExecutingLocked()
- oomAdjusted = false;
}
+ r.mOomAdjBumpedInExec = false;
}
r.executeFg = false;
if (r.tracker != null) {
@@ -6995,6 +6995,7 @@
sr.setProcess(null, null, 0, null);
sr.isolationHostProc = null;
sr.executeNesting = 0;
+ sr.mOomAdjBumpedInExec = false;
synchronized (mAm.mProcessStats.mLock) {
sr.forceClearTracker();
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index e222878..663ba8a 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -9028,6 +9028,7 @@
Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
+ Process.myUid());
BinderProxy.dumpProxyDebugInfo();
+ CriticalEventLog.getInstance().logExcessiveBinderCalls(uid);
if (uid == Process.SYSTEM_UID) {
Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
} else {
diff --git a/services/core/java/com/android/server/am/IntentBindRecord.java b/services/core/java/com/android/server/am/IntentBindRecord.java
index db47e3f..1a3652e 100644
--- a/services/core/java/com/android/server/am/IntentBindRecord.java
+++ b/services/core/java/com/android/server/am/IntentBindRecord.java
@@ -49,14 +49,6 @@
String stringName; // caching of toString
- /**
- * Mark if we've skipped oom adj update before calling into the {@link Service#onBind()}
- * or {@link Service#onUnbind()}.
- *
- * <p>If it's true, we'll skip the oom adj update too during the serviceDoneExecuting.
- */
- boolean mSkippedOomAdj;
-
void dump(PrintWriter pw, String prefix) {
pw.print(prefix); pw.print("service="); pw.println(service);
dumpInService(pw, prefix);
diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java
index 3c8d7fc..e3aac02 100644
--- a/services/core/java/com/android/server/am/ServiceRecord.java
+++ b/services/core/java/com/android/server/am/ServiceRecord.java
@@ -267,6 +267,11 @@
int mAllowStart_byBindings = REASON_DENIED;
/**
+ * Whether or not we've bumped its oom adj scores during its execution.
+ */
+ boolean mOomAdjBumpedInExec;
+
+ /**
* Whether to use the new "while-in-use permission" logic for FGS start
*/
private boolean useNewWiuLogic_forStart() {
diff --git a/services/core/java/com/android/server/am/flags.aconfig b/services/core/java/com/android/server/am/flags.aconfig
index 16dbe18..c06bdf9 100644
--- a/services/core/java/com/android/server/am/flags.aconfig
+++ b/services/core/java/com/android/server/am/flags.aconfig
@@ -53,3 +53,10 @@
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ namespace: "backstage_power"
+ name: "defer_outgoing_bcasts"
+ description: "Defer outgoing broadcasts from processes in freezable state"
+ bug: "327496592"
+}
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index cb6d26f..19dd7b7 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -12528,6 +12528,16 @@
if (app == null) {
return AudioManager.ERROR;
}
+ if (android.media.audiopolicy.Flags.audioMixOwnership()) {
+ for (AudioMix mix : policyConfig.getMixes()) {
+ if (!app.getMixes().contains(mix)) {
+ Slog.e(TAG,
+ "removeMixForPolicy attempted to unregister AudioMix(es) not "
+ + "belonging to the AudioPolicy");
+ return AudioManager.ERROR;
+ }
+ }
+ }
return app.removeMixes(policyConfig.getMixes()) == AudioSystem.SUCCESS
? AudioManager.SUCCESS : AudioManager.ERROR;
}
@@ -13306,7 +13316,13 @@
}
final long identity = Binder.clearCallingIdentity();
try {
- mAudioSystem.registerPolicyMixes(mMixes, false);
+ if (android.media.audiopolicy.Flags.audioMixOwnership()) {
+ synchronized (mMixes) {
+ removeMixes(new ArrayList(mMixes));
+ }
+ } else {
+ mAudioSystem.registerPolicyMixes(mMixes, false);
+ }
} finally {
Binder.restoreCallingIdentity(identity);
}
@@ -13350,6 +13366,17 @@
int addMixes(@NonNull ArrayList<AudioMix> mixes) {
synchronized (mMixes) {
+ if (android.media.audiopolicy.Flags.audioMixOwnership()) {
+ for (AudioMix mix : mixes) {
+ setMixRegistration(mix);
+ }
+
+ int result = mAudioSystem.registerPolicyMixes(mixes, true);
+ if (result == AudioSystem.SUCCESS) {
+ this.add(mixes);
+ }
+ return result;
+ }
this.add(mixes);
return mAudioSystem.registerPolicyMixes(mixes, true);
}
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
index 007b746..fb826c8 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
@@ -24,6 +24,7 @@
import android.app.TaskStackListener;
import android.content.Context;
import android.content.pm.UserInfo;
+import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricFaceConstants;
import android.hardware.biometrics.BiometricsProtoEnums;
import android.hardware.biometrics.ComponentInfoInternal;
@@ -39,6 +40,7 @@
import android.hardware.face.FaceSensorPropertiesInternal;
import android.hardware.face.IFaceServiceReceiver;
import android.os.Binder;
+import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
@@ -64,6 +66,7 @@
import com.android.server.biometrics.sensors.BaseClientMonitor;
import com.android.server.biometrics.sensors.BiometricScheduler;
import com.android.server.biometrics.sensors.BiometricStateCallback;
+import com.android.server.biometrics.sensors.BiometricUtils;
import com.android.server.biometrics.sensors.ClientMonitorCallback;
import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter;
import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback;
@@ -359,6 +362,17 @@
null /* callback */);
}
+ if (Build.isDebuggable()) {
+ BiometricUtils<Face> utils = FaceUtils.getInstance(
+ mFaceSensors.keyAt(0));
+ for (UserInfo user : UserManager.get(mContext).getAliveUsers()) {
+ List<Face> enrollments = utils.getBiometricsForUser(mContext, user.id);
+ Slog.d(getTag(), "Expecting enrollments for user " + user.id + ": "
+ + enrollments.stream().map(
+ BiometricAuthenticator.Identifier::getBiometricId).toList());
+ }
+ }
+
return mDaemon;
}
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
index a104cf4..c04c47e 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
@@ -27,6 +27,7 @@
import android.content.Context;
import android.content.pm.UserInfo;
import android.content.res.TypedArray;
+import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricsProtoEnums;
import android.hardware.biometrics.ComponentInfoInternal;
import android.hardware.biometrics.IInvalidationCallback;
@@ -46,6 +47,7 @@
import android.hardware.fingerprint.ISidefpsController;
import android.hardware.fingerprint.IUdfpsOverlayController;
import android.os.Binder;
+import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
@@ -71,6 +73,7 @@
import com.android.server.biometrics.sensors.BaseClientMonitor;
import com.android.server.biometrics.sensors.BiometricScheduler;
import com.android.server.biometrics.sensors.BiometricStateCallback;
+import com.android.server.biometrics.sensors.BiometricUtils;
import com.android.server.biometrics.sensors.ClientMonitorCallback;
import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter;
import com.android.server.biometrics.sensors.ClientMonitorCompositeCallback;
@@ -382,6 +385,17 @@
null /* callback */);
}
+ if (Build.isDebuggable()) {
+ BiometricUtils<Fingerprint> utils = FingerprintUtils.getInstance(
+ mFingerprintSensors.keyAt(0));
+ for (UserInfo user : UserManager.get(mContext).getAliveUsers()) {
+ List<Fingerprint> enrollments = utils.getBiometricsForUser(mContext, user.id);
+ Slog.d(getTag(), "Expecting enrollments for user " + user.id + ": "
+ + enrollments.stream().map(
+ BiometricAuthenticator.Identifier::getBiometricId).toList());
+ }
+ }
+
return mDaemon;
}
diff --git a/services/core/java/com/android/server/criticalevents/CriticalEventLog.java b/services/core/java/com/android/server/criticalevents/CriticalEventLog.java
index 816c349..036284f 100644
--- a/services/core/java/com/android/server/criticalevents/CriticalEventLog.java
+++ b/services/core/java/com/android/server/criticalevents/CriticalEventLog.java
@@ -30,6 +30,7 @@
import com.android.server.criticalevents.nano.CriticalEventProto.AppNotResponding;
import com.android.server.criticalevents.nano.CriticalEventProto.HalfWatchdog;
import com.android.server.criticalevents.nano.CriticalEventProto.InstallPackages;
+import com.android.server.criticalevents.nano.CriticalEventProto.ExcessiveBinderCalls;
import com.android.server.criticalevents.nano.CriticalEventProto.JavaCrash;
import com.android.server.criticalevents.nano.CriticalEventProto.NativeCrash;
import com.android.server.criticalevents.nano.CriticalEventProto.SystemServerStarted;
@@ -143,6 +144,15 @@
return System.currentTimeMillis();
}
+ /** Logs when a uid sends an excessive number of binder calls. */
+ public void logExcessiveBinderCalls(int uid) {
+ CriticalEventProto event = new CriticalEventProto();
+ ExcessiveBinderCalls calls = new ExcessiveBinderCalls();
+ calls.uid = uid;
+ event.setExcessiveBinderCalls(calls);
+ log(event);
+ }
+
/** Logs when one or more packages are installed. */
public void logInstallPackagesStarted() {
CriticalEventProto event = new CriticalEventProto();
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index dbe85ea..76f3035 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -1474,6 +1474,7 @@
&& mFlags.isDisplayOffloadEnabled()
&& mPowerRequest.policy == POLICY_DOZE
&& mDisplayOffloadSession != null
+ && mAutomaticBrightnessController != null
&& mAutomaticBrightnessStrategy.shouldUseAutoBrightness()) {
rawBrightnessState = mAutomaticBrightnessController
.getAutomaticScreenBrightnessBasedOnLastObservedLux(mTempBrightnessEvent);
@@ -1724,6 +1725,7 @@
mTempBrightnessEvent.setBrightness(brightnessState);
mTempBrightnessEvent.setPhysicalDisplayId(mUniqueDisplayId);
mTempBrightnessEvent.setDisplayState(state);
+ mTempBrightnessEvent.setDisplayPolicy(mPowerRequest.policy);
mTempBrightnessEvent.setReason(mBrightnessReason);
mTempBrightnessEvent.setHbmMax(mBrightnessRangeController.getCurrentBrightnessMax());
mTempBrightnessEvent.setHbmMode(mBrightnessRangeController.getHighBrightnessMode());
diff --git a/services/core/java/com/android/server/display/brightness/BrightnessEvent.java b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
index 5423b74..82b401a 100644
--- a/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
+++ b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
@@ -16,6 +16,9 @@
package com.android.server.display.brightness;
+import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest.POLICY_OFF;
+import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest.policyToString;
+
import static com.android.server.display.AutomaticBrightnessController.AUTO_BRIGHTNESS_MODE_DEFAULT;
import static com.android.server.display.config.DisplayBrightnessMappingConfig.autoBrightnessModeToString;
@@ -46,6 +49,7 @@
private int mDisplayId;
private String mPhysicalDisplayId;
private int mDisplayState;
+ private int mDisplayPolicy;
private long mTime;
private float mLux;
private float mPreThresholdLux;
@@ -85,6 +89,7 @@
mDisplayId = that.getDisplayId();
mPhysicalDisplayId = that.getPhysicalDisplayId();
mDisplayState = that.mDisplayState;
+ mDisplayPolicy = that.mDisplayPolicy;
mTime = that.getTime();
// Lux values
mLux = that.getLux();
@@ -117,6 +122,7 @@
mTime = SystemClock.uptimeMillis();
mPhysicalDisplayId = "";
mDisplayState = Display.STATE_UNKNOWN;
+ mDisplayPolicy = POLICY_OFF;
// Lux values
mLux = 0;
mPreThresholdLux = 0;
@@ -155,6 +161,7 @@
&& mDisplayId == that.mDisplayId
&& mPhysicalDisplayId.equals(that.mPhysicalDisplayId)
&& mDisplayState == that.mDisplayState
+ && mDisplayPolicy == that.mDisplayPolicy
&& Float.floatToRawIntBits(mLux) == Float.floatToRawIntBits(that.mLux)
&& Float.floatToRawIntBits(mPreThresholdLux)
== Float.floatToRawIntBits(that.mPreThresholdLux)
@@ -191,6 +198,7 @@
+ "disp=" + mDisplayId
+ ", physDisp=" + mPhysicalDisplayId
+ ", displayState=" + Display.stateToString(mDisplayState)
+ + ", displayPolicy=" + policyToString(mDisplayPolicy)
+ ", brt=" + mBrightness + ((mFlags & FLAG_USER_SET) != 0 ? "(user_set)" : "")
+ ", initBrt=" + mInitialBrightness
+ ", rcmdBrt=" + mRecommendedBrightness
@@ -251,6 +259,10 @@
mDisplayState = state;
}
+ public void setDisplayPolicy(int policy) {
+ mDisplayPolicy = policy;
+ }
+
public float getLux() {
return mLux;
}
diff --git a/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java b/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
index 055f94a..babc36e 100644
--- a/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
+++ b/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
@@ -71,6 +71,8 @@
@Nullable
private final OffloadBrightnessStrategy mOffloadBrightnessStrategy;
+ private final DisplayBrightnessStrategy[] mDisplayBrightnessStrategies;
+
// We take note of the old brightness strategy so that we can know when the strategy changes.
private String mOldBrightnessStrategyName;
@@ -98,6 +100,10 @@
} else {
mOffloadBrightnessStrategy = null;
}
+ mDisplayBrightnessStrategies = new DisplayBrightnessStrategy[]{mInvalidBrightnessStrategy,
+ mScreenOffBrightnessStrategy, mDozeBrightnessStrategy, mFollowerBrightnessStrategy,
+ mBoostBrightnessStrategy, mOverrideBrightnessStrategy, mTemporaryBrightnessStrategy,
+ mOffloadBrightnessStrategy};
mAllowAutoBrightnessWhileDozingConfig = context.getResources().getBoolean(
R.bool.config_allowAutoBrightnessWhileDozing);
mOldBrightnessStrategyName = mInvalidBrightnessStrategy.getName();
@@ -179,9 +185,10 @@
" mAllowAutoBrightnessWhileDozingConfig= "
+ mAllowAutoBrightnessWhileDozingConfig);
IndentingPrintWriter ipw = new IndentingPrintWriter(writer, " ");
- mTemporaryBrightnessStrategy.dump(ipw);
- if (mOffloadBrightnessStrategy != null) {
- mOffloadBrightnessStrategy.dump(ipw);
+ for (DisplayBrightnessStrategy displayBrightnessStrategy: mDisplayBrightnessStrategies) {
+ if (displayBrightnessStrategy != null) {
+ displayBrightnessStrategy.dump(ipw);
+ }
}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
index dd400d9..9ee1d73 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
@@ -23,6 +23,8 @@
import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.BrightnessUtils;
+import java.io.PrintWriter;
+
/**
* Manages the brightness of the display when the system brightness boost is requested.
*/
@@ -48,4 +50,7 @@
public String getName() {
return "BoostBrightnessStrategy";
}
+
+ @Override
+ public void dump(PrintWriter writer) {}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/DisplayBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/DisplayBrightnessStrategy.java
index 27d04fd..1f28eb4 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/DisplayBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/DisplayBrightnessStrategy.java
@@ -21,6 +21,8 @@
import com.android.server.display.DisplayBrightnessState;
+import java.io.PrintWriter;
+
/**
* Decides the DisplayBrighntessState that the display should change to based on strategy-specific
* logic within each implementation. Clamping should be done outside of DisplayBrightnessStrategy if
@@ -40,4 +42,10 @@
*/
@NonNull
String getName();
+
+ /**
+ * Dumps the state of the Strategy
+ * @param writer
+ */
+ void dump(PrintWriter writer);
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
index 8299586..2be7443 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
@@ -22,6 +22,8 @@
import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.BrightnessUtils;
+import java.io.PrintWriter;
+
/**
* Manages the brightness of the display when the system is in the doze state.
*/
@@ -42,4 +44,6 @@
return "DozeBrightnessStrategy";
}
+ @Override
+ public void dump(PrintWriter writer) {}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
index 585f576..54f9afc 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
@@ -75,6 +75,7 @@
/**
* Dumps the state of this class.
*/
+ @Override
public void dump(PrintWriter writer) {
writer.println("FollowerBrightnessStrategy:");
writer.println(" mDisplayId=" + mDisplayId);
diff --git a/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
index bc24196..49c3e03 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
@@ -23,6 +23,8 @@
import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.BrightnessUtils;
+import java.io.PrintWriter;
+
/**
* Manages the brightness of the display when the system is in the invalid state.
*/
@@ -39,4 +41,7 @@
public String getName() {
return "InvalidBrightnessStrategy";
}
+
+ @Override
+ public void dump(PrintWriter writer) {}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/OffloadBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/OffloadBrightnessStrategy.java
index 55f8914..4ffb16b 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/OffloadBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/OffloadBrightnessStrategy.java
@@ -67,6 +67,7 @@
/**
* Dumps the state of this class.
*/
+ @Override
public void dump(PrintWriter writer) {
writer.println("OffloadBrightnessStrategy:");
writer.println(" mOffloadScreenBrightness:" + mOffloadScreenBrightness);
diff --git a/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
index 13327cb..7b651d8 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
@@ -22,6 +22,8 @@
import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.BrightnessUtils;
+import java.io.PrintWriter;
+
/**
* Manages the brightness of the display when the system brightness is overridden
*/
@@ -40,4 +42,7 @@
public String getName() {
return "OverrideBrightnessStrategy";
}
+
+ @Override
+ public void dump(PrintWriter writer) {}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
index 3d411d3..201ef41 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
@@ -23,6 +23,8 @@
import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.BrightnessUtils;
+import java.io.PrintWriter;
+
/**
* Manages the brightness of the display when the system is in the ScreenOff state.
*/
@@ -41,4 +43,7 @@
public String getName() {
return "ScreenOffBrightnessStrategy";
}
+
+ @Override
+ public void dump(PrintWriter writer) {}
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
index 35f7dd0..bbd0c00 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
@@ -68,6 +68,7 @@
/**
* Dumps the state of this class.
*/
+ @Override
public void dump(PrintWriter writer) {
writer.println("TemporaryBrightnessStrategy:");
writer.println(" mTemporaryScreenBrightness:" + mTemporaryScreenBrightness);
diff --git a/services/core/java/com/android/server/dreams/DreamManagerService.java b/services/core/java/com/android/server/dreams/DreamManagerService.java
index d2aff25..c6d66db 100644
--- a/services/core/java/com/android/server/dreams/DreamManagerService.java
+++ b/services/core/java/com/android/server/dreams/DreamManagerService.java
@@ -67,6 +67,7 @@
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.logging.UiEventLoggerImpl;
import com.android.internal.util.DumpUtils;
@@ -112,7 +113,7 @@
private final Object mLock = new Object();
private final Context mContext;
- private final DreamHandler mHandler;
+ private final Handler mHandler;
private final DreamController mController;
private final PowerManager mPowerManager;
private final PowerManagerInternal mPowerManagerInternal;
@@ -211,9 +212,14 @@
}
public DreamManagerService(Context context) {
+ this(context, new DreamHandler(FgThread.get().getLooper()));
+ }
+
+ @VisibleForTesting
+ DreamManagerService(Context context, Handler handler) {
super(context);
mContext = context;
- mHandler = new DreamHandler(FgThread.get().getLooper());
+ mHandler = handler;
mController = new DreamController(context, mHandler, mControllerListener);
mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
@@ -244,7 +250,6 @@
com.android.internal.R.bool.config_keepDreamingWhenUnplugging);
mDreamsDisabledByAmbientModeSuppressionConfig = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_dreamsDisabledByAmbientModeSuppressionConfig);
-
}
@Override
diff --git a/services/core/java/com/android/server/input/KeyboardMetricsCollector.java b/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
index 4b9f2cf..277a4d4 100644
--- a/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
+++ b/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
@@ -231,7 +231,10 @@
DESKTOP_MODE(
FrameworkStatsLog
.KEYBOARD_SYSTEMS_EVENT_REPORTED__KEYBOARD_SYSTEM_EVENT__DESKTOP_MODE,
- "DESKTOP_MODE");
+ "DESKTOP_MODE"),
+ MULTI_WINDOW_NAVIGATION(FrameworkStatsLog
+ .KEYBOARD_SYSTEMS_EVENT_REPORTED__KEYBOARD_SYSTEM_EVENT__MULTI_WINDOW_NAVIGATION,
+ "MULTIWINDOW_NAVIGATION");
private final int mValue;
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 9a76ebd..29ea071 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -108,7 +108,6 @@
import android.provider.Settings;
import android.security.AndroidKeyStoreMaintenance;
import android.security.Authorization;
-import android.security.KeyStore;
import android.security.keystore.KeyProperties;
import android.security.keystore.KeyProtection;
import android.security.keystore.recovery.KeyChainProtectionParams;
@@ -169,6 +168,7 @@
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
+import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@@ -292,7 +292,7 @@
private final IActivityManager mActivityManager;
private final SyntheticPasswordManager mSpManager;
- private final java.security.KeyStore mJavaKeyStore;
+ private final KeyStore mKeyStore;
private final RecoverableKeyStoreManager mRecoverableKeyStoreManager;
private final UnifiedProfilePasswordCache mUnifiedProfilePasswordCache;
@@ -564,10 +564,6 @@
return DeviceStateCache.getInstance();
}
- public KeyStore getKeyStore() {
- return KeyStore.getInstance();
- }
-
public RecoverableKeyStoreManager getRecoverableKeyStoreManager() {
return RecoverableKeyStoreManager.getInstance(mContext);
}
@@ -619,9 +615,9 @@
return (BiometricManager) mContext.getSystemService(Context.BIOMETRIC_SERVICE);
}
- public java.security.KeyStore getJavaKeyStore() {
+ public KeyStore getKeyStore() {
try {
- java.security.KeyStore ks = java.security.KeyStore.getInstance(
+ KeyStore ks = KeyStore.getInstance(
SyntheticPasswordCrypto.androidKeystoreProviderName());
ks.load(new AndroidKeyStoreLoadStoreParameter(
SyntheticPasswordCrypto.keyNamespace()));
@@ -631,8 +627,7 @@
}
}
- public @NonNull UnifiedProfilePasswordCache getUnifiedProfilePasswordCache(
- java.security.KeyStore ks) {
+ public @NonNull UnifiedProfilePasswordCache getUnifiedProfilePasswordCache(KeyStore ks) {
return new UnifiedProfilePasswordCache(ks);
}
@@ -654,7 +649,7 @@
protected LockSettingsService(Injector injector) {
mInjector = injector;
mContext = injector.getContext();
- mJavaKeyStore = injector.getJavaKeyStore();
+ mKeyStore = injector.getKeyStore();
mRecoverableKeyStoreManager = injector.getRecoverableKeyStoreManager();
mHandler = injector.getHandler(injector.getServiceThread());
mStrongAuth = injector.getStrongAuth();
@@ -676,7 +671,7 @@
mGatekeeperPasswords = new LongSparseArray<>();
mSpManager = injector.getSyntheticPasswordManager(mStorage);
- mUnifiedProfilePasswordCache = injector.getUnifiedProfilePasswordCache(mJavaKeyStore);
+ mUnifiedProfilePasswordCache = injector.getUnifiedProfilePasswordCache(mKeyStore);
mBiometricDeferredQueue = new BiometricDeferredQueue(mSpManager, mHandler);
mRebootEscrowManager = injector.getRebootEscrowManager(new RebootEscrowCallbacks(),
@@ -1482,7 +1477,7 @@
byte[] encryptedPassword = Arrays.copyOfRange(storedData, PROFILE_KEY_IV_SIZE,
storedData.length);
byte[] decryptionResult;
- SecretKey decryptionKey = (SecretKey) mJavaKeyStore.getKey(
+ SecretKey decryptionKey = (SecretKey) mKeyStore.getKey(
PROFILE_KEY_NAME_DECRYPT + userId, null);
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
@@ -1875,9 +1870,10 @@
}
}
- private void onPostPasswordChanged(LockscreenCredential newCredential, int userHandle) {
- updatePasswordHistory(newCredential, userHandle);
- mContext.getSystemService(TrustManager.class).reportEnabledTrustAgentsChanged(userHandle);
+ private void onPostPasswordChanged(LockscreenCredential newCredential, int userId) {
+ updatePasswordHistory(newCredential, userId);
+ mContext.getSystemService(TrustManager.class).reportEnabledTrustAgentsChanged(userId);
+ sendMainUserCredentialChangedNotificationIfNeeded(userId);
}
/**
@@ -2076,16 +2072,16 @@
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
try {
- mJavaKeyStore.setEntry(
+ mKeyStore.setEntry(
PROFILE_KEY_NAME_ENCRYPT + profileUserId,
- new java.security.KeyStore.SecretKeyEntry(secretKey),
+ new KeyStore.SecretKeyEntry(secretKey),
new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
- mJavaKeyStore.setEntry(
+ mKeyStore.setEntry(
PROFILE_KEY_NAME_DECRYPT + profileUserId,
- new java.security.KeyStore.SecretKeyEntry(secretKey),
+ new KeyStore.SecretKeyEntry(secretKey),
new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
@@ -2094,7 +2090,7 @@
.setUserAuthenticationValidityDurationSeconds(30)
.build());
// Key imported, obtain a reference to it.
- SecretKey keyStoreEncryptionKey = (SecretKey) mJavaKeyStore.getKey(
+ SecretKey keyStoreEncryptionKey = (SecretKey) mKeyStore.getKey(
PROFILE_KEY_NAME_ENCRYPT + profileUserId, null);
Cipher cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/"
@@ -2104,7 +2100,7 @@
iv = cipher.getIV();
} finally {
// The original key can now be discarded.
- mJavaKeyStore.deleteEntry(PROFILE_KEY_NAME_ENCRYPT + profileUserId);
+ mKeyStore.deleteEntry(PROFILE_KEY_NAME_ENCRYPT + profileUserId);
}
} catch (UnrecoverableKeyException
| BadPaddingException | IllegalBlockSizeException | KeyStoreException
@@ -2556,11 +2552,10 @@
final String encryptAlias = PROFILE_KEY_NAME_ENCRYPT + targetUserId;
final String decryptAlias = PROFILE_KEY_NAME_DECRYPT + targetUserId;
try {
- if (mJavaKeyStore.containsAlias(encryptAlias) ||
- mJavaKeyStore.containsAlias(decryptAlias)) {
+ if (mKeyStore.containsAlias(encryptAlias) || mKeyStore.containsAlias(decryptAlias)) {
Slogf.i(TAG, "Removing keystore profile key for user %d", targetUserId);
- mJavaKeyStore.deleteEntry(encryptAlias);
- mJavaKeyStore.deleteEntry(decryptAlias);
+ mKeyStore.deleteEntry(encryptAlias);
+ mKeyStore.deleteEntry(decryptAlias);
}
} catch (KeyStoreException e) {
// We have tried our best to remove the key.
@@ -3062,7 +3057,6 @@
setCurrentLskfBasedProtectorId(newProtectorId, userId);
LockPatternUtils.invalidateCredentialTypeCache();
synchronizeUnifiedChallengeForProfiles(userId, profilePasswords);
- sendMainUserCredentialChangedNotificationIfNeeded(userId);
setUserPasswordMetrics(credential, userId);
mUnifiedProfilePasswordCache.removePassword(userId);
@@ -3457,7 +3451,7 @@
private void dumpKeystoreKeys(IndentingPrintWriter pw) {
try {
- final Enumeration<String> aliases = mJavaKeyStore.aliases();
+ final Enumeration<String> aliases = mKeyStore.aliases();
while (aliases.hasMoreElements()) {
pw.println(aliases.nextElement());
}
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index 3f9e989..9b0fec2 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -22,8 +22,8 @@
import static android.app.AppOpsManager.MODE_IGNORED;
import static android.app.AppOpsManager.OP_ARCHIVE_ICON_OVERLAY;
import static android.app.AppOpsManager.OP_UNARCHIVAL_CONFIRMATION;
-import static android.app.ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED;
-import static android.app.ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED;
import static android.app.PendingIntent.FLAG_IMMUTABLE;
import static android.app.PendingIntent.FLAG_MUTABLE;
import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
diff --git a/services/core/java/com/android/server/pm/PackageArchiver.java b/services/core/java/com/android/server/pm/PackageArchiver.java
index 2b20bfd..ef8453d 100644
--- a/services/core/java/com/android/server/pm/PackageArchiver.java
+++ b/services/core/java/com/android/server/pm/PackageArchiver.java
@@ -21,7 +21,7 @@
import static android.app.ActivityManager.START_PERMISSION_DENIED;
import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.MODE_IGNORED;
-import static android.app.ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED;
+import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED;
import static android.content.pm.ArchivedActivityInfo.bytesFromBitmap;
import static android.content.pm.ArchivedActivityInfo.drawableToBitmap;
import static android.content.pm.PackageInstaller.EXTRA_UNARCHIVE_STATUS;
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 69f7906..fe8030b 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -1541,6 +1541,19 @@
return;
}
+ // Initialize all necessary settings for archival installation.
+ pkgSetting
+ // No package.
+ .setPkg(null)
+ // Mark for later restore.
+ .setPendingRestore(true);
+ for (int userId : userIds) {
+ // Unmark "installed" for all users.
+ pkgSetting
+ .modifyUserState(userId)
+ .setInstalled(false);
+ }
+
String responsibleInstallerPackage = PackageArchiver.getResponsibleInstallerPackage(
pkgSetting);
// TODO(b/278553670) Check if responsibleInstallerPackage supports unarchival.
@@ -1551,16 +1564,11 @@
for (int userId : userIds) {
var archiveState = mInstallerService.mPackageArchiver.createArchiveState(
archivePackage, userId, responsibleInstallerPackage);
- if (archiveState == null) {
- continue;
- }
- pkgSetting
- .setPkg(null)
- // This package was installed as archived. Need to mark it for later restore.
- .setPendingRestore(true)
+ if (archiveState != null) {
+ pkgSetting
.modifyUserState(userId)
- .setInstalled(false)
.setArchiveState(archiveState);
+ }
}
}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 8781bf1..e9a7fe1 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3504,8 +3504,8 @@
if (firstDown && event.isMetaPressed() && event.isCtrlPressed()) {
StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
if (statusbar != null) {
- statusbar.goToFullscreenFromSplit();
- logKeyboardSystemsEvent(event, KeyboardLogEvent.SPLIT_SCREEN_NAVIGATION);
+ statusbar.moveFocusedTaskToFullscreen(event.getDisplayId());
+ logKeyboardSystemsEvent(event, KeyboardLogEvent.MULTI_WINDOW_NAVIGATION);
return true;
}
}
@@ -6410,7 +6410,7 @@
private boolean performHapticFeedback(int effectId, boolean always, String reason) {
return performHapticFeedback(Process.myUid(), mContext.getOpPackageName(),
- effectId, always, reason);
+ effectId, always, reason, false /* fromIme */);
}
@Override
@@ -6420,7 +6420,7 @@
@Override
public boolean performHapticFeedback(int uid, String packageName, int effectId,
- boolean always, String reason) {
+ boolean always, String reason, boolean fromIme) {
if (!mVibrator.hasVibrator()) {
return false;
}
@@ -6431,7 +6431,7 @@
}
VibrationAttributes attrs =
mHapticFeedbackVibrationProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ always);
+ effectId, /* bypassVibrationIntensitySetting= */ always, fromIme);
VibratorFrameworkStatsLogger.logPerformHapticsFeedbackIfKeyboard(uid, effectId);
mVibrator.vibrate(uid, packageName, effect, reason, attrs);
return true;
diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
index 2174fd6..5956594 100644
--- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
@@ -1072,7 +1072,7 @@
* Call from application to perform haptic feedback on its window.
*/
public boolean performHapticFeedback(int uid, String packageName, int effectId,
- boolean always, String reason);
+ boolean always, String reason, boolean fromIme);
/**
* Called when we have started keeping the screen on because a window
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerInternal.java b/services/core/java/com/android/server/statusbar/StatusBarManagerInternal.java
index 3c6baa8..14e0ce1 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerInternal.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerInternal.java
@@ -224,9 +224,11 @@
void showRearDisplayDialog(int currentBaseState);
/**
- * Called when requested to go to fullscreen from the active split app.
+ * Called when requested to go to fullscreen from the focused app.
+ *
+ * @param displayId of the current display.
*/
- void goToFullscreenFromSplit();
+ void moveFocusedTaskToFullscreen(int displayId);
/**
* Enters stage split from a current running app.
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 14c38bd..0b48a75 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -810,11 +810,11 @@
}
@Override
- public void goToFullscreenFromSplit() {
+ public void moveFocusedTaskToFullscreen(int displayId) {
IStatusBar bar = mBar;
if (bar != null) {
try {
- bar.goToFullscreenFromSplit();
+ bar.moveFocusedTaskToFullscreen(displayId);
} catch (RemoteException ex) { }
}
}
diff --git a/services/core/java/com/android/server/utils/AnrTimer.java b/services/core/java/com/android/server/utils/AnrTimer.java
index 743005a..b7d8cfc 100644
--- a/services/core/java/com/android/server/utils/AnrTimer.java
+++ b/services/core/java/com/android/server/utils/AnrTimer.java
@@ -767,7 +767,7 @@
* Return true if the native timers are supported. Native timers are supported if the method
* nativeAnrTimerSupported() can be executed and it returns true.
*/
- private static boolean nativeTimersSupported() {
+ public static boolean nativeTimersSupported() {
try {
return nativeAnrTimerSupported();
} catch (java.lang.UnsatisfiedLinkError e) {
diff --git a/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java b/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
index 519acec..126af1f 100644
--- a/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
+++ b/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
@@ -190,10 +190,11 @@
* to get.
* @param bypassVibrationIntensitySetting {@code true} if the returned attribute should bypass
* vibration intensity settings. {@code false} otherwise.
+ * @param fromIme the haptic feedback is performed from an IME.
* @return the {@link VibrationAttributes} that should be used for the provided haptic feedback.
*/
public VibrationAttributes getVibrationAttributesForHapticFeedback(
- int effectId, boolean bypassVibrationIntensitySetting) {
+ int effectId, boolean bypassVibrationIntensitySetting, boolean fromIme) {
VibrationAttributes attrs;
switch (effectId) {
case HapticFeedbackConstants.EDGE_SQUEEZE:
@@ -209,7 +210,7 @@
break;
case HapticFeedbackConstants.KEYBOARD_TAP:
case HapticFeedbackConstants.KEYBOARD_RELEASE:
- attrs = createKeyboardVibrationAttributes();
+ attrs = createKeyboardVibrationAttributes(fromIme);
break;
default:
attrs = TOUCH_VIBRATION_ATTRIBUTES;
@@ -222,7 +223,7 @@
if (shouldBypassInterruptionPolicy(effectId)) {
flags |= VibrationAttributes.FLAG_BYPASS_INTERRUPTION_POLICY;
}
- if (shouldBypassIntensityScale(effectId)) {
+ if (shouldBypassIntensityScale(effectId, fromIme)) {
flags |= VibrationAttributes.FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE;
}
@@ -337,9 +338,9 @@
/* fallbackForPredefinedEffect= */ predefinedEffectFallback);
}
- private boolean shouldBypassIntensityScale(int effectId) {
- if (!Flags.keyboardCategoryEnabled() || mKeyboardVibrationFixedAmplitude < 0) {
- // shouldn't bypass if not support keyboard category or no fixed amplitude
+ private boolean shouldBypassIntensityScale(int effectId, boolean isIme) {
+ if (!Flags.keyboardCategoryEnabled() || mKeyboardVibrationFixedAmplitude < 0 || !isIme) {
+ // Shouldn't bypass if not support keyboard category, no fixed amplitude or not an IME.
return false;
}
switch (effectId) {
@@ -353,8 +354,9 @@
return false;
}
- private static VibrationAttributes createKeyboardVibrationAttributes() {
- if (!Flags.keyboardCategoryEnabled()) {
+ private VibrationAttributes createKeyboardVibrationAttributes(boolean fromIme) {
+ // Use touch attribute when the keyboard category is disable or it's not from an IME.
+ if (!Flags.keyboardCategoryEnabled() || !fromIme) {
return TOUCH_VIBRATION_ATTRIBUTES;
}
diff --git a/services/core/java/com/android/server/vibrator/VibratorManagerService.java b/services/core/java/com/android/server/vibrator/VibratorManagerService.java
index 78e0ebb..78ebe24 100644
--- a/services/core/java/com/android/server/vibrator/VibratorManagerService.java
+++ b/services/core/java/com/android/server/vibrator/VibratorManagerService.java
@@ -416,14 +416,14 @@
}
@Override // Binder call
- public void performHapticFeedback(
- int uid, int deviceId, String opPkg, int constant, boolean always, String reason) {
+ public void performHapticFeedback(int uid, int deviceId, String opPkg, int constant,
+ boolean always, String reason, boolean fromIme) {
// Note that the `performHapticFeedback` method does not take a token argument from the
// caller, and instead, uses this service as the token. This is to mitigate performance
// impact that would otherwise be caused due to marshal latency. Haptic feedback effects are
// short-lived, so we don't need to cancel when the process dies.
performHapticFeedbackInternal(
- uid, deviceId, opPkg, constant, always, reason, /* token= */ this);
+ uid, deviceId, opPkg, constant, always, reason, /* token= */ this, fromIme);
}
/**
@@ -435,7 +435,7 @@
@Nullable
HalVibration performHapticFeedbackInternal(
int uid, int deviceId, String opPkg, int constant, boolean always, String reason,
- IBinder token) {
+ IBinder token, boolean fromIme) {
HapticFeedbackVibrationProvider hapticVibrationProvider = getHapticVibrationProvider();
if (hapticVibrationProvider == null) {
Slog.w(TAG, "performHapticFeedback; haptic vibration provider not ready.");
@@ -449,7 +449,7 @@
CombinedVibration combinedVibration = CombinedVibration.createParallel(effect);
VibrationAttributes attrs =
hapticVibrationProvider.getVibrationAttributesForHapticFeedback(
- constant, /* bypassVibrationIntensitySetting= */ always);
+ constant, /* bypassVibrationIntensitySetting= */ always, fromIme);
VibratorFrameworkStatsLogger.logPerformHapticsFeedbackIfKeyboard(uid, constant);
return vibrateWithoutPermissionCheck(uid, deviceId, opPkg, combinedVibration, attrs,
"performHapticFeedback: " + reason, token);
@@ -2300,7 +2300,7 @@
HalVibration vib = performHapticFeedbackInternal(Binder.getCallingUid(),
Context.DEVICE_ID_DEFAULT, SHELL_PACKAGE_NAME, constant,
/* always= */ commonOptions.force, /* reason= */ commonOptions.description,
- deathBinder);
+ deathBinder, false /* fromIme */);
maybeWaitOnVibration(vib, commonOptions);
return 0;
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperCropper.java b/services/core/java/com/android/server/wallpaper/WallpaperCropper.java
index 37f3825..601c7f4 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperCropper.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperCropper.java
@@ -357,15 +357,30 @@
* Given some suggested crops, find cropHints for all orientations of the default display.
*/
SparseArray<Rect> getDefaultCrops(SparseArray<Rect> suggestedCrops, Point bitmapSize) {
- SparseArray<Rect> result = new SparseArray<>();
- // add missing cropHints for all orientation of the default display
+
SparseArray<Point> defaultDisplaySizes = mWallpaperDisplayHelper.getDefaultDisplaySizes();
boolean rtl = TextUtils.getLayoutDirectionFromLocale(Locale.getDefault())
== View.LAYOUT_DIRECTION_RTL;
+
+ // adjust existing entries for the default display
+ SparseArray<Rect> adjustedSuggestedCrops = new SparseArray<>();
for (int i = 0; i < defaultDisplaySizes.size(); i++) {
int orientation = defaultDisplaySizes.keyAt(i);
Point displaySize = defaultDisplaySizes.valueAt(i);
- Rect newCrop = getCrop(displaySize, bitmapSize, suggestedCrops, rtl);
+ Rect suggestedCrop = suggestedCrops.get(orientation);
+ if (suggestedCrop != null) {
+ adjustedSuggestedCrops.put(orientation,
+ getCrop(displaySize, bitmapSize, suggestedCrops, rtl));
+ }
+ }
+
+ // add missing cropHints for all orientation of the default display
+ SparseArray<Rect> result = adjustedSuggestedCrops.clone();
+ for (int i = 0; i < defaultDisplaySizes.size(); i++) {
+ int orientation = defaultDisplaySizes.keyAt(i);
+ if (result.contains(orientation)) continue;
+ Point displaySize = defaultDisplaySizes.valueAt(i);
+ Rect newCrop = getCrop(displaySize, bitmapSize, adjustedSuggestedCrops, rtl);
result.put(orientation, newCrop);
}
return result;
diff --git a/services/core/java/com/android/server/wearable/WearableSensingManagerService.java b/services/core/java/com/android/server/wearable/WearableSensingManagerService.java
index 5f6ffd98..8742ab1 100644
--- a/services/core/java/com/android/server/wearable/WearableSensingManagerService.java
+++ b/services/core/java/com/android/server/wearable/WearableSensingManagerService.java
@@ -21,8 +21,8 @@
import android.Manifest;
import android.annotation.NonNull;
import android.annotation.UserIdInt;
+import android.app.ActivityOptions;
import android.app.BroadcastOptions;
-import android.app.ComponentOptions;
import android.app.PendingIntent;
import android.app.ambientcontext.AmbientContextEvent;
import android.app.wearable.IWearableSensingManager;
@@ -353,7 +353,7 @@
dataRequest);
BroadcastOptions options = BroadcastOptions.makeBasic();
options.setPendingIntentBackgroundActivityStartMode(
- ComponentOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);
+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);
mDataRequestRateLimiter.noteEvent(
userId, RATE_LIMITER_PACKAGE_NAME, RATE_LIMITER_TAG);
final long previousCallingIdentity = Binder.clearCallingIdentity();
diff --git a/services/core/java/com/android/server/wm/ActivityClientController.java b/services/core/java/com/android/server/wm/ActivityClientController.java
index ed5df5f..981c4c0 100644
--- a/services/core/java/com/android/server/wm/ActivityClientController.java
+++ b/services/core/java/com/android/server/wm/ActivityClientController.java
@@ -506,7 +506,8 @@
// keep backwards compatibility we remove the task from recents when finishing
// task with root activity.
mTaskSupervisor.removeTask(tr, false /*killProcess*/,
- finishWithRootActivity, "finish-activity", r.getUid(), r.info.name);
+ finishWithRootActivity, "finish-activity", r.getUid(), r.getPid(),
+ r.info.name);
res = true;
// Explicitly dismissing the activity so reset its relaunch flag.
r.mRelaunchReason = RELAUNCH_REASON_NONE;
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 90cff39..92fde18 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -1476,7 +1476,8 @@
}
}
- private void scheduleConfigurationChanged(Configuration config) {
+ private void scheduleConfigurationChanged(@NonNull Configuration config,
+ @NonNull ActivityWindowInfo activityWindowInfo) {
if (!attachedToProcess()) {
ProtoLog.w(WM_DEBUG_CONFIGURATION, "Can't report activity configuration "
+ "update - client not running, activityRecord=%s", this);
@@ -1487,7 +1488,7 @@
+ "config: %s", this, config);
mAtmService.getLifecycleManager().scheduleTransactionItem(app.getThread(),
- ActivityConfigurationChangeItem.obtain(token, config));
+ ActivityConfigurationChangeItem.obtain(token, config, activityWindowInfo));
} catch (RemoteException e) {
// If process died, whatever.
}
@@ -9785,7 +9786,11 @@
// configurations because there are cases (like moving a task to the root pinned task) where
// the combine configurations are equal, but would otherwise differ in the override config
mTmpConfig.setTo(mLastReportedConfiguration.getMergedConfiguration());
- if (getConfiguration().equals(mTmpConfig) && !displayChanged) {
+ final ActivityWindowInfo newActivityWindowInfo = getActivityWindowInfo();
+ final boolean isActivityWindowInfoChanged = Flags.activityWindowInfoFlag()
+ && !mLastReportedActivityWindowInfo.equals(newActivityWindowInfo);
+ if (!displayChanged && !isActivityWindowInfoChanged
+ && getConfiguration().equals(mTmpConfig)) {
ProtoLog.v(WM_DEBUG_CONFIGURATION, "Configuration & display "
+ "unchanged in %s", this);
return true;
@@ -9800,7 +9805,6 @@
// Update last reported values.
final Configuration newMergedOverrideConfig = getMergedOverrideConfiguration();
- final ActivityWindowInfo newActivityWindowInfo = getActivityWindowInfo();
setLastReportedConfiguration(getProcessGlobalConfiguration(), newMergedOverrideConfig);
setLastReportedActivityWindowInfo(newActivityWindowInfo);
@@ -9823,7 +9827,7 @@
scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig,
newActivityWindowInfo);
} else {
- scheduleConfigurationChanged(newMergedOverrideConfig);
+ scheduleConfigurationChanged(newMergedOverrideConfig, newActivityWindowInfo);
}
notifyDisplayCompatPolicyAboutConfigurationChange(
mLastReportedConfiguration.getMergedConfiguration(), mTmpConfig);
@@ -9891,7 +9895,7 @@
scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig,
newActivityWindowInfo);
} else {
- scheduleConfigurationChanged(newMergedOverrideConfig);
+ scheduleConfigurationChanged(newMergedOverrideConfig, newActivityWindowInfo);
}
notifyDisplayCompatPolicyAboutConfigurationChange(
mLastReportedConfiguration.getMergedConfiguration(), mTmpConfig);
diff --git a/services/core/java/com/android/server/wm/ActivitySecurityModelFeatureFlags.java b/services/core/java/com/android/server/wm/ActivitySecurityModelFeatureFlags.java
index 01d077a..4149bd9 100644
--- a/services/core/java/com/android/server/wm/ActivitySecurityModelFeatureFlags.java
+++ b/services/core/java/com/android/server/wm/ActivitySecurityModelFeatureFlags.java
@@ -41,7 +41,7 @@
static final String DOC_LINK = "go/android-asm";
/** Used to determine which version of the ASM logic was used in logs while we iterate */
- static final int ASM_VERSION = 9;
+ static final int ASM_VERSION = 10;
private static final String NAMESPACE = NAMESPACE_WINDOW_MANAGER;
private static final String KEY_ASM_PREFIX = "ActivitySecurity__";
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index c137c54..6ad056f 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -2089,7 +2089,7 @@
if (!mSupervisor.getBackgroundActivityLaunchController().checkActivityAllowedToStart(
mSourceRecord, r, newTask, avoidMoveToFront(), targetTask, mLaunchFlags, mBalCode,
- mCallingUid, mRealCallingUid)) {
+ mCallingUid, mRealCallingUid, mPreferredTaskDisplayArea)) {
return START_ABORTED;
}
diff --git a/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java b/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
index aefa777..d1d498d 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
@@ -42,6 +42,7 @@
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
+import static android.os.Process.INVALID_PID;
import static android.os.Process.INVALID_UID;
import static android.os.Process.SYSTEM_UID;
import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
@@ -1652,11 +1653,11 @@
* @return Returns true if the given task was found and removed.
*/
boolean removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents,
- String reason, int callingUid) {
+ String reason, int callingUid, int callingPid) {
final Task task =
mRootWindowContainer.anyTaskForId(taskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
if (task != null) {
- removeTask(task, killProcess, removeFromRecents, reason, callingUid, null);
+ removeTask(task, killProcess, removeFromRecents, reason, callingUid, callingPid, null);
return true;
}
Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
@@ -1664,11 +1665,11 @@
}
void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason) {
- removeTask(task, killProcess, removeFromRecents, reason, SYSTEM_UID, null);
+ removeTask(task, killProcess, removeFromRecents, reason, SYSTEM_UID, INVALID_PID, null);
}
void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason,
- int callingUid, String callerActivityClassName) {
+ int callingUid, int callingPid, String callerActivityClassName) {
if (task.mInRemoveTask) {
// Prevent recursion.
return;
@@ -1705,8 +1706,8 @@
if (task.isPersistable) {
mService.notifyTaskPersisterLocked(null, true);
}
- mBalController
- .checkActivityAllowedToClearTask(task, callingUid, callerActivityClassName);
+ mBalController.checkActivityAllowedToClearTask(
+ task, callingUid, callingPid, callerActivityClassName);
} finally {
task.mInRemoveTask = false;
}
@@ -1874,7 +1875,7 @@
// Task was trimmed from the recent tasks list -- remove the active task record as well
// since the user won't really be able to go back to it
removeTaskById(task.mTaskId, killProcess, false /* removeFromRecents */,
- "recent-task-trimmed", SYSTEM_UID);
+ "recent-task-trimmed", SYSTEM_UID, INVALID_PID);
}
task.removedFromRecents();
}
diff --git a/services/core/java/com/android/server/wm/AppTaskImpl.java b/services/core/java/com/android/server/wm/AppTaskImpl.java
index 50de0b0..d699af8 100644
--- a/services/core/java/com/android/server/wm/AppTaskImpl.java
+++ b/services/core/java/com/android/server/wm/AppTaskImpl.java
@@ -77,11 +77,13 @@
synchronized (mService.mGlobalLock) {
int origCallingUid = Binder.getCallingUid();
+ int origCallingPid = Binder.getCallingPid();
final long callingIdentity = Binder.clearCallingIdentity();
try {
// We remove the task from recents to preserve backwards
if (!mService.mTaskSupervisor.removeTaskById(mTaskId, false,
- REMOVE_FROM_RECENTS, "finish-and-remove-task", origCallingUid)) {
+ REMOVE_FROM_RECENTS, "finish-and-remove-task", origCallingUid,
+ origCallingPid)) {
throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
}
} finally {
diff --git a/services/core/java/com/android/server/wm/BackgroundActivityStartController.java b/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
index fdae53f..071f403 100644
--- a/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
+++ b/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
@@ -21,13 +21,16 @@
import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED;
import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED;
import static android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED;
-import static android.app.ComponentOptions.BackgroundActivityStartMode;
+import static android.app.ActivityOptions.BackgroundActivityStartMode;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
+import static android.os.Process.INVALID_PID;
+import static android.os.Process.INVALID_UID;
import static android.os.Process.SYSTEM_UID;
import static android.provider.DeviceConfig.NAMESPACE_WINDOW_MANAGER;
+import static com.android.server.wm.ActivityStarter.ASM_RESTRICTIONS;
import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ACTIVITY_STARTS;
import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
@@ -67,6 +70,7 @@
import android.util.Slog;
import android.widget.Toast;
+import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.FrameworkStatsLog;
@@ -75,6 +79,7 @@
import com.android.server.am.PendingIntentRecord;
import java.lang.annotation.Retention;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringJoiner;
import java.util.function.Consumer;
@@ -1022,7 +1027,7 @@
}
/**
- * Log activity starts which violate one of the following rules of the
+ * Check activity starts which violate one of the following rules of the
* activity security model (ASM):
* See go/activity-security for rationale behind the rules.
* 1. Within a task, only an activity matching a top UID of the task can start activities
@@ -1032,7 +1037,7 @@
boolean checkActivityAllowedToStart(@Nullable ActivityRecord sourceRecord,
@NonNull ActivityRecord targetRecord, boolean newTask, boolean avoidMoveTaskToFront,
@Nullable Task targetTask, int launchFlags, int balCode, int callingUid,
- int realCallingUid) {
+ int realCallingUid, TaskDisplayArea preferredTaskDisplayArea) {
// BAL Exception allowed in all cases
if (balCode == BAL_ALLOW_ALLOWLISTED_UID) {
return true;
@@ -1055,68 +1060,46 @@
}
}
- if (balCode == BAL_ALLOW_GRACE_PERIOD) {
- // Allow if launching into new task, and caller matches most recently finished activity
- if (taskToFront && mTopFinishedActivity != null
- && mTopFinishedActivity.mUid == callingUid) {
- return true;
- }
-
- // Launching into existing task - allow if matches most recently finished activity
- // within the task.
- // We can reach here multiple ways:
- // 1. activity in fg fires intent (taskToFront = false, sourceRecord is available)
- // 2. activity in bg fires intent (taskToFront = false, sourceRecord is available)
- // 3. activity in bg fires intent with NEW_FLAG (taskToFront = true,
- // avoidMoveTaskToFront = true, sourceRecord is available)
- // 4. activity in bg fires PI (taskToFront = true, avoidMoveTaskToFront = true,
- // sourceRecord is not available, targetTask may be available)
- if (!taskToFront || avoidMoveTaskToFront) {
- if (targetTask != null) {
- FinishedActivityEntry finishedEntry =
- mTaskIdToFinishedActivity.get(targetTask.mTaskId);
- if (finishedEntry != null && finishedEntry.mUid == callingUid) {
- return true;
- }
- }
-
- if (sourceRecord != null) {
- FinishedActivityEntry finishedEntry =
- mTaskIdToFinishedActivity.get(sourceRecord.getTask().mTaskId);
- if (finishedEntry != null && finishedEntry.mUid == callingUid) {
- return true;
- }
- }
- }
- }
-
- BlockActivityStart bas = null;
+ BlockActivityStart bas = new BlockActivityStart();
if (sourceRecord != null) {
- boolean passesAsmChecks = true;
Task sourceTask = sourceRecord.getTask();
+ Task taskToCheck = taskToFront ? sourceTask : targetTask;
+ bas = checkTopActivityForAsm(taskToCheck, sourceRecord.getUid(),
+ sourceRecord, bas);
+
// Allow launching into a new task (or a task matching the launched activity's
// affinity) only if the current task is foreground or mutating its own task.
// The latter can happen eg. if caller uses NEW_TASK flag and the activity being
// launched matches affinity of source task.
- if (taskToFront) {
- passesAsmChecks = sourceTask != null
- && (sourceTask.isVisible() || sourceTask == targetTask);
- }
-
- if (passesAsmChecks) {
- Task taskToCheck = taskToFront ? sourceTask : targetTask;
- bas = isTopActivityMatchingUidAbsentForAsm(taskToCheck, sourceRecord.getUid(),
- sourceRecord);
+ if (taskToFront && bas.mTopActivityMatchesSource) {
+ bas.mTopActivityMatchesSource = (sourceTask != null
+ && (sourceTask.isVisible() || sourceTask == targetTask));
}
} else if (targetTask != null && (!taskToFront || avoidMoveTaskToFront)) {
// We don't have a sourceRecord, and we're launching into an existing task.
// Allow if callingUid is top of stack.
- bas = isTopActivityMatchingUidAbsentForAsm(targetTask, callingUid,
- /*sourceRecord*/null);
+ bas = checkTopActivityForAsm(targetTask, callingUid,
+ /*sourceRecord*/null, bas);
+ } else {
+ // We're launching from a non-visible activity. Has any visible app opted in?
+ TaskDisplayArea displayArea = targetTask != null && targetTask.getDisplayArea() != null
+ ? targetTask.getDisplayArea()
+ : preferredTaskDisplayArea;
+ if (displayArea != null) {
+ ArrayList<Task> visibleTasks = displayArea.getVisibleTasks();
+ for (int i = 0; i < visibleTasks.size(); i++) {
+ Task task = visibleTasks.get(i);
+ if (visibleTasks.size() == 1 && task.isActivityTypeHomeOrRecents()) {
+ bas.optedIn(task.getTopMostActivity());
+ } else {
+ bas = checkTopActivityForAsm(task, callingUid, /*sourceRecord*/null, bas);
+ }
+ }
+ }
}
- if (bas != null && !bas.mWouldBlockActivityStartIgnoringFlag) {
+ if (bas.mTopActivityMatchesSource) {
return true;
}
@@ -1140,13 +1123,16 @@
? FrameworkStatsLog.ACTIVITY_ACTION_BLOCKED__ACTION__ACTIVITY_START_SAME_TASK
: FrameworkStatsLog.ACTIVITY_ACTION_BLOCKED__ACTION__ACTIVITY_START_DIFFERENT_TASK);
- boolean blockActivityStartAndFeatureEnabled = ActivitySecurityModelFeatureFlags
- .shouldRestrictActivitySwitch(callingUid)
- && (bas == null || bas.mBlockActivityStartIfFlagEnabled);
+ boolean enforceBlock = bas.mTopActivityOptedIn
+ && ActivitySecurityModelFeatureFlags.shouldRestrictActivitySwitch(callingUid);
+
+ boolean allowedByGracePeriod = allowedByAsmGracePeriod(callingUid, sourceRecord, targetTask,
+ balCode, taskToFront, avoidMoveTaskToFront);
String asmDebugInfo = getDebugInfoForActivitySecurity("Launch", sourceRecord,
targetRecord, targetTask, targetTopActivity, realCallingUid, balCode,
- blockActivityStartAndFeatureEnabled, taskToFront, avoidMoveTaskToFront);
+ enforceBlock, taskToFront, avoidMoveTaskToFront, allowedByGracePeriod,
+ bas.mActivityOptedIn);
FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_ACTION_BLOCKED,
/* caller_uid */
@@ -1184,7 +1170,7 @@
String launchedFromPackageName = targetRecord.launchedFromPackage;
if (ActivitySecurityModelFeatureFlags.shouldShowToast(callingUid)) {
String toastText = ActivitySecurityModelFeatureFlags.DOC_LINK
- + (blockActivityStartAndFeatureEnabled ? " blocked " : " would block ")
+ + (enforceBlock ? " blocked " : " would block ")
+ getApplicationLabel(mService.mContext.getPackageManager(),
launchedFromPackageName);
showToast(toastText);
@@ -1192,7 +1178,7 @@
Slog.i(TAG, asmDebugInfo);
}
- if (blockActivityStartAndFeatureEnabled) {
+ if (enforceBlock) {
Slog.e(TAG, "[ASM] Abort Launching r: " + targetRecord
+ " as source: "
+ (sourceRecord != null ? sourceRecord : launchedFromPackageName)
@@ -1251,18 +1237,18 @@
// Find the first activity which matches a safe UID and is not finishing. Clear everything
// above it
+ int[] finishCount = new int[1];
boolean shouldBlockActivityStart = ActivitySecurityModelFeatureFlags
.shouldRestrictActivitySwitch(callingUid);
- int[] finishCount = new int[0];
- if (shouldBlockActivityStart
- && blockCrossUidActivitySwitchFromBelowForActivity(targetTaskTop)) {
+ BlockActivityStart bas = checkCrossUidActivitySwitchFromBelow(
+ targetTaskTop, callingUid, new BlockActivityStart());
+ if (shouldBlockActivityStart && bas.mTopActivityOptedIn) {
ActivityRecord activity = targetTask.getActivity(isLaunchingOrLaunched);
if (activity == null) {
// mStartActivity is not in task, so clear everything
activity = targetRecord;
}
- finishCount = new int[1];
targetTask.performClearTop(activity, launchFlags, finishCount);
if (finishCount[0] > 0) {
Slog.w(TAG, "Cleared top n: " + finishCount[0] + " activities from task t: "
@@ -1279,7 +1265,8 @@
Slog.i(TAG, getDebugInfoForActivitySecurity("Clear Top", sourceRecord, targetRecord,
targetTask, targetTaskTop, realCallingUid, balCode, shouldBlockActivityStart,
- /* taskToFront */ true, /* avoidMoveTaskToFront */ false));
+ /* taskToFront */ true, /* avoidMoveTaskToFront */ false,
+ /* allowedByAsmGracePeriod */ false, bas.mActivityOptedIn));
}
}
@@ -1287,7 +1274,7 @@
* Returns home if the passed in callingUid is not top of the stack, rather than returning to
* previous task.
*/
- void checkActivityAllowedToClearTask(@NonNull Task task, int callingUid,
+ void checkActivityAllowedToClearTask(@NonNull Task task, int callingUid, int callingPid,
@NonNull String callerActivityClassName) {
// We may have already checked that the callingUid has additional clearTask privileges, and
// cleared the calling identify. If so, we infer we do not need further restrictions here.
@@ -1295,14 +1282,28 @@
return;
}
+ String packageName = mService.mContext.getPackageManager().getNameForUid(callingUid);
+ BalState state = new BalState(callingUid, callingPid, packageName, INVALID_UID,
+ INVALID_PID, null, null, null, null, null, ActivityOptions.makeBasic());
+ @BalCode int balCode = checkBackgroundActivityStartAllowedByCaller(state).mCode;
+ if (balCode == BAL_ALLOW_ALLOWLISTED_UID
+ || balCode == BAL_ALLOW_ALLOWLISTED_COMPONENT
+ || balCode == BAL_ALLOW_PERMISSION
+ || balCode == BAL_ALLOW_SAW_PERMISSION
+ || balCode == BAL_ALLOW_VISIBLE_WINDOW
+ || balCode == BAL_ALLOW_NON_APP_VISIBLE_WINDOW) {
+ return;
+ }
+
TaskDisplayArea displayArea = task.getTaskDisplayArea();
if (displayArea == null) {
// If there is no associated display area, we can not return home.
return;
}
- BlockActivityStart bas = isTopActivityMatchingUidAbsentForAsm(task, callingUid, null);
- if (!bas.mWouldBlockActivityStartIgnoringFlag) {
+ BlockActivityStart bas = checkTopActivityForAsm(task, callingUid, null,
+ new BlockActivityStart());
+ if (bas.mTopActivityMatchesSource) {
return;
}
@@ -1339,8 +1340,7 @@
);
boolean restrictActivitySwitch = ActivitySecurityModelFeatureFlags
- .shouldRestrictActivitySwitch(callingUid)
- && bas.mBlockActivityStartIfFlagEnabled;
+ .shouldRestrictActivitySwitch(callingUid) && bas.mTopActivityOptedIn;
PackageManager pm = mService.mContext.getPackageManager();
String callingPackage = pm.getNameForUid(callingUid);
@@ -1381,32 +1381,30 @@
* <p>
* The 'sourceRecord' can be considered top even if it is 'finishing'
* <p>
- * Returns a class where the elements are:
- * <pre>
- * shouldBlockActivityStart: {@code true} if we should actually block the transition (takes into
- * consideration feature flag and targetSdk).
- * wouldBlockActivityStartIgnoringFlags: {@code true} if we should warn about the transition via
- * toasts. This happens if the transition would be blocked in case both the app was targeting V+
- * and the feature was enabled.
- * </pre>
*/
- private BlockActivityStart isTopActivityMatchingUidAbsentForAsm(@NonNull Task task,
- int uid, @Nullable ActivityRecord sourceRecord) {
+ private BlockActivityStart checkTopActivityForAsm(@NonNull Task task,
+ int uid, @Nullable ActivityRecord sourceRecord, BlockActivityStart bas) {
// If the source is visible, consider it 'top'.
if (sourceRecord != null && sourceRecord.isVisibleRequested()) {
- return BlockActivityStart.ACTIVITY_START_ALLOWED;
+ return bas.matchesSource();
}
- // Always allow actual top activity to clear task
+ // Always allow actual top activity
ActivityRecord topActivity = task.getTopMostActivity();
- if (topActivity != null && topActivity.isUid(uid)) {
- return BlockActivityStart.ACTIVITY_START_ALLOWED;
+ if (topActivity == null) {
+ Slog.wtf(TAG, "Activities for task: " + task + " not found.");
+ return bas.optedIn(topActivity);
+ }
+
+ bas = checkCrossUidActivitySwitchFromBelow(topActivity, uid, bas);
+ if (bas.mTopActivityMatchesSource) {
+ return bas;
}
// If UID is visible in target task, allow launch
if (task.forAllActivities((Predicate<ActivityRecord>)
ar -> ar.isUid(uid) && ar.isVisibleRequested())) {
- return BlockActivityStart.ACTIVITY_START_ALLOWED;
+ return bas.matchesSource();
}
// Consider the source activity, whether or not it is finishing. Do not consider any other
@@ -1417,82 +1415,91 @@
// Check top of stack (or the first task fragment for embedding).
topActivity = task.getActivity(topOfStackPredicate);
if (topActivity == null) {
- return new BlockActivityStart(true, true);
+ return bas;
}
- BlockActivityStart pair = blockCrossUidActivitySwitchFromBelow(topActivity, uid);
- if (!pair.mBlockActivityStartIfFlagEnabled) {
- return pair;
+ bas = checkCrossUidActivitySwitchFromBelow(topActivity, uid, bas);
+ if (bas.mTopActivityMatchesSource) {
+ return bas;
}
// Even if the top activity is not a match, we may be in an embedded activity scenario with
// an adjacent task fragment. Get the second fragment.
TaskFragment taskFragment = topActivity.getTaskFragment();
if (taskFragment == null) {
- return pair;
+ return bas;
}
TaskFragment adjacentTaskFragment = taskFragment.getAdjacentTaskFragment();
if (adjacentTaskFragment == null) {
- return pair;
+ return bas;
}
// Check the second fragment.
topActivity = adjacentTaskFragment.getActivity(topOfStackPredicate);
if (topActivity == null) {
- return new BlockActivityStart(true, true);
+ return bas;
}
- return blockCrossUidActivitySwitchFromBelow(topActivity, uid);
+ return checkCrossUidActivitySwitchFromBelow(topActivity, uid, bas);
}
/**
* Determines if a source is allowed to add or remove activities from the task,
* if the current ActivityRecord is above it in the stack
* <p>
- * A transition is blocked ({@code false} returned) if all of the following are met:
+ * A transition is blocked if all of the following are met:
* <pre>
* 1. The source activity and the current activity record belong to different apps
* (i.e, have different UIDs).
- * 2. Both the source activity and the current activity target U+
- * 3. The current activity has not set
+ * 2. The current activity target V+
+ * 3. The current app has set
+ * {@link R.styleable#AndroidManifestApplication_allowCrossUidActivitySwitchFromBelow}
+ * to {@code false}
+ * 4. The current activity has not set
* {@link ActivityRecord#setAllowCrossUidActivitySwitchFromBelow(boolean)} to {@code true}
* </pre>
*
- * Returns a class where the elements are:
- * <pre>
- * shouldBlockActivityStart: {@code true} if we should actually block the transition (takes into
- * consideration feature flag and targetSdk).
- * wouldBlockActivityStartIgnoringFlags: {@code true} if we should warn about the transition via
- * toasts. This happens if the transition would be blocked in case both the app was targeting V+
- * and the feature was enabled.
- * </pre>
*
* @param sourceUid The source (s) activity performing the state change
*/
- private BlockActivityStart blockCrossUidActivitySwitchFromBelow(ActivityRecord ar,
- int sourceUid) {
+ private BlockActivityStart checkCrossUidActivitySwitchFromBelow(ActivityRecord ar,
+ int sourceUid, BlockActivityStart bas) {
if (ar.isUid(sourceUid)) {
- return BlockActivityStart.ACTIVITY_START_ALLOWED;
+ return bas.matchesSource();
}
- if (!blockCrossUidActivitySwitchFromBelowForActivity(ar)) {
- return BlockActivityStart.ACTIVITY_START_ALLOWED;
+ // We don't need to check package level if activity has opted out.
+ if (ar.mAllowCrossUidActivitySwitchFromBelow) {
+ bas.mTopActivityOptedIn = false;
+ return bas.matchesSource();
}
- // At this point, we would block if the feature is launched and both apps were V+
- // Since we have a feature flag, we need to check that too
- // TODO(b/258792202) Replace with CompatChanges and replace Pair with boolean once feature
- // flag is removed
- boolean restrictActivitySwitch =
- ActivitySecurityModelFeatureFlags.shouldRestrictActivitySwitch(ar.getUid())
- && ActivitySecurityModelFeatureFlags
- .shouldRestrictActivitySwitch(sourceUid);
- if (restrictActivitySwitch) {
- return BlockActivityStart.BLOCK;
- } else {
- return BlockActivityStart.LOG_ONLY;
+ if (!CompatChanges.isChangeEnabled(ASM_RESTRICTIONS, ar.getUid())) {
+ return bas;
}
+
+ if (ar.isUid(SYSTEM_UID)) {
+ return bas.optedIn(ar);
+ }
+
+ String packageName = ar.packageName;
+ if (packageName == null) {
+ Slog.wtf(TAG, "Package name: " + ar + " not found.");
+ return bas.optedIn(ar);
+ }
+
+ PackageManager pm = mService.mContext.getPackageManager();
+ ApplicationInfo applicationInfo;
+
+ try {
+ applicationInfo = pm.getApplicationInfo(packageName, 0);
+ } catch (PackageManager.NameNotFoundException e) {
+ Slog.wtf(TAG, "Package name: " + packageName + " not found.");
+ return bas.optedIn(ar);
+ }
+
+ return applicationInfo.allowCrossUidActivitySwitchFromBelow ? bas : bas.optedIn(ar);
}
/**
@@ -1502,8 +1509,9 @@
@Nullable ActivityRecord sourceRecord, @NonNull ActivityRecord targetRecord,
@Nullable Task targetTask, @Nullable ActivityRecord targetTopActivity,
int realCallingUid, @BalCode int balCode,
- boolean blockActivityStartAndFeatureEnabled, boolean taskToFront,
- boolean avoidMoveTaskToFront) {
+ boolean enforceBlock, boolean taskToFront,
+ boolean avoidMoveTaskToFront, boolean allowedByGracePeriod,
+ ActivityRecord activityOptedIn) {
final String prefix = "[ASM] ";
Function<ActivityRecord, String> recordToString = (ar) -> {
if (ar == null) {
@@ -1519,9 +1527,16 @@
StringJoiner joiner = new StringJoiner("\n");
joiner.add(prefix + "------ Activity Security " + action + " Debug Logging Start ------");
- joiner.add(prefix + "Block Enabled: " + blockActivityStartAndFeatureEnabled);
+ joiner.add(prefix + "Block Enabled: " + enforceBlock);
+ if (!enforceBlock) {
+ joiner.add(prefix + "Feature Flag Enabled: " + android.security
+ .Flags.asmRestrictionsEnabled());
+ joiner.add(prefix + "Mendel Override: " + ActivitySecurityModelFeatureFlags
+ .asmRestrictionsEnabledForAll());
+ }
joiner.add(prefix + "ASM Version: " + ActivitySecurityModelFeatureFlags.ASM_VERSION);
joiner.add(prefix + "System Time: " + SystemClock.uptimeMillis());
+ joiner.add(prefix + "Activity Opted In: " + recordToString.apply(activityOptedIn));
boolean targetTaskMatchesSourceTask = targetTask != null
&& sourceRecord != null && sourceRecord.getTask() == targetTask;
@@ -1561,6 +1576,7 @@
joiner.add(prefix + "TaskToFront: " + taskToFront);
joiner.add(prefix + "AvoidMoveToFront: " + avoidMoveTaskToFront);
joiner.add(prefix + "BalCode: " + balCodeToString(balCode));
+ joiner.add(prefix + "Allowed By Grace Period: " + allowedByGracePeriod);
joiner.add(prefix + "LastResumedActivity: "
+ recordToString.apply(mService.mLastResumedActivity));
@@ -1588,6 +1604,44 @@
return joiner.toString();
}
+ private boolean allowedByAsmGracePeriod(int callingUid, @Nullable ActivityRecord sourceRecord,
+ @Nullable Task targetTask, @BalCode int balCode, boolean taskToFront,
+ boolean avoidMoveTaskToFront) {
+ if (balCode == BAL_ALLOW_GRACE_PERIOD) {
+ // Allow if launching into new task, and caller matches most recently finished activity
+ if (taskToFront && mTopFinishedActivity != null
+ && mTopFinishedActivity.mUid == callingUid) {
+ return true;
+ }
+
+ // Launching into existing task - allow if matches most recently finished activity
+ // within the task.
+ // We can reach here multiple ways:
+ // 1. activity in fg fires intent (taskToFront = false, sourceRecord is available)
+ // 2. activity in bg fires intent (taskToFront = false, sourceRecord is available)
+ // 3. activity in bg fires intent with NEW_FLAG (taskToFront = true,
+ // avoidMoveTaskToFront = true, sourceRecord is available)
+ // 4. activity in bg fires PI (taskToFront = true, avoidMoveTaskToFront = true,
+ // sourceRecord is not available, targetTask may be available)
+ if (!taskToFront || avoidMoveTaskToFront) {
+ if (targetTask != null) {
+ FinishedActivityEntry finishedEntry =
+ mTaskIdToFinishedActivity.get(targetTask.mTaskId);
+ if (finishedEntry != null && finishedEntry.mUid == callingUid) {
+ return true;
+ }
+ }
+
+ if (sourceRecord != null) {
+ FinishedActivityEntry finishedEntry =
+ mTaskIdToFinishedActivity.get(sourceRecord.getTask().mTaskId);
+ return finishedEntry != null && finishedEntry.mUid == callingUid;
+ }
+ }
+ }
+ return false;
+ }
+
private static boolean isSystemExemptFlagEnabled() {
return DeviceConfig.getBoolean(
NAMESPACE_WINDOW_MANAGER,
@@ -1698,55 +1752,22 @@
}
}
- /**
- * Activity level allowCrossUidActivitySwitchFromBelow defaults to false.
- * Package level defaults to true.
- * We block the launch if dev has explicitly set package level to false, and activity level has
- * not opted out
- */
- private boolean blockCrossUidActivitySwitchFromBelowForActivity(@NonNull ActivityRecord ar) {
- // We don't need to check package level if activity has opted out.
- if (ar.mAllowCrossUidActivitySwitchFromBelow) {
- return false;
- }
-
- if (ActivitySecurityModelFeatureFlags.asmRestrictionsEnabledForAll()) {
- return true;
- }
-
- String packageName = ar.packageName;
- if (packageName == null) {
- return false;
- }
-
- PackageManager pm = mService.mContext.getPackageManager();
- ApplicationInfo applicationInfo;
-
- try {
- applicationInfo = pm.getApplicationInfo(packageName, 0);
- } catch (PackageManager.NameNotFoundException e) {
- Slog.wtf(TAG, "Package name: " + packageName + " not found.");
- return false;
- }
-
- return !applicationInfo.allowCrossUidActivitySwitchFromBelow;
- }
-
private static class BlockActivityStart {
- private static final BlockActivityStart ACTIVITY_START_ALLOWED =
- new BlockActivityStart(false, false);
- private static final BlockActivityStart LOG_ONLY = new BlockActivityStart(false, true);
- private static final BlockActivityStart BLOCK = new BlockActivityStart(true, true);
- // We should block if feature flag is enabled
- private final boolean mBlockActivityStartIfFlagEnabled;
- // Used for logging/toasts. Would we block if target sdk was V and feature was
- // enabled?
- private final boolean mWouldBlockActivityStartIgnoringFlag;
+ private boolean mTopActivityOptedIn;
+ private boolean mTopActivityMatchesSource;
+ private ActivityRecord mActivityOptedIn;
- private BlockActivityStart(boolean shouldBlockActivityStart,
- boolean wouldBlockActivityStartIgnoringFlags) {
- this.mBlockActivityStartIfFlagEnabled = shouldBlockActivityStart;
- this.mWouldBlockActivityStartIgnoringFlag = wouldBlockActivityStartIgnoringFlags;
+ BlockActivityStart optedIn(ActivityRecord activity) {
+ mTopActivityOptedIn = true;
+ if (mActivityOptedIn == null) {
+ mActivityOptedIn = activity;
+ }
+ return this;
+ }
+
+ BlockActivityStart matchesSource() {
+ mTopActivityMatchesSource = true;
+ return this;
}
}
diff --git a/services/core/java/com/android/server/wm/DesktopModeLaunchParamsModifier.java b/services/core/java/com/android/server/wm/DesktopModeLaunchParamsModifier.java
index f11d6ec..925a077 100644
--- a/services/core/java/com/android/server/wm/DesktopModeLaunchParamsModifier.java
+++ b/services/core/java/com/android/server/wm/DesktopModeLaunchParamsModifier.java
@@ -27,7 +27,7 @@
import android.util.Slog;
import com.android.server.wm.LaunchParamsController.LaunchParamsModifier;
-import com.android.wm.shell.Flags;
+import com.android.window.flags.Flags;
/**
* The class that defines default launch params for tasks in desktop mode
*/
@@ -37,8 +37,6 @@
TAG_WITH_CLASS_NAME ? "DesktopModeLaunchParamsModifier" : TAG_ATM;
private static final boolean DEBUG = false;
- // Desktop mode feature flags.
- private static final boolean ENABLE_DESKTOP_WINDOWING = Flags.enableDesktopWindowing();
private static final boolean DESKTOP_MODE_PROTO2_SUPPORTED =
SystemProperties.getBoolean("persist.wm.debug.desktop_mode_2", false);
public static final float DESKTOP_MODE_INITIAL_BOUNDS_SCALE =
@@ -67,6 +65,11 @@
LaunchParamsController.LaunchParams currentParams,
LaunchParamsController.LaunchParams outParams) {
+ if (!isDesktopModeEnabled()) {
+ appendLog("desktop mode is not enabled, continuing");
+ return RESULT_CONTINUE;
+ }
+
if (task == null) {
appendLog("task null, skipping");
return RESULT_SKIP;
@@ -87,7 +90,7 @@
// previous windowing mode to be restored even if the desktop mode state has changed.
// Let task launches inherit the windowing mode from the source task if available, which
// should have the desired windowing mode set by WM Shell. See b/286929122.
- if (isDesktopModeSupported() && source != null && source.getTask() != null) {
+ if (isDesktopModeEnabled() && source != null && source.getTask() != null) {
final Task sourceTask = source.getTask();
outParams.mWindowingMode = sourceTask.getWindowingMode();
appendLog("inherit-from-source=" + outParams.mWindowingMode);
@@ -140,14 +143,8 @@
if (DEBUG) Slog.d(TAG, mLogBuilder.toString());
}
- /** Whether desktop mode is supported. */
- static boolean isDesktopModeSupported() {
- // Check for aconfig flag first
- if (ENABLE_DESKTOP_WINDOWING) {
- return true;
- }
- // Fall back to sysprop flag
- // TODO(b/304778354): remove sysprop once desktop aconfig flag supports dynamic overriding
- return DESKTOP_MODE_PROTO2_SUPPORTED;
+ /** Whether desktop mode is enabled. */
+ static boolean isDesktopModeEnabled() {
+ return Flags.enableDesktopWindowingMode();
}
}
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index 76038b9..b266caa 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -216,8 +216,7 @@
mIsClosing = true;
// Unregister the input interceptor.
if (mInputInterceptor != null) {
- if (DEBUG_DRAG)
- Slog.d(TAG_WM, "unregistering drag input channel");
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Unregistering drag input channel");
// Input channel should be disposed on the thread where the input is being handled.
mDragDropController.sendHandlerMessage(
@@ -227,9 +226,7 @@
// Send drag end broadcast if drag start has been sent.
if (mDragInProgress) {
- if (DEBUG_DRAG) {
- Slog.d(TAG_WM, "broadcasting DRAG_ENDED");
- }
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Broadcasting DRAG_ENDED");
for (WindowState ws : mNotifiedWindows) {
float x = 0;
float y = 0;
@@ -248,6 +245,7 @@
x, y, mThumbOffsetX, mThumbOffsetY, null, null, null, dragSurface, null,
mDragResult);
try {
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Sending DRAG_ENDED to " + ws);
ws.mClient.dispatchDragEvent(event);
} catch (RemoteException e) {
Slog.w(TAG_WM, "Unable to drag-end window " + ws);
@@ -364,7 +362,7 @@
return false;
}
- if (DEBUG_DRAG) Slog.d(TAG_WM, "sending DROP to " + touchedWin);
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Sending DROP to " + touchedWin);
final IBinder clientToken = touchedWin.mClient.asBinder();
final DragEvent event = createDropEvent(x, y, touchedWin, false /* includePrivateInfo */);
@@ -460,7 +458,7 @@
*/
CompletableFuture<Void> register(Display display) {
display.getRealSize(mDisplaySize);
- if (DEBUG_DRAG) Slog.d(TAG_WM, "registering drag input channel");
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Registering drag input channel");
if (mInputInterceptor != null) {
Slog.e(TAG_WM, "Duplicate register of drag input channel");
return completedFuture(null);
@@ -489,7 +487,7 @@
mSourceUserId, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
if (DEBUG_DRAG) {
- Slog.d(TAG_WM, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
+ Slog.d(TAG_WM, "Broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
}
final boolean containsAppExtras = containsApplicationExtras(mDataDescription);
diff --git a/services/core/java/com/android/server/wm/LaunchParamsController.java b/services/core/java/com/android/server/wm/LaunchParamsController.java
index 91bb8d0..97b5925 100644
--- a/services/core/java/com/android/server/wm/LaunchParamsController.java
+++ b/services/core/java/com/android/server/wm/LaunchParamsController.java
@@ -64,10 +64,7 @@
void registerDefaultModifiers(ActivityTaskSupervisor supervisor) {
// {@link TaskLaunchParamsModifier} handles window layout preferences.
registerModifier(new TaskLaunchParamsModifier(supervisor));
- if (DesktopModeLaunchParamsModifier.isDesktopModeSupported()) {
- // {@link DesktopModeLaunchParamsModifier} handles default task size changes
- registerModifier(new DesktopModeLaunchParamsModifier());
- }
+ registerModifier(new DesktopModeLaunchParamsModifier());
}
/**
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 908cbd3..30134d8 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -336,19 +336,19 @@
}
@Override
- public boolean performHapticFeedback(int effectId, boolean always) {
+ public boolean performHapticFeedback(int effectId, boolean always, boolean fromIme) {
final long ident = Binder.clearCallingIdentity();
try {
return mService.mPolicy.performHapticFeedback(mUid, mPackageName,
- effectId, always, null);
+ effectId, always, null, fromIme);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
- public void performHapticFeedbackAsync(int effectId, boolean always) {
- performHapticFeedback(effectId, always);
+ public void performHapticFeedbackAsync(int effectId, boolean always, boolean fromIme) {
+ performHapticFeedback(effectId, always, fromIme);
}
/* Drag/drop */
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index c93cc07..7e061298 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -6706,7 +6706,7 @@
private void dumpLogStatus(PrintWriter pw) {
pw.println("WINDOW MANAGER LOGGING (dumpsys window logging)");
- if (android.tracing.Flags.perfettoProtolog()) {
+ if (android.tracing.Flags.perfettoProtologTracing()) {
pw.println("Deprecated legacy command. Use Perfetto commands instead.");
return;
}
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index a7a28c2..18ac0e7 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -2041,6 +2041,13 @@
if (!isVisible()) {
return;
}
+ final WallpaperWindowToken wallpaperToken = mToken.asWallpaperToken();
+ if (wallpaperToken != null) {
+ if (wallpaperToken.hasVisibleNotDrawnWallpaper()) {
+ outWaitingForDrawn.add(this);
+ }
+ return;
+ }
if (mActivityRecord != null) {
if (!mActivityRecord.isVisibleRequested()) return;
if (mActivityRecord.allDrawn) {
diff --git a/services/core/java/com/android/server/wm/WindowTracing.java b/services/core/java/com/android/server/wm/WindowTracing.java
index 424d504..6d5fc80 100644
--- a/services/core/java/com/android/server/wm/WindowTracing.java
+++ b/services/core/java/com/android/server/wm/WindowTracing.java
@@ -155,13 +155,13 @@
logAndPrintln(pw, "Stop tracing to " + mTraceFile + ". Waiting for traces to flush.");
writeTraceToFileLocked();
logAndPrintln(pw, "Trace written to " + mTraceFile + ".");
- if (!android.tracing.Flags.perfettoProtolog()) {
+ if (!android.tracing.Flags.perfettoProtologTracing()) {
((LegacyProtoLogImpl) mProtoLog).stopProtoLog(pw, true);
}
logAndPrintln(pw, "Start tracing to " + mTraceFile + ".");
mBuffer.resetBuffer();
mEnabled = mEnabledLockFree = true;
- if (!android.tracing.Flags.perfettoProtolog()) {
+ if (!android.tracing.Flags.perfettoProtologTracing()) {
((LegacyProtoLogImpl) mProtoLog).startProtoLog(pw);
}
}
diff --git a/services/permission/java/com/android/server/permission/access/permission/PermissionFlags.kt b/services/permission/java/com/android/server/permission/access/permission/PermissionFlags.kt
index b9d89c2..28889de 100644
--- a/services/permission/java/com/android/server/permission/access/permission/PermissionFlags.kt
+++ b/services/permission/java/com/android/server/permission/access/permission/PermissionFlags.kt
@@ -347,7 +347,8 @@
}
fun isAppOpGranted(flags: Int): Boolean =
- isPermissionGranted(flags) && !flags.hasBits(APP_OP_REVOKED)
+ isPermissionGranted(flags) && !flags.hasBits(RESTRICTION_REVOKED) &&
+ !flags.hasBits(APP_OP_REVOKED)
fun toApiFlags(flags: Int): Int {
var apiFlags = 0
diff --git a/services/tests/VpnTests/Android.bp b/services/tests/VpnTests/Android.bp
new file mode 100644
index 0000000..6ad27fc
--- /dev/null
+++ b/services/tests/VpnTests/Android.bp
@@ -0,0 +1,22 @@
+//########################################################################
+// Build FrameworksVpnTests package
+//########################################################################
+package {
+ default_team: "trendy_team_fwk_core_networking",
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "Android-Apache-2.0"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+ name: "FrameworksVpnTests",
+ srcs: [
+ "java/**/*.java",
+ "java/**/*.kt",
+ ],
+
+ test_suites: ["device-tests"],
+}
diff --git a/services/tests/VpnTests/AndroidManifest.xml b/services/tests/VpnTests/AndroidManifest.xml
new file mode 100644
index 0000000..d884084
--- /dev/null
+++ b/services/tests/VpnTests/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.frameworks.tests.vpn">
+ <application>
+ <uses-library android:name="android.test.runner" />
+ </application>
+
+ <instrumentation
+ android:name="androidx.test.runner.AndroidJUnitRunner"
+ android:targetPackage="com.android.frameworks.tests.vpn"
+ android:label="Frameworks VPN Tests" />
+</manifest>
\ No newline at end of file
diff --git a/services/tests/VpnTests/AndroidTest.xml b/services/tests/VpnTests/AndroidTest.xml
new file mode 100644
index 0000000..ebeeac7
--- /dev/null
+++ b/services/tests/VpnTests/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?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.
+ -->
+<configuration description="Runs VPN Tests.">
+ <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
+ <option name="test-file-name" value="FrameworksVpnTests.apk" />
+ </target_preparer>
+
+ <option name="test-tag" value="FrameworksVpnTests" />
+ <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+ <option name="package" value="com.android.frameworks.tests.vpn" />
+ <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+ <option name="hidden-api-checks" value="false"/>
+ </test>
+</configuration>
\ No newline at end of file
diff --git a/services/tests/VpnTests/OWNERS b/services/tests/VpnTests/OWNERS
new file mode 100644
index 0000000..45ea251
--- /dev/null
+++ b/services/tests/VpnTests/OWNERS
@@ -0,0 +1,2 @@
+set noparent
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
\ No newline at end of file
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
index acddc9d..fcee70f 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
@@ -1694,6 +1694,39 @@
/* ignoreAnimationLimits= */ anyBoolean());
}
+ @Test
+ public void testInitialDozeBrightness_AbcIsNull() {
+ when(mDisplayManagerFlagsMock.areAutoBrightnessModesEnabled()).thenReturn(true);
+ when(mDisplayManagerFlagsMock.isDisplayOffloadEnabled()).thenReturn(true);
+ Settings.System.putInt(mContext.getContentResolver(),
+ Settings.System.SCREEN_BRIGHTNESS_MODE,
+ Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.bool.config_allowAutoBrightnessWhileDozing, false);
+ mHolder = createDisplayPowerController(DISPLAY_ID, UNIQUE_ID, /* isEnabled= */ true,
+ /* isAutoBrightnessAvailable= */ false);
+ mHolder.dpc.setDisplayOffloadSession(mDisplayOffloadSession);
+ float brightness = 0.277f;
+ when(mHolder.displayPowerState.getColorFadeLevel()).thenReturn(1.0f);
+ when(mHolder.automaticBrightnessController
+ .getAutomaticScreenBrightnessBasedOnLastObservedLux(any(BrightnessEvent.class)))
+ .thenReturn(brightness);
+ when(mHolder.hbmController.getCurrentBrightnessMax())
+ .thenReturn(PowerManager.BRIGHTNESS_MAX);
+ when(mHolder.displayPowerState.getScreenState()).thenReturn(Display.STATE_DOZE);
+
+ DisplayPowerRequest dpr = new DisplayPowerRequest();
+ dpr.policy = DisplayPowerRequest.POLICY_DOZE;
+ mHolder.dpc.requestPowerState(dpr, /* waitForNegativeProximity= */ false);
+ advanceTime(1); // Run updatePowerState
+
+ // Automatic Brightness Controller is null so no initial doze brightness should be set and
+ // we should not crash
+ verify(mHolder.animator, never()).animateTo(eq(brightness),
+ /* linearSecondTarget= */ anyFloat(), /* rate= */ anyFloat(),
+ /* ignoreAnimationLimits= */ anyBoolean());
+ }
+
/**
* Creates a mock and registers it to {@link LocalServices}.
*/
@@ -1778,6 +1811,12 @@
private DisplayPowerControllerHolder createDisplayPowerController(int displayId,
String uniqueId, boolean isEnabled) {
+ return createDisplayPowerController(displayId, uniqueId, isEnabled,
+ /* isAutoBrightnessAvailable= */ true);
+ }
+
+ private DisplayPowerControllerHolder createDisplayPowerController(int displayId,
+ String uniqueId, boolean isEnabled, boolean isAutoBrightnessAvailable) {
final DisplayPowerState displayPowerState = mock(DisplayPowerState.class);
final DualRampAnimator<DisplayPowerState> animator = mock(DualRampAnimator.class);
final AutomaticBrightnessController automaticBrightnessController =
@@ -1812,6 +1851,7 @@
final DisplayDeviceConfig config = mock(DisplayDeviceConfig.class);
setUpDisplay(displayId, uniqueId, display, device, config, isEnabled);
+ when(config.isAutoBrightnessAvailable()).thenReturn(isAutoBrightnessAvailable);
final DisplayPowerController dpc = new DisplayPowerController(
mContext, injector, mDisplayPowerCallbacksMock, mHandler,
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/BrightnessEventTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/BrightnessEventTest.java
index 060f99b..397d77c 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/brightness/BrightnessEventTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/BrightnessEventTest.java
@@ -16,6 +16,8 @@
package com.android.server.display.brightness;
+import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest.POLICY_BRIGHT;
+
import static com.android.server.display.AutomaticBrightnessController.AUTO_BRIGHTNESS_MODE_IDLE;
import static org.junit.Assert.assertEquals;
@@ -43,6 +45,7 @@
getReason(BrightnessReason.REASON_DOZE, BrightnessReason.MODIFIER_LOW_POWER));
mBrightnessEvent.setPhysicalDisplayId("test");
mBrightnessEvent.setDisplayState(Display.STATE_ON);
+ mBrightnessEvent.setDisplayPolicy(POLICY_BRIGHT);
mBrightnessEvent.setLux(100.0f);
mBrightnessEvent.setPreThresholdLux(150.0f);
mBrightnessEvent.setTime(System.currentTimeMillis());
@@ -74,11 +77,12 @@
public void testToStringWorksAsExpected() {
String actualString = mBrightnessEvent.toString(false);
String expectedString =
- "BrightnessEvent: disp=1, physDisp=test, displayState=ON, brt=0.6, initBrt=25.0,"
- + " rcmdBrt=0.6, preBrt=NaN, lux=100.0, preLux=150.0, hbmMax=0.62, hbmMode=off,"
- + " rbcStrength=-1, thrmMax=0.65, powerFactor=0.2, wasShortTermModelActive=true,"
- + " flags=, reason=doze [ low_pwr ], autoBrightness=true, strategy="
- + DISPLAY_BRIGHTNESS_STRATEGY_NAME + ", autoBrightnessMode=idle";
+ "BrightnessEvent: disp=1, physDisp=test, displayState=ON, displayPolicy=BRIGHT,"
+ + " brt=0.6, initBrt=25.0, rcmdBrt=0.6, preBrt=NaN, lux=100.0, preLux=150.0,"
+ + " hbmMax=0.62, hbmMode=off, rbcStrength=-1, thrmMax=0.65, powerFactor=0.2,"
+ + " wasShortTermModelActive=true, flags=, reason=doze [ low_pwr ],"
+ + " autoBrightness=true, strategy=" + DISPLAY_BRIGHTNESS_STRATEGY_NAME
+ + ", autoBrightnessMode=idle";
assertEquals(expectedString, actualString);
}
diff --git a/services/tests/dreamservicetests/Android.bp b/services/tests/dreamservicetests/Android.bp
index 5aa5d61..86b3a6c 100644
--- a/services/tests/dreamservicetests/Android.bp
+++ b/services/tests/dreamservicetests/Android.bp
@@ -18,6 +18,11 @@
"mockito-target-minus-junit4",
"services.core",
"mockingservicestests-utils-mockito",
+ "servicestests-utils",
+ ],
+
+ defaults: [
+ "modules-utils-testable-device-config-defaults",
],
platform_apis: true,
diff --git a/services/tests/dreamservicetests/AndroidManifest.xml b/services/tests/dreamservicetests/AndroidManifest.xml
index f4b88d9..6092ef6 100644
--- a/services/tests/dreamservicetests/AndroidManifest.xml
+++ b/services/tests/dreamservicetests/AndroidManifest.xml
@@ -21,6 +21,7 @@
Insert permissions here. eg:
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
-->
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<application android:debuggable="true"
android:testOnly="true">
diff --git a/services/tests/dreamservicetests/src/com/android/server/dreams/DreamManagerServiceMockingTest.java b/services/tests/dreamservicetests/src/com/android/server/dreams/DreamManagerServiceMockingTest.java
index 32d4e75..992b853 100644
--- a/services/tests/dreamservicetests/src/com/android/server/dreams/DreamManagerServiceMockingTest.java
+++ b/services/tests/dreamservicetests/src/com/android/server/dreams/DreamManagerServiceMockingTest.java
@@ -36,13 +36,14 @@
import android.provider.Settings;
import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.FlakyTest;
-import com.android.server.LocalServices;
+import com.android.internal.util.test.LocalServiceKeeperRule;
import com.android.server.SystemService;
+import com.android.server.testutils.TestHandler;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -65,23 +66,24 @@
@Mock
private UserManager mUserManagerMock;
- private MockitoSession mMockitoSession;
+ @Rule
+ public LocalServiceKeeperRule mLocalServiceKeeperRule = new LocalServiceKeeperRule();
- private static <T> void addLocalServiceMock(Class<T> clazz, T mock) {
- LocalServices.removeServiceForTest(clazz);
- LocalServices.addService(clazz, mock);
- }
+ private TestHandler mTestHandler;
+ private MockitoSession mMockitoSession;
@Before
public void setUp() throws Exception {
+ mTestHandler = new TestHandler(/* callback= */ null);
MockitoAnnotations.initMocks(this);
-
mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
mResourcesSpy = spy(mContextSpy.getResources());
when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
- addLocalServiceMock(ActivityManagerInternal.class, mActivityManagerInternalMock);
- addLocalServiceMock(PowerManagerInternal.class, mPowerManagerInternalMock);
+ mLocalServiceKeeperRule.overrideLocalService(
+ ActivityManagerInternal.class, mActivityManagerInternalMock);
+ mLocalServiceKeeperRule.overrideLocalService(
+ PowerManagerInternal.class, mPowerManagerInternalMock);
when(mContextSpy.getSystemService(UserManager.class)).thenReturn(mUserManagerMock);
mMockitoSession = mockitoSession()
@@ -94,26 +96,20 @@
@After
public void tearDown() throws Exception {
mMockitoSession.finishMocking();
- LocalServices.removeServiceForTest(ActivityManagerInternal.class);
- LocalServices.removeServiceForTest(PowerManagerInternal.class);
}
private DreamManagerService createService() {
- return new DreamManagerService(mContextSpy);
+ return new DreamManagerService(mContextSpy, mTestHandler);
}
@Test
- @FlakyTest(bugId = 293443309)
public void testSettingsQueryUserChange() {
final DreamManagerService service = createService();
-
final SystemService.TargetUser from =
new SystemService.TargetUser(mock(UserInfo.class));
final SystemService.TargetUser to =
new SystemService.TargetUser(mock(UserInfo.class));
-
service.onUserSwitching(from, to);
-
verify(() -> Settings.Secure.getIntForUser(any(),
eq(Settings.Secure.SCREENSAVER_ENABLED),
anyInt(),
diff --git a/services/tests/servicestests/src/com/android/server/companion/utils/PackageUtilsTest.java b/services/tests/servicestests/src/com/android/server/companion/utils/PackageUtilsTest.java
index 01159b1..bcb4877 100644
--- a/services/tests/servicestests/src/com/android/server/companion/utils/PackageUtilsTest.java
+++ b/services/tests/servicestests/src/com/android/server/companion/utils/PackageUtilsTest.java
@@ -32,7 +32,6 @@
import androidx.test.platform.app.InstrumentationRegistry;
-import com.android.server.companion.PackageUtils;
import com.android.server.pm.pkg.AndroidPackage;
import org.junit.Test;
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
index e59b5ea..2ba3969 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
@@ -48,7 +48,6 @@
import android.os.storage.IStorageManager;
import android.os.storage.StorageManager;
import android.provider.Settings;
-import android.security.KeyStore;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
@@ -102,7 +101,6 @@
IActivityManager mActivityManager;
DevicePolicyManager mDevicePolicyManager;
DevicePolicyManagerInternal mDevicePolicyManagerInternal;
- KeyStore mKeyStore;
MockSyntheticPasswordManager mSpManager;
IAuthSecret mAuthSecretService;
WindowManagerInternal mMockWindowManager;
@@ -165,7 +163,6 @@
new LockSettingsServiceTestable.MockInjector(
mContext,
mStorage,
- mKeyStore,
mActivityManager,
setUpStorageManagerMock(),
mSpManager,
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
index 296d2cb..f9077c4 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
@@ -30,7 +30,6 @@
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.storage.IStorageManager;
-import android.security.KeyStore;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.service.gatekeeper.IGateKeeperService;
@@ -41,6 +40,7 @@
import com.android.server.pm.UserManagerInternal;
import java.io.FileNotFoundException;
+import java.security.KeyStore;
public class LockSettingsServiceTestable extends LockSettingsService {
private Intent mSavedFrpNotificationIntent = null;
@@ -50,7 +50,6 @@
public static class MockInjector extends LockSettingsService.Injector {
private LockSettingsStorage mLockSettingsStorage;
- private KeyStore mKeyStore;
private IActivityManager mActivityManager;
private IStorageManager mStorageManager;
private SyntheticPasswordManager mSpManager;
@@ -62,14 +61,13 @@
public boolean mIsHeadlessSystemUserMode = false;
public boolean mIsMainUserPermanentAdmin = false;
- public MockInjector(Context context, LockSettingsStorage storage, KeyStore keyStore,
- IActivityManager activityManager,
- IStorageManager storageManager, SyntheticPasswordManager spManager,
- FakeGsiService gsiService, RecoverableKeyStoreManager recoverableKeyStoreManager,
+ public MockInjector(Context context, LockSettingsStorage storage,
+ IActivityManager activityManager, IStorageManager storageManager,
+ SyntheticPasswordManager spManager, FakeGsiService gsiService,
+ RecoverableKeyStoreManager recoverableKeyStoreManager,
UserManagerInternal userManagerInternal, DeviceStateCache deviceStateCache) {
super(context);
mLockSettingsStorage = storage;
- mKeyStore = keyStore;
mActivityManager = activityManager;
mStorageManager = storageManager;
mSpManager = spManager;
@@ -110,11 +108,6 @@
}
@Override
- public KeyStore getKeyStore() {
- return mKeyStore;
- }
-
- @Override
public IStorageManager getStorageManager() {
return mStorageManager;
}
@@ -145,8 +138,7 @@
}
@Override
- public UnifiedProfilePasswordCache getUnifiedProfilePasswordCache(
- java.security.KeyStore ks) {
+ public UnifiedProfilePasswordCache getUnifiedProfilePasswordCache(KeyStore ks) {
return mock(UnifiedProfilePasswordCache.class);
}
diff --git a/services/tests/servicestests/src/com/android/server/utils/AnrTimerTest.java b/services/tests/servicestests/src/com/android/server/utils/AnrTimerTest.java
index c8bef45..076d5ca 100644
--- a/services/tests/servicestests/src/com/android/server/utils/AnrTimerTest.java
+++ b/services/tests/servicestests/src/com/android/server/utils/AnrTimerTest.java
@@ -312,10 +312,12 @@
}
/**
- * Verify the dump output.
+ * Verify the dump output. This only applies when native timers are supported.
*/
@Test
public void testDumpOutput() throws Exception {
+ if (!AnrTimer.nativeTimersSupported()) return;
+
String r1 = getDumpOutput();
assertThat(r1).doesNotContain("timer:");
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java b/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
index 3d0dca0..e3d4596 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
@@ -17,9 +17,11 @@
package com.android.server.vibrator;
import static android.os.VibrationAttributes.CATEGORY_KEYBOARD;
+import static android.os.VibrationAttributes.CATEGORY_UNKNOWN;
import static android.os.VibrationAttributes.FLAG_BYPASS_INTERRUPTION_POLICY;
import static android.os.VibrationAttributes.FLAG_BYPASS_USER_VIBRATION_INTENSITY_OFF;
import static android.os.VibrationAttributes.FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE;
+import static android.os.VibrationAttributes.USAGE_TOUCH;
import static android.os.VibrationEffect.Composition.PRIMITIVE_CLICK;
import static android.os.VibrationEffect.Composition.PRIMITIVE_TICK;
import static android.os.VibrationEffect.EFFECT_CLICK;
@@ -285,7 +287,8 @@
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- SAFE_MODE_ENABLED, /* bypassVibrationIntensitySetting= */ false);
+ SAFE_MODE_ENABLED, /* bypassVibrationIntensitySetting= */ false,
+ false /* fromIme*/);
assertThat(attrs.isFlagSet(FLAG_BYPASS_USER_VIBRATION_INTENSITY_OFF)).isFalse();
}
@@ -295,7 +298,7 @@
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- SAFE_MODE_ENABLED, /* bypassVibrationIntensitySetting= */ true);
+ SAFE_MODE_ENABLED, /* bypassVibrationIntensitySetting= */ true, false /* fromIme*/);
assertThat(attrs.isFlagSet(FLAG_BYPASS_USER_VIBRATION_INTENSITY_OFF)).isTrue();
}
@@ -307,7 +310,7 @@
for (int effectId : SCROLL_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, false /* fromIme*/);
assertWithMessage("Expected FLAG_BYPASS_INTERRUPTION_POLICY for effect " + effectId)
.that(attrs.isFlagSet(FLAG_BYPASS_INTERRUPTION_POLICY)).isTrue();
}
@@ -320,40 +323,59 @@
for (int effectId : SCROLL_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, false /* fromIme*/);
assertWithMessage("Expected no FLAG_BYPASS_INTERRUPTION_POLICY for effect " + effectId)
.that(attrs.isFlagSet(FLAG_BYPASS_INTERRUPTION_POLICY)).isFalse();
}
}
@Test
- public void testVibrationAttribute_keyboardCategoryOff_notUseKeyboardCategory() {
+ public void testVibrationAttribute_keyboardCategoryOff_isIme_notUseKeyboardCategory() {
mSetFlagsRule.disableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, true /* fromIme*/);
+ assertWithMessage("Expected USAGE_TOUCH for effect " + effectId)
+ .that(attrs.getUsage()).isEqualTo(USAGE_TOUCH);
assertWithMessage("Expected no CATEGORY_KEYBOARD for effect " + effectId)
- .that(attrs.getCategory()).isEqualTo(0);
+ .that(attrs.getCategory()).isEqualTo(CATEGORY_UNKNOWN);
}
}
@Test
- public void testVibrationAttribute_keyboardCategoryOn_useKeyboardCategory() {
+ public void testVibrationAttribute_keyboardCategoryOn_notIme_notUseKeyboardCategory() {
mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, false /* fromIme*/);
+ assertWithMessage("Expected USAGE_TOUCH for effect " + effectId)
+ .that(attrs.getUsage()).isEqualTo(USAGE_TOUCH);
+ assertWithMessage("Expected CATEGORY_KEYBOARD for effect " + effectId)
+ .that(attrs.getCategory()).isEqualTo(CATEGORY_UNKNOWN);
+ }
+ }
+
+ @Test
+ public void testVibrationAttribute_keyboardCategoryOn_isIme_useKeyboardCategory() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
+ HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
+
+ for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
+ VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
+ effectId, /* bypassVibrationIntensitySetting= */ false, true /* fromIme*/);
+ assertWithMessage("Expected USAGE_TOUCH for effect " + effectId)
+ .that(attrs.getUsage()).isEqualTo(USAGE_TOUCH);
assertWithMessage("Expected CATEGORY_KEYBOARD for effect " + effectId)
.that(attrs.getCategory()).isEqualTo(CATEGORY_KEYBOARD);
}
}
@Test
- public void testVibrationAttribute_noFixAmplitude_keyboardCategoryOn_noBypassIntensityScale() {
+ public void testVibrationAttribute_noFixAmplitude_notBypassIntensityScale() {
mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
mockVibratorPrimitiveSupport(PRIMITIVE_CLICK, PRIMITIVE_TICK);
mockKeyboardVibrationFixedAmplitude(-1);
@@ -361,7 +383,7 @@
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, true /* fromIme*/);
assertWithMessage("Expected no FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE for effect "
+ effectId)
.that(attrs.isFlagSet(FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE)).isFalse();
@@ -369,7 +391,7 @@
}
@Test
- public void testVibrationAttribute_fixAmplitude_keyboardCategoryOn_bypassIntensityScale() {
+ public void testVibrationAttribute_notIme_notBypassIntensityScale() {
mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
mockVibratorPrimitiveSupport(PRIMITIVE_CLICK, PRIMITIVE_TICK);
mockKeyboardVibrationFixedAmplitude(KEYBOARD_VIBRATION_FIXED_AMPLITUDE);
@@ -377,7 +399,23 @@
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* bypassVibrationIntensitySetting= */ false);
+ effectId, /* bypassVibrationIntensitySetting= */ false, false /* fromIme*/);
+ assertWithMessage("Expected no FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE for effect "
+ + effectId)
+ .that(attrs.isFlagSet(FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE)).isFalse();
+ }
+ }
+
+ @Test
+ public void testVibrationAttribute_fixAmplitude_isIme_bypassIntensityScale() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
+ mockVibratorPrimitiveSupport(PRIMITIVE_CLICK, PRIMITIVE_TICK);
+ mockKeyboardVibrationFixedAmplitude(KEYBOARD_VIBRATION_FIXED_AMPLITUDE);
+ HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
+
+ for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
+ VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
+ effectId, /* bypassVibrationIntensitySetting= */ false, true /* fromIme*/);
assertWithMessage("Expected FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE for effect "
+ effectId)
.that(attrs.isFlagSet(FLAG_BYPASS_USER_VIBRATION_INTENSITY_SCALE)).isTrue();
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/VibratorManagerServiceTest.java b/services/tests/vibrator/src/com/android/server/vibrator/VibratorManagerServiceTest.java
index d2ad61f..1ea90f5 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/VibratorManagerServiceTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/VibratorManagerServiceTest.java
@@ -2526,7 +2526,7 @@
int constant, boolean always) throws InterruptedException {
HalVibration vib =
service.performHapticFeedbackInternal(UID, Context.DEVICE_ID_DEFAULT, PACKAGE_NAME,
- constant, always, "some reason", service);
+ constant, always, "some reason", service, false /* fromIme */);
if (vib != null) {
vib.waitForEnd();
}
diff --git a/services/tests/wmtests/src/com/android/server/policy/ShortcutLoggingTests.java b/services/tests/wmtests/src/com/android/server/policy/ShortcutLoggingTests.java
index e904eae..0a29dfb 100644
--- a/services/tests/wmtests/src/com/android/server/policy/ShortcutLoggingTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/ShortcutLoggingTests.java
@@ -145,7 +145,7 @@
KeyboardLogEvent.SYSTEM_MUTE, KeyEvent.KEYCODE_MUTE, 0},
{"Meta + Ctrl + DPAD_UP -> Split screen navigation",
new int[]{META_KEY, CTRL_KEY, KeyEvent.KEYCODE_DPAD_UP},
- KeyboardLogEvent.SPLIT_SCREEN_NAVIGATION, KeyEvent.KEYCODE_DPAD_UP,
+ KeyboardLogEvent.MULTI_WINDOW_NAVIGATION, KeyEvent.KEYCODE_DPAD_UP,
META_ON | CTRL_ON},
{"Meta + Ctrl + DPAD_LEFT -> Split screen navigation",
new int[]{META_KEY, CTRL_KEY, KeyEvent.KEYCODE_DPAD_LEFT},
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 67c528c..09e7b91 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -527,7 +527,8 @@
// The configuration change is still sent to the activity, even if it doesn't relaunch.
final ActivityConfigurationChangeItem expected =
- ActivityConfigurationChangeItem.obtain(activity.token, newConfig);
+ ActivityConfigurationChangeItem.obtain(activity.token, newConfig,
+ activity.getActivityWindowInfo());
verify(mClientLifecycleManager).scheduleTransactionItem(
eq(activity.app.getThread()), eq(expected));
}
@@ -599,7 +600,8 @@
final Configuration currentConfig = activity.getConfiguration();
assertEquals(expectedOrientation, currentConfig.orientation);
final ActivityConfigurationChangeItem expected =
- ActivityConfigurationChangeItem.obtain(activity.token, currentConfig);
+ ActivityConfigurationChangeItem.obtain(activity.token, currentConfig,
+ activity.getActivityWindowInfo());
verify(mClientLifecycleManager).scheduleTransactionItem(activity.app.getThread(), expected);
verify(displayRotation).onSetRequestedOrientation();
}
@@ -818,7 +820,7 @@
final ActivityConfigurationChangeItem expected =
ActivityConfigurationChangeItem.obtain(activity.token,
- activity.getConfiguration());
+ activity.getConfiguration(), activity.getActivityWindowInfo());
verify(mClientLifecycleManager).scheduleTransactionItem(
activity.app.getThread(), expected);
} finally {
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index 6132ee3..173a1b6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -74,7 +74,6 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -86,9 +85,9 @@
import static org.mockito.ArgumentMatchers.notNull;
import android.app.ActivityOptions;
+import android.app.ActivityOptions.BackgroundActivityStartMode;
import android.app.AppOpsManager;
import android.app.BackgroundStartPrivileges;
-import android.app.ComponentOptions.BackgroundActivityStartMode;
import android.app.IApplicationThread;
import android.app.PictureInPictureParams;
import android.content.ComponentName;
diff --git a/services/tests/wmtests/src/com/android/server/wm/DesktopModeLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/DesktopModeLaunchParamsModifierTests.java
index ef36bff..4060d40 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DesktopModeLaunchParamsModifierTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DesktopModeLaunchParamsModifierTests.java
@@ -24,6 +24,7 @@
import static com.android.server.wm.DesktopModeLaunchParamsModifier.DESKTOP_MODE_INITIAL_BOUNDS_SCALE;
import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_BOUNDS;
import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_DISPLAY;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_DONE;
import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
@@ -31,11 +32,14 @@
import static org.mockito.Mockito.mock;
import android.graphics.Rect;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
import android.platform.test.annotations.Presubmit;
import androidx.test.filters.SmallTest;
import com.android.server.wm.LaunchParamsController.LaunchParamsModifier.Result;
+import com.android.window.flags.Flags;
import org.junit.Before;
import org.junit.Test;
@@ -70,11 +74,19 @@
}
@Test
+ @DisableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
+ public void testReturnsContinueIfDesktopWindowingIsDisabled() {
+ assertEquals(RESULT_CONTINUE, new CalculateRequestBuilder().setTask(null).calculate());
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsSkipIfTaskIsNull() {
assertEquals(RESULT_SKIP, new CalculateRequestBuilder().setTask(null).calculate());
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsSkipIfNotBoundsPhase() {
final Task task = new TaskBuilder(mSupervisor).build();
assertEquals(RESULT_SKIP, new CalculateRequestBuilder().setTask(task).setPhase(
@@ -82,6 +94,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsSkipIfTaskNotUsingActivityTypeStandardOrUndefined() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_ASSISTANT).build();
@@ -89,6 +102,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsDoneIfTaskUsingActivityTypeStandard() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_STANDARD).build();
@@ -96,6 +110,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsDoneIfTaskUsingActivityTypeUndefined() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_UNDEFINED).build();
@@ -103,6 +118,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testReturnsSkipIfCurrentParamsHasBounds() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_STANDARD).build();
@@ -111,6 +127,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testUsesDefaultBounds() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_STANDARD).build();
@@ -125,6 +142,7 @@
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE)
public void testUsesDisplayAreaAndWindowingModeFromSource() {
final Task task = new TaskBuilder(mSupervisor).setActivityType(
ACTIVITY_TYPE_STANDARD).build();
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
index 7551b165..1233686 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -265,7 +265,7 @@
@Override
public boolean performHapticFeedback(int uid, String packageName, int effectId,
- boolean always, String reason) {
+ boolean always, String reason, boolean fromIme) {
return false;
}
diff --git a/services/usb/java/com/android/server/usb/UsbService.java b/services/usb/java/com/android/server/usb/UsbService.java
index 530a39e..0f2c62d 100644
--- a/services/usb/java/com/android/server/usb/UsbService.java
+++ b/services/usb/java/com/android/server/usb/UsbService.java
@@ -53,11 +53,14 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.service.usb.UsbServiceDumpProto;
+import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Slog;
import android.util.proto.ProtoOutputStream;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.content.PackageMonitor;
+import com.android.internal.os.BackgroundThread;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
@@ -147,6 +150,7 @@
private final UsbSettingsManager mSettingsManager;
private final UsbPermissionManager mPermissionManager;
+ static final int PACKAGE_MONITOR_OPERATION_ID = 1;
/**
* The user id of the current user. There might be several profiles (with separate user ids)
* per user.
@@ -156,6 +160,10 @@
private final Object mLock = new Object();
+ // Key: USB port id
+ // Value: A set of UIDs of requesters who request disabling usb data
+ private final ArrayMap<String, ArraySet<Integer>> mUsbDisableRequesters = new ArrayMap<>();
+
/**
* @return the {@link UsbUserSettingsManager} for the given userId
*/
@@ -261,6 +269,10 @@
if (mDeviceManager != null) {
mDeviceManager.bootCompleted();
}
+ if (android.hardware.usb.flags.Flags.enableUsbDataSignalStaking()) {
+ new PackageUninstallMonitor()
+ .register(mContext, UserHandle.ALL, BackgroundThread.getHandler());
+ }
}
/** Called when a user is unlocked. */
@@ -873,6 +885,11 @@
Objects.requireNonNull(callback, "enableUsbData: callback must not be null. opId:"
+ operationId);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+
+ if (android.hardware.usb.flags.Flags.enableUsbDataSignalStaking()) {
+ if (!shouldUpdateUsbSignaling(portId, enable, Binder.getCallingUid())) return false;
+ }
+
final long ident = Binder.clearCallingIdentity();
boolean wait;
try {
@@ -892,6 +909,31 @@
return wait;
}
+ /**
+ * If enable = true, exclude UID from update list.
+ * If enable = false, include UID in update list.
+ * Return false if enable = true and the list is empty (no updates).
+ * Return true otherwise (let downstream decide on updates).
+ */
+ private boolean shouldUpdateUsbSignaling(String portId, boolean enable, int uid) {
+ synchronized (mUsbDisableRequesters) {
+ if (!mUsbDisableRequesters.containsKey(portId)) {
+ mUsbDisableRequesters.put(portId, new ArraySet<>());
+ }
+
+ ArraySet<Integer> uidsOfDisableRequesters = mUsbDisableRequesters.get(portId);
+
+ if (enable) {
+ uidsOfDisableRequesters.remove(uid);
+ // re-enable USB port (return true) if there are no other disable requesters
+ return uidsOfDisableRequesters.isEmpty();
+ } else {
+ uidsOfDisableRequesters.add(uid);
+ }
+ }
+ return true;
+ }
+
@Override
public void enableUsbDataWhileDocked(String portId, int operationId,
IUsbOperationInternal callback) {
@@ -1344,4 +1386,26 @@
private static String removeLastChar(String value) {
return value.substring(0, value.length() - 1);
}
+
+ /**
+ * Upon app removal, clear associated UIDs from the mUsbDisableRequesters list
+ * and re-enable USB data signaling if no remaining apps require USB disabling.
+ */
+ private class PackageUninstallMonitor extends PackageMonitor {
+ @Override
+ public void onUidRemoved(int uid) {
+ synchronized (mUsbDisableRequesters) {
+ for (String portId : mUsbDisableRequesters.keySet()) {
+ ArraySet<Integer> disabledUid = mUsbDisableRequesters.get(portId);
+ if (disabledUid != null) {
+ disabledUid.remove(uid);
+ if (disabledUid.isEmpty()) {
+ enableUsbData(portId, true, PACKAGE_MONITOR_OPERATION_ID,
+ new IUsbOperationInternal.Default());
+ }
+ }
+ }
+ }
+ }
+ }
}
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index aef7158..1e1dd00 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -181,10 +181,8 @@
LocalServices.getService(ActivityManagerInternal.class));
mAtmInternal = Objects.requireNonNull(
LocalServices.getService(ActivityTaskManagerInternal.class));
- mWmInternal = Objects.requireNonNull(
- LocalServices.getService(WindowManagerInternal.class));
- mDpmInternal = Objects.requireNonNull(
- LocalServices.getService(DevicePolicyManagerInternal.class));
+ mWmInternal = LocalServices.getService(WindowManagerInternal.class);
+ mDpmInternal = LocalServices.getService(DevicePolicyManagerInternal.class);
LegacyPermissionManagerInternal permissionManagerInternal = LocalServices.getService(
LegacyPermissionManagerInternal.class);
permissionManagerInternal.setVoiceInteractionPackagesProvider(
@@ -2750,11 +2748,17 @@
if (isAssistDataAllowed) {
visiblePackageNames.add(record.getComponentName().getPackageName());
}
- if (mDpmInternal.isUserOrganizationManaged(record.getUserId())) {
+ if (mDpmInternal != null
+ && mDpmInternal.isUserOrganizationManaged(record.getUserId())) {
isManagedProfileVisible = true;
}
}
- final ScreenCapture.ScreenshotHardwareBuffer shb = mWmInternal.takeAssistScreenshot();
+ final ScreenCapture.ScreenshotHardwareBuffer shb;
+ if (mWmInternal != null) {
+ shb = mWmInternal.takeAssistScreenshot();
+ } else {
+ shb = null;
+ }
final Bitmap bm = shb != null ? shb.asBitmap() : null;
// Now that everything is fetched, putting it in the launchIntent.
if (bm != null) {
diff --git a/telephony/java/android/telephony/SubscriptionInfo.java b/telephony/java/android/telephony/SubscriptionInfo.java
index 82ed340..58488d1 100644
--- a/telephony/java/android/telephony/SubscriptionInfo.java
+++ b/telephony/java/android/telephony/SubscriptionInfo.java
@@ -573,7 +573,7 @@
* Returns the number of this subscription.
*
* Starting with API level 30, returns the number of this subscription if the calling app meets
- * one of the following requirements:
+ * at least one of the following requirements:
* <ul>
* <li>If the calling app's target SDK is API level 29 or lower and the app has been granted
* the READ_PHONE_STATE permission.
@@ -584,8 +584,8 @@
* <li>If the calling app is the default SMS role holder.
* </ul>
*
- * @return the number of this subscription, or an empty string if one of these requirements is
- * not met
+ * @return the number of this subscription, or an empty string if none of the requirements
+ * are met.
* @deprecated use {@link SubscriptionManager#getPhoneNumber(int)} instead, which takes a
* {@link #getSubscriptionId() subscription ID}.
*/
diff --git a/telephony/java/android/telephony/ims/feature/MmTelFeature.java b/telephony/java/android/telephony/ims/feature/MmTelFeature.java
index 9789082..3f02ae9 100644
--- a/telephony/java/android/telephony/ims/feature/MmTelFeature.java
+++ b/telephony/java/android/telephony/ims/feature/MmTelFeature.java
@@ -549,13 +549,19 @@
public static final int CAPABILITY_TYPE_SMS = 1 << 3;
/**
- * This MmTelFeature supports Call Composer (section 2.4 of RC.20)
+ * This MmTelFeature supports Call Composer (section 2.4 of RC.20). This is the superset
+ * Call Composer, meaning that all subset types of Call Composers must be enabled when this
+ * capability is enabled
*/
public static final int CAPABILITY_TYPE_CALL_COMPOSER = 1 << 4;
/**
- * This MmTelFeature supports Business-only Call Composer
+ * This MmTelFeature supports Business-only Call Composer. This is a subset of
+ * {@code CAPABILITY_TYPE_CALL_COMPOSER} that only supports business related
+ * information for calling (e.g. information to signal if the call is a business call) in
+ * the SIP header. When enabling {@code CAPABILITY_TYPE_CALL_COMPOSER}, the
+ * {@code CAPABILITY_TYPE_CALL_COMPOSER_BUSINESS_ONLY} capability must also be enabled.
*/
@FlaggedApi(Flags.FLAG_BUSINESS_CALL_COMPOSER)
public static final int CAPABILITY_TYPE_CALL_COMPOSER_BUSINESS_ONLY = 1 << 5;
diff --git a/tests/Internal/src/com/android/internal/protolog/PerfettoDataSourceTest.java b/tests/Internal/src/com/android/internal/protolog/PerfettoDataSourceTest.java
index b9f1738..a963890 100644
--- a/tests/Internal/src/com/android/internal/protolog/PerfettoDataSourceTest.java
+++ b/tests/Internal/src/com/android/internal/protolog/PerfettoDataSourceTest.java
@@ -37,7 +37,7 @@
public class PerfettoDataSourceTest {
@Before
public void before() {
- assumeTrue(android.tracing.Flags.perfettoProtolog());
+ assumeTrue(android.tracing.Flags.perfettoProtologTracing());
}
@Test
diff --git a/tools/hoststubgen/hoststubgen/test-tiny-framework/tiny-framework-dump-test.py b/tools/hoststubgen/hoststubgen/test-tiny-framework/tiny-framework-dump-test.py
index cee29dc..1dec6ab 100755
--- a/tools/hoststubgen/hoststubgen/test-tiny-framework/tiny-framework-dump-test.py
+++ b/tools/hoststubgen/hoststubgen/test-tiny-framework/tiny-framework-dump-test.py
@@ -46,6 +46,7 @@
class TestWithGoldenOutput(unittest.TestCase):
# Test to check the generated jar files to the golden output.
+ @unittest.skip("Disabled until JDK 21 is merged and the golden files updated")
def test_compare_to_golden(self):
files = os.listdir(GOLDEN_DIR)
files.sort()
diff --git a/tools/protologtool/src/com/android/protolog/tool/Constants.kt b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
index aa3e00f..4a93de9 100644
--- a/tools/protologtool/src/com/android/protolog/tool/Constants.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
@@ -18,7 +18,7 @@
object Constants {
const val NAME = "protologtool"
- const val VERSION = "1.0.0"
+ const val VERSION = "2.0.0"
const val IS_ENABLED_METHOD = "isEnabled"
const val ENUM_VALUES_METHOD = "values"
}