Merge "Release visual indicator on snap to stable bounds" into main
diff --git a/core/api/current.txt b/core/api/current.txt
index c31928dc..1f5b8cb 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -20109,6 +20109,7 @@
public class MultiResolutionImageReader implements java.lang.AutoCloseable {
ctor public MultiResolutionImageReader(@NonNull java.util.Collection<android.hardware.camera2.params.MultiResolutionStreamInfo>, int, @IntRange(from=1) int);
+ ctor @FlaggedApi("com.android.internal.camera.flags.multiresolution_imagereader_usage_public") public MultiResolutionImageReader(@NonNull java.util.Collection<android.hardware.camera2.params.MultiResolutionStreamInfo>, int, @IntRange(from=1) int, long);
method public void close();
method protected void finalize();
method public void flush();
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 261c2ae..7ba5a4b 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -7227,6 +7227,7 @@
field @RequiresPermission(allOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.MODIFY_AUDIO_ROUTING}) public static final int USAGE_CALL_ASSISTANT = 17; // 0x11
field @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public static final int USAGE_EMERGENCY = 1000; // 0x3e8
field @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public static final int USAGE_SAFETY = 1001; // 0x3e9
+ field @FlaggedApi("android.media.audio.speaker_cleanup_usage") @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public static final int USAGE_SPEAKER_CLEANUP = 1004; // 0x3ec
field @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public static final int USAGE_VEHICLE_STATUS = 1002; // 0x3ea
}
@@ -11006,7 +11007,7 @@
public class Environment {
method @NonNull public static java.io.File getDataCePackageDirectoryForUser(@NonNull java.util.UUID, @NonNull android.os.UserHandle, @NonNull String);
method @NonNull public static java.io.File getDataDePackageDirectoryForUser(@NonNull java.util.UUID, @NonNull android.os.UserHandle, @NonNull String);
- method @FlaggedApi("android.crashrecovery.flags.enable_crashrecovery") @NonNull public static java.io.File getDataSystemDeDirectory();
+ method @FlaggedApi("android.crashrecovery.flags.enable_crashrecovery") @NonNull public static java.io.File getDataSystemDeviceProtectedDirectory();
method @NonNull public static java.util.Collection<java.io.File> getInternalMediaDirectories();
method @NonNull public static java.io.File getOdmDirectory();
method @NonNull public static java.io.File getOemDirectory();
@@ -18194,7 +18195,7 @@
method @FlaggedApi("com.android.internal.telephony.flags.oem_enabled_satellite_flag") public void onSatelliteDatagramReceived(long, @NonNull android.telephony.satellite.SatelliteDatagram, int, @NonNull java.util.function.Consumer<java.lang.Void>);
}
- @FlaggedApi("com.android.internal.telephony.flags.oem_enabled_satellite_flag") public final class SatelliteManager {
+ public final class SatelliteManager {
method @FlaggedApi("com.android.internal.telephony.flags.carrier_enabled_satellite_flag") @RequiresPermission(android.Manifest.permission.SATELLITE_COMMUNICATION) public void addAttachRestrictionForCarrier(int, int, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
method @FlaggedApi("com.android.internal.telephony.flags.oem_enabled_satellite_flag") @RequiresPermission(android.Manifest.permission.SATELLITE_COMMUNICATION) public void deprovisionService(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
method @FlaggedApi("com.android.internal.telephony.flags.carrier_enabled_satellite_flag") @NonNull @RequiresPermission(android.Manifest.permission.SATELLITE_COMMUNICATION) public java.util.Set<java.lang.Integer> getAttachRestrictionReasonsForCarrier(int);
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index ca1662e6..c6c0395 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -11831,7 +11831,7 @@
if (length <= 0) continue;
try {
- totalLength += Math.addExact(totalLength, length);
+ totalLength = Math.addExact(totalLength, length);
segments.add(sanitizeSegment(segment, backgroundColor,
defaultProgressColor));
} catch (ArithmeticException e) {
@@ -11853,7 +11853,6 @@
for (Point point : mProgressPoints) {
final int position = point.getPosition();
if (position < 0 || position > totalLength) continue;
-
points.add(sanitizePoint(point, backgroundColor, defaultProgressColor));
}
diff --git a/core/java/android/content/om/OverlayManager.java b/core/java/android/content/om/OverlayManager.java
index ed965b3..6db7dfe 100644
--- a/core/java/android/content/om/OverlayManager.java
+++ b/core/java/android/content/om/OverlayManager.java
@@ -78,7 +78,8 @@
/**
* Applications can use OverlayManager to create overlays to overlay on itself resources. The
- * overlay target is itself and the work range is only in caller application.
+ * overlay target is itself, or the Android package, and the work range is only in caller
+ * application.
*
* <p>In {@link android.content.Context#getSystemService(String)}, it crashes because of {@link
* java.lang.NullPointerException} if the parameter is OverlayManager. if the self-targeting is
@@ -401,7 +402,7 @@
}
/**
- * Get the related information of overlays for {@code targetPackageName}.
+ * Get the related information of self-targeting overlays for {@code targetPackageName}.
*
* @param targetPackageName the target package name
* @return a list of overlay information
diff --git a/core/java/android/content/om/OverlayManagerTransaction.java b/core/java/android/content/om/OverlayManagerTransaction.java
index becd0ea..87b2e93 100644
--- a/core/java/android/content/om/OverlayManagerTransaction.java
+++ b/core/java/android/content/om/OverlayManagerTransaction.java
@@ -209,6 +209,7 @@
*/
public static final class Builder {
private final List<Request> mRequests = new ArrayList<>();
+ private boolean mSelfTargeting = false;
/**
* Request that an overlay package be enabled and change its loading
@@ -246,6 +247,18 @@
}
/**
+ * Request that an overlay package be self-targeting. Self-targeting overlays enable
+ * applications to overlay on itself resources. The overlay target is itself, or the Android
+ * package, and the work range is only in caller application.
+ * @param selfTargeting whether the overlay is self-targeting, the default is false.
+ * @hide
+ */
+ public Builder setSelfTargeting(boolean selfTargeting) {
+ mSelfTargeting = selfTargeting;
+ return this;
+ }
+
+ /**
* Registers the fabricated overlay with the overlay manager so it can be enabled and
* disabled for any user.
*
@@ -286,7 +299,7 @@
*/
@NonNull
public OverlayManagerTransaction build() {
- return new OverlayManagerTransaction(mRequests, false /* selfTargeting */);
+ return new OverlayManagerTransaction(mRequests, mSelfTargeting);
}
}
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 6fd4d01..347bebd 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -75,7 +75,10 @@
private static final String TAG = "AssetManager";
private static final boolean DEBUG_REFS = false;
- private static final String FRAMEWORK_APK_PATH = getFrameworkApkPath();
+ /**
+ * @hide
+ */
+ public static final String FRAMEWORK_APK_PATH = getFrameworkApkPath();
private static final String FRAMEWORK_APK_PATH_DEVICE = "/system/framework/framework-res.apk";
private static final String FRAMEWORK_APK_PATH_RAVENWOOD = "ravenwood-data/framework-res.apk";
diff --git a/core/java/android/content/res/loader/ResourcesProvider.java b/core/java/android/content/res/loader/ResourcesProvider.java
index b097bc0..830b7e0 100644
--- a/core/java/android/content/res/loader/ResourcesProvider.java
+++ b/core/java/android/content/res/loader/ResourcesProvider.java
@@ -90,8 +90,6 @@
throws IOException {
Objects.requireNonNull(overlayInfo);
Preconditions.checkArgument(overlayInfo.isFabricated(), "Not accepted overlay");
- Preconditions.checkStringNotEmpty(
- overlayInfo.getTargetOverlayableName(), "Without overlayable name");
final String overlayName =
OverlayManagerImpl.checkOverlayNameValid(overlayInfo.getOverlayName());
final String path =
diff --git a/core/java/android/hardware/biometrics/flags.aconfig b/core/java/android/hardware/biometrics/flags.aconfig
index 52a4898..2d29900 100644
--- a/core/java/android/hardware/biometrics/flags.aconfig
+++ b/core/java/android/hardware/biometrics/flags.aconfig
@@ -54,3 +54,10 @@
description: "This flag is for API changes related to Identity Check"
bug: "373424727"
}
+
+flag {
+ name: "private_space_bp"
+ namespace: "biometrics_framework"
+ description: "Feature flag for biometric prompt improvements in private space"
+ bug: "365554098"
+}
diff --git a/core/java/android/hardware/camera2/MultiResolutionImageReader.java b/core/java/android/hardware/camera2/MultiResolutionImageReader.java
index 116928b..8ede7f3 100644
--- a/core/java/android/hardware/camera2/MultiResolutionImageReader.java
+++ b/core/java/android/hardware/camera2/MultiResolutionImageReader.java
@@ -224,9 +224,8 @@
* @see
* android.hardware.camera2.params.MultiResolutionStreamConfigurationMap
*
- * @hide
*/
- @FlaggedApi(Flags.FLAG_MULTIRESOLUTION_IMAGEREADER_USAGE_CONFIG)
+ @FlaggedApi(Flags.FLAG_MULTIRESOLUTION_IMAGEREADER_USAGE_PUBLIC)
public MultiResolutionImageReader(
@NonNull Collection<MultiResolutionStreamInfo> streams,
@Format int format,
diff --git a/core/java/android/net/vcn/flags.aconfig b/core/java/android/net/vcn/flags.aconfig
index 5b30624..1adefe5 100644
--- a/core/java/android/net/vcn/flags.aconfig
+++ b/core/java/android/net/vcn/flags.aconfig
@@ -10,8 +10,26 @@
}
flag {
+ name: "mainline_vcn_module_api"
+ namespace: "vcn"
+ description: "Expose APIs from VCN for mainline migration"
+ is_exported: true
+ bug: "376339506"
+}
+
+flag {
name: "safe_mode_timeout_config"
namespace: "vcn"
description: "Feature flag for adjustable safe mode timeout"
bug: "317406085"
+}
+
+flag {
+ name: "fix_config_garbage_collection"
+ namespace: "vcn"
+ description: "Handle race condition in subscription change"
+ bug: "370862489"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
}
\ No newline at end of file
diff --git a/core/java/android/os/ConcurrentMessageQueue/MessageQueue.java b/core/java/android/os/ConcurrentMessageQueue/MessageQueue.java
index 8eaadde..0efa02f 100644
--- a/core/java/android/os/ConcurrentMessageQueue/MessageQueue.java
+++ b/core/java/android/os/ConcurrentMessageQueue/MessageQueue.java
@@ -382,6 +382,18 @@
}
}
+ private class MatchDeliverableMessages extends MessageCompare {
+ @Override
+ public boolean compareMessage(Message m, Handler h, int what, Object object, Runnable r,
+ long when) {
+ if (m.when <= when) {
+ return true;
+ }
+ return false;
+ }
+ }
+ private final MatchDeliverableMessages mMatchDeliverableMessages =
+ new MatchDeliverableMessages();
/**
* Returns true if the looper has no pending messages which are due to be processed.
*
@@ -390,6 +402,12 @@
* @return True if the looper is idle.
*/
public boolean isIdle() {
+ final long now = SystemClock.uptimeMillis();
+
+ if (stackHasMessages(null, 0, null, null, now, mMatchDeliverableMessages, false)) {
+ return false;
+ }
+
MessageNode msgNode = null;
MessageNode asyncMsgNode = null;
@@ -405,7 +423,6 @@
} catch (NoSuchElementException e) { }
}
- final long now = SystemClock.uptimeMillis();
if ((msgNode != null && msgNode.getWhen() <= now)
|| (asyncMsgNode != null && asyncMsgNode.getWhen() <= now)) {
return false;
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 89a5e5d..69540c42 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -417,6 +417,14 @@
*/
@SystemApi
@FlaggedApi(android.crashrecovery.flags.Flags.FLAG_ENABLE_CRASHRECOVERY)
+ public static @NonNull File getDataSystemDeviceProtectedDirectory() {
+ return buildPath(getDataDirectory(), "system_de");
+ }
+
+ /** Use {@link #getDataSystemDeviceProtectedDirectory()} instead.
+ * {@hide}
+ */
+ @Deprecated
public static @NonNull File getDataSystemDeDirectory() {
return buildPath(getDataDirectory(), "system_de");
}
diff --git a/core/java/android/view/accessibility/flags/accessibility_flags.aconfig b/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
index 820a1fb..ffa819f 100644
--- a/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
+++ b/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
@@ -40,6 +40,13 @@
}
flag {
+ name: "a11y_character_in_window_api"
+ namespace: "accessibility"
+ description: "Enables new extra data key for an AccessibilityService to request character bounds in unmagnified window coordinates."
+ bug: "375429616"
+}
+
+flag {
namespace: "accessibility"
name: "allow_shortcut_chooser_on_lockscreen"
description: "Allows the a11y shortcut disambig dialog to appear on the lockscreen"
diff --git a/core/java/android/webkit/IWebViewUpdateService.aidl b/core/java/android/webkit/IWebViewUpdateService.aidl
index aeb746c..39092fe 100644
--- a/core/java/android/webkit/IWebViewUpdateService.aidl
+++ b/core/java/android/webkit/IWebViewUpdateService.aidl
@@ -72,16 +72,6 @@
PackageInfo getCurrentWebViewPackage();
/**
- * Used by Settings to determine whether multiprocess is enabled.
- */
- boolean isMultiProcessEnabled();
-
- /**
- * Used by Settings to enable/disable multiprocess.
- */
- void enableMultiProcess(boolean enable);
-
- /**
* Used by Settings to get the default WebView package.
*/
WebViewProviderInfo getDefaultWebViewPackage();
diff --git a/core/java/android/webkit/WebViewDelegate.java b/core/java/android/webkit/WebViewDelegate.java
index 4c5802c..778a51e 100644
--- a/core/java/android/webkit/WebViewDelegate.java
+++ b/core/java/android/webkit/WebViewDelegate.java
@@ -28,7 +28,6 @@
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.RecordingCanvas;
-import android.os.RemoteException;
import android.os.SystemProperties;
import android.os.Trace;
import android.util.SparseArray;
@@ -217,19 +216,7 @@
* Returns whether WebView should run in multiprocess mode.
*/
public boolean isMultiProcessEnabled() {
- if (Flags.updateServiceV2()) {
- return true;
- } else if (Flags.updateServiceIpcWrapper()) {
- // We don't want to support this method in the new wrapper because updateServiceV2 is
- // intended to ship in the same release (or sooner). It's only possible to disable it
- // with an obscure adb command, so just return true here too.
- return true;
- }
- try {
- return WebViewFactory.getUpdateService().isMultiProcessEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
+ return true;
}
/**
diff --git a/core/java/android/webkit/WebViewFactory.java b/core/java/android/webkit/WebViewFactory.java
index e10a398..de303f8 100644
--- a/core/java/android/webkit/WebViewFactory.java
+++ b/core/java/android/webkit/WebViewFactory.java
@@ -16,8 +16,6 @@
package android.webkit;
-import static android.webkit.Flags.updateServiceV2;
-
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.annotation.UptimeMillisLong;
@@ -490,7 +488,7 @@
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
- if (updateServiceV2() && !isInstalledPackage(newPackageInfo)) {
+ if (!isInstalledPackage(newPackageInfo)) {
throw new MissingWebViewPackageException(
TextUtils.formatSimple(
"Current WebView Package (%s) is not installed for the current "
@@ -498,7 +496,7 @@
newPackageInfo.packageName));
}
- if (updateServiceV2() && !isEnabledPackage(newPackageInfo)) {
+ if (!isEnabledPackage(newPackageInfo)) {
throw new MissingWebViewPackageException(
TextUtils.formatSimple(
"Current WebView Package (%s) is not enabled for the current user",
diff --git a/core/java/android/webkit/WebViewZygote.java b/core/java/android/webkit/WebViewZygote.java
index 668cd01..10d16af 100644
--- a/core/java/android/webkit/WebViewZygote.java
+++ b/core/java/android/webkit/WebViewZygote.java
@@ -16,8 +16,6 @@
package android.webkit;
-import static android.webkit.Flags.updateServiceV2;
-
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.ChildZygoteProcess;
@@ -52,13 +50,6 @@
@GuardedBy("sLock")
private static PackageInfo sPackage;
- /**
- * Flag for whether multi-process WebView is enabled. If this is {@code false}, the zygote will
- * not be started. Should be removed entirely after we remove the updateServiceV2 flag.
- */
- @GuardedBy("sLock")
- private static boolean sMultiprocessEnabled = false;
-
public static ZygoteProcess getProcess() {
synchronized (sLock) {
if (sZygote != null) return sZygote;
@@ -76,40 +67,13 @@
public static boolean isMultiprocessEnabled() {
synchronized (sLock) {
- if (updateServiceV2()) {
- return sPackage != null;
- } else {
- return sMultiprocessEnabled && sPackage != null;
- }
- }
- }
-
- public static void setMultiprocessEnabled(boolean enabled) {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "setMultiprocessEnabled shouldn't be called if update_service_v2 flag is set.");
- }
- synchronized (sLock) {
- sMultiprocessEnabled = enabled;
-
- // When multi-process is disabled, kill the zygote. When it is enabled,
- // the zygote will be started when it is first needed in getProcess().
- if (!enabled) {
- stopZygoteLocked();
- }
+ return sPackage != null;
}
}
static void onWebViewProviderChanged(PackageInfo packageInfo) {
synchronized (sLock) {
sPackage = packageInfo;
-
- // If multi-process is not enabled, then do not start the zygote service.
- // Only check sMultiprocessEnabled if updateServiceV2 is not enabled.
- if (!updateServiceV2() && !sMultiprocessEnabled) {
- return;
- }
-
stopZygoteLocked();
}
}
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 9b6311f..e6eec37 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -20,6 +20,7 @@
import static android.appwidget.flags.Flags.FLAG_REMOTE_VIEWS_PROTO;
import static android.appwidget.flags.Flags.drawDataParcel;
import static android.appwidget.flags.Flags.remoteAdapterConversion;
+import static android.util.TypedValue.TYPE_INT_COLOR_ARGB8;
import static android.util.proto.ProtoInputStream.NO_MORE_FIELDS;
import static android.view.inputmethod.Flags.FLAG_HOME_SCREEN_HANDWRITING_DELEGATOR;
@@ -54,6 +55,10 @@
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
+import android.content.om.FabricatedOverlay;
+import android.content.om.OverlayInfo;
+import android.content.om.OverlayManager;
+import android.content.om.OverlayManagerTransaction;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.ColorStateList;
@@ -79,14 +84,12 @@
import android.os.CancellationSignal;
import android.os.IBinder;
import android.os.Parcel;
-import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.Trace;
import android.os.UserHandle;
-import android.system.Os;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
@@ -128,11 +131,8 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -8552,12 +8552,8 @@
* @hide
*/
public static final class ColorResources {
- // Set of valid colors resources.
- private static final int FIRST_RESOURCE_COLOR_ID = android.R.color.system_neutral1_0;
- private static final int LAST_RESOURCE_COLOR_ID =
- android.R.color.system_error_1000;
- // Size, in bytes, of an entry in the array of colors in an ARSC file.
- private static final int ARSC_ENTRY_SIZE = 16;
+ private static final String OVERLAY_NAME = "remote_views_color_resources";
+ private static final String OVERLAY_TARGET_PACKAGE_NAME = "android";
private final ResourcesLoader mLoader;
private final SparseIntArray mColorMapping;
@@ -8591,44 +8587,6 @@
}
/**
- * Creates the compiled resources content from the asset stored in the APK.
- *
- * The asset is a compiled resource with the correct resources name and correct ids, only
- * the values are incorrect. The last value is at the very end of the file. The resources
- * are in an array, the array's entries are 16 bytes each. We use this to work out the
- * location of all the positions of the various resources.
- */
- @Nullable
- private static byte[] createCompiledResourcesContent(Context context,
- SparseIntArray colorResources) throws IOException {
- byte[] content;
- try (InputStream input = context.getResources().openRawResource(
- com.android.internal.R.raw.remote_views_color_resources)) {
- ByteArrayOutputStream rawContent = readFileContent(input);
- content = rawContent.toByteArray();
- }
- int valuesOffset =
- content.length - (LAST_RESOURCE_COLOR_ID & 0xffff) * ARSC_ENTRY_SIZE - 4;
- if (valuesOffset < 0) {
- Log.e(LOG_TAG, "ARSC file for theme colors is invalid.");
- return null;
- }
- for (int colorRes = FIRST_RESOURCE_COLOR_ID; colorRes <= LAST_RESOURCE_COLOR_ID;
- colorRes++) {
- // The last 2 bytes are the index in the color array.
- int index = colorRes & 0xffff;
- int offset = valuesOffset + index * ARSC_ENTRY_SIZE;
- int value = colorResources.get(colorRes, context.getColor(colorRes));
- // Write the 32 bit integer in little endian
- for (int b = 0; b < 4; b++) {
- content[offset + b] = (byte) (value & 0xff);
- value >>= 8;
- }
- }
- return content;
- }
-
- /**
* Adds a resource loader for theme colors to the given context.
*
* @param context Context of the view hosting the widget.
@@ -8639,31 +8597,38 @@
@Nullable
public static ColorResources create(Context context, SparseIntArray colorMapping) {
try {
- byte[] contentBytes = createCompiledResourcesContent(context, colorMapping);
- if (contentBytes == null) {
+ String owningPackage = context.getPackageName();
+ FabricatedOverlay overlay = new FabricatedOverlay.Builder(owningPackage,
+ OVERLAY_NAME, OVERLAY_TARGET_PACKAGE_NAME).build();
+
+ for (int i = 0; i < colorMapping.size(); i++) {
+ overlay.setResourceValue(
+ context.getResources().getResourceName(colorMapping.keyAt(i)),
+ TYPE_INT_COLOR_ARGB8, colorMapping.valueAt(i), null);
+ }
+ OverlayManager overlayManager = context.getSystemService(OverlayManager.class);
+ OverlayManagerTransaction.Builder transaction =
+ new OverlayManagerTransaction.Builder()
+ .registerFabricatedOverlay(overlay)
+ .setSelfTargeting(true);
+ overlayManager.commit(transaction.build());
+
+ OverlayInfo overlayInfo =
+ overlayManager.getOverlayInfosForTarget(OVERLAY_TARGET_PACKAGE_NAME)
+ .stream()
+ .filter(info -> TextUtils.equals(info.overlayName, OVERLAY_NAME)
+ && TextUtils.equals(info.packageName, owningPackage))
+ .findFirst()
+ .orElse(null);
+ if (overlayInfo == null) {
+ Log.e(LOG_TAG, "Failed to get overlay info ", new Throwable());
return null;
}
- FileDescriptor arscFile = null;
- try {
- arscFile = Os.memfd_create("remote_views_theme_colors.arsc", 0 /* flags */);
- // Note: This must not be closed through the OutputStream.
- try (OutputStream pipeWriter = new FileOutputStream(arscFile)) {
- pipeWriter.write(contentBytes);
-
- try (ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(arscFile)) {
- ResourcesLoader colorsLoader = new ResourcesLoader();
- colorsLoader.addProvider(ResourcesProvider
- .loadFromTable(pfd, null /* assetsProvider */));
- return new ColorResources(colorsLoader, colorMapping.clone());
- }
- }
- } finally {
- if (arscFile != null) {
- Os.close(arscFile);
- }
- }
- } catch (Exception ex) {
- Log.e(LOG_TAG, "Failed to setup the context for theme colors", ex);
+ ResourcesLoader colorsLoader = new ResourcesLoader();
+ colorsLoader.addProvider(ResourcesProvider.loadOverlay(overlayInfo));
+ return new ColorResources(colorsLoader, colorMapping.clone());
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "Failed to add theme color overlay into loader", e);
}
return null;
}
diff --git a/core/java/com/android/internal/content/om/OverlayConfig.java b/core/java/com/android/internal/content/om/OverlayConfig.java
index 07e178c..38593b4 100644
--- a/core/java/com/android/internal/content/om/OverlayConfig.java
+++ b/core/java/com/android/internal/content/om/OverlayConfig.java
@@ -19,6 +19,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.pm.PackagePartitions;
+import android.content.res.AssetManager;
import android.os.Build;
import android.os.Trace;
import android.util.ArrayMap;
@@ -533,7 +534,7 @@
*/
@NonNull
public String[] createImmutableFrameworkIdmapsInZygote() {
- final String targetPath = "/system/framework/framework-res.apk";
+ final String targetPath = AssetManager.FRAMEWORK_APK_PATH;
final ArrayList<String> idmapPaths = new ArrayList<>();
final ArrayList<IdmapInvocation> idmapInvocations =
getImmutableFrameworkOverlayIdmapInvocations();
diff --git a/core/java/com/android/internal/content/om/OverlayManagerImpl.java b/core/java/com/android/internal/content/om/OverlayManagerImpl.java
index c462449..fa5cf2a 100644
--- a/core/java/com/android/internal/content/om/OverlayManagerImpl.java
+++ b/core/java/com/android/internal/content/om/OverlayManagerImpl.java
@@ -35,6 +35,7 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.parsing.FrameworkParsingPackageUtils;
+import android.content.res.AssetManager;
import android.os.FabricatedOverlayInfo;
import android.os.FabricatedOverlayInternal;
import android.os.FabricatedOverlayInternalEntry;
@@ -60,8 +61,8 @@
import java.util.Objects;
/**
- * This class provides the functionalities of registering an overlay, unregistering an overlay, and
- * getting the list of overlays information.
+ * This class provides the functionalities for managing self-targeting overlays, including
+ * registering an overlay, unregistering an overlay, and getting the list of overlays information.
*/
public class OverlayManagerImpl {
private static final String TAG = "OverlayManagerImpl";
@@ -234,14 +235,17 @@
Preconditions.checkArgument(!entryList.isEmpty(), "overlay entries shouldn't be empty");
final String overlayName = checkOverlayNameValid(overlayInternal.overlayName);
checkPackageName(overlayInternal.packageName);
- checkPackageName(overlayInternal.targetPackageName);
- Preconditions.checkStringNotEmpty(
- overlayInternal.targetOverlayable,
- "Target overlayable should be neither null nor empty string.");
+ Preconditions.checkStringNotEmpty(overlayInternal.targetPackageName);
final ApplicationInfo applicationInfo = mContext.getApplicationInfo();
- final String targetPackage = Preconditions.checkStringNotEmpty(
- applicationInfo.getBaseCodePath());
+ String targetPackage = null;
+ if (TextUtils.equals(overlayInternal.targetPackageName, "android")) {
+ targetPackage = AssetManager.FRAMEWORK_APK_PATH;
+ } else {
+ targetPackage = Preconditions.checkStringNotEmpty(
+ applicationInfo.getBaseCodePath());
+ }
+
final Path frroPath = mBasePath.resolve(overlayName + FRRO_EXTENSION);
final Path idmapPath = mBasePath.resolve(overlayName + IDMAP_EXTENSION);
diff --git a/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java b/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
index 032ac42..c182b4a 100644
--- a/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
+++ b/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
@@ -421,6 +421,8 @@
@NonNull
private String[] mUsesStaticLibrariesSorted;
+ private Map<String, Boolean> mFeatureFlagState = new ArrayMap<>();
+
@NonNull
public static PackageImpl forParsing(@NonNull String packageName, @NonNull String baseCodePath,
@NonNull String codePath, @NonNull TypedArray manifestArray, boolean isCoreApp,
@@ -2819,6 +2821,7 @@
queriesProviders = Collections.unmodifiableSet(queriesProviders);
mimeGroups = Collections.unmodifiableSet(mimeGroups);
mKnownActivityEmbeddingCerts = Collections.unmodifiableSet(mKnownActivityEmbeddingCerts);
+ mFeatureFlagState = Collections.unmodifiableMap(mFeatureFlagState);
}
@Override
@@ -3118,6 +3121,8 @@
@Override
public void writeToParcel(Parcel dest, int flags) {
+ writeFeatureFlagState(dest);
+
sForBoolean.parcel(this.supportsSmallScreens, dest, flags);
sForBoolean.parcel(this.supportsNormalScreens, dest, flags);
sForBoolean.parcel(this.supportsLargeScreens, dest, flags);
@@ -3267,6 +3272,27 @@
dest.writeBoolean(this.mAllowCrossUidActivitySwitchFromBelow);
}
+ private void writeFeatureFlagState(@NonNull Parcel dest) {
+ // Use a string array to encode flag state. One string per flag in the form `<flag>=<value>`
+ // where value is 0 (disabled), 1 (enabled) or ? (unknown flag or value).
+ int featureFlagCount = this.mFeatureFlagState.size();
+ String[] featureFlagStateAsArray = new String[featureFlagCount];
+ var entryIterator = this.mFeatureFlagState.entrySet().iterator();
+ for (int i = 0; i < featureFlagCount; i++) {
+ var entry = entryIterator.next();
+ Boolean flagValue = entry.getValue();
+ if (flagValue == null) {
+ featureFlagStateAsArray[i] = entry.getKey() + "=?";
+ } else if (flagValue.booleanValue()) {
+ featureFlagStateAsArray[i] = entry.getKey() + "=1";
+ } else {
+ featureFlagStateAsArray[i] = entry.getKey() + "=0";
+ }
+
+ }
+ dest.writeStringArray(featureFlagStateAsArray);
+ }
+
public PackageImpl(Parcel in) {
this(in, /* callback */ null);
}
@@ -3275,6 +3301,9 @@
mCallback = callback;
// We use the boot classloader for all classes that we load.
final ClassLoader boot = Object.class.getClassLoader();
+
+ readFeatureFlagState(in);
+
this.supportsSmallScreens = sForBoolean.unparcel(in);
this.supportsNormalScreens = sForBoolean.unparcel(in);
this.supportsLargeScreens = sForBoolean.unparcel(in);
@@ -3440,6 +3469,27 @@
// to mutate this instance before it's finalized.
}
+ private void readFeatureFlagState(@NonNull Parcel in) {
+ // See comment in writeFeatureFlagState() for encoding of flag state.
+ String[] featureFlagStateAsArray = in.createStringArray();
+ for (String s : featureFlagStateAsArray) {
+ int sepIndex = s.lastIndexOf('=');
+ if (sepIndex >= 0 && sepIndex == s.length() - 2) {
+ String flagPackageAndName = s.substring(0, sepIndex);
+ char c = s.charAt(sepIndex + 1);
+ Boolean flagValue = null;
+ if (c == '1') {
+ flagValue = Boolean.TRUE;
+ } else if (c == '0') {
+ flagValue = Boolean.FALSE;
+ } else if (c != '?') {
+ continue;
+ }
+ this.mFeatureFlagState.put(flagPackageAndName, flagValue);
+ }
+ }
+ }
+
@NonNull
public static final Creator<PackageImpl> CREATOR = new Creator<PackageImpl>() {
@Override
@@ -3660,6 +3710,18 @@
return mBaseAppDataDeviceProtectedDirForSystemUser;
}
+ @Override
+ public PackageImpl addFeatureFlag(
+ @NonNull String flagPackageAndName,
+ @Nullable Boolean flagValue) {
+ mFeatureFlagState.put(flagPackageAndName, flagValue);
+ return this;
+ }
+
+ public Map<String, Boolean> getFeatureFlagState() {
+ return mFeatureFlagState;
+ }
+
/**
* Flags used for a internal bitset. These flags should never be persisted or exposed outside
* of this class. It is expected that PackageCacher explicitly clears itself whenever the
diff --git a/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java b/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java
index 8faaf95..70b7953 100644
--- a/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java
+++ b/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java
@@ -33,6 +33,7 @@
import android.util.Xml;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.pm.pkg.parsing.ParsingPackage;
import com.android.modules.utils.TypedXmlPullParser;
import org.xmlpull.v1.XmlPullParser;
@@ -199,7 +200,7 @@
* @return the current value of the given Aconfig flag, or null if there is no such flag
*/
@Nullable
- private Boolean getFlagValue(@NonNull String flagPackageAndName) {
+ public Boolean getFlagValue(@NonNull String flagPackageAndName) {
Boolean value = mFlagValues.get(flagPackageAndName);
if (DEBUG) {
Slog.v(LOG_TAG, "Aconfig flag value for " + flagPackageAndName + " = " + value);
@@ -209,10 +210,13 @@
/**
* Check if the element in {@code parser} should be skipped because of the feature flag.
+ * @param pkg The package being parsed
* @param parser XML parser object currently parsing an element
* @return true if the element is disabled because of its feature flag
*/
- public boolean skipCurrentElement(@NonNull XmlResourceParser parser) {
+ public boolean skipCurrentElement(
+ @NonNull ParsingPackage pkg,
+ @NonNull XmlResourceParser parser) {
if (!Flags.manifestFlagging()) {
return false;
}
@@ -227,18 +231,21 @@
featureFlag = featureFlag.substring(1).strip();
}
final Boolean flagValue = getFlagValue(featureFlag);
+ boolean shouldSkip = false;
if (flagValue == null) {
Slog.w(LOG_TAG, "Skipping element " + parser.getName()
+ " due to unknown feature flag " + featureFlag);
- return true;
- }
- // Skip if flag==false && attr=="flag" OR flag==true && attr=="!flag" (negated)
- if (flagValue == negated) {
+ shouldSkip = true;
+ } else if (flagValue == negated) {
+ // Skip if flag==false && attr=="flag" OR flag==true && attr=="!flag" (negated)
Slog.i(LOG_TAG, "Skipping element " + parser.getName()
+ " behind feature flag " + featureFlag + " = " + flagValue);
- return true;
+ shouldSkip = true;
}
- return false;
+ if (android.content.pm.Flags.includeFeatureFlagsInPackageCacher()) {
+ pkg.addFeatureFlag(featureFlag, flagValue);
+ }
+ return shouldSkip;
}
/**
diff --git a/core/java/com/android/internal/pm/pkg/component/ComponentParseUtils.java b/core/java/com/android/internal/pm/pkg/component/ComponentParseUtils.java
index 8858f94..335dedd 100644
--- a/core/java/com/android/internal/pm/pkg/component/ComponentParseUtils.java
+++ b/core/java/com/android/internal/pm/pkg/component/ComponentParseUtils.java
@@ -61,7 +61,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/core/java/com/android/internal/pm/pkg/component/InstallConstraintsTagParser.java b/core/java/com/android/internal/pm/pkg/component/InstallConstraintsTagParser.java
index bb01581..5f48d16 100644
--- a/core/java/com/android/internal/pm/pkg/component/InstallConstraintsTagParser.java
+++ b/core/java/com/android/internal/pm/pkg/component/InstallConstraintsTagParser.java
@@ -54,7 +54,7 @@
return input.skip("install-constraints cannot be used by this package");
}
- ParseResult<Set<String>> prefixes = parseFingerprintPrefixes(input, res, parser);
+ ParseResult<Set<String>> prefixes = parseFingerprintPrefixes(input, pkg, res, parser);
if (prefixes.isSuccess()) {
if (validateFingerprintPrefixes(prefixes.getResult())) {
return input.success(pkg);
@@ -68,7 +68,7 @@
}
private static ParseResult<Set<String>> parseFingerprintPrefixes(
- ParseInput input, Resources res, XmlResourceParser parser)
+ ParseInput input, ParsingPackage pkg, Resources res, XmlResourceParser parser)
throws XmlPullParserException, IOException {
Set<String> prefixes = new ArraySet<>();
int type;
@@ -81,7 +81,7 @@
}
return input.success(prefixes);
} else if (type == XmlPullParser.START_TAG) {
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
if (parser.getName().equals(TAG_FINGERPRINT_PREFIX)) {
diff --git a/core/java/com/android/internal/pm/pkg/component/ParsedActivityUtils.java b/core/java/com/android/internal/pm/pkg/component/ParsedActivityUtils.java
index 55baa53..a35150b 100644
--- a/core/java/com/android/internal/pm/pkg/component/ParsedActivityUtils.java
+++ b/core/java/com/android/internal/pm/pkg/component/ParsedActivityUtils.java
@@ -393,7 +393,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/core/java/com/android/internal/pm/pkg/component/ParsedIntentInfoUtils.java b/core/java/com/android/internal/pm/pkg/component/ParsedIntentInfoUtils.java
index da48b23..39d7af6 100644
--- a/core/java/com/android/internal/pm/pkg/component/ParsedIntentInfoUtils.java
+++ b/core/java/com/android/internal/pm/pkg/component/ParsedIntentInfoUtils.java
@@ -99,7 +99,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
@@ -200,7 +200,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/core/java/com/android/internal/pm/pkg/component/ParsedProviderUtils.java b/core/java/com/android/internal/pm/pkg/component/ParsedProviderUtils.java
index 6af2a29..3726b42 100644
--- a/core/java/com/android/internal/pm/pkg/component/ParsedProviderUtils.java
+++ b/core/java/com/android/internal/pm/pkg/component/ParsedProviderUtils.java
@@ -174,7 +174,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/core/java/com/android/internal/pm/pkg/component/ParsedServiceUtils.java b/core/java/com/android/internal/pm/pkg/component/ParsedServiceUtils.java
index c68ea2d..9601813 100644
--- a/core/java/com/android/internal/pm/pkg/component/ParsedServiceUtils.java
+++ b/core/java/com/android/internal/pm/pkg/component/ParsedServiceUtils.java
@@ -138,7 +138,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(parser)) {
+ if (ParsingPackageUtils.getAconfigFlags().skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
index 5d185af..341beed 100644
--- a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
+++ b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
@@ -123,6 +123,9 @@
ParsingPackage addQueriesProvider(String authority);
+ /** Adds a feature flag (`android:featureFlag` attribute) encountered in the manifest. */
+ ParsingPackage addFeatureFlag(@NonNull String flagPackageAndName, @Nullable Boolean flagValue);
+
/** Sets a process name -> {@link ParsedProcess} map coming from the <processes> tag. */
ParsingPackage setProcesses(@NonNull Map<String, ParsedProcess> processes);
diff --git a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
index 787006e..bb733f2 100644
--- a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
+++ b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
@@ -763,7 +763,7 @@
if (outerDepth + 1 < parser.getDepth() || type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
@@ -842,7 +842,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
@@ -988,7 +988,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
@@ -1610,7 +1610,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
@@ -1853,7 +1853,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
if (parser.getName().equals("intent")) {
@@ -2202,7 +2202,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
@@ -2620,7 +2620,7 @@
}
}
- ParseResult<String[]> certResult = parseAdditionalCertificates(input, res, parser);
+ ParseResult<String[]> certResult = parseAdditionalCertificates(input, pkg, res, parser);
if (certResult.isError()) {
return input.error(certResult);
}
@@ -2674,7 +2674,8 @@
// Fot apps targeting O-MR1 we require explicit enumeration of all certs.
String[] additionalCertSha256Digests = EmptyArray.STRING;
if (pkg.getTargetSdkVersion() >= Build.VERSION_CODES.O_MR1) {
- ParseResult<String[]> certResult = parseAdditionalCertificates(input, res, parser);
+ ParseResult<String[]> certResult =
+ parseAdditionalCertificates(input, pkg, res, parser);
if (certResult.isError()) {
return input.error(certResult);
}
@@ -2782,7 +2783,7 @@
}
private static ParseResult<String[]> parseAdditionalCertificates(ParseInput input,
- Resources resources, XmlResourceParser parser)
+ ParsingPackage pkg, Resources resources, XmlResourceParser parser)
throws XmlPullParserException, IOException {
String[] certSha256Digests = EmptyArray.STRING;
final int depth = parser.getDepth();
@@ -2793,7 +2794,7 @@
if (type != XmlPullParser.START_TAG) {
continue;
}
- if (sAconfigFlags.skipCurrentElement(parser)) {
+ if (sAconfigFlags.skipCurrentElement(pkg, parser)) {
continue;
}
diff --git a/services/core/java/com/android/server/FgThread.java b/core/java/com/android/server/FgThread.java
similarity index 99%
rename from services/core/java/com/android/server/FgThread.java
rename to core/java/com/android/server/FgThread.java
index b4b6e3f..f54ee5e 100644
--- a/services/core/java/com/android/server/FgThread.java
+++ b/core/java/com/android/server/FgThread.java
@@ -30,6 +30,8 @@
* relatively long-running operations like saving state to disk (in addition to
* simply being a background priority), which can cause operations scheduled on it
* to be delayed for a user-noticeable amount of time.
+ *
+ * @hide
*/
public final class FgThread extends ServiceThread {
private static final long SLOW_DISPATCH_THRESHOLD_MS = 100;
diff --git a/services/core/java/com/android/server/ServiceThread.java b/core/java/com/android/server/ServiceThread.java
similarity index 98%
rename from services/core/java/com/android/server/ServiceThread.java
rename to core/java/com/android/server/ServiceThread.java
index 6d8e49c..0eff1fc 100644
--- a/services/core/java/com/android/server/ServiceThread.java
+++ b/core/java/com/android/server/ServiceThread.java
@@ -24,6 +24,8 @@
/**
* Special handler thread that we create for system services that require their own loopers.
+ *
+ * @hide
*/
public class ServiceThread extends HandlerThread {
private static final String TAG = "ServiceThread";
diff --git a/services/core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java b/core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java
similarity index 99%
rename from services/core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java
rename to core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java
index 1526230..e8aeb86 100644
--- a/services/core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java
+++ b/core/java/com/android/server/servicewatcher/CurrentUserServiceSupplier.java
@@ -63,6 +63,8 @@
* <p>Optionally, two permissions may be specified: (1) a caller permission - any service that does
* not require callers to hold this permission is rejected (2) a service permission - any service
* whose package does not hold this permission is rejected.
+ *
+ * @hide
*/
public final class CurrentUserServiceSupplier extends BroadcastReceiver implements
ServiceSupplier<CurrentUserServiceSupplier.BoundServiceInfo> {
diff --git a/services/core/java/com/android/server/servicewatcher/OWNERS b/core/java/com/android/server/servicewatcher/OWNERS
similarity index 100%
rename from services/core/java/com/android/server/servicewatcher/OWNERS
rename to core/java/com/android/server/servicewatcher/OWNERS
diff --git a/services/core/java/com/android/server/servicewatcher/ServiceWatcher.java b/core/java/com/android/server/servicewatcher/ServiceWatcher.java
similarity index 92%
rename from services/core/java/com/android/server/servicewatcher/ServiceWatcher.java
rename to core/java/com/android/server/servicewatcher/ServiceWatcher.java
index 5636718..831ff67 100644
--- a/services/core/java/com/android/server/servicewatcher/ServiceWatcher.java
+++ b/core/java/com/android/server/servicewatcher/ServiceWatcher.java
@@ -16,6 +16,10 @@
package com.android.server.servicewatcher;
+import static android.content.Context.BIND_AUTO_CREATE;
+import static android.content.Context.BIND_NOT_FOREGROUND;
+import static android.content.Context.BIND_NOT_VISIBLE;
+
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.content.ComponentName;
@@ -52,6 +56,8 @@
* whether any particular {@link BinderOperation} will succeed. Clients must ensure they do not rely
* on this, and instead use {@link ServiceListener} notifications as necessary to recover from
* failures.
+ *
+ * @hide
*/
public interface ServiceWatcher {
@@ -144,6 +150,10 @@
protected final @Nullable String mAction;
protected final int mUid;
protected final ComponentName mComponentName;
+ private final int mFlags;
+
+ private static final int DEFAULT_FLAGS =
+ BIND_AUTO_CREATE | BIND_NOT_FOREGROUND | BIND_NOT_VISIBLE;
protected BoundServiceInfo(String action, ResolveInfo resolveInfo) {
this(action, resolveInfo.serviceInfo.applicationInfo.uid,
@@ -151,9 +161,14 @@
}
protected BoundServiceInfo(String action, int uid, ComponentName componentName) {
+ this(action, uid, componentName, DEFAULT_FLAGS);
+ }
+
+ protected BoundServiceInfo(String action, int uid, ComponentName componentName, int flags) {
mAction = action;
mUid = uid;
mComponentName = Objects.requireNonNull(componentName);
+ mFlags = flags;
}
/** Returns the action associated with this bound service. */
@@ -171,6 +186,11 @@
return UserHandle.getUserId(mUid);
}
+ /** Returns flags used when binding the service. */
+ public int getFlags() {
+ return mFlags;
+ }
+
@Override
public final boolean equals(Object o) {
if (this == o) {
@@ -183,12 +203,13 @@
BoundServiceInfo that = (BoundServiceInfo) o;
return mUid == that.mUid
&& Objects.equals(mAction, that.mAction)
- && mComponentName.equals(that.mComponentName);
+ && mComponentName.equals(that.mComponentName)
+ && mFlags == that.mFlags;
}
@Override
public final int hashCode() {
- return Objects.hash(mAction, mUid, mComponentName);
+ return Objects.hash(mAction, mUid, mComponentName, mFlags);
}
@Override
@@ -256,4 +277,4 @@
* Dumps ServiceWatcher information.
*/
void dump(PrintWriter pw);
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java b/core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java
similarity index 97%
rename from services/core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java
rename to core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java
index b178269..ccbab9f 100644
--- a/services/core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java
+++ b/core/java/com/android/server/servicewatcher/ServiceWatcherImpl.java
@@ -16,10 +16,6 @@
package com.android.server.servicewatcher;
-import static android.content.Context.BIND_AUTO_CREATE;
-import static android.content.Context.BIND_NOT_FOREGROUND;
-import static android.content.Context.BIND_NOT_VISIBLE;
-
import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
@@ -46,6 +42,8 @@
* Implementation of ServiceWatcher. Keeping the implementation separate from the interface allows
* us to store the generic relationship between the service supplier and the service listener, while
* hiding the generics from clients, simplifying the API.
+ *
+ * @hide
*/
class ServiceWatcherImpl<TBoundServiceInfo extends BoundServiceInfo> implements ServiceWatcher,
ServiceChangedListener {
@@ -212,7 +210,7 @@
mBoundServiceInfo.getComponentName());
try {
if (!mContext.bindServiceAsUser(bindIntent, this,
- BIND_AUTO_CREATE | BIND_NOT_FOREGROUND | BIND_NOT_VISIBLE,
+ mBoundServiceInfo.getFlags(),
mHandler, UserHandle.of(mBoundServiceInfo.getUserId()))) {
Log.e(TAG, "[" + mTag + "] unexpected bind failure - retrying later");
mRebinder = this::bind;
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 0d4870b..d3ef07ca 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -5337,7 +5337,9 @@
<!-- Zen mode - name of default automatic calendar time-based rule that is triggered every night (when sleeping). [CHAR LIMIT=40] -->
<string name="zen_mode_default_every_night_name">Sleeping</string>
- <!-- Zen mode - Trigger description of the rule, indicating which app owns it. [CHAR_LIMIT=100] -->
+ <!-- Implicit zen mode - Name of the rule, indicating which app owns it. [CHAR_LIMIT=30] -->
+ <string name="zen_mode_implicit_name">Do Not Disturb (<xliff:g id="app_name" example="Gmail">%1$s</xliff:g>)</string>
+ <!-- Implicit zen mode - Trigger description of the rule, indicating which app owns it. [CHAR_LIMIT=100] -->
<string name="zen_mode_implicit_trigger_description">Managed by <xliff:g id="app_name">%1$s</xliff:g></string>
<!-- Zen mode - Condition summary when a rule is activated due to a call to setInterruptionFilter(). [CHAR_LIMIT=NONE] -->
<string name="zen_mode_implicit_activated">On</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 51c405ae..b32d4cf 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2652,6 +2652,7 @@
<java-symbol type="string" name="zen_mode_default_weekends_name" />
<java-symbol type="string" name="zen_mode_default_events_name" />
<java-symbol type="string" name="zen_mode_default_every_night_name" />
+ <java-symbol type="string" name="zen_mode_implicit_name" />
<java-symbol type="string" name="zen_mode_implicit_trigger_description" />
<java-symbol type="string" name="zen_mode_implicit_activated" />
<java-symbol type="string" name="zen_mode_implicit_deactivated" />
diff --git a/core/tests/overlaytests/device_self_targeting/src/com/android/overlaytest/OverlayManagerImplTest.java b/core/tests/overlaytests/device_self_targeting/src/com/android/overlaytest/OverlayManagerImplTest.java
index 40d0bef..28d6545 100644
--- a/core/tests/overlaytests/device_self_targeting/src/com/android/overlaytest/OverlayManagerImplTest.java
+++ b/core/tests/overlaytests/device_self_targeting/src/com/android/overlaytest/OverlayManagerImplTest.java
@@ -210,21 +210,6 @@
}
@Test
- public void registerOverlay_forAndroidPackage_shouldFail() {
- FabricatedOverlayInternal overlayInternal =
- createOverlayWithName(
- mOverlayName,
- SYSTEM_APP_OVERLAYABLE,
- "android",
- List.of(Pair.create("color/white", Pair.create(null, Color.BLACK))));
-
- assertThrows(
- "Wrong target package name",
- IllegalArgumentException.class,
- () -> mOverlayManagerImpl.registerFabricatedOverlay(overlayInternal));
- }
-
- @Test
public void getOverlayInfosForTarget_defaultShouldBeZero() {
List<OverlayInfo> overlayInfos =
mOverlayManagerImpl.getOverlayInfosForTarget(mContext.getPackageName());
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
index fdb01ab..5648feb 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
@@ -294,6 +294,9 @@
taskId, isVisible, displayId)
logD("VisibleTaskCount has changed from %d to %d", prevCount, newCount)
notifyVisibleTaskListeners(displayId, newCount)
+ if (Flags.enableDesktopWindowingPersistence()) {
+ updatePersistentRepository(displayId)
+ }
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/persistence/DesktopPersistentRepository.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/persistence/DesktopPersistentRepository.kt
index 2d11e02..9e646f4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/persistence/DesktopPersistentRepository.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/persistence/DesktopPersistentRepository.kt
@@ -50,7 +50,9 @@
DataStoreFactory.create(
serializer = DesktopPersistentRepositoriesSerializer,
produceFile = { context.dataStoreFile(DESKTOP_REPOSITORIES_DATASTORE_FILE) },
- scope = bgCoroutineScope))
+ scope = bgCoroutineScope,
+ ),
+ )
/** Provides `dataStore.data` flow and handles exceptions thrown during collection */
private val dataStoreFlow: Flow<DesktopPersistentRepositories> =
@@ -116,7 +118,11 @@
val desktop =
getDesktop(currentRepository, desktopId)
.toBuilder()
- .updateTaskStates(visibleTasks, minimizedTasks)
+ .updateTaskStates(
+ visibleTasks,
+ minimizedTasks,
+ freeformTasksInZOrder,
+ )
.updateZOrder(freeformTasksInZOrder)
desktopPersistentRepositories
@@ -169,9 +175,21 @@
private fun Desktop.Builder.updateTaskStates(
visibleTasks: ArraySet<Int>,
- minimizedTasks: ArraySet<Int>
+ minimizedTasks: ArraySet<Int>,
+ freeformTasksInZOrder: ArrayList<Int>,
): Desktop.Builder {
clearTasksByTaskId()
+
+ // Handle the case where tasks are not marked as visible but are meant to be visible
+ // after reboot. E.g. User moves out of desktop when there are multiple tasks are
+ // visible, they will be marked as not visible afterwards. This ensures that they are
+ // still persisted as visible.
+ // TODO - b/350476823: Remove this logic once repository holds expanded tasks
+ if (freeformTasksInZOrder.size > visibleTasks.size + minimizedTasks.size &&
+ visibleTasks.isEmpty()
+ ) {
+ visibleTasks.addAll(freeformTasksInZOrder.filterNot { it in minimizedTasks })
+ }
putAllTasksByTaskId(
visibleTasks.associateWith {
createDesktopTask(it, state = DesktopTaskState.VISIBLE)
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/animation/PipExpandAnimator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/animation/PipExpandAnimator.java
index a93ef12..3f9b0c3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/animation/PipExpandAnimator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/animation/PipExpandAnimator.java
@@ -17,6 +17,7 @@
package com.android.wm.shell.pip2.animation;
import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
import android.animation.RectEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
@@ -27,6 +28,7 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.wm.shell.R;
import com.android.wm.shell.pip2.PipSurfaceTransactionHelper;
import com.android.wm.shell.shared.animation.Interpolators;
@@ -34,8 +36,7 @@
/**
* Animator that handles bounds animations for exit-via-expanding PIP.
*/
-public class PipExpandAnimator extends ValueAnimator
- implements ValueAnimator.AnimatorUpdateListener, ValueAnimator.AnimatorListener {
+public class PipExpandAnimator extends ValueAnimator {
@NonNull
private final SurfaceControl mLeash;
private final SurfaceControl.Transaction mStartTransaction;
@@ -58,12 +59,61 @@
// Bounds updated by the evaluator as animator is running.
private final Rect mAnimatedRect = new Rect();
- private final PipSurfaceTransactionHelper.SurfaceControlTransactionFactory
+ private PipSurfaceTransactionHelper.SurfaceControlTransactionFactory
mSurfaceControlTransactionFactory;
private final RectEvaluator mRectEvaluator;
private final RectEvaluator mInsetEvaluator;
private final PipSurfaceTransactionHelper mPipSurfaceTransactionHelper;
+ private final Animator.AnimatorListener mAnimatorListener = new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationStart(Animator animation) {
+ super.onAnimationStart(animation);
+ if (mAnimationStartCallback != null) {
+ mAnimationStartCallback.run();
+ }
+ if (mStartTransaction != null) {
+ mStartTransaction.apply();
+ }
+ }
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ super.onAnimationEnd(animation);
+ if (mFinishTransaction != null) {
+ // finishTransaction might override some state (eg. corner radii) so we want to
+ // manually set the state to the end of the animation
+ mPipSurfaceTransactionHelper.scaleAndCrop(mFinishTransaction, mLeash,
+ mSourceRectHint, mBaseBounds, mAnimatedRect, getInsets(1f),
+ false /* isInPipDirection */, 1f)
+ .round(mFinishTransaction, mLeash, false /* applyCornerRadius */)
+ .shadow(mFinishTransaction, mLeash, false /* applyCornerRadius */);
+ }
+ if (mAnimationEndCallback != null) {
+ mAnimationEndCallback.run();
+ }
+ }
+ };
+
+ private final ValueAnimator.AnimatorUpdateListener mAnimatorUpdateListener =
+ new AnimatorUpdateListener() {
+ @Override
+ public void onAnimationUpdate(@NonNull ValueAnimator animation) {
+ final SurfaceControl.Transaction tx =
+ mSurfaceControlTransactionFactory.getTransaction();
+ final float fraction = getAnimatedFraction();
+
+ // TODO (b/350801661): implement fixed rotation
+ Rect insets = getInsets(fraction);
+ mPipSurfaceTransactionHelper.scaleAndCrop(tx, mLeash, mSourceRectHint,
+ mBaseBounds, mAnimatedRect,
+ insets, false /* isInPipDirection */, fraction)
+ .round(tx, mLeash, false /* applyCornerRadius */)
+ .shadow(tx, mLeash, false /* applyCornerRadius */);
+ tx.apply();
+ }
+ };
+
public PipExpandAnimator(Context context,
@NonNull SurfaceControl leash,
SurfaceControl.Transaction startTransaction,
@@ -105,8 +155,8 @@
setObjectValues(startBounds, endBounds);
setEvaluator(mRectEvaluator);
setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
- addListener(this);
- addUpdateListener(this);
+ addListener(mAnimatorListener);
+ addUpdateListener(mAnimatorUpdateListener);
}
public void setAnimationStartCallback(@NonNull Runnable runnable) {
@@ -117,58 +167,15 @@
mAnimationEndCallback = runnable;
}
- @Override
- public void onAnimationStart(@NonNull Animator animation) {
- if (mAnimationStartCallback != null) {
- mAnimationStartCallback.run();
- }
- if (mStartTransaction != null) {
- mStartTransaction.apply();
- }
- }
-
- @Override
- public void onAnimationEnd(@NonNull Animator animation) {
- if (mFinishTransaction != null) {
- // finishTransaction might override some state (eg. corner radii) so we want to
- // manually set the state to the end of the animation
- mPipSurfaceTransactionHelper.scaleAndCrop(mFinishTransaction, mLeash, mSourceRectHint,
- mBaseBounds, mAnimatedRect, getInsets(1f),
- false /* isInPipDirection */, 1f)
- .round(mFinishTransaction, mLeash, false /* applyCornerRadius */)
- .shadow(mFinishTransaction, mLeash, false /* applyCornerRadius */);
- }
- if (mAnimationEndCallback != null) {
- mAnimationEndCallback.run();
- }
- }
-
- @Override
- public void onAnimationUpdate(@NonNull ValueAnimator animation) {
- final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
- final float fraction = getAnimatedFraction();
-
- // TODO (b/350801661): implement fixed rotation
-
- Rect insets = getInsets(fraction);
- mPipSurfaceTransactionHelper.scaleAndCrop(tx, mLeash, mSourceRectHint,
- mBaseBounds, mAnimatedRect, insets, false /* isInPipDirection */, fraction)
- .round(tx, mLeash, false /* applyCornerRadius */)
- .shadow(tx, mLeash, false /* applyCornerRadius */);
- tx.apply();
- }
-
private Rect getInsets(float fraction) {
final Rect startInsets = mSourceRectHintInsets;
final Rect endInsets = mZeroInsets;
return mInsetEvaluator.evaluate(fraction, startInsets, endInsets);
}
- // no-ops
-
- @Override
- public void onAnimationCancel(@NonNull Animator animation) {}
-
- @Override
- public void onAnimationRepeat(@NonNull Animator animation) {}
+ @VisibleForTesting
+ void setSurfaceControlTransactionFactory(
+ @NonNull PipSurfaceTransactionHelper.SurfaceControlTransactionFactory factory) {
+ mSurfaceControlTransactionFactory = factory;
+ }
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
index 38d9ab9..414c1a6 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
@@ -53,6 +53,7 @@
import org.mockito.Mockito.spy
import org.mockito.kotlin.any
import org.mockito.kotlin.never
+import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@@ -227,6 +228,33 @@
}
@Test
+ @EnableFlags(FLAG_ENABLE_DESKTOP_WINDOWING_PERSISTENCE)
+ fun updateTaskVisibility_multipleTasks_persistsVisibleTasks() =
+ runTest(StandardTestDispatcher()) {
+ repo.updateTask(DEFAULT_DISPLAY, taskId = 1, isVisible = true)
+ repo.updateTask(DEFAULT_DISPLAY, taskId = 2, isVisible = true)
+
+ inOrder(persistentRepository).run {
+ verify(persistentRepository)
+ .addOrUpdateDesktop(
+ DEFAULT_USER_ID,
+ DEFAULT_DESKTOP_ID,
+ visibleTasks = ArraySet(arrayOf(1)),
+ minimizedTasks = ArraySet(),
+ freeformTasksInZOrder = arrayListOf()
+ )
+ verify(persistentRepository)
+ .addOrUpdateDesktop(
+ DEFAULT_USER_ID,
+ DEFAULT_DESKTOP_ID,
+ visibleTasks = ArraySet(arrayOf(1, 2)),
+ minimizedTasks = ArraySet(),
+ freeformTasksInZOrder = arrayListOf()
+ )
+ }
+ }
+
+ @Test
fun isOnlyVisibleNonClosingTask_singleVisibleClosingTask() {
repo.updateTask(DEFAULT_DISPLAY, taskId = 1, isVisible = true)
repo.addClosingTask(DEFAULT_DISPLAY, 1)
@@ -614,7 +642,7 @@
minimizedTasks = ArraySet(),
freeformTasksInZOrder = arrayListOf(7, 6, 5)
)
- verify(persistentRepository)
+ verify(persistentRepository, times(2))
.addOrUpdateDesktop(
DEFAULT_USER_ID,
DEFAULT_DESKTOP_ID,
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/education/AppHandleEducationControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/education/AppHandleEducationControllerTest.kt
index 7dbadc9..5419887 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/education/AppHandleEducationControllerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/education/AppHandleEducationControllerTest.kt
@@ -68,6 +68,7 @@
@SmallTest
@RunWith(AndroidTestingRunner::class)
@OptIn(ExperimentalCoroutinesApi::class)
+@Ignore("b/374328725")
class AppHandleEducationControllerTest : ShellTestCase() {
@JvmField
@Rule
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip2/animation/PipExpandAnimatorTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip2/animation/PipExpandAnimatorTest.java
new file mode 100644
index 0000000..e19a10a
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip2/animation/PipExpandAnimatorTest.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.pip2.animation;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Matrix;
+import android.graphics.Rect;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.view.Surface;
+import android.view.SurfaceControl;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.wm.shell.pip2.PipSurfaceTransactionHelper;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Unit test against {@link PipExpandAnimator}.
+ */
+@SmallTest
+@TestableLooper.RunWithLooper
+@RunWith(AndroidTestingRunner.class)
+public class PipExpandAnimatorTest {
+
+ @Mock private Context mMockContext;
+
+ @Mock private Resources mMockResources;
+
+ @Mock private PipSurfaceTransactionHelper.SurfaceControlTransactionFactory mMockFactory;
+
+ @Mock private SurfaceControl.Transaction mMockTransaction;
+
+ @Mock private SurfaceControl.Transaction mMockStartTransaction;
+
+ @Mock private SurfaceControl.Transaction mMockFinishTransaction;
+
+ @Mock private Runnable mMockStartCallback;
+
+ @Mock private Runnable mMockEndCallback;
+
+ private PipExpandAnimator mPipExpandAnimator;
+ private Rect mBaseBounds;
+ private Rect mStartBounds;
+ private Rect mEndBounds;
+ private Rect mSourceRectHint;
+ @Surface.Rotation private int mRotation;
+ private SurfaceControl mTestLeash;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ when(mMockContext.getResources()).thenReturn(mMockResources);
+ when(mMockResources.getInteger(anyInt())).thenReturn(0);
+ when(mMockFactory.getTransaction()).thenReturn(mMockTransaction);
+ // No-op on the mMockTransaction
+ when(mMockTransaction.setAlpha(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockTransaction);
+ when(mMockTransaction.setCrop(any(SurfaceControl.class), any(Rect.class)))
+ .thenReturn(mMockTransaction);
+ when(mMockTransaction.setMatrix(any(SurfaceControl.class), any(Matrix.class), any()))
+ .thenReturn(mMockTransaction);
+ when(mMockTransaction.setCornerRadius(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockTransaction);
+ when(mMockTransaction.setShadowRadius(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockTransaction);
+ // Do the same for mMockFinishTransaction
+ when(mMockFinishTransaction.setAlpha(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockFinishTransaction);
+ when(mMockFinishTransaction.setCrop(any(SurfaceControl.class), any(Rect.class)))
+ .thenReturn(mMockFinishTransaction);
+ when(mMockFinishTransaction.setMatrix(any(SurfaceControl.class), any(Matrix.class), any()))
+ .thenReturn(mMockFinishTransaction);
+ when(mMockFinishTransaction.setCornerRadius(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockFinishTransaction);
+ when(mMockFinishTransaction.setShadowRadius(any(SurfaceControl.class), anyFloat()))
+ .thenReturn(mMockFinishTransaction);
+
+ mTestLeash = new SurfaceControl.Builder()
+ .setContainerLayer()
+ .setName("PipExpandAnimatorTest")
+ .setCallsite("PipExpandAnimatorTest")
+ .build();
+ }
+
+ @Test
+ public void setAnimationStartCallback_expand_callbackStartCallback() {
+ mRotation = Surface.ROTATION_0;
+ mBaseBounds = new Rect(0, 0, 1_000, 2_000);
+ mStartBounds = new Rect(500, 1_000, 1_000, 2_000);
+ mEndBounds = new Rect(mBaseBounds);
+ mPipExpandAnimator = new PipExpandAnimator(mMockContext, mTestLeash,
+ mMockStartTransaction, mMockFinishTransaction,
+ mBaseBounds, mStartBounds, mEndBounds, mSourceRectHint,
+ mRotation);
+ mPipExpandAnimator.setSurfaceControlTransactionFactory(mMockFactory);
+
+ mPipExpandAnimator.setAnimationStartCallback(mMockStartCallback);
+ mPipExpandAnimator.setAnimationEndCallback(mMockEndCallback);
+ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+ mPipExpandAnimator.start();
+ mPipExpandAnimator.pause();
+ });
+
+ verify(mMockStartCallback).run();
+ verifyZeroInteractions(mMockEndCallback);
+ }
+
+ @Test
+ public void setAnimationEndCallback_expand_callbackStartAndEndCallback() {
+ mRotation = Surface.ROTATION_0;
+ mBaseBounds = new Rect(0, 0, 1_000, 2_000);
+ mStartBounds = new Rect(500, 1_000, 1_000, 2_000);
+ mEndBounds = new Rect(mBaseBounds);
+ mPipExpandAnimator = new PipExpandAnimator(mMockContext, mTestLeash,
+ mMockStartTransaction, mMockFinishTransaction,
+ mBaseBounds, mStartBounds, mEndBounds, mSourceRectHint,
+ mRotation);
+ mPipExpandAnimator.setSurfaceControlTransactionFactory(mMockFactory);
+
+ mPipExpandAnimator.setAnimationStartCallback(mMockStartCallback);
+ mPipExpandAnimator.setAnimationEndCallback(mMockEndCallback);
+ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+ mPipExpandAnimator.start();
+ mPipExpandAnimator.end();
+ });
+
+ verify(mMockStartCallback).run();
+ verify(mMockEndCallback).run();
+ }
+
+ @Test
+ public void onAnimationEnd_expand_leashIsFullscreen() {
+ mRotation = Surface.ROTATION_0;
+ mBaseBounds = new Rect(0, 0, 1_000, 2_000);
+ mStartBounds = new Rect(500, 1_000, 1_000, 2_000);
+ mEndBounds = new Rect(mBaseBounds);
+ mPipExpandAnimator = new PipExpandAnimator(mMockContext, mTestLeash,
+ mMockStartTransaction, mMockFinishTransaction,
+ mBaseBounds, mStartBounds, mEndBounds, mSourceRectHint,
+ mRotation);
+ mPipExpandAnimator.setSurfaceControlTransactionFactory(mMockFactory);
+
+ mPipExpandAnimator.setAnimationStartCallback(mMockStartCallback);
+ mPipExpandAnimator.setAnimationEndCallback(mMockEndCallback);
+ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+ mPipExpandAnimator.start();
+ clearInvocations(mMockTransaction);
+ mPipExpandAnimator.end();
+ });
+
+ verify(mMockTransaction).setCrop(mTestLeash, mEndBounds);
+ verify(mMockTransaction).setCornerRadius(mTestLeash, 0f);
+ verify(mMockTransaction).setShadowRadius(mTestLeash, 0f);
+ }
+}
diff --git a/libs/androidfw/PngCrunch.cpp b/libs/androidfw/PngCrunch.cpp
index cf3c0ee..e945405 100644
--- a/libs/androidfw/PngCrunch.cpp
+++ b/libs/androidfw/PngCrunch.cpp
@@ -506,8 +506,7 @@
// Set up the write functions which write to our custom data sources.
png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr);
- // We want small files and can take the performance hit to achieve this goal.
- png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
+ png_set_compression_level(write_ptr, options.compression_level);
// Begin analysis of the image data.
// Scan the entire image and determine if:
diff --git a/libs/androidfw/include/androidfw/Png.h b/libs/androidfw/include/androidfw/Png.h
index 2ece43e..72be59b 100644
--- a/libs/androidfw/include/androidfw/Png.h
+++ b/libs/androidfw/include/androidfw/Png.h
@@ -31,6 +31,8 @@
struct PngOptions {
int grayscale_tolerance = 0;
+ // By default we want small files and can take the performance hit to achieve this goal.
+ int compression_level = 9;
};
/**
diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp
index f58dcc6..cc292d9 100644
--- a/libs/hwui/hwui/Bitmap.cpp
+++ b/libs/hwui/hwui/Bitmap.cpp
@@ -47,15 +47,16 @@
#include <SkImage.h>
#include <SkImageAndroid.h>
#include <SkImagePriv.h>
+#include <SkJpegEncoder.h>
#include <SkJpegGainmapEncoder.h>
#include <SkPixmap.h>
+#include <SkPngEncoder.h>
#include <SkRect.h>
#include <SkStream.h>
-#include <SkJpegEncoder.h>
-#include <SkPngEncoder.h>
#include <SkWebpEncoder.h>
#include <atomic>
+#include <format>
#include <limits>
#ifdef __ANDROID__
diff --git a/libs/hwui/platform/host/android/api-level.h b/libs/hwui/platform/host/android/api-level.h
deleted file mode 120000
index 4fb4784..0000000
--- a/libs/hwui/platform/host/android/api-level.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../../bionic/libc/include/android/api-level.h
\ No newline at end of file
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index 1024a55..5a8eb3a 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -16,11 +16,15 @@
package android.media;
+import static android.media.audio.Flags.FLAG_SPEAKER_CLEANUP_USAGE;
+
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
+// TODO switch from HIDL imports to AIDL
import android.audio.policy.configuration.V7_0.AudioUsage;
import android.compat.annotation.UnsupportedAppUsage;
import android.media.audiopolicy.AudioProductStrategy;
@@ -247,6 +251,16 @@
public static final int USAGE_ANNOUNCEMENT = SYSTEM_USAGE_OFFSET + 3;
/**
+ * @hide
+ * Usage value to use when a system application plays a signal intended to clean up the
+ * speaker transducers and free them of deposits of dust or water.
+ */
+ @FlaggedApi(FLAG_SPEAKER_CLEANUP_USAGE)
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+ public static final int USAGE_SPEAKER_CLEANUP = SYSTEM_USAGE_OFFSET + 4;
+
+ /**
* IMPORTANT: when adding new usage types, add them to SDK_USAGES and update SUPPRESSIBLE_USAGES
* if applicable, as well as audioattributes.proto.
* Also consider adding them to <aaudio/AAudio.h> for the NDK.
@@ -1522,6 +1536,8 @@
return "USAGE_VEHICLE_STATUS";
case USAGE_ANNOUNCEMENT:
return "USAGE_ANNOUNCEMENT";
+ case USAGE_SPEAKER_CLEANUP:
+ return "USAGE_SPEAKER_CLEANUP";
default:
return "unknown usage " + usage;
}
@@ -1662,12 +1678,8 @@
}
/**
- * @param usage one of {@link AttributeSystemUsage},
- * {@link AttributeSystemUsage#USAGE_CALL_ASSISTANT},
- * {@link AttributeSystemUsage#USAGE_EMERGENCY},
- * {@link AttributeSystemUsage#USAGE_SAFETY},
- * {@link AttributeSystemUsage#USAGE_VEHICLE_STATUS},
- * {@link AttributeSystemUsage#USAGE_ANNOUNCEMENT}
+ * Returns whether the given usage can only be used by system-privileged components
+ * @param usage one of {@link AttributeSystemUsage}.
* @return boolean indicating if the usage is a system usage or not
* @hide
*/
@@ -1677,7 +1689,8 @@
|| usage == USAGE_EMERGENCY
|| usage == USAGE_SAFETY
|| usage == USAGE_VEHICLE_STATUS
- || usage == USAGE_ANNOUNCEMENT);
+ || usage == USAGE_ANNOUNCEMENT
+ || usage == USAGE_SPEAKER_CLEANUP);
}
/**
@@ -1792,6 +1805,7 @@
case USAGE_SAFETY:
case USAGE_VEHICLE_STATUS:
case USAGE_ANNOUNCEMENT:
+ case USAGE_SPEAKER_CLEANUP:
case USAGE_UNKNOWN:
return AudioSystem.STREAM_MUSIC;
default:
@@ -1831,7 +1845,8 @@
USAGE_EMERGENCY,
USAGE_SAFETY,
USAGE_VEHICLE_STATUS,
- USAGE_ANNOUNCEMENT
+ USAGE_ANNOUNCEMENT,
+ USAGE_SPEAKER_CLEANUP
})
@Retention(RetentionPolicy.SOURCE)
public @interface AttributeSystemUsage {}
@@ -1881,6 +1896,7 @@
USAGE_SAFETY,
USAGE_VEHICLE_STATUS,
USAGE_ANNOUNCEMENT,
+ USAGE_SPEAKER_CLEANUP,
})
@Retention(RetentionPolicy.SOURCE)
public @interface AttributeUsage {}
diff --git a/native/android/libandroid.map.txt b/native/android/libandroid.map.txt
index 202535d..b025cb8 100644
--- a/native/android/libandroid.map.txt
+++ b/native/android/libandroid.map.txt
@@ -283,6 +283,7 @@
ASurfaceTransaction_setEnableBackPressure; # introduced=31
ASurfaceTransaction_setFrameRate; # introduced=30
ASurfaceTransaction_setFrameRateWithChangeStrategy; # introduced=31
+ ASurfaceTransaction_setFrameRateParams; # introduced=36
ASurfaceTransaction_clearFrameRate; # introduced=34
ASurfaceTransaction_setFrameTimeline; # introduced=Tiramisu
ASurfaceTransaction_setGeometry; # introduced=29
diff --git a/native/android/surface_control.cpp b/native/android/surface_control.cpp
index e46db6b..698bc84 100644
--- a/native/android/surface_control.cpp
+++ b/native/android/surface_control.cpp
@@ -731,6 +731,28 @@
transaction->setFrameRate(surfaceControl, frameRate, compatibility, changeFrameRateStrategy);
}
+void ASurfaceTransaction_setFrameRateParams(
+ ASurfaceTransaction* aSurfaceTransaction, ASurfaceControl* aSurfaceControl,
+ float desiredMinRate, float desiredMaxRate, float fixedSourceRate,
+ ANativeWindow_ChangeFrameRateStrategy changeFrameRateStrategy) {
+ CHECK_NOT_NULL(aSurfaceTransaction);
+ CHECK_NOT_NULL(aSurfaceControl);
+ Transaction* transaction = ASurfaceTransaction_to_Transaction(aSurfaceTransaction);
+ sp<SurfaceControl> surfaceControl = ASurfaceControl_to_SurfaceControl(aSurfaceControl);
+
+ if (desiredMaxRate < desiredMinRate) {
+ ALOGW("desiredMaxRate must be greater than or equal to desiredMinRate");
+ return;
+ }
+ // TODO(b/362798998): Fix plumbing to send modern params
+ int compatibility = fixedSourceRate == 0 ? ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT
+ : ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
+ double frameRate = compatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE
+ ? fixedSourceRate
+ : desiredMinRate;
+ transaction->setFrameRate(surfaceControl, frameRate, compatibility, changeFrameRateStrategy);
+}
+
void ASurfaceTransaction_clearFrameRate(ASurfaceTransaction* aSurfaceTransaction,
ASurfaceControl* aSurfaceControl) {
CHECK_NOT_NULL(aSurfaceTransaction);
diff --git a/packages/SettingsLib/src/com/android/settingslib/Utils.java b/packages/SettingsLib/src/com/android/settingslib/Utils.java
index 744e97e..1998d0c 100644
--- a/packages/SettingsLib/src/com/android/settingslib/Utils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/Utils.java
@@ -1,7 +1,6 @@
package com.android.settingslib;
import static android.app.admin.DevicePolicyResources.Strings.Settings.WORK_PROFILE_USER_LABEL;
-import static android.webkit.Flags.updateServiceV2;
import android.annotation.ColorInt;
import android.app.admin.DevicePolicyManager;
@@ -496,7 +495,7 @@
|| packageName.equals(sServicesSystemSharedLibPackageName)
|| packageName.equals(sSharedSystemSharedLibPackageName)
|| packageName.equals(PrintManager.PRINT_SPOOLER_PACKAGE_NAME)
- || (updateServiceV2() && packageName.equals(getDefaultWebViewPackageName(pm)))
+ || packageName.equals(getDefaultWebViewPackageName(pm))
|| isDeviceProvisioningPackage(resources, packageName);
}
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 4531b79..0537b14 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -30,6 +30,7 @@
<uses-permission android:name="android.permission.READ_WALLPAPER_INTERNAL" />
<!-- Used to read storage for all users -->
+ <uses-permission android:name="android.permission.STORAGE_INTERNAL" />
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
@@ -1137,5 +1138,11 @@
android:name="android.service.dream"
android:resource="@xml/home_controls_dream_metadata" />
</service>
+
+ <service android:name="com.android.systemui.dreams.homecontrols.system.HomeControlsRemoteService"
+ android:singleUser="true"
+ android:exported="false"
+ />
+
</application>
</manifest>
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 7921ce0..c4032c5 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -59,7 +59,7 @@
flag {
name: "notification_over_expansion_clipping_fix"
namespace: "systemui"
- description: "fix NSSL clipping when over-expanding; fixes split shade bug."
+ description: "Fix NSSL clipping when over-expanding; fixes split shade bug."
bug: "288553572"
metadata {
purpose: PURPOSE_BUGFIX
@@ -67,6 +67,14 @@
}
flag {
+ name: "notification_add_x_on_hover_to_dismiss"
+ namespace: "systemui"
+ description: "Adds an x to notifications which shows up on mouse hover, allowing the user to "
+ "dismiss a notification with mouse."
+ bug: "376297472"
+}
+
+flag {
name: "notification_async_group_header_inflation"
namespace: "systemui"
description: "Inflates the notification group summary header views from the background thread."
@@ -1615,6 +1623,16 @@
}
flag {
+ name: "home_controls_dream_hsum"
+ namespace: "systemui"
+ description: "Enables the home controls dream in HSUM"
+ bug: "370691405"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "only_show_media_stream_slider_in_single_volume_mode"
namespace: "systemui"
description: "When the device is in single volume mode, only show media stream slider and hide all other stream (e.g. call, notification, alarm, etc) sliders in volume panel"
@@ -1642,6 +1660,13 @@
}
flag {
+ name: "bouncer_ui_revamp"
+ namespace: "systemui"
+ description: "Updates to background (blur), button animations and font changes."
+ bug: "376491880"
+}
+
+flag {
name: "ensure_enr_views_visibility"
namespace: "systemui"
description: "Ensures public and private visibilities"
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/common/ui/compose/Icon.kt b/packages/SystemUI/compose/features/src/com/android/systemui/common/ui/compose/Icon.kt
index 6e83124..82d1436 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/common/ui/compose/Icon.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/common/ui/compose/Icon.kt
@@ -32,11 +32,7 @@
* Note: You can use [Color.Unspecified] to disable the tint and keep the original icon colors.
*/
@Composable
-fun Icon(
- icon: Icon,
- modifier: Modifier = Modifier,
- tint: Color = LocalContentColor.current,
-) {
+fun Icon(icon: Icon, modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) {
val contentDescription = icon.contentDescription?.load()
when (icon) {
is Icon.Loaded -> {
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/OverlayShade.kt b/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/OverlayShade.kt
index 6f1349f..9d4408a 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/OverlayShade.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/OverlayShade.kt
@@ -45,11 +45,13 @@
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalLayoutDirection
+import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.unit.dp
import com.android.compose.animation.scene.ElementKey
import com.android.compose.animation.scene.LowestZIndexContentPicker
import com.android.compose.animation.scene.SceneScope
import com.android.compose.windowsizeclass.LocalWindowSizeClass
+import com.android.systemui.res.R
/** Renders a lightweight shade UI container, as an overlay. */
@Composable
@@ -104,13 +106,11 @@
@Composable
private fun Modifier.panelSize(): Modifier {
val widthSizeClass = LocalWindowSizeClass.current.widthSizeClass
-
return this.then(
- when (widthSizeClass) {
- WindowWidthSizeClass.Compact -> Modifier.fillMaxWidth()
- WindowWidthSizeClass.Medium -> Modifier.width(OverlayShade.Dimensions.PanelWidthMedium)
- WindowWidthSizeClass.Expanded -> Modifier.width(OverlayShade.Dimensions.PanelWidthLarge)
- else -> error("Unsupported WindowWidthSizeClass \"$widthSizeClass\"")
+ if (widthSizeClass == WindowWidthSizeClass.Compact) {
+ Modifier.fillMaxWidth()
+ } else {
+ Modifier.width(dimensionResource(id = R.dimen.shade_panel_width))
}
)
}
@@ -176,8 +176,6 @@
object Dimensions {
val ScrimContentPadding = 16.dp
val PanelCornerRadius = 46.dp
- val PanelWidthMedium = 390.dp
- val PanelWidthLarge = 474.dp
val OverscrollLimit = 32.dp
}
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
index a883977..4ed8fd8 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ComposedDigitalLayerController.kt
@@ -27,7 +27,7 @@
import com.android.systemui.plugins.clocks.ClockEvents
import com.android.systemui.plugins.clocks.ClockFaceConfig
import com.android.systemui.plugins.clocks.ClockFaceEvents
-import com.android.systemui.plugins.clocks.ClockReactiveSetting
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
@@ -103,7 +103,9 @@
view.onZenDataChanged(data)
}
- override fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>) {}
+ override fun onFontAxesChanged(axes: List<ClockFontAxisSetting>) {
+ view.updateAxes(axes)
+ }
override var isReactiveTouchInteractionEnabled
get() = view.isReactiveTouchInteractionEnabled
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
index c5b7518..7014826 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
@@ -33,8 +33,8 @@
import com.android.systemui.plugins.clocks.ClockFaceConfig
import com.android.systemui.plugins.clocks.ClockFaceController
import com.android.systemui.plugins.clocks.ClockFaceEvents
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.ClockMessageBuffers
-import com.android.systemui.plugins.clocks.ClockReactiveSetting
import com.android.systemui.plugins.clocks.ClockSettings
import com.android.systemui.plugins.clocks.DefaultClockFaceLayout
import com.android.systemui.plugins.clocks.ThemeConfig
@@ -264,7 +264,7 @@
override fun onZenDataChanged(data: ZenData) {}
- override fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>) {}
+ override fun onFontAxesChanged(axes: List<ClockFontAxisSetting>) {}
}
open inner class DefaultClockAnimations(
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
index a89e6fb..d70d61c 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockProvider.kt
@@ -21,12 +21,12 @@
import com.android.systemui.log.core.LogcatOnlyMessageBuffer
import com.android.systemui.plugins.clocks.AxisType
import com.android.systemui.plugins.clocks.ClockController
+import com.android.systemui.plugins.clocks.ClockFontAxis
import com.android.systemui.plugins.clocks.ClockId
import com.android.systemui.plugins.clocks.ClockMessageBuffers
import com.android.systemui.plugins.clocks.ClockMetadata
import com.android.systemui.plugins.clocks.ClockPickerConfig
import com.android.systemui.plugins.clocks.ClockProvider
-import com.android.systemui.plugins.clocks.ClockReactiveAxis
import com.android.systemui.plugins.clocks.ClockSettings
import com.android.systemui.shared.clocks.view.HorizontalAlignment
import com.android.systemui.shared.clocks.view.VerticalAlignment
@@ -91,15 +91,42 @@
axes =
if (isClockReactiveVariantsEnabled)
listOf(
- ClockReactiveAxis(
- key = "wdth",
- type = AxisType.Slider,
- maxValue = 1000f,
- minValue = 100f,
+ ClockFontAxis(
+ key = "wght",
+ type = AxisType.Float,
+ minValue = 1f,
currentValue = 400f,
+ maxValue = 1000f,
+ name = "Weight",
+ description = "Glyph Weight",
+ ),
+ ClockFontAxis(
+ key = "wdth",
+ type = AxisType.Float,
+ minValue = 25f,
+ currentValue = 100f,
+ maxValue = 151f,
name = "Width",
description = "Glyph Width",
- )
+ ),
+ ClockFontAxis(
+ key = "ROND",
+ type = AxisType.Boolean,
+ minValue = 0f,
+ currentValue = 0f,
+ maxValue = 100f,
+ name = "Round",
+ description = "Glyph Roundness",
+ ),
+ ClockFontAxis(
+ key = "slnt",
+ type = AxisType.Boolean,
+ minValue = 0f,
+ currentValue = 0f,
+ maxValue = -10f,
+ name = "Slant",
+ description = "Glyph Slant",
+ ),
)
else listOf(),
)
@@ -121,12 +148,12 @@
FontTextStyle(
lineHeight = 147.25f,
fontVariation =
- "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100",
+ "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100, 'slnt' 0",
),
aodStyle =
FontTextStyle(
fontVariation =
- "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100",
+ "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fillColorLight = "#FFFFFFFF",
outlineColor = "#00000000",
renderType = RenderType.CHANGE_WEIGHT,
@@ -147,12 +174,12 @@
FontTextStyle(
lineHeight = 147.25f,
fontVariation =
- "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100",
+ "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100, 'slnt' 0",
),
aodStyle =
FontTextStyle(
fontVariation =
- "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100",
+ "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fillColorLight = "#FFFFFFFF",
outlineColor = "#00000000",
renderType = RenderType.CHANGE_WEIGHT,
@@ -173,12 +200,12 @@
FontTextStyle(
lineHeight = 147.25f,
fontVariation =
- "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100",
+ "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100, 'slnt' 0",
),
aodStyle =
FontTextStyle(
fontVariation =
- "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100",
+ "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fillColorLight = "#FFFFFFFF",
outlineColor = "#00000000",
renderType = RenderType.CHANGE_WEIGHT,
@@ -199,12 +226,12 @@
FontTextStyle(
lineHeight = 147.25f,
fontVariation =
- "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100",
+ "'wght' 603, 'wdth' 100, 'opsz' 144, 'ROND' 100, 'slnt' 0",
),
aodStyle =
FontTextStyle(
fontVariation =
- "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100",
+ "'wght' 74, 'wdth' 43, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fillColorLight = "#FFFFFFFF",
outlineColor = "#00000000",
renderType = RenderType.CHANGE_WEIGHT,
@@ -229,12 +256,14 @@
timespec = DigitalTimespec.TIME_FULL_FORMAT,
style =
FontTextStyle(
- fontVariation = "'wght' 600, 'wdth' 100, 'opsz' 144, 'ROND' 100",
+ fontVariation =
+ "'wght' 600, 'wdth' 100, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fontSizeScale = 0.98f,
),
aodStyle =
FontTextStyle(
- fontVariation = "'wght' 133, 'wdth' 43, 'opsz' 144, 'ROND' 100",
+ fontVariation =
+ "'wght' 133, 'wdth' 43, 'opsz' 144, 'ROND' 100, 'slnt' 0",
fillColorLight = "#FFFFFFFF",
outlineColor = "#00000000",
renderType = RenderType.CHANGE_WEIGHT,
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
index a75022a..d8fd776 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockController.kt
@@ -23,8 +23,8 @@
import com.android.systemui.plugins.clocks.ClockConfig
import com.android.systemui.plugins.clocks.ClockController
import com.android.systemui.plugins.clocks.ClockEvents
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.ClockMessageBuffers
-import com.android.systemui.plugins.clocks.ClockReactiveSetting
import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
@@ -113,9 +113,9 @@
largeClock.events.onZenDataChanged(data)
}
- override fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>) {
- smallClock.events.onReactiveAxesChanged(axes)
- largeClock.events.onReactiveAxesChanged(axes)
+ override fun onFontAxesChanged(axes: List<ClockFontAxisSetting>) {
+ smallClock.events.onFontAxesChanged(axes)
+ largeClock.events.onFontAxesChanged(axes)
}
}
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
index 8ffc00d..a4782ac 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/FlexClockFaceController.kt
@@ -32,7 +32,7 @@
import com.android.systemui.plugins.clocks.ClockFaceController
import com.android.systemui.plugins.clocks.ClockFaceEvents
import com.android.systemui.plugins.clocks.ClockFaceLayout
-import com.android.systemui.plugins.clocks.ClockReactiveSetting
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.DefaultClockFaceLayout
import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.WeatherData
@@ -136,13 +136,16 @@
override fun onFontSettingChanged(fontSizePx: Float) {
layerController.faceEvents.onFontSettingChanged(fontSizePx)
+ view.requestLayout()
}
override fun onThemeChanged(theme: ThemeConfig) {
layerController.faceEvents.onThemeChanged(theme)
}
- override fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>) {}
+ override fun onFontAxesChanged(axes: List<ClockFontAxisSetting>) {
+ layerController.events.onFontAxesChanged(axes)
+ }
/**
* targetRegion passed to all customized clock applies counter translationY of
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
index 7b1960e..143b28f 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/SimpleDigitalHandLayerController.kt
@@ -31,7 +31,7 @@
import com.android.systemui.plugins.clocks.ClockEvents
import com.android.systemui.plugins.clocks.ClockFaceConfig
import com.android.systemui.plugins.clocks.ClockFaceEvents
-import com.android.systemui.plugins.clocks.ClockReactiveSetting
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
@@ -246,7 +246,9 @@
override fun onZenDataChanged(data: ZenData) {}
- override fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>) {}
+ override fun onFontAxesChanged(axes: List<ClockFontAxisSetting>) {
+ view.updateAxes(axes)
+ }
}
override val animations =
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
index ce4d71c..b09332f 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/DigitalClockFaceView.kt
@@ -25,6 +25,7 @@
import com.android.systemui.log.core.Logger
import com.android.systemui.log.core.MessageBuffer
import com.android.systemui.plugins.clocks.AlarmData
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
import com.android.systemui.shared.clocks.LogUtil
@@ -126,6 +127,11 @@
invalidate()
}
+ fun updateAxes(axes: List<ClockFontAxisSetting>) {
+ digitalClockTextViewMap.forEach { _, view -> view.updateAxes(axes) }
+ requestLayout()
+ }
+
fun onFontSettingChanged(fontSizePx: Float) {
digitalClockTextViewMap.forEach { _, view -> view.applyTextSize(fontSizePx) }
}
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
index 25b2ad7..edcee9d 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/FlexClockView.kt
@@ -39,8 +39,7 @@
DigitalClockFaceView(context, messageBuffer) {
override var digitalClockTextViewMap = mutableMapOf<Int, SimpleDigitalClockTextView>()
val digitLeftTopMap = mutableMapOf<Int, Point>()
- var maxSingleDigitHeight = -1
- var maxSingleDigitWidth = -1
+ var maxSingleDigitSize = Point(-1, -1)
val lockscreenTranslate = Point(0, 0)
val aodTranslate = Point(0, 0)
@@ -119,25 +118,26 @@
}
protected override fun calculateSize(widthMeasureSpec: Int, heightMeasureSpec: Int): Point {
+ maxSingleDigitSize = Point(-1, -1)
digitalClockTextViewMap.forEach { (_, textView) ->
textView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
+ maxSingleDigitSize.x = max(maxSingleDigitSize.x, textView.measuredWidth)
+ maxSingleDigitSize.y = max(maxSingleDigitSize.y, textView.measuredHeight)
}
val textView = digitalClockTextViewMap[R.id.HOUR_FIRST_DIGIT]!!
- maxSingleDigitHeight = textView.measuredHeight
- maxSingleDigitWidth = textView.measuredWidth
- aodTranslate.x = -(maxSingleDigitWidth * AOD_HORIZONTAL_TRANSLATE_RATIO).toInt()
- aodTranslate.y = (maxSingleDigitHeight * AOD_VERTICAL_TRANSLATE_RATIO).toInt()
+ aodTranslate.x = -(maxSingleDigitSize.x * AOD_HORIZONTAL_TRANSLATE_RATIO).toInt()
+ aodTranslate.y = (maxSingleDigitSize.y * AOD_VERTICAL_TRANSLATE_RATIO).toInt()
return Point(
- ((maxSingleDigitWidth + abs(aodTranslate.x)) * 2),
- ((maxSingleDigitHeight + abs(aodTranslate.y)) * 2),
+ ((maxSingleDigitSize.x + abs(aodTranslate.x)) * 2),
+ ((maxSingleDigitSize.y + abs(aodTranslate.y)) * 2),
)
}
protected override fun calculateLeftTopPosition() {
digitLeftTopMap[R.id.HOUR_FIRST_DIGIT] = Point(0, 0)
- digitLeftTopMap[R.id.HOUR_SECOND_DIGIT] = Point(maxSingleDigitWidth, 0)
- digitLeftTopMap[R.id.MINUTE_FIRST_DIGIT] = Point(0, maxSingleDigitHeight)
- digitLeftTopMap[R.id.MINUTE_SECOND_DIGIT] = Point(maxSingleDigitWidth, maxSingleDigitHeight)
+ digitLeftTopMap[R.id.HOUR_SECOND_DIGIT] = Point(maxSingleDigitSize.x, 0)
+ digitLeftTopMap[R.id.MINUTE_FIRST_DIGIT] = Point(0, maxSingleDigitSize.y)
+ digitLeftTopMap[R.id.MINUTE_SECOND_DIGIT] = Point(maxSingleDigitSize)
digitLeftTopMap.forEach { _, point ->
point.x += abs(aodTranslate.x)
point.y += abs(aodTranslate.y)
@@ -162,7 +162,7 @@
override fun animateDoze(isDozing: Boolean, isAnimated: Boolean) {
dozeControlState.animateDoze = {
super.animateDoze(isDozing, isAnimated)
- if (maxSingleDigitHeight == -1) {
+ if (maxSingleDigitSize.x < 0 || maxSingleDigitSize.y < 0) {
measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
}
digitalClockTextViewMap.forEach { (id, textView) ->
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
index baed3ae..0dacce1 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockTextView.kt
@@ -41,6 +41,7 @@
import com.android.systemui.customization.R
import com.android.systemui.log.core.Logger
import com.android.systemui.log.core.MessageBuffer
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.shared.clocks.AssetLoader
import com.android.systemui.shared.clocks.ClockAnimation
import com.android.systemui.shared.clocks.DigitTranslateAnimator
@@ -140,6 +141,25 @@
invalidate()
}
+ override fun updateAxes(axes: List<ClockFontAxisSetting>) {
+ val sb = StringBuilder()
+ sb.append("'opsz' 144")
+
+ for (axis in axes) {
+ if (sb.length > 0) sb.append(", ")
+ sb.append("'${axis.key}' ${axis.value.toInt()}")
+ }
+
+ val fvar = sb.toString()
+ lockScreenPaint.typeface = typefaceCache.getTypefaceForVariant(fvar)
+ typeface = lockScreenPaint.typeface
+ textAnimator.setTextStyle(fvar = fvar, animate = true)
+ measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
+ recomputeMaxSingleDigitSizes()
+ requestLayout()
+ invalidate()
+ }
+
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
logger.d("onMeasure()")
if (isVertical) {
@@ -189,6 +209,7 @@
MeasureSpec.getMode(measuredHeight),
)
}
+
if (MeasureSpec.getMode(widthMeasureSpec) == EXACTLY) {
expectedWidth = widthMeasureSpec
} else {
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
index 30b54d8..3d2ed4a1 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/view/SimpleDigitalClockView.kt
@@ -17,6 +17,7 @@
package com.android.systemui.shared.clocks.view
import androidx.annotation.VisibleForTesting
+import com.android.systemui.plugins.clocks.ClockFontAxisSetting
import com.android.systemui.shared.clocks.AssetLoader
import com.android.systemui.shared.clocks.TextStyle
@@ -34,6 +35,8 @@
fun updateColor(color: Int)
+ fun updateAxes(axes: List<ClockFontAxisSetting>)
+
fun refreshTime()
fun animateCharge()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractorImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractorImplTest.kt
index 4856f15..e142169 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractorImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractorImplTest.kt
@@ -3,7 +3,9 @@
import android.app.admin.DevicePolicyManager
import android.app.admin.DevicePolicyResourcesManager
import android.content.pm.UserInfo
+import android.hardware.biometrics.Flags
import android.os.UserManager
+import android.platform.test.annotations.EnableFlags
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.internal.widget.LockPatternUtils
@@ -33,6 +35,7 @@
import org.mockito.junit.MockitoJUnit
private const val USER_ID = 22
+private const val OWNER_ID = 10
private const val OPERATION_ID = 100L
private const val MAX_ATTEMPTS = 5
@@ -67,7 +70,7 @@
lockPatternUtils,
userManager,
devicePolicyManager,
- systemClock
+ systemClock,
)
}
@@ -115,58 +118,87 @@
@Test fun pinCredentialWhenBadAndThrottled() = pinCredential(badCredential(timeout = 5_000))
- private fun pinCredential(result: VerifyCredentialResponse) = runTest {
- val usedAttempts = 1
- whenever(lockPatternUtils.getCurrentFailedPasswordAttempts(eq(USER_ID)))
- .thenReturn(usedAttempts)
- whenever(lockPatternUtils.verifyCredential(any(), eq(USER_ID), anyInt())).thenReturn(result)
- whenever(lockPatternUtils.verifyGatekeeperPasswordHandle(anyLong(), anyLong(), eq(USER_ID)))
- .thenReturn(result)
- whenever(lockPatternUtils.setLockoutAttemptDeadline(anyInt(), anyInt())).thenAnswer {
- systemClock.elapsedRealtime() + (it.arguments[1] as Int)
- }
+ @EnableFlags(Flags.FLAG_PRIVATE_SPACE_BP)
+ @Test
+ fun pinCredentialTiedProfileWhenGood() = pinCredential(goodCredential(), OWNER_ID)
- // wrap in an async block so the test can advance the clock if throttling credential
- // checks prevents the method from returning
- val statusList = mutableListOf<CredentialStatus>()
- interactor
- .verifyCredential(pinRequest(), LockscreenCredential.createPin("1234"))
- .toList(statusList)
+ @EnableFlags(Flags.FLAG_PRIVATE_SPACE_BP)
+ @Test
+ fun pinCredentialTiedProfileWhenBad() = pinCredential(badCredential(), OWNER_ID)
- val last = statusList.removeLastOrNull()
- if (result.isMatched) {
- assertThat(statusList).isEmpty()
- val successfulResult = last as? CredentialStatus.Success.Verified
- assertThat(successfulResult).isNotNull()
- assertThat(successfulResult!!.hat).isEqualTo(result.gatekeeperHAT)
+ @EnableFlags(Flags.FLAG_PRIVATE_SPACE_BP)
+ @Test
+ fun pinCredentialTiedProfileWhenBadAndThrottled() =
+ pinCredential(badCredential(timeout = 5_000), OWNER_ID)
- verify(lockPatternUtils).userPresent(eq(USER_ID))
- verify(lockPatternUtils)
- .removeGatekeeperPasswordHandle(eq(result.gatekeeperPasswordHandle))
- } else {
- val failedResult = last as? CredentialStatus.Fail.Error
- assertThat(failedResult).isNotNull()
- assertThat(failedResult!!.remainingAttempts)
- .isEqualTo(if (result.timeout > 0) null else MAX_ATTEMPTS - usedAttempts - 1)
- assertThat(failedResult.urgentMessage).isNull()
+ private fun pinCredential(result: VerifyCredentialResponse, credentialOwner: Int = USER_ID) =
+ runTest {
+ val usedAttempts = 1
+ whenever(lockPatternUtils.getCurrentFailedPasswordAttempts(eq(USER_ID)))
+ .thenReturn(usedAttempts)
+ whenever(lockPatternUtils.verifyCredential(any(), eq(USER_ID), anyInt()))
+ .thenReturn(result)
+ whenever(lockPatternUtils.verifyTiedProfileChallenge(any(), eq(USER_ID), anyInt()))
+ .thenReturn(result)
+ whenever(
+ lockPatternUtils.verifyGatekeeperPasswordHandle(
+ anyLong(),
+ anyLong(),
+ eq(USER_ID),
+ )
+ )
+ .thenReturn(result)
+ whenever(lockPatternUtils.setLockoutAttemptDeadline(anyInt(), anyInt())).thenAnswer {
+ systemClock.elapsedRealtime() + (it.arguments[1] as Int)
+ }
- if (result.timeout > 0) { // failed and throttled
- // messages are in the throttled errors, so the final Error.error is empty
- assertThat(failedResult.error).isEmpty()
- assertThat(statusList).isNotEmpty()
- assertThat(statusList.filterIsInstance(CredentialStatus.Fail.Throttled::class.java))
- .hasSize(statusList.size)
+ // wrap in an async block so the test can advance the clock if throttling credential
+ // checks prevents the method from returning
+ val statusList = mutableListOf<CredentialStatus>()
+ interactor
+ .verifyCredential(
+ pinRequest(credentialOwner),
+ LockscreenCredential.createPin("1234"),
+ )
+ .toList(statusList)
- verify(lockPatternUtils).setLockoutAttemptDeadline(eq(USER_ID), eq(result.timeout))
- } else { // failed
- assertThat(failedResult.error)
- .matches(Regex("(.*)try again(.*)", RegexOption.IGNORE_CASE).toPattern())
+ val last = statusList.removeLastOrNull()
+ if (result.isMatched) {
assertThat(statusList).isEmpty()
+ val successfulResult = last as? CredentialStatus.Success.Verified
+ assertThat(successfulResult).isNotNull()
+ assertThat(successfulResult!!.hat).isEqualTo(result.gatekeeperHAT)
- verify(lockPatternUtils).reportFailedPasswordAttempt(eq(USER_ID))
+ verify(lockPatternUtils).userPresent(eq(USER_ID))
+ verify(lockPatternUtils)
+ .removeGatekeeperPasswordHandle(eq(result.gatekeeperPasswordHandle))
+ } else {
+ val failedResult = last as? CredentialStatus.Fail.Error
+ assertThat(failedResult).isNotNull()
+ assertThat(failedResult!!.remainingAttempts)
+ .isEqualTo(if (result.timeout > 0) null else MAX_ATTEMPTS - usedAttempts - 1)
+ assertThat(failedResult.urgentMessage).isNull()
+
+ if (result.timeout > 0) { // failed and throttled
+ // messages are in the throttled errors, so the final Error.error is empty
+ assertThat(failedResult.error).isEmpty()
+ assertThat(statusList).isNotEmpty()
+ assertThat(
+ statusList.filterIsInstance(CredentialStatus.Fail.Throttled::class.java)
+ )
+ .hasSize(statusList.size)
+
+ verify(lockPatternUtils)
+ .setLockoutAttemptDeadline(eq(USER_ID), eq(result.timeout))
+ } else { // failed
+ assertThat(failedResult.error)
+ .matches(Regex("(.*)try again(.*)", RegexOption.IGNORE_CASE).toPattern())
+ assertThat(statusList).isEmpty()
+
+ verify(lockPatternUtils).reportFailedPasswordAttempt(eq(USER_ID))
+ }
}
}
- }
@Test
fun pinCredentialWhenBadAndFinalAttempt() = runTest {
@@ -212,11 +244,11 @@
}
}
-private fun pinRequest(): BiometricPromptRequest.Credential.Pin =
+private fun pinRequest(credentialOwner: Int = USER_ID): BiometricPromptRequest.Credential.Pin =
BiometricPromptRequest.Credential.Pin(
promptInfo(),
- BiometricUserInfo(USER_ID),
- BiometricOperationInfo(OPERATION_ID)
+ BiometricUserInfo(userId = USER_ID, deviceCredentialOwnerId = credentialOwner),
+ BiometricOperationInfo(OPERATION_ID),
)
private fun goodCredential(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
index dc499cd..b39a888 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorImplTest.kt
@@ -77,6 +77,7 @@
private val fingerprintRepository = FakeFingerprintPropertyRepository()
private val promptRepository = FakePromptRepository()
private val fakeExecutor = FakeExecutor(FakeSystemClock())
+ private val credentialInteractor = FakeCredentialInteractor()
private lateinit var displayStateRepository: FakeDisplayStateRepository
private lateinit var displayRepository: FakeDisplayRepository
@@ -99,8 +100,9 @@
PromptSelectorInteractorImpl(
fingerprintRepository,
displayStateInteractor,
+ credentialInteractor,
promptRepository,
- lockPatternUtils
+ lockPatternUtils,
)
}
@@ -134,13 +136,13 @@
testScope.runTest {
useBiometricsAndReset(
allowCredentialFallback = true,
- setComponentNameForConfirmDeviceCredentialActivity = true
+ setComponentNameForConfirmDeviceCredentialActivity = true,
)
}
private fun TestScope.useBiometricsAndReset(
allowCredentialFallback: Boolean,
- setComponentNameForConfirmDeviceCredentialActivity: Boolean = false
+ setComponentNameForConfirmDeviceCredentialActivity: Boolean = false,
) {
setUserCredentialType(isPassword = true)
@@ -357,7 +359,7 @@
private fun setPrompt(
info: PromptInfo = basicPromptInfo(),
- onSwitchToCredential: Boolean = false
+ onSwitchToCredential: Boolean = false,
) {
interactor.setPrompt(
info,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorTest.kt
index 2b7e7ad..20d6615 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorTest.kt
@@ -16,34 +16,57 @@
package com.android.systemui.deviceentry.domain.interactor
+import android.hardware.face.FaceManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
+import com.android.compose.animation.scene.ObservableTransitionState
+import com.android.keyguard.keyguardUpdateMonitor
import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.repository.fakeAuthenticationRepository
+import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.biometrics.authController
import com.android.systemui.biometrics.data.repository.fingerprintPropertyRepository
import com.android.systemui.biometrics.shared.model.FingerprintSensorType
import com.android.systemui.biometrics.shared.model.SensorStrength
+import com.android.systemui.bouncer.data.repository.keyguardBouncerRepository
import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.deviceentry.shared.model.FailedFaceAuthenticationStatus
+import com.android.systemui.deviceentry.shared.model.SuccessFaceAuthenticationStatus
+import com.android.systemui.flags.DisableSceneContainer
+import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.keyevent.data.repository.fakeKeyEventRepository
import com.android.systemui.keyguard.data.repository.biometricSettingsRepository
+import com.android.systemui.keyguard.data.repository.configureKeyguardBypass
import com.android.systemui.keyguard.data.repository.deviceEntryFingerprintAuthRepository
import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFaceAuthRepository
+import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFingerprintAuthRepository
import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
import com.android.systemui.keyguard.shared.model.BiometricUnlockMode
import com.android.systemui.keyguard.shared.model.BiometricUnlockSource
import com.android.systemui.keyguard.shared.model.FailFingerprintAuthenticationStatus
+import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
import com.android.systemui.kosmos.testScope
import com.android.systemui.power.data.repository.powerRepository
import com.android.systemui.power.shared.model.WakeSleepReason
import com.android.systemui.power.shared.model.WakefulnessState
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.statusbar.phone.dozeScrimController
+import com.android.systemui.statusbar.phone.screenOffAnimationController
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.kotlin.whenever
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@@ -51,24 +74,52 @@
class DeviceEntryHapticsInteractorTest : SysuiTestCase() {
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
- private val underTest = kosmos.deviceEntryHapticsInteractor
+ private lateinit var underTest: DeviceEntryHapticsInteractor
+
+ @Before
+ fun setup() {
+ if (SceneContainerFlag.isEnabled) {
+ whenever(kosmos.authController.isUdfpsFingerDown).thenReturn(false)
+ whenever(kosmos.dozeScrimController.isPulsing).thenReturn(false)
+ whenever(kosmos.keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean()))
+ .thenReturn(true)
+ whenever(kosmos.screenOffAnimationController.isKeyguardShowDelayed()).thenReturn(false)
+
+ // Dependencies for DeviceEntrySourceInteractor#biometricUnlockStateOnKeyguardDismissed
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ whenever(kosmos.keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean()))
+ .thenReturn(true)
+
+ // Mock authenticationMethodIsSecure true
+ kosmos.fakeAuthenticationRepository.setAuthenticationMethod(
+ AuthenticationMethodModel.Pin
+ )
+
+ kosmos.keyguardBouncerRepository.setAlternateVisible(false)
+ kosmos.sceneInteractor.changeScene(Scenes.Lockscreen, "reason")
+ } else {
+ underTest = kosmos.deviceEntryHapticsInteractor
+ }
+ }
+
+ @DisableSceneContainer
@Test
fun nonPowerButtonFPS_vibrateSuccess() =
testScope.runTest {
val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
- setFingerprintSensorType(FingerprintSensorType.UDFPS_ULTRASONIC)
+ enrollFingerprint(FingerprintSensorType.UDFPS_ULTRASONIC)
runCurrent()
- enterDeviceFromBiometricUnlock()
+ enterDeviceFromFingerprintUnlockLegacy()
assertThat(playSuccessHaptic).isNotNull()
}
+ @DisableSceneContainer
@Test
fun powerButtonFPS_vibrateSuccess() =
testScope.runTest {
val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
- setPowerButtonFingerprintProperty()
- setFingerprintEnrolled()
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
kosmos.fakeKeyEventRepository.setPowerButtonDown(false)
// It's been 10 seconds since the last power button wakeup
@@ -76,16 +127,16 @@
advanceTimeBy(10000)
runCurrent()
- enterDeviceFromBiometricUnlock()
+ enterDeviceFromFingerprintUnlockLegacy()
assertThat(playSuccessHaptic).isNotNull()
}
+ @DisableSceneContainer
@Test
fun powerButtonFPS_powerDown_doNotVibrateSuccess() =
testScope.runTest {
val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
- setPowerButtonFingerprintProperty()
- setFingerprintEnrolled()
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
kosmos.fakeKeyEventRepository.setPowerButtonDown(true) // power button is currently DOWN
// It's been 10 seconds since the last power button wakeup
@@ -93,16 +144,16 @@
advanceTimeBy(10000)
runCurrent()
- enterDeviceFromBiometricUnlock()
+ enterDeviceFromFingerprintUnlockLegacy()
assertThat(playSuccessHaptic).isNull()
}
+ @DisableSceneContainer
@Test
fun powerButtonFPS_powerButtonRecentlyPressed_doNotVibrateSuccess() =
testScope.runTest {
val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
- setPowerButtonFingerprintProperty()
- setFingerprintEnrolled()
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
kosmos.fakeKeyEventRepository.setPowerButtonDown(false)
// It's only been 50ms since the last power button wakeup
@@ -110,7 +161,7 @@
advanceTimeBy(50)
runCurrent()
- enterDeviceFromBiometricUnlock()
+ enterDeviceFromFingerprintUnlockLegacy()
assertThat(playSuccessHaptic).isNull()
}
@@ -118,7 +169,7 @@
fun nonPowerButtonFPS_vibrateError() =
testScope.runTest {
val playErrorHaptic by collectLastValue(underTest.playErrorHaptic)
- setFingerprintSensorType(FingerprintSensorType.UDFPS_ULTRASONIC)
+ enrollFingerprint(FingerprintSensorType.UDFPS_ULTRASONIC)
runCurrent()
fingerprintFailure()
assertThat(playErrorHaptic).isNotNull()
@@ -128,8 +179,8 @@
fun nonPowerButtonFPS_coExFaceFailure_doNotVibrateError() =
testScope.runTest {
val playErrorHaptic by collectLastValue(underTest.playErrorHaptic)
- setFingerprintSensorType(FingerprintSensorType.UDFPS_ULTRASONIC)
- coExEnrolledAndEnabled()
+ enrollFingerprint(FingerprintSensorType.UDFPS_ULTRASONIC)
+ enrollFace()
runCurrent()
faceFailure()
assertThat(playErrorHaptic).isNull()
@@ -139,8 +190,7 @@
fun powerButtonFPS_vibrateError() =
testScope.runTest {
val playErrorHaptic by collectLastValue(underTest.playErrorHaptic)
- setPowerButtonFingerprintProperty()
- setFingerprintEnrolled()
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
runCurrent()
fingerprintFailure()
assertThat(playErrorHaptic).isNotNull()
@@ -150,15 +200,143 @@
fun powerButtonFPS_powerDown_doNotVibrateError() =
testScope.runTest {
val playErrorHaptic by collectLastValue(underTest.playErrorHaptic)
- setPowerButtonFingerprintProperty()
- setFingerprintEnrolled()
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
kosmos.fakeKeyEventRepository.setPowerButtonDown(true)
runCurrent()
fingerprintFailure()
assertThat(playErrorHaptic).isNull()
}
- private suspend fun enterDeviceFromBiometricUnlock() {
+ @EnableSceneContainer
+ @Test
+ fun playSuccessHaptic_onDeviceEntryFromUdfps_sceneContainer() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntryHapticsInteractor
+ val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
+ enrollFingerprint(FingerprintSensorType.UDFPS_ULTRASONIC)
+ runCurrent()
+ configureDeviceEntryFromBiometricSource(isFpUnlock = true)
+ verifyDeviceEntryFromFingerprintAuth()
+ assertThat(playSuccessHaptic).isNotNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun playSuccessHaptic_onDeviceEntryFromSfps_sceneContainer() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntryHapticsInteractor
+ val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
+ kosmos.fakeKeyEventRepository.setPowerButtonDown(false)
+
+ // It's been 10 seconds since the last power button wakeup
+ setAwakeFromPowerButton()
+ advanceTimeBy(10000)
+ runCurrent()
+
+ configureDeviceEntryFromBiometricSource(isFpUnlock = true)
+ verifyDeviceEntryFromFingerprintAuth()
+ assertThat(playSuccessHaptic).isNotNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun playSuccessHaptic_onDeviceEntryFromFaceAuth_sceneContainer() =
+ testScope.runTest {
+ enrollFace()
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntryHapticsInteractor
+ val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
+ configureDeviceEntryFromBiometricSource(isFaceUnlock = true)
+ verifyDeviceEntryFromFaceAuth()
+ assertThat(playSuccessHaptic).isNotNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun skipSuccessHaptic_onDeviceEntryFromSfps_whenPowerDown_sceneContainer() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntryHapticsInteractor
+ val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
+ // power button is currently DOWN
+ kosmos.fakeKeyEventRepository.setPowerButtonDown(true)
+
+ // It's been 10 seconds since the last power button wakeup
+ setAwakeFromPowerButton()
+ advanceTimeBy(10000)
+ runCurrent()
+
+ configureDeviceEntryFromBiometricSource(isFpUnlock = true)
+ verifyDeviceEntryFromFingerprintAuth()
+ assertThat(playSuccessHaptic).isNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun skipSuccessHaptic_onDeviceEntryFromSfps_whenPowerButtonRecentlyPressed_sceneContainer() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntryHapticsInteractor
+ val playSuccessHaptic by collectLastValue(underTest.playSuccessHaptic)
+ enrollFingerprint(FingerprintSensorType.POWER_BUTTON)
+ kosmos.fakeKeyEventRepository.setPowerButtonDown(false)
+
+ // It's only been 50ms since the last power button wakeup
+ setAwakeFromPowerButton()
+ advanceTimeBy(50)
+ runCurrent()
+
+ configureDeviceEntryFromBiometricSource(isFpUnlock = true)
+ verifyDeviceEntryFromFingerprintAuth()
+ assertThat(playSuccessHaptic).isNull()
+ }
+
+ // Mock dependencies for DeviceEntrySourceInteractor#deviceEntryFromBiometricSource
+ private fun configureDeviceEntryFromBiometricSource(
+ isFpUnlock: Boolean = false,
+ isFaceUnlock: Boolean = false,
+ ) {
+ // Mock DeviceEntrySourceInteractor#deviceEntryBiometricAuthSuccessState
+ if (isFpUnlock) {
+ kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
+ SuccessFingerprintAuthenticationStatus(0, true)
+ )
+ }
+ if (isFaceUnlock) {
+ kosmos.fakeDeviceEntryFaceAuthRepository.setAuthenticationStatus(
+ SuccessFaceAuthenticationStatus(
+ FaceManager.AuthenticationResult(null, null, 0, true)
+ )
+ )
+
+ // Mock DeviceEntrySourceInteractor#faceWakeAndUnlockMode = MODE_UNLOCK_COLLAPSING
+ kosmos.sceneInteractor.setTransitionState(
+ MutableStateFlow<ObservableTransitionState>(
+ ObservableTransitionState.Idle(Scenes.Lockscreen)
+ )
+ )
+ }
+ underTest = kosmos.deviceEntryHapticsInteractor
+ }
+
+ private fun TestScope.verifyDeviceEntryFromFingerprintAuth() {
+ val deviceEntryFromBiometricSource by
+ collectLastValue(kosmos.deviceEntrySourceInteractor.deviceEntryFromBiometricSource)
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ private fun TestScope.verifyDeviceEntryFromFaceAuth() {
+ val deviceEntryFromBiometricSource by
+ collectLastValue(kosmos.deviceEntrySourceInteractor.deviceEntryFromBiometricSource)
+ assertThat(deviceEntryFromBiometricSource).isEqualTo(BiometricUnlockSource.FACE_SENSOR)
+ }
+
+ private fun enterDeviceFromFingerprintUnlockLegacy() {
kosmos.fakeKeyguardRepository.setBiometricUnlockSource(
BiometricUnlockSource.FINGERPRINT_SENSOR
)
@@ -177,21 +355,22 @@
)
}
- private fun setFingerprintSensorType(fingerprintSensorType: FingerprintSensorType) {
- kosmos.fingerprintPropertyRepository.setProperties(
- sensorId = 0,
- strength = SensorStrength.STRONG,
- sensorType = fingerprintSensorType,
- sensorLocations = mapOf(),
- )
+ private fun enrollFingerprint(fingerprintSensorType: FingerprintSensorType?) {
+ if (fingerprintSensorType == null) {
+ kosmos.biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
+ } else {
+ kosmos.biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(true)
+ kosmos.fingerprintPropertyRepository.setProperties(
+ sensorId = 0,
+ strength = SensorStrength.STRONG,
+ sensorType = fingerprintSensorType,
+ sensorLocations = mapOf(),
+ )
+ }
}
- private fun setPowerButtonFingerprintProperty() {
- setFingerprintSensorType(FingerprintSensorType.POWER_BUTTON)
- }
-
- private fun setFingerprintEnrolled() {
- kosmos.biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(true)
+ private fun enrollFace() {
+ kosmos.biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
}
private fun setAwakeFromPowerButton() {
@@ -202,9 +381,4 @@
powerButtonLaunchGestureTriggered = false,
)
}
-
- private fun coExEnrolledAndEnabled() {
- setFingerprintEnrolled()
- kosmos.biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
- }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorTest.kt
index 2e4c97b..b3c891d 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorTest.kt
@@ -16,21 +16,51 @@
package com.android.systemui.deviceentry.domain.interactor
+import android.hardware.face.FaceManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
+import com.android.compose.animation.scene.ObservableTransitionState
+import com.android.compose.animation.scene.SceneKey
+import com.android.keyguard.keyguardUpdateMonitor
import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.repository.fakeAuthenticationRepository
+import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.biometrics.authController
+import com.android.systemui.bouncer.data.repository.keyguardBouncerRepository
import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.deviceentry.shared.model.FaceAuthenticationStatus
+import com.android.systemui.deviceentry.shared.model.SuccessFaceAuthenticationStatus
+import com.android.systemui.flags.DisableSceneContainer
+import com.android.systemui.flags.EnableSceneContainer
+import com.android.systemui.keyguard.data.repository.configureKeyguardBypass
+import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFaceAuthRepository
+import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFingerprintAuthRepository
import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
+import com.android.systemui.keyguard.data.repository.keyguardBypassRepository
+import com.android.systemui.keyguard.data.repository.keyguardOcclusionRepository
+import com.android.systemui.keyguard.data.repository.verifyCallback
import com.android.systemui.keyguard.shared.model.BiometricUnlockMode
import com.android.systemui.keyguard.shared.model.BiometricUnlockSource
+import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
import com.android.systemui.kosmos.testScope
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.statusbar.phone.dozeScrimController
+import com.android.systemui.statusbar.phone.screenOffAnimationController
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED
+import com.android.systemui.statusbar.policy.devicePostureController
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.kotlin.whenever
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@@ -38,45 +68,328 @@
class DeviceEntrySourceInteractorTest : SysuiTestCase() {
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
- private val keyguardRepository = kosmos.fakeKeyguardRepository
- private val underTest = kosmos.deviceEntrySourceInteractor
+ private lateinit var underTest: DeviceEntrySourceInteractor
+ @Before
+ fun setup() {
+ if (SceneContainerFlag.isEnabled) {
+ whenever(kosmos.authController.isUdfpsFingerDown).thenReturn(false)
+ whenever(kosmos.dozeScrimController.isPulsing).thenReturn(false)
+ whenever(kosmos.keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean()))
+ .thenReturn(true)
+ whenever(kosmos.screenOffAnimationController.isKeyguardShowDelayed()).thenReturn(false)
+ kosmos.fakeAuthenticationRepository.setAuthenticationMethod(
+ AuthenticationMethodModel.Pin
+ )
+ } else {
+ underTest = kosmos.deviceEntrySourceInteractor
+ }
+ }
+
+ @DisableSceneContainer
@Test
fun deviceEntryFromFaceUnlock() =
testScope.runTest {
val deviceEntryFromBiometricAuthentication by
collectLastValue(underTest.deviceEntryFromBiometricSource)
- keyguardRepository.setBiometricUnlockState(
+
+ kosmos.fakeKeyguardRepository.setBiometricUnlockState(
BiometricUnlockMode.WAKE_AND_UNLOCK,
BiometricUnlockSource.FACE_SENSOR,
)
runCurrent()
+
assertThat(deviceEntryFromBiometricAuthentication)
.isEqualTo(BiometricUnlockSource.FACE_SENSOR)
}
+ @DisableSceneContainer
@Test
- fun deviceEntryFromFingerprintUnlock() = runTest {
- val deviceEntryFromBiometricAuthentication by
- collectLastValue(underTest.deviceEntryFromBiometricSource)
- keyguardRepository.setBiometricUnlockState(
- BiometricUnlockMode.WAKE_AND_UNLOCK,
- BiometricUnlockSource.FINGERPRINT_SENSOR,
- )
- runCurrent()
- assertThat(deviceEntryFromBiometricAuthentication)
- .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ fun deviceEntryFromFingerprintUnlock() =
+ testScope.runTest {
+ val deviceEntryFromBiometricAuthentication by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ kosmos.fakeKeyguardRepository.setBiometricUnlockState(
+ BiometricUnlockMode.WAKE_AND_UNLOCK,
+ BiometricUnlockSource.FINGERPRINT_SENSOR,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricAuthentication)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @DisableSceneContainer
+ @Test
+ fun noDeviceEntry() =
+ testScope.runTest {
+ val deviceEntryFromBiometricAuthentication by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ kosmos.fakeKeyguardRepository.setBiometricUnlockState(
+ BiometricUnlockMode.ONLY_WAKE, // doesn't dismiss keyguard:
+ BiometricUnlockSource.FINGERPRINT_SENSOR,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricAuthentication).isNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFingerprintUnlockOnLockScreen_sceneContainerEnabled() =
+ testScope.runTest {
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFingerprintAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntrySourceInteractor
+
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFingerprintUnlockOnAod_sceneContainerEnabled() =
+ testScope.runTest {
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(false)
+ configureDeviceEntryBiometricAuthSuccessState(isFingerprintAuth = true)
+ configureBiometricUnlockState(alternateBouncerVisible = false, sceneKey = Scenes.Dream)
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFingerprintUnlockOnBouncer_sceneContainerEnabled() =
+ testScope.runTest {
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFingerprintAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Bouncer,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFingerprintUnlockOnShade_sceneContainerEnabled() =
+ testScope.runTest {
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFingerprintAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFingerprintUnlockOnAlternateBouncer_sceneContainerEnabled() =
+ testScope.runTest {
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFingerprintAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = true,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource)
+ .isEqualTo(BiometricUnlockSource.FINGERPRINT_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnLockScreen_bypassAvailable_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntrySourceInteractor
+
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource).isEqualTo(BiometricUnlockSource.FACE_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnLockScreen_bypassDisabled_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntrySourceInteractor
+
+ collectLastValue(kosmos.keyguardBypassRepository.isBypassAvailable)
+ runCurrent()
+
+ val postureControllerCallback = kosmos.devicePostureController.verifyCallback()
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_OPENED)
+
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ // MODE_NONE does not dismiss keyguard
+ assertThat(deviceEntryFromBiometricSource).isNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnBouncer_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Bouncer,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource).isEqualTo(BiometricUnlockSource.FACE_SENSOR)
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnShade_bypassAvailable_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(alternateBouncerVisible = false, sceneKey = Scenes.Shade)
+ runCurrent()
+
+ // MODE_NONE does not dismiss keyguard
+ assertThat(deviceEntryFromBiometricSource).isNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnShade_bypassDisabled_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = false)
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = false,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource).isNull()
+ }
+
+ @EnableSceneContainer
+ @Test
+ fun deviceEntryFromFaceUnlockOnAlternateBouncer_sceneContainerEnabled() =
+ testScope.runTest {
+ kosmos.configureKeyguardBypass(isBypassAvailable = true)
+ underTest = kosmos.deviceEntrySourceInteractor
+ val deviceEntryFromBiometricSource by
+ collectLastValue(underTest.deviceEntryFromBiometricSource)
+
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
+ kosmos.keyguardOcclusionRepository.setShowWhenLockedActivityInfo(onTop = true)
+ configureDeviceEntryBiometricAuthSuccessState(isFaceAuth = true)
+ configureBiometricUnlockState(
+ alternateBouncerVisible = true,
+ sceneKey = Scenes.Lockscreen,
+ )
+ runCurrent()
+
+ assertThat(deviceEntryFromBiometricSource).isEqualTo(BiometricUnlockSource.FACE_SENSOR)
+ }
+
+ private fun configureDeviceEntryBiometricAuthSuccessState(
+ isFingerprintAuth: Boolean = false,
+ isFaceAuth: Boolean = false,
+ ) {
+ if (isFingerprintAuth) {
+ val successStatus = SuccessFingerprintAuthenticationStatus(0, true)
+ kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(successStatus)
+ }
+
+ if (isFaceAuth) {
+ val successStatus: FaceAuthenticationStatus =
+ SuccessFaceAuthenticationStatus(
+ FaceManager.AuthenticationResult(null, null, 0, true)
+ )
+ kosmos.fakeDeviceEntryFaceAuthRepository.setAuthenticationStatus(successStatus)
+ }
}
- @Test
- fun noDeviceEntry() = runTest {
- val deviceEntryFromBiometricAuthentication by
- collectLastValue(underTest.deviceEntryFromBiometricSource)
- keyguardRepository.setBiometricUnlockState(
- BiometricUnlockMode.ONLY_WAKE, // doesn't dismiss keyguard:
- BiometricUnlockSource.FINGERPRINT_SENSOR,
+ private fun configureBiometricUnlockState(
+ alternateBouncerVisible: Boolean,
+ sceneKey: SceneKey,
+ ) {
+ kosmos.keyguardBouncerRepository.setAlternateVisible(alternateBouncerVisible)
+ kosmos.sceneInteractor.changeScene(sceneKey, "reason")
+ kosmos.sceneInteractor.setTransitionState(
+ MutableStateFlow<ObservableTransitionState>(ObservableTransitionState.Idle(sceneKey))
)
- runCurrent()
- assertThat(deviceEntryFromBiometricAuthentication).isNull()
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
index 77337d3..a981e20 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
@@ -18,6 +18,7 @@
import android.content.Intent
import android.content.mockedContext
+import android.content.res.Resources
import android.hardware.fingerprint.FingerprintManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
@@ -41,13 +42,16 @@
import com.android.systemui.plugins.ActivityStarter.OnDismissAction
import com.android.systemui.plugins.activityStarter
import com.android.systemui.power.data.repository.fakePowerRepository
+import com.android.systemui.res.R
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.whenever
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
@@ -55,6 +59,7 @@
import org.mockito.ArgumentMatchers.isNull
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
+import org.mockito.kotlin.mock
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@@ -63,8 +68,8 @@
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
- private val underTest = kosmos.occludingAppDeviceEntryInteractor
-
+ private lateinit var underTest: OccludingAppDeviceEntryInteractor
+ private lateinit var mockedResources: Resources
private val fingerprintAuthRepository = kosmos.deviceEntryFingerprintAuthRepository
private val keyguardRepository = kosmos.fakeKeyguardRepository
private val bouncerRepository = kosmos.keyguardBouncerRepository
@@ -74,9 +79,18 @@
private val mockedContext = kosmos.mockedContext
private val mockedActivityStarter = kosmos.activityStarter
+ @Before
+ fun setup() {
+ mockedResources = mock<Resources>()
+ whenever(mockedContext.resources).thenReturn(mockedResources)
+ whenever(mockedResources.getBoolean(R.bool.config_goToHomeFromOccludedApps))
+ .thenReturn(true)
+ }
+
@Test
fun fingerprintSuccess_goToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(true)
fingerprintAuthRepository.setAuthenticationStatus(
SuccessFingerprintAuthenticationStatus(0, true)
@@ -86,8 +100,23 @@
}
@Test
+ fun fingerprintSuccess_configOff_doesNotGoToHomeScreen() =
+ testScope.runTest {
+ whenever(mockedResources.getBoolean(R.bool.config_goToHomeFromOccludedApps))
+ .thenReturn(false)
+ underTest = kosmos.occludingAppDeviceEntryInteractor
+ givenOnOccludingApp(true)
+ fingerprintAuthRepository.setAuthenticationStatus(
+ SuccessFingerprintAuthenticationStatus(0, true)
+ )
+ runCurrent()
+ verifyNeverGoToHomeScreen()
+ }
+
+ @Test
fun fingerprintSuccess_notInteractive_doesNotGoToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(true)
powerRepository.setInteractive(false)
fingerprintAuthRepository.setAuthenticationStatus(
@@ -100,6 +129,7 @@
@Test
fun fingerprintSuccess_dreaming_doesNotGoToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(true)
keyguardRepository.setDreaming(true)
fingerprintAuthRepository.setAuthenticationStatus(
@@ -112,6 +142,7 @@
@Test
fun fingerprintSuccess_notOnOccludingApp_doesNotGoToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(false)
fingerprintAuthRepository.setAuthenticationStatus(
SuccessFingerprintAuthenticationStatus(0, true)
@@ -123,11 +154,12 @@
@Test
fun lockout_goToHomeScreenOnDismissAction() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(true)
fingerprintAuthRepository.setAuthenticationStatus(
ErrorFingerprintAuthenticationStatus(
FingerprintManager.FINGERPRINT_ERROR_LOCKOUT,
- "lockoutTest"
+ "lockoutTest",
)
)
runCurrent()
@@ -137,11 +169,12 @@
@Test
fun lockout_notOnOccludingApp_neverGoToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(false)
fingerprintAuthRepository.setAuthenticationStatus(
ErrorFingerprintAuthenticationStatus(
FingerprintManager.FINGERPRINT_ERROR_LOCKOUT,
- "lockoutTest"
+ "lockoutTest",
)
)
runCurrent()
@@ -151,11 +184,12 @@
@Test
fun lockout_onOccludingApp_onCommunal_neverGoToHomeScreen() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
givenOnOccludingApp(isOnOccludingApp = true, isOnCommunal = true)
fingerprintAuthRepository.setAuthenticationStatus(
ErrorFingerprintAuthenticationStatus(
FingerprintManager.FINGERPRINT_ERROR_LOCKOUT,
- "lockoutTest"
+ "lockoutTest",
)
)
runCurrent()
@@ -165,6 +199,7 @@
@Test
fun message_fpFailOnOccludingApp_thenNotOnOccludingApp() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
val message by collectLastValue(underTest.message)
givenOnOccludingApp(true)
@@ -186,6 +221,7 @@
@Test
fun message_fpErrorHelpFailOnOccludingApp() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
val message by collectLastValue(underTest.message)
givenOnOccludingApp(true)
@@ -218,6 +254,7 @@
@Test
fun message_fpError_lockoutFilteredOut() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
val message by collectLastValue(underTest.message)
givenOnOccludingApp(true)
@@ -246,6 +283,7 @@
@Test
fun noMessage_fpErrorsWhileDozing() =
testScope.runTest {
+ underTest = kosmos.occludingAppDeviceEntryInteractor
val message by collectLastValue(underTest.message)
givenOnOccludingApp(true)
@@ -254,7 +292,7 @@
kosmos.fakeKeyguardTransitionRepository.sendTransitionSteps(
from = KeyguardState.OCCLUDED,
to = KeyguardState.DOZING,
- testScope
+ testScope,
)
runCurrent()
@@ -283,7 +321,7 @@
private suspend fun givenOnOccludingApp(
isOnOccludingApp: Boolean,
- isOnCommunal: Boolean = false
+ isOnCommunal: Boolean = false,
) {
powerRepository.setInteractive(true)
keyguardRepository.setIsDozing(false)
@@ -305,13 +343,13 @@
kosmos.fakeKeyguardTransitionRepository.sendTransitionSteps(
from = KeyguardState.LOCKSCREEN,
to = KeyguardState.OCCLUDED,
- testScope
+ testScope,
)
} else {
kosmos.fakeKeyguardTransitionRepository.sendTransitionSteps(
from = KeyguardState.OCCLUDED,
to = KeyguardState.LOCKSCREEN,
- testScope
+ testScope,
)
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamServiceTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamServiceTest.kt
index 9300db9..4317b9f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamServiceTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamServiceTest.kt
@@ -16,25 +16,37 @@
package com.android.systemui.dreams.homecontrols
import android.app.Activity
+import android.content.ComponentName
import android.content.Intent
+import android.os.powerManager
import android.service.controls.ControlsProviderService.CONTROLS_SURFACE_ACTIVITY_PANEL
import android.service.controls.ControlsProviderService.CONTROLS_SURFACE_DREAM
import android.service.controls.ControlsProviderService.EXTRA_CONTROLS_SURFACE
+import android.service.dreams.DreamService
import android.window.TaskFragmentInfo
+import androidx.lifecycle.testing.TestLifecycleOwner
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
-import com.android.systemui.controls.settings.FakeControlsSettingsRepository
+import com.android.systemui.dreams.homecontrols.service.TaskFragmentComponent
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.dreams.homecontrols.shared.model.fakeHomeControlsDataSource
+import com.android.systemui.dreams.homecontrols.shared.model.homeControlsDataSource
import com.android.systemui.kosmos.testDispatcher
import com.android.systemui.kosmos.testScope
import com.android.systemui.log.logcatLogBuffer
import com.android.systemui.testKosmos
+import com.android.systemui.util.time.fakeSystemClock
import com.android.systemui.util.wakelock.WakeLockFake
import com.google.common.truth.Truth.assertThat
-import java.util.Optional
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.test.setMain
+import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -47,7 +59,6 @@
import org.mockito.kotlin.never
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
-import org.mockito.kotlin.whenever
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@@ -62,13 +73,18 @@
WakeLockFake.Builder(context).apply { setWakeLock(fakeWakeLock) }
}
+ private val lifecycleOwner = TestLifecycleOwner(coroutineDispatcher = kosmos.testDispatcher)
+
private val taskFragmentComponent = mock<TaskFragmentComponent>()
private val activity = mock<Activity>()
private val onCreateCallback = argumentCaptor<(TaskFragmentInfo) -> Unit>()
private val onInfoChangedCallback = argumentCaptor<(TaskFragmentInfo) -> Unit>()
private val hideCallback = argumentCaptor<() -> Unit>()
- private val dreamServiceDelegate =
- mock<DreamServiceDelegate> { on { getActivity(any()) } doReturn activity }
+ private var dreamService =
+ mock<DreamService> {
+ on { activity } doReturn activity
+ on { redirectWake } doReturn false
+ }
private val taskFragmentComponentFactory =
mock<TaskFragmentComponent.Factory> {
@@ -82,12 +98,32 @@
} doReturn taskFragmentComponent
}
- private val underTest: HomeControlsDreamService by lazy { buildService() }
+ private val underTest: HomeControlsDreamServiceImpl by lazy {
+ with(kosmos) {
+ HomeControlsDreamServiceImpl(
+ taskFragmentFactory = taskFragmentComponentFactory,
+ wakeLockBuilder = fakeWakeLockBuilder,
+ powerManager = powerManager,
+ systemClock = fakeSystemClock,
+ dataSource = homeControlsDataSource,
+ logBuffer = logcatLogBuffer("HomeControlsDreamServiceTest"),
+ service = dreamService,
+ lifecycleOwner = lifecycleOwner,
+ )
+ }
+ }
@Before
fun setup() {
- whenever(kosmos.controlsComponent.getControlsListingController())
- .thenReturn(Optional.of(kosmos.controlsListingController))
+ Dispatchers.setMain(kosmos.testDispatcher)
+ kosmos.fakeHomeControlsDataSource.setComponentInfo(
+ HomeControlsComponentInfo(PANEL_COMPONENT, true)
+ )
+ }
+
+ @After
+ fun tearDown() {
+ Dispatchers.resetMain()
}
@Test
@@ -108,13 +144,10 @@
@Test
fun testNotCreatingTaskFragmentComponentWhenActivityIsNull() =
testScope.runTest {
- val serviceWithNullActivity =
- buildService(
- mock<DreamServiceDelegate> { on { getActivity(underTest) } doReturn null }
- )
-
- serviceWithNullActivity.onAttachedToWindow()
+ dreamService = mock<DreamService> { on { activity } doReturn null }
+ underTest.onAttachedToWindow()
verify(taskFragmentComponentFactory, never()).create(any(), any(), any(), any())
+ verify(dreamService).finish()
}
@Test
@@ -137,9 +170,9 @@
@Test
fun testFinishesDreamWithoutRestartingActivityWhenNotRedirectingWakes() =
testScope.runTest {
- whenever(dreamServiceDelegate.redirectWake(any())).thenReturn(false)
underTest.onAttachedToWindow()
onCreateCallback.firstValue.invoke(mock<TaskFragmentInfo>())
+ runCurrent()
verify(taskFragmentComponent, times(1)).startActivityInTaskFragment(intentMatcher())
// Task fragment becomes empty
@@ -149,16 +182,21 @@
advanceUntilIdle()
// Dream is finished and activity is not restarted
verify(taskFragmentComponent, times(1)).startActivityInTaskFragment(intentMatcher())
- verify(dreamServiceDelegate, never()).wakeUp(any())
- verify(dreamServiceDelegate).finish(any())
+ verify(dreamService, never()).wakeUp()
+ verify(dreamService).finish()
}
@Test
fun testRestartsActivityWhenRedirectingWakes() =
testScope.runTest {
- whenever(dreamServiceDelegate.redirectWake(any())).thenReturn(true)
+ dreamService =
+ mock<DreamService> {
+ on { activity } doReturn activity
+ on { redirectWake } doReturn true
+ }
underTest.onAttachedToWindow()
onCreateCallback.firstValue.invoke(mock<TaskFragmentInfo>())
+ runCurrent()
verify(taskFragmentComponent, times(1)).startActivityInTaskFragment(intentMatcher())
// Task fragment becomes empty
@@ -166,30 +204,20 @@
mock<TaskFragmentInfo> { on { isEmpty } doReturn true }
)
advanceUntilIdle()
+
// Activity is restarted instead of finishing the dream.
verify(taskFragmentComponent, times(2)).startActivityInTaskFragment(intentMatcher())
- verify(dreamServiceDelegate).wakeUp(any())
- verify(dreamServiceDelegate, never()).finish(any())
+ verify(dreamService).wakeUp()
+ verify(dreamService, never()).finish()
}
private fun intentMatcher() =
argThat<Intent> {
getIntExtra(EXTRA_CONTROLS_SURFACE, CONTROLS_SURFACE_ACTIVITY_PANEL) ==
- CONTROLS_SURFACE_DREAM
+ CONTROLS_SURFACE_DREAM && component == PANEL_COMPONENT
}
- private fun buildService(
- activityProvider: DreamServiceDelegate = dreamServiceDelegate
- ): HomeControlsDreamService =
- with(kosmos) {
- return HomeControlsDreamService(
- controlsSettingsRepository = FakeControlsSettingsRepository(),
- taskFragmentFactory = taskFragmentComponentFactory,
- homeControlsComponentInteractor = homeControlsComponentInteractor,
- wakeLockBuilder = fakeWakeLockBuilder,
- dreamServiceDelegate = activityProvider,
- bgDispatcher = testDispatcher,
- logBuffer = logcatLogBuffer("HomeControlsDreamServiceTest")
- )
- }
+ private companion object {
+ val PANEL_COMPONENT = ComponentName("test.pkg", "test.panel")
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartableTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartableTest.kt
index 1adf414..ed45e8c 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartableTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartableTest.kt
@@ -34,9 +34,14 @@
import com.android.systemui.controls.panels.SelectedComponentRepository
import com.android.systemui.controls.panels.authorizedPanelsRepository
import com.android.systemui.controls.panels.selectedComponentRepository
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor
+import com.android.systemui.dreams.homecontrols.system.HomeControlsDreamStartable
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.HomeControlsComponentInteractor
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsComponent
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsListingController
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.homeControlsComponentInteractor
import com.android.systemui.kosmos.applicationCoroutineScope
import com.android.systemui.kosmos.testScope
+import com.android.systemui.settings.userTracker
import com.android.systemui.testKosmos
import com.android.systemui.user.data.repository.FakeUserRepository
import com.android.systemui.user.data.repository.fakeUserRepository
@@ -96,8 +101,9 @@
HomeControlsDreamStartable(
mContext,
packageManager,
+ kosmos.userTracker,
homeControlsComponentInteractor,
- kosmos.applicationCoroutineScope
+ kosmos.applicationCoroutineScope,
)
}
@@ -113,7 +119,7 @@
.setComponentEnabledSetting(
eq(componentName),
eq(PackageManager.COMPONENT_ENABLED_STATE_ENABLED),
- eq(PackageManager.DONT_KILL_APP)
+ eq(PackageManager.DONT_KILL_APP),
)
}
@@ -128,7 +134,7 @@
.setComponentEnabledSetting(
eq(componentName),
eq(PackageManager.COMPONENT_ENABLED_STATE_DISABLED),
- eq(PackageManager.DONT_KILL_APP)
+ eq(PackageManager.DONT_KILL_APP),
)
}
@@ -143,14 +149,14 @@
.setComponentEnabledSetting(
eq(componentName),
eq(PackageManager.COMPONENT_ENABLED_STATE_DISABLED),
- eq(PackageManager.DONT_KILL_APP)
+ eq(PackageManager.DONT_KILL_APP),
)
}
private fun ControlsServiceInfo(
componentName: ComponentName,
label: CharSequence,
- hasPanel: Boolean
+ hasPanel: Boolean,
): ControlsServiceInfo {
val serviceInfo =
ServiceInfo().apply {
@@ -165,7 +171,7 @@
context: Context,
serviceInfo: ServiceInfo,
private val label: CharSequence,
- hasPanel: Boolean
+ hasPanel: Boolean,
) : ControlsServiceInfo(context, serviceInfo) {
init {
@@ -185,7 +191,7 @@
UserInfo(
/* id= */ PRIMARY_USER_ID,
/* name= */ "primary user",
- /* flags= */ UserInfo.FLAG_PRIMARY
+ /* flags= */ UserInfo.FLAG_PRIMARY,
)
private const val TEST_PACKAGE_PANEL = "pkg.panel"
private val TEST_COMPONENT_PANEL = ComponentName(TEST_PACKAGE_PANEL, "service")
@@ -193,13 +199,13 @@
SelectedComponentRepository.SelectedComponent(
TEST_PACKAGE_PANEL,
TEST_COMPONENT_PANEL,
- true
+ true,
)
private val TEST_SELECTED_COMPONENT_NON_PANEL =
SelectedComponentRepository.SelectedComponent(
TEST_PACKAGE_PANEL,
TEST_COMPONENT_PANEL,
- false
+ false,
)
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyTest.kt
new file mode 100644
index 0000000..e57776f
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyTest.kt
@@ -0,0 +1,95 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import android.content.ComponentName
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class HomeControlsRemoteProxyTest : SysuiTestCase() {
+
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+
+ private val fakeBinder = kosmos.fakeHomeControlsRemoteBinder
+
+ private val underTest by lazy { kosmos.homeControlsRemoteProxy }
+
+ @Test
+ fun testRegistersOnlyWhileSubscribed() =
+ testScope.runTest {
+ assertThat(fakeBinder.callbacks).isEmpty()
+
+ val job = launch { underTest.componentInfo.collect {} }
+ runCurrent()
+ assertThat(fakeBinder.callbacks).hasSize(1)
+
+ job.cancel()
+ runCurrent()
+ assertThat(fakeBinder.callbacks).isEmpty()
+ }
+
+ @Test
+ fun testEmitsOnCallback() =
+ testScope.runTest {
+ val componentInfo by collectLastValue(underTest.componentInfo)
+ assertThat(componentInfo).isNull()
+
+ fakeBinder.notifyCallbacks(TEST_COMPONENT, allowTrivialControlsOnLockscreen = true)
+ assertThat(componentInfo)
+ .isEqualTo(
+ HomeControlsComponentInfo(
+ TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = true,
+ )
+ )
+ }
+
+ @Test
+ fun testOnlyRegistersSingleCallbackForMultipleSubscribers() =
+ testScope.runTest {
+ assertThat(fakeBinder.callbacks).isEmpty()
+
+ // 2 collectors
+ val job = launch {
+ launch { underTest.componentInfo.collect {} }
+ launch { underTest.componentInfo.collect {} }
+ }
+ runCurrent()
+ assertThat(fakeBinder.callbacks).hasSize(1)
+ job.cancel()
+ }
+
+ private companion object {
+ val TEST_COMPONENT = ComponentName("pkg.test", "class.test")
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorTest.kt
new file mode 100644
index 0000000..4002175
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorTest.kt
@@ -0,0 +1,128 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import android.content.ComponentName
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.dreams.homecontrols.dagger.HomeControlsRemoteServiceComponent
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.testKosmos
+import com.android.systemui.util.service.ObservableServiceConnection
+import com.android.systemui.util.service.PersistentConnectionManager
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.doAnswer
+import org.mockito.kotlin.doReturn
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.stub
+import org.mockito.kotlin.times
+import org.mockito.kotlin.verify
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class RemoteHomeControlsDataSourceDelegatorTest : SysuiTestCase() {
+
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+
+ private val proxy = kosmos.homeControlsRemoteProxy
+ private val fakeBinder = kosmos.fakeHomeControlsRemoteBinder
+
+ private val callbackCaptor =
+ argumentCaptor<ObservableServiceConnection.Callback<HomeControlsRemoteProxy>>()
+
+ private val connectionManager =
+ mock<PersistentConnectionManager<HomeControlsRemoteProxy>> {
+ on { start() } doAnswer { simulateConnect() }
+ on { stop() } doAnswer { simulateDisconnect() }
+ }
+ private val serviceComponent =
+ mock<HomeControlsRemoteServiceComponent> {
+ on { connectionManager } doReturn connectionManager
+ }
+
+ private val underTest by lazy { kosmos.remoteHomeControlsDataSourceDelegator }
+
+ @Before
+ fun setUp() {
+ kosmos.homeControlsRemoteServiceFactory =
+ mock<HomeControlsRemoteServiceComponent.Factory>().stub {
+ on { create(callbackCaptor.capture()) } doReturn serviceComponent
+ }
+ }
+
+ @Test
+ fun testQueriesComponentInfoFromBinder() =
+ testScope.runTest {
+ assertThat(fakeBinder.callbacks).isEmpty()
+
+ val componentInfo by collectLastValue(underTest.componentInfo)
+
+ assertThat(componentInfo).isNull()
+ assertThat(fakeBinder.callbacks).hasSize(1)
+
+ fakeBinder.notifyCallbacks(TEST_COMPONENT, allowTrivialControlsOnLockscreen = true)
+ assertThat(componentInfo)
+ .isEqualTo(
+ HomeControlsComponentInfo(
+ TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = true,
+ )
+ )
+ }
+
+ @Test
+ fun testOnlyConnectToServiceOnSubscription() =
+ testScope.runTest {
+ verify(connectionManager, never()).start()
+
+ val job = launch { underTest.componentInfo.collect {} }
+ runCurrent()
+ verify(connectionManager, times(1)).start()
+ verify(connectionManager, never()).stop()
+
+ job.cancel()
+ runCurrent()
+ verify(connectionManager, times(1)).start()
+ verify(connectionManager, times(1)).stop()
+ }
+
+ private fun simulateConnect() {
+ callbackCaptor.lastValue.onConnected(mock(), proxy)
+ }
+
+ private fun simulateDisconnect() {
+ callbackCaptor.lastValue.onDisconnected(mock(), 0)
+ }
+
+ private companion object {
+ val TEST_COMPONENT = ComponentName("pkg.test", "class.test")
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteServiceBinderTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteServiceBinderTest.kt
new file mode 100644
index 0000000..f8a45e8
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteServiceBinderTest.kt
@@ -0,0 +1,236 @@
+/*
+ * 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.dreams.homecontrols.system
+
+import android.content.ComponentName
+import android.content.Context
+import android.content.pm.ApplicationInfo
+import android.content.pm.ServiceInfo
+import android.content.pm.UserInfo
+import androidx.lifecycle.testing.TestLifecycleOwner
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.controls.ControlsServiceInfo
+import com.android.systemui.controls.panels.SelectedComponentRepository
+import com.android.systemui.controls.panels.authorizedPanelsRepository
+import com.android.systemui.controls.panels.selectedComponentRepository
+import com.android.systemui.controls.settings.FakeControlsSettingsRepository
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.dreams.homecontrols.shared.IOnControlsSettingsChangeListener
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsComponent
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsListingController
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.homeControlsComponentInteractor
+import com.android.systemui.kosmos.backgroundCoroutineContext
+import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.log.logcatLogBuffer
+import com.android.systemui.settings.fakeUserTracker
+import com.android.systemui.testKosmos
+import com.android.systemui.user.data.repository.fakeUserRepository
+import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.mockito.withArgCaptor
+import com.android.systemui.utils.coroutines.flow.conflatedCallbackFlow
+import com.google.common.truth.Truth.assertThat
+import java.util.Optional
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class HomeControlsRemoteServiceBinderTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+
+ private val lifecycleOwner = TestLifecycleOwner(coroutineDispatcher = kosmos.testDispatcher)
+ private val fakeControlsSettingsRepository = FakeControlsSettingsRepository()
+
+ private val underTest by lazy {
+ HomeControlsRemoteServiceBinder(
+ kosmos.homeControlsComponentInteractor,
+ fakeControlsSettingsRepository,
+ kosmos.backgroundCoroutineContext,
+ logcatLogBuffer(),
+ lifecycleOwner,
+ )
+ }
+
+ @Before
+ fun setUp() {
+ with(kosmos) {
+ fakeUserRepository.setUserInfos(listOf(PRIMARY_USER))
+ whenever(controlsComponent.getControlsListingController())
+ .thenReturn(Optional.of(controlsListingController))
+ }
+ }
+
+ @Test
+ fun testRegisterSingleListener() =
+ testScope.runTest {
+ setup()
+ val controlsSettings by collectLastValue(addCallback())
+ runServicesUpdate()
+
+ assertThat(controlsSettings)
+ .isEqualTo(
+ CallbackArgs(
+ panelComponent = TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = false,
+ )
+ )
+ }
+
+ @Test
+ fun testRegisterMultipleListeners() =
+ testScope.runTest {
+ setup()
+ val controlsSettings1 by collectLastValue(addCallback())
+ val controlsSettings2 by collectLastValue(addCallback())
+ runServicesUpdate()
+
+ assertThat(controlsSettings1)
+ .isEqualTo(
+ CallbackArgs(
+ panelComponent = TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = false,
+ )
+ )
+ assertThat(controlsSettings2)
+ .isEqualTo(
+ CallbackArgs(
+ panelComponent = TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = false,
+ )
+ )
+ }
+
+ @Test
+ fun testListenerCalledWhenStateChanges() =
+ testScope.runTest {
+ setup()
+ val controlsSettings by collectLastValue(addCallback())
+ runServicesUpdate()
+
+ assertThat(controlsSettings)
+ .isEqualTo(
+ CallbackArgs(
+ panelComponent = TEST_COMPONENT,
+ allowTrivialControlsOnLockscreen = false,
+ )
+ )
+
+ kosmos.authorizedPanelsRepository.removeAuthorizedPanels(setOf(TEST_PACKAGE))
+
+ // Updated with null component now that we are no longer authorized.
+ assertThat(controlsSettings)
+ .isEqualTo(
+ CallbackArgs(panelComponent = null, allowTrivialControlsOnLockscreen = false)
+ )
+ }
+
+ private fun TestScope.runServicesUpdate() {
+ runCurrent()
+ val listings = listOf(ControlsServiceInfo(TEST_COMPONENT, "panel", hasPanel = true))
+ val callback = withArgCaptor {
+ Mockito.verify(kosmos.controlsListingController).addCallback(capture())
+ }
+ callback.onServicesUpdated(listings)
+ runCurrent()
+ }
+
+ private fun addCallback() = conflatedCallbackFlow {
+ val callback =
+ object : IOnControlsSettingsChangeListener.Stub() {
+ override fun onControlsSettingsChanged(
+ panelComponent: ComponentName?,
+ allowTrivialControlsOnLockscreen: Boolean,
+ ) {
+ trySend(CallbackArgs(panelComponent, allowTrivialControlsOnLockscreen))
+ }
+ }
+ underTest.registerListenerForCurrentUser(callback)
+ awaitClose { underTest.unregisterListenerForCurrentUser(callback) }
+ }
+
+ private suspend fun TestScope.setup() {
+ kosmos.fakeUserRepository.setSelectedUserInfo(PRIMARY_USER)
+ kosmos.fakeUserTracker.set(listOf(PRIMARY_USER), 0)
+ kosmos.authorizedPanelsRepository.addAuthorizedPanels(setOf(TEST_PACKAGE))
+ kosmos.selectedComponentRepository.setSelectedComponent(TEST_SELECTED_COMPONENT_PANEL)
+ runCurrent()
+ }
+
+ private data class CallbackArgs(
+ val panelComponent: ComponentName?,
+ val allowTrivialControlsOnLockscreen: Boolean,
+ )
+
+ private fun ControlsServiceInfo(
+ componentName: ComponentName,
+ label: CharSequence,
+ hasPanel: Boolean,
+ ): ControlsServiceInfo {
+ val serviceInfo =
+ ServiceInfo().apply {
+ applicationInfo = ApplicationInfo()
+ packageName = componentName.packageName
+ name = componentName.className
+ }
+ return FakeControlsServiceInfo(context, serviceInfo, label, hasPanel)
+ }
+
+ private class FakeControlsServiceInfo(
+ context: Context,
+ serviceInfo: ServiceInfo,
+ private val label: CharSequence,
+ hasPanel: Boolean,
+ ) : ControlsServiceInfo(context, serviceInfo) {
+
+ init {
+ if (hasPanel) {
+ panelActivity = serviceInfo.componentName
+ }
+ }
+
+ override fun loadLabel(): CharSequence {
+ return label
+ }
+ }
+
+ private companion object {
+ const val PRIMARY_USER_ID = 0
+ val PRIMARY_USER =
+ UserInfo(
+ /* id= */ PRIMARY_USER_ID,
+ /* name= */ "primary user",
+ /* flags= */ UserInfo.FLAG_PRIMARY,
+ )
+
+ private const val TEST_PACKAGE = "pkg"
+ private val TEST_COMPONENT = ComponentName(TEST_PACKAGE, "service")
+ private val TEST_SELECTED_COMPONENT_PANEL =
+ SelectedComponentRepository.SelectedComponent(TEST_PACKAGE, TEST_COMPONENT, true)
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorTest.kt
similarity index 64%
rename from packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorTest.kt
index 7292985..c950523 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorTest.kt
@@ -20,40 +20,32 @@
import android.content.pm.ApplicationInfo
import android.content.pm.ServiceInfo
import android.content.pm.UserInfo
-import android.os.PowerManager
-import android.os.UserHandle
-import android.os.powerManager
-import android.service.dream.dreamManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
-import com.android.systemui.common.data.repository.fakePackageChangeRepository
import com.android.systemui.controls.ControlsServiceInfo
import com.android.systemui.controls.panels.SelectedComponentRepository
import com.android.systemui.controls.panels.authorizedPanelsRepository
import com.android.systemui.controls.panels.selectedComponentRepository
import com.android.systemui.coroutines.collectLastValue
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor.Companion.MAX_UPDATE_CORRELATION_DELAY
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsComponent
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.controlsListingController
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.homeControlsComponentInteractor
import com.android.systemui.kosmos.testScope
import com.android.systemui.settings.fakeUserTracker
import com.android.systemui.testKosmos
import com.android.systemui.user.data.repository.fakeUserRepository
import com.android.systemui.util.mockito.whenever
import com.android.systemui.util.mockito.withArgCaptor
-import com.android.systemui.util.time.fakeSystemClock
import com.google.common.truth.Truth.assertThat
import java.util.Optional
import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentMatchers.anyInt
-import org.mockito.Mockito.anyLong
-import org.mockito.Mockito.never
import org.mockito.Mockito.verify
@OptIn(ExperimentalCoroutinesApi::class)
@@ -68,7 +60,6 @@
@Before
fun setUp() =
with(kosmos) {
- fakeSystemClock.setCurrentTimeMillis(0)
fakeUserRepository.setUserInfos(listOf(PRIMARY_USER, ANOTHER_USER))
whenever(controlsComponent.getControlsListingController())
.thenReturn(Optional.of(controlsListingController))
@@ -172,113 +163,6 @@
}
}
- @Test
- fun testMonitoringUpdatesAndRestart() =
- with(kosmos) {
- testScope.runTest {
- setActiveUser(PRIMARY_USER)
- authorizedPanelsRepository.addAuthorizedPanels(setOf(TEST_PACKAGE))
- selectedComponentRepository.setSelectedComponent(TEST_SELECTED_COMPONENT_PANEL)
- whenever(controlsListingController.getCurrentServices())
- .thenReturn(
- listOf(ControlsServiceInfo(TEST_COMPONENT, "panel", hasPanel = true))
- )
-
- val job = launch { underTest.monitorUpdatesAndRestart() }
- val panelComponent by collectLastValue(underTest.panelComponent)
-
- assertThat(panelComponent).isEqualTo(TEST_COMPONENT)
- verify(dreamManager, never()).startDream()
-
- fakeSystemClock.advanceTime(100)
- // The package update is started.
- fakePackageChangeRepository.notifyUpdateStarted(
- TEST_PACKAGE,
- UserHandle.of(PRIMARY_USER_ID),
- )
- fakeSystemClock.advanceTime(MAX_UPDATE_CORRELATION_DELAY.inWholeMilliseconds)
- // Task fragment becomes empty as a result of the update.
- underTest.onDreamEndUnexpectedly()
-
- runCurrent()
- verify(dreamManager, never()).startDream()
-
- fakeSystemClock.advanceTime(500)
- // The package update is finished.
- fakePackageChangeRepository.notifyUpdateFinished(
- TEST_PACKAGE,
- UserHandle.of(PRIMARY_USER_ID),
- )
-
- runCurrent()
- verify(dreamManager).startDream()
- job.cancel()
- }
- }
-
- @Test
- fun testMonitoringUpdatesAndRestart_dreamEndsAfterDelay() =
- with(kosmos) {
- testScope.runTest {
- setActiveUser(PRIMARY_USER)
- authorizedPanelsRepository.addAuthorizedPanels(setOf(TEST_PACKAGE))
- selectedComponentRepository.setSelectedComponent(TEST_SELECTED_COMPONENT_PANEL)
- whenever(controlsListingController.getCurrentServices())
- .thenReturn(
- listOf(ControlsServiceInfo(TEST_COMPONENT, "panel", hasPanel = true))
- )
-
- val job = launch { underTest.monitorUpdatesAndRestart() }
- val panelComponent by collectLastValue(underTest.panelComponent)
-
- assertThat(panelComponent).isEqualTo(TEST_COMPONENT)
- verify(dreamManager, never()).startDream()
-
- fakeSystemClock.advanceTime(100)
- // The package update is started.
- fakePackageChangeRepository.notifyUpdateStarted(
- TEST_PACKAGE,
- UserHandle.of(PRIMARY_USER_ID),
- )
- fakeSystemClock.advanceTime(MAX_UPDATE_CORRELATION_DELAY.inWholeMilliseconds + 100)
- // Task fragment becomes empty as a result of the update.
- underTest.onDreamEndUnexpectedly()
-
- runCurrent()
- verify(dreamManager, never()).startDream()
-
- fakeSystemClock.advanceTime(500)
- // The package update is finished.
- fakePackageChangeRepository.notifyUpdateFinished(
- TEST_PACKAGE,
- UserHandle.of(PRIMARY_USER_ID),
- )
-
- runCurrent()
- verify(dreamManager, never()).startDream()
- job.cancel()
- }
- }
-
- @Test
- fun testDreamUnexpectedlyEnds_triggersUserActivity() =
- with(kosmos) {
- testScope.runTest {
- fakeSystemClock.setUptimeMillis(100000L)
- verify(powerManager, never()).userActivity(anyLong(), anyInt(), anyInt())
-
- // Dream ends unexpectedly
- underTest.onDreamEndUnexpectedly()
-
- verify(powerManager)
- .userActivity(
- 100000L,
- PowerManager.USER_ACTIVITY_EVENT_OTHER,
- PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS
- )
- }
- }
-
private fun runServicesUpdate(hasPanelBoolean: Boolean = true) {
val listings =
listOf(ControlsServiceInfo(TEST_COMPONENT, "panel", hasPanel = hasPanelBoolean))
@@ -297,7 +181,7 @@
private fun ControlsServiceInfo(
componentName: ComponentName,
label: CharSequence,
- hasPanel: Boolean
+ hasPanel: Boolean,
): ControlsServiceInfo {
val serviceInfo =
ServiceInfo().apply {
@@ -312,7 +196,7 @@
context: Context,
serviceInfo: ServiceInfo,
private val label: CharSequence,
- hasPanel: Boolean
+ hasPanel: Boolean,
) : ControlsServiceInfo(context, serviceInfo) {
init {
@@ -332,7 +216,7 @@
UserInfo(
/* id= */ PRIMARY_USER_ID,
/* name= */ "primary user",
- /* flags= */ UserInfo.FLAG_PRIMARY
+ /* flags= */ UserInfo.FLAG_PRIMARY,
)
private const val ANOTHER_USER_ID = 1
@@ -340,7 +224,7 @@
UserInfo(
/* id= */ ANOTHER_USER_ID,
/* name= */ "another user",
- /* flags= */ UserInfo.FLAG_PRIMARY
+ /* flags= */ UserInfo.FLAG_PRIMARY,
)
private const val TEST_PACKAGE = "pkg"
private val TEST_COMPONENT = ComponentName(TEST_PACKAGE, "service")
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorTest.kt
index a8bb2b0..46d1ebe 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorTest.kt
@@ -31,6 +31,7 @@
import com.android.systemui.coroutines.collectValues
import com.android.systemui.dock.DockManager
import com.android.systemui.dock.DockManagerFake
+import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.flags.FakeFeatureFlags
import com.android.systemui.keyguard.data.quickaffordance.BuiltInKeyguardQuickAffordanceKeys
import com.android.systemui.keyguard.data.quickaffordance.FakeKeyguardQuickAffordanceConfig
@@ -54,6 +55,7 @@
import com.android.systemui.scene.domain.interactor.sceneInteractor
import com.android.systemui.settings.UserFileManager
import com.android.systemui.settings.UserTracker
+import com.android.systemui.shade.cameraLauncher
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
import com.android.systemui.statusbar.policy.KeyguardStateController
@@ -117,8 +119,8 @@
BuiltInKeyguardQuickAffordanceKeys.HOME_CONTROLS,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END +
":" +
- BuiltInKeyguardQuickAffordanceKeys.QUICK_ACCESS_WALLET
- )
+ BuiltInKeyguardQuickAffordanceKeys.QUICK_ACCESS_WALLET,
+ ),
)
repository = FakeKeyguardRepository()
@@ -141,13 +143,7 @@
context = context,
userFileManager =
mock<UserFileManager>().apply {
- whenever(
- getSharedPreferences(
- anyString(),
- anyInt(),
- anyInt(),
- )
- )
+ whenever(getSharedPreferences(anyString(), anyInt(), anyInt()))
.thenReturn(FakeSharedPreferences())
},
userTracker = userTracker,
@@ -181,10 +177,7 @@
featureFlags = FakeFeatureFlags()
val withDeps =
- KeyguardInteractorFactory.create(
- featureFlags = featureFlags,
- repository = repository,
- )
+ KeyguardInteractorFactory.create(featureFlags = featureFlags, repository = repository)
underTest =
KeyguardQuickAffordanceInteractor(
keyguardInteractor = withDeps.keyguardInteractor,
@@ -205,6 +198,7 @@
appContext = context,
sceneInteractor = { kosmos.sceneInteractor },
)
+ kosmos.keyguardQuickAffordanceInteractor = underTest
whenever(shadeInteractor.anyExpansion).thenReturn(MutableStateFlow(0f))
}
@@ -241,9 +235,7 @@
testScope.runTest {
val configKey = BuiltInKeyguardQuickAffordanceKeys.QUICK_ACCESS_WALLET
quickAccessWallet.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue =
@@ -268,9 +260,7 @@
whenever(devicePolicyManager.getKeyguardDisabledFeatures(null, userTracker.userId))
.thenReturn(DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL)
quickAccessWallet.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue by
@@ -287,9 +277,7 @@
whenever(devicePolicyManager.getKeyguardDisabledFeatures(null, userTracker.userId))
.thenReturn(DevicePolicyManager.KEYGUARD_DISABLE_SHORTCUTS_ALL)
quickAccessWallet.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue by
@@ -305,9 +293,7 @@
testScope.runTest {
biometricSettingsRepository.setIsUserInLockdown(true)
quickAccessWallet.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue by
@@ -323,9 +309,7 @@
testScope.runTest {
repository.setIsDozing(true)
homeControls.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue =
@@ -340,9 +324,7 @@
testScope.runTest {
repository.setKeyguardShowing(false)
homeControls.setState(
- KeyguardQuickAffordanceConfig.LockScreenState.Visible(
- icon = ICON,
- )
+ KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
val collectedValue =
@@ -446,7 +428,7 @@
val collectedValue =
collectLastValue(
underTest.quickAffordanceAlwaysVisible(
- KeyguardQuickAffordancePosition.BOTTOM_START,
+ KeyguardQuickAffordancePosition.BOTTOM_START
)
)
assertThat(collectedValue())
@@ -487,10 +469,7 @@
@Test
fun select() =
testScope.runTest {
- overrideResource(
- R.array.config_keyguardQuickAffordanceDefaults,
- arrayOf<String>(),
- )
+ overrideResource(R.array.config_keyguardQuickAffordanceDefaults, arrayOf<String>())
homeControls.setState(
KeyguardQuickAffordanceConfig.LockScreenState.Visible(icon = ICON)
)
@@ -530,10 +509,7 @@
activationState = ActivationState.NotSupported,
)
)
- assertThat(endConfig())
- .isEqualTo(
- KeyguardQuickAffordanceModel.Hidden,
- )
+ assertThat(endConfig()).isEqualTo(KeyguardQuickAffordanceModel.Hidden)
assertThat(underTest.getSelections())
.isEqualTo(
mapOf(
@@ -543,7 +519,7 @@
id = homeControls.key,
name = homeControls.pickerName(),
iconResourceId = homeControls.pickerIconResourceId,
- ),
+ )
),
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to emptyList(),
)
@@ -551,7 +527,7 @@
underTest.select(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
- quickAccessWallet.key
+ quickAccessWallet.key,
)
assertThat(startConfig())
@@ -564,10 +540,7 @@
activationState = ActivationState.NotSupported,
)
)
- assertThat(endConfig())
- .isEqualTo(
- KeyguardQuickAffordanceModel.Hidden,
- )
+ assertThat(endConfig()).isEqualTo(KeyguardQuickAffordanceModel.Hidden)
assertThat(underTest.getSelections())
.isEqualTo(
mapOf(
@@ -577,7 +550,7 @@
id = quickAccessWallet.key,
name = quickAccessWallet.pickerName(),
iconResourceId = quickAccessWallet.pickerIconResourceId,
- ),
+ )
),
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to emptyList(),
)
@@ -614,7 +587,7 @@
id = quickAccessWallet.key,
name = quickAccessWallet.pickerName(),
iconResourceId = quickAccessWallet.pickerIconResourceId,
- ),
+ )
),
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to
listOf(
@@ -622,7 +595,7 @@
id = qrCodeScanner.key,
name = qrCodeScanner.pickerName(),
iconResourceId = qrCodeScanner.pickerIconResourceId,
- ),
+ )
),
)
)
@@ -653,10 +626,7 @@
underTest.select(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END, quickAccessWallet.key)
underTest.unselect(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START, homeControls.key)
- assertThat(startConfig())
- .isEqualTo(
- KeyguardQuickAffordanceModel.Hidden,
- )
+ assertThat(startConfig()).isEqualTo(KeyguardQuickAffordanceModel.Hidden)
assertThat(endConfig())
.isEqualTo(
KeyguardQuickAffordanceModel.Visible(
@@ -677,24 +647,18 @@
id = quickAccessWallet.key,
name = quickAccessWallet.pickerName(),
iconResourceId = quickAccessWallet.pickerIconResourceId,
- ),
+ )
),
)
)
underTest.unselect(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
- quickAccessWallet.key
+ quickAccessWallet.key,
)
- assertThat(startConfig())
- .isEqualTo(
- KeyguardQuickAffordanceModel.Hidden,
- )
- assertThat(endConfig())
- .isEqualTo(
- KeyguardQuickAffordanceModel.Hidden,
- )
+ assertThat(startConfig()).isEqualTo(KeyguardQuickAffordanceModel.Hidden)
+ assertThat(endConfig()).isEqualTo(KeyguardQuickAffordanceModel.Hidden)
assertThat(underTest.getSelections())
.isEqualTo(
mapOf<String, List<String>>(
@@ -768,15 +732,12 @@
id = quickAccessWallet.key,
name = quickAccessWallet.pickerName(),
iconResourceId = quickAccessWallet.pickerIconResourceId,
- ),
+ )
),
)
)
- underTest.unselect(
- KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
- null,
- )
+ underTest.unselect(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END, null)
assertThat(underTest.getSelections())
.isEqualTo(
@@ -787,15 +748,29 @@
)
}
+ @EnableSceneContainer
+ @Test
+ fun updatesLaunchingAffordanceFromCameraLauncher() =
+ testScope.runTest {
+ val launchingAffordance by collectLastValue(underTest.launchingAffordance)
+ runCurrent()
+
+ kosmos.cameraLauncher.setLaunchingAffordance(true)
+ runCurrent()
+ assertThat(launchingAffordance).isTrue()
+
+ kosmos.cameraLauncher.setLaunchingAffordance(false)
+ runCurrent()
+ assertThat(launchingAffordance).isFalse()
+ }
+
companion object {
private const val CONTENT_DESCRIPTION_RESOURCE_ID = 1337
private val ICON: Icon =
Icon.Resource(
res = CONTENT_DESCRIPTION_RESOURCE_ID,
contentDescription =
- ContentDescription.Resource(
- res = CONTENT_DESCRIPTION_RESOURCE_ID,
- ),
+ ContentDescription.Resource(res = CONTENT_DESCRIPTION_RESOURCE_ID),
)
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
index 12eadfc..b5e670c 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
@@ -36,6 +36,7 @@
import com.android.systemui.flags.parameterizeSceneContainerFlag
import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionStep
@@ -82,6 +83,7 @@
private val communalRepository by lazy { kosmos.communalSceneRepository }
private val screenOffAnimationController by lazy { kosmos.screenOffAnimationController }
private val deviceEntryRepository by lazy { kosmos.fakeDeviceEntryRepository }
+ private val pulseExpansionInteractor by lazy { kosmos.pulseExpansionInteractor }
private val notificationsKeyguardInteractor by lazy { kosmos.notificationsKeyguardInteractor }
private val dozeParameters by lazy { kosmos.dozeParameters }
private val shadeTestUtil by lazy { kosmos.shadeTestUtil }
@@ -188,7 +190,7 @@
testScope.runTest {
val isVisible by collectLastValue(underTest.isNotifIconContainerVisible)
runCurrent()
- notificationsKeyguardInteractor.setPulseExpanding(true)
+ pulseExpansionInteractor.setPulseExpanding(true)
deviceEntryRepository.setBypassEnabled(false)
runCurrent()
@@ -200,7 +202,7 @@
testScope.runTest {
val isVisible by collectLastValue(underTest.isNotifIconContainerVisible)
runCurrent()
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(true)
notificationsKeyguardInteractor.setNotificationsFullyHidden(true)
runCurrent()
@@ -219,7 +221,7 @@
to = KeyguardState.DOZING,
testScope,
)
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(false)
whenever(dozeParameters.alwaysOn).thenReturn(false)
notificationsKeyguardInteractor.setNotificationsFullyHidden(true)
@@ -239,7 +241,7 @@
to = KeyguardState.DOZING,
testScope,
)
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(false)
whenever(dozeParameters.alwaysOn).thenReturn(true)
whenever(dozeParameters.displayNeedsBlanking).thenReturn(true)
@@ -260,7 +262,7 @@
to = KeyguardState.DOZING,
testScope,
)
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(false)
whenever(dozeParameters.alwaysOn).thenReturn(true)
whenever(dozeParameters.displayNeedsBlanking).thenReturn(false)
@@ -276,7 +278,7 @@
testScope.runTest {
val isVisible by collectLastValue(underTest.isNotifIconContainerVisible)
runCurrent()
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(true)
whenever(dozeParameters.alwaysOn).thenReturn(true)
whenever(dozeParameters.displayNeedsBlanking).thenReturn(false)
@@ -298,7 +300,7 @@
testScope.runTest {
val isVisible by collectLastValue(underTest.isNotifIconContainerVisible)
runCurrent()
- notificationsKeyguardInteractor.setPulseExpanding(false)
+ pulseExpansionInteractor.setPulseExpanding(false)
deviceEntryRepository.setBypassEnabled(false)
whenever(dozeParameters.alwaysOn).thenReturn(true)
whenever(dozeParameters.displayNeedsBlanking).thenReturn(false)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
index 4995920..2c8f7cf 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
@@ -32,6 +32,7 @@
import com.android.internal.logging.uiEventLoggerFake
import com.android.internal.policy.IKeyguardDismissCallback
import com.android.keyguard.AuthInteractionProperties
+import com.android.keyguard.keyguardUpdateMonitor
import com.android.systemui.Flags
import com.android.systemui.SysuiTestCase
import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
@@ -71,8 +72,6 @@
import com.android.systemui.keyguard.domain.interactor.keyguardEnabledInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.keyguard.domain.interactor.scenetransition.lockscreenSceneTransitionInteractor
-import com.android.systemui.keyguard.shared.model.BiometricUnlockMode
-import com.android.systemui.keyguard.shared.model.BiometricUnlockSource
import com.android.systemui.keyguard.shared.model.FailFingerprintAuthenticationStatus
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
@@ -128,6 +127,7 @@
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
+import org.mockito.kotlin.whenever
@SmallTest
@RunWith(AndroidJUnit4::class)
@@ -159,7 +159,8 @@
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
-
+ whenever(kosmos.keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean()))
+ .thenReturn(true)
underTest = kosmos.sceneContainerStartable
}
@@ -405,10 +406,7 @@
assertThat(currentSceneKey).isEqualTo(Scenes.Bouncer)
underTest.start()
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
-
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@@ -430,10 +428,7 @@
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
underTest.start()
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
-
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
assertThat(alternateBouncerVisible).isFalse()
}
@@ -464,9 +459,7 @@
runCurrent()
assertThat(currentSceneKey).isEqualTo(Scenes.QuickSettings)
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
assertThat(currentSceneKey).isEqualTo(Scenes.QuickSettings)
@@ -501,10 +494,7 @@
assertThat(currentSceneKey).isEqualTo(Scenes.Bouncer)
assertThat(backStack?.asIterable()?.last()).isEqualTo(Scenes.Lockscreen)
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
-
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(currentSceneKey).isEqualTo(Scenes.QuickSettings)
assertThat(backStack?.asIterable()?.last()).isEqualTo(Scenes.Gone)
}
@@ -535,10 +525,7 @@
runCurrent()
assertThat(currentSceneKey).isEqualTo(Scenes.Bouncer)
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
-
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@@ -554,10 +541,7 @@
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
underTest.start()
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
-
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@@ -592,9 +576,7 @@
transitionStateFlowValue.value = ObservableTransitionState.Idle(Scenes.Shade)
assertThat(currentSceneKey).isEqualTo(Scenes.Shade)
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
assertThat(currentSceneKey).isEqualTo(Scenes.Shade)
@@ -786,6 +768,7 @@
@DisableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun playSuccessHaptics_onSuccessfulLockscreenAuth_udfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -795,24 +778,19 @@
assertThat(kosmos.deviceEntryInteractor.isDeviceEntered.value).isFalse()
underTest.start()
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNotNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper)
- .vibrateAuthSuccess(
- "SceneContainerStartable, $currentSceneKey device-entry::success"
- )
+ verify(vibratorHelper).vibrateAuthSuccess(anyString())
verify(vibratorHelper, never()).vibrateAuthError(anyString())
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@EnableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun playSuccessMSDLHaptics_onSuccessfulLockscreenAuth_udfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -822,21 +800,19 @@
assertThat(kosmos.deviceEntryInteractor.isDeviceEntered.value).isFalse()
underTest.start()
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNotNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isEqualTo(MSDLToken.UNLOCK)
assertThat(msdlPlayer.latestPropertiesPlayed).isEqualTo(authInteractionProperties)
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@DisableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun playSuccessHaptics_onSuccessfulLockscreenAuth_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -847,24 +823,19 @@
underTest.start()
allowHapticsOnSfps()
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNotNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper)
- .vibrateAuthSuccess(
- "SceneContainerStartable, $currentSceneKey device-entry::success"
- )
+ verify(vibratorHelper).vibrateAuthSuccess(anyString())
verify(vibratorHelper, never()).vibrateAuthError(anyString())
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@EnableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun playSuccessMSDLHaptics_onSuccessfulLockscreenAuth_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -875,15 +846,12 @@
underTest.start()
allowHapticsOnSfps()
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNotNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isEqualTo(MSDLToken.UNLOCK)
assertThat(msdlPlayer.latestPropertiesPlayed).isEqualTo(authInteractionProperties)
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@@ -902,8 +870,7 @@
assertThat(playErrorHaptic).isNotNull()
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper)
- .vibrateAuthError("SceneContainerStartable, $currentSceneKey device-entry::error")
+ verify(vibratorHelper).vibrateAuthError(anyString())
verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
}
@@ -943,8 +910,7 @@
assertThat(playErrorHaptic).isNotNull()
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper)
- .vibrateAuthError("SceneContainerStartable, $currentSceneKey device-entry::error")
+ verify(vibratorHelper).vibrateAuthError(anyString())
verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
}
@@ -972,6 +938,7 @@
@DisableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun skipsSuccessHaptics_whenPowerButtonDown_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -982,24 +949,19 @@
underTest.start()
allowHapticsOnSfps(isPowerButtonDown = true)
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper, never())
- .vibrateAuthSuccess(
- "SceneContainerStartable, $currentSceneKey device-entry::success"
- )
+ verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
verify(vibratorHelper, never()).vibrateAuthError(anyString())
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@EnableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun skipsMSDLSuccessHaptics_whenPowerButtonDown_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -1010,21 +972,19 @@
underTest.start()
allowHapticsOnSfps(isPowerButtonDown = true)
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isNull()
assertThat(msdlPlayer.latestPropertiesPlayed).isNull()
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@DisableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun skipsSuccessHaptics_whenPowerButtonRecentlyPressed_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -1035,24 +995,19 @@
underTest.start()
allowHapticsOnSfps(lastPowerPress = 50)
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper, never())
- .vibrateAuthSuccess(
- "SceneContainerStartable, $currentSceneKey device-entry::success"
- )
+ verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
verify(vibratorHelper, never()).vibrateAuthError(anyString())
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@EnableFlags(Flags.FLAG_MSDL_FEEDBACK)
fun skipsMSDLSuccessHaptics_whenPowerButtonRecentlyPressed_sfps() =
testScope.runTest {
+ whenever(kosmos.keyguardUpdateMonitor.isDeviceInteractive).thenReturn(true)
val currentSceneKey by collectLastValue(sceneInteractor.currentScene)
val playSuccessHaptic by
collectLastValue(deviceEntryHapticsInteractor.playSuccessHaptic)
@@ -1063,15 +1018,12 @@
underTest.start()
allowHapticsOnSfps(lastPowerPress = 50)
- unlockWithFingerprintAuth()
+ // unlock with fingerprint
+ updateFingerprintAuthStatus(isSuccess = true)
assertThat(playSuccessHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isNull()
assertThat(msdlPlayer.latestPropertiesPlayed).isNull()
-
- updateFingerprintAuthStatus(isSuccess = true)
- assertThat(currentSceneKey).isEqualTo(Scenes.Gone)
}
@Test
@@ -1090,9 +1042,7 @@
updateFingerprintAuthStatus(isSuccess = false)
assertThat(playErrorHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper, never())
- .vibrateAuthError("SceneContainerStartable, $currentSceneKey device-entry::error")
+ verify(vibratorHelper, never()).vibrateAuthError(anyString())
verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
}
@@ -1112,7 +1062,6 @@
updateFingerprintAuthStatus(isSuccess = false)
assertThat(playErrorHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isNull()
assertThat(msdlPlayer.latestPropertiesPlayed).isNull()
}
@@ -1132,9 +1081,7 @@
updateFaceAuthStatus(isSuccess = false)
assertThat(playErrorHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
- verify(vibratorHelper, never())
- .vibrateAuthError("SceneContainerStartable, $currentSceneKey device-entry::error")
+ verify(vibratorHelper, never()).vibrateAuthError(anyString())
verify(vibratorHelper, never()).vibrateAuthSuccess(anyString())
}
@@ -1153,7 +1100,6 @@
updateFaceAuthStatus(isSuccess = false)
assertThat(playErrorHaptic).isNull()
- assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
assertThat(msdlPlayer.latestTokenPlayed).isNull()
assertThat(msdlPlayer.latestPropertiesPlayed).isNull()
}
@@ -1176,9 +1122,7 @@
)
.forEachIndexed { index, sceneKey ->
if (sceneKey == Scenes.Gone) {
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
}
fakeSceneDataSource.pause()
@@ -1334,9 +1278,7 @@
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
underTest.start()
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
powerInteractor.setAwakeForTest()
runCurrent()
@@ -1586,9 +1528,7 @@
runCurrent()
verify(falsingCollector).onBouncerShown()
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
sceneInteractor.changeScene(Scenes.Gone, "reason")
runCurrent()
@@ -2350,9 +2290,7 @@
val dismissCallback: IKeyguardDismissCallback = mock()
kosmos.dismissCallbackRegistry.addCallback(dismissCallback)
- kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
- SuccessFingerprintAuthenticationStatus(0, true)
- )
+ updateFingerprintAuthStatus(isSuccess = true)
runCurrent()
kosmos.fakeExecutor.runAllReady()
@@ -2641,13 +2579,6 @@
runCurrent()
}
- private fun unlockWithFingerprintAuth() {
- kosmos.fakeKeyguardRepository.setBiometricUnlockSource(
- BiometricUnlockSource.FINGERPRINT_SENSOR
- )
- kosmos.fakeKeyguardRepository.setBiometricUnlockState(BiometricUnlockMode.UNLOCK_COLLAPSING)
- }
-
private fun TestScope.setupBiometricAuth(
hasSfps: Boolean = false,
hasUdfps: Boolean = false,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
index ea2de25..01c17bd 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
@@ -619,7 +619,8 @@
mScreenOffAnimationController,
new NotificationWakeUpCoordinatorLogger(logcatLogBuffer()),
notifsKeyguardInteractor,
- mKosmos.getCommunalInteractor());
+ mKosmos.getCommunalInteractor(),
+ mKosmos.getPulseExpansionInteractor());
mConfigurationController = new ConfigurationControllerImpl(mContext);
PulseExpansionHandler expansionHandler = new PulseExpansionHandler(
mContext,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
index 9f752a8..3b5d358 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
@@ -26,6 +26,7 @@
import com.android.systemui.communal.domain.interactor.communalInteractor
import com.android.systemui.communal.shared.model.CommunalScenes
import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
import com.android.systemui.kosmos.applicationCoroutineScope
import com.android.systemui.kosmos.testScope
import com.android.systemui.log.logcatLogBuffer
@@ -86,6 +87,7 @@
private var bypassEnabled: Boolean = false
private var statusBarState: Int = StatusBarState.KEYGUARD
+
private fun eased(dozeAmount: Float) =
notificationWakeUpCoordinator.dozeAmountInterpolator.getInterpolation(dozeAmount)
@@ -119,6 +121,7 @@
logger,
kosmos.notificationsKeyguardInteractor,
kosmos.communalInteractor,
+ kosmos.pulseExpansionInteractor,
)
statusBarStateCallback = withArgCaptor {
verify(statusBarStateController).addCallback(capture())
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractorTest.kt
index 133a114..dcc8ecd 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractorTest.kt
@@ -58,19 +58,4 @@
assertThat(notifsFullyHidden).isTrue()
}
-
- @Test
- fun isPulseExpanding_reflectsRepository() =
- testComponent.runTest {
- underTest.setPulseExpanding(false)
- val isPulseExpanding by collectLastValue(underTest.isPulseExpanding)
- runCurrent()
-
- assertThat(isPulseExpanding).isFalse()
-
- underTest.setPulseExpanding(true)
- runCurrent()
-
- assertThat(isPulseExpanding).isTrue()
- }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
index 2349c25..07935e4 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
@@ -16,10 +16,12 @@
package com.android.systemui.statusbar.notification.stack
-import androidx.test.ext.junit.runners.AndroidJUnit4
+import android.platform.test.flag.junit.FlagsParameterization
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.dump.DumpManager
+import com.android.systemui.flags.DisableSceneContainer
+import com.android.systemui.flags.andSceneContainer
import com.android.systemui.shade.transition.LargeScreenShadeInterpolator
import com.android.systemui.statusbar.StatusBarState
import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager
@@ -30,12 +32,14 @@
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4
+import platform.test.runner.parameterized.Parameters
private const val MAX_PULSE_HEIGHT = 100000f
-@RunWith(AndroidJUnit4::class)
+@RunWith(ParameterizedAndroidJunit4::class)
@SmallTest
-class AmbientStateTest : SysuiTestCase() {
+class AmbientStateTest(flags: FlagsParameterization) : SysuiTestCase() {
private val dumpManager = mock<DumpManager>()
private val sectionProvider = StackScrollAlgorithm.SectionProvider { _, _ -> false }
@@ -46,6 +50,18 @@
private lateinit var sut: AmbientState
+ companion object {
+ @JvmStatic
+ @Parameters(name = "{0}")
+ fun getParams(): List<FlagsParameterization> {
+ return FlagsParameterization.allCombinationsOf().andSceneContainer()
+ }
+ }
+
+ init {
+ mSetFlagsRule.setFlagsParameterization(flags)
+ }
+
@Before
fun setUp() {
sut =
@@ -56,7 +72,7 @@
bypassController,
statusBarKeyguardViewManager,
largeScreenShadeInterpolator,
- avalancheController
+ avalancheController,
)
}
@@ -97,6 +113,7 @@
assertThat(sut.pulseHeight).isEqualTo(expected)
}
+
// endregion
// region statusBarState
@@ -119,6 +136,7 @@
assertThat(sut.isFlingRequiredAfterLockScreenSwipeUp).isTrue()
}
+
// endregion
// region hideAmount
@@ -141,6 +159,7 @@
assertThat(sut.pulseHeight).isEqualTo(1f)
}
+
// endregion
// region dozeAmount
@@ -173,6 +192,7 @@
assertThat(sut.pulseHeight).isEqualTo(1f)
}
+
// endregion
// region trackedHeadsUpRow
@@ -189,10 +209,12 @@
assertThat(sut.trackedHeadsUpRow).isNull()
}
+
// endregion
// region isSwipingUp
@Test
+ @DisableSceneContainer
fun isSwipingUp_whenValueChangedToTrue_shouldRequireFling() {
sut.isSwipingUp = false
sut.isFlingRequiredAfterLockScreenSwipeUp = false
@@ -203,6 +225,7 @@
}
@Test
+ @DisableSceneContainer
fun isSwipingUp_whenValueChangedToFalse_shouldRequireFling() {
sut.isSwipingUp = true
sut.isFlingRequiredAfterLockScreenSwipeUp = false
@@ -211,10 +234,12 @@
assertThat(sut.isFlingRequiredAfterLockScreenSwipeUp).isTrue()
}
+
// endregion
// region isFlinging
@Test
+ @DisableSceneContainer
fun isFlinging_shouldNotNeedFling() {
sut.arrangeFlinging(true)
@@ -224,6 +249,7 @@
}
@Test
+ @DisableSceneContainer
fun isFlinging_whenNotOnLockScreen_shouldDoNothing() {
sut.arrangeFlinging(true)
sut.setStatusBarState(StatusBarState.SHADE)
@@ -235,6 +261,7 @@
}
@Test
+ @DisableSceneContainer
fun isFlinging_whenValueChangedToTrue_shouldDoNothing() {
sut.arrangeFlinging(false)
@@ -242,10 +269,12 @@
assertThat(sut.isFlingRequiredAfterLockScreenSwipeUp).isTrue()
}
+
// endregion
// region scrollY
@Test
+ @DisableSceneContainer
fun scrollY_shouldSetValueGreaterThanZero() {
sut.scrollY = 0
@@ -255,6 +284,7 @@
}
@Test
+ @DisableSceneContainer
fun scrollY_shouldNotSetValueLessThanZero() {
sut.scrollY = 0
@@ -262,21 +292,24 @@
assertThat(sut.scrollY).isEqualTo(0)
}
+
// endregion
// region setOverScrollAmount
+ @Test
+ @DisableSceneContainer
fun setOverScrollAmount_shouldSetValueOnTop() {
- sut.setOverScrollAmount(/* amount = */ 10f, /* onTop = */ true)
+ sut.setOverScrollAmount(/* amount= */ 10f, /* onTop= */ true)
- val resultOnTop = sut.getOverScrollAmount(/* top = */ true)
- val resultOnBottom = sut.getOverScrollAmount(/* top = */ false)
+ val resultOnTop = sut.getOverScrollAmount(/* top= */ true)
+ val resultOnBottom = sut.getOverScrollAmount(/* top= */ false)
assertThat(resultOnTop).isEqualTo(10f)
assertThat(resultOnBottom).isEqualTo(0f)
}
fun setOverScrollAmount_shouldSetValueOnBottom() {
- sut.setOverScrollAmount(/* amount = */ 10f, /* onTop = */ false)
+ sut.setOverScrollAmount(/* amount= */ 10f, /* onTop= */ false)
val resultOnTop = sut.getOverScrollAmount(/* top */ true)
val resultOnBottom = sut.getOverScrollAmount(/* top */ false)
@@ -284,6 +317,7 @@
assertThat(resultOnTop).isEqualTo(0f)
assertThat(resultOnBottom).isEqualTo(10f)
}
+
// endregion
// region IsPulseExpanding
@@ -317,6 +351,7 @@
assertThat(sut.isPulseExpanding).isFalse()
}
+
// endregion
// region isOnKeyguard
@@ -333,6 +368,7 @@
assertThat(sut.isOnKeyguard).isFalse()
}
+
// endregion
// region mIsClosing
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 d5a7c89..a940ed4 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
@@ -19,6 +19,7 @@
package com.android.systemui.statusbar.notification.stack.ui.viewmodel
+import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.FlagsParameterization
import androidx.test.filters.SmallTest
@@ -66,10 +67,13 @@
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.mockLargeScreenHeaderHelper
import com.android.systemui.shade.shadeTestUtil
+import com.android.systemui.shade.shared.flag.DualShade
import com.android.systemui.statusbar.notification.stack.domain.interactor.sharedNotificationContainerInteractor
+import com.android.systemui.statusbar.notification.stack.ui.viewmodel.SharedNotificationContainerViewModel.HorizontalPosition
import com.android.systemui.testKosmos
import com.google.common.collect.Range
import com.google.common.truth.Truth.assertThat
+import kotlin.test.assertIs
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
@@ -165,6 +169,83 @@
}
@Test
+ fun validateHorizontalPositionSingleShade() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(false)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.EdgeToEdge>(horizontalPosition)
+ }
+
+ @Test
+ fun validateHorizontalPositionSplitShade() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(true)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.MiddleToEdge>(horizontalPosition)
+ assertThat(horizontalPosition.ratio).isEqualTo(0.5f)
+ }
+
+ @Test
+ @EnableSceneContainer
+ @DisableFlags(DualShade.FLAG_NAME)
+ fun validateHorizontalPositionInSceneContainerSingleShade() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(false)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.EdgeToEdge>(horizontalPosition)
+ }
+
+ @Test
+ @EnableSceneContainer
+ @DisableFlags(DualShade.FLAG_NAME)
+ fun validateHorizontalPositionInSceneContainerSplitShade() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(true)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.MiddleToEdge>(horizontalPosition)
+ assertThat(horizontalPosition.ratio).isEqualTo(0.5f)
+ }
+
+ @Test
+ @EnableSceneContainer
+ @EnableFlags(DualShade.FLAG_NAME)
+ fun validateHorizontalPositionInDualShade_narrowLayout() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(false)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.EdgeToEdge>(horizontalPosition)
+ }
+
+ @Test
+ @EnableSceneContainer
+ @EnableFlags(DualShade.FLAG_NAME)
+ fun validateHorizontalPositionInDualShade_wideLayout() =
+ testScope.runTest {
+ overrideDimensionPixelSize(R.dimen.shade_panel_width, 200)
+ val dimens by collectLastValue(underTest.configurationBasedDimensions)
+ shadeTestUtil.setSplitShade(true)
+
+ val horizontalPosition = checkNotNull(dimens).horizontalPosition
+ assertIs<HorizontalPosition.FloatAtEnd>(horizontalPosition)
+ assertThat(horizontalPosition.width).isEqualTo(200)
+ }
+
+ @Test
fun validatePaddingTopInSplitShade_usesLargeHeaderHelper() =
testScope.runTest {
whenever(largeScreenHeaderHelper.getLargeScreenHeaderHeight()).thenReturn(5)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/domain/interactor/KeyguardBypassInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/domain/interactor/KeyguardBypassInteractorTest.kt
new file mode 100644
index 0000000..c90183d
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/domain/interactor/KeyguardBypassInteractorTest.kt
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.phone.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.bouncer.data.repository.keyguardBouncerRepository
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.EnableSceneContainer
+import com.android.systemui.keyguard.data.repository.configureKeyguardBypass
+import com.android.systemui.keyguard.domain.interactor.KeyguardBypassInteractor
+import com.android.systemui.keyguard.domain.interactor.keyguardBypassInteractor
+import com.android.systemui.keyguard.domain.interactor.keyguardQuickAffordanceInteractor
+import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.shade.shadeTestUtil
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+@EnableSceneContainer
+class KeyguardBypassInteractorTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+ private lateinit var underTest: KeyguardBypassInteractor
+
+ @Test
+ fun canBypassFalseWhenBypassAvailableFalse() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipIsBypassAvailableCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isFalse()
+ }
+
+ @Test
+ fun canBypassTrueOnPrimaryBouncerShowing() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipBouncerShowingCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isTrue()
+ }
+
+ @Test
+ fun canBypassTrueOnAlternateBouncerShowing() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipAlternateBouncerShowingCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isTrue()
+ }
+
+ @Test
+ fun canBypassFalseWhenNotOnLockscreenScene() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipOnLockscreenSceneCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ val currentScene by collectLastValue(kosmos.sceneInteractor.currentScene)
+ runCurrent()
+ assertThat(currentScene).isNotEqualTo(Scenes.Lockscreen)
+ assertThat(canBypass).isFalse()
+ }
+
+ @Test
+ fun canBypassFalseOnLaunchingAffordance() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipLaunchingAffordanceCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isFalse()
+ }
+
+ @Test
+ fun canBypassFalseOnPulseExpanding() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipPulseExpandingCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isFalse()
+ }
+
+ @Test
+ fun canBypassFalseOnQsExpanded() =
+ testScope.runTest {
+ initializeDependenciesForCanBypass(skipQsExpandedCheck = false)
+ val canBypass by collectLastValue(underTest.canBypass)
+ runCurrent()
+ assertThat(canBypass).isFalse()
+ }
+
+ // Initializes all canBypass dependencies to opposite of value needed to return
+ private fun initializeDependenciesForCanBypass(
+ skipIsBypassAvailableCheck: Boolean = true,
+ skipBouncerShowingCheck: Boolean = true,
+ skipAlternateBouncerShowingCheck: Boolean = true,
+ skipOnLockscreenSceneCheck: Boolean = true,
+ skipLaunchingAffordanceCheck: Boolean = true,
+ skipPulseExpandingCheck: Boolean = true,
+ skipQsExpandedCheck: Boolean = true,
+ ) {
+ // !isBypassAvailable false
+ kosmos.configureKeyguardBypass(isBypassAvailable = skipIsBypassAvailableCheck)
+ underTest = kosmos.keyguardBypassInteractor
+
+ // bouncerShowing false, !onLockscreenScene false
+ // !onLockscreenScene false
+ setScene(
+ bouncerShowing = !skipBouncerShowingCheck,
+ onLockscreenScene = skipOnLockscreenSceneCheck,
+ )
+ // alternateBouncerShowing false
+ setAlternateBouncerShowing(!skipAlternateBouncerShowingCheck)
+ // launchingAffordance false
+ setLaunchingAffordance(!skipLaunchingAffordanceCheck)
+ // pulseExpanding false
+ setPulseExpanding(!skipPulseExpandingCheck)
+ // qsExpanding false
+ setQsExpanded(!skipQsExpandedCheck)
+ }
+
+ private fun setAlternateBouncerShowing(alternateBouncerVisible: Boolean) {
+ kosmos.keyguardBouncerRepository.setAlternateVisible(alternateBouncerVisible)
+ }
+
+ private fun setScene(bouncerShowing: Boolean, onLockscreenScene: Boolean) {
+ if (bouncerShowing) {
+ kosmos.sceneInteractor.changeScene(Scenes.Bouncer, "reason")
+ } else if (onLockscreenScene) {
+ kosmos.sceneInteractor.changeScene(Scenes.Lockscreen, "reason")
+ } else {
+ kosmos.sceneInteractor.changeScene(Scenes.Shade, "reason")
+ }
+ }
+
+ private fun setLaunchingAffordance(launchingAffordance: Boolean) {
+ kosmos.keyguardQuickAffordanceInteractor.setLaunchingAffordance(launchingAffordance)
+ }
+
+ private fun setPulseExpanding(pulseExpanding: Boolean) {
+ kosmos.pulseExpansionInteractor.setPulseExpanding(pulseExpanding)
+ }
+
+ private fun setQsExpanded(qsExpanded: Boolean) {
+ if (qsExpanded) {
+ kosmos.shadeTestUtil.setQsExpansion(1f)
+ } else {
+ kosmos.shadeTestUtil.setQsExpansion(0f)
+ }
+ }
+}
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt b/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
index e264264..5792175 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/clocks/ClockProviderPlugin.kt
@@ -203,12 +203,12 @@
fun onZenDataChanged(data: ZenData)
/** Update reactive axes for this clock */
- fun onReactiveAxesChanged(axes: List<ClockReactiveSetting>)
+ fun onFontAxesChanged(axes: List<ClockFontAxisSetting>)
}
/** Axis setting value for a clock */
-data class ClockReactiveSetting(
- /** Axis key; matches ClockReactiveAxis.key */
+data class ClockFontAxisSetting(
+ /** Axis key; matches ClockFontAxis.key */
val key: String,
/** Value to set this axis to */
@@ -323,11 +323,11 @@
val isReactiveToTone: Boolean = true,
/** Font axes that can be modified on this clock */
- val axes: List<ClockReactiveAxis> = listOf(),
+ val axes: List<ClockFontAxis> = listOf(),
)
/** Represents an Axis that can be modified */
-data class ClockReactiveAxis(
+data class ClockFontAxis(
/** Axis key, not user renderable */
val key: String,
@@ -348,15 +348,17 @@
/** Description of the axis */
val description: String,
-)
+) {
+ fun toSetting() = ClockFontAxisSetting(key, currentValue)
+}
/** Axis user interaction modes */
enum class AxisType {
- /** Boolean toggle. Swaps between minValue & maxValue */
- Toggle,
+ /** Continuous range between minValue & maxValue. */
+ Float,
- /** Continuous slider between minValue & maxValue */
- Slider,
+ /** Only minValue & maxValue are valid. No intermediate values between them are allowed. */
+ Boolean,
}
/** Render configuration for the full clock. Modifies the way systemUI behaves with this clock. */
@@ -404,7 +406,7 @@
data class ClockSettings(
val clockId: ClockId? = null,
val seedColor: Int? = null,
- val axes: List<ClockReactiveSetting>? = null,
+ val axes: List<ClockFontAxisSetting>? = null,
) {
// Exclude metadata from equality checks
var metadata: JSONObject = JSONObject()
diff --git a/packages/SystemUI/res/values-sw720dp-h1000dp/dimens.xml b/packages/SystemUI/res/values-sw720dp-h1000dp/dimens.xml
index ca62d28..f38f42d 100644
--- a/packages/SystemUI/res/values-sw720dp-h1000dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw720dp-h1000dp/dimens.xml
@@ -23,4 +23,7 @@
<dimen name="keyguard_clock_top_margin">80dp</dimen>
<dimen name="bouncer_user_switcher_view_mode_user_switcher_bottom_margin">155dp</dimen>
<dimen name="bouncer_user_switcher_view_mode_view_flipper_bottom_margin">85dp</dimen>
+
+ <!-- The width of the shade overlay panel (both notifications and quick settings). -->
+ <dimen name="shade_panel_width">474dp</dimen>
</resources>
diff --git a/packages/SystemUI/res/values-sw800dp/dimens.xml b/packages/SystemUI/res/values-sw800dp/dimens.xml
index 0d82217..8ae3a2e 100644
--- a/packages/SystemUI/res/values-sw800dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw800dp/dimens.xml
@@ -21,4 +21,7 @@
<!-- Biometric Auth pattern view size, better to align keyguard_security_width -->
<dimen name="biometric_auth_pattern_view_size">348dp</dimen>
+
+ <!-- The width of the shade overlay panel (both notifications and quick settings). -->
+ <dimen name="shade_panel_width">392dp</dimen>
</resources>
diff --git a/packages/SystemUI/res/values-w1000dp/dimens.xml b/packages/SystemUI/res/values-w1000dp/dimens.xml
new file mode 100644
index 0000000..b3f7acd
--- /dev/null
+++ b/packages/SystemUI/res/values-w1000dp/dimens.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2024 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<resources>
+ <!-- The width of the shade overlay panel (both notifications and quick settings). -->
+ <dimen name="shade_panel_width">474dp</dimen>
+</resources>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index f96a0b9..d4a52c3 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -338,6 +338,9 @@
<!-- Whether to show the full screen user switcher. -->
<bool name="config_enableFullscreenUserSwitcher">false</bool>
+ <!-- Whether to go to the launcher when unlocking via an occluding app -->
+ <bool name="config_goToHomeFromOccludedApps">false</bool>
+
<!-- Determines whether the shell features all run on another thread. -->
<bool name="config_enableShellMainThread">true</bool>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index c2d942f..de547ad 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -577,6 +577,13 @@
<dimen name="notification_panel_margin_horizontal">0dp</dimen>
+ <!--
+ The width of the shade overlay panel (both notifications and quick settings). On Compact screens
+ in portrait orientation (< w600dp) this is ignored, and the shade layout takes up the full
+ screen width.
+ -->
+ <dimen name="shade_panel_width">412dp</dimen>
+
<dimen name="brightness_mirror_height">48dp</dimen>
<dimen name="volume_dialog_panel_transparent_padding_right">8dp</dimen>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 9602163..ab64ae5 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -3930,10 +3930,10 @@
</string>
<!-- Title for the Reset Tiles dialog in QS Edit mode. [CHAR LIMIT=NONE] -->
<string name="qs_edit_mode_reset_dialog_title">
- Reset tiles
+ Reset all tiles?
</string>
<!-- Content of the Reset Tiles dialog in QS Edit mode. [CHAR LIMIT=NONE] -->
<string name="qs_edit_mode_reset_dialog_content">
- Reset tiles to their original order and sizes?
+ All Quick Settings tiles will reset to the device’s original settings
</string>
</resources>
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 69ab976..959ab64 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -323,7 +323,7 @@
final boolean isLandscape = mContext.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
mPromptSelectorInteractorProvider = promptSelectorInteractorProvider;
- mPromptSelectorInteractorProvider.get().setPrompt(mConfig.mPromptInfo, mEffectiveUserId,
+ mPromptSelectorInteractorProvider.get().setPrompt(mConfig.mPromptInfo, mConfig.mUserId,
getRequestId(), biometricModalities, mConfig.mOperationId, mConfig.mOpPackageName,
false /*onSwitchToCredential*/, isLandscape);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
index 4997370..b070068 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
@@ -3,6 +3,7 @@
import android.app.admin.DevicePolicyManager
import android.app.admin.DevicePolicyResources
import android.content.Context
+import android.hardware.biometrics.Flags
import android.os.UserManager
import com.android.internal.widget.LockPatternUtils
import com.android.internal.widget.LockscreenCredential
@@ -71,13 +72,22 @@
// Request LockSettingsService to return the Gatekeeper Password in the
// VerifyCredentialResponse so that we can request a Gatekeeper HAT with the
// Gatekeeper Password and operationId.
- val effectiveUserId = request.userInfo.deviceCredentialOwnerId
+ var effectiveUserId = request.userInfo.userIdForPasswordEntry
val response =
- lockPatternUtils.verifyCredential(
- credential,
- effectiveUserId,
- LockPatternUtils.VERIFY_FLAG_REQUEST_GK_PW_HANDLE
- )
+ if (Flags.privateSpaceBp() && effectiveUserId != request.userInfo.userId) {
+ effectiveUserId = request.userInfo.userId
+ lockPatternUtils.verifyTiedProfileChallenge(
+ credential,
+ request.userInfo.userId,
+ LockPatternUtils.VERIFY_FLAG_REQUEST_GK_PW_HANDLE,
+ )
+ } else {
+ lockPatternUtils.verifyCredential(
+ credential,
+ effectiveUserId,
+ LockPatternUtils.VERIFY_FLAG_REQUEST_GK_PW_HANDLE,
+ )
+ }
if (response.isMatched) {
lockPatternUtils.userPresent(effectiveUserId)
@@ -91,7 +101,7 @@
lockPatternUtils.verifyGatekeeperPasswordHandle(
pwHandle,
request.operationInfo.gatekeeperChallenge,
- effectiveUserId
+ effectiveUserId,
)
val hat = gkResponse.gatekeeperHAT
lockPatternUtils.removeGatekeeperPasswordHandle(pwHandle)
@@ -108,7 +118,7 @@
CredentialStatus.Fail.Throttled(
applicationContext.getString(
R.string.biometric_dialog_credential_too_many_attempts,
- remaining / 1000
+ remaining / 1000,
)
)
)
@@ -129,10 +139,10 @@
applicationContext.getString(
R.string.biometric_dialog_credential_attempts_before_wipe,
numAttempts,
- maxAttempts
+ maxAttempts,
),
remainingAttempts,
- fetchFinalAttemptMessageOrNull(request, remainingAttempts)
+ fetchFinalAttemptMessageOrNull(request, remainingAttempts),
)
)
}
@@ -150,9 +160,9 @@
devicePolicyManager,
userManager.getUserTypeForWipe(
devicePolicyManager,
- request.userInfo.deviceCredentialOwnerId
+ request.userInfo.deviceCredentialOwnerId,
),
- remainingAttempts
+ remainingAttempts,
)
} else {
null
@@ -205,7 +215,7 @@
}
private fun Context.getLastAttemptBeforeWipeDeviceMessage(
- request: BiometricPromptRequest.Credential,
+ request: BiometricPromptRequest.Credential
): String {
val id =
when (request) {
@@ -249,7 +259,7 @@
}
private fun Context.getLastAttemptBeforeWipeUserMessage(
- request: BiometricPromptRequest.Credential,
+ request: BiometricPromptRequest.Credential
): String {
val resId =
when (request) {
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 6da5e42..f1df5ca 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
@@ -104,6 +104,7 @@
constructor(
fingerprintPropertyRepository: FingerprintPropertyRepository,
private val displayStateInteractor: DisplayStateInteractor,
+ private val credentialInteractor: CredentialInteractor,
private val promptRepository: PromptRepository,
private val lockPatternUtils: LockPatternUtils,
) : PromptSelectorInteractor {
@@ -177,7 +178,7 @@
override fun setPrompt(
promptInfo: PromptInfo,
- effectiveUserId: Int,
+ userId: Int,
requestId: Long,
modalities: BiometricModalities,
challenge: Long,
@@ -185,6 +186,7 @@
onSwitchToCredential: Boolean,
isLandscape: Boolean,
) {
+ val effectiveUserId = credentialInteractor.getCredentialOwnerOrSelfId(userId)
val hasCredentialViewShown = promptKind.value.isCredential()
val showBpForCredential =
Flags.customBiometricPrompt() &&
@@ -211,10 +213,7 @@
PromptKind.Biometric.PaneType.ONE_PANE_NO_SENSOR_LANDSCAPE
else -> PromptKind.Biometric.PaneType.TWO_PANE_LANDSCAPE
}
- PromptKind.Biometric(
- modalities,
- paneType = paneType,
- )
+ PromptKind.Biometric(modalities, paneType = paneType)
} else {
PromptKind.Biometric(modalities)
}
@@ -224,7 +223,7 @@
promptRepository.setPrompt(
promptInfo = promptInfo,
- userId = effectiveUserId,
+ userId = userId,
requestId = requestId,
gatekeeperChallenge = challenge,
kind = kind,
diff --git a/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalContentSize.kt b/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalContentSize.kt
index 572794d..cf80b7d 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalContentSize.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalContentSize.kt
@@ -36,7 +36,7 @@
/** Converts from span to communal content size. */
fun toSize(span: Int): CommunalContentSize {
return entries.find { it.span == span }
- ?: throw Exception("Invalid span for communal content size")
+ ?: throw IllegalArgumentException("$span is not a valid span size")
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt b/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
index 6fb6236..4cdf286 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
@@ -29,7 +29,7 @@
import com.android.systemui.dagger.qualifiers.PerUser
import com.android.systemui.dreams.AssistantAttentionMonitor
import com.android.systemui.dreams.DreamMonitor
-import com.android.systemui.dreams.homecontrols.HomeControlsDreamStartable
+import com.android.systemui.dreams.homecontrols.system.HomeControlsDreamStartable
import com.android.systemui.globalactions.GlobalActionsComponent
import com.android.systemui.haptics.msdl.MSDLCoreStartable
import com.android.systemui.keyboard.KeyboardUI
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
index 59c8f06..cb649f2 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
@@ -70,6 +70,9 @@
import com.android.systemui.inputmethod.InputMethodModule;
import com.android.systemui.keyboard.KeyboardModule;
import com.android.systemui.keyevent.data.repository.KeyEventRepositoryModule;
+import com.android.systemui.keyguard.data.quickaffordance.KeyguardDataQuickAffordanceModule;
+import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancesMetricsLogger;
+import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancesMetricsLoggerImpl;
import com.android.systemui.keyguard.ui.composable.LockscreenContent;
import com.android.systemui.log.dagger.LogModule;
import com.android.systemui.log.dagger.MonitorLog;
@@ -227,6 +230,7 @@
InputMethodModule.class,
KeyEventRepositoryModule.class,
KeyboardModule.class,
+ KeyguardDataQuickAffordanceModule.class,
LetterboxModule.class,
LogModule.class,
MediaProjectionActivitiesModule.class,
@@ -428,6 +432,11 @@
sysuiUiBgExecutor));
}
+ @Provides
+ static KeyguardQuickAffordancesMetricsLogger providesKeyguardQuickAffordancesMetricsLogger() {
+ return new KeyguardQuickAffordancesMetricsLoggerImpl();
+ }
+
@Binds
abstract FgsManagerController bindFgsManagerController(FgsManagerControllerImpl impl);
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractor.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractor.kt
index 782bce4..41a59a9 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractor.kt
@@ -19,10 +19,12 @@
import com.android.systemui.biometrics.data.repository.FingerprintPropertyRepository
import com.android.systemui.biometrics.shared.model.FingerprintSensorType
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dump.DumpManager
import com.android.systemui.keyevent.domain.interactor.KeyEventInteractor
import com.android.systemui.keyguard.data.repository.BiometricSettingsRepository
import com.android.systemui.power.domain.interactor.PowerInteractor
import com.android.systemui.power.shared.model.WakeSleepReason
+import com.android.systemui.util.kotlin.FlowDumperImpl
import com.android.systemui.util.kotlin.sample
import com.android.systemui.util.time.SystemClock
import javax.inject.Inject
@@ -46,16 +48,17 @@
class DeviceEntryHapticsInteractor
@Inject
constructor(
- deviceEntrySourceInteractor: DeviceEntrySourceInteractor,
- deviceEntryFingerprintAuthInteractor: DeviceEntryFingerprintAuthInteractor,
- deviceEntryBiometricAuthInteractor: DeviceEntryBiometricAuthInteractor,
- fingerprintPropertyRepository: FingerprintPropertyRepository,
biometricSettingsRepository: BiometricSettingsRepository,
+ deviceEntryBiometricAuthInteractor: DeviceEntryBiometricAuthInteractor,
+ deviceEntryFingerprintAuthInteractor: DeviceEntryFingerprintAuthInteractor,
+ deviceEntrySourceInteractor: DeviceEntrySourceInteractor,
+ fingerprintPropertyRepository: FingerprintPropertyRepository,
keyEventInteractor: KeyEventInteractor,
+ private val logger: BiometricUnlockLogger,
powerInteractor: PowerInteractor,
private val systemClock: SystemClock,
- private val logger: BiometricUnlockLogger,
-) {
+ dumpManager: DumpManager,
+) : FlowDumperImpl(dumpManager) {
private val powerButtonSideFpsEnrolled =
combineTransform(
fingerprintPropertyRepository.sensorType,
@@ -86,7 +89,7 @@
powerButtonSideFpsEnrolled,
powerButtonDown,
lastPowerButtonWakeup,
- ::Triple
+ ::Triple,
)
)
.filter { (sideFpsEnrolled, powerButtonDown, lastPowerButtonWakeup) ->
@@ -100,14 +103,19 @@
}
allowHaptic
}
- .map {} // map to Unit
+ // map to Unit
+ .map {}
+ .dumpWhileCollecting("playSuccessHaptic")
private val playErrorHapticForBiometricFailure: Flow<Unit> =
merge(
deviceEntryFingerprintAuthInteractor.fingerprintFailure,
deviceEntryBiometricAuthInteractor.faceOnlyFaceFailure,
)
- .map {} // map to Unit
+ // map to Unit
+ .map {}
+ .dumpWhileCollecting("playErrorHapticForBiometricFailure")
+
val playErrorHaptic: Flow<Unit> =
playErrorHapticForBiometricFailure
.sample(combine(powerButtonSideFpsEnrolled, powerButtonDown, ::Pair))
@@ -118,7 +126,9 @@
}
allowHaptic
}
- .map {} // map to Unit
+ // map to Unit
+ .map {}
+ .dumpWhileCollecting("playErrorHaptic")
private val recentPowerButtonPressThresholdMs = 400L
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractor.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractor.kt
index 0b9336f..b2d4405 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractor.kt
@@ -16,18 +16,49 @@
package com.android.systemui.deviceentry.domain.interactor
+import androidx.annotation.VisibleForTesting
+import com.android.keyguard.KeyguardUpdateMonitor
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.biometrics.AuthController
+import com.android.systemui.bouncer.domain.interactor.AlternateBouncerInteractor
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.deviceentry.shared.model.SuccessFaceAuthenticationStatus
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.domain.interactor.KeyguardBypassInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
import com.android.systemui.keyguard.shared.model.BiometricUnlockMode
+import com.android.systemui.keyguard.shared.model.BiometricUnlockModel
import com.android.systemui.keyguard.shared.model.BiometricUnlockSource
+import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
+import com.android.systemui.scene.domain.interactor.SceneContainerOcclusionInteractor
+import com.android.systemui.scene.domain.interactor.SceneInteractor
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_DISMISS_BOUNCER
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_NONE
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_ONLY_WAKE
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_SHOW_BOUNCER
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_UNLOCK_COLLAPSING
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK_FROM_DREAM
+import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
+import com.android.systemui.statusbar.phone.BiometricUnlockController.WakeAndUnlockMode
+import com.android.systemui.statusbar.phone.DozeScrimController
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import com.android.systemui.util.kotlin.Utils.Companion.sampleFilter
+import com.android.systemui.util.kotlin.combine
import com.android.systemui.util.kotlin.sample
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
/**
* Hosts application business logic related to the source of the user entering the device. Note: The
@@ -42,13 +73,184 @@
class DeviceEntrySourceInteractor
@Inject
constructor(
+ authenticationInteractor: AuthenticationInteractor,
+ authController: AuthController,
+ alternateBouncerInteractor: AlternateBouncerInteractor,
+ deviceEntryFaceAuthInteractor: DeviceEntryFaceAuthInteractor,
+ deviceEntryFingerprintAuthInteractor: DeviceEntryFingerprintAuthInteractor,
+ dozeScrimController: DozeScrimController,
+ keyguardBypassInteractor: KeyguardBypassInteractor,
+ keyguardUpdateMonitor: KeyguardUpdateMonitor,
keyguardInteractor: KeyguardInteractor,
-) {
+ sceneContainerOcclusionInteractor: SceneContainerOcclusionInteractor,
+ sceneInteractor: SceneInteractor,
+ dumpManager: DumpManager,
+) : FlowDumperImpl(dumpManager) {
+ private val isShowingBouncerScene: Flow<Boolean> =
+ sceneInteractor.transitionState
+ .map { transitionState ->
+ transitionState.isIdle(Scenes.Bouncer) ||
+ transitionState.isTransitioning(null, Scenes.Bouncer)
+ }
+ .distinctUntilChanged()
+ .dumpWhileCollecting("isShowingBouncerScene")
+
+ private val isUnlockedWithStrongFaceUnlock =
+ deviceEntryFaceAuthInteractor.authenticationStatus
+ .map { status ->
+ (status as? SuccessFaceAuthenticationStatus)?.successResult?.isStrongBiometric
+ ?: false
+ }
+ .dumpWhileCollecting("unlockedWithStrongFaceUnlock")
+
+ private val isUnlockedWithStrongFingerprintUnlock =
+ deviceEntryFingerprintAuthInteractor.authenticationStatus
+ .map { status ->
+ (status as? SuccessFingerprintAuthenticationStatus)?.isStrongBiometric ?: false
+ }
+ .dumpWhileCollecting("unlockedWithStrongFingerprintUnlock")
+
+ private val faceWakeAndUnlockMode: Flow<BiometricUnlockMode> =
+ combine(
+ alternateBouncerInteractor.isVisible,
+ keyguardBypassInteractor.isBypassAvailable,
+ isUnlockedWithStrongFaceUnlock,
+ sceneContainerOcclusionInteractor.isOccludingActivityShown,
+ sceneInteractor.currentScene,
+ isShowingBouncerScene,
+ ) {
+ isAlternateBouncerVisible,
+ isBypassAvailable,
+ isFaceStrongBiometric,
+ isOccluded,
+ currentScene,
+ isShowingBouncerScene ->
+ val isUnlockingAllowed =
+ keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(isFaceStrongBiometric)
+ val bypass = isBypassAvailable || authController.isUdfpsFingerDown()
+
+ when {
+ !keyguardUpdateMonitor.isDeviceInteractive ->
+ when {
+ !isUnlockingAllowed -> if (bypass) MODE_SHOW_BOUNCER else MODE_NONE
+ bypass -> MODE_WAKE_AND_UNLOCK_PULSING
+ else -> MODE_ONLY_WAKE
+ }
+
+ isUnlockingAllowed && currentScene == Scenes.Dream ->
+ if (bypass) MODE_WAKE_AND_UNLOCK_FROM_DREAM else MODE_ONLY_WAKE
+
+ isUnlockingAllowed && isOccluded -> MODE_UNLOCK_COLLAPSING
+
+ (isShowingBouncerScene || isAlternateBouncerVisible) && isUnlockingAllowed ->
+ MODE_DISMISS_BOUNCER
+
+ isUnlockingAllowed && bypass -> MODE_UNLOCK_COLLAPSING
+
+ bypass -> MODE_SHOW_BOUNCER
+
+ else -> MODE_NONE
+ }
+ }
+ .map { biometricModeIntToObject(it) }
+ .dumpWhileCollecting("faceWakeAndUnlockMode")
+
+ private val fingerprintWakeAndUnlockMode: Flow<BiometricUnlockMode> =
+ combine(
+ alternateBouncerInteractor.isVisible,
+ authenticationInteractor.authenticationMethod,
+ sceneInteractor.currentScene,
+ isUnlockedWithStrongFingerprintUnlock,
+ isShowingBouncerScene,
+ ) {
+ alternateBouncerVisible,
+ authenticationMethod,
+ currentScene,
+ isFingerprintStrongBiometric,
+ isShowingBouncerScene ->
+ val unlockingAllowed =
+ keyguardUpdateMonitor.isUnlockingWithBiometricAllowed(
+ isFingerprintStrongBiometric
+ )
+ when {
+ !keyguardUpdateMonitor.isDeviceInteractive ->
+ when {
+ dozeScrimController.isPulsing && unlockingAllowed ->
+ MODE_WAKE_AND_UNLOCK_PULSING
+
+ unlockingAllowed || !authenticationMethod.isSecure ->
+ MODE_WAKE_AND_UNLOCK
+
+ else -> MODE_SHOW_BOUNCER
+ }
+
+ unlockingAllowed && currentScene == Scenes.Dream ->
+ MODE_WAKE_AND_UNLOCK_FROM_DREAM
+
+ isShowingBouncerScene && unlockingAllowed -> MODE_DISMISS_BOUNCER
+
+ unlockingAllowed -> MODE_UNLOCK_COLLAPSING
+
+ currentScene != Scenes.Bouncer && !alternateBouncerVisible -> MODE_SHOW_BOUNCER
+
+ else -> MODE_NONE
+ }
+ }
+ .map { biometricModeIntToObject(it) }
+ .dumpWhileCollecting("fingerprintWakeAndUnlockMode")
+
+ @VisibleForTesting
+ private val biometricUnlockStateOnKeyguardDismissed =
+ merge(
+ fingerprintWakeAndUnlockMode
+ .filter { BiometricUnlockMode.dismissesKeyguard(it) }
+ .map { mode ->
+ BiometricUnlockModel(mode, BiometricUnlockSource.FINGERPRINT_SENSOR)
+ },
+ faceWakeAndUnlockMode
+ .filter { BiometricUnlockMode.dismissesKeyguard(it) }
+ .map { mode -> BiometricUnlockModel(mode, BiometricUnlockSource.FACE_SENSOR) },
+ )
+ .dumpWhileCollecting("biometricUnlockState")
+
+ private val deviceEntryFingerprintAuthWakeAndUnlockEvents:
+ Flow<SuccessFingerprintAuthenticationStatus> =
+ deviceEntryFingerprintAuthInteractor.authenticationStatus
+ .filterIsInstance<SuccessFingerprintAuthenticationStatus>()
+ .dumpWhileCollecting("deviceEntryFingerprintAuthSuccessEvents")
+
+ private val deviceEntryFaceAuthWakeAndUnlockEvents: Flow<SuccessFaceAuthenticationStatus> =
+ deviceEntryFaceAuthInteractor.authenticationStatus
+ .filterIsInstance<SuccessFaceAuthenticationStatus>()
+ .sampleFilter(
+ combine(
+ sceneContainerOcclusionInteractor.isOccludingActivityShown,
+ keyguardBypassInteractor.isBypassAvailable,
+ keyguardBypassInteractor.canBypass,
+ ::Triple,
+ )
+ ) { (isOccludingActivityShown, isBypassAvailable, canBypass) ->
+ isOccludingActivityShown || !isBypassAvailable || canBypass
+ }
+ .dumpWhileCollecting("deviceEntryFaceAuthSuccessEvents")
+
+ private val deviceEntryBiometricAuthSuccessEvents =
+ merge(deviceEntryFingerprintAuthWakeAndUnlockEvents, deviceEntryFaceAuthWakeAndUnlockEvents)
+ .dumpWhileCollecting("deviceEntryBiometricAuthSuccessEvents")
+
val deviceEntryFromBiometricSource: Flow<BiometricUnlockSource> =
- keyguardInteractor.biometricUnlockState
- .filter { BiometricUnlockMode.dismissesKeyguard(it.mode) }
- .map { it.source }
- .filterNotNull()
+ if (SceneContainerFlag.isEnabled) {
+ deviceEntryBiometricAuthSuccessEvents
+ .sample(biometricUnlockStateOnKeyguardDismissed)
+ .map { it.source }
+ .filterNotNull()
+ } else {
+ keyguardInteractor.biometricUnlockState
+ .filter { BiometricUnlockMode.dismissesKeyguard(it.mode) }
+ .map { it.source }
+ .filterNotNull()
+ }
+ .dumpWhileCollecting("deviceEntryFromBiometricSource")
private val attemptEnterDeviceFromDeviceEntryIcon: MutableSharedFlow<Unit> = MutableSharedFlow()
val deviceEntryFromDeviceEntryIcon: Flow<Unit> =
@@ -60,4 +262,18 @@
suspend fun attemptEnterDeviceFromDeviceEntryIcon() {
attemptEnterDeviceFromDeviceEntryIcon.emit(Unit)
}
+
+ private fun biometricModeIntToObject(@WakeAndUnlockMode value: Int): BiometricUnlockMode {
+ return when (value) {
+ MODE_NONE -> BiometricUnlockMode.NONE
+ MODE_WAKE_AND_UNLOCK -> BiometricUnlockMode.WAKE_AND_UNLOCK
+ MODE_WAKE_AND_UNLOCK_PULSING -> BiometricUnlockMode.WAKE_AND_UNLOCK_PULSING
+ MODE_SHOW_BOUNCER -> BiometricUnlockMode.SHOW_BOUNCER
+ MODE_ONLY_WAKE -> BiometricUnlockMode.ONLY_WAKE
+ MODE_UNLOCK_COLLAPSING -> BiometricUnlockMode.UNLOCK_COLLAPSING
+ MODE_WAKE_AND_UNLOCK_FROM_DREAM -> BiometricUnlockMode.WAKE_AND_UNLOCK_FROM_DREAM
+ MODE_DISMISS_BOUNCER -> BiometricUnlockMode.DISMISS_BOUNCER
+ else -> throw IllegalArgumentException("Invalid BiometricUnlockModel value: $value")
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractor.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractor.kt
index a20556c..15631f8 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/OccludingAppDeviceEntryInteractor.kt
@@ -18,6 +18,7 @@
import android.content.Context
import android.content.Intent
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.bouncer.domain.interactor.AlternateBouncerInteractor
import com.android.systemui.bouncer.domain.interactor.PrimaryBouncerInteractor
import com.android.systemui.communal.domain.interactor.CommunalSceneInteractor
@@ -34,6 +35,7 @@
import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
import com.android.systemui.plugins.ActivityStarter
import com.android.systemui.power.domain.interactor.PowerInteractor
+import com.android.systemui.res.R
import com.android.systemui.util.kotlin.combine
import com.android.systemui.util.kotlin.sample
import javax.inject.Inject
@@ -48,7 +50,6 @@
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
-import com.android.app.tracing.coroutines.launchTraced as launch
/** Business logic for handling authentication events when an app is occluding the lockscreen. */
@ExperimentalCoroutinesApi
@@ -123,19 +124,28 @@
.ifKeyguardOccludedByApp(/* elseFlow */ flowOf(null))
init {
- scope.launch {
- // On fingerprint success when the screen is on and not dreaming, go to the home screen
- fingerprintUnlockSuccessEvents
- .sample(
- combine(powerInteractor.isInteractive, keyguardInteractor.isDreaming, ::Pair)
- )
- .collect { (interactive, dreaming) ->
- if (interactive && !dreaming) {
- goToHomeScreen()
+ // This seems undesirable in most cases, except when a video is playing and can PiP when
+ // unlocked. It was originally added for tablets, so allow it there
+ if (context.resources.getBoolean(R.bool.config_goToHomeFromOccludedApps)) {
+ scope.launch {
+ // On fingerprint success when the screen is on and not dreaming, go to the home
+ // screen
+ fingerprintUnlockSuccessEvents
+ .sample(
+ combine(
+ powerInteractor.isInteractive,
+ keyguardInteractor.isDreaming,
+ ::Pair,
+ )
+ )
+ .collect { (interactive, dreaming) ->
+ if (interactive && !dreaming) {
+ goToHomeScreen()
+ }
+ // don't go to the home screen if the authentication is from
+ // AOD/dozing/off/dreaming
}
- // don't go to the home screen if the authentication is from
- // AOD/dozing/off/dreaming
- }
+ }
}
scope.launch {
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/dagger/DreamModule.java b/packages/SystemUI/src/com/android/systemui/dreams/dagger/DreamModule.java
index a45ad15..3171bbc 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/dagger/DreamModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dreams/dagger/DreamModule.java
@@ -33,9 +33,10 @@
import com.android.systemui.dreams.DreamOverlayService;
import com.android.systemui.dreams.SystemDialogsCloser;
import com.android.systemui.dreams.complication.dagger.ComplicationComponent;
-import com.android.systemui.dreams.homecontrols.DreamServiceDelegate;
-import com.android.systemui.dreams.homecontrols.DreamServiceDelegateImpl;
import com.android.systemui.dreams.homecontrols.HomeControlsDreamService;
+import com.android.systemui.dreams.homecontrols.dagger.HomeControlsDataSourceModule;
+import com.android.systemui.dreams.homecontrols.dagger.HomeControlsRemoteServiceComponent;
+import com.android.systemui.dreams.homecontrols.system.HomeControlsRemoteService;
import com.android.systemui.qs.QsEventLogger;
import com.android.systemui.qs.pipeline.shared.TileSpec;
import com.android.systemui.qs.shared.model.TileCategory;
@@ -61,13 +62,15 @@
* Dagger Module providing Dream-related functionality.
*/
@Module(includes = {
- RegisteredComplicationsModule.class,
- LowLightDreamModule.class,
- ScrimModule.class
- },
+ RegisteredComplicationsModule.class,
+ LowLightDreamModule.class,
+ ScrimModule.class,
+ HomeControlsDataSourceModule.class,
+},
subcomponents = {
- ComplicationComponent.class,
- DreamOverlayComponent.class,
+ ComplicationComponent.class,
+ DreamOverlayComponent.class,
+ HomeControlsRemoteServiceComponent.class,
})
public interface DreamModule {
String DREAM_ONLY_ENABLED_FOR_DOCK_USER = "dream_only_enabled_for_dock_user";
@@ -113,6 +116,15 @@
HomeControlsDreamService service);
/**
+ * Provides Home Controls Remote Service
+ */
+ @Binds
+ @IntoMap
+ @ClassKey(HomeControlsRemoteService.class)
+ Service bindHomeControlsRemoteService(
+ HomeControlsRemoteService service);
+
+ /**
* Provides a touch inset manager for dreams.
*/
@Provides
@@ -202,10 +214,4 @@
QSTilePolicy.NoRestrictions.INSTANCE
);
}
-
-
- /** Provides delegate to allow for testing of dream service */
- @Binds
- DreamServiceDelegate bindDreamDelegate(DreamServiceDelegateImpl impl);
-
}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegate.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegate.kt
deleted file mode 100644
index 2cfb02e..0000000
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegate.kt
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.dreams.homecontrols
-
-import android.app.Activity
-import android.service.dreams.DreamService
-
-/** Provides abstraction for [DreamService] methods, so they can be mocked in tests. */
-interface DreamServiceDelegate {
- /** Wrapper for [DreamService.getActivity] which can be mocked in tests. */
- fun getActivity(dreamService: DreamService): Activity?
-
- /** Wrapper for [DreamService.wakeUp] which can be mocked in tests. */
- fun wakeUp(dreamService: DreamService)
-
- /** Wrapper for [DreamService.finish] which can be mocked in tests. */
- fun finish(dreamService: DreamService)
-
- /** Wrapper for [DreamService.getRedirectWake] which can be mocked in tests. */
- fun redirectWake(dreamService: DreamService): Boolean
-}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegateImpl.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegateImpl.kt
deleted file mode 100644
index 7dc5434..0000000
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/DreamServiceDelegateImpl.kt
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.dreams.homecontrols
-
-import android.app.Activity
-import android.service.dreams.DreamService
-import javax.inject.Inject
-
-class DreamServiceDelegateImpl @Inject constructor() : DreamServiceDelegate {
- override fun getActivity(dreamService: DreamService): Activity {
- return dreamService.activity
- }
-
- override fun finish(dreamService: DreamService) {
- dreamService.finish()
- }
-
- override fun wakeUp(dreamService: DreamService) {
- dreamService.wakeUp()
- }
-
- override fun redirectWake(dreamService: DreamService): Boolean {
- return dreamService.redirectWake
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamService.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamService.kt
index 6b14ebf..9eec1b6 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamService.kt
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamService.kt
@@ -16,75 +16,109 @@
package com.android.systemui.dreams.homecontrols
+import android.annotation.SuppressLint
import android.content.Intent
import android.os.PowerManager
import android.service.controls.ControlsProviderService
import android.service.dreams.DreamService
import android.window.TaskFragmentInfo
-import com.android.systemui.controls.settings.ControlsSettingsRepository
-import com.android.systemui.coroutines.newTracingContext
-import com.android.systemui.dagger.qualifiers.Background
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.ServiceLifecycleDispatcher
+import androidx.lifecycle.lifecycleScope
import com.android.systemui.dreams.DreamLogger
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor.Companion.MAX_UPDATE_CORRELATION_DELAY
+import com.android.systemui.dreams.homecontrols.service.TaskFragmentComponent
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsDataSource
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.dagger.DreamLog
+import com.android.systemui.util.time.SystemClock
import com.android.systemui.util.wakelock.WakeLock
-import com.android.systemui.util.wakelock.WakeLock.Builder.NO_TIMEOUT
+import dagger.assisted.Assisted
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
-import kotlin.time.Duration.Companion.seconds
-import kotlinx.coroutines.CoroutineDispatcher
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.SupervisorJob
-import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
-import com.android.app.tracing.coroutines.launchTraced as launch
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+/**
+ * [DreamService] which embeds the user's chosen home controls app to allow it to display as a
+ * screensaver. This service will run in the foreground user context.
+ */
class HomeControlsDreamService
@Inject
-constructor(
- private val controlsSettingsRepository: ControlsSettingsRepository,
- private val taskFragmentFactory: TaskFragmentComponent.Factory,
- private val homeControlsComponentInteractor: HomeControlsComponentInteractor,
- private val wakeLockBuilder: WakeLock.Builder,
- private val dreamServiceDelegate: DreamServiceDelegate,
- @Background private val bgDispatcher: CoroutineDispatcher,
- @DreamLog logBuffer: LogBuffer
-) : DreamService() {
+constructor(private val factory: HomeControlsDreamServiceImpl.Factory) :
+ DreamService(), LifecycleOwner {
- private val serviceJob = SupervisorJob()
- private val serviceScope =
- CoroutineScope(bgDispatcher + serviceJob + newTracingContext("HomeControlsDreamService"))
+ private val dispatcher = ServiceLifecycleDispatcher(this)
+ override val lifecycle: Lifecycle
+ get() = dispatcher.lifecycle
+
+ private val impl: HomeControlsDreamServiceImpl by lazy { factory.create(this, this) }
+
+ override fun onCreate() {
+ dispatcher.onServicePreSuperOnCreate()
+ super.onCreate()
+ }
+
+ override fun onDreamingStarted() {
+ dispatcher.onServicePreSuperOnStart()
+ super.onDreamingStarted()
+ }
+
+ override fun onAttachedToWindow() {
+ super.onAttachedToWindow()
+ impl.onAttachedToWindow()
+ }
+
+ override fun onDetachedFromWindow() {
+ dispatcher.onServicePreSuperOnDestroy()
+ super.onDetachedFromWindow()
+ impl.onDetachedFromWindow()
+ }
+}
+
+/**
+ * Implementation of the home controls dream service, which allows for injecting a [DreamService]
+ * and [LifecycleOwner] for testing.
+ */
+class HomeControlsDreamServiceImpl
+@AssistedInject
+constructor(
+ private val taskFragmentFactory: TaskFragmentComponent.Factory,
+ private val wakeLockBuilder: WakeLock.Builder,
+ private val powerManager: PowerManager,
+ private val systemClock: SystemClock,
+ private val dataSource: HomeControlsDataSource,
+ @DreamLog logBuffer: LogBuffer,
+ @Assisted private val service: DreamService,
+ @Assisted lifecycleOwner: LifecycleOwner,
+) : LifecycleOwner by lifecycleOwner {
+
private val logger = DreamLogger(logBuffer, TAG)
private lateinit var taskFragmentComponent: TaskFragmentComponent
private val wakeLock: WakeLock by lazy {
wakeLockBuilder
- .setMaxTimeout(NO_TIMEOUT)
+ .setMaxTimeout(WakeLock.Builder.NO_TIMEOUT)
.setTag(TAG)
.setLevelsAndFlags(PowerManager.SCREEN_BRIGHT_WAKE_LOCK)
.build()
}
- override fun onAttachedToWindow() {
- super.onAttachedToWindow()
- val activity = dreamServiceDelegate.getActivity(this)
+ fun onAttachedToWindow() {
+ val activity = service.activity
if (activity == null) {
- finish()
+ service.finish()
return
}
-
- // Start monitoring package updates to possibly restart the dream if the home controls
- // package is updated while we are dreaming.
- serviceScope.launch { homeControlsComponentInteractor.monitorUpdatesAndRestart() }
-
taskFragmentComponent =
taskFragmentFactory
.create(
activity = activity,
onCreateCallback = { launchActivity() },
onInfoChangedCallback = this::onTaskFragmentInfoChanged,
- hide = { endDream(false) }
+ hide = { endDream(false) },
)
.apply { createTaskFragment() }
@@ -99,53 +133,61 @@
}
private fun endDream(handleRedirect: Boolean) {
- homeControlsComponentInteractor.onDreamEndUnexpectedly()
- if (handleRedirect && dreamServiceDelegate.redirectWake(this)) {
- dreamServiceDelegate.wakeUp(this)
- serviceScope.launch {
+ pokeUserActivity()
+ if (handleRedirect && service.redirectWake) {
+ service.wakeUp()
+ lifecycleScope.launch {
delay(ACTIVITY_RESTART_DELAY)
launchActivity()
}
} else {
- dreamServiceDelegate.finish(this)
+ service.finish()
}
}
private fun launchActivity() {
- val setting = controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen.value
- val componentName = homeControlsComponentInteractor.panelComponent.value
- logger.d("Starting embedding $componentName")
- val intent =
- Intent().apply {
- component = componentName
- putExtra(ControlsProviderService.EXTRA_LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS, setting)
- putExtra(
- ControlsProviderService.EXTRA_CONTROLS_SURFACE,
- ControlsProviderService.CONTROLS_SURFACE_DREAM
- )
- }
- taskFragmentComponent.startActivityInTaskFragment(intent)
- }
-
- override fun onDetachedFromWindow() {
- super.onDetachedFromWindow()
- wakeLock.release(TAG)
- taskFragmentComponent.destroy()
- serviceScope.launch {
- delay(CANCELLATION_DELAY_AFTER_DETACHED)
- serviceJob.cancel("Dream detached from window")
+ lifecycleScope.launch {
+ val (componentName, setting) = dataSource.componentInfo.first()
+ logger.d("Starting embedding $componentName")
+ val intent =
+ Intent().apply {
+ component = componentName
+ putExtra(
+ ControlsProviderService.EXTRA_LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS,
+ setting,
+ )
+ putExtra(
+ ControlsProviderService.EXTRA_CONTROLS_SURFACE,
+ ControlsProviderService.CONTROLS_SURFACE_DREAM,
+ )
+ }
+ taskFragmentComponent.startActivityInTaskFragment(intent)
}
}
- private companion object {
- /**
- * Defines how long after the dream ends that we should keep monitoring for package updates
- * to attempt a restart of the dream. This should be larger than
- * [MAX_UPDATE_CORRELATION_DELAY] as it also includes the time the package update takes to
- * complete.
- */
- val CANCELLATION_DELAY_AFTER_DETACHED = 5.seconds
+ fun onDetachedFromWindow() {
+ wakeLock.release(TAG)
+ taskFragmentComponent.destroy()
+ }
+ @SuppressLint("MissingPermission")
+ private fun pokeUserActivity() {
+ powerManager.userActivity(
+ systemClock.uptimeMillis(),
+ PowerManager.USER_ACTIVITY_EVENT_OTHER,
+ PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
+ )
+ }
+
+ @AssistedFactory
+ interface Factory {
+ fun create(
+ service: DreamService,
+ lifecycleOwner: LifecycleOwner,
+ ): HomeControlsDreamServiceImpl
+ }
+
+ companion object {
/**
* Defines the delay after wakeup where we should attempt to restart the embedded activity.
* When a wakeup is redirected, the dream service may keep running. In this case, we should
@@ -153,6 +195,6 @@
* after the wakeup transition has played.
*/
val ACTIVITY_RESTART_DELAY = 334.milliseconds
- const val TAG = "HomeControlsDreamService"
+ private const val TAG = "HomeControlsDreamServiceImpl"
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsDataSourceModule.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsDataSourceModule.kt
new file mode 100644
index 0000000..3a2791f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsDataSourceModule.kt
@@ -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.systemui.dreams.homecontrols.dagger
+
+import com.android.systemui.Flags.homeControlsDreamHsum
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dreams.homecontrols.service.RemoteHomeControlsDataSourceDelegator
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsDataSource
+import com.android.systemui.dreams.homecontrols.system.LocalHomeControlsDataSourceDelegator
+import dagger.Lazy
+import dagger.Module
+import dagger.Provides
+
+@Module
+interface HomeControlsDataSourceModule {
+ companion object {
+ @Provides
+ @SysUISingleton
+ fun providesHomeControlsDataSource(
+ localSource: Lazy<LocalHomeControlsDataSourceDelegator>,
+ remoteSource: Lazy<RemoteHomeControlsDataSourceDelegator>,
+ ): HomeControlsDataSource {
+ return if (homeControlsDreamHsum()) {
+ remoteSource.get()
+ } else {
+ localSource.get()
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsRemoteServiceComponent.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsRemoteServiceComponent.kt
new file mode 100644
index 0000000..500d15e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/dagger/HomeControlsRemoteServiceComponent.kt
@@ -0,0 +1,116 @@
+/*
+ * 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.dreams.homecontrols.dagger
+
+import android.content.Context
+import android.content.Intent
+import android.os.IBinder
+import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.dreams.homecontrols.service.HomeControlsRemoteProxy
+import com.android.systemui.dreams.homecontrols.shared.IHomeControlsRemoteProxy
+import com.android.systemui.dreams.homecontrols.system.HomeControlsRemoteService
+import com.android.systemui.util.service.ObservableServiceConnection
+import com.android.systemui.util.service.Observer
+import com.android.systemui.util.service.PersistentConnectionManager
+import com.android.systemui.util.service.dagger.ObservableServiceModule
+import dagger.BindsInstance
+import dagger.Module
+import dagger.Provides
+import dagger.Subcomponent
+import javax.inject.Named
+
+/**
+ * This component is responsible for generating the connection to the home controls remote service
+ * which runs in the SYSTEM_USER context and provides the data needed to run the home controls dream
+ * in the foreground user context.
+ */
+@Subcomponent(
+ modules =
+ [
+ ObservableServiceModule::class,
+ HomeControlsRemoteServiceComponent.HomeControlsRemoteServiceModule::class,
+ ]
+)
+interface HomeControlsRemoteServiceComponent {
+ /** Creates a [HomeControlsRemoteServiceComponent]. */
+ @Subcomponent.Factory
+ interface Factory {
+ fun create(
+ @BindsInstance callback: ObservableServiceConnection.Callback<HomeControlsRemoteProxy>
+ ): HomeControlsRemoteServiceComponent
+ }
+
+ /** A [PersistentConnectionManager] pointing to the home controls remote service. */
+ val connectionManager: PersistentConnectionManager<HomeControlsRemoteProxy>
+
+ /** Scoped module providing specific components for the [ObservableServiceConnection]. */
+ @Module
+ interface HomeControlsRemoteServiceModule {
+ companion object {
+ @Provides
+ @Named(ObservableServiceModule.SERVICE_CONNECTION)
+ fun providesConnection(
+ connection: ObservableServiceConnection<HomeControlsRemoteProxy>,
+ callback: ObservableServiceConnection.Callback<HomeControlsRemoteProxy>,
+ ): ObservableServiceConnection<HomeControlsRemoteProxy> {
+ connection.addCallback(callback)
+ return connection
+ }
+
+ /** Provides the wrapper around the home controls remote binder */
+ @Provides
+ fun providesTransformer(
+ factory: HomeControlsRemoteProxy.Factory
+ ): ObservableServiceConnection.ServiceTransformer<HomeControlsRemoteProxy> {
+ return ObservableServiceConnection.ServiceTransformer { service: IBinder ->
+ factory.create(IHomeControlsRemoteProxy.Stub.asInterface(service))
+ }
+ }
+
+ /** Provides the intent to connect to [HomeControlsRemoteService] */
+ @Provides
+ fun providesIntent(@Application context: Context): Intent {
+ return Intent(context, HomeControlsRemoteService::class.java)
+ }
+
+ /** Provides no-op [Observer] since the remote service is in the same package */
+ @Provides
+ @Named(ObservableServiceModule.OBSERVER)
+ fun providesObserver(): Observer {
+ return object : Observer {
+ override fun addCallback(callback: Observer.Callback?) {
+ // no-op, do nothing
+ }
+
+ override fun removeCallback(callback: Observer.Callback?) {
+ // no-op, do nothing
+ }
+ }
+ }
+
+ /**
+ * Provides a name that will be used by [PersistentConnectionManager] when logging
+ * state.
+ */
+ @Provides
+ @Named(ObservableServiceModule.DUMPSYS_NAME)
+ fun providesDumpsysName(): String {
+ return "HomeControlsRemoteService"
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/domain/interactor/HomeControlsComponentInteractor.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/domain/interactor/HomeControlsComponentInteractor.kt
deleted file mode 100644
index 2034138..0000000
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/domain/interactor/HomeControlsComponentInteractor.kt
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.dreams.homecontrols.domain.interactor
-
-import android.annotation.SuppressLint
-import android.app.DreamManager
-import android.content.ComponentName
-import android.os.PowerManager
-import android.os.UserHandle
-import com.android.systemui.common.domain.interactor.PackageChangeInteractor
-import com.android.systemui.common.shared.model.PackageChangeModel
-import com.android.systemui.controls.ControlsServiceInfo
-import com.android.systemui.controls.dagger.ControlsComponent
-import com.android.systemui.controls.management.ControlsListingController
-import com.android.systemui.controls.panels.AuthorizedPanelsRepository
-import com.android.systemui.controls.panels.SelectedComponentRepository
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.dagger.qualifiers.Background
-import com.android.systemui.user.data.repository.UserRepository
-import com.android.systemui.util.kotlin.getOrNull
-import com.android.systemui.util.kotlin.pairwiseBy
-import com.android.systemui.util.kotlin.sample
-import com.android.systemui.util.time.SystemClock
-import com.android.systemui.utils.coroutines.flow.conflatedCallbackFlow
-import javax.inject.Inject
-import kotlin.math.abs
-import kotlin.time.Duration.Companion.milliseconds
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.channels.BufferOverflow
-import kotlinx.coroutines.channels.awaitClose
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.SharingStarted
-import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.emptyFlow
-import kotlinx.coroutines.flow.filter
-import kotlinx.coroutines.flow.filterNotNull
-import kotlinx.coroutines.flow.flatMapLatest
-import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.flow.stateIn
-
-@SysUISingleton
-@OptIn(ExperimentalCoroutinesApi::class)
-class HomeControlsComponentInteractor
-@Inject
-constructor(
- private val selectedComponentRepository: SelectedComponentRepository,
- controlsComponent: ControlsComponent,
- authorizedPanelsRepository: AuthorizedPanelsRepository,
- userRepository: UserRepository,
- private val packageChangeInteractor: PackageChangeInteractor,
- private val systemClock: SystemClock,
- private val powerManager: PowerManager,
- private val dreamManager: DreamManager,
- @Background private val bgScope: CoroutineScope
-) {
- private val controlsListingController: ControlsListingController? =
- controlsComponent.getControlsListingController().getOrNull()
-
- /** Gets the current user's selected panel, or null if there isn't one */
- private val selectedPanel: Flow<SelectedComponentRepository.SelectedComponent?> =
- userRepository.selectedUserInfo
- .flatMapLatest { user ->
- selectedComponentRepository.selectedComponentFlow(user.userHandle)
- }
- .map { if (it?.isPanel == true) it else null }
-
- /** Gets the current user's authorized panels */
- private val allAuthorizedPanels: Flow<Set<String>> =
- userRepository.selectedUserInfo.flatMapLatest { user ->
- authorizedPanelsRepository.observeAuthorizedPanels(user.userHandle)
- }
-
- /** Gets all the available services from [ControlsListingController] */
- private fun allAvailableServices(): Flow<List<ControlsServiceInfo>> {
- if (controlsListingController == null) {
- return emptyFlow()
- }
- return conflatedCallbackFlow {
- val listener =
- object : ControlsListingController.ControlsListingCallback {
- override fun onServicesUpdated(serviceInfos: List<ControlsServiceInfo>) {
- trySend(serviceInfos)
- }
- }
- controlsListingController.addCallback(listener)
- awaitClose { controlsListingController.removeCallback(listener) }
- }
- .onStart { emit(controlsListingController.getCurrentServices()) }
- }
-
- /** Gets all panels which are available and authorized by the user */
- private val allAvailableAndAuthorizedPanels: Flow<List<PanelComponent>> =
- combine(
- allAvailableServices(),
- allAuthorizedPanels,
- ) { serviceInfos, authorizedPanels ->
- serviceInfos.mapNotNull {
- val panelActivity = it.panelActivity
- if (it.componentName.packageName in authorizedPanels && panelActivity != null) {
- PanelComponent(it.componentName, panelActivity)
- } else {
- null
- }
- }
- }
-
- val panelComponent: StateFlow<ComponentName?> =
- combine(
- allAvailableAndAuthorizedPanels,
- selectedPanel,
- ) { panels, selected ->
- val item =
- panels.firstOrNull { it.componentName == selected?.componentName }
- ?: panels.firstOrNull()
- item?.panelActivity
- }
- .stateIn(bgScope, SharingStarted.Eagerly, null)
-
- private val taskFragmentFinished =
- MutableSharedFlow<Long>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
-
- fun onDreamEndUnexpectedly() {
- powerManager.userActivity(
- systemClock.uptimeMillis(),
- PowerManager.USER_ACTIVITY_EVENT_OTHER,
- PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
- )
- taskFragmentFinished.tryEmit(systemClock.currentTimeMillis())
- }
-
- /**
- * Monitors if the current home panel package is updated and causes the dream to finish, and
- * attempts to restart the dream in this case.
- */
- @SuppressLint("MissingPermission")
- suspend fun monitorUpdatesAndRestart() {
- taskFragmentFinished.resetReplayCache()
- panelComponent
- .flatMapLatest { component ->
- if (component == null) return@flatMapLatest emptyFlow()
- packageChangeInteractor.packageChanged(UserHandle.CURRENT, component.packageName)
- }
- .filter { it.isUpdate() }
- // Wait for an UpdatedStarted - UpdateFinished pair to ensure the update has finished.
- .pairwiseBy(::validateUpdatePair)
- .filterNotNull()
- .sample(taskFragmentFinished, ::Pair)
- .filter { (updateStarted, lastFinishedTimestamp) ->
- abs(updateStarted.timeMillis - lastFinishedTimestamp) <=
- MAX_UPDATE_CORRELATION_DELAY.inWholeMilliseconds
- }
- .collect { dreamManager.startDream() }
- }
-
- private data class PanelComponent(
- val componentName: ComponentName,
- val panelActivity: ComponentName,
- )
-
- companion object {
- /**
- * The maximum delay between a package update **starting** and the task fragment finishing
- * which causes us to correlate the package update as the cause of the task fragment
- * finishing.
- */
- val MAX_UPDATE_CORRELATION_DELAY = 500.milliseconds
- }
-}
-
-private fun PackageChangeModel.isUpdate() =
- this is PackageChangeModel.UpdateStarted || this is PackageChangeModel.UpdateFinished
-
-private fun validateUpdatePair(
- updateStarted: PackageChangeModel,
- updateFinished: PackageChangeModel
-): PackageChangeModel.UpdateStarted? =
- when {
- !updateStarted.isSamePackage(updateFinished) -> null
- updateStarted !is PackageChangeModel.UpdateStarted -> null
- updateFinished !is PackageChangeModel.UpdateFinished -> null
- else -> updateStarted
- }
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxy.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxy.kt
new file mode 100644
index 0000000..2bcfea8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxy.kt
@@ -0,0 +1,81 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import android.content.ComponentName
+import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.dreams.homecontrols.shared.IHomeControlsRemoteProxy
+import com.android.systemui.dreams.homecontrols.shared.IOnControlsSettingsChangeListener
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import com.android.systemui.utils.coroutines.flow.conflatedCallbackFlow
+import dagger.assisted.Assisted
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.stateIn
+
+/** Class to wrap [IHomeControlsRemoteProxy], which exposes the current user's home controls info */
+class HomeControlsRemoteProxy
+@AssistedInject
+constructor(
+ @Background bgScope: CoroutineScope,
+ dumpManager: DumpManager,
+ @Assisted private val proxy: IHomeControlsRemoteProxy,
+) : FlowDumperImpl(dumpManager) {
+
+ private companion object {
+ const val TAG = "HomeControlsRemoteProxy"
+ }
+
+ val componentInfo: Flow<HomeControlsComponentInfo> =
+ conflatedCallbackFlow {
+ val listener =
+ object : IOnControlsSettingsChangeListener.Stub() {
+ override fun onControlsSettingsChanged(
+ panelComponent: ComponentName?,
+ allowTrivialControlsOnLockscreen: Boolean,
+ ) {
+ trySendWithFailureLogging(
+ HomeControlsComponentInfo(
+ panelComponent,
+ allowTrivialControlsOnLockscreen,
+ ),
+ TAG,
+ )
+ }
+ }
+ proxy.registerListenerForCurrentUser(listener)
+ awaitClose { proxy.unregisterListenerForCurrentUser(listener) }
+ }
+ .distinctUntilChanged()
+ .stateIn(bgScope, SharingStarted.WhileSubscribed(), null)
+ .dumpValue("componentInfo")
+ .filterNotNull()
+
+ @AssistedFactory
+ interface Factory {
+ fun create(proxy: IHomeControlsRemoteProxy): HomeControlsRemoteProxy
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegator.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegator.kt
new file mode 100644
index 0000000..b14903d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegator.kt
@@ -0,0 +1,111 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.dreams.DreamLogger
+import com.android.systemui.dreams.homecontrols.dagger.HomeControlsRemoteServiceComponent
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsDataSource
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.dagger.DreamLog
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import com.android.systemui.util.service.ObservableServiceConnection
+import com.android.systemui.util.service.PersistentConnectionManager
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.dropWhile
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.launchIn
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onEach
+
+/**
+ * Queries a remote service for [HomeControlsComponentInfo] necessary to show the home controls
+ * dream.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+@SysUISingleton
+class RemoteHomeControlsDataSourceDelegator
+@Inject
+constructor(
+ @Background bgScope: CoroutineScope,
+ serviceFactory: HomeControlsRemoteServiceComponent.Factory,
+ @DreamLog logBuffer: LogBuffer,
+ dumpManager: DumpManager,
+) : HomeControlsDataSource, FlowDumperImpl(dumpManager) {
+ private val logger = DreamLogger(logBuffer, TAG)
+
+ private val connectionManager: PersistentConnectionManager<HomeControlsRemoteProxy> by lazy {
+ serviceFactory.create(callback).connectionManager
+ }
+
+ private val proxyState =
+ MutableStateFlow<HomeControlsRemoteProxy?>(null)
+ .apply {
+ subscriptionCount
+ .map { it > 0 }
+ .dropWhile { !it }
+ .distinctUntilChanged()
+ .onEach { active ->
+ logger.d({ "Remote service connection active: $bool1" }) { bool1 = active }
+ if (active) {
+ connectionManager.start()
+ } else {
+ connectionManager.stop()
+ }
+ }
+ .launchIn(bgScope)
+ }
+ .dumpValue("proxyState")
+
+ private val callback: ObservableServiceConnection.Callback<HomeControlsRemoteProxy> =
+ object : ObservableServiceConnection.Callback<HomeControlsRemoteProxy> {
+ override fun onConnected(
+ connection: ObservableServiceConnection<HomeControlsRemoteProxy>?,
+ proxy: HomeControlsRemoteProxy,
+ ) {
+ logger.d("Service connected")
+ proxyState.value = proxy
+ }
+
+ override fun onDisconnected(
+ connection: ObservableServiceConnection<HomeControlsRemoteProxy>?,
+ reason: Int,
+ ) {
+ logger.d({ "Service disconnected with reason $int1" }) { int1 = reason }
+ proxyState.value = null
+ }
+ }
+
+ override val componentInfo: Flow<HomeControlsComponentInfo> =
+ proxyState
+ .filterNotNull()
+ .flatMapLatest { proxy: HomeControlsRemoteProxy -> proxy.componentInfo }
+ .dumpWhileCollecting("componentInfo")
+
+ private companion object {
+ const val TAG = "HomeControlsRemoteDataSourceDelegator"
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/TaskFragmentComponent.kt
similarity index 72%
rename from packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt
rename to packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/TaskFragmentComponent.kt
index d547de2..67de30c 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/service/TaskFragmentComponent.kt
@@ -14,29 +14,18 @@
* limitations under the License.
*/
-package com.android.systemui.dreams.homecontrols
+package com.android.systemui.dreams.homecontrols.service
import android.app.Activity
-import android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN
+import android.app.WindowConfiguration
import android.content.Intent
import android.graphics.Rect
import android.os.Binder
import android.window.TaskFragmentCreationParams
import android.window.TaskFragmentInfo
import android.window.TaskFragmentOperation
-import android.window.TaskFragmentOperation.OP_TYPE_DELETE_TASK_FRAGMENT
-import android.window.TaskFragmentOperation.OP_TYPE_REORDER_TO_TOP_OF_TASK
import android.window.TaskFragmentOrganizer
-import android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE
-import android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CLOSE
-import android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_OPEN
import android.window.TaskFragmentTransaction
-import android.window.TaskFragmentTransaction.TYPE_ACTIVITY_REPARENTED_TO_TASK
-import android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_APPEARED
-import android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_ERROR
-import android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_INFO_CHANGED
-import android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED
-import android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_VANISHED
import android.window.WindowContainerTransaction
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.util.concurrency.DelayableExecutor
@@ -65,7 +54,7 @@
activity: Activity,
@Assisted("onCreateCallback") onCreateCallback: FragmentInfoCallback,
@Assisted("onInfoChangedCallback") onInfoChangedCallback: FragmentInfoCallback,
- hide: () -> Unit
+ hide: () -> Unit,
): TaskFragmentComponent
}
@@ -90,26 +79,28 @@
change.taskFragmentInfo?.let { taskFragmentInfo ->
if (taskFragmentInfo.fragmentToken == fragmentToken) {
when (change.type) {
- TYPE_TASK_FRAGMENT_APPEARED -> {
+ TaskFragmentTransaction.TYPE_TASK_FRAGMENT_APPEARED -> {
resultT.addTaskFragmentOperation(
fragmentToken,
- TaskFragmentOperation.Builder(OP_TYPE_REORDER_TO_TOP_OF_TASK)
- .build()
+ TaskFragmentOperation.Builder(
+ TaskFragmentOperation.OP_TYPE_REORDER_TO_TOP_OF_TASK
+ )
+ .build(),
)
onCreateCallback(taskFragmentInfo)
}
- TYPE_TASK_FRAGMENT_INFO_CHANGED -> {
+ TaskFragmentTransaction.TYPE_TASK_FRAGMENT_INFO_CHANGED -> {
onInfoChangedCallback(taskFragmentInfo)
}
- TYPE_TASK_FRAGMENT_VANISHED -> {
+ TaskFragmentTransaction.TYPE_TASK_FRAGMENT_VANISHED -> {
hide()
}
- TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED -> {}
- TYPE_TASK_FRAGMENT_ERROR -> {
+ TaskFragmentTransaction.TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED -> {}
+ TaskFragmentTransaction.TYPE_TASK_FRAGMENT_ERROR -> {
hide()
}
- TYPE_ACTIVITY_REPARENTED_TO_TASK -> {}
+ TaskFragmentTransaction.TYPE_ACTIVITY_REPARENTED_TO_TASK -> {}
else ->
throw IllegalArgumentException(
"Unknown TaskFragmentEvent=" + change.type
@@ -121,8 +112,8 @@
organizer.onTransactionHandled(
transaction.transactionToken,
resultT,
- TASK_FRAGMENT_TRANSIT_CHANGE,
- false
+ TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE,
+ false,
)
}
@@ -132,15 +123,15 @@
TaskFragmentCreationParams.Builder(
organizer.organizerToken,
fragmentToken,
- activity.activityToken!!
+ activity.activityToken!!,
)
.setInitialRelativeBounds(Rect())
- .setWindowingMode(WINDOWING_MODE_FULLSCREEN)
+ .setWindowingMode(WindowConfiguration.WINDOWING_MODE_FULLSCREEN)
.build()
organizer.applyTransaction(
WindowContainerTransaction().createTaskFragment(fragmentOptions),
- TASK_FRAGMENT_TRANSIT_CHANGE,
- false
+ TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE,
+ false,
)
}
@@ -151,8 +142,8 @@
fun startActivityInTaskFragment(intent: Intent) {
organizer.applyTransaction(
WindowContainerTransaction().startActivity(intent),
- TASK_FRAGMENT_TRANSIT_OPEN,
- false
+ TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_OPEN,
+ false,
)
}
@@ -162,10 +153,13 @@
WindowContainerTransaction()
.addTaskFragmentOperation(
fragmentToken,
- TaskFragmentOperation.Builder(OP_TYPE_DELETE_TASK_FRAGMENT).build()
+ TaskFragmentOperation.Builder(
+ TaskFragmentOperation.OP_TYPE_DELETE_TASK_FRAGMENT
+ )
+ .build(),
),
- TASK_FRAGMENT_TRANSIT_CLOSE,
- false
+ TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CLOSE,
+ false,
)
organizer.unregisterOrganizer()
}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IHomeControlsRemoteProxy.aidl b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IHomeControlsRemoteProxy.aidl
new file mode 100644
index 0000000..115b62c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IHomeControlsRemoteProxy.aidl
@@ -0,0 +1,9 @@
+package com.android.systemui.dreams.homecontrols.shared;
+
+import android.os.IRemoteCallback;
+import com.android.systemui.dreams.homecontrols.shared.IOnControlsSettingsChangeListener;
+
+oneway interface IHomeControlsRemoteProxy {
+ void registerListenerForCurrentUser(in IOnControlsSettingsChangeListener callback);
+ void unregisterListenerForCurrentUser(in IOnControlsSettingsChangeListener callback);
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IOnControlsSettingsChangeListener.aidl b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IOnControlsSettingsChangeListener.aidl
new file mode 100644
index 0000000..99e5fae
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/IOnControlsSettingsChangeListener.aidl
@@ -0,0 +1,7 @@
+package com.android.systemui.dreams.homecontrols.shared;
+
+import android.content.ComponentName;
+
+oneway interface IOnControlsSettingsChangeListener {
+ void onControlsSettingsChanged(in ComponentName panelComponent, boolean allowTrivialControlsOnLockscreen);
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsComponentInfo.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsComponentInfo.kt
new file mode 100644
index 0000000..b9e5080
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsComponentInfo.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.dreams.homecontrols.shared.model
+
+import android.content.ComponentName
+
+data class HomeControlsComponentInfo(
+ val componentName: ComponentName?,
+ val allowTrivialControlsOnLockscreen: Boolean,
+)
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSource.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSource.kt
new file mode 100644
index 0000000..8187c54
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSource.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.dreams.homecontrols.shared.model
+
+import kotlinx.coroutines.flow.Flow
+
+/** Source of data for home controls dream to get the necessary information it needs. */
+interface HomeControlsDataSource {
+ val componentInfo: Flow<HomeControlsComponentInfo>
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartable.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsDreamStartable.kt
similarity index 75%
rename from packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartable.kt
rename to packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsDreamStartable.kt
index 03f58ac..644d5fd 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/HomeControlsDreamStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsDreamStartable.kt
@@ -14,24 +14,28 @@
* limitations under the License.
*/
-package com.android.systemui.dreams.homecontrols
+package com.android.systemui.dreams.homecontrols.system
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.service.controls.flags.Flags.homePanelDream
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.CoreStartable
+import com.android.systemui.Flags.homeControlsDreamHsum
import com.android.systemui.dagger.qualifiers.Background
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor
+import com.android.systemui.dreams.homecontrols.HomeControlsDreamService
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.HomeControlsComponentInteractor
+import com.android.systemui.settings.UserContextProvider
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
-import com.android.app.tracing.coroutines.launchTraced as launch
class HomeControlsDreamStartable
@Inject
constructor(
context: Context,
- private val packageManager: PackageManager,
+ private val systemPackageManager: PackageManager,
+ private val userContextProvider: UserContextProvider,
private val homeControlsComponentInteractor: HomeControlsComponentInteractor,
@Background private val bgScope: CoroutineScope,
) : CoreStartable {
@@ -57,10 +61,16 @@
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
}
+ val packageManager =
+ if (homeControlsDreamHsum()) {
+ userContextProvider.userContext.packageManager
+ } else {
+ systemPackageManager
+ }
packageManager.setComponentEnabledSetting(
componentName,
packageState,
- PackageManager.DONT_KILL_APP
+ PackageManager.DONT_KILL_APP,
)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteService.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteService.kt
new file mode 100644
index 0000000..a65d216
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/HomeControlsRemoteService.kt
@@ -0,0 +1,155 @@
+/*
+ * 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.dreams.homecontrols.system
+
+import android.content.ComponentName
+import android.content.Intent
+import android.os.IBinder
+import android.os.RemoteCallbackList
+import android.os.RemoteException
+import android.util.Log
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.LifecycleService
+import androidx.lifecycle.lifecycleScope
+import com.android.systemui.controls.settings.ControlsSettingsRepository
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.dreams.DreamLogger
+import com.android.systemui.dreams.homecontrols.shared.IHomeControlsRemoteProxy
+import com.android.systemui.dreams.homecontrols.shared.IOnControlsSettingsChangeListener
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.HomeControlsComponentInteractor
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.dagger.DreamLog
+import dagger.assisted.Assisted
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
+import java.util.concurrent.atomic.AtomicInteger
+import javax.inject.Inject
+import kotlin.coroutines.CoroutineContext
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.launchIn
+import kotlinx.coroutines.launch
+
+/**
+ * Service which exports the current home controls component name, for use in SystemUI processes
+ * running in other users. This service should only run in the system user.
+ */
+class HomeControlsRemoteService
+@Inject
+constructor(binderFactory: HomeControlsRemoteServiceBinder.Factory) : LifecycleService() {
+ val binder by lazy { binderFactory.create(this) }
+
+ override fun onBind(intent: Intent): IBinder? {
+ super.onBind(intent)
+ return binder
+ }
+}
+
+class HomeControlsRemoteServiceBinder
+@AssistedInject
+constructor(
+ private val homeControlsComponentInteractor: HomeControlsComponentInteractor,
+ private val controlsSettingsRepository: ControlsSettingsRepository,
+ @Background private val bgContext: CoroutineContext,
+ @DreamLog logBuffer: LogBuffer,
+ @Assisted lifecycleOwner: LifecycleOwner,
+) : IHomeControlsRemoteProxy.Stub(), LifecycleOwner by lifecycleOwner {
+ private val logger = DreamLogger(logBuffer, TAG)
+ private val callbacks =
+ object : RemoteCallbackList<IOnControlsSettingsChangeListener>() {
+ override fun onCallbackDied(listener: IOnControlsSettingsChangeListener?) {
+ if (callbackCount.decrementAndGet() == 0) {
+ logger.d("Cancelling collection due to callback death")
+ collectionJob?.cancel()
+ collectionJob = null
+ }
+ }
+ }
+ private val callbackCount = AtomicInteger(0)
+ private var collectionJob: Job? = null
+
+ override fun registerListenerForCurrentUser(listener: IOnControlsSettingsChangeListener?) {
+ if (listener == null) return
+ logger.d("Register listener")
+ val registered = callbacks.register(listener)
+ if (registered && callbackCount.getAndIncrement() == 0) {
+ // If the first listener, start the collection job. This will also take
+ // care of notifying the listener of the initial state.
+ logger.d("Starting collection")
+ collectionJob =
+ lifecycleScope.launch(bgContext) {
+ combine(
+ homeControlsComponentInteractor.panelComponent,
+ controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen,
+ ) { panelComponent, allowTrivialControls ->
+ callbacks.notifyAllCallbacks(panelComponent, allowTrivialControls)
+ }
+ .launchIn(this)
+ }
+ } else if (registered) {
+ // If not the first listener, notify the listener of the current value immediately.
+ listener.notify(
+ homeControlsComponentInteractor.panelComponent.value,
+ controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen.value,
+ )
+ }
+ }
+
+ override fun unregisterListenerForCurrentUser(listener: IOnControlsSettingsChangeListener?) {
+ if (listener == null) return
+ logger.d("Unregister listener")
+ if (callbacks.unregister(listener) && callbackCount.decrementAndGet() == 0) {
+ logger.d("Cancelling collection due to unregister")
+ collectionJob?.cancel()
+ collectionJob = null
+ }
+ }
+
+ private companion object {
+ const val TAG = "HomeControlsRemoteServiceBinder"
+ }
+
+ private fun IOnControlsSettingsChangeListener.notify(
+ panelComponent: ComponentName?,
+ allowTrivialControlsOnLockscreen: Boolean,
+ ) {
+ try {
+ onControlsSettingsChanged(panelComponent, allowTrivialControlsOnLockscreen)
+ } catch (e: RemoteException) {
+ Log.e(TAG, "Error notifying callback", e)
+ }
+ }
+
+ private fun RemoteCallbackList<IOnControlsSettingsChangeListener>.notifyAllCallbacks(
+ panelComponent: ComponentName?,
+ allowTrivialControlsOnLockscreen: Boolean,
+ ) {
+ val itemCount = beginBroadcast()
+ try {
+ for (i in 0 until itemCount) {
+ getBroadcastItem(i).notify(panelComponent, allowTrivialControlsOnLockscreen)
+ }
+ } finally {
+ finishBroadcast()
+ }
+ }
+
+ @AssistedFactory
+ interface Factory {
+ fun create(lifecycleOwner: LifecycleOwner): HomeControlsRemoteServiceBinder
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/LocalHomeControlsDataSourceDelegator.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/LocalHomeControlsDataSourceDelegator.kt
new file mode 100644
index 0000000..ca255fd
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/LocalHomeControlsDataSourceDelegator.kt
@@ -0,0 +1,46 @@
+/*
+ * 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.dreams.homecontrols.system
+
+import com.android.systemui.controls.settings.ControlsSettingsRepository
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsComponentInfo
+import com.android.systemui.dreams.homecontrols.shared.model.HomeControlsDataSource
+import com.android.systemui.dreams.homecontrols.system.domain.interactor.HomeControlsComponentInteractor
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+
+/**
+ * Queries local data sources for the [HomeControlsComponentInfo] necessary to show the home
+ * controls dream.
+ */
+@SysUISingleton
+class LocalHomeControlsDataSourceDelegator
+@Inject
+constructor(
+ homeControlsComponentInteractor: HomeControlsComponentInteractor,
+ controlsSettingsRepository: ControlsSettingsRepository,
+) : HomeControlsDataSource {
+ override val componentInfo: Flow<HomeControlsComponentInfo> =
+ combine(
+ homeControlsComponentInteractor.panelComponent,
+ controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen,
+ ) { panelComponent, allowActionOnTrivialControlsInLockscreen ->
+ HomeControlsComponentInfo(panelComponent, allowActionOnTrivialControlsInLockscreen)
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractor.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractor.kt
new file mode 100644
index 0000000..31bd708
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractor.kt
@@ -0,0 +1,116 @@
+/*
+ * 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.dreams.homecontrols.system.domain.interactor
+
+import android.content.ComponentName
+import com.android.systemui.controls.ControlsServiceInfo
+import com.android.systemui.controls.dagger.ControlsComponent
+import com.android.systemui.controls.management.ControlsListingController
+import com.android.systemui.controls.panels.AuthorizedPanelsRepository
+import com.android.systemui.controls.panels.SelectedComponentRepository
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.user.data.repository.UserRepository
+import com.android.systemui.util.kotlin.getOrNull
+import com.android.systemui.utils.coroutines.flow.conflatedCallbackFlow
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.stateIn
+
+@SysUISingleton
+@OptIn(ExperimentalCoroutinesApi::class)
+class HomeControlsComponentInteractor
+@Inject
+constructor(
+ private val selectedComponentRepository: SelectedComponentRepository,
+ controlsComponent: ControlsComponent,
+ authorizedPanelsRepository: AuthorizedPanelsRepository,
+ userRepository: UserRepository,
+ @Background private val bgScope: CoroutineScope,
+) {
+ private val controlsListingController: ControlsListingController? =
+ controlsComponent.getControlsListingController().getOrNull()
+
+ /** Gets the current user's selected panel, or null if there isn't one */
+ private val selectedPanel: Flow<SelectedComponentRepository.SelectedComponent?> =
+ userRepository.selectedUserInfo
+ .flatMapLatest { user ->
+ selectedComponentRepository.selectedComponentFlow(user.userHandle)
+ }
+ .map { if (it?.isPanel == true) it else null }
+
+ /** Gets the current user's authorized panels */
+ private val allAuthorizedPanels: Flow<Set<String>> =
+ userRepository.selectedUserInfo.flatMapLatest { user ->
+ authorizedPanelsRepository.observeAuthorizedPanels(user.userHandle)
+ }
+
+ /** Gets all the available services from [ControlsListingController] */
+ private fun allAvailableServices(): Flow<List<ControlsServiceInfo>> {
+ if (controlsListingController == null) {
+ return emptyFlow()
+ }
+ return conflatedCallbackFlow {
+ val listener =
+ object : ControlsListingController.ControlsListingCallback {
+ override fun onServicesUpdated(serviceInfos: List<ControlsServiceInfo>) {
+ trySend(serviceInfos)
+ }
+ }
+ controlsListingController.addCallback(listener)
+ awaitClose { controlsListingController.removeCallback(listener) }
+ }
+ .onStart { emit(controlsListingController.getCurrentServices()) }
+ }
+
+ /** Gets all panels which are available and authorized by the user */
+ private val allAvailableAndAuthorizedPanels: Flow<List<PanelComponent>> =
+ combine(allAvailableServices(), allAuthorizedPanels) { serviceInfos, authorizedPanels ->
+ serviceInfos.mapNotNull {
+ val panelActivity = it.panelActivity
+ if (it.componentName.packageName in authorizedPanels && panelActivity != null) {
+ PanelComponent(it.componentName, panelActivity)
+ } else {
+ null
+ }
+ }
+ }
+
+ val panelComponent: StateFlow<ComponentName?> =
+ combine(allAvailableAndAuthorizedPanels, selectedPanel) { panels, selected ->
+ val item =
+ panels.firstOrNull { it.componentName == selected?.componentName }
+ ?: panels.firstOrNull()
+ item?.panelActivity
+ }
+ .stateIn(bgScope, SharingStarted.Eagerly, null)
+
+ private data class PanelComponent(
+ val componentName: ComponentName,
+ val panelActivity: ComponentName,
+ )
+}
diff --git a/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/ActionTutorialContent.kt b/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/ActionTutorialContent.kt
index 6dd56de..1b044de 100644
--- a/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/ActionTutorialContent.kt
+++ b/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/ActionTutorialContent.kt
@@ -77,7 +77,11 @@
}
}
val buttonAlpha by animateFloatAsState(if (actionState is Finished) 1f else 0f)
- DoneButton(onDoneButtonClicked, Modifier.graphicsLayer { alpha = buttonAlpha })
+ DoneButton(
+ onDoneButtonClicked = onDoneButtonClicked,
+ modifier = Modifier.graphicsLayer { alpha = buttonAlpha },
+ enabled = actionState is Finished,
+ )
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/TutorialComponents.kt b/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/TutorialComponents.kt
index 01ad585..202dba3 100644
--- a/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/TutorialComponents.kt
+++ b/packages/SystemUI/src/com/android/systemui/inputdevice/tutorial/ui/composable/TutorialComponents.kt
@@ -28,13 +28,17 @@
import com.android.systemui.res.R
@Composable
-fun DoneButton(onDoneButtonClicked: () -> Unit, modifier: Modifier = Modifier) {
+fun DoneButton(
+ onDoneButtonClicked: () -> Unit,
+ modifier: Modifier = Modifier,
+ enabled: Boolean = true,
+) {
Row(
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
- modifier = modifier.fillMaxWidth()
+ modifier = modifier.fillMaxWidth(),
) {
- Button(onClick = onDoneButtonClicked) {
+ Button(onClick = onDoneButtonClicked, enabled = enabled) {
Text(stringResource(R.string.touchpad_tutorial_done_button))
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
index d0a40ec..7638079 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
@@ -61,8 +61,6 @@
import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor;
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionBootInteractor;
import com.android.systemui.keyguard.domain.interactor.StartKeyguardTransitionModule;
-import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancesMetricsLogger;
-import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancesMetricsLoggerImpl;
import com.android.systemui.keyguard.ui.transitions.DeviceEntryIconTransitionModule;
import com.android.systemui.keyguard.ui.viewmodel.KeyguardQuickAffordancesCombinedViewModelModule;
import com.android.systemui.log.SessionTracker;
@@ -239,12 +237,6 @@
/** */
@Provides
- static KeyguardQuickAffordancesMetricsLogger providesKeyguardQuickAffordancesMetricsLogger() {
- return new KeyguardQuickAffordancesMetricsLoggerImpl();
- }
-
- /** */
- @Provides
@SysUISingleton
static ThreadAssert providesThreadAssert() {
return new ThreadAssert();
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFingerprintAuthRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFingerprintAuthRepository.kt
index e68d799..4d999df 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFingerprintAuthRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFingerprintAuthRepository.kt
@@ -106,7 +106,7 @@
trySendWithFailureLogging(
getFpSensorType(),
TAG,
- "onAllAuthenticatorsRegistered, emitting fpSensorType"
+ "onAllAuthenticatorsRegistered, emitting fpSensorType",
)
}
}
@@ -114,7 +114,7 @@
trySendWithFailureLogging(
getFpSensorType(),
TAG,
- "initial value for fpSensorType"
+ "initial value for fpSensorType",
)
awaitClose { authController.removeCallback(callback) }
}
@@ -134,7 +134,7 @@
trySendWithFailureLogging(
keyguardUpdateMonitor.isFingerprintLockedOut,
TAG,
- "onLockedOutStateChanged"
+ "onLockedOutStateChanged",
)
}
val callback =
@@ -154,7 +154,7 @@
.stateIn(
scope,
started = Eagerly,
- initialValue = keyguardUpdateMonitor.isFingerprintLockedOut
+ initialValue = keyguardUpdateMonitor.isFingerprintLockedOut,
)
}
@@ -165,13 +165,13 @@
object : KeyguardUpdateMonitorCallback() {
override fun onBiometricRunningStateChanged(
running: Boolean,
- biometricSourceType: BiometricSourceType?
+ biometricSourceType: BiometricSourceType?,
) {
if (biometricSourceType == BiometricSourceType.FINGERPRINT) {
trySendWithFailureLogging(
running,
TAG,
- "Fingerprint running state changed"
+ "Fingerprint running state changed",
)
}
}
@@ -180,7 +180,7 @@
trySendWithFailureLogging(
keyguardUpdateMonitor.isFingerprintDetectionRunning,
TAG,
- "Initial fingerprint running state"
+ "Initial fingerprint running state",
)
awaitClose { keyguardUpdateMonitor.removeCallback(callback) }
}
@@ -193,11 +193,7 @@
.map { it.isEngaged }
.filterNotNull()
.map { it }
- .stateIn(
- scope = scope,
- started = WhileSubscribed(),
- initialValue = false,
- )
+ .stateIn(scope = scope, started = WhileSubscribed(), initialValue = false)
// TODO(b/322555228) Remove after consolidating device entry auth messages with BP auth messages
// in BiometricStatusRepository
@@ -232,10 +228,7 @@
) {
sendUpdateIfFingerprint(
biometricSourceType,
- ErrorFingerprintAuthenticationStatus(
- msgId,
- errString,
- ),
+ ErrorFingerprintAuthenticationStatus(msgId, errString),
)
}
@@ -246,15 +239,12 @@
) {
sendUpdateIfFingerprint(
biometricSourceType,
- HelpFingerprintAuthenticationStatus(
- msgId,
- helpString,
- ),
+ HelpFingerprintAuthenticationStatus(msgId, helpString),
)
}
override fun onBiometricAuthFailed(
- biometricSourceType: BiometricSourceType,
+ biometricSourceType: BiometricSourceType
) {
sendUpdateIfFingerprint(
biometricSourceType,
@@ -270,14 +260,14 @@
biometricSourceType,
AcquiredFingerprintAuthenticationStatus(
AuthenticationReason.DeviceEntryAuthentication,
- acquireInfo
+ acquireInfo,
),
)
}
private fun sendUpdateIfFingerprint(
biometricSourceType: BiometricSourceType,
- authenticationStatus: FingerprintAuthenticationStatus
+ authenticationStatus: FingerprintAuthenticationStatus,
) {
if (biometricSourceType != BiometricSourceType.FINGERPRINT) {
return
@@ -285,13 +275,14 @@
trySendWithFailureLogging(
authenticationStatus,
TAG,
- "new fingerprint authentication status"
+ "new fingerprint authentication status",
)
}
}
keyguardUpdateMonitor.registerCallback(callback)
awaitClose { keyguardUpdateMonitor.removeCallback(callback) }
}
+ .flowOn(mainDispatcher)
.buffer(capacity = 4)
override val shouldUpdateIndicatorVisibility: Flow<Boolean> =
@@ -302,7 +293,7 @@
shouldUpdateIndicatorVisibility,
TAG,
"Error sending shouldUpdateIndicatorVisibility " +
- "$shouldUpdateIndicatorVisibility"
+ "$shouldUpdateIndicatorVisibility",
)
}
@@ -310,7 +301,7 @@
object : KeyguardUpdateMonitorCallback() {
override fun onBiometricRunningStateChanged(
running: Boolean,
- biometricSourceType: BiometricSourceType?
+ biometricSourceType: BiometricSourceType?,
) {
sendShouldUpdateIndicatorVisibility(true)
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepository.kt
new file mode 100644
index 0000000..be4ab4b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepository.kt
@@ -0,0 +1,143 @@
+/*
+ * 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.data.repository
+
+import android.annotation.IntDef
+import android.content.res.Resources
+import android.provider.Settings
+import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.shared.model.DevicePosture
+import com.android.systemui.keyguard.shared.model.DevicePosture.UNKNOWN
+import com.android.systemui.res.R
+import com.android.systemui.tuner.TunerService
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.callbackFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.flowOn
+import kotlinx.coroutines.flow.map
+
+@SysUISingleton
+class KeyguardBypassRepository
+@Inject
+constructor(
+ @Main resources: Resources,
+ biometricSettingsRepository: BiometricSettingsRepository,
+ devicePostureRepository: DevicePostureRepository,
+ dumpManager: DumpManager,
+ private val tunerService: TunerService,
+ @Background backgroundDispatcher: CoroutineDispatcher,
+) : FlowDumperImpl(dumpManager) {
+
+ @get:BypassOverride
+ private val bypassOverride: Int by lazy {
+ resources.getInteger(R.integer.config_face_unlock_bypass_override)
+ }
+
+ private val configFaceAuthSupportedPosture: DevicePosture by lazy {
+ DevicePosture.toPosture(resources.getInteger(R.integer.config_face_auth_supported_posture))
+ }
+
+ private val dismissByDefault: Int by lazy {
+ if (resources.getBoolean(com.android.internal.R.bool.config_faceAuthDismissesKeyguard)) {
+ 1
+ } else {
+ 0
+ }
+ }
+
+ private var bypassEnabledSetting: Flow<Boolean> =
+ callbackFlow {
+ val updateBypassSetting = { state: Boolean ->
+ trySendWithFailureLogging(state, TAG, "Error sending bypassSetting $state")
+ }
+
+ val tunable =
+ TunerService.Tunable { key, _ ->
+ updateBypassSetting(tunerService.getValue(key, dismissByDefault) != 0)
+ }
+
+ updateBypassSetting(false)
+ tunerService.addTunable(tunable, Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD)
+ awaitClose { tunerService.removeTunable(tunable) }
+ }
+ .flowOn(backgroundDispatcher)
+ .dumpWhileCollecting("bypassEnabledSetting")
+
+ val overrideFaceBypassSetting: Flow<Boolean> =
+ when (bypassOverride) {
+ FACE_UNLOCK_BYPASS_ALWAYS -> flowOf(true)
+ FACE_UNLOCK_BYPASS_NEVER -> flowOf(false)
+ else -> bypassEnabledSetting
+ }
+
+ val isPostureAllowedForFaceAuth: Flow<Boolean> =
+ when (configFaceAuthSupportedPosture) {
+ UNKNOWN -> flowOf(true)
+ else ->
+ devicePostureRepository.currentDevicePosture
+ .map { posture -> posture == configFaceAuthSupportedPosture }
+ .distinctUntilChanged()
+ }
+
+ /**
+ * Whether bypass is available.
+ *
+ * Bypass is the ability to skip the lockscreen when the device is unlocked using non-primary
+ * authentication types like face unlock, instead of requiring the user to explicitly dismiss
+ * the lockscreen by swiping after the device is already unlocked.
+ *
+ * "Available" refers to a combination of the user setting to skip the lockscreen being set,
+ * whether hard-wired OEM-overridable configs allow the feature, whether a foldable is in the
+ * right foldable posture, and other such things. It does _not_ model this based on more
+ * runtime-like states of the UI.
+ */
+ val isBypassAvailable: Flow<Boolean> =
+ combine(
+ overrideFaceBypassSetting,
+ biometricSettingsRepository.isFaceAuthEnrolledAndEnabled,
+ isPostureAllowedForFaceAuth,
+ ) {
+ bypassOverride: Boolean,
+ isFaceEnrolledAndEnabled: Boolean,
+ isPostureAllowedForFaceAuth: Boolean ->
+ bypassOverride && isFaceEnrolledAndEnabled && isPostureAllowedForFaceAuth
+ }
+ .distinctUntilChanged()
+ .dumpWhileCollecting("isBypassAvailable")
+
+ @IntDef(FACE_UNLOCK_BYPASS_NO_OVERRIDE, FACE_UNLOCK_BYPASS_ALWAYS, FACE_UNLOCK_BYPASS_NEVER)
+ @Retention(AnnotationRetention.SOURCE)
+ private annotation class BypassOverride
+
+ companion object {
+ private const val FACE_UNLOCK_BYPASS_NO_OVERRIDE = 0
+ private const val FACE_UNLOCK_BYPASS_ALWAYS = 1
+ private const val FACE_UNLOCK_BYPASS_NEVER = 2
+
+ private const val TAG = "KeyguardBypassRepository"
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepository.kt
index d49550e..d0de21b 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepository.kt
@@ -36,12 +36,14 @@
import com.android.systemui.keyguard.shared.model.KeyguardSlotPickerRepresentation
import com.android.systemui.res.R
import com.android.systemui.settings.UserTracker
+import com.android.systemui.util.kotlin.FlowDumperImpl
import java.io.PrintWriter
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -64,7 +66,14 @@
configs: Set<@JvmSuppressWildcards KeyguardQuickAffordanceConfig>,
dumpManager: DumpManager,
userHandle: UserHandle,
-) {
+) : FlowDumperImpl(dumpManager) {
+ /**
+ * Whether a quick affordance is being launched. Quick Affordances are interactive lockscreen UI
+ * elements that allow the user to perform quick actions without unlocking their device.
+ */
+ val launchingAffordance: MutableStateFlow<Boolean> =
+ MutableStateFlow(false).dumpValue("launchingAffordance")
+
// Configs for all keyguard quick affordances, mapped by the quick affordance ID as key
private val configsByAffordanceId: Map<String, KeyguardQuickAffordanceConfig> =
configs.associateBy { it.key }
@@ -112,11 +121,7 @@
}
}
}
- .stateIn(
- scope = scope,
- started = SharingStarted.Eagerly,
- initialValue = emptyMap(),
- )
+ .stateIn(scope = scope, started = SharingStarted.Eagerly, initialValue = emptyMap())
init {
legacySettingSyncer.startSyncing()
@@ -144,14 +149,8 @@
* Updates the IDs of affordances to show at the slot with the given ID. The order of affordance
* IDs should be descending priority order.
*/
- fun setSelections(
- slotId: String,
- affordanceIds: List<String>,
- ) {
- selectionManager.value.setSelections(
- slotId = slotId,
- affordanceIds = affordanceIds,
- )
+ fun setSelections(slotId: String, affordanceIds: List<String>) {
+ selectionManager.value.setSelections(slotId = slotId, affordanceIds = affordanceIds)
}
/**
@@ -222,10 +221,7 @@
val (slotId, slotCapacity) = parseSlot(unparsedSlot)
check(!seenSlotIds.contains(slotId)) { "Duplicate slot \"$slotId\"!" }
seenSlotIds.add(slotId)
- KeyguardSlotPickerRepresentation(
- id = slotId,
- maxSelectedAffordances = slotCapacity,
- )
+ KeyguardSlotPickerRepresentation(id = slotId, maxSelectedAffordances = slotCapacity)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepository.kt
new file mode 100644
index 0000000..7699bab
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepository.kt
@@ -0,0 +1,34 @@
+/*
+ * 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.data.repository
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import javax.inject.Inject
+import kotlinx.coroutines.flow.MutableStateFlow
+
+@SysUISingleton
+class PulseExpansionRepository @Inject constructor(dumpManager: DumpManager) :
+ FlowDumperImpl(dumpManager) {
+ /**
+ * Whether the notification panel is expanding from the user swiping downward on a notification
+ * from the pulsing state, or swiping anywhere on the screen when face bypass is enabled
+ */
+ val isPulseExpanding: MutableStateFlow<Boolean> =
+ MutableStateFlow(false).dumpValue("pulseExpanding")
+}
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 b60e98a..f3eeed2 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
@@ -39,7 +39,6 @@
import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.data.repository.ShadeRepository
-import com.android.systemui.util.kotlin.Utils.Companion.sample as sampleCombine
import com.android.systemui.util.kotlin.sample
import java.util.UUID
import javax.inject.Inject
@@ -52,7 +51,6 @@
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
-import com.android.app.tracing.coroutines.launchTraced as launch
@SysUISingleton
class FromLockscreenTransitionInteractor
@@ -176,99 +174,89 @@
if (SceneContainerFlag.isEnabled) return
var transitionId: UUID? = null
scope.launch("$TAG#listenForLockscreenToPrimaryBouncerDragging") {
- shadeRepository.legacyShadeExpansion
- .sampleCombine(
- transitionInteractor.startedKeyguardTransitionStep,
- keyguardInteractor.statusBarState,
- keyguardInteractor.isKeyguardDismissible,
- keyguardInteractor.isKeyguardOccluded,
- )
- .collect {
- (
- shadeExpansion,
- startedStep,
- statusBarState,
- isKeyguardUnlocked,
- isKeyguardOccluded) ->
- val id = transitionId
- val currentTransitionInfo =
- internalTransitionInteractor.currentTransitionInfoInternal()
- if (id != null) {
- if (startedStep.to == KeyguardState.PRIMARY_BOUNCER) {
- // An existing `id` means a transition is started, and calls to
- // `updateTransition` will control it until FINISHED or CANCELED
- var nextState =
- if (shadeExpansion == 0f) {
- TransitionState.FINISHED
- } else if (shadeExpansion == 1f) {
- TransitionState.CANCELED
- } else {
- TransitionState.RUNNING
- }
+ shadeRepository.legacyShadeExpansion.collect { shadeExpansion ->
+ val statusBarState = keyguardInteractor.statusBarState.value
+ val isKeyguardUnlocked = keyguardInteractor.isKeyguardDismissible.value
+ val isKeyguardOccluded = keyguardInteractor.isKeyguardOccluded.value
+ val startedStep = transitionInteractor.startedKeyguardTransitionStep.value
- // startTransition below will issue the CANCELED directly
- if (nextState != TransitionState.CANCELED) {
- transitionRepository.updateTransition(
- id,
- // This maps the shadeExpansion to a much faster curve, to match
- // the existing logic
- 1f -
- MathUtils.constrainedMap(0f, 1f, 0.95f, 1f, shadeExpansion),
- nextState,
- )
+ val id = transitionId
+ val currentTransitionInfo =
+ internalTransitionInteractor.currentTransitionInfoInternal()
+ if (id != null) {
+ if (startedStep.to == KeyguardState.PRIMARY_BOUNCER) {
+ // An existing `id` means a transition is started, and calls to
+ // `updateTransition` will control it until FINISHED or CANCELED
+ var nextState =
+ if (shadeExpansion == 0f) {
+ TransitionState.FINISHED
+ } else if (shadeExpansion == 1f) {
+ TransitionState.CANCELED
+ } else {
+ TransitionState.RUNNING
}
- if (
- nextState == TransitionState.CANCELED ||
- nextState == TransitionState.FINISHED
- ) {
- transitionId = null
- }
-
- // If canceled, just put the state back
- // TODO(b/278086361): This logic should happen in
- // FromPrimaryBouncerInteractor.
- if (nextState == TransitionState.CANCELED) {
- transitionRepository.startTransition(
- TransitionInfo(
- ownerName =
- "$name " +
- "(on behalf of FromPrimaryBouncerInteractor)",
- from = KeyguardState.PRIMARY_BOUNCER,
- to =
- if (isKeyguardOccluded) KeyguardState.OCCLUDED
- else KeyguardState.LOCKSCREEN,
- modeOnCanceled = TransitionModeOnCanceled.REVERSE,
- animator =
- getDefaultAnimatorForTransitionsToState(
- KeyguardState.LOCKSCREEN
- )
- .apply { duration = 100L },
- )
- )
- }
+ // startTransition below will issue the CANCELED directly
+ if (nextState != TransitionState.CANCELED) {
+ transitionRepository.updateTransition(
+ id,
+ // This maps the shadeExpansion to a much faster curve, to match
+ // the existing logic
+ 1f - MathUtils.constrainedMap(0f, 1f, 0.95f, 1f, shadeExpansion),
+ nextState,
+ )
}
- } else {
- // TODO (b/251849525): Remove statusbarstate check when that state is
- // integrated into KeyguardTransitionRepository
+
if (
- // Use currentTransitionInfo to decide whether to start the transition.
- currentTransitionInfo.to == KeyguardState.LOCKSCREEN &&
- shadeExpansion > 0f &&
- shadeExpansion < 1f &&
- shadeRepository.legacyShadeTracking.value &&
- !isKeyguardUnlocked &&
- statusBarState == KEYGUARD
+ nextState == TransitionState.CANCELED ||
+ nextState == TransitionState.FINISHED
) {
- transitionId =
- startTransitionTo(
- toState = KeyguardState.PRIMARY_BOUNCER,
- animator = null, // transition will be manually controlled,
- ownerReason = "#listenForLockscreenToPrimaryBouncerDragging",
+ transitionId = null
+ }
+
+ // If canceled, just put the state back
+ // TODO(b/278086361): This logic should happen in
+ // FromPrimaryBouncerInteractor.
+ if (nextState == TransitionState.CANCELED) {
+ transitionRepository.startTransition(
+ TransitionInfo(
+ ownerName =
+ "$name " + "(on behalf of FromPrimaryBouncerInteractor)",
+ from = KeyguardState.PRIMARY_BOUNCER,
+ to =
+ if (isKeyguardOccluded) KeyguardState.OCCLUDED
+ else KeyguardState.LOCKSCREEN,
+ modeOnCanceled = TransitionModeOnCanceled.REVERSE,
+ animator =
+ getDefaultAnimatorForTransitionsToState(
+ KeyguardState.LOCKSCREEN
+ )
+ .apply { duration = 100L },
)
+ )
}
}
+ } else {
+ // TODO (b/251849525): Remove statusbarstate check when that state is
+ // integrated into KeyguardTransitionRepository
+ if (
+ // Use currentTransitionInfo to decide whether to start the transition.
+ currentTransitionInfo.to == KeyguardState.LOCKSCREEN &&
+ shadeExpansion > 0f &&
+ shadeExpansion < 1f &&
+ shadeRepository.legacyShadeTracking.value &&
+ !isKeyguardUnlocked &&
+ statusBarState == KEYGUARD
+ ) {
+ transitionId =
+ startTransitionTo(
+ toState = KeyguardState.PRIMARY_BOUNCER,
+ animator = null, // transition will be manually controlled,
+ ownerReason = "#listenForLockscreenToPrimaryBouncerDragging",
+ )
+ }
}
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractor.kt
new file mode 100644
index 0000000..d793064
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractor.kt
@@ -0,0 +1,96 @@
+/*
+ * 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.domain.interactor
+
+import com.android.systemui.bouncer.domain.interactor.AlternateBouncerInteractor
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.data.repository.KeyguardBypassRepository
+import com.android.systemui.scene.domain.interactor.SceneInteractor
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.shade.domain.interactor.ShadeInteractor
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import com.android.systemui.util.kotlin.combine
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+
+@SysUISingleton
+class KeyguardBypassInteractor
+@Inject
+constructor(
+ keyguardBypassRepository: KeyguardBypassRepository,
+ alternateBouncerInteractor: AlternateBouncerInteractor,
+ keyguardQuickAffordanceInteractor: KeyguardQuickAffordanceInteractor,
+ pulseExpansionInteractor: PulseExpansionInteractor,
+ sceneInteractor: SceneInteractor,
+ shadeInteractor: ShadeInteractor,
+ dumpManager: DumpManager,
+) : FlowDumperImpl(dumpManager) {
+
+ /**
+ * Whether bypassing the keyguard is enabled by the user in user settings (skipping the
+ * lockscreen when authenticating using secondary authentication types like face unlock).
+ */
+ val isBypassAvailable: Flow<Boolean> =
+ keyguardBypassRepository.isBypassAvailable.dumpWhileCollecting("isBypassAvailable")
+
+ /**
+ * Models whether bypass is unavailable (no secondary authentication types enrolled), or if the
+ * keyguard can be bypassed as a combination of the settings toggle value set by the user and
+ * other factors related to device state.
+ */
+ val canBypass: Flow<Boolean> =
+ isBypassAvailable
+ .flatMapLatest { isBypassAvailable ->
+ if (isBypassAvailable) {
+ combine(
+ sceneInteractor.currentScene.map { scene -> scene == Scenes.Bouncer },
+ alternateBouncerInteractor.isVisible,
+ sceneInteractor.currentScene.map { scene -> scene == Scenes.Lockscreen },
+ keyguardQuickAffordanceInteractor.launchingAffordance,
+ pulseExpansionInteractor.isPulseExpanding,
+ shadeInteractor.isQsExpanded,
+ ) {
+ isBouncerShowing,
+ isAlternateBouncerShowing,
+ isOnLockscreenScene,
+ isLaunchingAffordance,
+ isPulseExpanding,
+ isQsExpanded ->
+ when {
+ isBouncerShowing -> true
+ isAlternateBouncerShowing -> true
+ !isOnLockscreenScene -> false
+ isLaunchingAffordance -> false
+ isPulseExpanding -> false
+ isQsExpanded -> false
+ else -> true
+ }
+ }
+ } else {
+ flowOf(false)
+ }
+ }
+ .dumpWhileCollecting("canBypass")
+
+ companion object {
+ private const val TAG: String = "KeyguardBypassInteractor"
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
index b24ca1a..2e0a160 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
@@ -284,7 +284,7 @@
}
/** Observable for the [StatusBarState] */
- val statusBarState: Flow<StatusBarState> = repository.statusBarState
+ val statusBarState: StateFlow<StatusBarState> = repository.statusBarState
/** Observable for [BiometricUnlockModel] when biometrics are used to unlock the device. */
val biometricUnlockState: StateFlow<BiometricUnlockModel> = repository.biometricUnlockState
@@ -350,23 +350,21 @@
val dismissAlpha: Flow<Float> =
shadeRepository.legacyShadeExpansion
.sampleCombine(
- statusBarState,
keyguardTransitionInteractor.currentKeyguardState,
keyguardTransitionInteractor.transitionState,
isKeyguardDismissible,
keyguardTransitionInteractor.isFinishedIn(Scenes.Communal, GLANCEABLE_HUB),
)
- .filter { (_, _, _, step, _, _) -> !step.transitionState.isTransitioning() }
+ .filter { (_, _, step, _, _) -> !step.transitionState.isTransitioning() }
.transform {
(
legacyShadeExpansion,
- statusBarState,
currentKeyguardState,
step,
isKeyguardDismissible,
onGlanceableHub) ->
if (
- statusBarState == StatusBarState.KEYGUARD &&
+ statusBarState.value == StatusBarState.KEYGUARD &&
isKeyguardDismissible &&
currentKeyguardState == LOCKSCREEN &&
legacyShadeExpansion != 1f
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractor.kt
index 26bf26b..21afd3e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractor.kt
@@ -61,6 +61,8 @@
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
@@ -91,6 +93,11 @@
@Application private val appContext: Context,
private val sceneInteractor: Lazy<SceneInteractor>,
) {
+ /**
+ * Whether a quick affordance is being launched. Quick Affordances are interactive lockscreen UI
+ * elements that allow the user to perform quick actions without unlocking their device.
+ */
+ val launchingAffordance: StateFlow<Boolean> = repository.get().launchingAffordance.asStateFlow()
/**
* Whether the UI should use the long press gesture to activate quick affordances.
@@ -167,11 +174,7 @@
* @param expandable An optional [Expandable] for the activity- or dialog-launch animation
* @param slotId The id of the lockscreen slot that the affordance is in
*/
- fun onQuickAffordanceTriggered(
- configKey: String,
- expandable: Expandable?,
- slotId: String,
- ) {
+ fun onQuickAffordanceTriggered(configKey: String, expandable: Expandable?, slotId: String) {
val (decodedSlotId, decodedConfigKey) = configKey.decode()
val config =
repository.get().selections.value[decodedSlotId]?.find { it.key == decodedConfigKey }
@@ -191,10 +194,7 @@
)
is KeyguardQuickAffordanceConfig.OnTriggeredResult.Handled -> Unit
is KeyguardQuickAffordanceConfig.OnTriggeredResult.ShowDialog ->
- showDialog(
- result.dialog,
- result.expandable,
- )
+ showDialog(result.dialog, result.expandable)
}
}
@@ -225,12 +225,7 @@
selections.add(affordanceId)
- repository
- .get()
- .setSelections(
- slotId = slotId,
- affordanceIds = selections,
- )
+ repository.get().setSelections(slotId = slotId, affordanceIds = selections)
logger.logQuickAffordanceSelected(slotId, affordanceId)
metricsLogger.logOnShortcutSelected(slotId, affordanceId)
@@ -274,12 +269,7 @@
.getOrDefault(slotId, emptyList())
.toMutableList()
return if (selections.remove(affordanceId)) {
- repository
- .get()
- .setSelections(
- slotId = slotId,
- affordanceIds = selections,
- )
+ repository.get().setSelections(slotId = slotId, affordanceIds = selections)
true
} else {
false
@@ -399,11 +389,15 @@
intent,
true /* dismissShade */,
expandable?.activityTransitionController(),
- true /* showOverLockscreenWhenLocked */,
+ true, /* showOverLockscreenWhenLocked */
)
}
}
+ fun setLaunchingAffordance(isLaunchingAffordance: Boolean) {
+ repository.get().launchingAffordance.value = isLaunchingAffordance
+ }
+
private fun String.encode(slotId: String): String {
return "$slotId$DELIMITER$this"
}
@@ -444,19 +438,19 @@
),
KeyguardPickerFlag(
name = Contract.FlagsTable.FLAG_NAME_MONOCHROMATIC_THEME,
- value = featureFlags.isEnabled(Flags.MONOCHROMATIC_THEME)
+ value = featureFlags.isEnabled(Flags.MONOCHROMATIC_THEME),
),
KeyguardPickerFlag(
name = Contract.FlagsTable.FLAG_NAME_WALLPAPER_PICKER_UI_FOR_AIWP,
- value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_UI_FOR_AIWP)
+ value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_UI_FOR_AIWP),
),
KeyguardPickerFlag(
name = Contract.FlagsTable.FLAG_NAME_PAGE_TRANSITIONS,
- value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_PAGE_TRANSITIONS)
+ value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_PAGE_TRANSITIONS),
),
KeyguardPickerFlag(
name = Contract.FlagsTable.FLAG_NAME_WALLPAPER_PICKER_PREVIEW_ANIMATION,
- value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_PREVIEW_ANIMATION)
+ value = featureFlags.isEnabled(Flags.WALLPAPER_PICKER_PREVIEW_ANIMATION),
),
)
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractor.kt
new file mode 100644
index 0000000..377d7ea
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractor.kt
@@ -0,0 +1,43 @@
+/*
+ * 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.domain.interactor
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.data.repository.PulseExpansionRepository
+import com.android.systemui.util.kotlin.FlowDumperImpl
+import javax.inject.Inject
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+@SysUISingleton
+class PulseExpansionInteractor
+@Inject
+constructor(private val repository: PulseExpansionRepository, dumpManager: DumpManager) :
+ FlowDumperImpl(dumpManager) {
+ /**
+ * Whether the notification panel is expanding from the user swiping downward on a notification
+ * from the pulsing state, or swiping anywhere on the screen when face bypass is enabled
+ */
+ val isPulseExpanding: StateFlow<Boolean> =
+ repository.isPulseExpanding.asStateFlow().dumpValue("isPulseExpanding")
+
+ /** Updates whether a pulse expansion is occurring. */
+ fun setPulseExpanding(pulseExpanding: Boolean) {
+ repository.isPulseExpanding.value = pulseExpanding
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/SwipeToDismissInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/SwipeToDismissInteractor.kt
index e404f27..2e3a095 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/SwipeToDismissInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/SwipeToDismissInteractor.kt
@@ -20,13 +20,13 @@
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.StatusBarState
+import com.android.systemui.shade.data.repository.FlingInfo
import com.android.systemui.shade.data.repository.ShadeRepository
-import com.android.systemui.util.kotlin.Utils.Companion.sample
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filter
-import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
/**
@@ -39,8 +39,8 @@
constructor(
@Background backgroundScope: CoroutineScope,
shadeRepository: ShadeRepository,
- transitionInteractor: KeyguardTransitionInteractor,
- keyguardInteractor: KeyguardInteractor,
+ private val transitionInteractor: KeyguardTransitionInteractor,
+ private val keyguardInteractor: KeyguardInteractor,
) {
/**
* Emits a [FlingInfo] whenever a swipe to dismiss gesture has started a fling animation on the
@@ -50,20 +50,15 @@
* LOCKSCREEN -> GONE, and by [KeyguardSurfaceBehindInteractor] to match the surface remote
* animation's velocity to the fling velocity, if applicable.
*/
- val dismissFling =
+ val dismissFling: StateFlow<FlingInfo?> =
shadeRepository.currentFling
- .sample(
- transitionInteractor.startedKeyguardTransitionStep,
- keyguardInteractor.isKeyguardDismissible,
- keyguardInteractor.statusBarState,
- )
- .filter { (flingInfo, startedStep, keyguardDismissable, statusBarState) ->
+ .filter { flingInfo ->
flingInfo != null &&
!flingInfo.expand &&
- statusBarState != StatusBarState.SHADE_LOCKED &&
- startedStep.to == KeyguardState.LOCKSCREEN &&
- keyguardDismissable
+ keyguardInteractor.statusBarState.value != StatusBarState.SHADE_LOCKED &&
+ transitionInteractor.startedKeyguardTransitionStep.value.to ==
+ KeyguardState.LOCKSCREEN &&
+ keyguardInteractor.isKeyguardDismissible.value
}
- .map { (flingInfo, _) -> flingInfo }
.stateIn(backgroundScope, SharingStarted.Eagerly, null)
}
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 40d4193..0d81604 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
@@ -27,6 +27,7 @@
import com.android.systemui.deviceentry.domain.interactor.DeviceEntryInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.PulseExpansionInteractor
import com.android.systemui.keyguard.shared.model.Edge
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.KeyguardState.AOD
@@ -81,6 +82,7 @@
private val communalInteractor: CommunalInteractor,
private val keyguardTransitionInteractor: KeyguardTransitionInteractor,
private val notificationsKeyguardInteractor: NotificationsKeyguardInteractor,
+ private val pulseExpansionInteractor: PulseExpansionInteractor,
notificationShadeWindowModel: NotificationShadeWindowModel,
private val aodNotificationIconViewModel: NotificationIconContainerAlwaysOnDisplayViewModel,
private val alternateBouncerToAodTransitionViewModel: AlternateBouncerToAodTransitionViewModel,
@@ -371,7 +373,7 @@
/** Is there an expanded pulse, are we animating in response? */
private fun isPulseExpandingAnimated(): Flow<AnimatedValue<Boolean>> {
- return notificationsKeyguardInteractor.isPulseExpanding
+ return pulseExpansionInteractor.isPulseExpanding
.pairwise(initialValue = null)
// If pulsing changes, start animating, unless it's the first emission
.map { (prev, expanding) -> AnimatableEvent(expanding, startAnimating = prev != null) }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
index 978a353..d107222 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
@@ -18,12 +18,12 @@
import android.graphics.drawable.Animatable
import android.text.TextUtils
+import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.graphics.ExperimentalAnimationGraphicsApi
import androidx.compose.animation.graphics.res.animatedVectorResource
import androidx.compose.animation.graphics.res.rememberAnimatedVectorPainter
import androidx.compose.animation.graphics.vector.AnimatedImageVector
import androidx.compose.foundation.Image
-import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -32,8 +32,9 @@
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -44,6 +45,7 @@
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.Shape
@@ -57,7 +59,9 @@
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
+import com.android.compose.modifiers.size
import com.android.compose.modifiers.thenIf
import com.android.systemui.Flags
import com.android.systemui.common.shared.model.Icon
@@ -88,12 +92,14 @@
) {
// Icon
val longPressLabel = longPressLabel().takeIf { onLongClick != null }
+ val animatedBackgroundColor by
+ animateColorAsState(colors.iconBackground, label = "QSTileDualTargetBackgroundColor")
Box(
modifier =
Modifier.size(CommonTileDefaults.ToggleTargetSize).thenIf(toggleClick != null) {
Modifier.clip(iconShape)
.verticalSquish(squishiness)
- .background(colors.iconBackground)
+ .drawBehind { drawRect(animatedBackgroundColor) }
.combinedClickable(
onClick = toggleClick!!,
onLongClick = onLongClick,
@@ -117,6 +123,7 @@
SmallTileContent(
icon = icon,
color = colors.icon,
+ size = { CommonTileDefaults.LargeTileIconSize },
modifier = Modifier.align(Alignment.Center),
)
}
@@ -139,18 +146,22 @@
modifier: Modifier = Modifier,
accessibilityUiState: AccessibilityUiState? = null,
) {
+ val animatedLabelColor by animateColorAsState(colors.label, label = "QSTileLabelColor")
+ val animatedSecondaryLabelColor by
+ animateColorAsState(colors.secondaryLabel, label = "QSTileSecondaryLabelColor")
Column(verticalArrangement = Arrangement.Center, modifier = modifier.fillMaxHeight()) {
- Text(
+ BasicText(
label,
style = MaterialTheme.typography.labelLarge,
- color = colors.label,
+ color = { animatedLabelColor },
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (!TextUtils.isEmpty(secondaryLabel)) {
- Text(
+ BasicText(
secondaryLabel ?: "",
- color = colors.secondaryLabel,
+ color = { animatedSecondaryLabelColor },
+ maxLines = 1,
style = MaterialTheme.typography.bodyMedium,
modifier =
Modifier.thenIf(
@@ -170,9 +181,11 @@
modifier: Modifier = Modifier,
icon: Icon,
color: Color,
+ size: () -> Dp = { CommonTileDefaults.IconSize },
animateToEnd: Boolean = false,
) {
- val iconModifier = modifier.size(CommonTileDefaults.IconSize)
+ val animatedColor by animateColorAsState(color, label = "QSTileIconColor")
+ val iconModifier = modifier.size({ size().roundToPx() }, { size().roundToPx() })
val context = LocalContext.current
val loadedDrawable =
remember(icon, context) {
@@ -182,7 +195,7 @@
}
}
if (loadedDrawable !is Animatable) {
- Icon(icon = icon, tint = color, modifier = iconModifier)
+ Icon(icon = icon, tint = animatedColor, modifier = iconModifier)
} else if (icon is Icon.Resource) {
val image = AnimatedImageVector.animatedVectorResource(id = icon.res)
val painter =
@@ -198,14 +211,15 @@
Image(
painter = painter,
contentDescription = icon.contentDescription?.load(),
- colorFilter = ColorFilter.tint(color = color),
+ colorFilter = ColorFilter.tint(color = animatedColor),
modifier = iconModifier,
)
}
}
object CommonTileDefaults {
- val IconSize = 24.dp
+ val IconSize = 32.dp
+ val LargeTileIconSize = 28.dp
val ToggleTargetSize = 56.dp
val TileHeight = 72.dp
val TilePadding = 8.dp
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
index 418ed0b..b5cec12 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
@@ -20,6 +20,7 @@
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
@@ -54,7 +55,6 @@
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
-import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
@@ -69,21 +69,22 @@
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
-import androidx.compose.ui.BiasAlignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
-import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.MeasureScope
+import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
@@ -103,6 +104,7 @@
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.fastMap
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.compose.animation.bounceable
import com.android.compose.modifiers.height
import com.android.systemui.common.ui.compose.load
@@ -134,9 +136,10 @@
import com.android.systemui.qs.pipeline.shared.TileSpec
import com.android.systemui.qs.shared.model.groupAndSort
import com.android.systemui.res.R
+import kotlin.math.roundToInt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
-import com.android.app.tracing.coroutines.launchTraced as launch
+import kotlinx.coroutines.flow.collectLatest
object TileType
@@ -222,7 +225,7 @@
if (dragIsInProgress) {
RemoveTileTarget()
} else {
- Text(text = "Hold and drag to rearrange tiles.")
+ Text(text = stringResource(id = R.string.drag_to_rearrange_tiles))
}
}
}
@@ -240,7 +243,9 @@
spacedBy(dimensionResource(id = R.dimen.qs_label_container_margin)),
modifier = modifier.fillMaxSize(),
) {
- EditGridHeader { Text(text = "Hold and drag to add tiles.") }
+ EditGridHeader {
+ Text(text = stringResource(id = R.string.drag_to_add_tiles))
+ }
AvailableTileGrid(otherTiles, selectionState, columns, listState)
}
@@ -286,7 +291,7 @@
.padding(10.dp),
) {
Icon(imageVector = Icons.Default.Clear, contentDescription = null)
- Text(text = "Remove")
+ Text(text = stringResource(id = R.string.qs_customize_remove))
}
}
@@ -409,7 +414,7 @@
/**
* Adds a list of [GridCell] to the lazy grid
*
- * @param cells the pairs of [GridCell] to [BounceableTileViewModel]
+ * @param cells the pairs of [GridCell] to [AnimatableTileViewModel]
* @param dragAndDropState the [DragAndDropState] for this grid
* @param selectionState the [MutableSelectionState] for this grid
* @param onToggleSize the callback when a tile's size is toggled
@@ -545,9 +550,27 @@
selectionState::unSelect,
)
.tileBackground(colors.background)
- .tilePadding()
) {
- EditTile(tile = cell.tile, iconOnly = cell.isIcon)
+ val targetValue = if (cell.isIcon) 0f else 1f
+ val animatedProgress = remember { Animatable(targetValue) }
+
+ if (selected) {
+ val resizingState = selectionState.resizingState
+ LaunchedEffect(targetValue, resizingState) {
+ if (resizingState == null) {
+ animatedProgress.animateTo(targetValue)
+ } else {
+ snapshotFlow { resizingState.progression }
+ .collectLatest { animatedProgress.snapTo(it) }
+ }
+ }
+ }
+
+ EditTile(
+ tile = cell.tile,
+ tileWidths = { tileWidths },
+ progress = { animatedProgress.value },
+ )
}
}
}
@@ -612,45 +635,72 @@
}
@Composable
-fun BoxScope.EditTile(
+fun EditTile(
tile: EditTileViewModel,
- iconOnly: Boolean,
+ tileWidths: () -> TileWidths?,
+ progress: () -> Float,
colors: TileColors = EditModeTileDefaults.editTileColors(),
) {
- // Animated horizontal alignment from center (0f) to start (-1f)
- val alignmentValue by
- animateFloatAsState(
- targetValue = if (iconOnly) 0f else -1f,
- label = "QSEditTileContentAlignment",
- )
- val alignment by remember {
- derivedStateOf { BiasAlignment(horizontalBias = alignmentValue, verticalBias = 0f) }
- }
- // Icon
- Box(Modifier.size(ToggleTargetSize).align(alignment)) {
- SmallTileContent(
- icon = tile.icon,
- color = colors.icon,
- animateToEnd = true,
- modifier = Modifier.align(Alignment.Center),
- )
- }
+ val iconSizeDiff = CommonTileDefaults.IconSize - CommonTileDefaults.LargeTileIconSize
+ Row(
+ horizontalArrangement = spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ modifier =
+ Modifier.layout { measurable, constraints ->
+ // Always display the tile using the large size and trust the parent composable
+ // to clip the content as needed. This stop the labels from being truncated.
+ val width = tileWidths()?.max ?: constraints.maxWidth
+ val placeable =
+ measurable.measure(constraints.copy(minWidth = width, maxWidth = width))
+ val currentProgress = progress()
+ val startPadding =
+ if (currentProgress == 0f) {
+ // Find the center of the max width when the tile is icon only
+ iconHorizontalCenter(constraints.maxWidth)
+ } else {
+ // Find the center of the minimum width to hold the same position as the
+ // tile is resized.
+ val basePadding =
+ tileWidths()?.min?.let { iconHorizontalCenter(it) } ?: 0f
+ // Large tiles, represented with a progress of 1f, have a 0.dp padding
+ basePadding * (1f - currentProgress)
+ }
- // Labels, positioned after the icon
- AnimatedVisibility(visible = !iconOnly, enter = fadeIn(), exit = fadeOut()) {
+ layout(constraints.maxWidth, constraints.maxHeight) {
+ placeable.place(startPadding.roundToInt(), 0)
+ }
+ }
+ .tilePadding(),
+ ) {
+ // Icon
+ Box(Modifier.size(ToggleTargetSize)) {
+ SmallTileContent(
+ icon = tile.icon,
+ color = colors.icon,
+ animateToEnd = true,
+ size = { CommonTileDefaults.IconSize - iconSizeDiff * progress() },
+ modifier = Modifier.align(Alignment.Center),
+ )
+ }
+
+ // Labels, positioned after the icon
LargeTileLabels(
label = tile.label.text,
secondaryLabel = tile.appName?.text,
colors = colors,
- modifier = Modifier.padding(start = ToggleTargetSize + TileArrangementPadding),
+ modifier = Modifier.weight(1f).graphicsLayer { alpha = progress() },
)
}
}
+private fun MeasureScope.iconHorizontalCenter(containerSize: Int): Float {
+ return (containerSize - ToggleTargetSize.roundToPx()) / 2f -
+ CommonTileDefaults.TilePadding.toPx()
+}
+
private fun Modifier.tileBackground(color: Color): Modifier {
- return drawBehind {
- drawRoundRect(SolidColor(color), cornerRadius = CornerRadius(InactiveCornerRadius.toPx()))
- }
+ // Clip tile contents from overflowing past the tile
+ return clip(RoundedCornerShape(InactiveCornerRadius)).drawBehind { drawRect(color) }
}
private object EditModeTileDefaults {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/Tile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/Tile.kt
index e1583e3..5bebdbc 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/Tile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/Tile.kt
@@ -21,6 +21,7 @@
import android.content.res.Resources
import android.service.quicksettings.Tile.STATE_ACTIVE
import android.service.quicksettings.Tile.STATE_INACTIVE
+import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
@@ -61,6 +62,7 @@
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.compose.animation.Expandable
import com.android.compose.animation.bounceable
import com.android.compose.modifiers.thenIf
@@ -74,6 +76,7 @@
import com.android.systemui.plugins.qs.QSTile
import com.android.systemui.qs.panels.ui.compose.BounceableInfo
import com.android.systemui.qs.panels.ui.compose.infinitegrid.CommonTileDefaults.InactiveCornerRadius
+import com.android.systemui.qs.panels.ui.compose.infinitegrid.CommonTileDefaults.TileHeight
import com.android.systemui.qs.panels.ui.compose.infinitegrid.CommonTileDefaults.longPressLabel
import com.android.systemui.qs.panels.ui.viewmodel.TileUiState
import com.android.systemui.qs.panels.ui.viewmodel.TileViewModel
@@ -82,7 +85,6 @@
import com.android.systemui.res.R
import java.util.function.Supplier
import kotlinx.coroutines.CoroutineScope
-import com.android.app.tracing.coroutines.launchTraced as launch
private const val TEST_TAG_SMALL = "qs_tile_small"
private const val TEST_TAG_LARGE = "qs_tile_large"
@@ -128,14 +130,18 @@
// TODO(b/361789146): Draw the shapes instead of clipping
val tileShape = TileDefaults.animateTileShape(uiState.state)
-
- TileExpandable(
- color =
+ val animatedColor by
+ animateColorAsState(
if (iconOnly || !uiState.handlesSecondaryClick) {
colors.iconBackground
} else {
colors.background
},
+ label = "QSTileBackgroundColor",
+ )
+
+ TileExpandable(
+ color = { animatedColor },
shape = tileShape,
squishiness = squishiness,
hapticsViewModel = hapticsViewModel,
@@ -212,7 +218,7 @@
@Composable
private fun TileExpandable(
- color: Color,
+ color: () -> Color,
shape: Shape,
squishiness: () -> Float,
hapticsViewModel: TileHapticsViewModel?,
@@ -220,7 +226,7 @@
content: @Composable (Expandable) -> Unit,
) {
Expandable(
- color = color,
+ color = color(),
shape = shape,
modifier = modifier.clip(shape).verticalSquish(squishiness),
) {
@@ -238,7 +244,7 @@
) {
Box(
modifier =
- Modifier.height(CommonTileDefaults.TileHeight)
+ Modifier.height(TileHeight)
.fillMaxWidth()
.tileCombinedClickable(
onClick = onClick,
@@ -336,6 +342,16 @@
)
@Composable
+ fun inactiveDualTargetTileColors(): TileColors =
+ TileColors(
+ background = MaterialTheme.colorScheme.surfaceVariant,
+ iconBackground = MaterialTheme.colorScheme.surfaceContainerHighest,
+ label = MaterialTheme.colorScheme.onSurfaceVariant,
+ secondaryLabel = MaterialTheme.colorScheme.onSurfaceVariant,
+ icon = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+
+ @Composable
fun inactiveTileColors(): TileColors =
TileColors(
background = MaterialTheme.colorScheme.surfaceVariant,
@@ -365,7 +381,13 @@
activeTileColors()
}
}
- STATE_INACTIVE -> inactiveTileColors()
+ STATE_INACTIVE -> {
+ if (uiState.handlesSecondaryClick) {
+ inactiveDualTargetTileColors()
+ } else {
+ inactiveTileColors()
+ }
+ }
else -> unavailableTileColors()
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/ResizingState.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/ResizingState.kt
index a084bc2..9552aa9 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/ResizingState.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/ResizingState.kt
@@ -17,25 +17,30 @@
package com.android.systemui.qs.panels.ui.compose.selection
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import com.android.systemui.qs.panels.ui.compose.selection.ResizingDefaults.RESIZING_THRESHOLD
class ResizingState(private val widths: TileWidths, private val onResize: () -> Unit) {
- // Total drag offset of this resize operation
- private var totalOffset = 0f
+ /** Total drag offset of this resize operation. */
+ private var totalOffset by mutableFloatStateOf(0f)
/** Width in pixels of the resizing tile. */
var width by mutableIntStateOf(widths.base)
+ /** Progression between icon (0) and large (1) sizes. */
+ val progression
+ get() = calculateProgression()
+
// Whether the tile is currently over the threshold and should be a large tile
- private var passedThreshold: Boolean = passedThreshold(calculateProgression(width))
+ private var passedThreshold: Boolean = passedThreshold(progression)
fun onDrag(offset: Float) {
totalOffset += offset
width = (widths.base + totalOffset).toInt().coerceIn(widths.min, widths.max)
- passedThreshold(calculateProgression(width)).let {
+ passedThreshold(progression).let {
// Resize if we went over the threshold
if (passedThreshold != it) {
passedThreshold = it
@@ -49,7 +54,7 @@
}
/** The progression of the resizing tile between an icon tile (0f) and a large tile (1f) */
- private fun calculateProgression(width: Int): Float {
+ private fun calculateProgression(): Float {
return ((width - widths.min) / (widths.max - widths.min).toFloat()).coerceIn(0f, 1f)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/Selection.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/Selection.kt
index 9f13a37..8a345ce 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/Selection.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/selection/Selection.kt
@@ -16,7 +16,11 @@
package com.android.systemui.qs.panels.ui.compose.selection
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateIntAsState
+import androidx.compose.animation.core.spring
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Box
@@ -78,7 +82,6 @@
ResizingHandle(
enabled = selected,
selectionState = selectionState,
- transition = selectionAlpha,
tileWidths = tileWidths,
modifier =
// Higher zIndex to make sure the handle is drawn above the content
@@ -91,7 +94,6 @@
private fun ResizingHandle(
enabled: Boolean,
selectionState: MutableSelectionState,
- transition: () -> Float,
tileWidths: () -> TileWidths?,
modifier: Modifier = Modifier,
) {
@@ -126,19 +128,24 @@
}
}
) {
- ResizingDot(transition = transition, modifier = Modifier.align(Alignment.Center))
+ ResizingDot(enabled = enabled, modifier = Modifier.align(Alignment.Center))
}
}
@Composable
private fun ResizingDot(
- transition: () -> Float,
+ enabled: Boolean,
modifier: Modifier = Modifier,
color: Color = MaterialTheme.colorScheme.primary,
) {
+ val alpha by animateFloatAsState(if (enabled) 1f else 0f)
+ val radius by
+ animateDpAsState(
+ if (enabled) ResizingDotSize / 2 else 0.dp,
+ animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
+ )
Canvas(modifier = modifier.size(ResizingDotSize)) {
- val v = transition()
- drawCircle(color = color, radius = (ResizingDotSize / 2).toPx() * v, alpha = v)
+ drawCircle(color = color, radius = radius.toPx(), alpha = alpha)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/dialog/QSResetDialogDelegate.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/dialog/QSResetDialogDelegate.kt
index 03fc425..cbece2c 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/dialog/QSResetDialogDelegate.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/dialog/QSResetDialogDelegate.kt
@@ -23,7 +23,7 @@
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.android.compose.PlatformButton
-import com.android.compose.PlatformOutlinedButton
+import com.android.compose.PlatformTextButton
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dialog.ui.composable.AlertDialogContent
import com.android.systemui.qs.panels.domain.interactor.EditTilesResetInteractor
@@ -84,8 +84,8 @@
Text(stringResource(id = android.R.string.ok))
}
},
- neutralButton = {
- PlatformOutlinedButton(onClick = { dialog.dismiss() }) {
+ negativeButton = {
+ PlatformTextButton(onClick = { dialog.dismiss() }) {
Text(stringResource(id = android.R.string.cancel))
}
},
diff --git a/packages/SystemUI/src/com/android/systemui/shade/CameraLauncher.java b/packages/SystemUI/src/com/android/systemui/shade/CameraLauncher.java
index fc61e90..1d81e40 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/CameraLauncher.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/CameraLauncher.java
@@ -18,25 +18,33 @@
import com.android.systemui.camera.CameraGestureHelper;
import com.android.systemui.dagger.SysUISingleton;
+import com.android.systemui.keyguard.domain.interactor.KeyguardQuickAffordanceInteractor;
+import com.android.systemui.scene.shared.flag.SceneContainerFlag;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
+import dagger.Lazy;
+
import javax.inject.Inject;
+
/** Handles launching camera from Shade. */
@SysUISingleton
public class CameraLauncher {
private final CameraGestureHelper mCameraGestureHelper;
private final KeyguardBypassController mKeyguardBypassController;
+ private final Lazy<KeyguardQuickAffordanceInteractor> mKeyguardQuickAffordanceInteractorLazy;
private boolean mLaunchingAffordance;
@Inject
public CameraLauncher(
CameraGestureHelper cameraGestureHelper,
- KeyguardBypassController keyguardBypassController
+ KeyguardBypassController keyguardBypassController,
+ Lazy<KeyguardQuickAffordanceInteractor> keyguardQuickAffordanceInteractorLazy
) {
mCameraGestureHelper = cameraGestureHelper;
mKeyguardBypassController = keyguardBypassController;
+ mKeyguardQuickAffordanceInteractorLazy = keyguardQuickAffordanceInteractorLazy;
}
/** Launches the camera. */
@@ -54,7 +62,12 @@
*/
public void setLaunchingAffordance(boolean launchingAffordance) {
mLaunchingAffordance = launchingAffordance;
- mKeyguardBypassController.setLaunchingAffordance(launchingAffordance);
+ if (SceneContainerFlag.isEnabled()) {
+ mKeyguardQuickAffordanceInteractorLazy.get()
+ .setLaunchingAffordance(launchingAffordance);
+ } else {
+ mKeyguardBypassController.setLaunchingAffordance(launchingAffordance);
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
index ea515e0..08ffbf2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
@@ -22,11 +22,13 @@
import androidx.core.animation.ObjectAnimator
import com.android.app.animation.Interpolators
import com.android.app.animation.InterpolatorsAndroidX
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.Dumpable
import com.android.systemui.communal.domain.interactor.CommunalInteractor
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.domain.interactor.PulseExpansionInteractor
import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.shade.ShadeExpansionChangeEvent
import com.android.systemui.shade.ShadeExpansionListener
@@ -49,7 +51,6 @@
import kotlin.math.max
import kotlin.math.min
import kotlinx.coroutines.CoroutineScope
-import com.android.app.tracing.coroutines.launchTraced as launch
@SysUISingleton
class NotificationWakeUpCoordinator
@@ -65,6 +66,7 @@
private val logger: NotificationWakeUpCoordinatorLogger,
private val notifsKeyguardInteractor: NotificationsKeyguardInteractor,
private val communalInteractor: CommunalInteractor,
+ private val pulseExpansionInteractor: PulseExpansionInteractor,
) :
OnHeadsUpChangedListener,
StatusBarStateController.StateListener,
@@ -115,7 +117,7 @@
// they were blocked by the proximity sensor
updateNotificationVisibility(
animate = shouldAnimateVisibility(),
- increaseSpeed = false
+ increaseSpeed = false,
)
}
}
@@ -139,7 +141,7 @@
// the waking up callback
updateNotificationVisibility(
animate = shouldAnimateVisibility(),
- increaseSpeed = false
+ increaseSpeed = false,
)
}
}
@@ -200,7 +202,7 @@
setNotificationsVisibleForExpansion(
visible = false,
animate = false,
- increaseSpeed = false
+ increaseSpeed = false,
)
}
}
@@ -226,7 +228,7 @@
for (listener in wakeUpListeners) {
listener.onPulseExpandingChanged(pulseExpanding)
}
- notifsKeyguardInteractor.setPulseExpanding(pulseExpanding)
+ pulseExpansionInteractor.setPulseExpanding(pulseExpanding)
}
}
}
@@ -241,7 +243,7 @@
fun setNotificationsVisibleForExpansion(
visible: Boolean,
animate: Boolean,
- increaseSpeed: Boolean
+ increaseSpeed: Boolean,
) {
notificationsVisibleForExpansion = visible
updateNotificationVisibility(animate, increaseSpeed)
@@ -282,7 +284,7 @@
private fun setNotificationsVisible(
visible: Boolean,
animate: Boolean,
- increaseSpeed: Boolean
+ increaseSpeed: Boolean,
) {
if (notificationsVisible == visible) {
return
@@ -363,7 +365,7 @@
hardOverride = hardDozeAmountOverride,
outputLinear = outputLinearDozeAmount,
state = statusBarStateController.state,
- changed = changed
+ changed = changed,
)
stackScrollerController.setDozeAmount(outputEasedDozeAmount)
updateHideAmount()
@@ -372,7 +374,7 @@
setNotificationsVisibleForExpansion(
visible = false,
animate = false,
- increaseSpeed = false
+ increaseSpeed = false,
)
}
}
@@ -389,10 +391,7 @@
* call with `false` at some point in the near future. A call with `true` before that will
* happen if the animation is not already running.
*/
- fun setWakingUp(
- wakingUp: Boolean,
- requestDelayedAnimation: Boolean,
- ) {
+ fun setWakingUp(wakingUp: Boolean, requestDelayedAnimation: Boolean) {
logger.logSetWakingUp(wakingUp, requestDelayedAnimation)
this.wakingUp = wakingUp
if (wakingUp && requestDelayedAnimation) {
@@ -432,7 +431,7 @@
// See: UnlockedScreenOffAnimationController.onFinishedWakingUp()
setHardDozeAmountOverride(
dozing = false,
- source = "Override: Shade->Shade (lock cancelled by unlock)"
+ source = "Override: Shade->Shade (lock cancelled by unlock)",
)
this.state = newState
return
@@ -478,7 +477,7 @@
wasCollapsedEnoughToHide,
isCollapsedEnoughToHide,
couldShowPulsingHuns,
- canShowPulsingHuns
+ canShowPulsingHuns,
)
if (couldShowPulsingHuns && !canShowPulsingHuns) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/data/repository/NotificationsKeyguardViewStateRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/data/repository/NotificationsKeyguardViewStateRepository.kt
index bd6ea30..f9fd5ca 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/data/repository/NotificationsKeyguardViewStateRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/data/repository/NotificationsKeyguardViewStateRepository.kt
@@ -24,7 +24,4 @@
class NotificationsKeyguardViewStateRepository @Inject constructor() {
/** Are notifications fully hidden from view? */
val areNotificationsFullyHidden = MutableStateFlow(false)
-
- /** Is a pulse expansion occurring? */
- val isPulseExpanding = MutableStateFlow(false)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractor.kt
index a6361cb..1cb4144 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/domain/interactor/NotificationsKeyguardInteractor.kt
@@ -22,12 +22,7 @@
/** Domain logic pertaining to notifications on the keyguard. */
class NotificationsKeyguardInteractor
@Inject
-constructor(
- private val repository: NotificationsKeyguardViewStateRepository,
-) {
- /** Is a pulse expansion occurring? */
- val isPulseExpanding: Flow<Boolean> = repository.isPulseExpanding
-
+constructor(private val repository: NotificationsKeyguardViewStateRepository) {
/** Are notifications fully hidden from view? */
val areNotificationsFullyHidden: Flow<Boolean> = repository.areNotificationsFullyHidden
@@ -35,9 +30,4 @@
fun setNotificationsFullyHidden(fullyHidden: Boolean) {
repository.areNotificationsFullyHidden.value = fullyHidden
}
-
- /** Updates whether a pulse expansion is occurring. */
- fun setPulseExpanding(pulseExpanding: Boolean) {
- repository.isPulseExpanding.value = pulseExpanding
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
index ffab9ea..42acd7bc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
@@ -29,19 +29,15 @@
import androidx.constraintlayout.widget.ConstraintSet.TOP
import androidx.constraintlayout.widget.ConstraintSet.VERTICAL
import com.android.systemui.res.R
+import com.android.systemui.scene.shared.flag.SceneContainerFlag
+import com.android.systemui.statusbar.notification.stack.ui.viewmodel.SharedNotificationContainerViewModel.HorizontalPosition
/**
* Container for the stack scroller, so that the bounds can be externally specified, such as from
* the keyguard or shade scenes.
*/
-class SharedNotificationContainer(
- context: Context,
- private val attrs: AttributeSet?,
-) :
- ConstraintLayout(
- context,
- attrs,
- ) {
+class SharedNotificationContainer(context: Context, attrs: AttributeSet?) :
+ ConstraintLayout(context, attrs) {
private val baseConstraintSet = ConstraintSet()
@@ -59,24 +55,40 @@
}
fun updateConstraints(
- useSplitShade: Boolean,
+ horizontalPosition: HorizontalPosition,
marginStart: Int,
marginTop: Int,
marginEnd: Int,
- marginBottom: Int
+ marginBottom: Int,
) {
val constraintSet = ConstraintSet()
constraintSet.clone(baseConstraintSet)
val startConstraintId =
- if (useSplitShade) {
+ if (horizontalPosition is HorizontalPosition.MiddleToEdge) {
R.id.nssl_guideline
} else {
PARENT_ID
}
+
val nsslId = R.id.notification_stack_scroller
constraintSet.apply {
- connect(nsslId, START, startConstraintId, START, marginStart)
+ if (SceneContainerFlag.isEnabled) {
+ when (horizontalPosition) {
+ is HorizontalPosition.FloatAtEnd ->
+ constrainWidth(nsslId, horizontalPosition.width)
+ is HorizontalPosition.MiddleToEdge ->
+ setGuidelinePercent(R.id.nssl_guideline, horizontalPosition.ratio)
+ else -> Unit
+ }
+ }
+
+ if (
+ !SceneContainerFlag.isEnabled ||
+ horizontalPosition !is HorizontalPosition.FloatAtEnd
+ ) {
+ connect(nsslId, START, startConstraintId, START, marginStart)
+ }
connect(nsslId, END, PARENT_ID, END, marginEnd)
connect(nsslId, BOTTOM, PARENT_ID, BOTTOM, marginBottom)
connect(nsslId, TOP, PARENT_ID, TOP, marginTop)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
index ce89d78..4a55dfa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
@@ -18,6 +18,7 @@
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.Flags
import com.android.systemui.common.ui.view.onLayoutChanged
import com.android.systemui.communal.domain.interactor.CommunalSettingsInteractor
@@ -36,11 +37,8 @@
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.DisposableHandle
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import com.android.app.tracing.coroutines.launchTraced as launch
/** Binds the shared notification container to its view-model. */
-@OptIn(ExperimentalCoroutinesApi::class)
@SysUISingleton
class SharedNotificationContainerBinder
@Inject
@@ -74,7 +72,7 @@
launch {
viewModel.configurationBasedDimensions.collect {
view.updateConstraints(
- useSplitShade = it.useSplitShade,
+ horizontalPosition = it.horizontalPosition,
marginStart = it.marginStart,
marginTop = it.marginTop,
marginEnd = it.marginEnd,
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 e6663d5..96d0d76 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
@@ -224,33 +224,54 @@
if (SceneContainerFlag.isEnabled) {
combine(
shadeInteractor.isShadeLayoutWide,
+ shadeInteractor.shadeMode,
configurationInteractor.onAnyConfigurationChange,
- ) { isShadeLayoutWide, _ ->
+ ) { isShadeLayoutWide, shadeMode, _ ->
with(context.resources) {
// TODO(b/338033836): Define separate horizontal margins for dual shade.
val marginHorizontal =
getDimensionPixelSize(R.dimen.notification_panel_margin_horizontal)
+
+ val horizontalPosition =
+ when (shadeMode) {
+ Single -> HorizontalPosition.EdgeToEdge
+ Split -> HorizontalPosition.MiddleToEdge(ratio = 0.5f)
+ Dual ->
+ if (isShadeLayoutWide) {
+ HorizontalPosition.FloatAtEnd(
+ width = getDimensionPixelSize(R.dimen.shade_panel_width)
+ )
+ } else {
+ HorizontalPosition.EdgeToEdge
+ }
+ }
+
ConfigurationBasedDimensions(
- marginStart = if (isShadeLayoutWide) 0 else marginHorizontal,
+ horizontalPosition = horizontalPosition,
+ marginStart =
+ if (horizontalPosition is HorizontalPosition.EdgeToEdge)
+ marginHorizontal
+ else 0,
marginEnd = marginHorizontal,
marginBottom =
getDimensionPixelSize(R.dimen.notification_panel_margin_bottom),
// y position of the NSSL in the window needs to be 0 under scene
// container
marginTop = 0,
- useSplitShade = isShadeLayoutWide,
)
}
}
} else {
interactor.configurationBasedDimensions.map {
ConfigurationBasedDimensions(
+ horizontalPosition =
+ if (it.useSplitShade) HorizontalPosition.MiddleToEdge()
+ else HorizontalPosition.EdgeToEdge,
marginStart = if (it.useSplitShade) 0 else it.marginHorizontal,
marginEnd = it.marginHorizontal,
marginBottom = it.marginBottom,
marginTop =
if (it.useLargeScreenHeader) it.marginTopLargeScreen else it.marginTop,
- useSplitShade = it.useSplitShade,
)
}
}
@@ -446,59 +467,63 @@
*/
private val alphaForShadeAndQsExpansion: Flow<Float> =
if (SceneContainerFlag.isEnabled) {
- shadeInteractor.shadeMode.flatMapLatest { shadeMode ->
- when (shadeMode) {
- Single ->
- combineTransform(
- shadeInteractor.shadeExpansion,
- shadeInteractor.qsExpansion,
- ) { shadeExpansion, qsExpansion ->
- if (qsExpansion == 1f) {
- // Ensure HUNs will be visible in QS shade (at least while unlocked)
+ shadeInteractor.shadeMode.flatMapLatest { shadeMode ->
+ when (shadeMode) {
+ Single ->
+ combineTransform(
+ shadeInteractor.shadeExpansion,
+ shadeInteractor.qsExpansion,
+ ) { shadeExpansion, qsExpansion ->
+ if (qsExpansion == 1f) {
+ // Ensure HUNs will be visible in QS shade (at least while
+ // unlocked)
+ emit(1f)
+ } else if (shadeExpansion > 0f || qsExpansion > 0f) {
+ // Fade as QS shade expands
+ emit(1f - qsExpansion)
+ }
+ }
+ Split -> isAnyExpanded.filter { it }.map { 1f }
+ Dual ->
+ combineTransform(
+ headsUpNotificationInteractor.get().isHeadsUpOrAnimatingAway,
+ shadeInteractor.shadeExpansion,
+ shadeInteractor.qsExpansion,
+ ) { isHeadsUpOrAnimatingAway, shadeExpansion, qsExpansion ->
+ if (isHeadsUpOrAnimatingAway) {
+ // Ensure HUNs will be visible in QS shade (at least while
+ // unlocked)
+ emit(1f)
+ } else if (shadeExpansion > 0f || qsExpansion > 0f) {
+ // Fade out as QS shade expands
+ emit(1f - qsExpansion)
+ }
+ }
+ }
+ }
+ } else {
+ interactor.configurationBasedDimensions.flatMapLatest { configurationBasedDimensions
+ ->
+ combineTransform(shadeInteractor.shadeExpansion, shadeInteractor.qsExpansion) {
+ shadeExpansion,
+ qsExpansion ->
+ if (shadeExpansion > 0f || qsExpansion > 0f) {
+ if (configurationBasedDimensions.useSplitShade) {
emit(1f)
- } else if (shadeExpansion > 0f || qsExpansion > 0f) {
+ } else if (qsExpansion == 1f) {
+ // Ensure HUNs will be visible in QS shade (at least while
+ // unlocked)
+ emit(1f)
+ } else {
// Fade as QS shade expands
emit(1f - qsExpansion)
}
}
- Split -> isAnyExpanded.filter { it }.map { 1f }
- Dual ->
- combineTransform(
- headsUpNotificationInteractor.get().isHeadsUpOrAnimatingAway,
- shadeInteractor.shadeExpansion,
- shadeInteractor.qsExpansion,
- ) { isHeadsUpOrAnimatingAway, shadeExpansion, qsExpansion ->
- if (isHeadsUpOrAnimatingAway) {
- // Ensure HUNs will be visible in QS shade (at least while unlocked)
- emit(1f)
- } else if (shadeExpansion > 0f || qsExpansion > 0f) {
- // Fade out as QS shade expands
- emit(1f - qsExpansion)
- }
- }
- }
- }
- } else {
- interactor.configurationBasedDimensions.flatMapLatest { configurationBasedDimensions ->
- combineTransform(shadeInteractor.shadeExpansion, shadeInteractor.qsExpansion) {
- shadeExpansion,
- qsExpansion ->
- if (shadeExpansion > 0f || qsExpansion > 0f) {
- if (configurationBasedDimensions.useSplitShade) {
- emit(1f)
- } else if (qsExpansion == 1f) {
- // Ensure HUNs will be visible in QS shade (at least while unlocked)
- emit(1f)
- } else {
- // Fade as QS shade expands
- emit(1f - qsExpansion)
- }
}
}
}
- }
- .onStart { emit(1f) }
- .dumpWhileCollecting("alphaForShadeAndQsExpansion")
+ .onStart { emit(1f) }
+ .dumpWhileCollecting("alphaForShadeAndQsExpansion")
val panelAlpha = keyguardInteractor.panelAlpha
@@ -766,10 +791,25 @@
}
data class ConfigurationBasedDimensions(
+ val horizontalPosition: HorizontalPosition,
val marginStart: Int,
val marginTop: Int,
val marginEnd: Int,
val marginBottom: Int,
- val useSplitShade: Boolean,
)
+
+ /** Specifies the horizontal layout constraints for the notification container. */
+ sealed interface HorizontalPosition {
+ /** The container is using the full width of the screen (minus any margins). */
+ data object EdgeToEdge : HorizontalPosition
+
+ /** The container is laid out from the given [ratio] of the screen width to the end edge. */
+ data class MiddleToEdge(val ratio: Float = 0.5f) : HorizontalPosition
+
+ /**
+ * The container has a fixed [width] and is aligned to the end of the screen. In this
+ * layout, the start edge of the container is floating, i.e. unconstrained.
+ */
+ data class FloatAtEnd(val width: Int) : HorizontalPosition
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/ui/dialog/composable/ModeTileGrid.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/ui/dialog/composable/ModeTileGrid.kt
index 5392e38..903c7e1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/ui/dialog/composable/ModeTileGrid.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/ui/dialog/composable/ModeTileGrid.kt
@@ -34,7 +34,7 @@
LazyVerticalGrid(
columns = GridCells.Fixed(1),
- modifier = Modifier.fillMaxWidth().heightIn(max = 320.dp),
+ modifier = Modifier.fillMaxWidth().heightIn(max = 280.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
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 61eeab3..48a3ada 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
@@ -138,6 +138,7 @@
PromptSelectorInteractorImpl(
fingerprintRepository,
displayStateInteractor,
+ credentialInteractor,
biometricPromptRepository,
lockPatternUtils,
)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/data/repository/KeyguardBypassRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/data/repository/KeyguardBypassRepositoryTest.kt
new file mode 100644
index 0000000..0c0b5ba
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/data/repository/KeyguardBypassRepositoryTest.kt
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.phone.data.repository
+
+import android.provider.Settings
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.EnableSceneContainer
+import com.android.systemui.keyguard.data.repository.KeyguardBypassRepository
+import com.android.systemui.keyguard.data.repository.configureKeyguardBypass
+import com.android.systemui.keyguard.data.repository.keyguardBypassRepository
+import com.android.systemui.keyguard.data.repository.verifyCallback
+import com.android.systemui.keyguard.data.repository.verifyNoCallback
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.statusbar.policy.DevicePostureController
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_CLOSED
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN
+import com.android.systemui.statusbar.policy.devicePostureController
+import com.android.systemui.testKosmos
+import com.android.systemui.tuner.TunerService
+import com.android.systemui.tuner.tunerService
+import com.android.systemui.util.mockito.withArgCaptor
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+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.anyInt
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+import org.mockito.junit.MockitoJUnit
+import org.mockito.junit.MockitoRule
+import org.mockito.kotlin.whenever
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+@EnableSceneContainer
+class KeyguardBypassRepositoryTest : SysuiTestCase() {
+ @JvmField @Rule val mockito: MockitoRule = MockitoJUnit.rule()
+
+ private lateinit var tunableCallback: TunerService.Tunable
+ private lateinit var postureControllerCallback: DevicePostureController.Callback
+
+ private val kosmos = testKosmos()
+ private lateinit var underTest: KeyguardBypassRepository
+ private val testScope = kosmos.testScope
+
+ @Before
+ fun setup() {
+ MockitoAnnotations.initMocks(this)
+ }
+
+ // overrideFaceBypassSetting overridden to true
+ // isFaceEnrolledAndEnabled true
+ // isPostureAllowedForFaceAuth true/false on posture changes
+ @Test
+ fun updatesBypassAvailableOnPostureChanges_bypassOverrideAlways() =
+ testScope.runTest {
+ // KeyguardBypassRepository#overrideFaceBypassSetting = true due to ALWAYS override
+ // Initialize face auth posture to DEVICE_POSTURE_OPENED config
+ initUnderTest(
+ faceUnlockBypassOverrideConfig = FACE_UNLOCK_BYPASS_ALWAYS,
+ faceAuthPostureConfig = DEVICE_POSTURE_CLOSED,
+ )
+ val isBypassAvailable by collectLastValue(underTest.isBypassAvailable)
+ runCurrent()
+
+ postureControllerCallback = kosmos.devicePostureController.verifyCallback()
+
+ // Update face auth posture to match config
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_CLOSED)
+
+ // Assert bypass available
+ assertThat(isBypassAvailable).isTrue()
+
+ // Set face auth posture to not match config
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_OPENED)
+
+ // Assert bypass not available
+ assertThat(isBypassAvailable).isFalse()
+ }
+
+ // overrideFaceBypassSetting overridden to false
+ // isFaceEnrolledAndEnabled true
+ // isPostureAllowedForFaceAuth true/false on posture changes
+ @Test
+ fun updatesBypassEnabledOnPostureChanges_bypassOverrideNever() =
+ testScope.runTest {
+ // KeyguardBypassRepository#overrideFaceBypassSetting = false due to NEVER override
+ // Initialize face auth posture to DEVICE_POSTURE_OPENED config
+ initUnderTest(
+ faceUnlockBypassOverrideConfig = FACE_UNLOCK_BYPASS_NEVER,
+ faceAuthPostureConfig = DEVICE_POSTURE_CLOSED,
+ )
+ val bypassEnabled by collectLastValue(underTest.isBypassAvailable)
+ runCurrent()
+ postureControllerCallback = kosmos.devicePostureController.verifyCallback()
+
+ // Update face auth posture to match config
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_CLOSED)
+
+ // Assert bypass not enabled
+ assertThat(bypassEnabled).isFalse()
+
+ // Set face auth posture to not match config
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_OPENED)
+
+ // Assert bypass not enabled
+ assertThat(bypassEnabled).isFalse()
+ }
+
+ // overrideFaceBypassSetting set true/false depending on Setting
+ // isFaceEnrolledAndEnabled true
+ // isPostureAllowedForFaceAuth true
+ @Test
+ fun updatesBypassEnabledOnSettingsChanges_bypassNoOverride_devicePostureMatchesConfig() =
+ testScope.runTest {
+ // No bypass override
+ // Initialize face auth posture to DEVICE_POSTURE_OPENED config
+ initUnderTest(
+ faceUnlockBypassOverrideConfig = FACE_UNLOCK_BYPASS_NO_OVERRIDE,
+ faceAuthPostureConfig = DEVICE_POSTURE_CLOSED,
+ )
+
+ val bypassEnabled by collectLastValue(underTest.isBypassAvailable)
+ runCurrent()
+ postureControllerCallback = kosmos.devicePostureController.verifyCallback()
+ tunableCallback = kosmos.tunerService.captureCallback()
+
+ // Update face auth posture to match config
+ postureControllerCallback.onPostureChanged(DEVICE_POSTURE_CLOSED)
+
+ // FACE_UNLOCK_DISMISSES_KEYGUARD setting true
+ whenever(kosmos.tunerService.getValue(eq(faceUnlockDismissesKeyguard), anyInt()))
+ .thenReturn(1)
+ tunableCallback.onTuningChanged(faceUnlockDismissesKeyguard, "")
+
+ runCurrent()
+ // Assert bypass enabled
+ assertThat(bypassEnabled).isTrue()
+
+ // FACE_UNLOCK_DISMISSES_KEYGUARD setting false
+ whenever(kosmos.tunerService.getValue(eq(faceUnlockDismissesKeyguard), anyInt()))
+ .thenReturn(0)
+ tunableCallback.onTuningChanged(faceUnlockDismissesKeyguard, "")
+
+ runCurrent()
+ // Assert bypass not enabled
+ assertThat(bypassEnabled).isFalse()
+ }
+
+ // overrideFaceBypassSetting overridden to true
+ // isFaceEnrolledAndEnabled true
+ // isPostureAllowedForFaceAuth always true given DEVICE_POSTURE_UNKNOWN config
+ @Test
+ fun bypassEnabledTrue_bypassAlways_unknownDevicePostureConfig() =
+ testScope.runTest {
+ // KeyguardBypassRepository#overrideFaceBypassSetting = true due to ALWAYS override
+ // Set face auth posture config to unknown
+ initUnderTest(
+ faceUnlockBypassOverrideConfig = FACE_UNLOCK_BYPASS_ALWAYS,
+ faceAuthPostureConfig = DEVICE_POSTURE_UNKNOWN,
+ )
+ val bypassEnabled by collectLastValue(underTest.isBypassAvailable)
+ kosmos.devicePostureController.verifyNoCallback()
+
+ // Assert bypass enabled
+ assertThat(bypassEnabled).isTrue()
+ }
+
+ // overrideFaceBypassSetting overridden to false
+ // isFaceEnrolledAndEnabled true
+ // isPostureAllowedForFaceAuth always true given DEVICE_POSTURE_UNKNOWN config
+ @Test
+ fun bypassEnabledFalse_bypassNever_unknownDevicePostureConfig() =
+ testScope.runTest {
+ // KeyguardBypassRepository#overrideFaceBypassSetting = false due to NEVER override
+ // Set face auth posture config to unknown
+ initUnderTest(
+ faceUnlockBypassOverrideConfig = FACE_UNLOCK_BYPASS_NEVER,
+ faceAuthPostureConfig = DEVICE_POSTURE_UNKNOWN,
+ )
+ val bypassEnabled by collectLastValue(underTest.isBypassAvailable)
+ kosmos.devicePostureController.verifyNoCallback()
+
+ // Assert bypass enabled
+ assertThat(bypassEnabled).isFalse()
+ }
+
+ private fun TestScope.initUnderTest(
+ faceUnlockBypassOverrideConfig: Int,
+ faceAuthPostureConfig: Int,
+ ) {
+ kosmos.configureKeyguardBypass(
+ faceAuthEnrolledAndEnabled = true,
+ faceUnlockBypassOverrideConfig = faceUnlockBypassOverrideConfig,
+ faceAuthPostureConfig = faceAuthPostureConfig,
+ )
+ underTest = kosmos.keyguardBypassRepository
+ runCurrent()
+ }
+
+ companion object {
+ private const val FACE_UNLOCK_BYPASS_NO_OVERRIDE = 0
+ private const val FACE_UNLOCK_BYPASS_ALWAYS = 1
+ private const val FACE_UNLOCK_BYPASS_NEVER = 2
+ }
+}
+
+private const val faceUnlockDismissesKeyguard = Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD
+
+private fun TunerService.captureCallback() =
+ withArgCaptor<TunerService.Tunable> {
+ verify(this@captureCallback).addTunable(capture(), eq(faceUnlockDismissesKeyguard))
+ }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/SysUITestModule.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/SysUITestModule.kt
index 020f7fa..c945812 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/SysUITestModule.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/SysUITestModule.kt
@@ -30,6 +30,8 @@
import com.android.systemui.deviceentry.data.repository.FaceWakeUpTriggersConfigModule
import com.android.systemui.deviceentry.domain.interactor.DeviceEntryFaceAuthInteractor
import com.android.systemui.deviceentry.domain.interactor.SystemUIDeviceEntryFaceAuthInteractor
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.data.repository.PulseExpansionRepository
import com.android.systemui.keyguard.ui.composable.blueprint.DefaultBlueprintModule
import com.android.systemui.scene.SceneContainerFrameworkModule
import com.android.systemui.scene.shared.flag.SceneContainerFlag
@@ -70,11 +72,17 @@
interface SysUITestModule {
@Binds fun bindTestableContext(sysuiTestableContext: SysuiTestableContext): TestableContext
+
@Binds fun bindContext(testableContext: TestableContext): Context
+
@Binds @Application fun bindAppContext(context: Context): Context
+
@Binds @Application fun bindAppResources(resources: Resources): Resources
+
@Binds @Main fun bindMainResources(resources: Resources): Resources
+
@Binds fun bindBroadcastDispatcher(fake: FakeBroadcastDispatcher): BroadcastDispatcher
+
@Binds @SysUISingleton fun bindsShadeInteractor(sii: ShadeInteractorImpl): ShadeInteractor
@Binds
@@ -108,7 +116,7 @@
@Provides
fun provideBaseShadeInteractor(
sceneContainerOn: Provider<ShadeInteractorSceneContainerImpl>,
- sceneContainerOff: Provider<ShadeInteractorLegacyImpl>
+ sceneContainerOff: Provider<ShadeInteractorLegacyImpl>,
): BaseShadeInteractor {
return if (SceneContainerFlag.isEnabled) {
sceneContainerOn.get()
@@ -125,6 +133,12 @@
): SceneDataSourceDelegator {
return SceneDataSourceDelegator(applicationScope, config)
}
+
+ @Provides
+ @SysUISingleton
+ fun providesPulseExpansionRepository(dumpManager: DumpManager): PulseExpansionRepository {
+ return PulseExpansionRepository(dumpManager)
+ }
}
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorKosmos.kt
index 56297f0..787a471 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/biometrics/domain/interactor/PromptSelectorInteractorKosmos.kt
@@ -27,6 +27,7 @@
fingerprintPropertyRepository = fingerprintPropertyRepository,
displayStateInteractor = displayStateInteractor,
promptRepository = promptRepository,
- lockPatternUtils = lockPatternUtils
+ credentialInteractor = FakeCredentialInteractor(),
+ lockPatternUtils = lockPatternUtils,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorKosmos.kt
index 878e385..2a7e3e9 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryHapticsInteractorKosmos.kt
@@ -20,6 +20,7 @@
import com.android.keyguard.logging.biometricUnlockLogger
import com.android.systemui.biometrics.data.repository.fingerprintPropertyRepository
+import com.android.systemui.dump.dumpManager
import com.android.systemui.keyevent.domain.interactor.keyEventInteractor
import com.android.systemui.keyguard.data.repository.biometricSettingsRepository
import com.android.systemui.kosmos.Kosmos
@@ -27,17 +28,19 @@
import com.android.systemui.util.time.systemClock
import kotlinx.coroutines.ExperimentalCoroutinesApi
+@OptIn(ExperimentalCoroutinesApi::class)
val Kosmos.deviceEntryHapticsInteractor by
Kosmos.Fixture {
DeviceEntryHapticsInteractor(
- deviceEntrySourceInteractor = deviceEntrySourceInteractor,
- deviceEntryFingerprintAuthInteractor = deviceEntryFingerprintAuthInteractor,
- deviceEntryBiometricAuthInteractor = deviceEntryBiometricAuthInteractor,
- fingerprintPropertyRepository = fingerprintPropertyRepository,
biometricSettingsRepository = biometricSettingsRepository,
+ deviceEntryBiometricAuthInteractor = deviceEntryBiometricAuthInteractor,
+ deviceEntryFingerprintAuthInteractor = deviceEntryFingerprintAuthInteractor,
+ deviceEntrySourceInteractor = deviceEntrySourceInteractor,
+ fingerprintPropertyRepository = fingerprintPropertyRepository,
keyEventInteractor = keyEventInteractor,
+ logger = biometricUnlockLogger,
powerInteractor = powerInteractor,
systemClock = systemClock,
- logger = biometricUnlockLogger,
+ dumpManager = dumpManager,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorKosmos.kt
index 0b9ec92..f91a044 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntrySourceInteractorKosmos.kt
@@ -16,14 +16,34 @@
package com.android.systemui.deviceentry.domain.interactor
+import com.android.keyguard.keyguardUpdateMonitor
+import com.android.systemui.authentication.domain.interactor.authenticationInteractor
+import com.android.systemui.biometrics.authController
+import com.android.systemui.bouncer.domain.interactor.alternateBouncerInteractor
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.domain.interactor.keyguardBypassInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.scene.domain.interactor.sceneContainerOcclusionInteractor
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.statusbar.phone.dozeScrimController
import kotlinx.coroutines.ExperimentalCoroutinesApi
@ExperimentalCoroutinesApi
val Kosmos.deviceEntrySourceInteractor by
Kosmos.Fixture {
DeviceEntrySourceInteractor(
+ authenticationInteractor = authenticationInteractor,
+ authController = authController,
+ alternateBouncerInteractor = alternateBouncerInteractor,
+ deviceEntryFaceAuthInteractor = deviceEntryFaceAuthInteractor,
+ deviceEntryFingerprintAuthInteractor = deviceEntryFingerprintAuthInteractor,
+ dozeScrimController = dozeScrimController,
+ keyguardBypassInteractor = keyguardBypassInteractor,
+ keyguardUpdateMonitor = keyguardUpdateMonitor,
keyguardInteractor = keyguardInteractor,
+ sceneContainerOcclusionInteractor = sceneContainerOcclusionInteractor,
+ sceneInteractor = sceneInteractor,
+ dumpManager = dumpManager,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/FakeIHomeControlsRemoteProxyBinder.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/FakeIHomeControlsRemoteProxyBinder.kt
new file mode 100644
index 0000000..f469d74
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/FakeIHomeControlsRemoteProxyBinder.kt
@@ -0,0 +1,40 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import android.content.ComponentName
+import com.android.systemui.dreams.homecontrols.shared.IHomeControlsRemoteProxy
+import com.android.systemui.dreams.homecontrols.shared.IOnControlsSettingsChangeListener
+
+/** Fake binder implementation of [IHomeControlsRemoteProxy] */
+class FakeIHomeControlsRemoteProxyBinder : IHomeControlsRemoteProxy.Stub() {
+ val callbacks = mutableSetOf<IOnControlsSettingsChangeListener>()
+
+ override fun registerListenerForCurrentUser(callback: IOnControlsSettingsChangeListener) {
+ callbacks.add(callback)
+ }
+
+ override fun unregisterListenerForCurrentUser(callback: IOnControlsSettingsChangeListener) {
+ callbacks.remove(callback)
+ }
+
+ fun notifyCallbacks(component: ComponentName, allowTrivialControlsOnLockscreen: Boolean) {
+ for (callback in callbacks.toSet()) {
+ callback.onControlsSettingsChanged(component, allowTrivialControlsOnLockscreen)
+ }
+ }
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyKosmos.kt
new file mode 100644
index 0000000..58ebbf4
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/HomeControlsRemoteProxyKosmos.kt
@@ -0,0 +1,33 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.applicationCoroutineScope
+
+val Kosmos.homeControlsRemoteProxy by
+ Kosmos.Fixture {
+ HomeControlsRemoteProxy(
+ bgScope = applicationCoroutineScope,
+ proxy = fakeHomeControlsRemoteBinder,
+ dumpManager = dumpManager,
+ )
+ }
+
+val Kosmos.fakeHomeControlsRemoteBinder by
+ Kosmos.Fixture<FakeIHomeControlsRemoteProxyBinder> { FakeIHomeControlsRemoteProxyBinder() }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorKosmos.kt
new file mode 100644
index 0000000..c85c888
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/service/RemoteHomeControlsDataSourceDelegatorKosmos.kt
@@ -0,0 +1,37 @@
+/*
+ * 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.dreams.homecontrols.service
+
+import com.android.systemui.dreams.homecontrols.dagger.HomeControlsRemoteServiceComponent
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.applicationCoroutineScope
+import com.android.systemui.log.logcatLogBuffer
+import org.mockito.kotlin.mock
+
+val Kosmos.remoteHomeControlsDataSourceDelegator by
+ Kosmos.Fixture {
+ RemoteHomeControlsDataSourceDelegator(
+ bgScope = applicationCoroutineScope,
+ serviceFactory = homeControlsRemoteServiceFactory,
+ logBuffer = logcatLogBuffer("HomeControlsDreamInteractor"),
+ dumpManager = dumpManager,
+ )
+ }
+
+var Kosmos.homeControlsRemoteServiceFactory by
+ Kosmos.Fixture<HomeControlsRemoteServiceComponent.Factory> { mock() }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/FakeHomeControlsDataSource.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/FakeHomeControlsDataSource.kt
new file mode 100644
index 0000000..f8ea022
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/FakeHomeControlsDataSource.kt
@@ -0,0 +1,33 @@
+/*
+ * 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.dreams.homecontrols.shared.model
+
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.filterNotNull
+
+class FakeHomeControlsDataSource : HomeControlsDataSource {
+
+ private val _componentInfo = MutableStateFlow<HomeControlsComponentInfo?>(null)
+
+ override val componentInfo: Flow<HomeControlsComponentInfo>
+ get() = _componentInfo.filterNotNull()
+
+ fun setComponentInfo(info: HomeControlsComponentInfo) {
+ _componentInfo.value = info
+ }
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSourceKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSourceKosmos.kt
new file mode 100644
index 0000000..942216b
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/shared/model/HomeControlsDataSourceKosmos.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.dreams.homecontrols.shared.model
+
+import com.android.systemui.kosmos.Kosmos
+
+val Kosmos.homeControlsDataSource by
+ Kosmos.Fixture<HomeControlsDataSource> { fakeHomeControlsDataSource }
+
+val Kosmos.fakeHomeControlsDataSource by
+ Kosmos.Fixture<FakeHomeControlsDataSource> { FakeHomeControlsDataSource() }
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorKosmos.kt
similarity index 75%
rename from packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorKosmos.kt
rename to packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorKosmos.kt
index 7d7841f..a1182a1 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/dreams/homecontrols/HomeControlsComponentInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/dreams/homecontrols/system/domain/interactor/HomeControlsComponentInteractorKosmos.kt
@@ -13,21 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.systemui.dreams.homecontrols
+package com.android.systemui.dreams.homecontrols.system.domain.interactor
-import android.os.powerManager
-import android.service.dream.dreamManager
-import com.android.systemui.common.domain.interactor.packageChangeInteractor
import com.android.systemui.controls.dagger.ControlsComponent
import com.android.systemui.controls.management.ControlsListingController
import com.android.systemui.controls.panels.authorizedPanelsRepository
import com.android.systemui.controls.panels.selectedComponentRepository
-import com.android.systemui.dreams.homecontrols.domain.interactor.HomeControlsComponentInteractor
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.applicationCoroutineScope
import com.android.systemui.user.data.repository.fakeUserRepository
import com.android.systemui.util.mockito.mock
-import com.android.systemui.util.time.fakeSystemClock
val Kosmos.homeControlsComponentInteractor by
Kosmos.Fixture {
@@ -37,10 +32,6 @@
authorizedPanelsRepository = authorizedPanelsRepository,
userRepository = fakeUserRepository,
bgScope = applicationCoroutineScope,
- systemClock = fakeSystemClock,
- powerManager = powerManager,
- dreamManager = dreamManager,
- packageChangeInteractor = packageChangeInteractor,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/KeyguardQuickAffordanceProviderClientFactoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/KeyguardQuickAffordanceProviderClientFactoryKosmos.kt
new file mode 100644
index 0000000..fd882a8
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/KeyguardQuickAffordanceProviderClientFactoryKosmos.kt
@@ -0,0 +1,23 @@
+/*
+ * 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.data.quickaffordance
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.settings.userTracker
+
+val Kosmos.keyguardQuickAffordanceProviderClientFactory by
+ Kosmos.Fixture { FakeKeyguardQuickAffordanceProviderClientFactory(userTracker) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/LocalUserSelectionManagerKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/LocalUserSelectionManagerKosmos.kt
new file mode 100644
index 0000000..21d1a76
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/LocalUserSelectionManagerKosmos.kt
@@ -0,0 +1,33 @@
+/*
+ * 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.data.quickaffordance
+
+import android.content.applicationContext
+import com.android.systemui.broadcast.broadcastDispatcher
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.settings.userFileManager
+import com.android.systemui.settings.userTracker
+
+val Kosmos.localUserSelectionManager by
+ Kosmos.Fixture {
+ KeyguardQuickAffordanceLocalUserSelectionManager(
+ context = applicationContext,
+ userFileManager = userFileManager,
+ userTracker = userTracker,
+ broadcastDispatcher = broadcastDispatcher,
+ )
+ }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/RemoteUserSelectionManagerKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/RemoteUserSelectionManagerKosmos.kt
new file mode 100644
index 0000000..ec63071
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/quickaffordance/RemoteUserSelectionManagerKosmos.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.data.quickaffordance
+
+import android.os.UserHandle
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.settings.userTracker
+
+val Kosmos.remoteUserSelectionManager by
+ Kosmos.Fixture {
+ KeyguardQuickAffordanceRemoteUserSelectionManager(
+ scope = testScope.backgroundScope,
+ userTracker = userTracker,
+ clientFactory = keyguardQuickAffordanceProviderClientFactory,
+ userHandle = UserHandle.SYSTEM,
+ )
+ }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/DevicePostureRepositoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/DevicePostureRepositoryKosmos.kt
index 9bbb34c..84eea62 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/DevicePostureRepositoryKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/DevicePostureRepositoryKosmos.kt
@@ -17,6 +17,8 @@
package com.android.systemui.keyguard.data.repository
import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.statusbar.policy.devicePostureController
val Kosmos.devicePostureRepository: DevicePostureRepository by
- Kosmos.Fixture { FakeDevicePostureRepository() }
+ Kosmos.Fixture { DevicePostureRepositoryImpl(devicePostureController, testDispatcher) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepositoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepositoryKosmos.kt
new file mode 100644
index 0000000..c91823c
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardBypassRepositoryKosmos.kt
@@ -0,0 +1,94 @@
+/*
+ * 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.data.repository
+
+import android.content.testableContext
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.res.R
+import com.android.systemui.statusbar.policy.DevicePostureController
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_CLOSED
+import com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN
+import com.android.systemui.tuner.tunerService
+import com.android.systemui.util.mockito.withArgCaptor
+import org.mockito.ArgumentMatchers.any
+import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
+
+val Kosmos.keyguardBypassRepository: KeyguardBypassRepository by Fixture {
+ KeyguardBypassRepository(
+ testableContext.resources,
+ biometricSettingsRepository,
+ devicePostureRepository,
+ dumpManager,
+ tunerService,
+ testDispatcher,
+ )
+}
+
+fun Kosmos.configureKeyguardBypass(
+ isBypassAvailable: Boolean? = null,
+ faceAuthEnrolledAndEnabled: Boolean = true,
+ faceUnlockBypassOverrideConfig: Int = 0, /* FACE_UNLOCK_BYPASS_NO_OVERRIDE */
+ faceAuthPostureConfig: Int = DEVICE_POSTURE_UNKNOWN,
+) {
+ when (isBypassAvailable) {
+ null -> {
+ biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(faceAuthEnrolledAndEnabled)
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_unlock_bypass_override,
+ faceUnlockBypassOverrideConfig,
+ )
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_auth_supported_posture,
+ faceAuthPostureConfig,
+ )
+ }
+ true -> {
+ biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_unlock_bypass_override,
+ 1, /* FACE_UNLOCK_BYPASS_ALWAYS */
+ )
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_auth_supported_posture,
+ DEVICE_POSTURE_UNKNOWN,
+ )
+ }
+ false -> {
+ biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_unlock_bypass_override,
+ 2, /* FACE_UNLOCK_BYPASS_NEVER */
+ )
+ testableContext.orCreateTestableResources.addOverride(
+ R.integer.config_face_auth_supported_posture,
+ DEVICE_POSTURE_CLOSED,
+ )
+ }
+ }
+}
+
+fun DevicePostureController.verifyCallback() =
+ withArgCaptor<DevicePostureController.Callback> {
+ verify(this@verifyCallback).addCallback(capture())
+ }
+
+fun DevicePostureController.verifyNoCallback() =
+ verify(this@verifyNoCallback, never()).addCallback(any())
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepositoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepositoryKosmos.kt
new file mode 100644
index 0000000..a6d4ec5
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/KeyguardQuickAffordanceRepositoryKosmos.kt
@@ -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.systemui.keyguard.data.repository
+
+import android.content.applicationContext
+import android.os.UserHandle
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.data.quickaffordance.localUserSelectionManager
+import com.android.systemui.keyguard.data.quickaffordance.remoteUserSelectionManager
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.settings.userTracker
+import org.mockito.kotlin.mock
+
+val Kosmos.keyguardQuickAffordanceRepository by Fixture {
+ KeyguardQuickAffordanceRepository(
+ appContext = applicationContext,
+ scope = testScope.backgroundScope,
+ localUserSelectionManager = localUserSelectionManager,
+ remoteUserSelectionManager = remoteUserSelectionManager,
+ userTracker = userTracker,
+ legacySettingSyncer = mock(),
+ configs = setOf(),
+ dumpManager = dumpManager,
+ userHandle = UserHandle.SYSTEM,
+ )
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepositoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepositoryKosmos.kt
new file mode 100644
index 0000000..1851774
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/PulseExpansionRepositoryKosmos.kt
@@ -0,0 +1,23 @@
+/*
+ * 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.data.repository
+
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.kosmos.Kosmos
+
+val Kosmos.pulseExpansionRepository: PulseExpansionRepository by
+ Kosmos.Fixture { PulseExpansionRepository(dumpManager) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractorKosmos.kt
new file mode 100644
index 0000000..59ef9df
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardBypassInteractorKosmos.kt
@@ -0,0 +1,37 @@
+/*
+ * 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.domain.interactor
+
+import com.android.systemui.bouncer.domain.interactor.alternateBouncerInteractor
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.data.repository.keyguardBypassRepository
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.shade.domain.interactor.shadeInteractor
+
+val Kosmos.keyguardBypassInteractor by Fixture {
+ KeyguardBypassInteractor(
+ keyguardBypassRepository,
+ alternateBouncerInteractor,
+ keyguardQuickAffordanceInteractor,
+ pulseExpansionInteractor,
+ sceneInteractor,
+ shadeInteractor,
+ dumpManager,
+ )
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorKosmos.kt
new file mode 100644
index 0000000..009d17e
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardQuickAffordanceInteractorKosmos.kt
@@ -0,0 +1,59 @@
+/*
+ * 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.domain.interactor
+
+import android.app.admin.devicePolicyManager
+import android.content.applicationContext
+import com.android.internal.widget.lockPatternUtils
+import com.android.keyguard.logging.KeyguardQuickAffordancesLogger
+import com.android.systemui.animation.dialogTransitionAnimator
+import com.android.systemui.dock.dockManager
+import com.android.systemui.flags.featureFlagsClassic
+import com.android.systemui.keyguard.data.repository.biometricSettingsRepository
+import com.android.systemui.keyguard.data.repository.keyguardQuickAffordanceRepository
+import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancesMetricsLogger
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.plugins.activityStarter
+import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.settings.userTracker
+import com.android.systemui.shade.domain.interactor.shadeInteractor
+import com.android.systemui.statusbar.policy.keyguardStateController
+import org.mockito.kotlin.mock
+
+var Kosmos.keyguardQuickAffordanceInteractor by Fixture {
+ KeyguardQuickAffordanceInteractor(
+ keyguardInteractor = keyguardInteractor,
+ shadeInteractor = shadeInteractor,
+ lockPatternUtils = lockPatternUtils,
+ keyguardStateController = keyguardStateController,
+ userTracker = userTracker,
+ activityStarter = activityStarter,
+ featureFlags = featureFlagsClassic,
+ repository = { keyguardQuickAffordanceRepository },
+ launchAnimator = dialogTransitionAnimator,
+ logger = mock<KeyguardQuickAffordancesLogger>(),
+ metricsLogger = mock<KeyguardQuickAffordancesMetricsLogger>(),
+ devicePolicyManager = devicePolicyManager,
+ dockManager = dockManager,
+ biometricSettingsRepository = biometricSettingsRepository,
+ backgroundDispatcher = testDispatcher,
+ appContext = applicationContext,
+ sceneInteractor = { sceneInteractor },
+ )
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractorKosmos.kt
new file mode 100644
index 0000000..f02e0a4
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/PulseExpansionInteractorKosmos.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.domain.interactor
+
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.data.repository.pulseExpansionRepository
+import com.android.systemui.kosmos.Kosmos
+
+val Kosmos.pulseExpansionInteractor: PulseExpansionInteractor by
+ Kosmos.Fixture { PulseExpansionInteractor(pulseExpansionRepository, dumpManager) }
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 3c87106..3ab686d 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
@@ -21,6 +21,7 @@
import com.android.systemui.deviceentry.domain.interactor.deviceEntryInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.Kosmos.Fixture
import com.android.systemui.kosmos.applicationCoroutineScope
@@ -41,6 +42,7 @@
communalInteractor = communalInteractor,
keyguardTransitionInteractor = keyguardTransitionInteractor,
notificationsKeyguardInteractor = notificationsKeyguardInteractor,
+ pulseExpansionInteractor = pulseExpansionInteractor,
aodNotificationIconViewModel = notificationIconContainerAlwaysOnDisplayViewModel,
notificationShadeWindowModel = notificationShadeWindowModel,
alternateBouncerToAodTransitionViewModel = alternateBouncerToAodTransitionViewModel,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
index 522c387..5eaa198 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/kosmos/KosmosJavaAdapter.kt
@@ -50,6 +50,7 @@
import com.android.systemui.keyguard.domain.interactor.keyguardClockInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
import com.android.systemui.model.sceneContainerPlugin
import com.android.systemui.plugins.statusbar.statusBarStateController
import com.android.systemui.power.data.repository.fakePowerRepository
@@ -124,6 +125,7 @@
val sceneBackInteractor by lazy { kosmos.sceneBackInteractor }
val falsingCollector by lazy { kosmos.falsingCollector }
val powerInteractor by lazy { kosmos.powerInteractor }
+ val pulseExpansionInteractor by lazy { kosmos.pulseExpansionInteractor }
val deviceEntryInteractor by lazy { kosmos.deviceEntryInteractor }
val deviceEntryUdfpsInteractor by lazy { kosmos.deviceEntryUdfpsInteractor }
val deviceUnlockedInteractor by lazy { kosmos.deviceUnlockedInteractor }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/CameraLauncherKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/CameraLauncherKosmos.kt
new file mode 100644
index 0000000..d6dd867
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/CameraLauncherKosmos.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.shade
+
+import com.android.systemui.camera.cameraGestureHelper
+import com.android.systemui.keyguard.domain.interactor.keyguardQuickAffordanceInteractor
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.statusbar.phone.keyguardBypassController
+
+val Kosmos.cameraLauncher by
+ Kosmos.Fixture {
+ CameraLauncher(cameraGestureHelper, keyguardBypassController) {
+ keyguardQuickAffordanceInteractor
+ }
+ }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/domain/interactor/NotificationsKeyguardInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/domain/interactor/NotificationsKeyguardInteractorKosmos.kt
index 61a38b8..9c2a2be 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/domain/interactor/NotificationsKeyguardInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/domain/interactor/NotificationsKeyguardInteractorKosmos.kt
@@ -22,7 +22,5 @@
import com.android.systemui.statusbar.notification.domain.interactor.NotificationsKeyguardInteractor
val Kosmos.notificationsKeyguardInteractor by Fixture {
- NotificationsKeyguardInteractor(
- repository = notificationsKeyguardViewStateRepository,
- )
+ NotificationsKeyguardInteractor(repository = notificationsKeyguardViewStateRepository)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/tuner/TunerServiceKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/tuner/TunerServiceKosmos.kt
new file mode 100644
index 0000000..9bc3ae9
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/tuner/TunerServiceKosmos.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.tuner
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import org.mockito.kotlin.mock
+
+val Kosmos.tunerService by Fixture { mock<TunerService>() }
diff --git a/ravenwood/TEST_MAPPING b/ravenwood/TEST_MAPPING
index 7fa0ef1..a1243e3 100644
--- a/ravenwood/TEST_MAPPING
+++ b/ravenwood/TEST_MAPPING
@@ -35,18 +35,18 @@
},
{
"name": "CarLibHostUnitTest",
- "host": true,
- "keywords": ["automotive_code_coverage"]
+ "keywords": ["automotive_code_coverage"],
+ "host": true
},
{
"name": "CarServiceHostUnitTest",
- "host": true,
- "keywords": ["automotive_code_coverage"]
+ "keywords": ["automotive_code_coverage"],
+ "host": true
},
{
"name": "CarSystemUIRavenTests",
- "host": true,
- "keywords": ["automotive_code_coverage"]
+ "keywords": ["automotive_code_coverage"],
+ "host": true
},
{
"name": "CtsAccountManagerTestCasesRavenwood",
@@ -65,6 +65,10 @@
"host": true
},
{
+ "name": "CtsDeviceConfigTestCasesRavenwood",
+ "host": true
+ },
+ {
"name": "CtsGraphicsTestCasesRavenwood",
"host": true
},
diff --git a/ravenwood/scripts/update-test-mapping.sh b/ravenwood/scripts/update-test-mapping.sh
index e478b50..ab37baf 100755
--- a/ravenwood/scripts/update-test-mapping.sh
+++ b/ravenwood/scripts/update-test-mapping.sh
@@ -23,6 +23,14 @@
# Tests that shouldn't be in presubmit.
EXEMPT='^(SystemUiRavenTests)$'
+is_car() {
+ local module="$1"
+
+ # If the module name starts with "Car", then it's a test for "Car".
+ [[ "$module" =~ ^Car ]]
+ return $?
+}
+
main() {
local script_name="${0##*/}"
local script_dir="${0%/*}"
@@ -62,6 +70,10 @@
fi
echo " {"
echo " \"name\": \"${tests[$i]}\","
+ if is_car "${tests[$i]}"; then
+ echo ' "keywords": ["automotive_code_coverage"],'
+ fi
+
echo " \"host\": true"
echo " }$comma"
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index c6fe497..974cba2 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -52,6 +52,7 @@
import static com.android.internal.accessibility.common.ShortcutConstants.CHOOSER_PACKAGE_NAME;
import static com.android.internal.accessibility.common.ShortcutConstants.USER_SHORTCUT_TYPES;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType;
+import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.ALL;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.GESTURE;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.HARDWARE;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.QUICK_SETTINGS;
@@ -3897,6 +3898,7 @@
userState.getShortcutTargetsLocked(HARDWARE);
final Set<String> qsShortcutTargets =
userState.getShortcutTargetsLocked(QUICK_SETTINGS);
+ final Set<String> shortcutTargets = userState.getShortcutTargetsLocked(ALL);
userState.mEnabledServices.forEach(componentName -> {
if (packageName != null && componentName != null
&& !packageName.equals(componentName.getPackageName())) {
@@ -3917,7 +3919,11 @@
if (TextUtils.isEmpty(serviceName)) {
return;
}
- if (doesShortcutTargetsStringContain(buttonTargets, serviceName)
+ if (android.provider.Flags.a11yStandaloneGestureEnabled()) {
+ if (doesShortcutTargetsStringContain(shortcutTargets, serviceName)) {
+ return;
+ }
+ } else if (doesShortcutTargetsStringContain(buttonTargets, serviceName)
|| doesShortcutTargetsStringContain(shortcutKeyTargets, serviceName)
|| doesShortcutTargetsStringContain(qsShortcutTargets, serviceName)) {
return;
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
index 0bf7ec00..67b4063 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
@@ -106,21 +106,17 @@
final Set<ComponentName> mTouchExplorationGrantedServices = new HashSet<>();
- private final ArraySet<String> mAccessibilityShortcutKeyTargets = new ArraySet<>();
-
- private final ArraySet<String> mAccessibilityButtonTargets = new ArraySet<>();
- private final ArraySet<String> mAccessibilityGestureTargets = new ArraySet<>();
- private final ArraySet<String> mAccessibilityQsTargets = new ArraySet<>();
+ private final HashMap<Integer, ArraySet<String>> mShortcutTargets = new HashMap<>();
/**
- * The QuickSettings tiles in the QS Panel. This can be different from
- * {@link #mAccessibilityQsTargets} in that {@link #mA11yTilesInQsPanel} stores the
+ * The QuickSettings tiles in the QS Panel. This can be different from the QS targets in
+ * {@link #mShortcutTargets} in that {@link #mA11yTilesInQsPanel} stores the
* TileService's or the a11y framework tile component names (e.g.
* {@link AccessibilityShortcutController#COLOR_INVERSION_TILE_COMPONENT_NAME}) instead of the
* A11y Feature's component names.
* <p/>
* In addition, {@link #mA11yTilesInQsPanel} stores what's on the QS Panel, whereas
- * {@link #mAccessibilityQsTargets} stores the targets that configured qs as their shortcut and
+ * {@link #mShortcutTargets} stores the targets that configured qs as their shortcut and
* also grant full device control permission.
*/
private final ArraySet<ComponentName> mA11yTilesInQsPanel = new ArraySet<>();
@@ -208,6 +204,11 @@
mSupportWindowMagnification = mContext.getResources().getBoolean(
R.bool.config_magnification_area) && mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WINDOW_MAGNIFICATION);
+
+ mShortcutTargets.put(HARDWARE, new ArraySet<>());
+ mShortcutTargets.put(SOFTWARE, new ArraySet<>());
+ mShortcutTargets.put(GESTURE, new ArraySet<>());
+ mShortcutTargets.put(QUICK_SETTINGS, new ArraySet<>());
}
boolean isHandlingAccessibilityEventsLocked() {
@@ -233,10 +234,7 @@
// Clear state persisted in settings.
mEnabledServices.clear();
mTouchExplorationGrantedServices.clear();
- mAccessibilityShortcutKeyTargets.clear();
- mAccessibilityButtonTargets.clear();
- mAccessibilityGestureTargets.clear();
- mAccessibilityQsTargets.clear();
+ mShortcutTargets.forEach((type, targets) -> targets.clear());
mA11yTilesInQsPanel.clear();
mTargetAssignedToAccessibilityButton = null;
mIsTouchExplorationEnabled = false;
@@ -541,7 +539,7 @@
private void dumpShortcutTargets(
PrintWriter pw, @UserShortcutType int shortcutType, String name) {
pw.append(" ").append(name).append(":{");
- ArraySet<String> targets = getShortcutTargetsInternalLocked(shortcutType);
+ ArraySet<String> targets = getShortcutTargetsLocked(shortcutType);
int size = targets.size();
for (int i = 0; i < size; i++) {
if (i > 0) {
@@ -712,7 +710,7 @@
*/
public boolean isShortcutMagnificationEnabledLocked() {
for (int shortcutType : ShortcutConstants.USER_SHORTCUT_TYPES) {
- if (getShortcutTargetsInternalLocked(shortcutType)
+ if (getShortcutTargetsLocked(shortcutType)
.contains(MAGNIFICATION_CONTROLLER_NAME)) {
return true;
}
@@ -788,43 +786,29 @@
}
/**
- * Disable both shortcuts' magnification function.
- */
- public void disableShortcutMagnificationLocked() {
- mAccessibilityShortcutKeyTargets.remove(MAGNIFICATION_CONTROLLER_NAME);
- mAccessibilityButtonTargets.remove(MAGNIFICATION_CONTROLLER_NAME);
- }
-
- /**
* Returns a set which contains the flattened component names and the system class names
- * assigned to the given shortcut. The set is a defensive copy. To apply any changes to the set,
- * use {@link #updateShortcutTargetsLocked(Set, int)}
+ * assigned to the given shortcut. <strong>The set is a defensive copy.</strong>
+ * To apply any changes to the set, use {@link #updateShortcutTargetsLocked(Set, int)}
*
- * @param shortcutType The shortcut type.
+ * @param shortcutTypes The shortcut type or types (in bitmask format).
* @return The array set of the strings
*/
- public ArraySet<String> getShortcutTargetsLocked(@UserShortcutType int shortcutType) {
- return new ArraySet<>(getShortcutTargetsInternalLocked(shortcutType));
- }
-
- private ArraySet<String> getShortcutTargetsInternalLocked(@UserShortcutType int shortcutType) {
- if (shortcutType == HARDWARE) {
- return mAccessibilityShortcutKeyTargets;
- } else if (shortcutType == SOFTWARE) {
- return mAccessibilityButtonTargets;
- } else if (shortcutType == GESTURE) {
- return mAccessibilityGestureTargets;
- } else if (shortcutType == QUICK_SETTINGS) {
- return mAccessibilityQsTargets;
- } else if ((shortcutType == TRIPLETAP
- && isMagnificationSingleFingerTripleTapEnabledLocked()) || (
- shortcutType == TWOFINGER_DOUBLETAP
- && isMagnificationTwoFingerTripleTapEnabledLocked())) {
- ArraySet<String> targets = new ArraySet<>();
- targets.add(MAGNIFICATION_CONTROLLER_NAME);
- return targets;
+ public ArraySet<String> getShortcutTargetsLocked(int shortcutTypes) {
+ ArraySet<String> targets = new ArraySet<>();
+ for (int shortcutType : ShortcutConstants.USER_SHORTCUT_TYPES) {
+ if ((shortcutTypes & shortcutType) != shortcutType) {
+ continue;
+ }
+ if ((shortcutType == TRIPLETAP
+ && isMagnificationSingleFingerTripleTapEnabledLocked()) || (
+ shortcutType == TWOFINGER_DOUBLETAP
+ && isMagnificationTwoFingerTripleTapEnabledLocked())) {
+ targets.add(MAGNIFICATION_CONTROLLER_NAME);
+ } else if (mShortcutTargets.containsKey(shortcutType)) {
+ targets.addAll(mShortcutTargets.get(shortcutType));
+ }
}
- return new ArraySet<>();
+ return targets;
}
/**
@@ -843,8 +827,10 @@
if ((shortcutType & mask) != 0) {
throw new IllegalArgumentException("Tap shortcuts cannot be updated with target sets.");
}
-
- final Set<String> currentTargets = getShortcutTargetsInternalLocked(shortcutType);
+ if (!mShortcutTargets.containsKey(shortcutType)) {
+ mShortcutTargets.put(shortcutType, new ArraySet<>());
+ }
+ ArraySet<String> currentTargets = mShortcutTargets.get(shortcutType);
if (newTargets.equals(currentTargets)) {
return false;
}
@@ -904,7 +890,7 @@
}
// getting internal set lets us directly modify targets, as it's not a copy.
- Set<String> targets = getShortcutTargetsInternalLocked(shortcutType);
+ Set<String> targets = mShortcutTargets.get(shortcutType);
return targets.removeIf(name -> {
ComponentName componentName;
if (name == null
@@ -1169,13 +1155,6 @@
);
}
- /**
- * Returns a copy of the targets which has qs shortcut turned on
- */
- public ArraySet<String> getA11yQsTargets() {
- return new ArraySet<>(mAccessibilityQsTargets);
- }
-
public void updateA11yTilesInQsPanelLocked(Set<ComponentName> componentNames) {
mA11yTilesInQsPanel.clear();
mA11yTilesInQsPanel.addAll(componentNames);
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index c9f8929..b52c6505 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -92,6 +92,7 @@
import com.android.server.contentcapture.ContentCaptureManagerInternal;
import com.android.server.infra.AbstractPerUserSystemService;
import com.android.server.inputmethod.InputMethodManagerInternal;
+import com.android.server.pm.UserManagerInternal;
import com.android.server.wm.ActivityTaskManagerInternal;
import java.io.PrintWriter;
@@ -192,6 +193,8 @@
private final ContentCaptureManagerInternal mContentCaptureManagerInternal;
+ private final UserManagerInternal mUserManagerInternal;
+
private final DisabledInfoCache mDisabledInfoCache;
AutofillManagerServiceImpl(AutofillManagerService master, Object lock,
@@ -208,6 +211,7 @@
mInputMethodManagerInternal = LocalServices.getService(InputMethodManagerInternal.class);
mContentCaptureManagerInternal = LocalServices.getService(
ContentCaptureManagerInternal.class);
+ mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
mDisabledInfoCache = disableCache;
updateLocked(disabled);
}
@@ -379,6 +383,13 @@
return 0;
}
+ // TODO(b/376482880): remove this check once autofill service supports visible
+ // background users.
+ if (mUserManagerInternal.isVisibleBackgroundFullUser(mUserId)) {
+ Slog.d(TAG, "Currently, autofill service does not support visible background users.");
+ return 0;
+ }
+
if (!forAugmentedAutofillOnly && isAutofillDisabledLocked(clientActivity)) {
// Standard autofill is enabled, but service disabled autofill for this activity; that
// means no session, unless the activity is allowlisted for augmented autofill
diff --git a/services/core/java/com/android/server/VcnManagementService.java b/services/core/java/com/android/server/VcnManagementService.java
index 51c768b..dc7749c 100644
--- a/services/core/java/com/android/server/VcnManagementService.java
+++ b/services/core/java/com/android/server/VcnManagementService.java
@@ -48,6 +48,7 @@
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
+import android.net.vcn.Flags;
import android.net.vcn.IVcnManagementService;
import android.net.vcn.IVcnStatusCallback;
import android.net.vcn.IVcnUnderlyingNetworkPolicyListener;
@@ -878,6 +879,7 @@
private void garbageCollectAndWriteVcnConfigsLocked() {
final SubscriptionManager subMgr = mContext.getSystemService(SubscriptionManager.class);
+ final Set<ParcelUuid> subGroups = mLastSnapshot.getAllSubscriptionGroups();
boolean shouldWrite = false;
@@ -885,11 +887,20 @@
while (configsIterator.hasNext()) {
final ParcelUuid subGrp = configsIterator.next();
- final List<SubscriptionInfo> subscriptions = subMgr.getSubscriptionsInGroup(subGrp);
- if (subscriptions == null || subscriptions.isEmpty()) {
- // Trim subGrps with no more subscriptions; must have moved to another subGrp
- configsIterator.remove();
- shouldWrite = true;
+ if (Flags.fixConfigGarbageCollection()) {
+ if (!subGroups.contains(subGrp)) {
+ // Trim subGrps with no more subscriptions; must have moved to another subGrp
+ logDbg("Garbage collect VcnConfig for group=" + subGrp);
+ configsIterator.remove();
+ shouldWrite = true;
+ }
+ } else {
+ final List<SubscriptionInfo> subscriptions = subMgr.getSubscriptionsInGroup(subGrp);
+ if (subscriptions == null || subscriptions.isEmpty()) {
+ // Trim subGrps with no more subscriptions; must have moved to another subGrp
+ configsIterator.remove();
+ shouldWrite = true;
+ }
}
}
@@ -1094,13 +1105,7 @@
synchronized (mLock) {
final Vcn vcn = mVcns.get(subGrp);
final VcnConfig vcnConfig = mConfigs.get(subGrp);
- if (vcn != null) {
- if (vcnConfig == null) {
- // TODO: b/284381334 Investigate for the root cause of this issue
- // and handle it properly
- logWtf("Vcn instance exists but VcnConfig does not for " + subGrp);
- }
-
+ if (vcn != null && vcnConfig != null) {
if (vcn.getStatus() == VCN_STATUS_CODE_ACTIVE) {
isVcnManagedNetwork = true;
}
@@ -1120,6 +1125,8 @@
}
}
}
+ } else if (vcn != null && vcnConfig == null) {
+ logWtf("Vcn instance exists but VcnConfig does not for " + subGrp);
}
}
diff --git a/services/core/java/com/android/server/am/BroadcastFilter.java b/services/core/java/com/android/server/am/BroadcastFilter.java
index f016590..3c7fb52 100644
--- a/services/core/java/com/android/server/am/BroadcastFilter.java
+++ b/services/core/java/com/android/server/am/BroadcastFilter.java
@@ -19,7 +19,6 @@
import android.annotation.Nullable;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
-import android.compat.annotation.Overridable;
import android.content.IntentFilter;
import android.os.UserHandle;
import android.util.PrintWriterPrinter;
@@ -40,7 +39,6 @@
*/
@ChangeId
@EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.BASE)
- @Overridable
@VisibleForTesting
static final long CHANGE_RESTRICT_PRIORITY_VALUES = 371309185L;
diff --git a/services/core/java/com/android/server/audio/MediaFocusControl.java b/services/core/java/com/android/server/audio/MediaFocusControl.java
index 1da62d7..1604e94 100644
--- a/services/core/java/com/android/server/audio/MediaFocusControl.java
+++ b/services/core/java/com/android/server/audio/MediaFocusControl.java
@@ -1068,6 +1068,7 @@
switch (attr.getUsage()) {
case AudioAttributes.USAGE_MEDIA:
case AudioAttributes.USAGE_GAME:
+ case AudioAttributes.USAGE_SPEAKER_CLEANUP:
return 1000;
case AudioAttributes.USAGE_ALARM:
case AudioAttributes.USAGE_NOTIFICATION_RINGTONE:
diff --git a/services/core/java/com/android/server/biometrics/AuthSession.java b/services/core/java/com/android/server/biometrics/AuthSession.java
index 3afecf1..290aab2 100644
--- a/services/core/java/com/android/server/biometrics/AuthSession.java
+++ b/services/core/java/com/android/server/biometrics/AuthSession.java
@@ -305,7 +305,7 @@
mSensors /* sensorIds */,
true /* credentialAllowed */,
false /* requireConfirmation */,
- mUserId,
+ mPreAuthInfo.callingUserId,
mOperationId,
mOpPackageName,
mRequestId);
@@ -357,7 +357,7 @@
mSensors,
mPreAuthInfo.shouldShowCredential(),
requireConfirmation,
- mUserId,
+ mPreAuthInfo.callingUserId,
mOperationId,
mOpPackageName,
mRequestId);
@@ -491,7 +491,7 @@
mSensors /* sensorIds */,
true /* credentialAllowed */,
false /* requireConfirmation */,
- mUserId,
+ mPreAuthInfo.callingUserId,
mOperationId,
mOpPackageName,
mRequestId);
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 4c91789..00280c8f 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -1133,7 +1133,7 @@
return PreAuthInfo.create(mTrustManager, mDevicePolicyManager, mSettingObserver, mSensors,
userId, promptInfo, opPackageName, false /* checkDevicePolicyManager */,
- getContext(), mBiometricCameraManager);
+ getContext(), mBiometricCameraManager, mUserManager);
}
/**
@@ -1520,9 +1520,9 @@
mHandler.post(() -> {
try {
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager,
- mDevicePolicyManager, mSettingObserver, mSensors, userId, promptInfo,
- opPackageName, promptInfo.isDisallowBiometricsIfPolicyExists(),
- getContext(), mBiometricCameraManager);
+ mDevicePolicyManager, mSettingObserver, mSensors, userId,
+ promptInfo, opPackageName, promptInfo.isDisallowBiometricsIfPolicyExists(),
+ getContext(), mBiometricCameraManager, mUserManager);
// Set the default title if necessary.
if (promptInfo.isUseDefaultTitle()) {
@@ -1572,8 +1572,8 @@
promptInfo.setAuthenticators(Authenticators.DEVICE_CREDENTIAL);
}
- authenticateInternal(token, requestId, operationId, userId, receiver,
- opPackageName, promptInfo, preAuthInfo);
+ authenticateInternal(token, requestId, operationId, preAuthInfo.userId,
+ receiver, opPackageName, promptInfo, preAuthInfo);
} else {
receiver.onError(preAuthStatus.first /* modality */,
preAuthStatus.second /* errorCode */,
diff --git a/services/core/java/com/android/server/biometrics/PreAuthInfo.java b/services/core/java/com/android/server/biometrics/PreAuthInfo.java
index 96c178a..a9ada29 100644
--- a/services/core/java/com/android/server/biometrics/PreAuthInfo.java
+++ b/services/core/java/com/android/server/biometrics/PreAuthInfo.java
@@ -32,6 +32,7 @@
import android.hardware.biometrics.Flags;
import android.hardware.biometrics.PromptInfo;
import android.os.RemoteException;
+import android.os.UserManager;
import android.util.Pair;
import android.util.Slog;
@@ -72,6 +73,7 @@
final boolean confirmationRequested;
final boolean ignoreEnrollmentState;
final int userId;
+ final int callingUserId;
final Context context;
private final boolean mBiometricRequested;
private final int mBiometricStrengthRequested;
@@ -82,7 +84,7 @@
private PreAuthInfo(boolean biometricRequested, int biometricStrengthRequested,
boolean credentialRequested, List<BiometricSensor> eligibleSensors,
List<Pair<BiometricSensor, Integer>> ineligibleSensors, boolean credentialAvailable,
- PromptInfo promptInfo, int userId, Context context,
+ PromptInfo promptInfo, int userId, int callingUserId, Context context,
BiometricCameraManager biometricCameraManager,
boolean isOnlyMandatoryBiometricsRequested,
boolean isMandatoryBiometricsAuthentication) {
@@ -97,6 +99,7 @@
this.confirmationRequested = promptInfo.isConfirmationRequested();
this.ignoreEnrollmentState = promptInfo.isIgnoreEnrollmentState();
this.userId = userId;
+ this.callingUserId = callingUserId;
this.context = context;
this.mOnlyMandatoryBiometricsRequested = isOnlyMandatoryBiometricsRequested;
this.mIsMandatoryBiometricsAuthentication = isMandatoryBiometricsAuthentication;
@@ -108,7 +111,8 @@
List<BiometricSensor> sensors,
int userId, PromptInfo promptInfo, String opPackageName,
boolean checkDevicePolicyManager, Context context,
- BiometricCameraManager biometricCameraManager)
+ BiometricCameraManager biometricCameraManager,
+ UserManager userManager)
throws RemoteException {
final boolean isOnlyMandatoryBiometricsRequested = promptInfo.getAuthenticators()
@@ -141,14 +145,20 @@
final List<BiometricSensor> eligibleSensors = new ArrayList<>();
final List<Pair<BiometricSensor, Integer>> ineligibleSensors = new ArrayList<>();
+ final int effectiveUserId;
+ if (Flags.privateSpaceBp()) {
+ effectiveUserId = userManager.getCredentialOwnerProfile(userId);
+ } else {
+ effectiveUserId = userId;
+ }
+
if (biometricRequested) {
for (BiometricSensor sensor : sensors) {
@AuthenticatorStatus int status = getStatusForBiometricAuthenticator(
- devicePolicyManager, settingObserver, sensor, userId, opPackageName,
- checkDevicePolicyManager, requestedStrength,
- promptInfo.getAllowedSensorIds(),
- promptInfo.isIgnoreEnrollmentState(),
+ devicePolicyManager, settingObserver, sensor, effectiveUserId,
+ opPackageName, checkDevicePolicyManager, requestedStrength,
+ promptInfo.getAllowedSensorIds(), promptInfo.isIgnoreEnrollmentState(),
biometricCameraManager);
Slog.d(TAG, "Package: " + opPackageName
@@ -172,9 +182,9 @@
}
return new PreAuthInfo(biometricRequested, requestedStrength, credentialRequested,
- eligibleSensors, ineligibleSensors, credentialAvailable, promptInfo, userId,
- context, biometricCameraManager, isOnlyMandatoryBiometricsRequested,
- isMandatoryBiometricsAuthentication);
+ eligibleSensors, ineligibleSensors, credentialAvailable, promptInfo,
+ effectiveUserId, userId, context, biometricCameraManager,
+ isOnlyMandatoryBiometricsRequested, isMandatoryBiometricsAuthentication);
}
private static boolean dropCredentialFallback(int authenticators,
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index 0766c3a..132d6fa 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -3178,6 +3178,10 @@
HdmiCecLocalDeviceSource source = playback();
if (source == null) {
source = audioSystem();
+ } else {
+ // Cancel an existing timer to send the device to sleep since OTP was triggered.
+ playback().mDelayedStandbyOnActiveSourceLostHandler
+ .removeCallbacksAndMessages(null);
}
if (source == null) {
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index bbdac56..8798a64 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -1183,9 +1183,7 @@
// If config_disableWeaverOnUnsecuredUsers=true, then the Weaver HAL may be buggy and
// need multiple retries before it works here to unwrap the SP, if the SP was already
- // protected by Weaver. Note that the problematic HAL can also deadlock if called with
- // the ActivityManagerService lock held, but that should not be a problem here since
- // that lock isn't held here, unlike unlockUserKeyIfUnsecured() where it is.
+ // protected by Weaver.
for (int i = 0; i < 12 && sp == null; i++) {
Slog.e(TAG, "Failed to unwrap synthetic password. Waiting 5 seconds to retry.");
SystemClock.sleep(5000);
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index ce249c6..d5f13a8 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -40,6 +40,7 @@
import static android.service.notification.ZenModeConfig.ZenRule.OVERRIDE_ACTIVATE;
import static android.service.notification.ZenModeConfig.ZenRule.OVERRIDE_DEACTIVATE;
import static android.service.notification.ZenModeConfig.implicitRuleId;
+import static android.service.notification.ZenModeConfig.isImplicitRuleId;
import static com.android.internal.util.FrameworkStatsLog.DND_MODE_RULE;
import static com.android.internal.util.Preconditions.checkArgument;
@@ -170,7 +171,6 @@
private final Clock mClock;
private final SettingsObserver mSettingsObserver;
private final AppOpsManager mAppOps;
- private final NotificationManager mNotificationManager;
private final ZenModeConfig mDefaultConfig;
private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
private final ZenModeFiltering mFiltering;
@@ -217,7 +217,6 @@
mClock = clock;
addCallback(mMetrics);
mAppOps = context.getSystemService(AppOpsManager.class);
- mNotificationManager = context.getSystemService(NotificationManager.class);
mDefaultConfig = Flags.modesUi()
? ZenModeConfig.getDefaultConfig()
@@ -660,7 +659,12 @@
// (whether initialized here or set via app or user).
rule.zenPolicy = config.getZenPolicy().copy();
newConfig.automaticRules.put(rule.id, rule);
+ } else {
+ if (Flags.modesUi()) {
+ updateImplicitZenRuleNameAndDescription(rule);
+ }
}
+
// If the user has changed the rule's *zenMode*, then don't let app overwrite it.
// We allow the update if the user has only changed other aspects of the rule.
if ((rule.userModifiedFields & AutomaticZenRule.FIELD_INTERRUPTION_FILTER) == 0) {
@@ -707,7 +711,12 @@
rule = newImplicitZenRule(callingPkg);
rule.zenMode = Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
newConfig.automaticRules.put(rule.id, rule);
+ } else {
+ if (Flags.modesUi()) {
+ updateImplicitZenRuleNameAndDescription(rule);
+ }
}
+
// If the user has changed the rule's *ZenPolicy*, then don't let app overwrite it.
// We allow the update if the user has only changed other aspects of the rule.
if (rule.zenPolicyUserModifiedFields == 0) {
@@ -777,24 +786,8 @@
rule.id = implicitRuleId(pkg);
rule.pkg = pkg;
rule.creationTime = mClock.millis();
-
- Binder.withCleanCallingIdentity(() -> {
- try {
- ApplicationInfo applicationInfo = mPm.getApplicationInfo(pkg, 0);
- rule.name = applicationInfo.loadLabel(mPm).toString();
- if (!Flags.modesUi()) {
- rule.iconResName = drawableResIdToResName(pkg, applicationInfo.icon);
- }
- } catch (PackageManager.NameNotFoundException e) {
- // Should not happen, since it's the app calling us (?)
- Log.w(TAG, "Package not found for creating implicit zen rule");
- rule.name = "Unknown";
- }
- });
-
+ updateImplicitZenRuleNameAndDescription(rule);
rule.type = AutomaticZenRule.TYPE_OTHER;
- rule.triggerDescription = mContext.getString(R.string.zen_mode_implicit_trigger_description,
- rule.name);
rule.condition = null;
rule.conditionId = new Uri.Builder()
.scheme(Condition.SCHEME)
@@ -809,6 +802,38 @@
return rule;
}
+ private void updateImplicitZenRuleNameAndDescription(ZenRule rule) {
+ checkArgument(isImplicitRuleId(rule.id));
+ requireNonNull(rule.pkg, "Implicit rule is not associated to package yet!");
+
+ String pkgAppName = Binder.withCleanCallingIdentity(() -> {
+ try {
+ ApplicationInfo applicationInfo = mPm.getApplicationInfo(rule.pkg, 0);
+ return applicationInfo.loadLabel(mPm).toString();
+ } catch (PackageManager.NameNotFoundException e) {
+ // Should not happen. When creating it's the app calling us, and when updating
+ // the rule would've been deleted if the package was removed.
+ Slog.e(TAG, "Package not found when updating implicit zen rule name", e);
+ return null;
+ }
+ });
+
+ if (pkgAppName != null) {
+ if ((rule.userModifiedFields & AutomaticZenRule.FIELD_NAME) == 0) {
+ if (Flags.modesUi()) {
+ rule.name = mContext.getString(R.string.zen_mode_implicit_name, pkgAppName);
+ } else {
+ rule.name = pkgAppName;
+ }
+ }
+ rule.triggerDescription = mContext.getString(
+ R.string.zen_mode_implicit_trigger_description, pkgAppName);
+ } else if (rule.name == null) {
+ // We must give a new rule SOME name. But this path should never be hit.
+ rule.name = "Unknown";
+ }
+ }
+
boolean removeAutomaticZenRule(UserHandle user, String id, @ConfigOrigin int origin,
String reason, int callingUid) {
checkManageRuleOrigin("removeAutomaticZenRule", origin);
@@ -1130,6 +1155,8 @@
for (ZenRule rule : newConfig.automaticRules.values()) {
if (SystemZenRules.isSystemOwnedRule(rule)) {
updated |= SystemZenRules.updateTriggerDescription(mContext, rule);
+ } else if (isImplicitRuleId(rule.id)) {
+ updateImplicitZenRuleNameAndDescription(rule);
}
}
}
diff --git a/services/core/java/com/android/server/pm/parsing/PackageCacher.java b/services/core/java/com/android/server/pm/parsing/PackageCacher.java
index 2db454a..db65bf0 100644
--- a/services/core/java/com/android/server/pm/parsing/PackageCacher.java
+++ b/services/core/java/com/android/server/pm/parsing/PackageCacher.java
@@ -33,6 +33,7 @@
import com.android.internal.pm.parsing.PackageParser2;
import com.android.internal.pm.parsing.pkg.PackageImpl;
import com.android.internal.pm.parsing.pkg.ParsedPackage;
+import com.android.internal.pm.pkg.component.AconfigFlags;
import com.android.internal.pm.pkg.parsing.ParsingPackageUtils;
import com.android.server.pm.ApexManager;
@@ -41,6 +42,8 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class PackageCacher implements IPackageCacher {
@@ -57,6 +60,8 @@
@Nullable
private final PackageParser2.Callback mCallback;
+ private static final AconfigFlags sAconfigFlags = ParsingPackageUtils.getAconfigFlags();
+
public PackageCacher(File cacheDir) {
this(cacheDir, null);
}
@@ -136,7 +141,7 @@
* Given a {@code packageFile} and a {@code cacheFile} returns whether the
* cache file is up to date based on the mod-time of both files.
*/
- private static boolean isCacheUpToDate(File packageFile, File cacheFile) {
+ private static boolean isCacheFileUpToDate(File packageFile, File cacheFile) {
try {
// In case packageFile is located on one of /apex mount points it's mtime will always be
// 0. Instead, we can use mtime of the APEX file backing the corresponding mount point.
@@ -185,16 +190,36 @@
try {
// If the cache is not up to date, return null.
- if (!isCacheUpToDate(packageFile, cacheFile)) {
+ if (!isCacheFileUpToDate(packageFile, cacheFile)) {
return null;
}
final byte[] bytes = IoUtils.readFileAsByteArray(cacheFile.getAbsolutePath());
- ParsedPackage parsed = fromCacheEntry(bytes);
+ final ParsedPackage parsed = fromCacheEntry(bytes);
if (!packageFile.getAbsolutePath().equals(parsed.getPath())) {
// Don't use this cache if the path doesn't match
return null;
}
+
+ if (!android.content.pm.Flags.includeFeatureFlagsInPackageCacher()) {
+ return parsed;
+ }
+
+ final Map<String, Boolean> featureFlagState =
+ ((PackageImpl) parsed).getFeatureFlagState();
+ if (!featureFlagState.isEmpty()) {
+ Slog.d(TAG, "Feature flags for package " + packageFile + ": " + featureFlagState);
+ for (var entry : featureFlagState.entrySet()) {
+ final String flagPackageAndName = entry.getKey();
+ if (!Objects.equals(sAconfigFlags.getFlagValue(flagPackageAndName),
+ entry.getValue())) {
+ Slog.i(TAG, "Feature flag " + flagPackageAndName + " changed for package "
+ + packageFile + "; cached result is invalid");
+ return null;
+ }
+ }
+ }
+
return parsed;
} catch (Throwable e) {
Slog.w(TAG, "Error reading package cache: ", e);
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index bc6a40a..07fd1cb 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -1271,6 +1271,7 @@
*/
private boolean isFixedOrUserSet(int flags) {
return (flags & (PackageManager.FLAG_PERMISSION_USER_SET
+ | PackageManager.FLAG_PERMISSION_ONE_TIME
| PackageManager.FLAG_PERMISSION_USER_FIXED
| PackageManager.FLAG_PERMISSION_POLICY_FIXED
| PackageManager.FLAG_PERMISSION_SYSTEM_FIXED)) != 0;
diff --git a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
index baf84cf..3392d03 100644
--- a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
+++ b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
@@ -436,6 +436,17 @@
return mPrivilegedPackages.keySet();
}
+ /** Returns all subscription groups */
+ @NonNull
+ public Set<ParcelUuid> getAllSubscriptionGroups() {
+ final Set<ParcelUuid> subGroups = new ArraySet<>();
+ for (SubscriptionInfo subInfo : mSubIdToInfoMap.values()) {
+ subGroups.add(subInfo.getGroupUuid());
+ }
+
+ return subGroups;
+ }
+
/** Checks if the provided package is carrier privileged for the specified sub group. */
public boolean packageHasPermissionsForSubscriptionGroup(
@NonNull ParcelUuid subGrp, @NonNull String packageName) {
diff --git a/services/core/java/com/android/server/webkit/SystemImpl.java b/services/core/java/com/android/server/webkit/SystemImpl.java
index ab5316f..92ce251 100644
--- a/services/core/java/com/android/server/webkit/SystemImpl.java
+++ b/services/core/java/com/android/server/webkit/SystemImpl.java
@@ -16,8 +16,6 @@
package com.android.server.webkit;
-import static android.webkit.Flags.updateServiceV2;
-
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
@@ -253,46 +251,11 @@
}
@Override
- public int getMultiProcessSetting() {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "getMultiProcessSetting shouldn't be called if update_service_v2 flag is set.");
- }
- return Settings.Global.getInt(
- mContext.getContentResolver(), Settings.Global.WEBVIEW_MULTIPROCESS, 0);
- }
-
- @Override
- public void setMultiProcessSetting(int value) {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "setMultiProcessSetting shouldn't be called if update_service_v2 flag is set.");
- }
- Settings.Global.putInt(
- mContext.getContentResolver(), Settings.Global.WEBVIEW_MULTIPROCESS, value);
- }
-
- @Override
- public void notifyZygote(boolean enableMultiProcess) {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "notifyZygote shouldn't be called if update_service_v2 flag is set.");
- }
- WebViewZygote.setMultiprocessEnabled(enableMultiProcess);
- }
-
- @Override
public void ensureZygoteStarted() {
WebViewZygote.getProcess();
}
@Override
- public boolean isMultiProcessDefaultEnabled() {
- // Multiprocess is enabled by default for all devices.
- return true;
- }
-
- @Override
public void pinWebviewIfRequired(ApplicationInfo appInfo) {
PinnerService pinnerService = LocalServices.getService(PinnerService.class);
int webviewPinQuota = pinnerService.getWebviewPinQuota();
diff --git a/services/core/java/com/android/server/webkit/SystemInterface.java b/services/core/java/com/android/server/webkit/SystemInterface.java
index 3b77d07..6710554 100644
--- a/services/core/java/com/android/server/webkit/SystemInterface.java
+++ b/services/core/java/com/android/server/webkit/SystemInterface.java
@@ -55,12 +55,8 @@
*/
List<UserPackage> getPackageInfoForProviderAllUsers(WebViewProviderInfo configInfo);
- int getMultiProcessSetting();
- void setMultiProcessSetting(int value);
- void notifyZygote(boolean enableMultiProcess);
/** Start the zygote if it's not already running. */
void ensureZygoteStarted();
- boolean isMultiProcessDefaultEnabled();
void pinWebviewIfRequired(ApplicationInfo appInfo);
}
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdateService.java b/services/core/java/com/android/server/webkit/WebViewUpdateService.java
index 7acb864..744c3da6 100644
--- a/services/core/java/com/android/server/webkit/WebViewUpdateService.java
+++ b/services/core/java/com/android/server/webkit/WebViewUpdateService.java
@@ -16,8 +16,6 @@
package com.android.server.webkit;
-import static android.webkit.Flags.updateServiceV2;
-
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -63,7 +61,7 @@
new Histogram.ScaledRangeOptions(20, 0, 1, 1.4f));
private BroadcastReceiver mWebViewUpdatedReceiver;
- private WebViewUpdateServiceInterface mImpl;
+ private WebViewUpdateServiceImpl2 mImpl;
static final int PACKAGE_CHANGED = 0;
static final int PACKAGE_ADDED = 1;
@@ -72,11 +70,7 @@
public WebViewUpdateService(Context context) {
super(context);
- if (updateServiceV2()) {
- mImpl = new WebViewUpdateServiceImpl2(new SystemImpl(context));
- } else {
- mImpl = new WebViewUpdateServiceImpl(new SystemImpl(context));
- }
+ mImpl = new WebViewUpdateServiceImpl2(new SystemImpl(context));
}
@Override
@@ -170,13 +164,8 @@
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
- if (updateServiceV2()) {
- (new WebViewUpdateServiceShellCommand2(this))
- .exec(this, in, out, err, args, callback, resultReceiver);
- } else {
- (new WebViewUpdateServiceShellCommand(this))
- .exec(this, in, out, err, args, callback, resultReceiver);
- }
+ (new WebViewUpdateServiceShellCommand2(this))
+ .exec(this, in, out, err, args, callback, resultReceiver);
}
@@ -300,45 +289,6 @@
return currentWebViewPackage;
}
- @Override // Binder call
- public boolean isMultiProcessEnabled() {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "isMultiProcessEnabled shouldn't be called if update_service_v2 flag is"
- + " set.");
- }
- return WebViewUpdateService.this.mImpl.isMultiProcessEnabled();
- }
-
- @Override // Binder call
- public void enableMultiProcess(boolean enable) {
- if (updateServiceV2()) {
- throw new IllegalStateException(
- "enableMultiProcess shouldn't be called if update_service_v2 flag is set.");
- }
- if (getContext()
- .checkCallingPermission(
- android.Manifest.permission.WRITE_SECURE_SETTINGS)
- != PackageManager.PERMISSION_GRANTED) {
- String msg =
- "Permission Denial: enableMultiProcess() from pid="
- + Binder.getCallingPid()
- + ", uid="
- + Binder.getCallingUid()
- + " requires "
- + android.Manifest.permission.WRITE_SECURE_SETTINGS;
- Slog.w(TAG, msg);
- throw new SecurityException(msg);
- }
-
- final long callingId = Binder.clearCallingIdentity();
- try {
- WebViewUpdateService.this.mImpl.enableMultiProcess(enable);
- } finally {
- Binder.restoreCallingIdentity(callingId);
- }
- }
-
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl.java b/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl.java
deleted file mode 100644
index b9be4a2..0000000
--- a/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl.java
+++ /dev/null
@@ -1,768 +0,0 @@
-/*
- * Copyright (C) 2016 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.webkit;
-
-import android.annotation.Nullable;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.Signature;
-import android.os.AsyncTask;
-import android.os.Trace;
-import android.os.UserHandle;
-import android.util.AndroidRuntimeException;
-import android.util.Slog;
-import android.webkit.UserPackage;
-import android.webkit.WebViewFactory;
-import android.webkit.WebViewProviderInfo;
-import android.webkit.WebViewProviderResponse;
-
-import com.android.modules.expresslog.Counter;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Implementation of the WebViewUpdateService.
- * This class doesn't depend on the android system like the actual Service does and can be used
- * directly by tests (as long as they implement a SystemInterface).
- *
- * This class keeps track of and prepares the current WebView implementation, and needs to keep
- * track of a couple of different things such as what package is used as WebView implementation.
- *
- * The package-visible methods in this class are accessed from WebViewUpdateService either on the UI
- * thread or on one of multiple Binder threads. The WebView preparation code shares state between
- * threads meaning that code that chooses a new WebView implementation or checks which
- * implementation is being used needs to hold a lock.
- *
- * The WebViewUpdateService can be accessed in a couple of different ways.
- * 1. It is started from the SystemServer at boot - at that point we just initiate some state such
- * as the WebView preparation class.
- * 2. The SystemServer calls WebViewUpdateService.prepareWebViewInSystemServer. This happens at boot
- * and the WebViewUpdateService should not have been accessed before this call. In this call we
- * choose WebView implementation for the first time.
- * 3. The update service listens for Intents related to package installs and removals. These intents
- * are received and processed on the UI thread. Each intent can result in changing WebView
- * implementation.
- * 4. The update service can be reached through Binder calls which are handled on specific binder
- * threads. These calls can be made from any process. Generally they are used for changing WebView
- * implementation (from Settings), getting information about the current WebView implementation (for
- * loading WebView into an app process), or notifying the service about Relro creation being
- * completed.
- *
- * @hide
- */
-class WebViewUpdateServiceImpl implements WebViewUpdateServiceInterface {
- private static final String TAG = WebViewUpdateServiceImpl.class.getSimpleName();
-
- private static class WebViewPackageMissingException extends Exception {
- WebViewPackageMissingException(String message) {
- super(message);
- }
-
- WebViewPackageMissingException(Exception e) {
- super(e);
- }
- }
-
- private static final int WAIT_TIMEOUT_MS = 1000; // KEY_DISPATCHING_TIMEOUT is 5000.
- private static final long NS_PER_MS = 1000000;
-
- private static final int VALIDITY_OK = 0;
- private static final int VALIDITY_INCORRECT_SDK_VERSION = 1;
- private static final int VALIDITY_INCORRECT_VERSION_CODE = 2;
- private static final int VALIDITY_INCORRECT_SIGNATURE = 3;
- private static final int VALIDITY_NO_LIBRARY_FLAG = 4;
-
- private static final int MULTIPROCESS_SETTING_ON_VALUE = Integer.MAX_VALUE;
- private static final int MULTIPROCESS_SETTING_OFF_VALUE = Integer.MIN_VALUE;
-
- private final SystemInterface mSystemInterface;
-
- private long mMinimumVersionCode = -1;
-
- // Keeps track of the number of running relro creations
- private int mNumRelroCreationsStarted = 0;
- private int mNumRelroCreationsFinished = 0;
- // Implies that we need to rerun relro creation because we are using an out-of-date package
- private boolean mWebViewPackageDirty = false;
- private boolean mAnyWebViewInstalled = false;
-
- private static final int NUMBER_OF_RELROS_UNKNOWN = Integer.MAX_VALUE;
-
- // The WebView package currently in use (or the one we are preparing).
- private PackageInfo mCurrentWebViewPackage = null;
-
- private final Object mLock = new Object();
-
- WebViewUpdateServiceImpl(SystemInterface systemInterface) {
- mSystemInterface = systemInterface;
- }
-
- @Override
- public void packageStateChanged(String packageName, int changedState, int userId) {
- // We don't early out here in different cases where we could potentially early-out (e.g. if
- // we receive PACKAGE_CHANGED for another user than the system user) since that would
- // complicate this logic further and open up for more edge cases.
- for (WebViewProviderInfo provider : mSystemInterface.getWebViewPackages()) {
- String webviewPackage = provider.packageName;
-
- if (webviewPackage.equals(packageName)) {
- boolean updateWebView = false;
- boolean removedOrChangedOldPackage = false;
- String oldProviderName = null;
- PackageInfo newPackage = null;
- synchronized (mLock) {
- try {
- newPackage = findPreferredWebViewPackage();
- if (mCurrentWebViewPackage != null) {
- oldProviderName = mCurrentWebViewPackage.packageName;
- }
- // Only trigger update actions if the updated package is the one
- // that will be used, or the one that was in use before the
- // update, or if we haven't seen a valid WebView package before.
- updateWebView =
- provider.packageName.equals(newPackage.packageName)
- || provider.packageName.equals(oldProviderName)
- || mCurrentWebViewPackage == null;
- // We removed the old package if we received an intent to remove
- // or replace the old package.
- removedOrChangedOldPackage =
- provider.packageName.equals(oldProviderName);
- if (updateWebView) {
- onWebViewProviderChanged(newPackage);
- }
- } catch (WebViewPackageMissingException e) {
- mCurrentWebViewPackage = null;
- Slog.e(TAG, "Could not find valid WebView package to create relro with "
- + e);
- }
- }
- if (updateWebView && !removedOrChangedOldPackage
- && oldProviderName != null) {
- // If the provider change is the result of adding or replacing a
- // package that was not the previous provider then we must kill
- // packages dependent on the old package ourselves. The framework
- // only kills dependents of packages that are being removed.
- mSystemInterface.killPackageDependents(oldProviderName);
- }
- return;
- }
- }
- }
-
- @Override
- public void prepareWebViewInSystemServer() {
- mSystemInterface.notifyZygote(isMultiProcessEnabled());
- try {
- synchronized (mLock) {
- mCurrentWebViewPackage = findPreferredWebViewPackage();
- String userSetting = mSystemInterface.getUserChosenWebViewProvider();
- if (userSetting != null
- && !userSetting.equals(mCurrentWebViewPackage.packageName)) {
- // Don't persist the user-chosen setting across boots if the package being
- // chosen is not used (could be disabled or uninstalled) so that the user won't
- // be surprised by the device switching to using a certain webview package,
- // that was uninstalled/disabled a long time ago, if it is installed/enabled
- // again.
- mSystemInterface.updateUserSetting(mCurrentWebViewPackage.packageName);
- }
- onWebViewProviderChanged(mCurrentWebViewPackage);
- }
- } catch (WebViewPackageMissingException e) {
- Slog.e(TAG, "Could not find valid WebView package to create relro with", e);
- } catch (Throwable t) {
- // We don't know a case when this should happen but we log and discard errors at this
- // stage as we must not crash the system server.
- Slog.wtf(TAG, "error preparing webview provider from system server", t);
- }
-
- if (getCurrentWebViewPackage() == null) {
- // We didn't find a valid WebView implementation. Try explicitly re-enabling the
- // fallback package for all users in case it was disabled, even if we already did the
- // one-time migration before. If this actually changes the state, we will see the
- // PackageManager broadcast shortly and try again.
- WebViewProviderInfo[] webviewProviders = mSystemInterface.getWebViewPackages();
- WebViewProviderInfo fallbackProvider = getFallbackProvider(webviewProviders);
- if (fallbackProvider != null) {
- Slog.w(TAG, "No valid provider, trying to enable " + fallbackProvider.packageName);
- mSystemInterface.enablePackageForAllUsers(fallbackProvider.packageName, true);
- } else {
- Slog.e(TAG, "No valid provider and no fallback available.");
- }
- }
- }
-
- private void startZygoteWhenReady() {
- // Wait on a background thread for RELRO creation to be done. We ignore the return value
- // because even if RELRO creation failed we still want to start the zygote.
- waitForAndGetProvider();
- mSystemInterface.ensureZygoteStarted();
- }
-
- @Override
- public void handleNewUser(int userId) {
- // The system user is always started at boot, and by that point we have already run one
- // round of the package-changing logic (through prepareWebViewInSystemServer()), so early
- // out here.
- if (userId == UserHandle.USER_SYSTEM) return;
- handleUserChange();
- }
-
- @Override
- public void handleUserRemoved(int userId) {
- handleUserChange();
- }
-
- /**
- * Called when a user was added or removed to ensure WebView preparation is triggered.
- * This has to be done since the WebView package we use depends on the enabled-state
- * of packages for all users (so adding or removing a user might cause us to change package).
- */
- private void handleUserChange() {
- // Potentially trigger package-changing logic.
- updateCurrentWebViewPackage(null);
- }
-
- @Override
- public void notifyRelroCreationCompleted() {
- synchronized (mLock) {
- mNumRelroCreationsFinished++;
- checkIfRelrosDoneLocked();
- }
- }
-
- @Override
- public WebViewProviderResponse waitForAndGetProvider() {
- PackageInfo webViewPackage = null;
- final long timeoutTimeMs = System.nanoTime() / NS_PER_MS + WAIT_TIMEOUT_MS;
- boolean webViewReady = false;
- int webViewStatus = WebViewFactory.LIBLOAD_SUCCESS;
- synchronized (mLock) {
- webViewReady = webViewIsReadyLocked();
- while (!webViewReady) {
- final long timeNowMs = System.nanoTime() / NS_PER_MS;
- if (timeNowMs >= timeoutTimeMs) break;
- try {
- mLock.wait(timeoutTimeMs - timeNowMs);
- } catch (InterruptedException e) {
- // ignore
- }
- webViewReady = webViewIsReadyLocked();
- }
- // Make sure we return the provider that was used to create the relro file
- webViewPackage = mCurrentWebViewPackage;
- if (webViewReady) {
- // success
- } else if (!mAnyWebViewInstalled) {
- webViewStatus = WebViewFactory.LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES;
- } else {
- // Either the current relro creation isn't done yet, or the new relro creatioin
- // hasn't kicked off yet (the last relro creation used an out-of-date WebView).
- webViewStatus = WebViewFactory.LIBLOAD_FAILED_WAITING_FOR_RELRO;
- String timeoutError = "Timed out waiting for relro creation, relros started "
- + mNumRelroCreationsStarted
- + " relros finished " + mNumRelroCreationsFinished
- + " package dirty? " + mWebViewPackageDirty;
- Slog.e(TAG, timeoutError);
- Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, timeoutError);
- }
- }
- if (!webViewReady) Slog.w(TAG, "creating relro file timed out");
- return new WebViewProviderResponse(webViewPackage, webViewStatus);
- }
-
- /**
- * Change WebView provider and provider setting and kill packages using the old provider.
- * Return the new provider (in case we are in the middle of creating relro files, or
- * replacing that provider it will not be in use directly, but will be used when the relros
- * or the replacement are done).
- */
- @Override
- public String changeProviderAndSetting(String newProviderName) {
- PackageInfo newPackage = updateCurrentWebViewPackage(newProviderName);
- if (newPackage == null) return "";
- return newPackage.packageName;
- }
-
- /**
- * Update the current WebView package.
- * @param newProviderName the package to switch to, null if no package has been explicitly
- * chosen.
- */
- private PackageInfo updateCurrentWebViewPackage(@Nullable String newProviderName) {
- PackageInfo oldPackage = null;
- PackageInfo newPackage = null;
- boolean providerChanged = false;
- synchronized (mLock) {
- oldPackage = mCurrentWebViewPackage;
-
- if (newProviderName != null) {
- mSystemInterface.updateUserSetting(newProviderName);
- }
-
- try {
- newPackage = findPreferredWebViewPackage();
- providerChanged = (oldPackage == null)
- || !newPackage.packageName.equals(oldPackage.packageName);
- } catch (WebViewPackageMissingException e) {
- // If updated the Setting but don't have an installed WebView package, the
- // Setting will be used when a package is available.
- mCurrentWebViewPackage = null;
- Slog.e(TAG, "Couldn't find WebView package to use " + e);
- return null;
- }
- // Perform the provider change if we chose a new provider
- if (providerChanged) {
- onWebViewProviderChanged(newPackage);
- }
- }
- // Kill apps using the old provider only if we changed provider
- if (providerChanged && oldPackage != null) {
- mSystemInterface.killPackageDependents(oldPackage.packageName);
- }
- // Return the new provider, this is not necessarily the one we were asked to switch to,
- // but the persistent setting will now be pointing to the provider we were asked to
- // switch to anyway.
- return newPackage;
- }
-
- /**
- * This is called when we change WebView provider, either when the current provider is
- * updated or a new provider is chosen / takes precedence.
- */
- private void onWebViewProviderChanged(PackageInfo newPackage) {
- synchronized (mLock) {
- mAnyWebViewInstalled = true;
- if (mNumRelroCreationsStarted == mNumRelroCreationsFinished) {
- mSystemInterface.pinWebviewIfRequired(newPackage.applicationInfo);
- mCurrentWebViewPackage = newPackage;
-
- // The relro creations might 'finish' (not start at all) before
- // WebViewFactory.onWebViewProviderChanged which means we might not know the
- // number of started creations before they finish.
- mNumRelroCreationsStarted = NUMBER_OF_RELROS_UNKNOWN;
- mNumRelroCreationsFinished = 0;
- mNumRelroCreationsStarted =
- mSystemInterface.onWebViewProviderChanged(newPackage);
- Counter.logIncrement("webview.value_on_webview_provider_changed_counter");
- if (newPackage.packageName.equals(getDefaultWebViewPackage().packageName)) {
- Counter.logIncrement(
- "webview.value_on_webview_provider_changed_"
- + "with_default_package_counter");
- }
- // If the relro creations finish before we know the number of started creations
- // we will have to do any cleanup/notifying here.
- checkIfRelrosDoneLocked();
- } else {
- mWebViewPackageDirty = true;
- }
- }
-
- // Once we've notified the system that the provider has changed and started RELRO creation,
- // try to restart the zygote so that it will be ready when apps use it.
- if (isMultiProcessEnabled()) {
- AsyncTask.THREAD_POOL_EXECUTOR.execute(this::startZygoteWhenReady);
- }
- }
-
- /**
- * Fetch only the currently valid WebView packages.
- **/
- @Override
- public WebViewProviderInfo[] getValidWebViewPackages() {
- ProviderAndPackageInfo[] providersAndPackageInfos = getValidWebViewPackagesAndInfos();
- WebViewProviderInfo[] providers =
- new WebViewProviderInfo[providersAndPackageInfos.length];
- for (int n = 0; n < providersAndPackageInfos.length; n++) {
- providers[n] = providersAndPackageInfos[n].provider;
- }
- return providers;
- }
-
- @Override
- public WebViewProviderInfo getDefaultWebViewPackage() {
- for (WebViewProviderInfo provider : getWebViewPackages()) {
- if (provider.availableByDefault) {
- return provider;
- }
- }
-
- // This should be unreachable because the config parser enforces that there is at least
- // one availableByDefault provider.
- throw new AndroidRuntimeException("No available by default WebView Provider.");
- }
-
- private static class ProviderAndPackageInfo {
- public final WebViewProviderInfo provider;
- public final PackageInfo packageInfo;
-
- ProviderAndPackageInfo(WebViewProviderInfo provider, PackageInfo packageInfo) {
- this.provider = provider;
- this.packageInfo = packageInfo;
- }
- }
-
- private ProviderAndPackageInfo[] getValidWebViewPackagesAndInfos() {
- WebViewProviderInfo[] allProviders = mSystemInterface.getWebViewPackages();
- List<ProviderAndPackageInfo> providers = new ArrayList<>();
- for (int n = 0; n < allProviders.length; n++) {
- try {
- PackageInfo packageInfo =
- mSystemInterface.getPackageInfoForProvider(allProviders[n]);
- if (validityResult(allProviders[n], packageInfo) == VALIDITY_OK) {
- providers.add(new ProviderAndPackageInfo(allProviders[n], packageInfo));
- }
- } catch (NameNotFoundException e) {
- // Don't add non-existent packages
- }
- }
- return providers.toArray(new ProviderAndPackageInfo[providers.size()]);
- }
-
- /**
- * Returns either the package info of the WebView provider determined in the following way:
- * If the user has chosen a provider then use that if it is valid,
- * otherwise use the first package in the webview priority list that is valid.
- *
- */
- private PackageInfo findPreferredWebViewPackage() throws WebViewPackageMissingException {
- ProviderAndPackageInfo[] providers = getValidWebViewPackagesAndInfos();
-
- String userChosenProvider = mSystemInterface.getUserChosenWebViewProvider();
-
- // If the user has chosen provider, use that (if it's installed and enabled for all
- // users).
- for (ProviderAndPackageInfo providerAndPackage : providers) {
- if (providerAndPackage.provider.packageName.equals(userChosenProvider)) {
- // userPackages can contain null objects.
- List<UserPackage> userPackages =
- mSystemInterface.getPackageInfoForProviderAllUsers(
- providerAndPackage.provider);
- if (isInstalledAndEnabledForAllUsers(userPackages)) {
- return providerAndPackage.packageInfo;
- }
- }
- }
-
- // User did not choose, or the choice failed; use the most stable provider that is
- // installed and enabled for all users, and available by default (not through
- // user choice).
- for (ProviderAndPackageInfo providerAndPackage : providers) {
- if (providerAndPackage.provider.availableByDefault) {
- // userPackages can contain null objects.
- List<UserPackage> userPackages =
- mSystemInterface.getPackageInfoForProviderAllUsers(
- providerAndPackage.provider);
- if (isInstalledAndEnabledForAllUsers(userPackages)) {
- return providerAndPackage.packageInfo;
- }
- }
- }
-
- // This should never happen during normal operation (only with modified system images).
- mAnyWebViewInstalled = false;
- throw new WebViewPackageMissingException("Could not find a loadable WebView package");
- }
-
- /**
- * Return true iff {@param packageInfos} point to only installed and enabled packages.
- * The given packages {@param packageInfos} should all be pointing to the same package, but each
- * PackageInfo representing a different user's package.
- */
- private static boolean isInstalledAndEnabledForAllUsers(
- List<UserPackage> userPackages) {
- for (UserPackage userPackage : userPackages) {
- if (!userPackage.isInstalledPackage() || !userPackage.isEnabledPackage()) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public WebViewProviderInfo[] getWebViewPackages() {
- return mSystemInterface.getWebViewPackages();
- }
-
- @Override
- public PackageInfo getCurrentWebViewPackage() {
- synchronized (mLock) {
- return mCurrentWebViewPackage;
- }
- }
-
- /**
- * Returns whether WebView is ready and is not going to go through its preparation phase
- * again directly.
- */
- private boolean webViewIsReadyLocked() {
- return !mWebViewPackageDirty
- && (mNumRelroCreationsStarted == mNumRelroCreationsFinished)
- // The current package might be replaced though we haven't received an intent
- // declaring this yet, the following flag makes anyone loading WebView to wait in
- // this case.
- && mAnyWebViewInstalled;
- }
-
- private void checkIfRelrosDoneLocked() {
- if (mNumRelroCreationsStarted == mNumRelroCreationsFinished) {
- if (mWebViewPackageDirty) {
- mWebViewPackageDirty = false;
- // If we have changed provider since we started the relro creation we need to
- // redo the whole process using the new package instead.
- try {
- PackageInfo newPackage = findPreferredWebViewPackage();
- onWebViewProviderChanged(newPackage);
- } catch (WebViewPackageMissingException e) {
- mCurrentWebViewPackage = null;
- // If we can't find any valid WebView package we are now in a state where
- // mAnyWebViewInstalled is false, so loading WebView will be blocked and we
- // should simply wait until we receive an intent declaring a new package was
- // installed.
- }
- } else {
- mLock.notifyAll();
- }
- }
- }
-
- private int validityResult(WebViewProviderInfo configInfo, PackageInfo packageInfo) {
- // Ensure the provider targets this framework release (or a later one).
- if (!UserPackage.hasCorrectTargetSdkVersion(packageInfo)) {
- return VALIDITY_INCORRECT_SDK_VERSION;
- }
- if (!versionCodeGE(packageInfo.getLongVersionCode(), getMinimumVersionCode())
- && !mSystemInterface.systemIsDebuggable()) {
- // Webview providers may be downgraded arbitrarily low, prevent that by enforcing
- // minimum version code. This check is only enforced for user builds.
- return VALIDITY_INCORRECT_VERSION_CODE;
- }
- if (!providerHasValidSignature(configInfo, packageInfo, mSystemInterface)) {
- return VALIDITY_INCORRECT_SIGNATURE;
- }
- if (WebViewFactory.getWebViewLibrary(packageInfo.applicationInfo) == null) {
- return VALIDITY_NO_LIBRARY_FLAG;
- }
- return VALIDITY_OK;
- }
-
- /**
- * Both versionCodes should be from a WebView provider package implemented by Chromium.
- * VersionCodes from other kinds of packages won't make any sense in this method.
- *
- * An introduction to Chromium versionCode scheme:
- * "BBBBPPPXX"
- * BBBB: 4 digit branch number. It monotonically increases over time.
- * PPP: patch number in the branch. It is padded with zeroes to the left. These three digits
- * may change their meaning in the future.
- * XX: Digits to differentiate different APK builds of the same source version.
- *
- * This method takes the "BBBB" of versionCodes and compare them.
- *
- * https://www.chromium.org/developers/version-numbers describes general Chromium versioning;
- * https://source.chromium.org/chromium/chromium/src/+/master:build/util/android_chrome_version.py
- * is the canonical source for how Chromium versionCodes are calculated.
- *
- * @return true if versionCode1 is higher than or equal to versionCode2.
- */
- private static boolean versionCodeGE(long versionCode1, long versionCode2) {
- long v1 = versionCode1 / 100000;
- long v2 = versionCode2 / 100000;
-
- return v1 >= v2;
- }
-
- /**
- * Gets the minimum version code allowed for a valid provider. It is the minimum versionCode
- * of all available-by-default WebView provider packages. If there is no such WebView provider
- * package on the system, then return -1, which means all positive versionCode WebView packages
- * are accepted.
- *
- * Note that this is a private method that handles a variable (mMinimumVersionCode) which is
- * shared between threads. Furthermore, this method does not hold mLock meaning that we must
- * take extra care to ensure this method is thread-safe.
- */
- private long getMinimumVersionCode() {
- if (mMinimumVersionCode > 0) {
- return mMinimumVersionCode;
- }
-
- long minimumVersionCode = -1;
- for (WebViewProviderInfo provider : mSystemInterface.getWebViewPackages()) {
- if (provider.availableByDefault) {
- try {
- long versionCode =
- mSystemInterface.getFactoryPackageVersion(provider.packageName);
- if (minimumVersionCode < 0 || versionCode < minimumVersionCode) {
- minimumVersionCode = versionCode;
- }
- } catch (NameNotFoundException e) {
- // Safe to ignore.
- }
- }
- }
-
- mMinimumVersionCode = minimumVersionCode;
- return mMinimumVersionCode;
- }
-
- private static boolean providerHasValidSignature(WebViewProviderInfo provider,
- PackageInfo packageInfo, SystemInterface systemInterface) {
- // Skip checking signatures on debuggable builds, for development purposes.
- if (systemInterface.systemIsDebuggable()) return true;
-
- // Allow system apps to be valid providers regardless of signature.
- if (packageInfo.applicationInfo.isSystemApp()) return true;
-
- // We don't support packages with multiple signatures.
- if (packageInfo.signatures.length != 1) return false;
-
- // If any of the declared signatures match the package signature, it's valid.
- for (Signature signature : provider.signatures) {
- if (signature.equals(packageInfo.signatures[0])) return true;
- }
-
- return false;
- }
-
- /**
- * Returns the only fallback provider in the set of given packages, or null if there is none.
- */
- private static WebViewProviderInfo getFallbackProvider(WebViewProviderInfo[] webviewPackages) {
- for (WebViewProviderInfo provider : webviewPackages) {
- if (provider.isFallback) {
- return provider;
- }
- }
- return null;
- }
-
- @Override
- public boolean isMultiProcessEnabled() {
- int settingValue = mSystemInterface.getMultiProcessSetting();
- if (mSystemInterface.isMultiProcessDefaultEnabled()) {
- // Multiprocess should be enabled unless the user has turned it off manually.
- return settingValue > MULTIPROCESS_SETTING_OFF_VALUE;
- } else {
- // Multiprocess should not be enabled, unless the user has turned it on manually.
- return settingValue >= MULTIPROCESS_SETTING_ON_VALUE;
- }
- }
-
- @Override
- public void enableMultiProcess(boolean enable) {
- PackageInfo current = getCurrentWebViewPackage();
- mSystemInterface.setMultiProcessSetting(
- enable ? MULTIPROCESS_SETTING_ON_VALUE : MULTIPROCESS_SETTING_OFF_VALUE);
- mSystemInterface.notifyZygote(enable);
- if (current != null) {
- mSystemInterface.killPackageDependents(current.packageName);
- }
- }
-
- /**
- * Dump the state of this Service.
- */
- @Override
- public void dumpState(PrintWriter pw) {
- pw.println("Current WebView Update Service state");
- pw.println(String.format(" Multiprocess enabled: %b", isMultiProcessEnabled()));
- synchronized (mLock) {
- if (mCurrentWebViewPackage == null) {
- pw.println(" Current WebView package is null");
- } else {
- pw.println(String.format(" Current WebView package (name, version): (%s, %s)",
- mCurrentWebViewPackage.packageName,
- mCurrentWebViewPackage.versionName));
- }
- pw.println(String.format(" Minimum targetSdkVersion: %d",
- UserPackage.MINIMUM_SUPPORTED_SDK));
- pw.println(String.format(" Minimum WebView version code: %d",
- mMinimumVersionCode));
- pw.println(String.format(" Number of relros started: %d",
- mNumRelroCreationsStarted));
- pw.println(String.format(" Number of relros finished: %d",
- mNumRelroCreationsFinished));
- pw.println(String.format(" WebView package dirty: %b", mWebViewPackageDirty));
- pw.println(String.format(" Any WebView package installed: %b",
- mAnyWebViewInstalled));
-
- try {
- PackageInfo preferredWebViewPackage = findPreferredWebViewPackage();
- pw.println(String.format(
- " Preferred WebView package (name, version): (%s, %s)",
- preferredWebViewPackage.packageName,
- preferredWebViewPackage.versionName));
- } catch (WebViewPackageMissingException e) {
- pw.println(String.format(" Preferred WebView package: none"));
- }
-
- dumpAllPackageInformationLocked(pw);
- }
- }
-
- private void dumpAllPackageInformationLocked(PrintWriter pw) {
- WebViewProviderInfo[] allProviders = mSystemInterface.getWebViewPackages();
- pw.println(" WebView packages:");
- for (WebViewProviderInfo provider : allProviders) {
- List<UserPackage> userPackages =
- mSystemInterface.getPackageInfoForProviderAllUsers(provider);
- PackageInfo systemUserPackageInfo =
- userPackages.get(UserHandle.USER_SYSTEM).getPackageInfo();
- if (systemUserPackageInfo == null) {
- pw.println(String.format(" %s is NOT installed.", provider.packageName));
- continue;
- }
-
- int validity = validityResult(provider, systemUserPackageInfo);
- String packageDetails = String.format(
- "versionName: %s, versionCode: %d, targetSdkVersion: %d",
- systemUserPackageInfo.versionName,
- systemUserPackageInfo.getLongVersionCode(),
- systemUserPackageInfo.applicationInfo.targetSdkVersion);
- if (validity == VALIDITY_OK) {
- boolean installedForAllUsers = isInstalledAndEnabledForAllUsers(
- mSystemInterface.getPackageInfoForProviderAllUsers(provider));
- pw.println(String.format(
- " Valid package %s (%s) is %s installed/enabled for all users",
- systemUserPackageInfo.packageName,
- packageDetails,
- installedForAllUsers ? "" : "NOT"));
- } else {
- pw.println(String.format(" Invalid package %s (%s), reason: %s",
- systemUserPackageInfo.packageName,
- packageDetails,
- getInvalidityReason(validity)));
- }
- }
- }
-
- private static String getInvalidityReason(int invalidityReason) {
- switch (invalidityReason) {
- case VALIDITY_INCORRECT_SDK_VERSION:
- return "SDK version too low";
- case VALIDITY_INCORRECT_VERSION_CODE:
- return "Version code too low";
- case VALIDITY_INCORRECT_SIGNATURE:
- return "Incorrect signature";
- case VALIDITY_NO_LIBRARY_FLAG:
- return "No WebView-library manifest flag";
- default:
- return "Unexcepted validity-reason";
- }
- }
-}
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl2.java b/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl2.java
index 307c15b..a5a02cd 100644
--- a/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl2.java
+++ b/services/core/java/com/android/server/webkit/WebViewUpdateServiceImpl2.java
@@ -66,7 +66,7 @@
*
* @hide
*/
-class WebViewUpdateServiceImpl2 implements WebViewUpdateServiceInterface {
+class WebViewUpdateServiceImpl2 {
private static final String TAG = WebViewUpdateServiceImpl2.class.getSimpleName();
private static class WebViewPackageMissingException extends Exception {
@@ -125,7 +125,6 @@
mDefaultProvider = defaultProvider;
}
- @Override
public void packageStateChanged(String packageName, int changedState, int userId) {
// We don't early out here in different cases where we could potentially early-out (e.g. if
// we receive PACKAGE_CHANGED for another user than the system user) since that would
@@ -216,7 +215,6 @@
mSystemInterface.enablePackageForAllUsers(mDefaultProvider.packageName, true);
}
- @Override
public void prepareWebViewInSystemServer() {
try {
boolean repairNeeded = true;
@@ -256,7 +254,6 @@
mSystemInterface.ensureZygoteStarted();
}
- @Override
public void handleNewUser(int userId) {
// The system user is always started at boot, and by that point we have already run one
// round of the package-changing logic (through prepareWebViewInSystemServer()), so early
@@ -265,7 +262,6 @@
handleUserChange();
}
- @Override
public void handleUserRemoved(int userId) {
handleUserChange();
}
@@ -280,7 +276,6 @@
updateCurrentWebViewPackage(null);
}
- @Override
public void notifyRelroCreationCompleted() {
synchronized (mLock) {
mNumRelroCreationsFinished++;
@@ -288,7 +283,6 @@
}
}
- @Override
public WebViewProviderResponse waitForAndGetProvider() {
PackageInfo webViewPackage = null;
final long timeoutTimeMs = System.nanoTime() / NS_PER_MS + WAIT_TIMEOUT_MS;
@@ -334,7 +328,6 @@
* replacing that provider it will not be in use directly, but will be used when the relros
* or the replacement are done).
*/
- @Override
public String changeProviderAndSetting(String newProviderName) {
PackageInfo newPackage = updateCurrentWebViewPackage(newProviderName);
if (newPackage == null) return "";
@@ -430,7 +423,6 @@
}
/** Fetch only the currently valid WebView packages. */
- @Override
public WebViewProviderInfo[] getValidWebViewPackages() {
ProviderAndPackageInfo[] providersAndPackageInfos = getValidWebViewPackagesAndInfos();
WebViewProviderInfo[] providers =
@@ -445,7 +437,6 @@
* Returns the default WebView provider which should be first availableByDefault option in the
* system config.
*/
- @Override
public WebViewProviderInfo getDefaultWebViewPackage() {
return mDefaultProvider;
}
@@ -550,12 +541,10 @@
return true;
}
- @Override
public WebViewProviderInfo[] getWebViewPackages() {
return mSystemInterface.getWebViewPackages();
}
- @Override
public PackageInfo getCurrentWebViewPackage() {
synchronized (mLock) {
return mCurrentWebViewPackage;
@@ -708,20 +697,7 @@
return null;
}
- @Override
- public boolean isMultiProcessEnabled() {
- throw new IllegalStateException(
- "isMultiProcessEnabled shouldn't be called if update_service_v2 flag is set.");
- }
-
- @Override
- public void enableMultiProcess(boolean enable) {
- throw new IllegalStateException(
- "enableMultiProcess shouldn't be called if update_service_v2 flag is set.");
- }
-
/** Dump the state of this Service. */
- @Override
public void dumpState(PrintWriter pw) {
pw.println("Current WebView Update Service state");
synchronized (mLock) {
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdateServiceInterface.java b/services/core/java/com/android/server/webkit/WebViewUpdateServiceInterface.java
deleted file mode 100644
index 1772ef9..0000000
--- a/services/core/java/com/android/server/webkit/WebViewUpdateServiceInterface.java
+++ /dev/null
@@ -1,52 +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.server.webkit;
-
-import android.content.pm.PackageInfo;
-import android.webkit.WebViewProviderInfo;
-import android.webkit.WebViewProviderResponse;
-
-import java.io.PrintWriter;
-
-interface WebViewUpdateServiceInterface {
- void packageStateChanged(String packageName, int changedState, int userId);
-
- void handleNewUser(int userId);
-
- void handleUserRemoved(int userId);
-
- WebViewProviderInfo[] getWebViewPackages();
-
- void prepareWebViewInSystemServer();
-
- void notifyRelroCreationCompleted();
-
- WebViewProviderResponse waitForAndGetProvider();
-
- String changeProviderAndSetting(String newProviderName);
-
- WebViewProviderInfo[] getValidWebViewPackages();
-
- WebViewProviderInfo getDefaultWebViewPackage();
-
- PackageInfo getCurrentWebViewPackage();
-
- boolean isMultiProcessEnabled();
-
- void enableMultiProcess(boolean enable);
-
- void dumpState(PrintWriter pw);
-}
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdateServiceShellCommand.java b/services/core/java/com/android/server/webkit/WebViewUpdateServiceShellCommand.java
deleted file mode 100644
index 7529c41..0000000
--- a/services/core/java/com/android/server/webkit/WebViewUpdateServiceShellCommand.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2016 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.webkit;
-
-import android.os.RemoteException;
-import android.os.ShellCommand;
-import android.webkit.IWebViewUpdateService;
-
-import java.io.PrintWriter;
-
-class WebViewUpdateServiceShellCommand extends ShellCommand {
- final IWebViewUpdateService mInterface;
-
- WebViewUpdateServiceShellCommand(IWebViewUpdateService service) {
- mInterface = service;
- }
-
- @Override
- public int onCommand(String cmd) {
- if (cmd == null) {
- return handleDefaultCommands(cmd);
- }
-
- final PrintWriter pw = getOutPrintWriter();
- try {
- switch(cmd) {
- case "set-webview-implementation":
- return setWebViewImplementation();
- case "enable-multiprocess":
- return enableMultiProcess(true);
- case "disable-multiprocess":
- return enableMultiProcess(false);
- default:
- return handleDefaultCommands(cmd);
- }
- } catch (RemoteException e) {
- pw.println("Remote exception: " + e);
- }
- return -1;
- }
-
- private int setWebViewImplementation() throws RemoteException {
- final PrintWriter pw = getOutPrintWriter();
- String shellChosenPackage = getNextArg();
- if (shellChosenPackage == null) {
- pw.println("Failed to switch, no PACKAGE provided.");
- pw.println("");
- helpSetWebViewImplementation();
- return 1;
- }
- String newPackage = mInterface.changeProviderAndSetting(shellChosenPackage);
- if (shellChosenPackage.equals(newPackage)) {
- pw.println("Success");
- return 0;
- } else {
- pw.println(String.format(
- "Failed to switch to %s, the WebView implementation is now provided by %s.",
- shellChosenPackage, newPackage));
- return 1;
- }
- }
-
- private int enableMultiProcess(boolean enable) throws RemoteException {
- final PrintWriter pw = getOutPrintWriter();
- mInterface.enableMultiProcess(enable);
- pw.println("Success");
- return 0;
- }
-
- public void helpSetWebViewImplementation() {
- PrintWriter pw = getOutPrintWriter();
- pw.println(" set-webview-implementation PACKAGE");
- pw.println(" Set the WebView implementation to the specified package.");
- }
-
- @Override
- public void onHelp() {
- PrintWriter pw = getOutPrintWriter();
- pw.println("WebView updater commands:");
- pw.println(" help");
- pw.println(" Print this help text.");
- pw.println("");
- helpSetWebViewImplementation();
- pw.println(" enable-multiprocess");
- pw.println(" Enable multi-process mode for WebView");
- pw.println(" disable-multiprocess");
- pw.println(" Disable multi-process mode for WebView");
- pw.println();
- }
-}
diff --git a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
index 15c9b9f..a4546ae 100644
--- a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
+++ b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
@@ -297,6 +297,7 @@
private const val MASK_ANY_FIXED =
PermissionFlags.USER_SET or
+ PermissionFlags.ONE_TIME or
PermissionFlags.USER_FIXED or
PermissionFlags.POLICY_FIXED or
PermissionFlags.SYSTEM_FIXED
diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
index d4b57f1..f439770 100644
--- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
+++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
@@ -26,6 +26,8 @@
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
+import android.platform.test.annotations.EnableFlags
+import android.platform.test.flag.junit.SetFlagsRule
import android.util.ArraySet
import android.util.SparseArray
import android.util.SparseIntArray
@@ -47,14 +49,19 @@
import com.android.server.pm.pkg.AndroidPackage
import com.android.server.testutils.mockThrowOnUnmocked
import com.android.server.testutils.whenever
+import org.junit.Rule
import java.security.KeyPairGenerator
import java.security.PublicKey
import java.util.UUID
import kotlin.contracts.ExperimentalContracts
@ExperimentalContracts
+@EnableFlags(android.content.pm.Flags.FLAG_INCLUDE_FEATURE_FLAGS_IN_PACKAGE_CACHER)
class AndroidPackageTest : ParcelableComponentTest(AndroidPackage::class, PackageImpl::class) {
+ @get:Rule
+ val setFlagsRule: SetFlagsRule = SetFlagsRule()
+
companion object {
private val TEST_UUID = UUID.fromString("57554103-df3e-4475-ae7a-8feba49353ac")
}
@@ -93,6 +100,8 @@
"getUsesOptionalLibrariesSorted",
"getUsesSdkLibrariesSorted",
"getUsesStaticLibrariesSorted",
+ "readFeatureFlagState",
+ "writeFeatureFlagState",
// Tested through setting minor/major manually
"setLongVersionCode",
"getLongVersionCode",
@@ -149,6 +158,10 @@
"isSystem",
"isSystemExt",
"isVendor",
+
+ // Tested through addFeatureFlag
+ "addFeatureFlag",
+ "getFeatureFlagState",
)
override val baseParams = listOf(
@@ -613,6 +626,9 @@
.setSplitClassLoaderName(1, "testSplitClassLoaderNameOne")
.addUsesSdkLibrary("testSdk", 2L, arrayOf("testCertDigest1"), true)
.addUsesStaticLibrary("testStatic", 3L, arrayOf("testCertDigest2"))
+ .addFeatureFlag("testFlag1", null)
+ .addFeatureFlag("testFlag2", true)
+ .addFeatureFlag("testFlag3", false)
override fun finalizeObject(parcelable: Parcelable) {
(parcelable as PackageImpl).hideAsParsed().hideAsFinal()
@@ -673,6 +689,12 @@
.containsExactly("testCertDigest2")
expect.that(after.storageUuid).isEqualTo(TEST_UUID)
+
+ expect.that(after.featureFlagState).containsExactlyEntriesIn(mapOf(
+ "testFlag1" to null,
+ "testFlag2" to true,
+ "testFlag3" to false,
+ ))
}
private fun testKey() = KeyPairGenerator.getInstance("RSA")
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityManagerServiceTest.java
index 7481fc8..2edde9b 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityManagerServiceTest.java
@@ -1615,7 +1615,8 @@
List.of(tile)
);
- assertThat(mA11yms.getCurrentUserState().getA11yQsTargets()).doesNotContain(tile);
+ assertThat(mA11yms.getCurrentUserState()
+ .getShortcutTargetsLocked(QUICK_SETTINGS)).doesNotContain(tile.flattenToString());
}
@Test
@@ -1636,7 +1637,7 @@
List.of(tile)
);
- assertThat(mA11yms.getCurrentUserState().getA11yQsTargets())
+ assertThat(mA11yms.getCurrentUserState().getShortcutTargetsLocked(QUICK_SETTINGS))
.contains(TARGET_ALWAYS_ON_A11Y_SERVICE.flattenToString());
}
@@ -1656,7 +1657,7 @@
);
assertThat(
- mA11yms.getCurrentUserState().getA11yQsTargets()
+ mA11yms.getCurrentUserState().getShortcutTargetsLocked(QUICK_SETTINGS)
).containsExactlyElementsIn(List.of(
AccessibilityShortcutController.DALTONIZER_COMPONENT_NAME.flattenToString(),
AccessibilityShortcutController.COLOR_INVERSION_COMPONENT_NAME.flattenToString())
@@ -1676,7 +1677,7 @@
);
assertThat(
- mA11yms.getCurrentUserState().getA11yQsTargets()
+ mA11yms.getCurrentUserState().getShortcutTargetsLocked(QUICK_SETTINGS)
).doesNotContain(
AccessibilityShortcutController.DALTONIZER_COMPONENT_NAME.flattenToString());
}
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
index 627b5e3..8c35925 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
@@ -29,6 +29,7 @@
import static android.view.accessibility.AccessibilityManager.STATE_FLAG_TOUCH_EXPLORATION_ENABLED;
import static com.android.internal.accessibility.AccessibilityShortcutController.MAGNIFICATION_CONTROLLER_NAME;
+import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.ALL;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.GESTURE;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.HARDWARE;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.QUICK_SETTINGS;
@@ -72,6 +73,7 @@
import com.android.internal.accessibility.AccessibilityShortcutController;
import com.android.internal.accessibility.common.ShortcutConstants;
import com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType;
+import com.android.internal.accessibility.util.ShortcutUtils;
import com.android.internal.util.test.FakeSettingsProvider;
import org.junit.After;
@@ -454,17 +456,7 @@
mUserState.updateShortcutTargetsLocked(newTargets, QUICK_SETTINGS);
- assertThat(mUserState.getA11yQsTargets()).isEqualTo(newTargets);
- }
-
- @Test
- public void getA11yQsTargets_returnsCopiedData() {
- updateShortcutTargetsLocked_quickSettings_valueUpdated();
-
- Set<String> targets = mUserState.getA11yQsTargets();
- targets.clear();
-
- assertThat(mUserState.getA11yQsTargets()).isNotEmpty();
+ assertThat(mUserState.getShortcutTargetsLocked(QUICK_SETTINGS)).isEqualTo(newTargets);
}
@Test
@@ -539,6 +531,31 @@
assertThat(mUserState.isShortcutMagnificationEnabledLocked()).isFalse();
}
+ @Test
+ public void getShortcutTargetsLocked_returnsCorrectTargets() {
+ for (int shortcutType : ShortcutConstants.USER_SHORTCUT_TYPES) {
+ if (((TRIPLETAP | TWOFINGER_DOUBLETAP) & shortcutType) == shortcutType) {
+ continue;
+ }
+ Set<String> expectedSet = Set.of(ShortcutUtils.convertToKey(shortcutType));
+ mUserState.updateShortcutTargetsLocked(expectedSet, shortcutType);
+
+ assertThat(mUserState.getShortcutTargetsLocked(shortcutType))
+ .containsExactlyElementsIn(expectedSet);
+ }
+ }
+
+ @Test
+ public void getShortcutTargetsLocked_returnsCopiedData() {
+ Set<String> set = Set.of("FOO", "BAR");
+ mUserState.updateShortcutTargetsLocked(set, SOFTWARE);
+
+ Set<String> targets = mUserState.getShortcutTargetsLocked(ALL);
+ targets.clear();
+
+ assertThat(mUserState.getShortcutTargetsLocked(ALL)).isNotEmpty();
+ }
+
private int getSecureIntForUser(String key, int userId) {
return Settings.Secure.getIntForUser(mMockResolver, key, -1, userId);
}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
index 2f7b8d2..4ef37b9 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
@@ -69,6 +69,7 @@
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
+import android.os.UserManager;
import android.platform.test.annotations.Presubmit;
import android.security.KeyStoreAuthorization;
import android.testing.TestableContext;
@@ -119,6 +120,7 @@
@Mock private AuthSession.ClientDeathReceiver mClientDeathReceiver;
@Mock private BiometricFrameworkStatsLogger mBiometricFrameworkStatsLogger;
@Mock private BiometricCameraManager mBiometricCameraManager;
+ @Mock private UserManager mUserManager;
@Mock private BiometricManager mBiometricManager;
private Random mRandom;
@@ -846,7 +848,8 @@
TEST_PACKAGE,
checkDevicePolicyManager,
mContext,
- mBiometricCameraManager);
+ mBiometricCameraManager,
+ mUserManager);
}
private AuthSession createAuthSession(List<BiometricSensor> sensors,
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java b/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
index 85e45f4..510dd4d 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/PreAuthInfoTest.java
@@ -39,6 +39,7 @@
import android.hardware.biometrics.IBiometricAuthenticator;
import android.hardware.biometrics.PromptInfo;
import android.os.RemoteException;
+import android.os.UserManager;
import android.platform.test.annotations.Presubmit;
import android.platform.test.annotations.RequiresFlagsEnabled;
import android.platform.test.flag.junit.CheckFlagsRule;
@@ -64,6 +65,8 @@
public final CheckFlagsRule mCheckFlagsRule =
DeviceFlagsValueProvider.createCheckFlagsRule();
+ private static final int USER_ID = 0;
+ private static final int OWNER_ID = 10;
private static final int SENSOR_ID_FINGERPRINT = 0;
private static final int SENSOR_ID_FACE = 1;
private static final String TEST_PACKAGE_NAME = "PreAuthInfoTestPackage";
@@ -84,6 +87,8 @@
BiometricService.SettingObserver mSettingObserver;
@Mock
BiometricCameraManager mBiometricCameraManager;
+ @Mock
+ UserManager mUserManager;
@Before
public void setup() throws RemoteException {
@@ -118,9 +123,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).isEmpty();
}
@@ -134,9 +139,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(1);
}
@@ -151,9 +156,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(0);
}
@@ -171,9 +176,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(faceSensor, fingerprintSensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(faceSensor, fingerprintSensor), USER_ID,
+ promptInfo, TEST_PACKAGE_NAME, false /* checkDevicePolicyManager */, mContext,
+ mBiometricCameraManager, mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(0);
assertThat(preAuthInfo.getCanAuthenticateResult()).isEqualTo(
@@ -191,9 +196,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(faceSensor, fingerprintSensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(faceSensor, fingerprintSensor), USER_ID,
+ promptInfo, TEST_PACKAGE_NAME, false /* checkDevicePolicyManager */, mContext,
+ mBiometricCameraManager, mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(1);
assertThat(preAuthInfo.eligibleSensors.get(0).modality).isEqualTo(TYPE_FINGERPRINT);
@@ -209,8 +214,9 @@
final PromptInfo promptInfo = new PromptInfo();
promptInfo.setAuthenticators(BiometricManager.Authenticators.IDENTITY_CHECK);
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor), 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(1);
}
@@ -224,8 +230,9 @@
final PromptInfo promptInfo = new PromptInfo();
promptInfo.setAuthenticators(BiometricManager.Authenticators.IDENTITY_CHECK);
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(), 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(0);
}
@@ -241,8 +248,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.IDENTITY_CHECK
| BiometricManager.Authenticators.BIOMETRIC_STRONG);
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor), 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(1);
}
@@ -257,8 +265,9 @@
final PromptInfo promptInfo = new PromptInfo();
promptInfo.setAuthenticators(BiometricManager.Authenticators.IDENTITY_CHECK);
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor), 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(preAuthInfo.getCanAuthenticateResult()).isEqualTo(
BiometricManager.BIOMETRIC_ERROR_IDENTITY_CHECK_NOT_ACTIVE);
@@ -279,9 +288,9 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
promptInfo.setDisallowBiometricsIfPolicyExists(false /* checkDevicePolicy */);
PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(faceSensor, fingerprintSensor),
- 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(faceSensor, fingerprintSensor), USER_ID,
+ promptInfo, TEST_PACKAGE_NAME, false /* checkDevicePolicyManager */, mContext,
+ mBiometricCameraManager, mUserManager);
assertThat(preAuthInfo.eligibleSensors).hasSize(0);
assertThat(preAuthInfo.getCanAuthenticateResult()).isEqualTo(
@@ -299,11 +308,30 @@
promptInfo.setAuthenticators(BiometricManager.Authenticators.IDENTITY_CHECK);
promptInfo.setNegativeButtonText(TEST_PACKAGE_NAME);
final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
- mSettingObserver, List.of(sensor), 0 /* userId */, promptInfo, TEST_PACKAGE_NAME,
- false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager);
+ mSettingObserver, List.of(sensor), USER_ID, promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
assertThat(promptInfo.getNegativeButtonText()).isEqualTo(TEST_PACKAGE_NAME);
}
+ @Test
+ @RequiresFlagsEnabled(Flags.FLAG_PRIVATE_SPACE_BP)
+ public void testCredentialOwnerIdAsUserId() throws Exception {
+ when(mUserManager.getCredentialOwnerProfile(USER_ID)).thenReturn(OWNER_ID);
+
+ final BiometricSensor sensor = getFaceSensor();
+ final PromptInfo promptInfo = new PromptInfo();
+ promptInfo.setAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG);
+ promptInfo.setNegativeButtonText(TEST_PACKAGE_NAME);
+ final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager, mDevicePolicyManager,
+ mSettingObserver, List.of(sensor), USER_ID , promptInfo, TEST_PACKAGE_NAME,
+ false /* checkDevicePolicyManager */, mContext, mBiometricCameraManager,
+ mUserManager);
+
+ assertThat(preAuthInfo.userId).isEqualTo(OWNER_ID);
+ assertThat(preAuthInfo.callingUserId).isEqualTo(USER_ID);
+ }
+
private BiometricSensor getFingerprintSensor() {
BiometricSensor sensor = new BiometricSensor(mContext, SENSOR_ID_FINGERPRINT,
TYPE_FINGERPRINT, BiometricManager.Authenticators.BIOMETRIC_STRONG,
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
index 3360e1d..c741c6c 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
@@ -37,6 +37,7 @@
import android.hardware.hdmi.HdmiPortInfo;
import android.hardware.hdmi.IHdmiControlCallback;
import android.hardware.tv.cec.V1_0.SendMessageResult;
+import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.os.test.TestLooper;
@@ -2676,6 +2677,60 @@
}
@Test
+ public void onActiveSourceLost_oneTouchPlay_noStandbyAfterTimeout() {
+ mHdmiCecLocalDevicePlayback.mService.getHdmiCecConfig().setStringValue(
+ HdmiControlManager.CEC_SETTING_NAME_POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST,
+ HdmiControlManager.POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST_STANDBY_NOW);
+ mHdmiCecLocalDevicePlayback.setActiveSource(mPlaybackLogicalAddress,
+ mPlaybackPhysicalAddress, "HdmiCecLocalDevicePlaybackTest");
+ mPowerManager.setInteractive(true);
+ mNativeWrapper.clearResultMessages();
+ mTestLooper.dispatchAll();
+
+ HdmiCecMessage activeSourceFromTv =
+ HdmiCecMessageBuilder.buildActiveSource(ADDR_TV, 0x0000);
+ HdmiCecMessage activeSourceFromPlayback =
+ HdmiCecMessageBuilder.buildActiveSource(mPlaybackLogicalAddress,
+ mPlaybackPhysicalAddress);
+
+ assertThat(mHdmiCecLocalDevicePlayback.handleActiveSource(activeSourceFromTv))
+ .isEqualTo(Constants.HANDLED);
+ assertThat(mHdmiCecLocalDevicePlayback.getActiveSource().logicalAddress).isEqualTo(ADDR_TV);
+ mTestLooper.dispatchAll();
+
+ // Pop-up is triggered.
+ mTestLooper.moveTimeForward(POPUP_AFTER_ACTIVE_SOURCE_LOST_DELAY_MS);
+ mTestLooper.dispatchAll();
+ // RequestActiveSourceAction is triggered and TV confirms active source.
+ mNativeWrapper.onCecMessage(activeSourceFromTv);
+ mTestLooper.dispatchAll();
+
+ assertThat(mIsOnActiveSourceLostPopupActive).isTrue();
+ mHdmiControlService.oneTouchPlay(new IHdmiControlCallback() {
+ @Override
+ public void onComplete(int result) throws RemoteException {
+ }
+
+ @Override
+ public IBinder asBinder() {
+ return null;
+ }
+ });
+ mTestLooper.dispatchAll();
+
+ assertThat(mIsOnActiveSourceLostPopupActive).isFalse();
+ assertThat(mNativeWrapper.getResultMessages().contains(activeSourceFromPlayback)).isTrue();
+ assertThat(mHdmiCecLocalDevicePlayback.getActiveSource().logicalAddress)
+ .isEqualTo(mPlaybackLogicalAddress);
+ assertThat(mHdmiCecLocalDevicePlayback.getActiveSource().physicalAddress)
+ .isEqualTo(mPlaybackPhysicalAddress);
+ mTestLooper.moveTimeForward(STANDBY_AFTER_ACTIVE_SOURCE_LOST_DELAY_MS);
+ mTestLooper.dispatchAll();
+
+ assertThat(mPowerManager.isInteractive()).isTrue();
+ }
+
+ @Test
public void handleRoutingChange_addressNotAllocated_removeActiveSourceAction() {
long allocationDelay = TimeUnit.SECONDS.toMillis(60);
mHdmiCecLocalDevicePlayback.mPlaybackDeviceActionOnRoutingControl =
diff --git a/services/tests/servicestests/src/com/android/server/webkit/TestSystemImpl.java b/services/tests/servicestests/src/com/android/server/webkit/TestSystemImpl.java
index def3355..aee9f0f 100644
--- a/services/tests/servicestests/src/com/android/server/webkit/TestSystemImpl.java
+++ b/services/tests/servicestests/src/com/android/server/webkit/TestSystemImpl.java
@@ -36,18 +36,15 @@
Map<String, Map<Integer, PackageInfo>> mPackages = new HashMap();
private final int mNumRelros;
private final boolean mIsDebuggable;
- private int mMultiProcessSetting;
- private final boolean mMultiProcessDefault;
public static final int PRIMARY_USER_ID = 0;
- public TestSystemImpl(WebViewProviderInfo[] packageConfigs, int numRelros, boolean isDebuggable,
- boolean multiProcessDefault) {
+ public TestSystemImpl(WebViewProviderInfo[] packageConfigs, int numRelros,
+ boolean isDebuggable) {
mPackageConfigs = packageConfigs;
mNumRelros = numRelros;
mIsDebuggable = isDebuggable;
mUsers.add(PRIMARY_USER_ID);
- mMultiProcessDefault = multiProcessDefault;
}
public void addUser(int userId) {
@@ -181,26 +178,8 @@
}
@Override
- public int getMultiProcessSetting() {
- return mMultiProcessSetting;
- }
-
- @Override
- public void setMultiProcessSetting(int value) {
- mMultiProcessSetting = value;
- }
-
- @Override
- public void notifyZygote(boolean enableMultiProcess) {}
-
- @Override
public void ensureZygoteStarted() {}
@Override
- public boolean isMultiProcessDefaultEnabled() {
- return mMultiProcessDefault;
- }
-
- @Override
public void pinWebviewIfRequired(ApplicationInfo appInfo) {}
}
diff --git a/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java b/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
index 06479c8..42eb609 100644
--- a/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
@@ -16,8 +16,6 @@
package com.android.server.webkit;
-import static android.webkit.Flags.updateServiceV2;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -27,8 +25,6 @@
import android.content.pm.Signature;
import android.os.Build;
import android.os.Bundle;
-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.Base64;
@@ -62,7 +58,7 @@
public class WebViewUpdateServiceTest {
private final static String TAG = WebViewUpdateServiceTest.class.getSimpleName();
- private WebViewUpdateServiceInterface mWebViewUpdateServiceImpl;
+ private WebViewUpdateServiceImpl2 mWebViewUpdateServiceImpl;
private TestSystemImpl mTestSystemImpl;
private static final String WEBVIEW_LIBRARY_FLAG = "com.android.webview.WebViewLibrary";
@@ -77,38 +73,23 @@
}
private void setupWithPackages(WebViewProviderInfo[] packages) {
- setupWithAllParameters(packages, 1 /* numRelros */, true /* isDebuggable */,
- false /* multiProcessDefault */);
+ setupWithAllParameters(packages, 1 /* numRelros */, true /* isDebuggable */);
}
private void setupWithPackagesAndRelroCount(WebViewProviderInfo[] packages, int numRelros) {
- setupWithAllParameters(packages, numRelros, true /* isDebuggable */,
- false /* multiProcessDefault */);
+ setupWithAllParameters(packages, numRelros, true /* isDebuggable */);
}
private void setupWithPackagesNonDebuggable(WebViewProviderInfo[] packages) {
- setupWithAllParameters(packages, 1 /* numRelros */, false /* isDebuggable */,
- false /* multiProcessDefault */);
- }
-
- private void setupWithPackagesAndMultiProcess(WebViewProviderInfo[] packages,
- boolean multiProcessDefault) {
- setupWithAllParameters(packages, 1 /* numRelros */, true /* isDebuggable */,
- multiProcessDefault);
+ setupWithAllParameters(packages, 1 /* numRelros */, false /* isDebuggable */);
}
private void setupWithAllParameters(WebViewProviderInfo[] packages, int numRelros,
- boolean isDebuggable, boolean multiProcessDefault) {
- TestSystemImpl testing = new TestSystemImpl(packages, numRelros, isDebuggable,
- multiProcessDefault);
+ boolean isDebuggable) {
+ TestSystemImpl testing = new TestSystemImpl(packages, numRelros, isDebuggable);
mTestSystemImpl = Mockito.spy(testing);
- if (updateServiceV2()) {
- mWebViewUpdateServiceImpl =
- new WebViewUpdateServiceImpl2(mTestSystemImpl);
- } else {
- mWebViewUpdateServiceImpl =
- new WebViewUpdateServiceImpl(mTestSystemImpl);
- }
+ mWebViewUpdateServiceImpl =
+ new WebViewUpdateServiceImpl2(mTestSystemImpl);
}
private void setEnabledAndValidPackageInfos(WebViewProviderInfo[] providers) {
@@ -350,24 +331,6 @@
}
@Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- // If the flag is set, will throw an exception because of no available by default provider.
- public void testEmptyConfig() {
- WebViewProviderInfo[] packages = new WebViewProviderInfo[0];
- setupWithPackages(packages);
- setEnabledAndValidPackageInfos(packages);
-
- runWebViewBootPreparationOnMainSync();
-
- Mockito.verify(mTestSystemImpl, Mockito.never()).onWebViewProviderChanged(
- Matchers.anyObject());
-
- WebViewProviderResponse response = mWebViewUpdateServiceImpl.waitForAndGetProvider();
- assertEquals(WebViewFactory.LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES, response.status);
- assertEquals(null, mWebViewUpdateServiceImpl.getCurrentWebViewPackage());
- }
-
- @Test
public void testFailListingEmptyWebviewPackages() {
String singlePackage = "singlePackage";
WebViewProviderInfo[] packages = new WebViewProviderInfo[]{
@@ -554,73 +517,6 @@
}
}
- /**
- * Scenario for testing re-enabling a fallback package.
- */
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- public void testFallbackPackageEnabling() {
- String testPackage = "testFallback";
- WebViewProviderInfo[] packages = new WebViewProviderInfo[] {
- new WebViewProviderInfo(
- testPackage, "", true /* default available */, true /* fallback */, null)};
- setupWithPackages(packages);
- mTestSystemImpl.setPackageInfo(
- createPackageInfo(testPackage, false /* enabled */ , true /* valid */,
- true /* installed */));
-
- // Check that the boot time logic re-enables the fallback package.
- runWebViewBootPreparationOnMainSync();
- Mockito.verify(mTestSystemImpl).enablePackageForAllUsers(
- Mockito.eq(testPackage), Mockito.eq(true));
-
- // Fake the message about the enabling having changed the package state,
- // and check we now use that package.
- mWebViewUpdateServiceImpl.packageStateChanged(
- testPackage, WebViewUpdateService.PACKAGE_CHANGED, TestSystemImpl.PRIMARY_USER_ID);
- checkPreparationPhasesForPackage(testPackage, 1);
- }
-
- /**
- * Scenario for installing primary package when secondary in use.
- * 1. Start with only secondary installed
- * 2. Install primary
- * 3. Primary should be used
- */
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- // If the flag is set, we don't automitally switch to secondary package unless it is
- // chosen directly.
- public void testInstallingPrimaryPackage() {
- String primaryPackage = "primary";
- String secondaryPackage = "secondary";
- WebViewProviderInfo[] packages = new WebViewProviderInfo[] {
- new WebViewProviderInfo(
- primaryPackage, "", true /* default available */, false /* fallback */, null),
- new WebViewProviderInfo(
- secondaryPackage, "", true /* default available */, false /* fallback */,
- null)};
- setupWithPackages(packages);
- mTestSystemImpl.setPackageInfo(
- createPackageInfo(secondaryPackage, true /* enabled */ , true /* valid */,
- true /* installed */));
-
- runWebViewBootPreparationOnMainSync();
- checkPreparationPhasesForPackage(secondaryPackage,
- 1 /* first preparation for this package*/);
-
- // Install primary package
- mTestSystemImpl.setPackageInfo(
- createPackageInfo(primaryPackage, true /* enabled */ , true /* valid */,
- true /* installed */));
- mWebViewUpdateServiceImpl.packageStateChanged(primaryPackage,
- WebViewUpdateService.PACKAGE_ADDED_REPLACED, TestSystemImpl.PRIMARY_USER_ID);
-
- // Verify primary package used as provider, and secondary package killed
- checkPreparationPhasesForPackage(primaryPackage, 1 /* first preparation for this package*/);
- Mockito.verify(mTestSystemImpl).killPackageDependents(Mockito.eq(secondaryPackage));
- }
-
@Test
public void testRemovingSecondarySelectsPrimarySingleUser() {
for (PackageRemovalType removalType : REMOVAL_TYPES) {
@@ -848,14 +744,6 @@
checkRecoverAfterFailListingWebviewPackages(true);
}
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- // If the flag is set, we don't automitally switch to second package unless it is chosen
- // directly.
- public void testRecoverFailedListingWebViewPackagesAddedPackage() {
- checkRecoverAfterFailListingWebviewPackages(false);
- }
-
/**
* Test that we can recover correctly from failing to list WebView packages.
* settingsChange: whether to fail during changeProviderAndSetting or packageStateChanged
@@ -1114,31 +1002,6 @@
}
}
- /**
- * Ensure that the update service does not use an uninstalled package even if it is the only
- * package available.
- */
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- // If the flag is set, we return the package even if it is not installed.
- public void testWithSingleUninstalledPackage() {
- String testPackageName = "test.package.name";
- WebViewProviderInfo[] webviewPackages = new WebViewProviderInfo[] {
- new WebViewProviderInfo(testPackageName, "",
- true /*default available*/, false /* fallback */, null)};
- setupWithPackages(webviewPackages);
- mTestSystemImpl.setPackageInfo(createPackageInfo(testPackageName, true /* enabled */,
- true /* valid */, false /* installed */));
-
- runWebViewBootPreparationOnMainSync();
-
- Mockito.verify(mTestSystemImpl, Mockito.never()).onWebViewProviderChanged(
- Matchers.anyObject());
- WebViewProviderResponse response = mWebViewUpdateServiceImpl.waitForAndGetProvider();
- assertEquals(WebViewFactory.LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES, response.status);
- assertEquals(null, mWebViewUpdateServiceImpl.getCurrentWebViewPackage());
- }
-
@Test
public void testNonhiddenPackageUserOverHidden() {
checkVisiblePackageUserOverNonVisible(false /* multiUser*/, PackageRemovalType.HIDE);
@@ -1374,95 +1237,6 @@
mWebViewUpdateServiceImpl.getCurrentWebViewPackage().versionName);
}
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- public void testMultiProcessEnabledByDefault() {
- testMultiProcessByDefault(true /* enabledByDefault */);
- }
-
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- public void testMultiProcessDisabledByDefault() {
- testMultiProcessByDefault(false /* enabledByDefault */);
- }
-
- private void testMultiProcessByDefault(boolean enabledByDefault) {
- String primaryPackage = "primary";
- WebViewProviderInfo[] packages = new WebViewProviderInfo[] {
- new WebViewProviderInfo(
- primaryPackage, "", true /* default available */, false /* fallback */, null)};
- setupWithPackagesAndMultiProcess(packages, enabledByDefault);
- mTestSystemImpl.setPackageInfo(createPackageInfo(primaryPackage, true /* enabled */,
- true /* valid */, true /* installed */, null /* signatures */,
- 10 /* lastUpdateTime*/, false /* not hidden */, 1000 /* versionCode */,
- false /* isSystemApp */));
-
- runWebViewBootPreparationOnMainSync();
- checkPreparationPhasesForPackage(primaryPackage, 1 /* first preparation phase */);
-
- // Check it's off by default
- assertEquals(enabledByDefault, mWebViewUpdateServiceImpl.isMultiProcessEnabled());
-
- // Test toggling it
- mWebViewUpdateServiceImpl.enableMultiProcess(!enabledByDefault);
- assertEquals(!enabledByDefault, mWebViewUpdateServiceImpl.isMultiProcessEnabled());
- mWebViewUpdateServiceImpl.enableMultiProcess(enabledByDefault);
- assertEquals(enabledByDefault, mWebViewUpdateServiceImpl.isMultiProcessEnabled());
- }
-
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- public void testMultiProcessEnabledByDefaultWithSettingsValue() {
- testMultiProcessByDefaultWithSettingsValue(
- true /* enabledByDefault */, Integer.MIN_VALUE, false /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- true /* enabledByDefault */, -999999, true /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- true /* enabledByDefault */, 0, true /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- true /* enabledByDefault */, 999999, true /* expectEnabled */);
- }
-
- @Test
- @RequiresFlagsDisabled("android.webkit.update_service_v2")
- public void testMultiProcessDisabledByDefaultWithSettingsValue() {
- testMultiProcessByDefaultWithSettingsValue(
- false /* enabledByDefault */, Integer.MIN_VALUE, false /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- false /* enabledByDefault */, 0, false /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- false /* enabledByDefault */, 999999, false /* expectEnabled */);
- testMultiProcessByDefaultWithSettingsValue(
- false /* enabledByDefault */, Integer.MAX_VALUE, true /* expectEnabled */);
- }
-
- /**
- * Test the logic of the multiprocess setting depending on whether multiprocess is enabled by
- * default, and what the setting is set to.
- * @param enabledByDefault whether multiprocess is enabled by default.
- * @param settingValue value of the multiprocess setting.
- */
- private void testMultiProcessByDefaultWithSettingsValue(
- boolean enabledByDefault, int settingValue, boolean expectEnabled) {
- String primaryPackage = "primary";
- WebViewProviderInfo[] packages = new WebViewProviderInfo[] {
- new WebViewProviderInfo(
- primaryPackage, "", true /* default available */, false /* fallback */, null)};
- setupWithPackagesAndMultiProcess(packages, enabledByDefault);
- mTestSystemImpl.setPackageInfo(createPackageInfo(primaryPackage, true /* enabled */,
- true /* valid */, true /* installed */, null /* signatures */,
- 10 /* lastUpdateTime*/, false /* not hidden */, 1000 /* versionCode */,
- false /* isSystemApp */));
-
- runWebViewBootPreparationOnMainSync();
- checkPreparationPhasesForPackage(primaryPackage, 1 /* first preparation phase */);
-
- mTestSystemImpl.setMultiProcessSetting(settingValue);
-
- assertEquals(expectEnabled, mWebViewUpdateServiceImpl.isMultiProcessEnabled());
- }
-
-
/**
* Ensure that packages with a targetSdkVersion targeting the current platform are valid, and
* that packages targeting an older version are not valid.
@@ -1507,7 +1281,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testDefaultWebViewPackageIsTheFirstAvailableByDefault() {
String nonDefaultPackage = "nonDefaultPackage";
String defaultPackage1 = "defaultPackage1";
@@ -1524,7 +1297,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testDefaultWebViewPackageEnabling() {
String testPackage = "testDefault";
WebViewProviderInfo[] packages =
@@ -1548,7 +1320,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testDefaultWebViewPackageInstallingDuringStartUp() {
String testPackage = "testDefault";
WebViewProviderInfo[] packages =
@@ -1572,7 +1343,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testDefaultWebViewPackageInstallingAfterStartUp() {
String testPackage = "testDefault";
WebViewProviderInfo[] packages =
@@ -1603,7 +1373,6 @@
* the repair logic.
*/
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testAddingNewUserWithDefaultdPackageNotInstalled() {
String testPackage = "testDefault";
WebViewProviderInfo[] packages =
@@ -1651,7 +1420,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testDisabledDefaultPackageChosen() {
PackageInfo disabledPackage =
createPackageInfo(
@@ -1664,7 +1432,6 @@
}
@Test
- @RequiresFlagsEnabled("android.webkit.update_service_v2")
public void testUninstalledDefaultPackageChosen() {
PackageInfo uninstalledPackage =
createPackageInfo(
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
index 6792377..0019b3e 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -6249,6 +6249,50 @@
}
@Test
+ @EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
+ public void applyGlobalZenModeAsImplicitZenRule_again_refreshesRuleName() {
+ mZenModeHelper.mConfig.automaticRules.clear();
+ mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, ZEN_MODE_IMPORTANT_INTERRUPTIONS);
+ assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ // "Break" the rule name to check that applying again restores it.
+ mZenModeHelper.mConfig.automaticRules.valueAt(0).name = "BOOM!";
+
+ mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, ZEN_MODE_ALARMS);
+
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ }
+
+ @Test
+ @EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
+ public void applyGlobalZenModeAsImplicitZenRule_again_doesNotChangeCustomizedRuleName() {
+ mZenModeHelper.mConfig.automaticRules.clear();
+ mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, ZEN_MODE_IMPORTANT_INTERRUPTIONS);
+ assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ String ruleId = ZenModeConfig.implicitRuleId(mContext.getPackageName());
+
+ // User chooses a new name.
+ AutomaticZenRule azr = mZenModeHelper.getAutomaticZenRule(UserHandle.CURRENT, ruleId);
+ mZenModeHelper.updateAutomaticZenRule(UserHandle.CURRENT, ruleId,
+ new AutomaticZenRule.Builder(azr).setName("User chose this").build(),
+ ORIGIN_USER_IN_SYSTEMUI, "reason", SYSTEM_UID);
+
+ // App triggers the rule again.
+ mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, ZEN_MODE_ALARMS);
+
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("User chose this");
+ }
+
+ @Test
@DisableFlags(FLAG_MODES_API)
public void applyGlobalZenModeAsImplicitZenRule_flagOff_ignored() {
mZenModeHelper.mConfig.automaticRules.clear();
@@ -6399,6 +6443,50 @@
}
@Test
+ @EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
+ public void applyGlobalPolicyAsImplicitZenRule_again_refreshesRuleName() {
+ mZenModeHelper.mConfig.automaticRules.clear();
+ mZenModeHelper.applyGlobalPolicyAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, new Policy(0, 0, 0));
+ assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ // "Break" the rule name to check that updating it again restores it.
+ mZenModeHelper.mConfig.automaticRules.valueAt(0).name = "BOOM!";
+
+ mZenModeHelper.applyGlobalPolicyAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, new Policy(0, 0, 0));
+
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ }
+
+ @Test
+ @EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
+ public void applyGlobalPolicyAsImplicitZenRule_again_doesNotChangeCustomizedRuleName() {
+ mZenModeHelper.mConfig.automaticRules.clear();
+ mZenModeHelper.applyGlobalPolicyAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, new Policy(0, 0, 0));
+ assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("Do Not Disturb (" + CUSTOM_APP_LABEL + ")");
+ String ruleId = ZenModeConfig.implicitRuleId(mContext.getPackageName());
+
+ // User chooses a new name.
+ AutomaticZenRule azr = mZenModeHelper.getAutomaticZenRule(UserHandle.CURRENT, ruleId);
+ mZenModeHelper.updateAutomaticZenRule(UserHandle.CURRENT, ruleId,
+ new AutomaticZenRule.Builder(azr).setName("User chose this").build(),
+ ORIGIN_USER_IN_SYSTEMUI, "reason", SYSTEM_UID);
+
+ // App updates the implicit rule again.
+ mZenModeHelper.applyGlobalPolicyAsImplicitZenRule(UserHandle.CURRENT,
+ mContext.getPackageName(), CUSTOM_PKG_UID, new Policy(0, 0, 0));
+
+ assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).name)
+ .isEqualTo("User chose this");
+ }
+
+ @Test
@DisableFlags(FLAG_MODES_API)
public void applyGlobalPolicyAsImplicitZenRule_flagOff_ignored() {
mZenModeHelper.mConfig.automaticRules.clear();
@@ -7247,9 +7335,10 @@
rule.zenMode = zenMode;
rule.zenPolicy = policy;
rule.pkg = ownerPkg;
- rule.name = CUSTOM_APP_LABEL;
- if (!Flags.modesUi()) {
- rule.iconResName = ICON_RES_NAME;
+ if (Flags.modesUi()) {
+ rule.name = mContext.getString(R.string.zen_mode_implicit_name, CUSTOM_APP_LABEL);
+ } else {
+ rule.name = CUSTOM_APP_LABEL;
}
rule.triggerDescription = mContext.getString(R.string.zen_mode_implicit_trigger_description,
CUSTOM_APP_LABEL);
diff --git a/telephony/java/android/telephony/satellite/SatelliteManager.java b/telephony/java/android/telephony/satellite/SatelliteManager.java
index c78dbe7..e332d0f 100644
--- a/telephony/java/android/telephony/satellite/SatelliteManager.java
+++ b/telephony/java/android/telephony/satellite/SatelliteManager.java
@@ -68,7 +68,6 @@
*/
@RequiresFeature(PackageManager.FEATURE_TELEPHONY_SATELLITE)
@SystemApi
-@FlaggedApi(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
public final class SatelliteManager {
private static final String TAG = "SatelliteManager";
diff --git a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
index 7e0bbc4..3828a71 100644
--- a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
+++ b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
@@ -70,6 +70,7 @@
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.Uri;
+import android.net.vcn.Flags;
import android.net.vcn.IVcnStatusCallback;
import android.net.vcn.IVcnUnderlyingNetworkPolicyListener;
import android.net.vcn.VcnConfig;
@@ -84,6 +85,7 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.os.test.TestLooper;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
@@ -102,6 +104,7 @@
import com.android.server.vcn.util.PersistableBundleUtils.PersistableBundleWrapper;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -119,6 +122,8 @@
@RunWith(AndroidJUnit4.class)
@SmallTest
public class VcnManagementServiceTest {
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private static final String CONTEXT_ATTRIBUTION_TAG = "VCN";
private static final String TEST_PACKAGE_NAME =
VcnManagementServiceTest.class.getPackage().getName();
@@ -288,6 +293,8 @@
doReturn(Collections.singleton(TRANSPORT_WIFI))
.when(mMockDeps)
.getRestrictedTransports(any(), any(), any());
+
+ mSetFlagsRule.enableFlags(Flags.FLAG_FIX_CONFIG_GARBAGE_COLLECTION);
}
@@ -438,6 +445,14 @@
return subIds;
}).when(snapshot).getAllSubIdsInGroup(any());
+ doAnswer(invocation -> {
+ final Set<ParcelUuid> subGroups = new ArraySet<>();
+ for (Entry<Integer, ParcelUuid> entry : subIdToGroupMap.entrySet()) {
+ subGroups.add(entry.getValue());
+ }
+ return subGroups;
+ }).when(snapshot).getAllSubscriptionGroups();
+
return snapshot;
}
@@ -1483,6 +1498,28 @@
}
@Test
+ public void testGarbageCollectionKeepConfigUntilNewSnapshot() throws Exception {
+ setupActiveSubscription(TEST_UUID_2);
+ startAndGetVcnInstance(TEST_UUID_2);
+
+ // Report loss of subscription from mSubMgr
+ doReturn(Collections.emptyList()).when(mSubMgr).getSubscriptionsInGroup(any());
+ triggerSubscriptionTrackerCbAndGetSnapshot(
+ TEST_UUID_2,
+ Collections.singleton(TEST_UUID_2),
+ Collections.singletonMap(TEST_SUBSCRIPTION_ID, TEST_UUID_2));
+
+ assertTrue(mVcnMgmtSvc.getConfigs().containsKey(TEST_UUID_2));
+
+ // Report loss of subscription from snapshot
+ triggerSubscriptionTrackerCbAndGetSnapshot(null, Collections.emptySet());
+
+ mTestLooper.moveTimeForward(VcnManagementService.CARRIER_PRIVILEGES_LOST_TEARDOWN_DELAY_MS);
+ mTestLooper.dispatchAll();
+ assertFalse(mVcnMgmtSvc.getConfigs().containsKey(TEST_UUID_2));
+ }
+
+ @Test
public void testVcnCarrierConfigChangeUpdatesPolicyListener() throws Exception {
setupActiveSubscription(TEST_UUID_2);
diff --git a/tools/aapt2/cmd/Command.cpp b/tools/aapt2/cmd/Command.cpp
index 514651e..449d93d 100644
--- a/tools/aapt2/cmd/Command.cpp
+++ b/tools/aapt2/cmd/Command.cpp
@@ -213,15 +213,28 @@
bool match = false;
for (Flag& flag : flags_) {
- if (arg == flag.name) {
+ // Allow both "--arg value" and "--arg=value" syntax.
+ if (arg.starts_with(flag.name) &&
+ (arg.size() == flag.name.size() || (flag.num_args > 0 && arg[flag.name.size()] == '='))) {
if (flag.num_args > 0) {
- i++;
- if (i >= args.size()) {
- *out_error << flag.name << " missing argument.\n\n";
- Usage(out_error);
- return false;
+ if (arg.size() == flag.name.size()) {
+ i++;
+ if (i >= args.size()) {
+ *out_error << flag.name << " missing argument.\n\n";
+ Usage(out_error);
+ return 1;
+ }
+ arg = args[i];
+ } else {
+ arg.remove_prefix(flag.name.size() + 1);
+ // Disallow empty arguments after '='.
+ if (arg.empty()) {
+ *out_error << flag.name << " has empty argument.\n\n";
+ Usage(out_error);
+ return 1;
+ }
}
- flag.action(args[i]);
+ flag.action(arg);
} else {
flag.action({});
}
diff --git a/tools/aapt2/cmd/Command_test.cpp b/tools/aapt2/cmd/Command_test.cpp
index 7aa1aa01..20d87e0 100644
--- a/tools/aapt2/cmd/Command_test.cpp
+++ b/tools/aapt2/cmd/Command_test.cpp
@@ -19,6 +19,7 @@
#include "test/Test.h"
using ::testing::Eq;
+using namespace std::literals;
namespace aapt {
@@ -94,4 +95,27 @@
}
#endif
+TEST(CommandTest, OptionsWithValues) {
+ TestCommand command;
+ std::string flag;
+ command.AddRequiredFlag("--flag", "", &flag);
+
+ ASSERT_EQ(0, command.Execute({"--flag"s, "1"s}, &std::cerr));
+ EXPECT_STREQ("1", flag.c_str());
+
+ ASSERT_EQ(0, command.Execute({"--flag=1"s}, &std::cerr));
+ EXPECT_STREQ("1", flag.c_str());
+
+ ASSERT_EQ(0, command.Execute({"--flag"s, "=2"s}, &std::cerr));
+ EXPECT_STREQ("=2", flag.c_str());
+
+ ASSERT_EQ(0, command.Execute({"--flag"s, "--flag"s}, &std::cerr));
+ EXPECT_STREQ("--flag", flag.c_str());
+
+ EXPECT_NE(0, command.Execute({"--flag"s}, &std::cerr));
+ EXPECT_NE(0, command.Execute({"--flag="s}, &std::cerr));
+ EXPECT_NE(0, command.Execute({"--flag1=2"s}, &std::cerr));
+ EXPECT_NE(0, command.Execute({"--flag1"s, "2"s}, &std::cerr));
+}
+
} // namespace aapt
\ No newline at end of file
diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp
index 52372fa..a5e18d35 100644
--- a/tools/aapt2/cmd/Compile.cpp
+++ b/tools/aapt2/cmd/Compile.cpp
@@ -605,8 +605,9 @@
}
// Write the crunched PNG.
- if (!android::WritePng(image.get(), nine_patch.get(), &crunched_png_buffer_out, {},
- &source_diag, context->IsVerbose())) {
+ if (!android::WritePng(image.get(), nine_patch.get(), &crunched_png_buffer_out,
+ {.compression_level = options.png_compression_level_int}, &source_diag,
+ context->IsVerbose())) {
return false;
}
@@ -924,6 +925,19 @@
}
}
+ if (!options_.png_compression_level) {
+ options_.png_compression_level_int = 9;
+ } else {
+ if (options_.png_compression_level->size() != 1 ||
+ options_.png_compression_level->front() < '0' ||
+ options_.png_compression_level->front() > '9') {
+ context.GetDiagnostics()->Error(
+ android::DiagMessage() << "PNG compression level should be a number in [0..9] range");
+ return 1;
+ }
+ options_.png_compression_level_int = options_.png_compression_level->front() - '0';
+ }
+
return Compile(&context, file_collection.get(), archive_writer.get(), options_);
}
diff --git a/tools/aapt2/cmd/Compile.h b/tools/aapt2/cmd/Compile.h
index 70c8791..e244546 100644
--- a/tools/aapt2/cmd/Compile.h
+++ b/tools/aapt2/cmd/Compile.h
@@ -47,6 +47,8 @@
bool verbose = false;
std::optional<std::string> product_;
FeatureFlagValues feature_flag_values;
+ std::optional<std::string> png_compression_level;
+ int png_compression_level_int = 9;
};
/** Parses flags and compiles resources to be used in linking. */
@@ -65,6 +67,9 @@
AddOptionalSwitch("--pseudo-localize", "Generate resources for pseudo-locales "
"(en-XA and ar-XB)", &options_.pseudolocalize);
AddOptionalSwitch("--no-crunch", "Disables PNG processing", &options_.no_png_crunch);
+ AddOptionalFlag("--png-compression-level",
+ "Set the zlib compression level for crunched PNG images, [0-9], 9 by default.",
+ &options_.png_compression_level);
AddOptionalSwitch("--legacy", "Treat errors that used to be valid in AAPT as warnings",
&options_.legacy_mode);
AddOptionalSwitch("--preserve-visibility-of-styleables",