Merge "[Screen share] Add CTS AudioPlaybackCaptureTest to presubmit." into main
diff --git a/PERFORMANCE_OWNERS b/PERFORMANCE_OWNERS
index 48a0201..02b0a1e 100644
--- a/PERFORMANCE_OWNERS
+++ b/PERFORMANCE_OWNERS
@@ -6,3 +6,4 @@
shayba@google.com
jdduke@google.com
shombert@google.com
+kevinjeon@google.com
diff --git a/Ravenwood.bp b/Ravenwood.bp
index cebeb18..7faa33f 100644
--- a/Ravenwood.bp
+++ b/Ravenwood.bp
@@ -26,24 +26,13 @@
}
// Generate the stub/impl from framework-all, with hidden APIs.
-java_genrule {
- name: "framework-minus-apex.ravenwood-base",
+// This step takes several tens of seconds, so we manually shard it to multiple modules.
+// All the copies have to be kept in sync.
+// TODO: Do the sharding better.
+
+genrule_defaults {
+ name: "framework-minus-apex.ravenwood-base_defaults",
tools: ["hoststubgen"],
- cmd: "$(location hoststubgen) " +
- "@$(location :ravenwood-standard-options) " +
-
- "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
- "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
- "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
-
- "--out-impl-jar $(location ravenwood.jar) " +
-
- "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
- "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
-
- "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
- "--policy-override-file $(location :ravenwood-framework-policies) " +
- "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
srcs: [
":framework-minus-apex-for-hoststubgen",
":ravenwood-framework-policies",
@@ -61,24 +50,221 @@
"hoststubgen_framework-minus-apex_stats.csv",
"hoststubgen_framework-minus-apex_apis.csv",
],
- defaults: ["ravenwood-internal-only-visibility-genrule"],
+ visibility: ["//visibility:private"],
}
-// Extract the impl jar from "framework-minus-apex.ravenwood-base" for subsequent build rules.
-// Note this emits a "device side" output, so that ravenwood tests can (implicitly)
-// depend on it.
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X0",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 0 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X1",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 1 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X2",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 2 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X3",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 3 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X4",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 4 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+java_genrule {
+ name: "framework-minus-apex.ravenwood-base_X5",
+ defaults: ["framework-minus-apex.ravenwood-base_defaults"],
+ cmd: "$(location hoststubgen) " +
+ "--num-shards 6 --shard-index 5 " + // Only this line differs
+
+ "@$(location :ravenwood-standard-options) " +
+
+ "--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
+ "--supported-api-list-file $(location hoststubgen_framework-minus-apex_apis.csv) " +
+
+ "--out-impl-jar $(location ravenwood.jar) " +
+
+ "--gen-keep-all-file $(location hoststubgen_framework-minus-apex_keep_all.txt) " +
+ "--gen-input-dump-file $(location hoststubgen_framework-minus-apex_dump.txt) " +
+
+ "--in-jar $(location :framework-minus-apex-for-hoststubgen) " +
+ "--policy-override-file $(location :ravenwood-framework-policies) " +
+ "--annotation-allowed-classes-file $(location :ravenwood-annotation-allowed-classes) ",
+}
+
+// Marge all the sharded jars
java_genrule {
name: "framework-minus-apex.ravenwood",
- defaults: ["ravenwood-internal-only-visibility-genrule"],
- cmd: "cp $(in) $(out)",
+ defaults: ["ravenwood-internal-only-visibility-java"],
+ cmd: "$(location merge_zips) $(out) $(in)",
+ tools: ["merge_zips"],
srcs: [
- ":framework-minus-apex.ravenwood-base{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X0{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X1{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X2{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X3{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X4{ravenwood.jar}",
+ ":framework-minus-apex.ravenwood-base_X5{ravenwood.jar}",
],
out: [
"framework-minus-apex.ravenwood.jar",
],
}
+// Merge the sharded text files
+genrule {
+ name: "hoststubgen_framework-minus-apex_stats.csv",
+ defaults: ["ravenwood-internal-only-visibility-genrule"],
+ cmd: "cat $(in) > $(out)",
+ srcs: [
+ ":framework-minus-apex.ravenwood-base_X0{hoststubgen_framework-minus-apex_stats.csv}",
+ ":framework-minus-apex.ravenwood-base_X1{hoststubgen_framework-minus-apex_stats.csv}",
+ ":framework-minus-apex.ravenwood-base_X2{hoststubgen_framework-minus-apex_stats.csv}",
+ ":framework-minus-apex.ravenwood-base_X3{hoststubgen_framework-minus-apex_stats.csv}",
+ ":framework-minus-apex.ravenwood-base_X4{hoststubgen_framework-minus-apex_stats.csv}",
+ ":framework-minus-apex.ravenwood-base_X5{hoststubgen_framework-minus-apex_stats.csv}",
+ ],
+ out: ["hoststubgen_framework-minus-apex_stats.csv"],
+}
+
+genrule {
+ name: "hoststubgen_framework-minus-apex_apis.csv",
+ defaults: ["ravenwood-internal-only-visibility-genrule"],
+ cmd: "cat $(in) > $(out)",
+ srcs: [
+ ":framework-minus-apex.ravenwood-base_X0{hoststubgen_framework-minus-apex_apis.csv}",
+ ":framework-minus-apex.ravenwood-base_X1{hoststubgen_framework-minus-apex_apis.csv}",
+ ":framework-minus-apex.ravenwood-base_X2{hoststubgen_framework-minus-apex_apis.csv}",
+ ":framework-minus-apex.ravenwood-base_X3{hoststubgen_framework-minus-apex_apis.csv}",
+ ":framework-minus-apex.ravenwood-base_X4{hoststubgen_framework-minus-apex_apis.csv}",
+ ":framework-minus-apex.ravenwood-base_X5{hoststubgen_framework-minus-apex_apis.csv}",
+ ],
+ out: ["hoststubgen_framework-minus-apex_apis.csv"],
+}
+
+genrule {
+ name: "hoststubgen_framework-minus-apex_keep_all.txt",
+ defaults: ["ravenwood-internal-only-visibility-genrule"],
+ cmd: "cat $(in) > $(out)",
+ srcs: [
+ ":framework-minus-apex.ravenwood-base_X0{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ":framework-minus-apex.ravenwood-base_X1{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ":framework-minus-apex.ravenwood-base_X2{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ":framework-minus-apex.ravenwood-base_X3{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ":framework-minus-apex.ravenwood-base_X4{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ":framework-minus-apex.ravenwood-base_X5{hoststubgen_framework-minus-apex_keep_all.txt}",
+ ],
+ out: ["hoststubgen_framework-minus-apex_keep_all.txt"],
+}
+
+genrule {
+ name: "hoststubgen_framework-minus-apex_dump.txt",
+ defaults: ["ravenwood-internal-only-visibility-genrule"],
+ cmd: "cat $(in) > $(out)",
+ srcs: [
+ ":framework-minus-apex.ravenwood-base_X0{hoststubgen_framework-minus-apex_dump.txt}",
+ ":framework-minus-apex.ravenwood-base_X1{hoststubgen_framework-minus-apex_dump.txt}",
+ ":framework-minus-apex.ravenwood-base_X2{hoststubgen_framework-minus-apex_dump.txt}",
+ ":framework-minus-apex.ravenwood-base_X3{hoststubgen_framework-minus-apex_dump.txt}",
+ ":framework-minus-apex.ravenwood-base_X4{hoststubgen_framework-minus-apex_dump.txt}",
+ ":framework-minus-apex.ravenwood-base_X5{hoststubgen_framework-minus-apex_dump.txt}",
+ ],
+ out: ["hoststubgen_framework-minus-apex_dump.txt"],
+}
+
java_library {
name: "services.core-for-hoststubgen",
installable: false, // host only jar.
diff --git a/ZYGOTE_OWNERS b/ZYGOTE_OWNERS
index f6d15e0..6918c16 100644
--- a/ZYGOTE_OWNERS
+++ b/ZYGOTE_OWNERS
@@ -1,4 +1,4 @@
chriswailes@google.com
+hboehm@google.com
maco@google.com
-narayan@google.com
ngeoffray@google.com
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp
index f264125..6902d6d 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.cpp
+++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp
@@ -78,6 +78,11 @@
namespace android::os {
+template <typename T>
+const T* Idmap2Service::GetPointer(const OwningPtr<T>& ptr) {
+ return std::visit([](auto&& ptr) { return ptr.get(); }, ptr);
+}
+
Status Idmap2Service::getIdmapPath(const std::string& overlay_path,
int32_t user_id ATTRIBUTE_UNUSED, std::string* _aidl_return) {
assert(_aidl_return);
@@ -224,7 +229,7 @@
if (is_framework ||
(item.dev == st.st_dev && item.inode == st.st_ino && item.size == st.st_size
&& item.mtime.tv_sec == st.st_mtim.tv_sec && item.mtime.tv_nsec == st.st_mtim.tv_nsec)) {
- return {item.apk.get()};
+ return {item.apk};
}
container_cache_.erase(cache_it);
}
@@ -238,14 +243,14 @@
return {std::move(*target)};
}
- const auto res = target->get();
+ auto res = std::shared_ptr(std::move(*target));
std::lock_guard lock(container_cache_mutex_);
container_cache_.emplace(target_path, CachedContainer {
.dev = dev_t(st.st_dev),
.inode = ino_t(st.st_ino),
.size = st.st_size,
.mtime = st.st_mtim,
- .apk = std::move(*target)
+ .apk = res
});
return {res};
}
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.h b/cmds/idmap2/idmap2d/Idmap2Service.h
index a69fa61..272ec6b 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.h
+++ b/cmds/idmap2/idmap2d/Idmap2Service.h
@@ -85,7 +85,7 @@
ino_t inode;
int64_t size;
struct timespec mtime;
- std::unique_ptr<idmap2::TargetResourceContainer> apk;
+ std::shared_ptr<idmap2::TargetResourceContainer> apk;
};
std::unordered_map<std::string, CachedContainer> container_cache_;
std::mutex container_cache_mutex_;
@@ -95,24 +95,15 @@
std::mutex frro_iter_mutex_;
template <typename T>
- using MaybeUniquePtr = std::variant<std::unique_ptr<T>, T*>;
+ using OwningPtr = std::variant<std::unique_ptr<T>, std::shared_ptr<T>>;
- using TargetResourceContainerPtr = MaybeUniquePtr<idmap2::TargetResourceContainer>;
+ using TargetResourceContainerPtr = OwningPtr<idmap2::TargetResourceContainer>;
idmap2::Result<TargetResourceContainerPtr> GetTargetContainer(const std::string& target_path);
template <typename T>
- WARN_UNUSED static const T* GetPointer(const MaybeUniquePtr<T>& ptr);
+ WARN_UNUSED static const T* GetPointer(const OwningPtr<T>& ptr);
};
-template <typename T>
-const T* Idmap2Service::GetPointer(const MaybeUniquePtr<T>& ptr) {
- auto u = std::get_if<T*>(&ptr);
- if (u != nullptr) {
- return *u;
- }
- return std::get<std::unique_ptr<T>>(ptr).get();
-}
-
} // namespace android::os
#endif // IDMAP2_IDMAP2D_IDMAP2SERVICE_H_
diff --git a/config/preloaded-classes-denylist b/config/preloaded-classes-denylist
index dd2569a..a413bbd 100644
--- a/config/preloaded-classes-denylist
+++ b/config/preloaded-classes-denylist
@@ -1,23 +1,13 @@
android.content.AsyncTaskLoader$LoadTask
-android.media.MediaCodecInfo$CodecCapabilities$FeatureList
-android.media.MediaCodecInfo$LazyHolder
android.net.ConnectivityThread$Singleton
+android.os.FileObserver
+android.os.NullVibrator
+android.speech.tts.TextToSpeech$Connection$SetupConnectionAsyncTask
+android.widget.Magnifier
+gov.nist.core.net.DefaultNetworkLayer
android.net.rtp.AudioGroup
android.net.rtp.AudioStream
android.net.rtp.RtpStream
-android.os.FileObserver
-android.os.NullVibrator
-android.permission.PermissionManager
-android.provider.MediaStore
-android.speech.tts.TextToSpeech$Connection$SetupConnectionAsyncTask
-android.view.HdrRenderState
-android.text.TextFlags
-android.widget.Magnifier
-com.android.internal.jank.InteractionJankMonitor$InstanceHolder
-com.android.internal.os.BinderCallsStats$SettingsObserver
-com.android.internal.util.LatencyTracker$SLatencyTrackerHolder
-com.android.server.BootReceiver$2
-gov.nist.core.net.DefaultNetworkLayer
-java.util.ImmutableCollections
java.util.concurrent.ThreadLocalRandom
-sun.nio.fs.UnixChannelFactory
+java.util.ImmutableCollections
+com.android.internal.jank.InteractionJankMonitor$InstanceHolder
diff --git a/core/java/android/content/pm/multiuser.aconfig b/core/java/android/content/pm/multiuser.aconfig
index 835459e..e370e85 100644
--- a/core/java/android/content/pm/multiuser.aconfig
+++ b/core/java/android/content/pm/multiuser.aconfig
@@ -381,8 +381,9 @@
}
flag {
- name: "unicorn_mode_refactoring_for_hsum"
+ name: "unicorn_mode_refactoring_for_hsum_read_only"
namespace: "multiuser"
- description: "Refactorings related to unicorn mode to work on HSUM mode"
+ description: "Refactorings related to unicorn mode to work on HSUM mode (Read only flag)"
bug: "339201286"
-}
+ is_fixed_read_only: true
+}
\ No newline at end of file
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index 7f3c49d..1e7f70b 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -918,7 +918,7 @@
checkIfCameraClosedOrInError();
for (String physicalId : physicalCameraIdSet) {
- if (physicalId == getId()) {
+ if (Objects.equals(physicalId, getId())) {
throw new IllegalStateException("Physical id matches the logical id!");
}
}
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index 00ce949..e79b8f3 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -2796,6 +2796,9 @@
* <p>This dismisses the {@link #getStylusHandwritingWindow ink window} and stops intercepting
* stylus {@code MotionEvent}s.
*
+ * <p>Connectionless handwriting sessions should be finished using {@link
+ * #finishConnectionlessStylusHandwriting(CharSequence)}.
+ *
* <p>Note for IME developers: Call this method at any time to finish the current handwriting
* session. Generally, this should be invoked after a short timeout, giving the user enough time
* to start the next stylus stroke, if any. By default, system will time-out after few seconds.
@@ -2803,9 +2806,6 @@
*
* <p>Handwriting session will be finished by framework on next {@link #onFinishInput()}.
*/
- // TODO(b/300979854): Once connectionless APIs are finalised, update documentation to add:
- // <p>Connectionless handwriting sessions should be finished using {@link
- // #finishConnectionlessStylusHandwriting(CharSequence)}.
public final void finishStylusHandwriting() {
if (DEBUG) Log.v(TAG, "finishStylusHandwriting()");
if (mInkWindow == null) {
diff --git a/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java b/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java
index 540243c..bfa95f7 100644
--- a/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java
+++ b/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java
@@ -22,6 +22,7 @@
import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK;
import static android.view.accessibility.AccessibilityNodeInfo.ACTION_LONG_CLICK;
+import android.annotation.Nullable;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
@@ -126,15 +127,29 @@
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
- if (mCode != KEYCODE_UNKNOWN) {
+ if (isClickable()) {
info.addAction(new AccessibilityNodeInfo.AccessibilityAction(ACTION_CLICK, null));
if (isLongClickable()) {
info.addAction(
- new AccessibilityNodeInfo.AccessibilityAction(ACTION_LONG_CLICK, null));
+ new AccessibilityNodeInfo.AccessibilityAction(ACTION_LONG_CLICK,
+ getAccessibilityLongClickActionLabel()));
}
}
}
+ /**
+ * Gets the accessibility long click action label for the button, or {@code null} for no label.
+ */
+ @Nullable
+ private CharSequence getAccessibilityLongClickActionLabel() {
+ if (Flags.imeSwitcherRevamp()
+ && getId() == com.android.internal.R.id.input_method_nav_ime_switcher) {
+ return getContext().getText(
+ com.android.internal.R.string.input_method_ime_switch_long_click_action_desc);
+ }
+ return null;
+ }
+
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
diff --git a/core/java/android/os/vibrator/flags.aconfig b/core/java/android/os/vibrator/flags.aconfig
index 40dd91f..3fad8dd 100644
--- a/core/java/android/os/vibrator/flags.aconfig
+++ b/core/java/android/os/vibrator/flags.aconfig
@@ -20,13 +20,6 @@
flag {
namespace: "haptics"
- name: "keyboard_category_enabled"
- description: "Enables the independent keyboard vibration settings feature"
- bug: "289107579"
-}
-
-flag {
- namespace: "haptics"
name: "adaptive_haptics_enabled"
description: "Enables the adaptive haptics feature"
bug: "305961689"
diff --git a/core/java/android/service/notification/DeviceEffectsApplier.java b/core/java/android/service/notification/DeviceEffectsApplier.java
index 5194cdd..2472860 100644
--- a/core/java/android/service/notification/DeviceEffectsApplier.java
+++ b/core/java/android/service/notification/DeviceEffectsApplier.java
@@ -16,8 +16,6 @@
package android.service.notification;
-import android.service.notification.ZenModeConfig.ConfigChangeOrigin;
-
/**
* Responsible for making any service calls needed to apply the set of {@link ZenDeviceEffects} that
* make sense for the current platform.
@@ -43,5 +41,5 @@
* changing as a result of an explicit user action, then it makes sense to
* apply them immediately regardless.
*/
- void apply(ZenDeviceEffects effects, @ConfigChangeOrigin int source);
+ void apply(ZenDeviceEffects effects, @ZenModeConfig.ConfigOrigin int source);
}
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index 7ca248d..5e15e01 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -112,68 +112,83 @@
private static final String TAG = "ZenModeConfig";
/**
- * The {@link ZenModeConfig} is being updated because of an unknown reason.
+ * The {@link ZenModeConfig} is updated because of an unknown reason.
*/
- public static final int UPDATE_ORIGIN_UNKNOWN = 0;
+ public static final int ORIGIN_UNKNOWN = 0;
/**
- * The {@link ZenModeConfig} is being updated because of system initialization (i.e. load from
+ * The {@link ZenModeConfig} is updated because of system initialization (i.e. load from
* storage, on device boot).
*/
- public static final int UPDATE_ORIGIN_INIT = 1;
+ public static final int ORIGIN_INIT = 1;
- /** The {@link ZenModeConfig} is being updated (replaced) because of a user switch or unlock. */
- public static final int UPDATE_ORIGIN_INIT_USER = 2;
+ /** The {@link ZenModeConfig} is updated (replaced) because of a user switch or unlock. */
+ public static final int ORIGIN_INIT_USER = 2;
- /** The {@link ZenModeConfig} is being updated because of a user action, for example:
+ /**
+ * The {@link ZenModeConfig} is updated because of a <em>user action</em> performed from a
+ * system surface, such as:
* <ul>
- * <li>{@link NotificationManager#setAutomaticZenRuleState} with a
- * {@link Condition#source} equal to {@link Condition#SOURCE_USER_ACTION}.</li>
- * <li>Adding, updating, or removing a rule from Settings.</li>
- * <li>Directly activating or deactivating/snoozing a rule through some UI affordance (e.g.
- * Quick Settings).</li>
+ * <li>Adding, updating, or removing a rule from Settings.
+ * <li>Activating or deactivating a rule through the System (e.g. from Settings/Modes).
+ * <li>Activating or deactivating a rule through SystemUi (e.g. with Quick Settings).
* </ul>
+ *
+ * <p>This does <em>not</em> include user actions from apps ({@link #ORIGIN_USER_IN_APP} nor
+ * non-user actions from the system ({@link #ORIGIN_SYSTEM}).
*/
- public static final int UPDATE_ORIGIN_USER = 3;
+ public static final int ORIGIN_USER_IN_SYSTEMUI = 3;
/**
- * The {@link ZenModeConfig} is being "independently" updated by an app, and not as a result of
- * a user's action inside that app (for example, activating an {@link AutomaticZenRule} based on
- * a previously set schedule).
+ * The {@link ZenModeConfig} is updated by an app, but (probably) not as a result of a user
+ * action (for example, activating an {@link AutomaticZenRule} based on a previously set
+ * schedule).
+ *
+ * <p>Note that {@code ORIGIN_APP} is the only option for all public APIs except
+ * {@link NotificationManager#setAutomaticZenRuleState} -- apps cannot claim to be adding or
+ * updating a rule on behalf of the user.
*/
- public static final int UPDATE_ORIGIN_APP = 4;
+ public static final int ORIGIN_APP = 4;
/**
- * The {@link ZenModeConfig} is being updated by the System or SystemUI. Note that this only
- * includes cases where the call is coming from the System/SystemUI but the change is not due to
- * a user action (e.g. automatically activating a schedule-based rule). If the change is a
- * result of a user action (e.g. activating a rule by tapping on its QS tile) then
- * {@link #UPDATE_ORIGIN_USER} is used instead.
+ * The {@link ZenModeConfig} is updated by the System (or SystemUI). This only includes cases
+ * where the call is coming from the System/SystemUI but the change is not due to a user action
+ * (e.g. automatically activating a schedule-based rule, or some service toggling Do Not
+ * Disturb). See {@link #ORIGIN_USER_IN_SYSTEMUI}.
*/
- public static final int UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI = 5;
+ public static final int ORIGIN_SYSTEM = 5;
/**
* The {@link ZenModeConfig} is being updated (replaced) because the user's DND configuration
* is being restored from a backup.
*/
- public static final int UPDATE_ORIGIN_RESTORE_BACKUP = 6;
+ public static final int ORIGIN_RESTORE_BACKUP = 6;
- @IntDef(prefix = { "UPDATE_ORIGIN_" }, value = {
- UPDATE_ORIGIN_UNKNOWN,
- UPDATE_ORIGIN_INIT,
- UPDATE_ORIGIN_INIT_USER,
- UPDATE_ORIGIN_USER,
- UPDATE_ORIGIN_APP,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- UPDATE_ORIGIN_RESTORE_BACKUP
+ /**
+ * The {@link ZenModeConfig} is updated from an app, and the app reports it's the result
+ * of a user action (e.g. tapping a button in the Wellbeing App to start Bedtime Mode).
+ * Corresponds to {@link NotificationManager#setAutomaticZenRuleState} with a
+ * {@link Condition#source} equal to {@link Condition#SOURCE_USER_ACTION}.</li>
+ */
+ public static final int ORIGIN_USER_IN_APP = 7;
+
+ @IntDef(prefix = { "ORIGIN_" }, value = {
+ ORIGIN_UNKNOWN,
+ ORIGIN_INIT,
+ ORIGIN_INIT_USER,
+ ORIGIN_USER_IN_SYSTEMUI,
+ ORIGIN_APP,
+ ORIGIN_SYSTEM,
+ ORIGIN_RESTORE_BACKUP,
+ ORIGIN_USER_IN_APP
})
@Retention(RetentionPolicy.SOURCE)
- public @interface ConfigChangeOrigin {}
+ public @interface ConfigOrigin {}
public static final int SOURCE_ANYONE = Policy.PRIORITY_SENDERS_ANY;
public static final int SOURCE_CONTACT = Policy.PRIORITY_SENDERS_CONTACTS;
public static final int SOURCE_STAR = Policy.PRIORITY_SENDERS_STARRED;
- public static final int MAX_SOURCE = SOURCE_STAR;
+ private static final int MAX_SOURCE = SOURCE_STAR;
private static final int DEFAULT_SOURCE = SOURCE_STAR;
private static final int DEFAULT_CALLS_SOURCE = SOURCE_STAR;
@@ -1174,7 +1189,7 @@
}
if (Flags.modesUi()) {
rt.disabledOrigin = safeInt(parser, RULE_ATT_DISABLED_ORIGIN,
- UPDATE_ORIGIN_UNKNOWN);
+ ORIGIN_UNKNOWN);
rt.legacySuppressedEffects = safeInt(parser,
RULE_ATT_LEGACY_SUPPRESSED_EFFECTS, 0);
}
@@ -2537,7 +2552,8 @@
@ZenDeviceEffects.ModifiableField public int zenDeviceEffectsUserModifiedFields;
@Nullable public Instant deletionInstant; // Only set on deleted rules.
@FlaggedApi(Flags.FLAG_MODES_UI)
- @ConfigChangeOrigin public int disabledOrigin = UPDATE_ORIGIN_UNKNOWN;
+ @ConfigOrigin
+ public int disabledOrigin = ORIGIN_UNKNOWN;
// The obsolete suppressed effects in NM.Policy (SCREEN_ON, SCREEN_OFF) cannot be put in a
// ZenPolicy, so we store them here, only for the manual rule.
@FlaggedApi(Flags.FLAG_MODES_UI)
diff --git a/core/java/android/view/HapticScrollFeedbackProvider.java b/core/java/android/view/HapticScrollFeedbackProvider.java
index 6b354a0..f370256 100644
--- a/core/java/android/view/HapticScrollFeedbackProvider.java
+++ b/core/java/android/view/HapticScrollFeedbackProvider.java
@@ -135,15 +135,16 @@
private void maybeUpdateCurrentConfig(int deviceId, int source, int axis) {
if (mAxis != axis || mSource != source || mDeviceId != deviceId) {
+ mSource = source;
+ mAxis = axis;
+ mDeviceId = deviceId;
+
if (mDisabledIfViewPlaysScrollHaptics
&& (source == InputDevice.SOURCE_ROTARY_ENCODER)
&& mViewConfig.isViewBasedRotaryEncoderHapticScrollFeedbackEnabled()) {
mHapticScrollFeedbackEnabled = false;
return;
}
- mSource = source;
- mAxis = axis;
- mDeviceId = deviceId;
mHapticScrollFeedbackEnabled =
mViewConfig.isHapticScrollFeedbackEnabled(deviceId, axis, source);
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 4ab6758..b281015 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -2887,6 +2887,11 @@
* initiation delegation was previously requested using
* {@link #prepareStylusHandwritingDelegation(View)} from the delegator.
*
+ * <p>Otherwise, if the delegator view previously started delegation using {@link
+ * #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, Executor,
+ * ConnectionlessHandwritingCallback)}, requests the IME to commit the recognised handwritten
+ * text from the connectionless session to the delegate view.
+ *
* <p>Note: If delegator and delegate are in different application packages, use
* {@link #acceptStylusHandwritingDelegation(View, String)} instead.</p>
*
@@ -2895,14 +2900,9 @@
* {@link #prepareStylusHandwritingDelegation(View)} and delegation is accepted
* @see #prepareStylusHandwritingDelegation(View)
* @see #acceptStylusHandwritingDelegation(View, String)
+ * @see #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, Executor,
+ * ConnectionlessHandwritingCallback)
*/
- // TODO(b/300979854): Once connectionless APIs are finalised, update documentation to add:
- // <p>Otherwise, if the delegator view previously started delegation using {@link
- // #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver, CursorAnchorInfo)},
- // requests the IME to commit the recognised handwritten text from the connectionless session to
- // the delegate view.
- // @see #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver,
- // CursorAnchorInfo)
public boolean acceptStylusHandwritingDelegation(@NonNull View delegateView) {
return startStylusHandwritingInternal(
delegateView, delegateView.getContext().getOpPackageName(),
@@ -2915,6 +2915,11 @@
* {@link #prepareStylusHandwritingDelegation(View, String)} from the delegator and the view
* belongs to a specified delegate package.
*
+ * <p>Otherwise, if the delegator view previously started delegation using {@link
+ * #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String, Executor,
+ * ConnectionlessHandwritingCallback)}, requests the IME to commit the recognised handwritten
+ * text from the connectionless session to the delegate view.
+ *
* <p>Note: If delegator and delegate are in the same application package, use
* {@link #acceptStylusHandwritingDelegation(View)} instead.</p>
*
@@ -2924,15 +2929,10 @@
* #prepareStylusHandwritingDelegation(View, String)} and delegation is accepted
* @see #prepareStylusHandwritingDelegation(View, String)
* @see #acceptStylusHandwritingDelegation(View)
+ * @see #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String,
+ * Executor, ConnectionlessHandwritingCallback)
* TODO (b/293640003): deprecate this method once flag is enabled.
*/
- // TODO(b/300979854): Once connectionless APIs are finalised, update documentation to add:
- // <p>Otherwise, if the delegator view previously started delegation using {@link
- // #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver, CursorAnchorInfo,
- // String)}, requests the IME to commit the recognised handwritten text from the connectionless
- // session to the delegate view.
- // @see #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver,
- // CursorAnchorInfo, String)
public boolean acceptStylusHandwritingDelegation(
@NonNull View delegateView, @NonNull String delegatorPackageName) {
Objects.requireNonNull(delegatorPackageName);
@@ -2946,6 +2946,11 @@
* {@link #prepareStylusHandwritingDelegation(View, String)} from the delegator and the view
* belongs to a specified delegate package.
*
+ * <p>Otherwise, if the delegator view previously started delegation using {@link
+ * #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String, Executor,
+ * ConnectionlessHandwritingCallback)}, requests the IME to commit the recognised handwritten
+ * text from the connectionless session to the delegate view.
+ *
* @param delegateView delegate view capable of receiving input via {@link InputConnection}
* on which {@link #startStylusHandwriting(View)} will be called.
* @param delegatorPackageName package name of the delegator that handled initial stylus stroke.
@@ -2957,6 +2962,8 @@
* The framework only holds a weak reference.
* @see #prepareStylusHandwritingDelegation(View, String)
* @see #acceptStylusHandwritingDelegation(View)
+ * @see #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String,
+ * Executor, ConnectionlessHandwritingCallback)
*/
@FlaggedApi(Flags.FLAG_USE_ZERO_JANK_PROXY)
public void acceptStylusHandwritingDelegation(
@@ -2977,6 +2984,11 @@
* #prepareStylusHandwritingDelegation(View, String)} from the delegator and the view belongs to
* a specified delegate package.
*
+ * <p>Otherwise, if the delegator view previously started delegation using {@link
+ * #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String, Executor,
+ * ConnectionlessHandwritingCallback)}, requests the IME to commit the recognised handwritten
+ * text from the connectionless session to the delegate view.
+ *
* <p>Note: If delegator and delegate are in the same application package, use {@link
* #acceptStylusHandwritingDelegation(View)} instead.
*
@@ -2988,15 +3000,9 @@
* hold a reference to the callback. The framework only holds a weak reference.
* @see #prepareStylusHandwritingDelegation(View, String)
* @see #acceptStylusHandwritingDelegation(View)
+ * @see #startConnectionlessStylusHandwritingForDelegation(View, CursorAnchorInfo, String,
+ * Executor, ConnectionlessHandwritingCallback)
*/
- // TODO(b/300979854): Once connectionless APIs are finalised, update documentation to add:
- // <p>Otherwise, if the delegator view previously started delegation using {@link
- // #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver, CursorAnchorInfo,
- // String)}, requests the IME to commit the recognised handwritten text from the connectionless
- // session to the delegate view.
- // @see #startConnectionlessStylusHandwritingForDelegation(View, ResultReceiver,
- // CursorAnchorInfo, String)
- //
@FlaggedApi(FLAG_HOME_SCREEN_HANDWRITING_DELEGATOR)
public void acceptStylusHandwritingDelegation(
@NonNull View delegateView, @NonNull String delegatorPackageName,
diff --git a/core/res/res/layout/input_method_switch_dialog_new.xml b/core/res/res/layout/input_method_switch_dialog_new.xml
index 5a4d6b1..6bb969b 100644
--- a/core/res/res/layout/input_method_switch_dialog_new.xml
+++ b/core/res/res/layout/input_method_switch_dialog_new.xml
@@ -51,7 +51,8 @@
<Space
android:layout_width="0dp"
android:layout_height="wrap_content"
- android:layout_weight="1"/>
+ android:layout_weight="1"
+ android:importantForAccessibility="no"/>
<Button
style="?attr/buttonBarButtonStyle"
diff --git a/core/res/res/layout/input_method_switch_item_new.xml b/core/res/res/layout/input_method_switch_item_new.xml
index 16a97c4..09ed650 100644
--- a/core/res/res/layout/input_method_switch_item_new.xml
+++ b/core/res/res/layout/input_method_switch_item_new.xml
@@ -31,7 +31,8 @@
android:layout_marginTop="8dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="12dp"
- android:visibility="gone"/>
+ android:visibility="gone"
+ android:importantForAccessibility="no"/>
<TextView
android:id="@+id/header_text"
@@ -81,7 +82,8 @@
android:layout_marginStart="12dp"
android:src="@drawable/ic_check_24dp"
android:tint="?attr/materialColorOnSurface"
- android:visibility="gone"/>
+ android:visibility="gone"
+ android:importantForAccessibility="no"/>
</LinearLayout>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 9104379..cb58339 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -3277,6 +3277,9 @@
<string name="input_method_nav_back_button_desc">Back</string>
<!-- Content description of the switch input method button for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
<string name="input_method_ime_switch_button_desc">Switch input method</string>
+ <!-- Accessibility text for the long click action on the switch input method button. This will
+ be used following "Double-tap and hold to..." [CHAR LIMIT=NONE] -->
+ <string name="input_method_ime_switch_long_click_action_desc">Open input method picker</string>
<!-- If the device is getting low on internal storage, a notification is shown to the user. This is the title of that notification. -->
<string name="low_internal_storage_view_title">Storage space running out</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 8f4018f..bdcba9d 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2245,6 +2245,7 @@
<java-symbol type="string" name="heavy_weight_notification_detail" />
<java-symbol type="string" name="image_wallpaper_component" />
<java-symbol type="string" name="input_method_binding_label" />
+ <java-symbol type="string" name="input_method_ime_switch_long_click_action_desc" />
<java-symbol type="string" name="launch_warning_original" />
<java-symbol type="string" name="launch_warning_replace" />
<java-symbol type="string" name="launch_warning_title" />
diff --git a/core/tests/coretests/src/android/view/HapticScrollFeedbackProviderTest.java b/core/tests/coretests/src/android/view/HapticScrollFeedbackProviderTest.java
index 3dfeb7f..b9a9557 100644
--- a/core/tests/coretests/src/android/view/HapticScrollFeedbackProviderTest.java
+++ b/core/tests/coretests/src/android/view/HapticScrollFeedbackProviderTest.java
@@ -428,6 +428,35 @@
assertFeedbackCount(mView, HapticFeedbackConstants.SCROLL_LIMIT, 1);
}
+ @Test
+ public void testNonRotaryInputFeedbackNotBlockedByRotaryUnavailability() {
+ when(mMockViewConfig.isViewBasedRotaryEncoderHapticScrollFeedbackEnabled())
+ .thenReturn(true);
+ setHapticScrollFeedbackEnabled(true);
+ setHapticScrollTickInterval(5);
+ mProvider = new HapticScrollFeedbackProvider(mView, mMockViewConfig,
+ /* disabledIfViewPlaysScrollHaptics= */ true);
+
+ // Expect one feedback here. Touch input should provide feedback since scroll feedback has
+ // been enabled via `setHapticScrollFeedbackEnabled(true)`.
+ mProvider.onScrollProgress(
+ INPUT_DEVICE_1, InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.AXIS_Y,
+ /* deltaInPixels= */ 10);
+ // Because `isViewBasedRotaryEncoderHapticScrollFeedbackEnabled()` is false and
+ // `disabledIfViewPlaysScrollHaptics` is true, the scroll progress from rotary encoders will
+ // produce no feedback.
+ mProvider.onScrollProgress(
+ INPUT_DEVICE_2, InputDevice.SOURCE_ROTARY_ENCODER, MotionEvent.AXIS_SCROLL,
+ /* deltaInPixels= */ 20);
+ // This event from the touch screen should produce feedback. The rotary encoder event's
+ // inability to not play scroll feedback should not impact this touch input.
+ mProvider.onScrollProgress(
+ INPUT_DEVICE_1, InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.AXIS_Y,
+ /* deltaInPixels= */ 30);
+
+ assertFeedbackCount(mView, HapticFeedbackConstants.SCROLL_TICK, 2);
+ }
+
private void assertNoFeedback(TestView view) {
for (int feedback : new int[] {SCROLL_ITEM_FOCUS, SCROLL_LIMIT, SCROLL_TICK}) {
diff --git a/libs/WindowManager/Shell/OWNERS b/libs/WindowManager/Shell/OWNERS
index cb422ea..2e19d52 100644
--- a/libs/WindowManager/Shell/OWNERS
+++ b/libs/WindowManager/Shell/OWNERS
@@ -1,5 +1,5 @@
xutan@google.com
# Give submodule owners in shell resource approval
-per-file res*/*/*.xml = atsjenk@google.com, hwwang@google.com, jorgegil@google.com, lbill@google.com, madym@google.com, vaniadesmonda@google.com, pbdr@google.com, tkachenkoi@google.com, mpodolian@google.com, liranb@google.com
+per-file res*/*/*.xml = atsjenk@google.com, hwwang@google.com, jorgegil@google.com, lbill@google.com, madym@google.com, vaniadesmonda@google.com, pbdr@google.com, tkachenkoi@google.com, mpodolian@google.com, liranb@google.com, pragyabajoria@google.com, uysalorhan@google.com, gsennton@google.com
per-file res*/*/tv_*.xml = bronger@google.com
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java
index 434b512..b6da761 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java
@@ -174,6 +174,7 @@
BubbleBarUpdate getInitialState() {
BubbleBarUpdate bubbleBarUpdate = BubbleBarUpdate.createInitialState();
bubbleBarUpdate.shouldShowEducation = shouldShowEducation;
+ bubbleBarUpdate.showOverflow = !overflowBubbles.isEmpty();
for (int i = 0; i < bubbles.size(); i++) {
bubbleBarUpdate.currentBubbleList.add(bubbles.get(i).asBubbleBarBubble());
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/OWNERS b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/OWNERS
index b01b2b7..afdda8f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/OWNERS
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/OWNERS
@@ -5,3 +5,6 @@
pbdr@google.com
tkachenkoi@google.com
vaniadesmonda@google.com
+pragyabajoria@google.com
+uysalorhan@google.com
+gsennton@google.com
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/OWNERS b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/OWNERS
index 8a0eea0..93351c3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/OWNERS
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/OWNERS
@@ -5,3 +5,7 @@
nmusgrave@google.com
pbdr@google.com
tkachenkoi@google.com
+vaniadesmonda@google.com
+pragyabajoria@google.com
+uysalorhan@google.com
+gsennton@google.com
diff --git a/libs/WindowManager/Shell/tests/OWNERS b/libs/WindowManager/Shell/tests/OWNERS
index 9f735c4..d1be12f 100644
--- a/libs/WindowManager/Shell/tests/OWNERS
+++ b/libs/WindowManager/Shell/tests/OWNERS
@@ -15,3 +15,6 @@
mpodolian@google.com
jeremysim@google.com
peanutbutter@google.com
+pragyabajoria@google.com
+uysalorhan@google.com
+gsennton@google.com
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DragResizeWindowGeometryTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DragResizeWindowGeometryTests.java
index 77337a0..d8f395d 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DragResizeWindowGeometryTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DragResizeWindowGeometryTests.java
@@ -56,7 +56,7 @@
public class DragResizeWindowGeometryTests extends ShellTestCase {
private static final Size TASK_SIZE = new Size(500, 1000);
private static final int TASK_CORNER_RADIUS = 10;
- private static final int EDGE_RESIZE_THICKNESS = 15;
+ private static final int EDGE_RESIZE_THICKNESS = 12;
private static final int FINE_CORNER_SIZE = EDGE_RESIZE_THICKNESS * 2 + 10;
private static final int LARGE_CORNER_SIZE = FINE_CORNER_SIZE + 10;
private static final DragResizeWindowGeometry GEOMETRY = new DragResizeWindowGeometry(
diff --git a/libs/androidfw/Idmap.cpp b/libs/androidfw/Idmap.cpp
index 9824190..f066e46 100644
--- a/libs/androidfw/Idmap.cpp
+++ b/libs/androidfw/Idmap.cpp
@@ -121,7 +121,7 @@
uint8_t target_assigned_package_id)
: data_header_(data_header),
entries_(entries),
- target_assigned_package_id_(target_assigned_package_id) { };
+ target_assigned_package_id_(target_assigned_package_id) {}
status_t OverlayDynamicRefTable::lookupResourceId(uint32_t* resId) const {
const Idmap_overlay_entry* first_entry = entries_;
diff --git a/libs/androidfw/include/androidfw/Idmap.h b/libs/androidfw/include/androidfw/Idmap.h
index c32a38e..64b1f0c 100644
--- a/libs/androidfw/include/androidfw/Idmap.h
+++ b/libs/androidfw/include/androidfw/Idmap.h
@@ -171,14 +171,14 @@
}
// Returns a mapping from target resource ids to overlay values.
- const IdmapResMap GetTargetResourcesMap(uint8_t target_assigned_package_id,
- const OverlayDynamicRefTable* overlay_ref_table) const {
+ IdmapResMap GetTargetResourcesMap(uint8_t target_assigned_package_id,
+ const OverlayDynamicRefTable* overlay_ref_table) const {
return IdmapResMap(data_header_, target_entries_, target_inline_entries_, inline_entry_values_,
configurations_, target_assigned_package_id, overlay_ref_table);
}
// Returns a dynamic reference table for a loaded overlay package.
- const OverlayDynamicRefTable GetOverlayDynamicRefTable(uint8_t target_assigned_package_id) const {
+ OverlayDynamicRefTable GetOverlayDynamicRefTable(uint8_t target_assigned_package_id) const {
return OverlayDynamicRefTable(data_header_, overlay_entries_, target_assigned_package_id);
}
diff --git a/nfc/java/android/nfc/NfcActivityManager.java b/nfc/java/android/nfc/NfcActivityManager.java
index 0e40db6..0eb846d 100644
--- a/nfc/java/android/nfc/NfcActivityManager.java
+++ b/nfc/java/android/nfc/NfcActivityManager.java
@@ -236,11 +236,7 @@
public void setReaderMode(Binder token, int flags, Bundle extras) {
if (DBG) Log.d(TAG, "Setting reader mode");
- try {
- NfcAdapter.sService.setReaderMode(token, this, flags, extras);
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.setReaderMode(token, this, flags, extras));
}
/**
@@ -248,19 +244,11 @@
* Makes IPC call - do not hold lock.
*/
void requestNfcServiceCallback() {
- try {
- NfcAdapter.sService.setAppCallback(this);
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.setAppCallback(this));
}
void verifyNfcPermission() {
- try {
- NfcAdapter.sService.verifyNfcPermission();
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.verifyNfcPermission());
}
@Override
@@ -406,11 +394,8 @@
}
private void changeDiscoveryTech(Binder token, int pollTech, int listenTech) {
- try {
- NfcAdapter.sService.updateDiscoveryTechnology(token, pollTech, listenTech);
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(
+ () -> NfcAdapter.sService.updateDiscoveryTechnology(token, pollTech, listenTech));
}
}
diff --git a/nfc/java/android/nfc/NfcAdapter.java b/nfc/java/android/nfc/NfcAdapter.java
index 0ffab4b..b36b705 100644
--- a/nfc/java/android/nfc/NfcAdapter.java
+++ b/nfc/java/android/nfc/NfcAdapter.java
@@ -922,8 +922,8 @@
* @hide
*/
@UnsupportedAppUsage
- public INfcAdapter getService() {
- isEnabled(); // NOP call to recover sService if it is stale
+ public static INfcAdapter getService() {
+ isEnabledStatic(); // NOP call to recover sService if it is stale
return sService;
}
@@ -931,8 +931,8 @@
* Returns the binder interface to the tag service.
* @hide
*/
- public INfcTag getTagService() {
- isEnabled(); // NOP call to recover sTagService if it is stale
+ public static INfcTag getTagService() {
+ isEnabledStatic(); // NOP call to recover sTagService if it is stale
return sTagService;
}
@@ -940,8 +940,8 @@
* Returns the binder interface to the card emulation service.
* @hide
*/
- public INfcCardEmulation getCardEmulationService() {
- isEnabled();
+ public static INfcCardEmulation getCardEmulationService() {
+ isEnabledStatic();
return sCardEmulationService;
}
@@ -949,8 +949,8 @@
* Returns the binder interface to the NFC-F card emulation service.
* @hide
*/
- public INfcFCardEmulation getNfcFCardEmulationService() {
- isEnabled();
+ public static INfcFCardEmulation getNfcFCardEmulationService() {
+ isEnabledStatic();
return sNfcFCardEmulationService;
}
@@ -973,14 +973,14 @@
* @hide
*/
@UnsupportedAppUsage
- public void attemptDeadServiceRecovery(Exception e) {
+ public static void attemptDeadServiceRecovery(RemoteException e) {
Log.e(TAG, "NFC service dead - attempting to recover", e);
INfcAdapter service = getServiceInterface();
if (service == null) {
Log.e(TAG, "could not retrieve NFC service during service recovery");
// nothing more can be done now, sService is still stale, we'll hit
// this recovery path again later
- return;
+ e.rethrowAsRuntimeException();
}
// assigning to sService is not thread-safe, but this is best-effort code
// and on a well-behaved system should never happen
@@ -993,7 +993,7 @@
Log.e(TAG, "could not retrieve NFC tag service during service recovery");
// nothing more can be done now, sService is still stale, we'll hit
// this recovery path again later
- return;
+ ee.rethrowAsRuntimeException();
}
}
@@ -1014,24 +1014,27 @@
"could not retrieve NFC-F card emulation service during service recovery");
}
}
-
- return;
}
- private boolean isCardEmulationEnabled() {
+ private static boolean isCardEmulationEnabled() {
if (sHasCeFeature) {
return (sCardEmulationService != null || sNfcFCardEmulationService != null);
}
return false;
}
- private boolean isTagReadingEnabled() {
+ private static boolean isTagReadingEnabled() {
if (sHasNfcFeature) {
return sTagService != null;
}
return false;
}
+ private static boolean isEnabledStatic() {
+ boolean serviceState = callServiceReturn(() -> sService.getState() == STATE_ON, false);
+ return serviceState
+ && (isTagReadingEnabled() || isCardEmulationEnabled() || sHasNfcWlcFeature);
+ }
/**
* Return true if this NFC Adapter has any features enabled.
@@ -1046,24 +1049,7 @@
* @return true if this NFC Adapter has any features enabled
*/
public boolean isEnabled() {
- boolean serviceState = false;
- try {
- serviceState = sService.getState() == STATE_ON;
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- // Try one more time
- if (sService == null) {
- Log.e(TAG, "Failed to recover NFC Service.");
- return false;
- }
- try {
- serviceState = sService.getState() == STATE_ON;
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover NFC Service.");
- }
- }
- return serviceState
- && (isTagReadingEnabled() || isCardEmulationEnabled() || sHasNfcWlcFeature);
+ return isEnabledStatic();
}
/**
@@ -1157,11 +1143,7 @@
* @hide
*/
public void pausePolling(int timeoutInMs) {
- try {
- sService.pausePolling(timeoutInMs);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService(() -> sService.pausePolling(timeoutInMs));
}
@@ -1222,11 +1204,7 @@
* @hide
*/
public void resumePolling() {
- try {
- sService.resumePolling();
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService(() -> sService.resumePolling());
}
/**
@@ -1645,15 +1623,10 @@
if (activity == null || intent == null) {
throw new NullPointerException();
}
- try {
- TechListParcel parcel = null;
- if (techLists != null && techLists.length > 0) {
- parcel = new TechListParcel(techLists);
- }
- sService.setForegroundDispatch(intent, filters, parcel);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ final TechListParcel parcel = (techLists != null && techLists.length > 0)
+ ? new TechListParcel(techLists)
+ : null;
+ callService(() -> sService.setForegroundDispatch(intent, filters, parcel));
}
/**
@@ -1677,11 +1650,7 @@
throw new UnsupportedOperationException();
}
}
- try {
- sService.setForegroundDispatch(null, null, null);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService(() -> sService.setForegroundDispatch(null, null, null));
}
/**
@@ -1762,11 +1731,7 @@
}
Binder token = new Binder();
int flags = enable ? ENABLE_POLLING_FLAGS : DISABLE_POLLING_FLAGS;
- try {
- NfcAdapter.sService.setReaderMode(token, null, flags, null);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService(() -> sService.setReaderMode(token, null, flags, null));
}
/**
@@ -1838,12 +1803,8 @@
&& ((pollTechnology & FLAG_SET_DEFAULT_TECH) == FLAG_SET_DEFAULT_TECH
|| (listenTechnology & FLAG_SET_DEFAULT_TECH) == FLAG_SET_DEFAULT_TECH)) {
Binder token = new Binder();
- try {
- NfcAdapter.sService.updateDiscoveryTechnology(token,
- pollTechnology, listenTechnology);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService( () ->
+ sService.updateDiscoveryTechnology(token, pollTechnology, listenTechnology));
} else {
mNfcActivityManager.setDiscoveryTech(activity, pollTechnology, listenTechnology);
}
@@ -2227,11 +2188,7 @@
if (tag == null) {
throw new NullPointerException("tag cannot be null");
}
- try {
- sService.dispatch(tag);
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- }
+ callService(() -> sService.dispatch(tag));
}
/**
@@ -2267,8 +2224,10 @@
synchronized (mLock) {
if (mNfcUnlockHandlers.containsKey(unlockHandler)) {
// update the tag technologies
- sService.removeNfcUnlockHandler(mNfcUnlockHandlers.get(unlockHandler));
- mNfcUnlockHandlers.remove(unlockHandler);
+ callService(() -> {
+ sService.removeNfcUnlockHandler(mNfcUnlockHandlers.get(unlockHandler));
+ mNfcUnlockHandlers.remove(unlockHandler);
+ });
}
INfcUnlockHandler.Stub iHandler = new INfcUnlockHandler.Stub() {
@@ -2277,20 +2236,18 @@
return unlockHandler.onUnlockAttempted(tag);
}
};
-
- sService.addNfcUnlockHandler(iHandler,
- Tag.getTechCodesFromStrings(tagTechnologies));
- mNfcUnlockHandlers.put(unlockHandler, iHandler);
+ return callServiceReturn(() -> {
+ sService.addNfcUnlockHandler(
+ iHandler, Tag.getTechCodesFromStrings(tagTechnologies));
+ mNfcUnlockHandlers.put(unlockHandler, iHandler);
+ return true;
+ }, false);
}
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- return false;
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to register LockscreenDispatch", e);
return false;
}
- return true;
}
/**
@@ -2307,17 +2264,14 @@
throw new UnsupportedOperationException();
}
}
- try {
- synchronized (mLock) {
- if (mNfcUnlockHandlers.containsKey(unlockHandler)) {
+ synchronized (mLock) {
+ if (mNfcUnlockHandlers.containsKey(unlockHandler)) {
+ return callServiceReturn(() -> {
sService.removeNfcUnlockHandler(mNfcUnlockHandlers.remove(unlockHandler));
- }
-
- return true;
+ return true;
+ }, false);
}
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- return false;
+ return true;
}
}
@@ -2525,26 +2479,8 @@
Log.e(TAG, "TagIntentAppPreference is not supported");
throw new UnsupportedOperationException();
}
- try {
- Map<String, Boolean> result = (Map<String, Boolean>) sService
- .getTagIntentAppPreferenceForUser(userId);
- return result;
- } catch (RemoteException e) {
- attemptDeadServiceRecovery(e);
- // Try one more time
- if (sService == null) {
- Log.e(TAG, "Failed to recover NFC Service.");
- return Collections.emptyMap();
- }
- try {
- Map<String, Boolean> result = (Map<String, Boolean>) sService
- .getTagIntentAppPreferenceForUser(userId);
- return result;
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover NFC Service.");
- }
- return Collections.emptyMap();
- }
+ return callServiceReturn( () ->
+ sService.getTagIntentAppPreferenceForUser(userId), Collections.emptyMap());
}
/**
@@ -2590,50 +2526,44 @@
callService(() -> sService.notifyTestHceData(technology, data));
}
+ /** @hide */
interface ServiceCall {
void call() throws RemoteException;
}
-
- void callService(ServiceCall call) {
+ /** @hide */
+ static void callService(ServiceCall call) {
try {
if (sService == null) {
- attemptDeadServiceRecovery(null);
+ attemptDeadServiceRecovery(new RemoteException("NFC Service is null"));
}
call.call();
} catch (RemoteException e) {
attemptDeadServiceRecovery(e);
- // Try one more time
- if (sService == null) {
- Log.e(TAG, "Failed to recover NFC Service.");
- return;
- }
try {
call.call();
} catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover NFC Service.");
+ ee.rethrowAsRuntimeException();
}
}
}
+ /** @hide */
interface ServiceCallReturn<T> {
T call() throws RemoteException;
}
- <T> T callServiceReturn(ServiceCallReturn<T> call, T defaultReturn) {
+ /** @hide */
+ static <T> T callServiceReturn(ServiceCallReturn<T> call, T defaultReturn) {
try {
if (sService == null) {
- attemptDeadServiceRecovery(null);
+ attemptDeadServiceRecovery(new RemoteException("NFC Service is null"));
}
return call.call();
} catch (RemoteException e) {
attemptDeadServiceRecovery(e);
// Try one more time
- if (sService == null) {
- Log.e(TAG, "Failed to recover NFC Service.");
- return defaultReturn;
- }
try {
return call.call();
} catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover NFC Service.");
+ ee.rethrowAsRuntimeException();
}
}
return defaultReturn;
diff --git a/nfc/java/android/nfc/NfcOemExtension.java b/nfc/java/android/nfc/NfcOemExtension.java
index f6138a6..2ec819c 100644
--- a/nfc/java/android/nfc/NfcOemExtension.java
+++ b/nfc/java/android/nfc/NfcOemExtension.java
@@ -89,13 +89,11 @@
+ "registering");
throw new IllegalArgumentException();
}
- try {
+ NfcAdapter.callService(() -> {
NfcAdapter.sService.registerOemExtensionCallback(mOemNfcExtensionCallback);
mCallback = callback;
mExecutor = executor;
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ });
}
}
@@ -117,13 +115,11 @@
Log.e(TAG, "Callback not registered");
throw new IllegalArgumentException();
}
- try {
+ NfcAdapter.callService(() -> {
NfcAdapter.sService.unregisterOemExtensionCallback(mOemNfcExtensionCallback);
mCallback = null;
mExecutor = null;
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ });
}
}
@@ -134,11 +130,7 @@
@FlaggedApi(Flags.FLAG_NFC_OEM_EXTENSION)
@RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
public void clearPreference() {
- try {
- NfcAdapter.sService.clearPreference();
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.clearPreference());
}
/**
@@ -147,11 +139,7 @@
@FlaggedApi(Flags.FLAG_NFC_OEM_EXTENSION)
@RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
public void synchronizeScreenState() {
- try {
- NfcAdapter.sService.setScreenState();
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.setScreenState());
}
/**
@@ -162,11 +150,7 @@
@FlaggedApi(Flags.FLAG_NFC_OEM_EXTENSION)
@RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
public void maybeTriggerFirmwareUpdate() {
- try {
- NfcAdapter.sService.checkFirmware();
- } catch (RemoteException e) {
- mAdapter.attemptDeadServiceRecovery(e);
- }
+ NfcAdapter.callService(() -> NfcAdapter.sService.checkFirmware());
}
private final class NfcOemExtensionCallback extends INfcOemExtensionCallback.Stub {
diff --git a/nfc/java/android/nfc/cardemulation/CardEmulation.java b/nfc/java/android/nfc/cardemulation/CardEmulation.java
index 2fe2ce3..e0438ce 100644
--- a/nfc/java/android/nfc/cardemulation/CardEmulation.java
+++ b/nfc/java/android/nfc/cardemulation/CardEmulation.java
@@ -219,24 +219,9 @@
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*/
public boolean isDefaultServiceForCategory(ComponentName service, String category) {
- try {
- return sService.isDefaultServiceForCategory(mContext.getUser().getIdentifier(),
- service, category);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.isDefaultServiceForCategory(mContext.getUser().getIdentifier(),
- service, category);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.isDefaultServiceForCategory(
+ mContext.getUser().getIdentifier(), service, category), false);
}
/**
@@ -251,24 +236,9 @@
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*/
public boolean isDefaultServiceForAid(ComponentName service, String aid) {
- try {
- return sService.isDefaultServiceForAid(mContext.getUser().getIdentifier(),
- service, aid);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.isDefaultServiceForAid(mContext.getUser().getIdentifier(),
- service, aid);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.isDefaultServiceForAid(
+ mContext.getUser().getIdentifier(), service, aid), false);
}
/**
@@ -331,22 +301,8 @@
*/
public int getSelectionModeForCategory(String category) {
if (CATEGORY_PAYMENT.equals(category)) {
- boolean paymentRegistered = false;
- try {
- paymentRegistered = sService.isDefaultPaymentRegistered();
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return SELECTION_MODE_ALWAYS_ASK;
- }
- try {
- paymentRegistered = sService.isDefaultPaymentRegistered();
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return SELECTION_MODE_ALWAYS_ASK;
- }
- }
+ boolean paymentRegistered = callServiceReturn(() ->
+ sService.isDefaultPaymentRegistered(), false);
if (paymentRegistered) {
return SELECTION_MODE_PREFER_DEFAULT;
} else {
@@ -369,13 +325,9 @@
@FlaggedApi(Flags.FLAG_NFC_OBSERVE_MODE)
public boolean setShouldDefaultToObserveModeForService(@NonNull ComponentName service,
boolean enable) {
- try {
- return sService.setShouldDefaultToObserveModeForService(
- mContext.getUser().getIdentifier(), service, enable);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- }
- return false;
+ return callServiceReturn(() ->
+ sService.setShouldDefaultToObserveModeForService(
+ mContext.getUser().getIdentifier(), service, enable), false);
}
/**
@@ -396,27 +348,11 @@
@FlaggedApi(Flags.FLAG_NFC_READ_POLLING_LOOP)
public boolean registerPollingLoopFilterForService(@NonNull ComponentName service,
@NonNull String pollingLoopFilter, boolean autoTransact) {
- pollingLoopFilter = validatePollingLoopFilter(pollingLoopFilter);
-
- try {
- return sService.registerPollingLoopFilterForService(mContext.getUser().getIdentifier(),
- service, pollingLoopFilter, autoTransact);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.registerPollingLoopFilterForService(
- mContext.getUser().getIdentifier(), service,
- pollingLoopFilter, autoTransact);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final String pollingLoopFilterV = validatePollingLoopFilter(pollingLoopFilter);
+ return callServiceReturn(() ->
+ sService.registerPollingLoopFilterForService(
+ mContext.getUser().getIdentifier(), service, pollingLoopFilterV, autoTransact),
+ false);
}
/**
@@ -431,27 +367,10 @@
@FlaggedApi(Flags.FLAG_NFC_READ_POLLING_LOOP)
public boolean removePollingLoopFilterForService(@NonNull ComponentName service,
@NonNull String pollingLoopFilter) {
- pollingLoopFilter = validatePollingLoopFilter(pollingLoopFilter);
-
- try {
- return sService.removePollingLoopFilterForService(mContext.getUser().getIdentifier(),
- service, pollingLoopFilter);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.removePollingLoopFilterForService(
- mContext.getUser().getIdentifier(), service,
- pollingLoopFilter);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final String pollingLoopFilterV = validatePollingLoopFilter(pollingLoopFilter);
+ return callServiceReturn(() ->
+ sService.removePollingLoopFilterForService(
+ mContext.getUser().getIdentifier(), service, pollingLoopFilterV), false);
}
@@ -477,28 +396,13 @@
@FlaggedApi(Flags.FLAG_NFC_READ_POLLING_LOOP)
public boolean registerPollingLoopPatternFilterForService(@NonNull ComponentName service,
@NonNull String pollingLoopPatternFilter, boolean autoTransact) {
- pollingLoopPatternFilter = validatePollingLoopPatternFilter(pollingLoopPatternFilter);
-
- try {
- return sService.registerPollingLoopPatternFilterForService(
- mContext.getUser().getIdentifier(),
- service, pollingLoopPatternFilter, autoTransact);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.registerPollingLoopPatternFilterForService(
- mContext.getUser().getIdentifier(), service,
- pollingLoopPatternFilter, autoTransact);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final String pollingLoopPatternFilterV =
+ validatePollingLoopPatternFilter(pollingLoopPatternFilter);
+ return callServiceReturn(() ->
+ sService.registerPollingLoopPatternFilterForService(
+ mContext.getUser().getIdentifier(), service, pollingLoopPatternFilterV,
+ autoTransact),
+ false);
}
/**
@@ -518,27 +422,11 @@
@FlaggedApi(Flags.FLAG_NFC_READ_POLLING_LOOP)
public boolean removePollingLoopPatternFilterForService(@NonNull ComponentName service,
@NonNull String pollingLoopPatternFilter) {
- pollingLoopPatternFilter = validatePollingLoopPatternFilter(pollingLoopPatternFilter);
-
- try {
- return sService.removePollingLoopPatternFilterForService(
- mContext.getUser().getIdentifier(), service, pollingLoopPatternFilter);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.removePollingLoopPatternFilterForService(
- mContext.getUser().getIdentifier(), service,
- pollingLoopPatternFilter);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final String pollingLoopPatternFilterV =
+ validatePollingLoopPatternFilter(pollingLoopPatternFilter);
+ return callServiceReturn(() ->
+ sService.removePollingLoopPatternFilterForService(
+ mContext.getUser().getIdentifier(), service, pollingLoopPatternFilterV), false);
}
/**
@@ -563,25 +451,10 @@
*/
public boolean registerAidsForService(ComponentName service, String category,
List<String> aids) {
- AidGroup aidGroup = new AidGroup(aids, category);
- try {
- return sService.registerAidGroupForService(mContext.getUser().getIdentifier(),
- service, aidGroup);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.registerAidGroupForService(mContext.getUser().getIdentifier(),
- service, aidGroup);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final AidGroup aidGroup = new AidGroup(aids, category);
+ return callServiceReturn(() ->
+ sService.registerAidGroupForService(
+ mContext.getUser().getIdentifier(), service, aidGroup), false);
}
/**
@@ -603,27 +476,9 @@
@RequiresPermission(android.Manifest.permission.NFC)
@NonNull
public boolean unsetOffHostForService(@NonNull ComponentName service) {
- NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mContext);
- if (adapter == null) {
- return false;
- }
-
- try {
- return sService.unsetOffHostForService(mContext.getUser().getIdentifier(), service);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.unsetOffHostForService(mContext.getUser().getIdentifier(), service);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.unsetOffHostForService(
+ mContext.getUser().getIdentifier(), service), false);
}
/**
@@ -662,8 +517,6 @@
@NonNull
public boolean setOffHostForService(@NonNull ComponentName service,
@NonNull String offHostSecureElement) {
- boolean validSecureElement = false;
-
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mContext);
if (adapter == null || offHostSecureElement == null) {
return false;
@@ -684,25 +537,10 @@
} else if (offHostSecureElement.equals("SIM")) {
offHostSecureElement = "SIM1";
}
-
- try {
- return sService.setOffHostForService(mContext.getUser().getIdentifier(), service,
- offHostSecureElement);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setOffHostForService(mContext.getUser().getIdentifier(), service,
- offHostSecureElement);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ final String offHostSecureElementV = new String(offHostSecureElement);
+ return callServiceReturn(() ->
+ sService.setOffHostForService(
+ mContext.getUser().getIdentifier(), service, offHostSecureElementV), false);
}
/**
@@ -720,25 +558,10 @@
* @return The list of AIDs registered for this category, or null if it couldn't be found.
*/
public List<String> getAidsForService(ComponentName service, String category) {
- try {
- AidGroup group = sService.getAidGroupForService(mContext.getUser().getIdentifier(),
- service, category);
- return (group != null ? group.getAids() : null);
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return null;
- }
- try {
- AidGroup group = sService.getAidGroupForService(mContext.getUser().getIdentifier(),
- service, category);
- return (group != null ? group.getAids() : null);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return null;
- }
- }
+ AidGroup group = callServiceReturn(() ->
+ sService.getAidGroupForService(
+ mContext.getUser().getIdentifier(), service, category), null);
+ return (group != null ? group.getAids() : null);
}
/**
@@ -757,24 +580,9 @@
* @return whether the group was successfully removed.
*/
public boolean removeAidsForService(ComponentName service, String category) {
- try {
- return sService.removeAidGroupForService(mContext.getUser().getIdentifier(), service,
- category);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.removeAidGroupForService(mContext.getUser().getIdentifier(),
- service, category);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.removeAidGroupForService(
+ mContext.getUser().getIdentifier(), service, category), false);
}
/**
@@ -811,22 +619,7 @@
if (activity == null || service == null) {
throw new NullPointerException("activity or service or category is null");
}
- try {
- return sService.setPreferredService(service);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setPreferredService(service);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() -> sService.setPreferredService(service), false);
}
/**
@@ -843,22 +636,7 @@
if (activity == null) {
throw new NullPointerException("activity is null");
}
- try {
- return sService.unsetPreferredService();
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.unsetPreferredService();
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() -> sService.unsetPreferredService(), false);
}
/**
@@ -872,21 +650,7 @@
* @return whether AID prefix registering is supported on this device.
*/
public boolean supportsAidPrefixRegistration() {
- try {
- return sService.supportsAidPrefixRegistration();
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.supportsAidPrefixRegistration();
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() -> sService.supportsAidPrefixRegistration(), false);
}
/**
@@ -897,25 +661,9 @@
@RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO)
@Nullable
public List<String> getAidsForPreferredPaymentService() {
- try {
- ApduServiceInfo serviceInfo = sService.getPreferredPaymentService(
- mContext.getUser().getIdentifier());
- return (serviceInfo != null ? serviceInfo.getAids() : null);
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
- try {
- ApduServiceInfo serviceInfo =
- sService.getPreferredPaymentService(mContext.getUser().getIdentifier());
- return (serviceInfo != null ? serviceInfo.getAids() : null);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
- }
+ ApduServiceInfo serviceInfo = callServiceReturn(() ->
+ sService.getPreferredPaymentService(mContext.getUser().getIdentifier()), null);
+ return (serviceInfo != null ? serviceInfo.getAids() : null);
}
/**
@@ -944,40 +692,16 @@
@RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO)
@Nullable
public String getRouteDestinationForPreferredPaymentService() {
- try {
- ApduServiceInfo serviceInfo = sService.getPreferredPaymentService(
- mContext.getUser().getIdentifier());
- if (serviceInfo != null) {
- if (!serviceInfo.isOnHost()) {
- return serviceInfo.getOffHostSecureElement() == null ?
- "OffHost" : serviceInfo.getOffHostSecureElement();
- }
- return "Host";
+ ApduServiceInfo serviceInfo = callServiceReturn(() ->
+ sService.getPreferredPaymentService(mContext.getUser().getIdentifier()), null);
+ if (serviceInfo != null) {
+ if (!serviceInfo.isOnHost()) {
+ return serviceInfo.getOffHostSecureElement() == null ?
+ "OffHost" : serviceInfo.getOffHostSecureElement();
}
- return null;
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
- try {
- ApduServiceInfo serviceInfo =
- sService.getPreferredPaymentService(mContext.getUser().getIdentifier());
- if (serviceInfo != null) {
- if (!serviceInfo.isOnHost()) {
- return serviceInfo.getOffHostSecureElement() == null ?
- "Offhost" : serviceInfo.getOffHostSecureElement();
- }
- return "Host";
- }
- return null;
-
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
+ return "Host";
}
+ return null;
}
/**
@@ -995,115 +719,44 @@
@RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO)
@Nullable
public CharSequence getDescriptionForPreferredPaymentService() {
- try {
- ApduServiceInfo serviceInfo = sService.getPreferredPaymentService(
- mContext.getUser().getIdentifier());
- return (serviceInfo != null ? serviceInfo.getDescription() : null);
- } catch (RemoteException e) {
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
- try {
- ApduServiceInfo serviceInfo =
- sService.getPreferredPaymentService(mContext.getUser().getIdentifier());
- return (serviceInfo != null ? serviceInfo.getDescription() : null);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- throw e.rethrowFromSystemServer();
- }
- }
+ ApduServiceInfo serviceInfo = callServiceReturn(() ->
+ sService.getPreferredPaymentService(mContext.getUser().getIdentifier()), null);
+ return (serviceInfo != null ? serviceInfo.getDescription() : null);
}
/**
* @hide
*/
public boolean setDefaultServiceForCategory(ComponentName service, String category) {
- try {
- return sService.setDefaultServiceForCategory(mContext.getUser().getIdentifier(),
- service, category);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setDefaultServiceForCategory(mContext.getUser().getIdentifier(),
- service, category);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.setDefaultServiceForCategory(
+ mContext.getUser().getIdentifier(), service, category), false);
}
/**
* @hide
*/
public boolean setDefaultForNextTap(ComponentName service) {
- try {
- return sService.setDefaultForNextTap(mContext.getUser().getIdentifier(), service);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setDefaultForNextTap(mContext.getUser().getIdentifier(), service);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.setDefaultForNextTap(
+ mContext.getUser().getIdentifier(), service), false);
}
/**
* @hide
*/
public boolean setDefaultForNextTap(int userId, ComponentName service) {
- try {
- return sService.setDefaultForNextTap(userId, service);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setDefaultForNextTap(userId, service);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.setDefaultForNextTap(userId, service), false);
}
/**
* @hide
*/
public List<ApduServiceInfo> getServices(String category) {
- try {
- return sService.getServices(mContext.getUser().getIdentifier(), category);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return null;
- }
- try {
- return sService.getServices(mContext.getUser().getIdentifier(), category);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return null;
- }
- }
+ return callServiceReturn(() ->
+ sService.getServices(
+ mContext.getUser().getIdentifier(), category), null);
}
/**
@@ -1117,22 +770,8 @@
@FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
@NonNull
public List<ApduServiceInfo> getServices(@NonNull String category, @UserIdInt int userId) {
- try {
- return sService.getServices(userId, category);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return null;
- }
- try {
- return sService.getServices(userId, category);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return null;
- }
- }
+ return callServiceReturn(() ->
+ sService.getServices(userId, category), null);
}
/**
@@ -1222,22 +861,8 @@
if (service == null) {
throw new NullPointerException("activity or service or category is null");
}
- try {
- return sService.setServiceEnabledForCategoryOther(userId, service, status);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.setServiceEnabledForCategoryOther(userId, service, status);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.setServiceEnabledForCategoryOther(userId, service, status), false);
}
/**
@@ -1269,22 +894,9 @@
if (!activity.isResumed()) {
throw new IllegalArgumentException("Activity must be resumed.");
}
- try {
- return sService.overrideRoutingTable(UserHandle.myUserId(), protocol, technology);
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.overrideRoutingTable(UserHandle.myUserId(), protocol, technology);
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
+ return callServiceReturn(() ->
+ sService.overrideRoutingTable(
+ mContext.getUser().getIdentifier(), protocol, technology), false);
}
/**
@@ -1303,27 +915,9 @@
if (!activity.isResumed()) {
throw new IllegalArgumentException("Activity must be resumed.");
}
- try {
- return sService.recoverRoutingTable(UserHandle.myUserId());
- } catch (RemoteException e) {
- // Try one more time
- recoverService();
- if (sService == null) {
- Log.e(TAG, "Failed to recover CardEmulationService.");
- return false;
- }
- try {
- return sService.recoverRoutingTable(UserHandle.myUserId());
- } catch (RemoteException ee) {
- Log.e(TAG, "Failed to reach CardEmulationService.");
- return false;
- }
- }
- }
-
- void recoverService() {
- NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mContext);
- sService = adapter.getCardEmulationService();
+ return callServiceReturn(() ->
+ sService.recoverRoutingTable(
+ mContext.getUser().getIdentifier()), false);
}
/**
@@ -1351,4 +945,53 @@
return ComponentName.unflattenFromString(defaultPaymentComponent);
}
+
+ /** @hide */
+ interface ServiceCall {
+ void call() throws RemoteException;
+ }
+ /** @hide */
+ public static void callService(ServiceCall call) {
+ try {
+ if (sService == null) {
+ NfcAdapter.attemptDeadServiceRecovery(
+ new RemoteException("NFC CardEmulation Service is null"));
+ sService = NfcAdapter.getCardEmulationService();
+ }
+ call.call();
+ } catch (RemoteException e) {
+ NfcAdapter.attemptDeadServiceRecovery(e);
+ sService = NfcAdapter.getCardEmulationService();
+ try {
+ call.call();
+ } catch (RemoteException ee) {
+ ee.rethrowAsRuntimeException();
+ }
+ }
+ }
+ /** @hide */
+ interface ServiceCallReturn<T> {
+ T call() throws RemoteException;
+ }
+ /** @hide */
+ public static <T> T callServiceReturn(ServiceCallReturn<T> call, T defaultReturn) {
+ try {
+ if (sService == null) {
+ NfcAdapter.attemptDeadServiceRecovery(
+ new RemoteException("NFC CardEmulation Service is null"));
+ sService = NfcAdapter.getCardEmulationService();
+ }
+ return call.call();
+ } catch (RemoteException e) {
+ NfcAdapter.attemptDeadServiceRecovery(e);
+ sService = NfcAdapter.getCardEmulationService();
+ // Try one more time
+ try {
+ return call.call();
+ } catch (RemoteException ee) {
+ ee.rethrowAsRuntimeException();
+ }
+ }
+ return defaultReturn;
+ }
}
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPageTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPageTest.kt
index d7147b5..0d73cb3 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPageTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPageTest.kt
@@ -22,8 +22,9 @@
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertIsNotEnabled
-import androidx.compose.ui.test.assertIsOff
-import androidx.compose.ui.test.assertIsOn
+import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.isOff
+import androidx.compose.ui.test.isOn
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.onRoot
@@ -31,6 +32,7 @@
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.settingslib.spa.testutils.FakeNavControllerWrapper
+import com.android.settingslib.spa.testutils.waitUntilExists
import com.android.settingslib.spaprivileged.R
import com.android.settingslib.spaprivileged.model.app.IPackageManagers
import com.android.settingslib.spaprivileged.model.enterprise.NoRestricted
@@ -99,8 +101,8 @@
setEntryItem(listModel)
- composeTestRule.onNodeWithText(context.getString(R.string.app_permission_summary_allowed))
- .assertIsDisplayed()
+ composeTestRule.waitUntilExists(
+ hasText(context.getString(R.string.app_permission_summary_allowed)))
}
@Test
@@ -141,8 +143,8 @@
setTogglePermissionAppInfoPage(listModel)
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .assertIsOn()
+ composeTestRule.waitUntilExists(
+ hasText(context.getString(listModel.switchTitleResId)) and isOn())
}
@Test
@@ -151,8 +153,8 @@
setTogglePermissionAppInfoPage(listModel)
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .assertIsOff()
+ composeTestRule.waitUntilExists(
+ hasText(context.getString(listModel.switchTitleResId)) and isOff())
}
@Test
@@ -160,11 +162,10 @@
val listModel = TestTogglePermissionAppListModel(isAllowed = false, isChangeable = true)
setTogglePermissionAppInfoPage(listModel)
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .performClick()
+ composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId)).performClick()
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .assertIsOn()
+ composeTestRule.waitUntilExists(
+ hasText(context.getString(listModel.switchTitleResId)) and isOn())
}
@Test
@@ -172,11 +173,10 @@
val listModel = TestTogglePermissionAppListModel(isAllowed = false, isChangeable = false)
setTogglePermissionAppInfoPage(listModel)
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .performClick()
+ composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId)).performClick()
- composeTestRule.onNodeWithText(context.getString(listModel.switchTitleResId))
- .assertIsOff()
+ composeTestRule.waitUntilExists(
+ hasText(context.getString(listModel.switchTitleResId)) and isOff())
}
@Test
diff --git a/packages/SettingsLib/aconfig/settingslib.aconfig b/packages/SettingsLib/aconfig/settingslib.aconfig
index 754d9423..0d124e8 100644
--- a/packages/SettingsLib/aconfig/settingslib.aconfig
+++ b/packages/SettingsLib/aconfig/settingslib.aconfig
@@ -108,4 +108,14 @@
namespace: "android_settings"
description: "Settings catalyst project migration"
bug: "323791114"
-}
\ No newline at end of file
+}
+
+flag {
+ name: "asha_profile_access_profile_enabled_true"
+ namespace: "accessibility"
+ description: "Changes the return value of HearingAidProfile.accessProfileEnabled() to true"
+ bug: "356530795"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
index f2450de..fb9b4df 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
@@ -34,6 +34,7 @@
import com.android.settingslib.R;
import com.android.settingslib.Utils;
+import com.android.settingslib.flags.Flags;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -141,7 +142,7 @@
}
public boolean accessProfileEnabled() {
- return false;
+ return Flags.ashaProfileAccessProfileEnabledTrue();
}
public boolean isAutoConnectable() {
diff --git a/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java b/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
index a06f084..22e6133 100644
--- a/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
+++ b/packages/SettingsLib/src/com/android/settingslib/notification/modes/TestModeBuilder.java
@@ -16,8 +16,8 @@
package com.android.settingslib.notification.modes;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_UNKNOWN;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_UNKNOWN;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
import android.app.AutomaticZenRule;
import android.app.NotificationManager;
@@ -154,7 +154,7 @@
mRule.setEnabled(enabled);
mConfigZenRule.enabled = enabled;
if (!enabled) {
- mConfigZenRule.disabledOrigin = byUser ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_UNKNOWN;
+ mConfigZenRule.disabledOrigin = byUser ? ORIGIN_USER_IN_SYSTEMUI : ORIGIN_UNKNOWN;
}
return this;
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java b/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
index 88af7ee..88497a3 100644
--- a/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
+++ b/packages/SettingsLib/src/com/android/settingslib/notification/modes/ZenMode.java
@@ -66,7 +66,7 @@
private static final String TAG = "ZenMode";
- static final String MANUAL_DND_MODE_ID = "manual_dnd";
+ static final String MANUAL_DND_MODE_ID = ZenModeConfig.MANUAL_RULE_ID;
static final String TEMP_NEW_MODE_ID = "temp_new_mode";
// Must match com.android.server.notification.ZenModeHelper#applyCustomPolicy.
@@ -119,7 +119,7 @@
return Status.ENABLED;
}
} else {
- if (zenRuleExtraData.disabledOrigin == ZenModeConfig.UPDATE_ORIGIN_USER) {
+ if (zenRuleExtraData.disabledOrigin == ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI) {
return Status.DISABLED_BY_USER;
} else {
return Status.DISABLED_BY_OTHER; // by APP, SYSTEM, UNKNOWN.
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/notification/modes/ZenModeTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/notification/modes/ZenModeTest.java
index 651e57c..d9fdcc38 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/notification/modes/ZenModeTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/notification/modes/ZenModeTest.java
@@ -93,7 +93,7 @@
public void constructor_disabledRuleByUser_statusDisabledByUser() {
AutomaticZenRule azr = new AutomaticZenRule.Builder(ZEN_RULE).setEnabled(false).build();
ZenModeConfig.ZenRule configZenRule = zenConfigRuleFor(azr, false);
- configZenRule.disabledOrigin = ZenModeConfig.UPDATE_ORIGIN_USER;
+ configZenRule.disabledOrigin = ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
ZenMode mode = new ZenMode("id", azr, configZenRule);
assertThat(mode.getStatus()).isEqualTo(ZenMode.Status.DISABLED_BY_USER);
@@ -103,7 +103,7 @@
public void constructor_disabledRuleByOther_statusDisabledByOther() {
AutomaticZenRule azr = new AutomaticZenRule.Builder(ZEN_RULE).setEnabled(false).build();
ZenModeConfig.ZenRule configZenRule = zenConfigRuleFor(azr, false);
- configZenRule.disabledOrigin = ZenModeConfig.UPDATE_ORIGIN_APP;
+ configZenRule.disabledOrigin = ZenModeConfig.ORIGIN_APP;
ZenMode mode = new ZenMode("id", azr, configZenRule);
assertThat(mode.getStatus()).isEqualTo(ZenMode.Status.DISABLED_BY_OTHER);
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index b99aead..6d78705 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -953,35 +953,36 @@
strict_mode: false,
}
-android_ravenwood_test {
- name: "SystemUiRavenTests",
- srcs: [
- ":SystemUI-tests-utils",
- ":SystemUI-tests-multivalent",
- // TODO(b/294256649): pivot to using {.aapt.jar} and re-enable
- // use_resource_processor: true when better supported by soong
- ":SystemUIRobo-stub{.aapt.srcjar}",
- ],
- static_libs: [
- "SystemUI-core",
- "SystemUI-res",
- "SystemUI-tests-base",
- "androidx.test.uiautomator_uiautomator",
- "androidx.core_core-animation-testing",
- "androidx.test.ext.junit",
- "kosmos",
- "mockito-kotlin-nodeps",
- ],
- libs: [
- "android.test.runner",
- "android.test.base",
- "android.test.mock",
- ],
- auto_gen_config: true,
- plugins: [
- "dagger2-compiler",
- ],
-}
+// Disable for now. TODO(b/356666754) Re-enable it
+// android_ravenwood_test {
+// name: "SystemUiRavenTests",
+// srcs: [
+// ":SystemUI-tests-utils",
+// ":SystemUI-tests-multivalent",
+// // TODO(b/294256649): pivot to using {.aapt.jar} and re-enable
+// // use_resource_processor: true when better supported by soong
+// ":SystemUIRobo-stub{.aapt.srcjar}",
+// ],
+// static_libs: [
+// "SystemUI-core",
+// "SystemUI-res",
+// "SystemUI-tests-base",
+// "androidx.test.uiautomator_uiautomator",
+// "androidx.core_core-animation-testing",
+// "androidx.test.ext.junit",
+// "kosmos",
+// "mockito-kotlin-nodeps",
+// ],
+// libs: [
+// "android.test.runner",
+// "android.test.base",
+// "android.test.mock",
+// ],
+// auto_gen_config: true,
+// plugins: [
+// "dagger2-compiler",
+// ],
+// }
// Opt-out config for optimizing the SystemUI target using R8.
// Disabled via `export SYSTEMUI_OPTIMIZE_JAVA=false`, or explicitly in Make via
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 23c6098..3767a27 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -1272,14 +1272,4 @@
namespace: "systemui"
description: "Adding haptic component infrastructure to sliders in Compose."
bug: "341968766"
-}
-
-flag {
- namespace: "systemui"
- name: "settings_ext_register_content_observer_on_bg_thread"
- description: "Register content observer in callback flow APIs on background thread in SettingsProxyExt."
- bug: "355389014"
- metadata {
- purpose: PURPOSE_BUGFIX
- }
}
\ No newline at end of file
diff --git a/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/scene/LockscreenSceneModule.kt b/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/scene/LockscreenSceneModule.kt
index bd5b795a..72965fb 100644
--- a/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/scene/LockscreenSceneModule.kt
+++ b/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/scene/LockscreenSceneModule.kt
@@ -66,11 +66,11 @@
@Provides
fun providesLockscreenContent(
- viewModel: LockscreenContentViewModel,
+ viewModelFactory: LockscreenContentViewModel.Factory,
blueprints: Set<@JvmSuppressWildcards ComposableLockscreenSceneBlueprint>,
clockInteractor: KeyguardClockInteractor,
): LockscreenContent {
- return LockscreenContent(viewModel, blueprints, clockInteractor)
+ return LockscreenContent(viewModelFactory, blueprints, clockInteractor)
}
}
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenContent.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenContent.kt
index 25e91be..672b8a7 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenContent.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenContent.kt
@@ -29,6 +29,7 @@
import com.android.systemui.keyguard.domain.interactor.KeyguardClockInteractor
import com.android.systemui.keyguard.ui.composable.blueprint.ComposableLockscreenSceneBlueprint
import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
+import com.android.systemui.lifecycle.rememberViewModel
/**
* Renders the content of the lockscreen.
@@ -37,7 +38,7 @@
* outside the scene container framework.
*/
class LockscreenContent(
- private val viewModel: LockscreenContentViewModel,
+ private val viewModelFactory: LockscreenContentViewModel.Factory,
private val blueprints: Set<@JvmSuppressWildcards ComposableLockscreenSceneBlueprint>,
private val clockInteractor: KeyguardClockInteractor,
) {
@@ -49,6 +50,7 @@
fun SceneScope.Content(
modifier: Modifier = Modifier,
) {
+ val viewModel = rememberViewModel { viewModelFactory.create() }
val isContentVisible: Boolean by viewModel.isContentVisible.collectAsStateWithLifecycle()
if (!isContentVisible) {
// If the content isn't supposed to be visible, show a large empty box as it's needed
@@ -69,6 +71,6 @@
}
val blueprint = blueprintByBlueprintId[blueprintId] ?: return
- with(blueprint) { Content(modifier.sysuiResTag("keyguard_root_view")) }
+ with(blueprint) { Content(viewModel, modifier.sysuiResTag("keyguard_root_view")) }
}
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
index b077e18..7fe1b3e 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
@@ -24,7 +24,7 @@
import com.android.compose.animation.scene.UserActionResult
import com.android.compose.animation.scene.animateSceneFloatAsState
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.keyguard.ui.viewmodel.LockscreenSceneViewModel
+import com.android.systemui.keyguard.ui.viewmodel.LockscreenSceneActionsViewModel
import com.android.systemui.qs.ui.composable.QuickSettings
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.scene.ui.composable.ComposableScene
@@ -37,13 +37,21 @@
class LockscreenScene
@Inject
constructor(
- viewModel: LockscreenSceneViewModel,
+ actionsViewModelFactory: LockscreenSceneActionsViewModel.Factory,
private val lockscreenContent: Lazy<LockscreenContent>,
) : ComposableScene {
override val key = Scenes.Lockscreen
+ private val actionsViewModel: LockscreenSceneActionsViewModel by lazy {
+ actionsViewModelFactory.create()
+ }
+
override val destinationScenes: Flow<Map<UserAction, UserActionResult>> =
- viewModel.destinationScenes
+ actionsViewModel.actions
+
+ override suspend fun activate() {
+ actionsViewModel.activate()
+ }
@Composable
override fun SceneScope.Content(
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/CommunalBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/CommunalBlueprint.kt
index 210ca69..adad446 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/CommunalBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/CommunalBlueprint.kt
@@ -32,16 +32,15 @@
import javax.inject.Inject
/** Renders the lockscreen scene when showing the communal glanceable hub. */
-class CommunalBlueprint
-@Inject
-constructor(
- private val viewModel: LockscreenContentViewModel,
-) : ComposableLockscreenSceneBlueprint {
+class CommunalBlueprint @Inject constructor() : ComposableLockscreenSceneBlueprint {
override val id: String = "communal"
@Composable
- override fun SceneScope.Content(modifier: Modifier) {
+ override fun SceneScope.Content(
+ viewModel: LockscreenContentViewModel,
+ modifier: Modifier,
+ ) {
LockscreenLongPress(
viewModel = viewModel.touchHandling,
modifier = modifier,
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ComposableLockscreenSceneBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ComposableLockscreenSceneBlueprint.kt
index cb73983..df36d07 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ComposableLockscreenSceneBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ComposableLockscreenSceneBlueprint.kt
@@ -20,9 +20,14 @@
import androidx.compose.ui.Modifier
import com.android.compose.animation.scene.SceneScope
import com.android.systemui.keyguard.shared.model.LockscreenSceneBlueprint
+import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
/** Defines interface for classes that can render the content for a specific blueprint/layout. */
interface ComposableLockscreenSceneBlueprint : LockscreenSceneBlueprint {
/** Renders the content of this blueprint. */
- @Composable fun SceneScope.Content(modifier: Modifier)
+ @Composable
+ fun SceneScope.Content(
+ viewModel: LockscreenContentViewModel,
+ modifier: Modifier,
+ )
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
index a9e63c6..a3e0701 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/DefaultBlueprint.kt
@@ -53,7 +53,6 @@
class DefaultBlueprint
@Inject
constructor(
- private val viewModel: LockscreenContentViewModel,
private val statusBarSection: StatusBarSection,
private val lockSection: LockSection,
private val ambientIndicationSectionOptional: Optional<AmbientIndicationSection>,
@@ -66,10 +65,17 @@
override val id: String = "default"
@Composable
- override fun SceneScope.Content(modifier: Modifier) {
+ override fun SceneScope.Content(
+ viewModel: LockscreenContentViewModel,
+ modifier: Modifier,
+ ) {
val isUdfpsVisible = viewModel.isUdfpsVisible
val isShadeLayoutWide by viewModel.isShadeLayoutWide.collectAsStateWithLifecycle()
val unfoldTranslations by viewModel.unfoldTranslations.collectAsStateWithLifecycle()
+ val areNotificationsVisible by
+ viewModel
+ .areNotificationsVisible(contentKey)
+ .collectAsStateWithLifecycle(initialValue = false)
LockscreenLongPress(
viewModel = viewModel.touchHandling,
@@ -94,6 +100,7 @@
Box {
with(topAreaSection) {
DefaultClockLayout(
+ smartSpacePaddingTop = viewModel::getSmartSpacePaddingTop,
modifier =
Modifier.thenIf(isShadeLayoutWide) {
Modifier.fillMaxWidth(0.5f)
@@ -106,6 +113,8 @@
if (isShadeLayoutWide) {
with(notificationSection) {
Notifications(
+ areNotificationsVisible = areNotificationsVisible,
+ isShadeLayoutWide = isShadeLayoutWide,
burnInParams = null,
modifier =
Modifier.fillMaxWidth(0.5f)
@@ -118,6 +127,8 @@
if (!isShadeLayoutWide) {
with(notificationSection) {
Notifications(
+ areNotificationsVisible = areNotificationsVisible,
+ isShadeLayoutWide = isShadeLayoutWide,
burnInParams = null,
modifier = Modifier.weight(weight = 1f)
)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
index 72cf832..a5e120c 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/blueprint/ShortcutsBesideUdfpsBlueprint.kt
@@ -54,7 +54,6 @@
class ShortcutsBesideUdfpsBlueprint
@Inject
constructor(
- private val viewModel: LockscreenContentViewModel,
private val statusBarSection: StatusBarSection,
private val lockSection: LockSection,
private val ambientIndicationSectionOptional: Optional<AmbientIndicationSection>,
@@ -67,10 +66,17 @@
override val id: String = "shortcuts-besides-udfps"
@Composable
- override fun SceneScope.Content(modifier: Modifier) {
+ override fun SceneScope.Content(
+ viewModel: LockscreenContentViewModel,
+ modifier: Modifier,
+ ) {
val isUdfpsVisible = viewModel.isUdfpsVisible
val isShadeLayoutWide by viewModel.isShadeLayoutWide.collectAsStateWithLifecycle()
val unfoldTranslations by viewModel.unfoldTranslations.collectAsStateWithLifecycle()
+ val areNotificationsVisible by
+ viewModel
+ .areNotificationsVisible(contentKey)
+ .collectAsStateWithLifecycle(initialValue = false)
LockscreenLongPress(
viewModel = viewModel.touchHandling,
@@ -95,6 +101,7 @@
Box {
with(topAreaSection) {
DefaultClockLayout(
+ smartSpacePaddingTop = viewModel::getSmartSpacePaddingTop,
modifier =
Modifier.graphicsLayer {
translationX = unfoldTranslations.start
@@ -104,6 +111,8 @@
if (isShadeLayoutWide) {
with(notificationSection) {
Notifications(
+ areNotificationsVisible = areNotificationsVisible,
+ isShadeLayoutWide = isShadeLayoutWide,
burnInParams = null,
modifier =
Modifier.fillMaxWidth(0.5f)
@@ -116,6 +125,8 @@
if (!isShadeLayoutWide) {
with(notificationSection) {
Notifications(
+ areNotificationsVisible = areNotificationsVisible,
+ isShadeLayoutWide = isShadeLayoutWide,
burnInParams = null,
modifier = Modifier.weight(weight = 1f)
)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/NotificationSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/NotificationSection.kt
index df068c4..f0f407a 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/NotificationSection.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/NotificationSection.kt
@@ -26,7 +26,6 @@
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
-import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.android.compose.animation.scene.SceneScope
import com.android.compose.modifiers.thenIf
import com.android.systemui.Flags
@@ -35,7 +34,6 @@
import com.android.systemui.keyguard.ui.composable.modifier.burnInAware
import com.android.systemui.keyguard.ui.viewmodel.AodBurnInViewModel
import com.android.systemui.keyguard.ui.viewmodel.BurnInParameters
-import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
import com.android.systemui.notifications.ui.composable.ConstrainedNotificationStack
import com.android.systemui.res.R
import com.android.systemui.shade.LargeScreenHeaderHelper
@@ -59,7 +57,6 @@
sharedNotificationContainerViewModel: SharedNotificationContainerViewModel,
stackScrollLayout: NotificationStackScrollLayout,
sharedNotificationContainerBinder: SharedNotificationContainerBinder,
- private val lockscreenContentViewModel: LockscreenContentViewModel,
) {
init {
@@ -89,17 +86,16 @@
* adjustment
*/
@Composable
- fun SceneScope.Notifications(burnInParams: BurnInParameters?, modifier: Modifier = Modifier) {
- val areNotificationsVisible by
- lockscreenContentViewModel
- .areNotificationsVisible(contentKey)
- .collectAsStateWithLifecycle(initialValue = false)
+ fun SceneScope.Notifications(
+ areNotificationsVisible: Boolean,
+ isShadeLayoutWide: Boolean,
+ burnInParams: BurnInParameters?,
+ modifier: Modifier = Modifier
+ ) {
if (!areNotificationsVisible) {
return
}
- val isShadeLayoutWide by
- lockscreenContentViewModel.isShadeLayoutWide.collectAsStateWithLifecycle()
val splitShadeTopMargin: Dp =
if (Flags.centralizedStatusBarHeightFix()) {
LargeScreenHeaderHelper.getLargeScreenHeaderHeight(LocalContext.current).dp
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/SmartSpaceSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/SmartSpaceSection.kt
index 33ed14b..da78eed 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/SmartSpaceSection.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/SmartSpaceSection.kt
@@ -16,6 +16,7 @@
package com.android.systemui.keyguard.ui.composable.section
+import android.content.res.Resources
import android.widget.FrameLayout
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
@@ -43,7 +44,6 @@
import com.android.systemui.keyguard.ui.viewmodel.AodBurnInViewModel
import com.android.systemui.keyguard.ui.viewmodel.BurnInParameters
import com.android.systemui.keyguard.ui.viewmodel.KeyguardSmartspaceViewModel
-import com.android.systemui.keyguard.ui.viewmodel.LockscreenContentViewModel
import com.android.systemui.res.R
import com.android.systemui.statusbar.lockscreen.LockscreenSmartspaceController
import javax.inject.Inject
@@ -55,12 +55,12 @@
private val keyguardUnlockAnimationController: KeyguardUnlockAnimationController,
private val keyguardSmartspaceViewModel: KeyguardSmartspaceViewModel,
private val aodBurnInViewModel: AodBurnInViewModel,
- private val lockscreenContentViewModel: LockscreenContentViewModel,
) {
@Composable
fun SceneScope.SmartSpace(
burnInParams: BurnInParameters,
onTopChanged: (top: Float?) -> Unit,
+ smartSpacePaddingTop: (Resources) -> Int,
modifier: Modifier = Modifier,
) {
val resources = LocalContext.current.resources
@@ -72,9 +72,7 @@
modifier
.onTopPlacementChanged(onTopChanged)
.padding(
- top = {
- lockscreenContentViewModel.getSmartSpacePaddingTop(resources)
- },
+ top = { smartSpacePaddingTop(resources) },
bottom = {
resources.getDimensionPixelSize(
R.dimen.keyguard_status_view_bottom_margin
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/TopAreaSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/TopAreaSection.kt
index c0832d9..0eeb79b 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/TopAreaSection.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/TopAreaSection.kt
@@ -17,6 +17,7 @@
package com.android.systemui.keyguard.ui.composable.section
import android.content.Context
+import android.content.res.Resources
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@@ -61,6 +62,7 @@
) {
@Composable
fun SceneScope.DefaultClockLayout(
+ smartSpacePaddingTop: (Resources) -> Int,
modifier: Modifier = Modifier,
) {
val currentClockLayout by clockViewModel.currentClockLayout.collectAsStateWithLifecycle()
@@ -99,22 +101,41 @@
SceneTransitionLayout(state) {
scene(splitShadeLargeClockScene) {
LargeClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
shouldOffSetClockToOneHalf = !hasCustomPositionUpdatedAnimation
)
}
scene(splitShadeSmallClockScene) {
- SmallClockWithSmartSpace(modifier = Modifier.fillMaxWidth(0.5f))
+ SmallClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
+ modifier = Modifier.fillMaxWidth(0.5f),
+ )
}
- scene(smallClockScene) { SmallClockWithSmartSpace() }
+ scene(smallClockScene) {
+ SmallClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
+ )
+ }
- scene(largeClockScene) { LargeClockWithSmartSpace() }
+ scene(largeClockScene) {
+ LargeClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
+ )
+ }
- scene(WeatherClockScenes.largeClockScene) { WeatherLargeClockWithSmartSpace() }
+ scene(WeatherClockScenes.largeClockScene) {
+ WeatherLargeClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
+ )
+ }
scene(WeatherClockScenes.splitShadeLargeClockScene) {
- WeatherLargeClockWithSmartSpace(modifier = Modifier.fillMaxWidth(0.5f))
+ WeatherLargeClockWithSmartSpace(
+ smartSpacePaddingTop = smartSpacePaddingTop,
+ modifier = Modifier.fillMaxWidth(0.5f),
+ )
}
}
with(mediaCarouselSection) { KeyguardMediaCarousel() }
@@ -122,7 +143,10 @@
}
@Composable
- private fun SceneScope.SmallClockWithSmartSpace(modifier: Modifier = Modifier) {
+ private fun SceneScope.SmallClockWithSmartSpace(
+ smartSpacePaddingTop: (Resources) -> Int,
+ modifier: Modifier = Modifier,
+ ) {
val burnIn = rememberBurnIn(clockInteractor)
Column(modifier = modifier) {
@@ -137,13 +161,17 @@
SmartSpace(
burnInParams = burnIn.parameters,
onTopChanged = burnIn.onSmartspaceTopChanged,
+ smartSpacePaddingTop = smartSpacePaddingTop,
)
}
}
}
@Composable
- private fun SceneScope.LargeClockWithSmartSpace(shouldOffSetClockToOneHalf: Boolean = false) {
+ private fun SceneScope.LargeClockWithSmartSpace(
+ smartSpacePaddingTop: (Resources) -> Int,
+ shouldOffSetClockToOneHalf: Boolean = false,
+ ) {
val burnIn = rememberBurnIn(clockInteractor)
val isLargeClockVisible by clockViewModel.isLargeClockVisible.collectAsStateWithLifecycle()
@@ -158,6 +186,7 @@
SmartSpace(
burnInParams = burnIn.parameters,
onTopChanged = burnIn.onSmartspaceTopChanged,
+ smartSpacePaddingTop = smartSpacePaddingTop,
)
}
with(clockSection) {
@@ -180,7 +209,10 @@
}
@Composable
- private fun SceneScope.WeatherLargeClockWithSmartSpace(modifier: Modifier = Modifier) {
+ private fun SceneScope.WeatherLargeClockWithSmartSpace(
+ smartSpacePaddingTop: (Resources) -> Int,
+ modifier: Modifier = Modifier,
+ ) {
val burnIn = rememberBurnIn(clockInteractor)
val isLargeClockVisible by clockViewModel.isLargeClockVisible.collectAsStateWithLifecycle()
val currentClockState = clockViewModel.currentClock.collectAsStateWithLifecycle()
@@ -206,6 +238,7 @@
SmartSpace(
burnInParams = burnIn.parameters,
onTopChanged = burnIn.onSmartspaceTopChanged,
+ smartSpacePaddingTop = smartSpacePaddingTop,
modifier =
Modifier.heightIn(
min = getDimen(context, "enhanced_smartspace_height", density)
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/GoneScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/GoneScene.kt
index a9ddf84..b0c3fb31 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/GoneScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/GoneScene.kt
@@ -31,7 +31,7 @@
import com.android.systemui.qs.ui.composable.QuickSettings.SharedValues.MediaLandscapeTopOffset
import com.android.systemui.qs.ui.composable.QuickSettings.SharedValues.MediaOffset.Default
import com.android.systemui.scene.shared.model.Scenes
-import com.android.systemui.scene.ui.viewmodel.GoneSceneViewModel
+import com.android.systemui.scene.ui.viewmodel.GoneSceneActionsViewModel
import com.android.systemui.statusbar.notification.stack.ui.view.NotificationScrollView
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.NotificationsPlaceholderViewModel
import dagger.Lazy
@@ -48,12 +48,18 @@
constructor(
private val notificationStackScrolLView: Lazy<NotificationScrollView>,
private val notificationsPlaceholderViewModel: NotificationsPlaceholderViewModel,
- private val viewModel: GoneSceneViewModel,
+ private val viewModelFactory: GoneSceneActionsViewModel.Factory,
) : ComposableScene {
override val key = Scenes.Gone
+ private val actionsViewModel: GoneSceneActionsViewModel by lazy { viewModelFactory.create() }
+
override val destinationScenes: Flow<Map<UserAction, UserActionResult>> =
- viewModel.destinationScenes
+ actionsViewModel.actions
+
+ override suspend fun activate() {
+ actionsViewModel.activate()
+ }
@Composable
override fun SceneScope.Content(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
index 3075c54..8236eec 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelTest.kt
@@ -34,6 +34,7 @@
import com.android.systemui.keyguard.shared.model.ClockSize
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
import com.android.systemui.res.R
import com.android.systemui.scene.domain.interactor.sceneInteractor
import com.android.systemui.scene.shared.model.Scenes
@@ -79,6 +80,7 @@
fakeFeatureFlagsClassic.set(Flags.LOCK_SCREEN_LONG_PRESS_ENABLED, true)
shadeRepository.setShadeLayoutWide(false)
underTest = lockscreenContentViewModel
+ underTest.activateIn(testScope)
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModelTest.kt
similarity index 95%
rename from packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModelTest.kt
index bca83f0..b3ea03e 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModelTest.kt
@@ -37,6 +37,7 @@
import com.android.systemui.deviceentry.domain.interactor.deviceEntryInteractor
import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
import com.android.systemui.power.data.repository.fakePowerRepository
import com.android.systemui.power.shared.model.WakefulnessState
import com.android.systemui.scene.domain.interactor.sceneInteractor
@@ -44,9 +45,7 @@
import com.android.systemui.scene.shared.model.TransitionKeys
import com.android.systemui.shade.data.repository.shadeRepository
import com.android.systemui.shade.domain.interactor.shadeInteractor
-import com.android.systemui.statusbar.notification.stack.ui.viewmodel.notificationsPlaceholderViewModel
import com.android.systemui.testKosmos
-import com.android.systemui.util.mockito.mock
import com.google.common.truth.Truth.assertThat
import kotlin.math.pow
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -63,7 +62,7 @@
@RunWith(ParameterizedAndroidJunit4::class)
@RunWithLooper
@EnableSceneContainer
-class LockscreenSceneViewModelTest : SysuiTestCase() {
+class LockscreenSceneActionsViewModelTest : SysuiTestCase() {
companion object {
private const val parameterCount = 6
@@ -172,6 +171,7 @@
@EnableFlags(Flags.FLAG_COMMUNAL_HUB)
fun destinationScenes() =
testScope.runTest {
+ underTest.activateIn(this)
kosmos.fakeDeviceEntryRepository.setLockscreenEnabled(true)
kosmos.fakeAuthenticationRepository.setAuthenticationMethod(
if (canSwipeToEnter) {
@@ -192,7 +192,7 @@
},
)
- val destinationScenes by collectLastValue(underTest.destinationScenes)
+ val destinationScenes by collectLastValue(underTest.actions)
val downDestination =
destinationScenes?.get(
Swipe(
@@ -255,15 +255,10 @@
)
}
- private fun createLockscreenSceneViewModel(): LockscreenSceneViewModel {
- return LockscreenSceneViewModel(
+ private fun createLockscreenSceneViewModel(): LockscreenSceneActionsViewModel {
+ return LockscreenSceneActionsViewModel(
deviceEntryInteractor = kosmos.deviceEntryInteractor,
communalInteractor = kosmos.communalInteractor,
- touchHandling =
- KeyguardTouchHandlingViewModel(
- interactor = mock(),
- ),
- notifications = kosmos.notificationsPlaceholderViewModel,
shadeInteractor = kosmos.shadeInteractor,
)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
index 228d61a..72a5cd1 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
@@ -48,9 +48,9 @@
import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.flags.Flags
import com.android.systemui.flags.fakeFeatureFlagsClassic
-import com.android.systemui.keyguard.ui.viewmodel.KeyguardTouchHandlingViewModel
-import com.android.systemui.keyguard.ui.viewmodel.LockscreenSceneViewModel
+import com.android.systemui.keyguard.ui.viewmodel.LockscreenSceneActionsViewModel
import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
import com.android.systemui.power.domain.interactor.PowerInteractor.Companion.setAsleepForTest
import com.android.systemui.power.domain.interactor.PowerInteractor.Companion.setAwakeForTest
import com.android.systemui.power.domain.interactor.powerInteractor
@@ -65,13 +65,11 @@
import com.android.systemui.shade.domain.interactor.shadeInteractor
import com.android.systemui.shade.ui.viewmodel.ShadeSceneViewModel
import com.android.systemui.shade.ui.viewmodel.shadeSceneViewModel
-import com.android.systemui.statusbar.notification.stack.ui.viewmodel.notificationsPlaceholderViewModel
import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionsRepository
import com.android.systemui.statusbar.pipeline.mobile.data.repository.fakeMobileConnectionsRepository
import com.android.systemui.telephony.data.repository.fakeTelephonyRepository
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
-import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.whenever
import com.android.telecom.telecomManager
import com.google.common.truth.Truth.assertThat
@@ -141,15 +139,10 @@
private lateinit var bouncerActionButtonInteractor: BouncerActionButtonInteractor
private lateinit var bouncerViewModel: BouncerViewModel
- private val lockscreenSceneViewModel by lazy {
- LockscreenSceneViewModel(
+ private val lockscreenSceneActionsViewModel by lazy {
+ LockscreenSceneActionsViewModel(
deviceEntryInteractor = deviceEntryInteractor,
communalInteractor = communalInteractor,
- touchHandling =
- KeyguardTouchHandlingViewModel(
- interactor = mock(),
- ),
- notifications = kosmos.notificationsPlaceholderViewModel,
shadeInteractor = kosmos.shadeInteractor,
)
}
@@ -198,6 +191,8 @@
val startable = kosmos.sceneContainerStartable
startable.start()
+ lockscreenSceneActionsViewModel.activateIn(testScope)
+
assertWithMessage("Initial scene key mismatch!")
.that(sceneContainerViewModel.currentScene.value)
.isEqualTo(sceneContainerConfig.initialSceneKey)
@@ -225,7 +220,7 @@
@Test
fun swipeUpOnLockscreen_enterCorrectPin_unlocksDevice() =
testScope.runTest {
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Bouncer)
emulateUserDrivenTransition(
@@ -245,7 +240,7 @@
testScope.runTest {
setAuthMethod(AuthenticationMethodModel.None, enableLockscreen = true)
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Gone)
emulateUserDrivenTransition(
@@ -351,7 +346,7 @@
fun swipeUpOnLockscreenWhileUnlocked_dismissesLockscreen() =
testScope.runTest {
unlockDevice()
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Gone)
}
@@ -373,7 +368,7 @@
fun dismissingIme_whileOnPasswordBouncer_navigatesToLockscreen() =
testScope.runTest {
setAuthMethod(AuthenticationMethodModel.Password)
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Bouncer)
emulateUserDrivenTransition(
@@ -391,7 +386,7 @@
fun bouncerActionButtonClick_opensEmergencyServicesDialer() =
testScope.runTest {
setAuthMethod(AuthenticationMethodModel.Password)
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Bouncer)
emulateUserDrivenTransition(to = upDestinationSceneKey)
@@ -411,7 +406,7 @@
testScope.runTest {
setAuthMethod(AuthenticationMethodModel.Password)
startPhoneCall()
- val destinationScenes by collectLastValue(lockscreenSceneViewModel.destinationScenes)
+ val destinationScenes by collectLastValue(lockscreenSceneActionsViewModel.actions)
val upDestinationSceneKey = destinationScenes?.get(Swipe.Up)?.toScene
assertThat(upDestinationSceneKey).isEqualTo(Scenes.Bouncer)
emulateUserDrivenTransition(to = upDestinationSceneKey)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModelTest.kt
similarity index 91%
rename from packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModelTest.kt
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModelTest.kt
index a4992e2..b526275 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModelTest.kt
@@ -25,6 +25,7 @@
import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
import com.android.systemui.scene.shared.model.TransitionKeys.ToSplitShade
import com.android.systemui.shade.data.repository.shadeRepository
import com.android.systemui.shade.domain.interactor.shadeInteractor
@@ -42,25 +43,26 @@
@RunWith(AndroidJUnit4::class)
@TestableLooper.RunWithLooper
@EnableSceneContainer
-class GoneSceneViewModelTest : SysuiTestCase() {
+class GoneSceneActionsViewModelTest : SysuiTestCase() {
private val kosmos = testKosmos()
private val testScope = kosmos.testScope
private val shadeRepository by lazy { kosmos.shadeRepository }
- private lateinit var underTest: GoneSceneViewModel
+ private lateinit var underTest: GoneSceneActionsViewModel
@Before
fun setUp() {
underTest =
- GoneSceneViewModel(
+ GoneSceneActionsViewModel(
shadeInteractor = kosmos.shadeInteractor,
)
+ underTest.activateIn(testScope)
}
@Test
fun downTransitionKey_splitShadeEnabled_isGoneToSplitShade() =
testScope.runTest {
- val destinationScenes by collectLastValue(underTest.destinationScenes)
+ val destinationScenes by collectLastValue(underTest.actions)
shadeRepository.setShadeLayoutWide(true)
runCurrent()
@@ -71,7 +73,7 @@
@Test
fun downTransitionKey_splitShadeDisabled_isNull() =
testScope.runTest {
- val destinationScenes by collectLastValue(underTest.destinationScenes)
+ val destinationScenes by collectLastValue(underTest.actions)
shadeRepository.setShadeLayoutWide(false)
runCurrent()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModelTest.kt
new file mode 100644
index 0000000..206d3ac
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModelTest.kt
@@ -0,0 +1,133 @@
+/*
+ * 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.
+ */
+
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
+package com.android.systemui.scene.ui.viewmodel
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.compose.animation.scene.Back
+import com.android.compose.animation.scene.Swipe
+import com.android.compose.animation.scene.SwipeDirection
+import com.android.compose.animation.scene.UserAction
+import com.android.compose.animation.scene.UserActionResult
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SceneActionsViewModelTest : SysuiTestCase() {
+
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+
+ private val underTest = FakeSceneActionsViewModel()
+
+ @Test
+ fun actions_emptyBeforeActivation() =
+ testScope.runTest {
+ val actions by collectLastValue(underTest.actions)
+
+ assertThat(underTest.isActive).isFalse()
+ assertThat(actions).isEmpty()
+ }
+
+ @Test
+ fun actions_emptyBeforeFirstValue() =
+ testScope.runTest {
+ val actions by collectLastValue(underTest.actions)
+ underTest.activateIn(testScope)
+ runCurrent()
+
+ assertThat(underTest.isActive).isTrue()
+ assertThat(actions).isEmpty()
+ }
+
+ @Test
+ fun actions() =
+ testScope.runTest {
+ val actions by collectLastValue(underTest.actions)
+ underTest.activateIn(testScope)
+ runCurrent()
+ assertThat(underTest.isActive).isTrue()
+
+ val expected1 =
+ mapOf(
+ Back to UserActionResult(toScene = Scenes.Gone),
+ Swipe(SwipeDirection.Up) to UserActionResult(toScene = Scenes.Shade)
+ )
+ underTest.upstream.value = expected1
+ runCurrent()
+ assertThat(actions).isEqualTo(expected1)
+
+ val expected2 =
+ mapOf(
+ Back to UserActionResult(toScene = Scenes.Lockscreen),
+ Swipe(SwipeDirection.Down) to UserActionResult(toScene = Scenes.Shade)
+ )
+ underTest.upstream.value = expected2
+ runCurrent()
+ assertThat(actions).isEqualTo(expected2)
+ }
+
+ @Test
+ fun actions_emptyAfterCancellation() =
+ testScope.runTest {
+ val actions by collectLastValue(underTest.actions)
+ val job = Job()
+ underTest.activateIn(testScope, job)
+ runCurrent()
+
+ val expected =
+ mapOf(
+ Back to UserActionResult(toScene = Scenes.Lockscreen),
+ Swipe(SwipeDirection.Down) to UserActionResult(toScene = Scenes.Shade)
+ )
+ underTest.upstream.value = expected
+ runCurrent()
+ assertThat(actions).isEqualTo(expected)
+
+ job.cancel()
+ runCurrent()
+ assertThat(underTest.isActive).isFalse()
+ assertThat(actions).isEmpty()
+ }
+
+ private class FakeSceneActionsViewModel : SceneActionsViewModel() {
+
+ val upstream = MutableStateFlow<Map<UserAction, UserActionResult>>(emptyMap())
+
+ override suspend fun hydrateActions(
+ setActions: (Map<UserAction, UserActionResult>) -> Unit,
+ ) {
+ upstream.collectLatest { setActions(it) }
+ }
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModelTest.kt
index add33da..6a88664 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModelTest.kt
@@ -43,7 +43,7 @@
}
@Test
- fun transitionToOccluded() =
+ fun transitionToOccludedByOCCLUDEDTransition() =
testScope.runTest {
val isKeyguardOccluded by collectLastValue(underTest.isKeyguardOccluded)
assertThat(isKeyguardOccluded).isFalse()
@@ -62,4 +62,25 @@
)
assertThat(isKeyguardOccluded).isFalse()
}
+
+ @Test
+ fun transitionToOccludedByDREAMINGTransition() =
+ testScope.runTest {
+ val isKeyguardOccluded by collectLastValue(underTest.isKeyguardOccluded)
+ assertThat(isKeyguardOccluded).isFalse()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.DREAMING,
+ testScope,
+ )
+ assertThat(isKeyguardOccluded).isTrue()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.DREAMING,
+ to = KeyguardState.AOD,
+ testScope,
+ )
+ assertThat(isKeyguardOccluded).isFalse()
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/DozeServiceHostTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/DozeServiceHostTest.java
index 2114489..6441405 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/DozeServiceHostTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/phone/DozeServiceHostTest.java
@@ -88,7 +88,6 @@
@Mock private PowerManager mPowerManager;
@Mock private WakefulnessLifecycle mWakefullnessLifecycle;
@Mock private CentralSurfaces mCentralSurfaces;
- @Mock private NotificationIconAreaController mNotificationIconAreaController;
@Mock private NotificationShadeWindowViewController mNotificationShadeWindowViewController;
@Mock private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
@Mock private ShadeLockscreenInteractor mShadeLockscreenInteractor;
@@ -106,7 +105,7 @@
mHeadsUpManager, mBatteryController, mScrimController,
() -> mBiometricUnlockController, () -> mAssistManager, mDozeScrimController,
mKeyguardUpdateMonitor, mPulseExpansionHandler, mNotificationShadeWindowController,
- mNotificationWakeUpCoordinator, mAuthController, mNotificationIconAreaController,
+ mNotificationWakeUpCoordinator, mAuthController,
mShadeLockscreenInteractor, mDozeInteractor);
mDozeServiceHost.initialize(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/util/settings/SettingsProxyExtTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/util/settings/SettingsProxyExtTest.kt
deleted file mode 100644
index e281894..0000000
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/util/settings/SettingsProxyExtTest.kt
+++ /dev/null
@@ -1,165 +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.util.settings
-
-import android.database.ContentObserver
-import android.platform.test.annotations.DisableFlags
-import android.platform.test.annotations.EnableFlags
-import androidx.test.ext.junit.runners.AndroidJUnit4
-import androidx.test.filters.SmallTest
-import com.android.systemui.Flags
-import com.android.systemui.SysuiTestCase
-import com.android.systemui.coroutines.collectLastValue
-import com.android.systemui.kosmos.testScope
-import com.android.systemui.testKosmos
-import com.android.systemui.util.settings.SettingsProxyExt.observerFlow
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.Job
-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.Mock
-import org.mockito.MockitoAnnotations
-import org.mockito.kotlin.any
-import org.mockito.kotlin.times
-import org.mockito.kotlin.verify
-
-/** Tests for [SettingsProxyExt]. */
-@RunWith(AndroidJUnit4::class)
-@SmallTest
-@OptIn(ExperimentalCoroutinesApi::class)
-class SettingsProxyExtTest : SysuiTestCase() {
- private val kosmos = testKosmos()
- private val testScope = kosmos.testScope
- @Mock lateinit var settingsProxy: SettingsProxy
- @Mock lateinit var userSettingsProxy: UserSettingsProxy
-
- @Before
- fun setUp() {
- MockitoAnnotations.initMocks(this)
- }
-
- @Test
- @EnableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagEnabled_settingsProxy_registerContentObserverInvoked() =
- testScope.runTest {
- val unused by collectLastValue(settingsProxy.observerFlow(SETTING_1, SETTING_2))
- runCurrent()
- verify(settingsProxy, times(2))
- .registerContentObserver(any<String>(), any<ContentObserver>())
- }
-
- @Test
- @DisableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagDisabled_multipleSettings_SettingsProxy_registerContentObserverInvoked() =
- testScope.runTest {
- val unused by collectLastValue(settingsProxy.observerFlow(SETTING_1, SETTING_2))
- runCurrent()
- verify(settingsProxy, times(2))
- .registerContentObserverSync(any<String>(), any<ContentObserver>())
- }
-
- @Test
- @EnableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagEnabled_channelClosed_settingsProxy_unregisterContentObserverInvoked() =
- testScope.runTest {
- val job = Job()
- val unused by
- collectLastValue(settingsProxy.observerFlow(SETTING_1, SETTING_2), context = job)
- runCurrent()
- job.cancel()
- runCurrent()
- verify(settingsProxy).unregisterContentObserverAsync(any<ContentObserver>())
- }
-
- @Test
- @DisableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagDisabled_channelClosed_settingsProxy_unregisterContentObserverInvoked() =
- testScope.runTest {
- val job = Job()
- val unused by
- collectLastValue(settingsProxy.observerFlow(SETTING_1, SETTING_2), context = job)
- runCurrent()
- job.cancel()
- runCurrent()
- verify(settingsProxy).unregisterContentObserverSync(any<ContentObserver>())
- }
-
- @Test
- @EnableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagEnabled_userSettingsProxy_registerContentObserverForUserInvoked() =
- testScope.runTest {
- val unused by
- collectLastValue(userSettingsProxy.observerFlow(userId = 0, SETTING_1, SETTING_2))
- runCurrent()
- verify(userSettingsProxy, times(2))
- .registerContentObserverForUser(any<String>(), any<ContentObserver>(), any<Int>())
- }
-
- @Test
- @DisableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagDisabled_userSettingsProxy_registerContentObserverForUserInvoked() =
- testScope.runTest {
- val unused by
- collectLastValue(userSettingsProxy.observerFlow(userId = 0, SETTING_1, SETTING_2))
- runCurrent()
- verify(userSettingsProxy, times(2))
- .registerContentObserverForUserSync(
- any<String>(),
- any<ContentObserver>(),
- any<Int>()
- )
- }
-
- @Test
- @EnableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagEnabled_channelClosed_userSettingsProxy_unregisterContentObserverInvoked() =
- testScope.runTest {
- val job = Job()
- val unused by
- collectLastValue(
- userSettingsProxy.observerFlow(userId = 0, SETTING_1, SETTING_2),
- context = job
- )
- runCurrent()
- job.cancel()
- runCurrent()
- verify(userSettingsProxy).unregisterContentObserverAsync(any<ContentObserver>())
- }
-
- @Test
- @DisableFlags(Flags.FLAG_SETTINGS_EXT_REGISTER_CONTENT_OBSERVER_ON_BG_THREAD)
- fun observeFlow_bgFlagDisabled_channelClosed_userSettingsProxy_unregisterContentObserverInvoked() =
- testScope.runTest {
- val job = Job()
- val unused by
- collectLastValue(
- userSettingsProxy.observerFlow(userId = 0, SETTING_1, SETTING_2),
- context = job
- )
- runCurrent()
- job.cancel()
- runCurrent()
- verify(userSettingsProxy).unregisterContentObserverSync(any<ContentObserver>())
- }
-
- private companion object {
- val SETTING_1 = "settings_1"
- val SETTING_2 = "settings_2"
- }
-}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
index f688d4f..d468f2f 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
@@ -60,9 +60,7 @@
import com.android.systemui.statusbar.notification.AnimatableProperty;
import com.android.systemui.statusbar.notification.PropertyAnimator;
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerAlwaysOnDisplayViewBinder;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.AnimationProperties;
-import com.android.systemui.statusbar.phone.NotificationIconAreaController;
import com.android.systemui.statusbar.phone.NotificationIconContainer;
import com.android.systemui.util.ViewController;
import com.android.systemui.util.concurrency.DelayableExecutor;
@@ -87,7 +85,6 @@
private final StatusBarStateController mStatusBarStateController;
private final ClockRegistry mClockRegistry;
private final KeyguardSliceViewController mKeyguardSliceViewController;
- private final NotificationIconAreaController mNotificationIconAreaController;
private final LockscreenSmartspaceController mSmartspaceController;
private final SecureSettings mSecureSettings;
private final DumpManager mDumpManager;
@@ -165,7 +162,6 @@
StatusBarStateController statusBarStateController,
ClockRegistry clockRegistry,
KeyguardSliceViewController keyguardSliceViewController,
- NotificationIconAreaController notificationIconAreaController,
LockscreenSmartspaceController smartspaceController,
NotificationIconContainerAlwaysOnDisplayViewBinder nicViewBinder,
KeyguardUnlockAnimationController keyguardUnlockAnimationController,
@@ -183,7 +179,6 @@
mStatusBarStateController = statusBarStateController;
mClockRegistry = clockRegistry;
mKeyguardSliceViewController = keyguardSliceViewController;
- mNotificationIconAreaController = notificationIconAreaController;
mSmartspaceController = smartspaceController;
mNicViewBinder = nicViewBinder;
mSecureSettings = secureSettings;
@@ -351,10 +346,8 @@
int getNotificationIconAreaHeight() {
if (MigrateClocksToBlueprint.isEnabled()) {
return 0;
- } else if (NotificationIconContainerRefactor.isEnabled()) {
- return mAodIconContainer != null ? mAodIconContainer.getHeight() : 0;
} else {
- return mNotificationIconAreaController.getHeight();
+ return mAodIconContainer != null ? mAodIconContainer.getHeight() : 0;
}
}
@@ -603,16 +596,11 @@
NotificationIconContainer nic = (NotificationIconContainer)
mView.findViewById(
com.android.systemui.res.R.id.left_aligned_notification_icon_container);
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (mAodIconsBindHandle != null) {
- mAodIconsBindHandle.dispose();
- }
- if (nic != null) {
- mAodIconsBindHandle = mNicViewBinder.bindWhileAttached(nic);
- mAodIconContainer = nic;
- }
- } else {
- mNotificationIconAreaController.setupAodIcons(nic);
+ if (mAodIconsBindHandle != null) {
+ mAodIconsBindHandle.dispose();
+ }
+ if (nic != null) {
+ mAodIconsBindHandle = mNicViewBinder.bindWhileAttached(nic);
mAodIconContainer = nic;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
index fbc6470..214420d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
@@ -833,7 +833,7 @@
messageJob?.cancel()
messageJob = null
- if (helpMessage.isNotBlank()) {
+ if (helpMessage.isNotBlank() && needsUserConfirmation) {
showHelp(helpMessage)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
index 609aa39..25b6b14 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
@@ -132,7 +132,6 @@
import com.android.systemui.statusbar.phone.CentralSurfaces;
import com.android.systemui.statusbar.phone.ConfigurationControllerModule;
import com.android.systemui.statusbar.phone.LetterboxModule;
-import com.android.systemui.statusbar.phone.NotificationIconAreaControllerModule;
import com.android.systemui.statusbar.pipeline.dagger.StatusBarPipelineModule;
import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -230,7 +229,6 @@
MediaProjectionTaskSwitcherModule.class,
MediaRouterModule.class,
MotionToolModule.class,
- NotificationIconAreaControllerModule.class,
PeopleHubModule.class,
PeopleModule.class,
PluginModule.class,
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
index 59de203..1d1ac5a 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
@@ -39,14 +39,11 @@
import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.shade.shared.flag.DualShade
import com.android.systemui.statusbar.notification.collection.SortBySectionTimeFlag
-import com.android.systemui.statusbar.notification.footer.shared.FooterViewRefactor
import com.android.systemui.statusbar.notification.interruption.VisualInterruptionRefactor
import com.android.systemui.statusbar.notification.shared.NotificationAvalancheSuppression
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.shared.NotificationMinimalismPrototype
import com.android.systemui.statusbar.notification.shared.NotificationThrottleHun
import com.android.systemui.statusbar.notification.shared.NotificationsHeadsUpRefactor
-import com.android.systemui.statusbar.notification.shared.NotificationsLiveDataStoreRefactor
import com.android.systemui.statusbar.notification.shared.PriorityPeopleSection
import javax.inject.Inject
@@ -61,8 +58,6 @@
modesUi dependsOn modesApi
// Internal notification frontend dependencies
- NotificationsLiveDataStoreRefactor.token dependsOn NotificationIconContainerRefactor.token
- FooterViewRefactor.token dependsOn NotificationIconContainerRefactor.token
NotificationAvalancheSuppression.token dependsOn VisualInterruptionRefactor.token
PriorityPeopleSection.token dependsOn SortBySectionTimeFlag.token
NotificationMinimalismPrototype.token dependsOn NotificationsHeadsUpRefactor.token
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
index 80cf4c5..ba533ce 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
@@ -106,7 +106,7 @@
private val falsingManager: FalsingManager,
private val keyguardClockViewModel: KeyguardClockViewModel,
private val smartspaceViewModel: KeyguardSmartspaceViewModel,
- private val lockscreenContentViewModel: LockscreenContentViewModel,
+ private val lockscreenContentViewModelFactory: LockscreenContentViewModel.Factory,
private val lockscreenSceneBlueprintsLazy: Lazy<Set<LockscreenSceneBlueprint>>,
private val clockInteractor: KeyguardClockInteractor,
private val keyguardViewMediator: KeyguardViewMediator,
@@ -143,7 +143,7 @@
val composeView =
createLockscreen(
context = context,
- viewModel = lockscreenContentViewModel,
+ viewModelFactory = lockscreenContentViewModelFactory,
blueprints = lockscreenSceneBlueprintsLazy.get(),
)
composeView.id = View.generateViewId()
@@ -224,7 +224,7 @@
private fun createLockscreen(
context: Context,
- viewModel: LockscreenContentViewModel,
+ viewModelFactory: LockscreenContentViewModel.Factory,
blueprints: Set<@JvmSuppressWildcards LockscreenSceneBlueprint>,
): View {
val sceneBlueprints =
@@ -239,7 +239,7 @@
scene(currentScene) {
with(
LockscreenContent(
- viewModel = viewModel,
+ viewModelFactory = viewModelFactory,
blueprints = sceneBlueprints,
clockInteractor = clockInteractor
)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
index 91b66c3..aab5b9b 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
@@ -70,7 +70,6 @@
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.statusbar.CrossFadeHelper
import com.android.systemui.statusbar.VibratorHelper
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.phone.ScreenOffAnimationController
import com.android.systemui.temporarydisplay.ViewPriority
import com.android.systemui.temporarydisplay.chipbar.ChipbarCoordinator
@@ -292,20 +291,18 @@
}
}
- if (NotificationIconContainerRefactor.isEnabled) {
- launch {
- val iconsAppearTranslationPx =
- configuration
- .getDimensionPixelSize(R.dimen.shelf_appear_translation)
- .stateIn(this)
- viewModel.isNotifIconContainerVisible.collect { isVisible ->
- childViews[aodNotificationIconContainerId]
- ?.setAodNotifIconContainerIsVisible(
- isVisible,
- iconsAppearTranslationPx.value,
- screenOffAnimationController,
- )
- }
+ launch {
+ val iconsAppearTranslationPx =
+ configuration
+ .getDimensionPixelSize(R.dimen.shelf_appear_translation)
+ .stateIn(this)
+ viewModel.isNotifIconContainerVisible.collect { isVisible ->
+ childViews[aodNotificationIconContainerId]
+ ?.setAodNotifIconContainerIsVisible(
+ isVisible,
+ iconsAppearTranslationPx.value,
+ screenOffAnimationController,
+ )
}
}
@@ -519,7 +516,6 @@
if (MigrateClocksToBlueprint.isEnabled) {
throw IllegalStateException("should only be called in legacy code paths")
}
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return
coroutineScope {
val iconAppearTranslationPx =
configuration.getDimensionPixelSize(R.dimen.shelf_appear_translation).stateIn(this)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
index d77b548..36ef78e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/AodNotificationIconsSection.kt
@@ -37,8 +37,6 @@
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerViewBinder
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.StatusBarIconViewBindingFailureTracker
import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerAlwaysOnDisplayViewModel
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
import com.android.systemui.statusbar.phone.NotificationIconContainer
import com.android.systemui.statusbar.ui.SystemBarUtilsState
import com.android.systemui.util.ui.value
@@ -53,7 +51,6 @@
private val iconBindingFailureTracker: StatusBarIconViewBindingFailureTracker,
private val nicAodViewModel: NotificationIconContainerAlwaysOnDisplayViewModel,
private val nicAodIconViewStore: AlwaysOnDisplayNotificationIconViewStore,
- private val notificationIconAreaController: NotificationIconAreaController,
private val systemBarUtilsState: SystemBarUtilsState,
private val rootViewModel: KeyguardRootViewModel,
) : KeyguardSection() {
@@ -86,20 +83,16 @@
return
}
- if (NotificationIconContainerRefactor.isEnabled) {
- nicBindingDisposable?.dispose()
- nicBindingDisposable =
- NotificationIconContainerViewBinder.bindWhileAttached(
- nic,
- nicAodViewModel,
- configurationState,
- systemBarUtilsState,
- iconBindingFailureTracker,
- nicAodIconViewStore,
- )
- } else {
- notificationIconAreaController.setupAodIcons(nic)
- }
+ nicBindingDisposable?.dispose()
+ nicBindingDisposable =
+ NotificationIconContainerViewBinder.bindWhileAttached(
+ nic,
+ nicAodViewModel,
+ configurationState,
+ systemBarUtilsState,
+ iconBindingFailureTracker,
+ nicAodIconViewStore,
+ )
}
override fun applyConstraints(constraintSet: ConstraintSet) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
index 3fffeff..59cb6e5 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModel.kt
@@ -20,40 +20,43 @@
import com.android.compose.animation.scene.ContentKey
import com.android.internal.annotations.VisibleForTesting
import com.android.systemui.biometrics.AuthController
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.keyguard.domain.interactor.KeyguardBlueprintInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardClockInteractor
import com.android.systemui.keyguard.shared.model.ClockSize
+import com.android.systemui.lifecycle.SysUiViewModel
import com.android.systemui.res.R
import com.android.systemui.scene.domain.interactor.SceneContainerOcclusionInteractor
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.unfold.domain.interactor.UnfoldTransitionInteractor
-import javax.inject.Inject
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
-@SysUISingleton
class LockscreenContentViewModel
-@Inject
+@AssistedInject
constructor(
clockInteractor: KeyguardClockInteractor,
private val interactor: KeyguardBlueprintInteractor,
private val authController: AuthController,
val touchHandling: KeyguardTouchHandlingViewModel,
- val shadeInteractor: ShadeInteractor,
- @Application private val applicationScope: CoroutineScope,
- unfoldTransitionInteractor: UnfoldTransitionInteractor,
- occlusionInteractor: SceneContainerOcclusionInteractor,
-) {
+ private val shadeInteractor: ShadeInteractor,
+ private val unfoldTransitionInteractor: UnfoldTransitionInteractor,
+ private val occlusionInteractor: SceneContainerOcclusionInteractor,
+) : SysUiViewModel() {
@VisibleForTesting val clockSize = clockInteractor.clockSize
val isUdfpsVisible: Boolean
@@ -61,32 +64,36 @@
val isShadeLayoutWide: StateFlow<Boolean> = shadeInteractor.isShadeLayoutWide
+ private val _unfoldTranslations = MutableStateFlow(UnfoldTranslations())
/** Amount of horizontal translation that should be applied to elements in the scene. */
- val unfoldTranslations: StateFlow<UnfoldTranslations> =
- combine(
- unfoldTransitionInteractor.unfoldTranslationX(isOnStartSide = true),
- unfoldTransitionInteractor.unfoldTranslationX(isOnStartSide = false),
- ) { start, end ->
- UnfoldTranslations(
- start = start,
- end = end,
- )
- }
- .stateIn(
- scope = applicationScope,
- started = SharingStarted.WhileSubscribed(),
- initialValue = UnfoldTranslations(),
- )
+ val unfoldTranslations: StateFlow<UnfoldTranslations> = _unfoldTranslations.asStateFlow()
+ private val _isContentVisible = MutableStateFlow(true)
/** Whether the content of the scene UI should be shown. */
- val isContentVisible: StateFlow<Boolean> =
- occlusionInteractor.isOccludingActivityShown
- .map { !it }
- .stateIn(
- scope = applicationScope,
- started = SharingStarted.WhileSubscribed(),
- initialValue = true,
- )
+ val isContentVisible: StateFlow<Boolean> = _isContentVisible.asStateFlow()
+
+ override suspend fun onActivated() {
+ coroutineScope {
+ launch {
+ combine(
+ unfoldTransitionInteractor.unfoldTranslationX(isOnStartSide = true),
+ unfoldTransitionInteractor.unfoldTranslationX(isOnStartSide = false),
+ ) { start, end ->
+ UnfoldTranslations(
+ start = start,
+ end = end,
+ )
+ }
+ .collectLatest { _unfoldTranslations.value = it }
+ }
+
+ launch {
+ occlusionInteractor.isOccludingActivityShown
+ .map { !it }
+ .collectLatest { _isContentVisible.value = it }
+ }
+ }
+ }
/**
* Returns a flow that indicates whether lockscreen notifications should be rendered in the
@@ -142,4 +149,9 @@
*/
val end: Float = 0f,
)
+
+ @AssistedFactory
+ interface Factory {
+ fun create(): LockscreenContentViewModel
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModel.kt
new file mode 100644
index 0000000..7383f57
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneActionsViewModel.kt
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.Swipe
+import com.android.compose.animation.scene.SwipeDirection
+import com.android.compose.animation.scene.UserAction
+import com.android.compose.animation.scene.UserActionResult
+import com.android.systemui.communal.domain.interactor.CommunalInteractor
+import com.android.systemui.deviceentry.domain.interactor.DeviceEntryInteractor
+import com.android.systemui.scene.shared.model.SceneFamilies
+import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.scene.shared.model.TransitionKeys.ToSplitShade
+import com.android.systemui.scene.ui.viewmodel.SceneActionsViewModel
+import com.android.systemui.shade.domain.interactor.ShadeInteractor
+import com.android.systemui.shade.shared.model.ShadeMode
+import com.android.systemui.util.kotlin.filterValuesNotNull
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+
+/** Models UI state and handles user input for the lockscreen scene. */
+class LockscreenSceneActionsViewModel
+@AssistedInject
+constructor(
+ private val deviceEntryInteractor: DeviceEntryInteractor,
+ private val communalInteractor: CommunalInteractor,
+ private val shadeInteractor: ShadeInteractor,
+) : SceneActionsViewModel() {
+
+ override suspend fun hydrateActions(setActions: (Map<UserAction, UserActionResult>) -> Unit) {
+ shadeInteractor.isShadeTouchable
+ .flatMapLatest { isShadeTouchable ->
+ if (!isShadeTouchable) {
+ flowOf(emptyMap())
+ } else {
+ combine(
+ deviceEntryInteractor.isUnlocked,
+ communalInteractor.isCommunalAvailable,
+ shadeInteractor.shadeMode,
+ ) { isDeviceUnlocked, isCommunalAvailable, shadeMode ->
+ val notifShadeSceneKey =
+ UserActionResult(
+ toScene = SceneFamilies.NotifShade,
+ transitionKey =
+ ToSplitShade.takeIf { shadeMode is ShadeMode.Split },
+ )
+
+ mapOf(
+ Swipe.Left to
+ UserActionResult(Scenes.Communal).takeIf {
+ isCommunalAvailable
+ },
+ Swipe.Up to if (isDeviceUnlocked) Scenes.Gone else Scenes.Bouncer,
+
+ // Swiping down from the top edge goes to QS (or shade if in split
+ // shade mode).
+ swipeDownFromTop(pointerCount = 1) to
+ if (shadeMode is ShadeMode.Single) {
+ UserActionResult(Scenes.QuickSettings)
+ } else {
+ notifShadeSceneKey
+ },
+
+ // TODO(b/338577208): Remove once we add Dual Shade invocation zones
+ swipeDownFromTop(pointerCount = 2) to
+ UserActionResult(
+ toScene = SceneFamilies.QuickSettings,
+ transitionKey =
+ ToSplitShade.takeIf { shadeMode is ShadeMode.Split }
+ ),
+
+ // Swiping down, not from the edge, always navigates to the notif
+ // shade scene.
+ swipeDown(pointerCount = 1) to notifShadeSceneKey,
+ swipeDown(pointerCount = 2) to notifShadeSceneKey,
+ )
+ .filterValuesNotNull()
+ }
+ }
+ }
+ .collectLatest { setActions(it) }
+ }
+
+ private fun swipeDownFromTop(pointerCount: Int): Swipe {
+ return Swipe(
+ SwipeDirection.Down,
+ fromSource = Edge.Top,
+ pointerCount = pointerCount,
+ )
+ }
+
+ private fun swipeDown(pointerCount: Int): Swipe {
+ return Swipe(
+ SwipeDirection.Down,
+ pointerCount = pointerCount,
+ )
+ }
+
+ @AssistedFactory
+ interface Factory {
+ fun create(): LockscreenSceneActionsViewModel
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt
deleted file mode 100644
index 15892e9..0000000
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt
+++ /dev/null
@@ -1,116 +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.
- */
-
-@file:OptIn(ExperimentalCoroutinesApi::class)
-
-package com.android.systemui.keyguard.ui.viewmodel
-
-import com.android.compose.animation.scene.Edge
-import com.android.compose.animation.scene.Swipe
-import com.android.compose.animation.scene.SwipeDirection
-import com.android.compose.animation.scene.UserAction
-import com.android.compose.animation.scene.UserActionResult
-import com.android.systemui.communal.domain.interactor.CommunalInteractor
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.deviceentry.domain.interactor.DeviceEntryInteractor
-import com.android.systemui.scene.shared.model.SceneFamilies
-import com.android.systemui.scene.shared.model.Scenes
-import com.android.systemui.scene.shared.model.TransitionKeys.ToSplitShade
-import com.android.systemui.shade.domain.interactor.ShadeInteractor
-import com.android.systemui.shade.shared.model.ShadeMode
-import com.android.systemui.statusbar.notification.stack.ui.viewmodel.NotificationsPlaceholderViewModel
-import com.android.systemui.util.kotlin.filterValuesNotNull
-import javax.inject.Inject
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.flatMapLatest
-import kotlinx.coroutines.flow.flowOf
-
-/** Models UI state and handles user input for the lockscreen scene. */
-@SysUISingleton
-class LockscreenSceneViewModel
-@Inject
-constructor(
- private val deviceEntryInteractor: DeviceEntryInteractor,
- private val communalInteractor: CommunalInteractor,
- private val shadeInteractor: ShadeInteractor,
- val touchHandling: KeyguardTouchHandlingViewModel,
- val notifications: NotificationsPlaceholderViewModel,
-) {
- val destinationScenes: Flow<Map<UserAction, UserActionResult>> =
- shadeInteractor.isShadeTouchable.flatMapLatest { isShadeTouchable ->
- if (!isShadeTouchable) {
- flowOf(emptyMap())
- } else {
- combine(
- deviceEntryInteractor.isUnlocked,
- communalInteractor.isCommunalAvailable,
- shadeInteractor.shadeMode,
- ) { isDeviceUnlocked, isCommunalAvailable, shadeMode ->
- val notifShadeSceneKey =
- UserActionResult(
- toScene = SceneFamilies.NotifShade,
- transitionKey = ToSplitShade.takeIf { shadeMode is ShadeMode.Split },
- )
-
- mapOf(
- Swipe.Left to
- UserActionResult(Scenes.Communal).takeIf { isCommunalAvailable },
- Swipe.Up to if (isDeviceUnlocked) Scenes.Gone else Scenes.Bouncer,
-
- // Swiping down from the top edge goes to QS (or shade if in split shade
- // mode).
- swipeDownFromTop(pointerCount = 1) to
- if (shadeMode is ShadeMode.Single) {
- UserActionResult(Scenes.QuickSettings)
- } else {
- notifShadeSceneKey
- },
-
- // TODO(b/338577208): Remove once we add Dual Shade invocation zones.
- swipeDownFromTop(pointerCount = 2) to
- UserActionResult(
- toScene = SceneFamilies.QuickSettings,
- transitionKey =
- ToSplitShade.takeIf { shadeMode is ShadeMode.Split }
- ),
-
- // Swiping down, not from the edge, always navigates to the notif shade
- // scene.
- swipeDown(pointerCount = 1) to notifShadeSceneKey,
- swipeDown(pointerCount = 2) to notifShadeSceneKey,
- )
- .filterValuesNotNull()
- }
- }
- }
-
- private fun swipeDownFromTop(pointerCount: Int): Swipe {
- return Swipe(
- SwipeDirection.Down,
- fromSource = Edge.Top,
- pointerCount = pointerCount,
- )
- }
-
- private fun swipeDown(pointerCount: Int): Swipe {
- return Swipe(
- SwipeDirection.Down,
- pointerCount = pointerCount,
- )
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/views/buttons/KeyButtonView.java b/packages/SystemUI/src/com/android/systemui/navigationbar/views/buttons/KeyButtonView.java
index 133d14d..111a2d4 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/views/buttons/KeyButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/views/buttons/KeyButtonView.java
@@ -21,6 +21,7 @@
import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK;
import static android.view.accessibility.AccessibilityNodeInfo.ACTION_LONG_CLICK;
+import android.annotation.Nullable;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
@@ -49,6 +50,7 @@
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.inputmethod.Flags;
import android.widget.ImageView;
import com.android.internal.annotations.VisibleForTesting;
@@ -231,15 +233,28 @@
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
- if (mCode != KEYCODE_UNKNOWN) {
+ if (isClickable()) {
info.addAction(new AccessibilityNodeInfo.AccessibilityAction(ACTION_CLICK, null));
if (isLongClickable()) {
info.addAction(
- new AccessibilityNodeInfo.AccessibilityAction(ACTION_LONG_CLICK, null));
+ new AccessibilityNodeInfo.AccessibilityAction(ACTION_LONG_CLICK,
+ getAccessibilityLongClickActionLabel()));
}
}
}
+ /**
+ * Gets the accessibility long click action label for the button, or {@code null} for no label.
+ */
+ @Nullable
+ private CharSequence getAccessibilityLongClickActionLabel() {
+ if (Flags.imeSwitcherRevamp() && getId() == R.id.ime_switcher) {
+ return getContext().getText(
+ com.android.internal.R.string.input_method_ime_switch_long_click_action_desc);
+ }
+ return null;
+ }
+
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
index 8d0a386..432a35a 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
@@ -16,7 +16,9 @@
package com.android.systemui.recents;
+import static com.android.systemui.Flags.enableViewCaptureTracing;
import static com.android.systemui.shared.recents.utilities.Utilities.isLargeScreen;
+import static com.android.systemui.util.ConvenienceExtensionsKt.toKotlinLazy;
import static com.android.systemui.util.leak.RotationUtils.ROTATION_LANDSCAPE;
import static com.android.systemui.util.leak.RotationUtils.ROTATION_NONE;
import static com.android.systemui.util.leak.RotationUtils.ROTATION_SEASCAPE;
@@ -53,6 +55,8 @@
import androidx.annotation.NonNull;
+import com.android.app.viewcapture.ViewCapture;
+import com.android.app.viewcapture.ViewCaptureAwareWindowManager;
import com.android.systemui.CoreStartable;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dagger.SysUISingleton;
@@ -83,6 +87,7 @@
private final Lazy<NavigationBarController> mNavigationBarControllerLazy;
private final AccessibilityManager mAccessibilityService;
private final WindowManager mWindowManager;
+ private final ViewCaptureAwareWindowManager mViewCaptureAwareWindowManager;
private final BroadcastDispatcher mBroadcastDispatcher;
private final UserTracker mUserTracker;
@@ -106,13 +111,16 @@
NavigationModeController navigationModeController,
Lazy<NavigationBarController> navigationBarControllerLazy,
BroadcastDispatcher broadcastDispatcher,
- UserTracker userTracker) {
+ UserTracker userTracker,
+ Lazy<ViewCapture> daggerLazyViewCapture) {
mContext = context;
mNavigationBarControllerLazy = navigationBarControllerLazy;
mAccessibilityService = (AccessibilityManager)
mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
mWindowManager = (WindowManager)
mContext.getSystemService(Context.WINDOW_SERVICE);
+ mViewCaptureAwareWindowManager = new ViewCaptureAwareWindowManager(mWindowManager,
+ toKotlinLazy(daggerLazyViewCapture), enableViewCaptureTracing());
mNavBarMode = navigationModeController.addListener(this);
mBroadcastDispatcher = broadcastDispatcher;
mUserTracker = userTracker;
@@ -123,7 +131,7 @@
public void clearPrompt() {
if (mRequestWindow != null) {
- mWindowManager.removeView(mRequestWindow);
+ mViewCaptureAwareWindowManager.removeView(mRequestWindow);
mRequestWindow = null;
}
}
@@ -144,7 +152,7 @@
// show the confirmation
WindowManager.LayoutParams lp = getWindowLayoutParams();
- mWindowManager.addView(mRequestWindow, lp);
+ mViewCaptureAwareWindowManager.addView(mRequestWindow, lp);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModel.kt
new file mode 100644
index 0000000..b707a5a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneActionsViewModel.kt
@@ -0,0 +1,92 @@
+/*
+ * 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.scene.ui.viewmodel
+
+import androidx.compose.ui.Alignment
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.Swipe
+import com.android.compose.animation.scene.SwipeDirection
+import com.android.compose.animation.scene.UserAction
+import com.android.compose.animation.scene.UserActionResult
+import com.android.systemui.scene.shared.model.SceneFamilies
+import com.android.systemui.scene.shared.model.TransitionKeys.OpenBottomShade
+import com.android.systemui.scene.shared.model.TransitionKeys.ToSplitShade
+import com.android.systemui.shade.domain.interactor.ShadeInteractor
+import com.android.systemui.shade.shared.model.ShadeMode
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.map
+
+class GoneSceneActionsViewModel
+@AssistedInject
+constructor(
+ private val shadeInteractor: ShadeInteractor,
+) : SceneActionsViewModel() {
+
+ override suspend fun hydrateActions(setActions: (Map<UserAction, UserActionResult>) -> Unit) {
+ shadeInteractor.shadeMode
+ .map { shadeMode ->
+ buildMap<UserAction, UserActionResult> {
+ if (
+ shadeMode is ShadeMode.Single ||
+ // TODO(b/338577208): Remove this once we add Dual Shade invocation
+ // zones.
+ shadeMode is ShadeMode.Dual
+ ) {
+ if (shadeInteractor.shadeAlignment == Alignment.BottomEnd) {
+ put(
+ Swipe(
+ pointerCount = 2,
+ fromSource = Edge.Bottom,
+ direction = SwipeDirection.Up,
+ ),
+ UserActionResult(SceneFamilies.QuickSettings, OpenBottomShade)
+ )
+ } else {
+ put(
+ Swipe(
+ pointerCount = 2,
+ fromSource = Edge.Top,
+ direction = SwipeDirection.Down,
+ ),
+ UserActionResult(SceneFamilies.QuickSettings)
+ )
+ }
+ }
+
+ if (shadeInteractor.shadeAlignment == Alignment.BottomEnd) {
+ put(Swipe.Up, UserActionResult(SceneFamilies.NotifShade, OpenBottomShade))
+ } else {
+ put(
+ Swipe.Down,
+ UserActionResult(
+ SceneFamilies.NotifShade,
+ ToSplitShade.takeIf { shadeMode is ShadeMode.Split }
+ )
+ )
+ }
+ }
+ }
+ .collectLatest { setActions(it) }
+ }
+
+ @AssistedFactory
+ interface Factory {
+ fun create(): GoneSceneActionsViewModel
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModel.kt
deleted file mode 100644
index b739ffe..0000000
--- a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/GoneSceneViewModel.kt
+++ /dev/null
@@ -1,83 +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.scene.ui.viewmodel
-
-import androidx.compose.ui.Alignment
-import com.android.compose.animation.scene.Edge
-import com.android.compose.animation.scene.Swipe
-import com.android.compose.animation.scene.SwipeDirection
-import com.android.compose.animation.scene.UserAction
-import com.android.compose.animation.scene.UserActionResult
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.scene.shared.model.SceneFamilies
-import com.android.systemui.scene.shared.model.TransitionKeys.OpenBottomShade
-import com.android.systemui.scene.shared.model.TransitionKeys.ToSplitShade
-import com.android.systemui.shade.domain.interactor.ShadeInteractor
-import com.android.systemui.shade.shared.model.ShadeMode
-import javax.inject.Inject
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
-
-@SysUISingleton
-class GoneSceneViewModel
-@Inject
-constructor(
- private val shadeInteractor: ShadeInteractor,
-) {
- val destinationScenes: Flow<Map<UserAction, UserActionResult>> =
- shadeInteractor.shadeMode.map { shadeMode ->
- buildMap {
- if (
- shadeMode is ShadeMode.Single ||
- // TODO(b/338577208): Remove this once we add Dual Shade invocation zones.
- shadeMode is ShadeMode.Dual
- ) {
- if (shadeInteractor.shadeAlignment == Alignment.BottomEnd) {
- put(
- Swipe(
- pointerCount = 2,
- fromSource = Edge.Bottom,
- direction = SwipeDirection.Up,
- ),
- UserActionResult(SceneFamilies.QuickSettings, OpenBottomShade)
- )
- } else {
- put(
- Swipe(
- pointerCount = 2,
- fromSource = Edge.Top,
- direction = SwipeDirection.Down,
- ),
- UserActionResult(SceneFamilies.QuickSettings)
- )
- }
- }
-
- if (shadeInteractor.shadeAlignment == Alignment.BottomEnd) {
- put(Swipe.Up, UserActionResult(SceneFamilies.NotifShade, OpenBottomShade))
- } else {
- put(
- Swipe.Down,
- UserActionResult(
- SceneFamilies.NotifShade,
- ToSplitShade.takeIf { shadeMode is ShadeMode.Split }
- )
- )
- }
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModel.kt
new file mode 100644
index 0000000..c2fd65b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneActionsViewModel.kt
@@ -0,0 +1,67 @@
+/*
+ * 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.scene.ui.viewmodel
+
+import com.android.compose.animation.scene.UserAction
+import com.android.compose.animation.scene.UserActionResult
+import com.android.systemui.lifecycle.SysUiViewModel
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Base class for view-models that need to keep a map of scene actions (also known as "destination
+ * scenes") up-to-date.
+ *
+ * Subclasses need only to override [hydrateActions], suspending forever if they need; they don't
+ * need to worry about resetting the value of [actions] when the view-model is deactivated/canceled,
+ * this base class takes care of it.
+ */
+abstract class SceneActionsViewModel : SysUiViewModel() {
+
+ private val _actions = MutableStateFlow<Map<UserAction, UserActionResult>>(emptyMap())
+ /**
+ * [UserActionResult] by [UserAction] to be collected by the scene container to enable the right
+ * user input/gestures.
+ */
+ val actions: StateFlow<Map<UserAction, UserActionResult>> = _actions.asStateFlow()
+
+ final override suspend fun onActivated() {
+ try {
+ hydrateActions { state -> _actions.value = state }
+ awaitCancellation()
+ } finally {
+ _actions.value = emptyMap()
+ }
+ }
+
+ /**
+ * Keeps the user actions up-to-date (AKA "hydrated").
+ *
+ * Subclasses should implement this `suspend fun` by running coroutine work and calling
+ * [setActions] each time the actions should be published/updated. The work can safely suspend
+ * forever; the base class will take care of canceling it as needed. There's no need to handle
+ * cancellation in this method.
+ *
+ * The base class will also take care of resetting the [actions] flow back to the default value
+ * when this happens.
+ */
+ protected abstract suspend fun hydrateActions(
+ setActions: (Map<UserAction, UserActionResult>) -> Unit,
+ )
+}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 257390f..104d4b5 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -1097,14 +1097,6 @@
}
@Override
- public void onPulseExpansionAmountChanged(boolean expandingChanged) {
- if (mKeyguardBypassController.getBypassEnabled()) {
- // Position the notifications while dragging down while pulsing
- requestScrollerTopPaddingUpdate(false /* animate */);
- }
- }
-
- @Override
public void onDelayedDozeAmountAnimationRunning(boolean running) {
// On running OR finished, the animation is no longer waiting to play
setWillPlayDelayedDozeAmountAnimation(false);
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModel.kt b/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModel.kt
index e1289af..2f98488 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/NotificationShadeWindowModel.kt
@@ -17,8 +17,11 @@
package com.android.systemui.shade.ui.viewmodel
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
import com.android.systemui.keyguard.shared.model.KeyguardState.OCCLUDED
+import com.android.systemui.util.kotlin.BooleanFlowOperators.anyOf
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
@@ -29,7 +32,11 @@
@Inject
constructor(
keyguardTransitionInteractor: KeyguardTransitionInteractor,
+ keyguardInteractor: KeyguardInteractor,
) {
val isKeyguardOccluded: Flow<Boolean> =
- keyguardTransitionInteractor.transitionValue(OCCLUDED).map { it == 1f }
+ anyOf(
+ keyguardTransitionInteractor.transitionValue(OCCLUDED).map { it == 1f },
+ keyguardTransitionInteractor.transitionValue(DREAMING).map { it == 1f },
+ )
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
index 49743bf..ccea254 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
@@ -35,7 +35,6 @@
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.PipelineDumpable;
import com.android.systemui.statusbar.notification.collection.PipelineDumper;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.phone.CentralSurfaces;
import com.android.systemui.statusbar.phone.NotificationListenerWithPlugins;
import com.android.systemui.util.time.SystemClock;
@@ -66,7 +65,6 @@
private final SystemClock mSystemClock;
private final Executor mMainExecutor;
private final List<NotificationHandler> mNotificationHandlers = new ArrayList<>();
- private final ArrayList<NotificationSettingsListener> mSettingsListeners = new ArrayList<>();
private final Deque<RankingMap> mRankingMapQueue = new ConcurrentLinkedDeque<>();
private final Runnable mDispatchRankingUpdateRunnable = this::dispatchRankingUpdate;
@@ -99,13 +97,6 @@
mNotificationHandlers.add(handler);
}
- /** Registers a listener that's notified when any notification-related settings change. */
- @Deprecated
- public void addNotificationSettingsListener(NotificationSettingsListener listener) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mSettingsListeners.add(listener);
- }
-
@Override
public void onListenerConnected() {
if (DEBUG) Log.d(TAG, "onListenerConnected");
@@ -237,13 +228,7 @@
@Override
public void onSilentStatusBarIconsVisibilityChanged(boolean hideSilentStatusIcons) {
- if (NotificationIconContainerRefactor.isEnabled()) {
- mStatusIconInteractor.setHideSilentStatusIcons(hideSilentStatusIcons);
- } else {
- for (NotificationSettingsListener listener : mSettingsListeners) {
- listener.onStatusBarIconsBehaviorChanged(hideSilentStatusIcons);
- }
- }
+ mStatusIconInteractor.setHideSilentStatusIcons(hideSilentStatusIcons);
}
public final void unsnoozeNotification(@NonNull String key) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 28e3a83..696e222 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -48,7 +48,6 @@
import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.ExpandableView;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.AmbientState;
import com.android.systemui.statusbar.notification.stack.AnimationProperties;
import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
@@ -153,11 +152,7 @@
R.dimen.notification_corner_animation_distance);
mEnableNotificationClipping = res.getBoolean(R.bool.notification_enable_clipping);
- if (NotificationIconContainerRefactor.isEnabled()) {
- mShelfIcons.setOverrideIconColor(true);
- } else {
- mShelfIcons.setInNotificationIconShelf(true);
- }
+ mShelfIcons.setOverrideIconColor(true);
if (!mShowNotificationShelf) {
setVisibility(GONE);
}
@@ -228,9 +223,6 @@
} else {
viewState.setAlpha(1f - ambientState.getHideAmount());
}
- if (!NotificationIconContainerRefactor.isEnabled()) {
- viewState.belowSpeedBump = getSpeedBumpIndex() == 0;
- }
viewState.hideSensitive = false;
viewState.setXTranslation(getTranslationX());
viewState.hasItemsInStableShelf = lastViewState.inShelf;
@@ -276,30 +268,7 @@
}
}
- private int getSpeedBumpIndex() {
- NotificationIconContainerRefactor.assertInLegacyMode();
- return mHostLayout.getSpeedBumpIndex();
- }
-
- /**
- * @param fractionToShade Fraction of lockscreen to shade transition
- * @param shortestWidth Shortest width to use for lockscreen shelf
- */
- @VisibleForTesting
- public void updateActualWidth(float fractionToShade, float shortestWidth) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- final float actualWidth = mAmbientState.isOnKeyguard()
- ? MathUtils.lerp(shortestWidth, getWidth(), fractionToShade)
- : getWidth();
- setBackgroundWidth((int) actualWidth);
- if (mShelfIcons != null) {
- mShelfIcons.setActualLayoutWidth((int) actualWidth);
- }
- mActualWidth = actualWidth;
- }
-
private void setActualWidth(float actualWidth) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
setBackgroundWidth((int) actualWidth);
if (mShelfIcons != null) {
mShelfIcons.setActualLayoutWidth((int) actualWidth);
@@ -482,25 +451,17 @@
final float fractionToShade = Interpolators.STANDARD.getInterpolation(
mAmbientState.getFractionToShade());
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (mAmbientState.isOnKeyguard()) {
- float numViews = MathUtils.min(numViewsInShelf, mMaxIconsOnLockscreen + 1);
- float shortestWidth = mShelfIcons.calculateWidthFor(numViews);
- float actualWidth = MathUtils.lerp(shortestWidth, getWidth(), fractionToShade);
- setActualWidth(actualWidth);
- } else {
- setActualWidth(getWidth());
- }
+ if (mAmbientState.isOnKeyguard()) {
+ float numViews = MathUtils.min(numViewsInShelf, mMaxIconsOnLockscreen + 1);
+ float shortestWidth = mShelfIcons.calculateWidthFor(numViews);
+ float actualWidth = MathUtils.lerp(shortestWidth, getWidth(), fractionToShade);
+ setActualWidth(actualWidth);
} else {
- final float shortestWidth = mShelfIcons.calculateWidthFor(numViewsInShelf);
- updateActualWidth(fractionToShade, shortestWidth);
+ setActualWidth(getWidth());
}
// TODO(b/172289889) transition last icon in shelf to notification icon and vice versa.
setVisibility(isHidden ? View.INVISIBLE : View.VISIBLE);
- if (!NotificationIconContainerRefactor.isEnabled()) {
- mShelfIcons.setSpeedBumpIndex(getSpeedBumpIndex());
- }
mShelfIcons.calculateIconXTranslations();
mShelfIcons.applyIconStates();
for (int i = 0; i < getHostLayoutChildCount(); i++) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
index bbf0ae1..3068460 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
@@ -64,7 +64,6 @@
import com.android.systemui.statusbar.notification.NotificationContentDescription;
import com.android.systemui.statusbar.notification.NotificationDozeHelper;
import com.android.systemui.statusbar.notification.NotificationUtils;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.util.drawable.DrawableSize;
import java.lang.annotation.Retention;
@@ -906,12 +905,7 @@
return mDotAppearAmount;
}
- public void setDozing(boolean dozing, boolean animate, long delay) {
- setDozing(dozing, animate, delay, /* onChildCompleted= */ null);
- }
-
public void setTintAlpha(float tintAlpha) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
setDozeAmount(tintAlpha);
}
@@ -921,15 +915,6 @@
updateIconColor();
}
- public void setDozing(boolean dozing, boolean animate, long delay,
- @Nullable Runnable endRunnable) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mDozer.setDozing(f -> {
- setDozeAmount(f);
- updateAllowAnimation();
- }, dozing, animate, delay, this, endRunnable);
- }
-
private void updateAllowAnimation() {
if (mDozeAmount == 0 || mDozeAmount == 1) {
setAllowAnimation(mDozeAmount == 0);
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 9240c1c..22c537c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
@@ -34,7 +34,6 @@
import com.android.systemui.statusbar.StatusBarState
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.notification.domain.interactor.NotificationsKeyguardInteractor
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController
import com.android.systemui.statusbar.notification.stack.StackStateAnimator
import com.android.systemui.statusbar.phone.DozeParameters
@@ -223,11 +222,6 @@
val nowExpanding = isPulseExpanding()
val changed = nowExpanding != pulseExpanding
pulseExpanding = nowExpanding
- if (!NotificationIconContainerRefactor.isEnabled) {
- for (listener in wakeUpListeners) {
- listener.onPulseExpansionAmountChanged(changed)
- }
- }
if (changed) {
for (listener in wakeUpListeners) {
listener.onPulseExpandingChanged(pulseExpanding)
@@ -683,17 +677,6 @@
fun onFullyHiddenChanged(isFullyHidden: Boolean) {}
/**
- * Called whenever the pulseExpansion changes
- *
- * @param expandingChanged if the user has started or stopped expanding
- */
- @Deprecated(
- message = "Use onPulseExpandedChanged instead.",
- replaceWith = ReplaceWith("onPulseExpandedChanged"),
- )
- fun onPulseExpansionAmountChanged(expandingChanged: Boolean) {}
-
- /**
* Called when the animator started by [scheduleDelayedDozeAmountAnimation] begins running
* after the start delay, or after it ends/is cancelled.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
index 1511abd..f74c9a6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
@@ -28,9 +28,7 @@
import com.android.systemui.statusbar.notification.domain.interactor.ActiveNotificationsInteractor
import com.android.systemui.statusbar.notification.domain.interactor.RenderNotificationListInteractor
import com.android.systemui.statusbar.notification.footer.shared.FooterViewRefactor
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.stack.BUCKET_SILENT
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
import com.android.systemui.statusbar.policy.SensitiveNotificationProtectionController
import javax.inject.Inject
@@ -43,7 +41,6 @@
@Inject
internal constructor(
private val groupExpansionManagerImpl: GroupExpansionManagerImpl,
- private val notificationIconAreaController: NotificationIconAreaController,
private val renderListInteractor: RenderNotificationListInteractor,
private val activeNotificationsInteractor: ActiveNotificationsInteractor,
private val sensitiveNotificationProtectionController:
@@ -63,12 +60,7 @@
} else {
controller.setNotifStats(notifStats)
}
- if (NotificationIconContainerRefactor.isEnabled || FooterViewRefactor.isEnabled) {
- renderListInteractor.setRenderedList(entries)
- }
- if (!NotificationIconContainerRefactor.isEnabled) {
- notificationIconAreaController.updateNotificationIcons(entries)
- }
+ renderListInteractor.setRenderedList(entries)
}
private fun calculateNotifStats(entries: List<ListEntry>): NotifStats {
@@ -76,9 +68,10 @@
var hasClearableAlertingNotifs = false
var hasNonClearableSilentNotifs = false
var hasClearableSilentNotifs = false
- val isSensitiveContentProtectionActive = screenshareNotificationHiding() &&
- screenshareNotificationHidingBugFix() &&
- sensitiveNotificationProtectionController.isSensitiveStateActive
+ val isSensitiveContentProtectionActive =
+ screenshareNotificationHiding() &&
+ screenshareNotificationHidingBugFix() &&
+ sensitiveNotificationProtectionController.isSensitiveStateActive
entries.forEach {
val section = checkNotNull(it.section) { "Null section for ${it.key}" }
val entry = checkNotNull(it.representativeEntry) { "Null notif entry for ${it.key}" }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt
deleted file mode 100644
index 1bcab3f..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.statusbar.notification.icon.ui.viewbinder
-
-import android.content.Context
-import android.graphics.Rect
-import android.view.View
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.StatusBarIconView
-import com.android.systemui.statusbar.notification.collection.ListEntry
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
-import com.android.systemui.statusbar.phone.NotificationIconContainer
-import javax.inject.Inject
-
-/**
- * Controller class for [NotificationIconContainer]. This implementation serves as a temporary
- * wrapper around [NotificationIconContainerViewBinder], so that external code can continue to
- * depend on the [NotificationIconAreaController] interface. Once
- * [LegacyNotificationIconAreaControllerImpl] is removed, this class can go away and the ViewBinder
- * can be used directly.
- */
-@SysUISingleton
-class NotificationIconAreaControllerViewBinderWrapperImpl @Inject constructor() :
- NotificationIconAreaController {
-
- /** Called by the Keyguard*ViewController whose view contains the aod icons. */
- override fun setupAodIcons(aodIcons: NotificationIconContainer?) = unsupported
-
- override fun setShelfIcons(icons: NotificationIconContainer) = unsupported
-
- override fun onDensityOrFontScaleChanged(context: Context) = unsupported
-
- /** Returns the view that represents the notification area. */
- override fun getNotificationInnerAreaView(): View? = unsupported
-
- /** Updates the notifications with the given list of notifications to display. */
- override fun updateNotificationIcons(entries: List<ListEntry>) = unsupported
-
- override fun updateAodNotificationIcons() = unsupported
-
- override fun showIconIsolated(icon: StatusBarIconView?, animated: Boolean) = unsupported
-
- override fun setIsolatedIconLocation(iconDrawingRect: Rect, requireStateUpdate: Boolean) =
- unsupported
-
- override fun setAnimationsEnabled(enabled: Boolean) = unsupported
-
- override fun onThemeChanged() = unsupported
-
- override fun getHeight(): Int = unsupported
-
- companion object {
- val unsupported: Nothing
- get() =
- error(
- "Code path not supported when ${NotificationIconContainerRefactor.FLAG_NAME}" +
- " is disabled"
- )
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/StatusBarIconViewBindingFailureTracker.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/StatusBarIconViewBindingFailureTracker.kt
index 0c114a2..931381f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/StatusBarIconViewBindingFailureTracker.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/StatusBarIconViewBindingFailureTracker.kt
@@ -17,7 +17,6 @@
import com.android.systemui.CoreStartable
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.util.asIndenting
import com.android.systemui.util.printCollection
import dagger.Binds
@@ -40,7 +39,6 @@
}
override fun dump(pw: PrintWriter, args: Array<out String>) {
- if (!NotificationIconContainerRefactor.isEnabled) return
pw.asIndenting().run {
printCollection("AOD Icon binding failures:", aodFailures)
printCollection("Status Bar Icon binding failures:", statusBarFailures)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
index d2d0aaa..560028c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
@@ -46,7 +46,6 @@
import com.android.systemui.statusbar.notification.NotificationUtils;
import com.android.systemui.statusbar.notification.SourceType;
import com.android.systemui.statusbar.notification.shared.NotificationHeadsUpCycling;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.shared.NotificationsImprovedHunAnimation;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
import com.android.systemui.statusbar.notification.stack.StackStateAnimator;
@@ -236,16 +235,6 @@
setOutlineAlpha(alpha);
}
- @Override
- public void setBelowSpeedBump(boolean below) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- super.setBelowSpeedBump(below);
- if (below != mIsBelowSpeedBump) {
- mIsBelowSpeedBump = below;
- updateBackgroundTint();
- }
- }
-
/**
* Sets the tint color of the background
*/
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
index 6becbd2..afda426 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
@@ -40,7 +40,6 @@
import com.android.systemui.statusbar.StatusBarIconView;
import com.android.systemui.statusbar.notification.Roundable;
import com.android.systemui.statusbar.notification.RoundableState;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
import com.android.systemui.util.Compile;
@@ -394,14 +393,6 @@
public abstract void performAddAnimation(long delay, long duration, boolean isHeadsUpAppear,
Runnable onEndRunnable);
- /**
- * Set the notification appearance to be below the speed bump.
- * @param below true if it is below.
- */
- public void setBelowSpeedBump(boolean below) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- }
-
public int getPinnedHeadsUpHeight() {
return getIntrinsicHeight();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shared/NotificationIconContainerRefactor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/shared/NotificationIconContainerRefactor.kt
deleted file mode 100644
index a08af75..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shared/NotificationIconContainerRefactor.kt
+++ /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.systemui.statusbar.notification.shared
-
-import com.android.systemui.Flags
-import com.android.systemui.flags.FlagToken
-import com.android.systemui.flags.RefactorFlagUtils
-
-/** Helper for reading or using the NotificationIconContainer refactor flag state. */
-@Suppress("NOTHING_TO_INLINE")
-object NotificationIconContainerRefactor {
- /** The aconfig flag name */
- const val FLAG_NAME = Flags.FLAG_NOTIFICATIONS_ICON_CONTAINER_REFACTOR
-
- /** A token used for dependency declaration */
- val token: FlagToken
- get() = FlagToken(FLAG_NAME, isEnabled)
-
- /** Is the refactor enabled? */
- @JvmStatic
- inline val isEnabled
- get() = Flags.notificationsIconContainerRefactor()
-
- /**
- * Called to ensure code is only run when the flag is enabled. This protects users from the
- * unintended behaviors caused by accidentally running new logic, while also crashing on an eng
- * build to ensure that the refactor author catches issues in testing.
- */
- @JvmStatic
- inline fun isUnexpectedlyInLegacyMode() =
- RefactorFlagUtils.isUnexpectedlyInLegacyMode(isEnabled, FLAG_NAME)
-
- /**
- * Called to ensure code is only run when the flag is disabled. This will throw an exception if
- * the flag is enabled to ensure that the refactor author catches issues in testing.
- */
- @JvmStatic
- inline fun assertInLegacyMode() = RefactorFlagUtils.assertInLegacyMode(isEnabled, FLAG_NAME)
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
index 819527e..15dc115 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
@@ -21,9 +21,7 @@
import com.android.systemui.statusbar.NotificationShelf
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerShelfViewBinder
import com.android.systemui.statusbar.notification.row.ui.viewbinder.ActivatableNotificationViewBinder
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.shelf.ui.viewmodel.NotificationShelfViewModel
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
@@ -35,17 +33,10 @@
viewModel: NotificationShelfViewModel,
falsingManager: FalsingManager,
nicBinder: NotificationIconContainerShelfViewBinder,
- notificationIconAreaController: NotificationIconAreaController,
): Unit = coroutineScope {
ActivatableNotificationViewBinder.bind(viewModel, shelf, falsingManager)
shelf.apply {
- traceSection("NotifShelf#bindShelfIcons") {
- if (NotificationIconContainerRefactor.isEnabled) {
- launch { nicBinder.bind(shelfIcons) }
- } else {
- notificationIconAreaController.setShelfIcons(shelfIcons)
- }
- }
+ traceSection("NotifShelf#bindShelfIcons") { launch { nicBinder.bind(shelfIcons) } }
launch {
viewModel.canModifyColorOfNotifications.collect(::setCanModifyColorOfNotifications)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
index 83de226..69c9a4b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
@@ -26,7 +26,6 @@
import com.android.systemui.res.R;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.ExpandableView;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
/**
* A state of an expandable view
@@ -157,11 +156,6 @@
expandableView.setHideSensitive(
this.hideSensitive, false /* animated */, 0 /* delay */, 0 /* duration */);
- // apply below shelf speed bump
- if (!NotificationIconContainerRefactor.isEnabled()) {
- expandableView.setBelowSpeedBump(this.belowSpeedBump);
- }
-
// apply clipping
final float oldClipTopAmount = expandableView.getClipTopAmount();
if (oldClipTopAmount != this.clipTopAmount) {
@@ -211,11 +205,6 @@
abortAnimation(child, TAG_ANIMATOR_BOTTOM_INSET);
}
- // apply below the speed bump
- if (!NotificationIconContainerRefactor.isEnabled()) {
- expandableView.setBelowSpeedBump(this.belowSpeedBump);
- }
-
// start hiding sensitive animation
expandableView.setHideSensitive(this.hideSensitive, animationFilter.animateHideSensitive,
properties.delay, properties.duration);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 608fe95..41195aa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -1426,6 +1426,7 @@
}
public void setHeadsUpBoundaries(int height, int bottomBarHeight) {
+ SceneContainerFlag.assertInLegacyMode();
mView.setHeadsUpBoundaries(height, bottomBarHeight);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinder.kt
index 5544f93..5572f8e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinder.kt
@@ -46,7 +46,6 @@
import com.android.systemui.statusbar.notification.stack.ui.viewbinder.HideNotificationsBinder.bindHideList
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.NotificationListViewModel
import com.android.systemui.statusbar.notification.ui.viewbinder.HeadsUpNotificationViewBinder
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
import com.android.systemui.util.kotlin.awaitCancellationThenDispose
import com.android.systemui.util.kotlin.getOrNull
import com.android.systemui.util.ui.isAnimating
@@ -74,7 +73,6 @@
private val configuration: ConfigurationState,
private val falsingManager: FalsingManager,
private val hunBinder: HeadsUpNotificationViewBinder,
- private val iconAreaController: NotificationIconAreaController,
private val loggerOptional: Optional<NotificationStatsLogger>,
private val metricsLogger: MetricsLogger,
private val nicBinder: NotificationIconContainerShelfViewBinder,
@@ -128,7 +126,6 @@
viewModel.shelf,
falsingManager,
nicBinder,
- iconAreaController,
)
}
@@ -183,12 +180,12 @@
launchNotificationSettings = { view ->
notificationActivityStarter
.get()
- .startHistoryIntent(view, /* showHistory = */ false)
+ .startHistoryIntent(view, /* showHistory= */ false)
},
launchNotificationHistory = { view ->
notificationActivityStarter
.get()
- .startHistoryIntent(view, /* showHistory = */ true)
+ .startHistoryIntent(view, /* showHistory= */ true)
},
)
launch {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/NotificationsPlaceholderViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/NotificationsPlaceholderViewModel.kt
index e8a7840..db91eed 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/NotificationsPlaceholderViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/NotificationsPlaceholderViewModel.kt
@@ -74,7 +74,8 @@
}
/** Whether or not the notification scrim should be clickable. */
- val isClickable: StateFlow<Boolean> = shadeSceneViewModel.isClickable
+ val isClickable: StateFlow<Boolean>
+ get() = shadeSceneViewModel.isClickable
/** True when a HUN is pinned or animating away. */
val isHeadsUpOrAnimatingAway: Flow<Boolean> =
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
index 3a3b05b..2c7ce00 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
@@ -209,7 +209,6 @@
import com.android.systemui.statusbar.notification.init.NotificationsController;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController;
@@ -237,10 +236,10 @@
import com.android.wm.shell.startingsurface.SplashscreenContentDrawer;
import com.android.wm.shell.startingsurface.StartingSurface;
-import dalvik.annotation.optimization.NeverCompile;
-
import dagger.Lazy;
+import dalvik.annotation.optimization.NeverCompile;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
@@ -546,7 +545,6 @@
protected final BatteryController mBatteryController;
private UiModeManager mUiModeManager;
private LogMaker mStatusBarStateLog;
- protected final NotificationIconAreaController mNotificationIconAreaController;
@Nullable private View mAmbientIndicationContainer;
private final SysuiColorExtractor mColorExtractor;
private final ScreenLifecycle mScreenLifecycle;
@@ -683,7 +681,6 @@
DemoModeController demoModeController,
Lazy<NotificationShadeDepthController> notificationShadeDepthControllerLazy,
StatusBarTouchableRegionManager statusBarTouchableRegionManager,
- NotificationIconAreaController notificationIconAreaController,
BrightnessSliderController.Factory brightnessSliderFactory,
ScreenOffAnimationController screenOffAnimationController,
WallpaperController wallpaperController,
@@ -787,7 +784,6 @@
mUserInfoControllerImpl = userInfoControllerImpl;
mIconPolicy = phoneStatusBarPolicy;
mDemoModeController = demoModeController;
- mNotificationIconAreaController = notificationIconAreaController;
mBrightnessSliderFactory = brightnessSliderFactory;
mWallpaperController = wallpaperController;
mStatusBarSignalPolicy = statusBarSignalPolicy;
@@ -2652,9 +2648,6 @@
!mDozeServiceHost.isPulsing());
mShadeSurface.setTouchAndAnimationDisabled(disabled);
- if (!NotificationIconContainerRefactor.isEnabled()) {
- mNotificationIconAreaController.setAnimationsEnabled(!disabled);
- }
}
final ScreenLifecycle.Observer mScreenObserver = new ScreenLifecycle.Observer() {
@@ -3053,9 +3046,6 @@
}
// TODO: Bring these out of CentralSurfaces.
mUserInfoControllerImpl.onDensityOrFontScaleChanged();
- if (!NotificationIconContainerRefactor.isEnabled()) {
- mNotificationIconAreaController.onDensityOrFontScaleChanged(mContext);
- }
}
@Override
@@ -3073,9 +3063,6 @@
if (mAmbientIndicationContainer instanceof AutoReinflateContainer) {
((AutoReinflateContainer) mAmbientIndicationContainer).inflateLayout();
}
- if (!NotificationIconContainerRefactor.isEnabled()) {
- mNotificationIconAreaController.onThemeChanged();
- }
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeServiceHost.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeServiceHost.java
index ca1fb78b..f13a593 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeServiceHost.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeServiceHost.java
@@ -52,7 +52,6 @@
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -106,7 +105,6 @@
private final NotificationWakeUpCoordinator mNotificationWakeUpCoordinator;
private NotificationShadeWindowViewController mNotificationShadeWindowViewController;
private final AuthController mAuthController;
- private final NotificationIconAreaController mNotificationIconAreaController;
private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
private final ShadeLockscreenInteractor mShadeLockscreenInteractor;
private View mAmbientIndicationContainer;
@@ -129,7 +127,6 @@
NotificationShadeWindowController notificationShadeWindowController,
NotificationWakeUpCoordinator notificationWakeUpCoordinator,
AuthController authController,
- NotificationIconAreaController notificationIconAreaController,
ShadeLockscreenInteractor shadeLockscreenInteractor,
DozeInteractor dozeInteractor) {
super();
@@ -149,7 +146,6 @@
mNotificationShadeWindowController = notificationShadeWindowController;
mNotificationWakeUpCoordinator = notificationWakeUpCoordinator;
mAuthController = authController;
- mNotificationIconAreaController = notificationIconAreaController;
mShadeLockscreenInteractor = shadeLockscreenInteractor;
mHeadsUpManager.addListener(mOnHeadsUpChangedListener);
mDozeInteractor = dozeInteractor;
@@ -196,13 +192,8 @@
void fireNotificationPulse(NotificationEntry entry) {
Runnable pulseSuppressedListener = () -> {
- if (NotificationIconContainerRefactor.isEnabled()) {
- mHeadsUpManager.removeNotification(
- entry.getKey(), /* releaseImmediately= */ true, /* animate= */ false);
- } else {
- entry.setPulseSuppressed(true);
- mNotificationIconAreaController.updateAodNotificationIcons();
- }
+ mHeadsUpManager.removeNotification(
+ entry.getKey(), /* releaseImmediately= */ true, /* animate= */ false);
};
Assert.isMainThread();
for (Callback callback : mCallbacks) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
index f99a81e..8f94c06 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
@@ -42,7 +42,6 @@
import com.android.systemui.statusbar.notification.domain.interactor.HeadsUpNotificationIconInteractor;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.shared.AsyncGroupHeaderViewInflation;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.NotificationRoundnessManager;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController;
import com.android.systemui.statusbar.phone.fragment.dagger.StatusBarFragmentScope;
@@ -74,7 +73,6 @@
private static final SourceType HEADS_UP = SourceType.from("HeadsUp");
private static final SourceType PULSING = SourceType.from("Pulsing");
- private final NotificationIconAreaController mNotificationIconAreaController;
private final HeadsUpManager mHeadsUpManager;
private final NotificationStackScrollLayoutController mStackScrollerController;
@@ -114,7 +112,6 @@
@VisibleForTesting
@Inject
public HeadsUpAppearanceController(
- NotificationIconAreaController notificationIconAreaController,
HeadsUpManager headsUpManager,
StatusBarStateController stateController,
PhoneStatusBarTransitions phoneStatusBarTransitions,
@@ -132,7 +129,6 @@
HeadsUpNotificationIconInteractor headsUpNotificationIconInteractor,
@Named(OPERATOR_NAME_FRAME_VIEW) Optional<View> operatorNameViewOptional) {
super(headsUpStatusBarView);
- mNotificationIconAreaController = notificationIconAreaController;
mNotificationRoundnessManager = notificationRoundnessManager;
mHeadsUpManager = headsUpManager;
@@ -178,11 +174,8 @@
@Override
protected void onViewAttached() {
mHeadsUpManager.addListener(this);
- mView.setOnDrawingRectChangedListener(
- () -> updateIsolatedIconLocation(true /* requireUpdate */));
- if (NotificationIconContainerRefactor.isEnabled()) {
- updateIsolatedIconLocation(true);
- }
+ mView.setOnDrawingRectChangedListener(this::updateIsolatedIconLocation);
+ updateIsolatedIconLocation();
mWakeUpCoordinator.addListener(this);
getShadeHeadsUpTracker().addTrackingHeadsUpListener(mSetTrackingHeadsUp);
getShadeHeadsUpTracker().setHeadsUpAppearanceController(this);
@@ -198,9 +191,7 @@
protected void onViewDetached() {
mHeadsUpManager.removeListener(this);
mView.setOnDrawingRectChangedListener(null);
- if (NotificationIconContainerRefactor.isEnabled()) {
- mHeadsUpNotificationIconInteractor.setIsolatedIconLocation(null);
- }
+ mHeadsUpNotificationIconInteractor.setIsolatedIconLocation(null);
mWakeUpCoordinator.removeListener(this);
getShadeHeadsUpTracker().removeTrackingHeadsUpListener(mSetTrackingHeadsUp);
getShadeHeadsUpTracker().setHeadsUpAppearanceController(null);
@@ -208,14 +199,8 @@
mDarkIconDispatcher.removeDarkReceiver(this);
}
- private void updateIsolatedIconLocation(boolean requireStateUpdate) {
- if (NotificationIconContainerRefactor.isEnabled()) {
- mHeadsUpNotificationIconInteractor
- .setIsolatedIconLocation(mView.getIconDrawingRect());
- } else {
- mNotificationIconAreaController.setIsolatedIconLocation(
- mView.getIconDrawingRect(), requireStateUpdate);
- }
+ private void updateIsolatedIconLocation() {
+ mHeadsUpNotificationIconInteractor.setIsolatedIconLocation(mView.getIconDrawingRect());
}
@Override
@@ -251,14 +236,8 @@
setShown(true);
animateIsolation = !isExpanded();
}
- if (NotificationIconContainerRefactor.isEnabled()) {
- mHeadsUpNotificationIconInteractor.setIsolatedIconNotificationKey(
- newEntry == null ? null : newEntry.getRepresentativeEntry().getKey());
- } else {
- updateIsolatedIconLocation(false /* requireUpdate */);
- mNotificationIconAreaController.showIconIsolated(newEntry == null ? null
- : newEntry.getIcons().getStatusBarIcon(), animateIsolation);
- }
+ mHeadsUpNotificationIconInteractor.setIsolatedIconNotificationKey(
+ newEntry == null ? null : newEntry.getRepresentativeEntry().getKey());
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java
deleted file mode 100644
index f84efbb..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java
+++ /dev/null
@@ -1,700 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.statusbar.phone;
-
-import static com.android.systemui.Flags.newAodTransition;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Color;
-import android.graphics.Rect;
-import android.os.Bundle;
-import android.os.Trace;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.FrameLayout;
-
-import androidx.annotation.ColorInt;
-import androidx.annotation.NonNull;
-import androidx.annotation.VisibleForTesting;
-import androidx.collection.ArrayMap;
-
-import com.android.app.animation.Interpolators;
-import com.android.internal.statusbar.StatusBarIcon;
-import com.android.internal.util.ContrastColorUtil;
-import com.android.settingslib.Utils;
-import com.android.systemui.dagger.SysUISingleton;
-import com.android.systemui.demomode.DemoMode;
-import com.android.systemui.demomode.DemoModeController;
-import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.keyguard.MigrateClocksToBlueprint;
-import com.android.systemui.plugins.DarkIconDispatcher;
-import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.res.R;
-import com.android.systemui.statusbar.CrossFadeHelper;
-import com.android.systemui.statusbar.NotificationListener;
-import com.android.systemui.statusbar.NotificationMediaManager;
-import com.android.systemui.statusbar.StatusBarIconView;
-import com.android.systemui.statusbar.StatusBarState;
-import com.android.systemui.statusbar.notification.NotificationUtils;
-import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
-import com.android.systemui.statusbar.notification.collection.ListEntry;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.provider.SectionStyleProvider;
-import com.android.systemui.statusbar.window.StatusBarWindowController;
-import com.android.wm.shell.bubbles.Bubbles;
-
-import org.jetbrains.annotations.NotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-import java.util.function.Function;
-
-import javax.inject.Inject;
-
-/**
- * A controller for the space in the status bar to the left of the system icons. This area is
- * normally reserved for notifications.
- */
-@SysUISingleton
-public class LegacyNotificationIconAreaControllerImpl implements
- NotificationIconAreaController,
- DarkReceiver,
- StatusBarStateController.StateListener,
- NotificationWakeUpCoordinator.WakeUpListener,
- DemoMode {
-
- private static final long AOD_ICONS_APPEAR_DURATION = 200;
- @ColorInt
- private static final int DEFAULT_AOD_ICON_COLOR = 0xffffffff;
-
- private final ContrastColorUtil mContrastColorUtil;
- private final Runnable mUpdateStatusBarIcons = this::updateStatusBarIcons;
- private final StatusBarStateController mStatusBarStateController;
- private final NotificationMediaManager mMediaManager;
- private final NotificationWakeUpCoordinator mWakeUpCoordinator;
- private final KeyguardBypassController mBypassController;
- private final DozeParameters mDozeParameters;
- private final SectionStyleProvider mSectionStyleProvider;
- private final Optional<Bubbles> mBubblesOptional;
- private final StatusBarWindowController mStatusBarWindowController;
- private final ScreenOffAnimationController mScreenOffAnimationController;
-
- private int mIconSize;
- private int mIconHPadding;
- private int mIconTint = Color.WHITE;
-
- private List<ListEntry> mNotificationEntries = List.of();
- protected View mNotificationIconArea;
- private NotificationIconContainer mNotificationIcons;
- private NotificationIconContainer mShelfIcons;
- private NotificationIconContainer mAodIcons;
- private final ArrayList<Rect> mTintAreas = new ArrayList<>();
- private final Context mContext;
- private int mAodIconAppearTranslation;
-
- private boolean mAnimationsEnabled;
- private int mAodIconTint;
- private boolean mAodIconsVisible;
- private boolean mShowLowPriority = true;
-
- @VisibleForTesting
- final NotificationListener.NotificationSettingsListener mSettingsListener =
- new NotificationListener.NotificationSettingsListener() {
- @Override
- public void onStatusBarIconsBehaviorChanged(boolean hideSilentStatusIcons) {
- mShowLowPriority = !hideSilentStatusIcons;
- updateStatusBarIcons();
- }
- };
-
- @Inject
- public LegacyNotificationIconAreaControllerImpl(
- Context context,
- StatusBarStateController statusBarStateController,
- NotificationWakeUpCoordinator wakeUpCoordinator,
- KeyguardBypassController keyguardBypassController,
- NotificationMediaManager notificationMediaManager,
- NotificationListener notificationListener,
- DozeParameters dozeParameters,
- SectionStyleProvider sectionStyleProvider,
- Optional<Bubbles> bubblesOptional,
- DemoModeController demoModeController,
- DarkIconDispatcher darkIconDispatcher,
- FeatureFlags featureFlags,
- StatusBarWindowController statusBarWindowController,
- ScreenOffAnimationController screenOffAnimationController) {
- mContrastColorUtil = ContrastColorUtil.getInstance(context);
- mContext = context;
- mStatusBarStateController = statusBarStateController;
- mStatusBarStateController.addCallback(this);
- mMediaManager = notificationMediaManager;
- mDozeParameters = dozeParameters;
- mSectionStyleProvider = sectionStyleProvider;
- mWakeUpCoordinator = wakeUpCoordinator;
- wakeUpCoordinator.addListener(this);
- mBypassController = keyguardBypassController;
- mBubblesOptional = bubblesOptional;
- demoModeController.addCallback(this);
- mStatusBarWindowController = statusBarWindowController;
- mScreenOffAnimationController = screenOffAnimationController;
- notificationListener.addNotificationSettingsListener(mSettingsListener);
- initializeNotificationAreaViews(context);
- reloadAodColor();
- darkIconDispatcher.addDarkReceiver(this);
- }
-
- protected View inflateIconArea(LayoutInflater inflater) {
- return inflater.inflate(R.layout.notification_icon_area, null);
- }
-
- /**
- * Initializes the views that will represent the notification area.
- */
- protected void initializeNotificationAreaViews(Context context) {
- reloadDimens(context);
-
- LayoutInflater layoutInflater = LayoutInflater.from(context);
- mNotificationIconArea = inflateIconArea(layoutInflater);
- mNotificationIcons = mNotificationIconArea.findViewById(R.id.notificationIcons);
- }
-
- /**
- * Called by the Keyguard*ViewController whose view contains the aod icons.
- */
- public void setupAodIcons(@NonNull NotificationIconContainer aodIcons) {
- boolean changed = mAodIcons != null && aodIcons != mAodIcons;
- if (changed) {
- mAodIcons.setAnimationsEnabled(false);
- mAodIcons.removeAllViews();
- }
- mAodIcons = aodIcons;
- mAodIcons.setOnLockScreen(true);
- updateAodIconsVisibility(false /* animate */, changed);
- updateAnimations();
- if (changed) {
- updateAodNotificationIcons();
- }
- updateIconLayoutParams(mContext);
- }
-
- public void setShelfIcons(NotificationIconContainer icons) {
- mShelfIcons = icons;
- }
-
- public void onDensityOrFontScaleChanged(@NotNull Context context) {
- updateIconLayoutParams(context);
- }
-
- private void updateIconLayoutParams(Context context) {
- reloadDimens(context);
- final FrameLayout.LayoutParams params = generateIconLayoutParams();
- for (int i = 0; i < mNotificationIcons.getChildCount(); i++) {
- View child = mNotificationIcons.getChildAt(i);
- child.setLayoutParams(params);
- }
- if (mShelfIcons != null) {
- for (int i = 0; i < mShelfIcons.getChildCount(); i++) {
- View child = mShelfIcons.getChildAt(i);
- child.setLayoutParams(params);
- }
- }
- if (mAodIcons != null) {
- for (int i = 0; i < mAodIcons.getChildCount(); i++) {
- View child = mAodIcons.getChildAt(i);
- child.setLayoutParams(params);
- }
- }
- }
-
- @NonNull
- private FrameLayout.LayoutParams generateIconLayoutParams() {
- return new FrameLayout.LayoutParams(
- mIconSize + 2 * mIconHPadding, mStatusBarWindowController.getStatusBarHeight());
- }
-
- private void reloadDimens(Context context) {
- Resources res = context.getResources();
- mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size_sp);
- mIconHPadding = res.getDimensionPixelSize(R.dimen.status_bar_icon_horizontal_margin);
- mAodIconAppearTranslation = res.getDimensionPixelSize(
- R.dimen.shelf_appear_translation);
- }
-
- /**
- * Returns the view that represents the notification area.
- */
- public View getNotificationInnerAreaView() {
- return mNotificationIconArea;
- }
-
- /**
- * See {@link com.android.systemui.statusbar.policy.DarkIconDispatcher#setIconsDarkArea}.
- * Sets the color that should be used to tint any icons in the notification area.
- *
- * @param tintAreas the areas in which to tint the icons, specified in screen coordinates
- * @param darkIntensity
- */
- public void onDarkChanged(ArrayList<Rect> tintAreas, float darkIntensity, int iconTint) {
- mTintAreas.clear();
- mTintAreas.addAll(tintAreas);
-
- if (DarkIconDispatcher.isInAreas(tintAreas, mNotificationIconArea)) {
- mIconTint = iconTint;
- }
-
- applyNotificationIconsTint();
- }
-
- protected boolean shouldShowNotificationIcon(NotificationEntry entry,
- boolean showAmbient, boolean showLowPriority, boolean hideDismissed,
- boolean hideRepliedMessages, boolean hideCurrentMedia, boolean hidePulsing) {
- if (!showAmbient && mSectionStyleProvider.isMinimized(entry)) {
- return false;
- }
- if (hideCurrentMedia && entry.getKey().equals(mMediaManager.getMediaNotificationKey())) {
- return false;
- }
- if (!showLowPriority && mSectionStyleProvider.isSilent(entry)) {
- return false;
- }
- if (entry.isRowDismissed() && hideDismissed) {
- return false;
- }
- if (hideRepliedMessages && entry.isLastMessageFromReply()) {
- return false;
- }
- // showAmbient == show in shade but not shelf
- if (!showAmbient && entry.shouldSuppressStatusBar()) {
- return false;
- }
- if (hidePulsing && entry.showingPulsing()
- && (!mWakeUpCoordinator.getNotificationsFullyHidden()
- || !entry.isPulseSuppressed())) {
- return false;
- }
- if (mBubblesOptional.isPresent()
- && mBubblesOptional.get().isBubbleExpanded(entry.getKey())) {
- return false;
- }
- return true;
- }
-
- /**
- * Updates the notifications with the given list of notifications to display.
- */
- public void updateNotificationIcons(List<ListEntry> entries) {
- mNotificationEntries = entries;
- updateNotificationIcons();
- }
-
- private void updateNotificationIcons() {
- Trace.beginSection("NotificationIconAreaController.updateNotificationIcons");
- updateStatusBarIcons();
- updateShelfIcons();
- updateAodNotificationIcons();
-
- applyNotificationIconsTint();
- Trace.endSection();
- }
-
- private void updateShelfIcons() {
- if (mShelfIcons == null) {
- return;
- }
- updateIconsForLayout(entry -> entry.getIcons().getShelfIcon(), mShelfIcons,
- true /* showAmbient */,
- true /* showLowPriority */,
- false /* hideDismissed */,
- false /* hideRepliedMessages */,
- false /* hideCurrentMedia */,
- false /* hidePulsing */);
- }
-
- public void updateStatusBarIcons() {
- updateIconsForLayout(entry -> entry.getIcons().getStatusBarIcon(), mNotificationIcons,
- false /* showAmbient */,
- mShowLowPriority,
- true /* hideDismissed */,
- true /* hideRepliedMessages */,
- false /* hideCurrentMedia */,
- false /* hidePulsing */);
- }
-
- public void updateAodNotificationIcons() {
- if (mAodIcons == null) {
- return;
- }
- updateIconsForLayout(entry -> entry.getIcons().getAodIcon(), mAodIcons,
- false /* showAmbient */,
- true /* showLowPriority */,
- true /* hideDismissed */,
- true /* hideRepliedMessages */,
- true /* hideCurrentMedia */,
- mBypassController.getBypassEnabled() /* hidePulsing */);
- }
-
- @VisibleForTesting
- boolean shouldShouldLowPriorityIcons() {
- return mShowLowPriority;
- }
-
- /**
- * Updates the notification icons for a host layout. This will ensure that the notification
- * host layout will have the same icons like the ones in here.
- * @param function A function to look up an icon view based on an entry
- * @param hostLayout which layout should be updated
- * @param showAmbient should ambient notification icons be shown
- * @param showLowPriority should icons from silent notifications be shown
- * @param hideDismissed should dismissed icons be hidden
- * @param hideRepliedMessages should messages that have been replied to be hidden
- * @param hidePulsing should pulsing notifications be hidden
- */
- private void updateIconsForLayout(Function<NotificationEntry, StatusBarIconView> function,
- NotificationIconContainer hostLayout, boolean showAmbient, boolean showLowPriority,
- boolean hideDismissed, boolean hideRepliedMessages, boolean hideCurrentMedia,
- boolean hidePulsing) {
- ArrayList<StatusBarIconView> toShow = new ArrayList<>(mNotificationEntries.size());
- // Filter out ambient notifications and notification children.
- for (int i = 0; i < mNotificationEntries.size(); i++) {
- NotificationEntry entry = mNotificationEntries.get(i).getRepresentativeEntry();
- if (entry != null && entry.getRow() != null) {
- if (shouldShowNotificationIcon(entry, showAmbient, showLowPriority, hideDismissed,
- hideRepliedMessages, hideCurrentMedia, hidePulsing)) {
- StatusBarIconView iconView = function.apply(entry);
- if (iconView != null) {
- toShow.add(iconView);
- }
- }
- }
- }
-
- // In case we are changing the suppression of a group, the replacement shouldn't flicker
- // and it should just be replaced instead. We therefore look for notifications that were
- // just replaced by the child or vice-versa to suppress this.
-
- ArrayMap<String, ArrayList<StatusBarIcon>> replacingIcons = new ArrayMap<>();
- ArrayList<View> toRemove = new ArrayList<>();
- for (int i = 0; i < hostLayout.getChildCount(); i++) {
- View child = hostLayout.getChildAt(i);
- if (!(child instanceof StatusBarIconView)) {
- continue;
- }
- if (!toShow.contains(child)) {
- boolean iconWasReplaced = false;
- StatusBarIconView removedIcon = (StatusBarIconView) child;
- String removedGroupKey = removedIcon.getNotification().getGroupKey();
- for (int j = 0; j < toShow.size(); j++) {
- StatusBarIconView candidate = toShow.get(j);
- if (candidate.getSourceIcon().sameAs((removedIcon.getSourceIcon()))
- && candidate.getNotification().getGroupKey().equals(removedGroupKey)) {
- if (!iconWasReplaced) {
- iconWasReplaced = true;
- } else {
- iconWasReplaced = false;
- break;
- }
- }
- }
- if (iconWasReplaced) {
- ArrayList<StatusBarIcon> statusBarIcons = replacingIcons.get(removedGroupKey);
- if (statusBarIcons == null) {
- statusBarIcons = new ArrayList<>();
- replacingIcons.put(removedGroupKey, statusBarIcons);
- }
- statusBarIcons.add(removedIcon.getStatusBarIcon());
- }
- toRemove.add(removedIcon);
- }
- }
- // removing all duplicates
- ArrayList<String> duplicates = new ArrayList<>();
- for (String key : replacingIcons.keySet()) {
- ArrayList<StatusBarIcon> statusBarIcons = replacingIcons.get(key);
- if (statusBarIcons.size() != 1) {
- duplicates.add(key);
- }
- }
- replacingIcons.removeAll(duplicates);
- hostLayout.setReplacingIconsLegacy(replacingIcons);
-
- final int toRemoveCount = toRemove.size();
- for (int i = 0; i < toRemoveCount; i++) {
- hostLayout.removeView(toRemove.get(i));
- }
-
- final FrameLayout.LayoutParams params = generateIconLayoutParams();
- for (int i = 0; i < toShow.size(); i++) {
- StatusBarIconView v = toShow.get(i);
- // The view might still be transiently added if it was just removed and added again
- hostLayout.removeTransientView(v);
- if (v.getParent() == null) {
- if (hideDismissed) {
- v.setOnDismissListener(mUpdateStatusBarIcons);
- }
- hostLayout.addView(v, i, params);
- }
- }
-
- hostLayout.setChangingViewPositions(true);
- // Re-sort notification icons
- final int childCount = hostLayout.getChildCount();
- for (int i = 0; i < childCount; i++) {
- View actual = hostLayout.getChildAt(i);
- StatusBarIconView expected = toShow.get(i);
- if (actual == expected) {
- continue;
- }
- hostLayout.removeView(expected);
- hostLayout.addView(expected, i);
- }
- hostLayout.setChangingViewPositions(false);
- hostLayout.setReplacingIconsLegacy(null);
- }
-
- /**
- * Applies {@link #mIconTint} to the notification icons.
- */
- private void applyNotificationIconsTint() {
- for (int i = 0; i < mNotificationIcons.getChildCount(); i++) {
- final StatusBarIconView iv = (StatusBarIconView) mNotificationIcons.getChildAt(i);
- if (iv.getWidth() != 0) {
- updateTintForIcon(iv, mIconTint);
- } else {
- iv.executeOnLayout(() -> updateTintForIcon(iv, mIconTint));
- }
- }
-
- updateAodIconColors();
- }
-
- private void updateTintForIcon(StatusBarIconView v, int tint) {
- boolean isPreL = Boolean.TRUE.equals(v.getTag(R.id.icon_is_pre_L));
- int color = StatusBarIconView.NO_COLOR;
- boolean colorize = !isPreL || NotificationUtils.isGrayscale(v, mContrastColorUtil);
- if (colorize) {
- color = DarkIconDispatcher.getTint(mTintAreas, v, tint);
- }
- v.setStaticDrawableColor(color);
- v.setDecorColor(tint);
- }
-
- public void showIconIsolated(StatusBarIconView icon, boolean animated) {
- mNotificationIcons.showIconIsolatedLegacy(icon, animated);
- }
-
- public void setIsolatedIconLocation(@NotNull Rect iconDrawingRect, boolean requireStateUpdate) {
- mNotificationIcons.setIsolatedIconLocation(iconDrawingRect, requireStateUpdate);
- }
-
- @Override
- public void onDozingChanged(boolean isDozing) {
- if (mAodIcons == null) {
- return;
- }
- boolean animate = mDozeParameters.getAlwaysOn()
- && !mDozeParameters.getDisplayNeedsBlanking();
- mAodIcons.setDozing(isDozing, animate, 0);
- }
-
- public void setAnimationsEnabled(boolean enabled) {
- mAnimationsEnabled = enabled;
- updateAnimations();
- }
-
- @Override
- public void onStateChanged(int newState) {
- updateAodIconsVisibility(false /* animate */, false /* force */);
- updateAnimations();
- }
-
- private void updateAnimations() {
- boolean inShade = mStatusBarStateController.getState() == StatusBarState.SHADE;
- if (mAodIcons != null) {
- mAodIcons.setAnimationsEnabled(mAnimationsEnabled && !inShade);
- }
- mNotificationIcons.setAnimationsEnabled(mAnimationsEnabled && inShade);
- }
-
- public void onThemeChanged() {
- reloadAodColor();
- updateAodIconColors();
- }
-
- public int getHeight() {
- return mAodIcons == null ? 0 : mAodIcons.getHeight();
- }
-
- public void appearAodIcons() {
- if (mAodIcons == null) {
- return;
- }
- if (mScreenOffAnimationController.shouldAnimateAodIcons()) {
- if (!MigrateClocksToBlueprint.isEnabled()) {
- mAodIcons.setTranslationY(-mAodIconAppearTranslation);
- }
- mAodIcons.setAlpha(0);
- animateInAodIconTranslation();
- mAodIcons.animate()
- .alpha(1)
- .setInterpolator(Interpolators.LINEAR)
- .setDuration(AOD_ICONS_APPEAR_DURATION)
- .start();
- } else {
- mAodIcons.setAlpha(1.0f);
- if (!MigrateClocksToBlueprint.isEnabled()) {
- mAodIcons.setTranslationY(0);
- }
- }
- }
-
- private void animateInAodIconTranslation() {
- if (!MigrateClocksToBlueprint.isEnabled()) {
- mAodIcons.animate()
- .setInterpolator(Interpolators.DECELERATE_QUINT)
- .translationY(0)
- .setDuration(AOD_ICONS_APPEAR_DURATION)
- .start();
- }
- }
-
- private void reloadAodColor() {
- mAodIconTint = Utils.getColorAttrDefaultColor(mContext,
- R.attr.wallpaperTextColor, DEFAULT_AOD_ICON_COLOR);
- }
-
- private void updateAodIconColors() {
- if (mAodIcons != null) {
- for (int i = 0; i < mAodIcons.getChildCount(); i++) {
- final StatusBarIconView iv = (StatusBarIconView) mAodIcons.getChildAt(i);
- if (iv.getWidth() != 0) {
- updateTintForIcon(iv, mAodIconTint);
- } else {
- iv.executeOnLayout(() -> updateTintForIcon(iv, mAodIconTint));
- }
- }
- }
- }
-
- @Override
- public void onFullyHiddenChanged(boolean fullyHidden) {
- boolean animate = true;
- if (!mBypassController.getBypassEnabled()) {
- animate = mDozeParameters.getAlwaysOn() && !mDozeParameters.getDisplayNeedsBlanking();
- if (!newAodTransition()) {
- // We only want the appear animations to happen when the notifications get fully
- // hidden, since otherwise the unhide animation overlaps
- animate &= fullyHidden;
- }
- }
- updateAodIconsVisibility(animate, false /* force */);
- updateAodNotificationIcons();
- updateAodIconColors();
- }
-
- @Override
- public void onPulseExpansionAmountChanged(boolean expandingChanged) {
- if (expandingChanged) {
- updateAodIconsVisibility(true /* animate */, false /* force */);
- }
- }
-
- private void updateAodIconsVisibility(boolean animate, boolean forceUpdate) {
- if (mAodIcons == null) {
- return;
- }
- boolean visible = mBypassController.getBypassEnabled()
- || mWakeUpCoordinator.getNotificationsFullyHidden();
-
- // Hide the AOD icons if we're not in the KEYGUARD state unless the screen off animation is
- // playing, in which case we want them to be visible since we're animating in the AOD UI and
- // will be switching to KEYGUARD shortly.
- if (mStatusBarStateController.getState() != StatusBarState.KEYGUARD
- && !mScreenOffAnimationController.shouldShowAodIconsWhenShade()) {
- visible = false;
- }
- if (visible && mWakeUpCoordinator.isPulseExpanding()
- && !mBypassController.getBypassEnabled()) {
- visible = false;
- }
- if (mAodIconsVisible != visible || forceUpdate) {
- mAodIconsVisible = visible;
- mAodIcons.animate().cancel();
- if (animate) {
- if (newAodTransition()) {
- // Let's make sure the icon are translated to 0, since we cancelled it above
- animateInAodIconTranslation();
- if (mAodIconsVisible) {
- CrossFadeHelper.fadeIn(mAodIcons);
- } else {
- CrossFadeHelper.fadeOut(mAodIcons);
- }
- } else {
- boolean wasFullyInvisible = mAodIcons.getVisibility() != View.VISIBLE;
- if (mAodIconsVisible) {
- if (wasFullyInvisible) {
- // No fading here, let's just appear the icons instead!
- mAodIcons.setVisibility(View.VISIBLE);
- mAodIcons.setAlpha(1.0f);
- appearAodIcons();
- } else {
- // Let's make sure the icon are translated to 0, since we cancelled it
- // above
- animateInAodIconTranslation();
- // We were fading out, let's fade in instead
- CrossFadeHelper.fadeIn(mAodIcons);
- }
- } else {
- // Let's make sure the icon are translated to 0, since we cancelled it above
- animateInAodIconTranslation();
- CrossFadeHelper.fadeOut(mAodIcons);
- }
- }
- } else {
- mAodIcons.setAlpha(1.0f);
- if (!MigrateClocksToBlueprint.isEnabled()) {
- mAodIcons.setTranslationY(0);
- }
- mAodIcons.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
- }
- }
- }
-
- @Override
- public List<String> demoCommands() {
- ArrayList<String> commands = new ArrayList<>();
- commands.add(DemoMode.COMMAND_NOTIFICATIONS);
- return commands;
- }
-
- @Override
- public void dispatchDemoCommand(String command, Bundle args) {
- if (mNotificationIconArea != null) {
- String visible = args.getString("visible");
- int vis = "false".equals(visible) ? View.INVISIBLE : View.VISIBLE;
- mNotificationIconArea.setVisibility(vis);
- }
- }
-
- @Override
- public void onDemoModeFinished() {
- if (mNotificationIconArea != null) {
- mNotificationIconArea.setVisibility(View.VISIBLE);
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt
deleted file mode 100644
index 4385a2e..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.statusbar.phone
-
-import android.content.Context
-import android.graphics.Rect
-import android.view.View
-import com.android.systemui.statusbar.StatusBarIconView
-import com.android.systemui.statusbar.notification.collection.ListEntry
-
-/**
- * A controller for the space in the status bar to the left of the system icons. This area is
- * normally reserved for notifications.
- */
-interface NotificationIconAreaController {
- /** Called by the Keyguard*ViewController whose view contains the aod icons. */
- fun setupAodIcons(aodIcons: NotificationIconContainer?)
- fun setShelfIcons(icons: NotificationIconContainer)
- fun onDensityOrFontScaleChanged(context: Context)
-
- /** Returns the view that represents the notification area. */
- fun getNotificationInnerAreaView(): View?
-
- /** Updates the notifications with the given list of notifications to display. */
- fun updateNotificationIcons(entries: List<@JvmSuppressWildcards ListEntry>)
- fun updateAodNotificationIcons()
- fun showIconIsolated(icon: StatusBarIconView?, animated: Boolean)
- fun setIsolatedIconLocation(iconDrawingRect: Rect, requireStateUpdate: Boolean)
- fun setAnimationsEnabled(enabled: Boolean)
- fun onThemeChanged()
- fun getHeight(): Int
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt
deleted file mode 100644
index ba69370..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.statusbar.phone
-
-import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconAreaControllerViewBinderWrapperImpl
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
-import dagger.Module
-import dagger.Provides
-import javax.inject.Provider
-
-@Module
-object NotificationIconAreaControllerModule {
- @Provides
- fun provideNotificationIconAreaControllerImpl(
- legacyProvider: Provider<LegacyNotificationIconAreaControllerImpl>,
- newProvider: Provider<NotificationIconAreaControllerViewBinderWrapperImpl>,
- ): NotificationIconAreaController =
- if (NotificationIconContainerRefactor.isEnabled) {
- newProvider.get()
- } else {
- legacyProvider.get()
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
index 8e3d678..ecd62bd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
@@ -26,7 +26,6 @@
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.util.AttributeSet;
-import android.util.MathUtils;
import android.util.Property;
import android.view.ContextThemeWrapper;
import android.view.View;
@@ -42,7 +41,6 @@
import com.android.settingslib.Utils;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.StatusBarIconView;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.statusbar.notification.stack.AnimationFilter;
import com.android.systemui.statusbar.notification.stack.AnimationProperties;
import com.android.systemui.statusbar.notification.stack.ViewState;
@@ -243,7 +241,7 @@
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int childCount = getChildCount();
- final int maxVisibleIcons = getMaxVisibleIcons(childCount);
+ final int maxVisibleIcons = mMaxIcons;
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int childWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.UNSPECIFIED);
int totalWidth = (int) (getActualPaddingStart() + getActualPaddingEnd());
@@ -284,22 +282,13 @@
@Override
public String toString() {
- if (NotificationIconContainerRefactor.isEnabled()) {
- return super.toString()
- + " {"
- + " overrideIconColor=" + mOverrideIconColor
- + ", maxIcons=" + mMaxIcons
- + ", isStaticLayout=" + mIsStaticLayout
- + ", themedTextColorPrimary=#" + Integer.toHexString(mThemedTextColorPrimary)
- + " }";
- } else {
- return "NotificationIconContainer("
- + "dozing=" + mDozing + " onLockScreen=" + mOnLockScreen
- + " overrideIconColor=" + mOverrideIconColor
- + " speedBumpIndex=" + mSpeedBumpIndex
- + " themedTextColorPrimary=#" + Integer.toHexString(mThemedTextColorPrimary)
- + ')';
- }
+ return super.toString()
+ + " {"
+ + " overrideIconColor=" + mOverrideIconColor
+ + ", maxIcons=" + mMaxIcons
+ + ", isStaticLayout=" + mIsStaticLayout
+ + ", themedTextColorPrimary=#" + Integer.toHexString(mThemedTextColorPrimary)
+ + " }";
}
@VisibleForTesting
@@ -349,13 +338,8 @@
}
}
if (child instanceof StatusBarIconView) {
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (!mChangingViewPositions) {
- ((StatusBarIconView) child).updateIconDimens();
- }
- } else {
+ if (!mChangingViewPositions) {
((StatusBarIconView) child).updateIconDimens();
- ((StatusBarIconView) child).setDozing(mDozing, false, 0);
}
}
}
@@ -367,23 +351,11 @@
StatusBarIconView iconView = (StatusBarIconView) child;
Icon sourceIcon = iconView.getSourceIcon();
String groupKey = iconView.getNotification().getGroupKey();
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (mReplacingIcons == null) {
- return false;
- }
- StatusBarIcon replacedIcon = mReplacingIcons.get(groupKey);
- return replacedIcon != null && sourceIcon.sameAs(replacedIcon.icon);
- } else {
- if (mReplacingIconsLegacy == null) {
- return false;
- }
- ArrayList<StatusBarIcon> statusBarIcons = mReplacingIconsLegacy.get(groupKey);
- if (statusBarIcons != null) {
- StatusBarIcon replacedIcon = statusBarIcons.get(0);
- return sourceIcon.sameAs(replacedIcon.icon);
- }
+ if (mReplacingIcons == null) {
return false;
}
+ StatusBarIcon replacedIcon = mReplacingIcons.get(groupKey);
+ return replacedIcon != null && sourceIcon.sameAs(replacedIcon.icon);
}
@Override
@@ -468,24 +440,14 @@
if (numIcons == 0) {
return 0f;
}
- final float contentWidth;
- if (NotificationIconContainerRefactor.isEnabled()) {
- contentWidth = mIconSize * numIcons;
- } else {
- contentWidth = mIconSize * MathUtils.min(numIcons, mMaxIconsOnLockscreen + 1);
- }
+ final float contentWidth = mIconSize * numIcons;
return getActualPaddingStart() + contentWidth + getActualPaddingEnd();
}
@VisibleForTesting
boolean shouldForceOverflow(int i, int speedBumpIndex, float iconAppearAmount,
int maxVisibleIcons) {
- if (NotificationIconContainerRefactor.isEnabled()) {
- return i >= maxVisibleIcons && iconAppearAmount > 0.0f;
- } else {
- return speedBumpIndex != -1 && i >= speedBumpIndex
- && iconAppearAmount > 0.0f || i >= maxVisibleIcons;
- }
+ return i >= maxVisibleIcons && iconAppearAmount > 0.0f;
}
@VisibleForTesting
@@ -510,7 +472,7 @@
float translationX = getActualPaddingStart();
int firstOverflowIndex = -1;
int childCount = getChildCount();
- int maxVisibleIcons = getMaxVisibleIcons(childCount);
+ int maxVisibleIcons = mMaxIcons;
float layoutEnd = getLayoutEnd();
mVisualOverflowStart = 0;
mFirstVisibleIconState = null;
@@ -592,27 +554,15 @@
}
private float getDrawingScale(View view) {
- final boolean useIncreasedScale = NotificationIconContainerRefactor.isEnabled()
- ? mUseIncreasedIconScale
- : mOnLockScreen;
- return useIncreasedScale && view instanceof StatusBarIconView
+ return mUseIncreasedIconScale && view instanceof StatusBarIconView
? ((StatusBarIconView) view).getIconScaleIncreased()
: 1f;
}
public void setUseIncreasedIconScale(boolean useIncreasedIconScale) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mUseIncreasedIconScale = useIncreasedIconScale;
}
- private int getMaxVisibleIcons(int childCount) {
- if (NotificationIconContainerRefactor.isEnabled()) {
- return mMaxIcons;
- } else {
- return mOnLockScreen ? mMaxIconsOnAod : mIsStaticLayout ? mMaxStaticIcons : childCount;
- }
- }
-
private float getLayoutEnd() {
return getActualWidth() - getActualPaddingEnd();
}
@@ -689,50 +639,11 @@
mChangingViewPositions = changingViewPositions;
}
- public void setDozing(boolean dozing, boolean animate, long delay) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- setDozing(dozing, animate, delay, /* endRunnable= */ null);
- }
-
- private void setDozing(boolean dozing, boolean animate, long delay,
- @Nullable Runnable endRunnable) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mDozing = dozing;
- mDisallowNextAnimation |= !animate;
- final int childCount = getChildCount();
- // Track all the child invocations of setDozing, invoking the top-level endRunnable once
- // they have all completed.
- final Runnable onChildCompleted = endRunnable == null ? null : new Runnable() {
- private int mPendingCallbacks = childCount;
-
- @Override
- public void run() {
- if (--mPendingCallbacks == 0) {
- endRunnable.run();
- }
- }
- };
- for (int i = 0; i < childCount; i++) {
- View view = getChildAt(i);
- if (view instanceof StatusBarIconView) {
- ((StatusBarIconView) view).setDozing(dozing, animate, delay, onChildCompleted);
- } else if (onChildCompleted != null) {
- onChildCompleted.run();
- }
- }
- }
-
public IconState getIconState(StatusBarIconView icon) {
return mIconStates.get(icon);
}
- public void setSpeedBumpIndex(int speedBumpIndex) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mSpeedBumpIndex = speedBumpIndex;
- }
-
public void setMaxIconsAmount(int maxIcons) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mMaxIcons = maxIcons;
}
@@ -754,36 +665,18 @@
mAnimationsEnabled = enabled;
}
- public void setReplacingIconsLegacy(ArrayMap<String, ArrayList<StatusBarIcon>> replacingIcons) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mReplacingIconsLegacy = replacingIcons;
- }
-
public void setReplacingIcons(ArrayMap<String, StatusBarIcon> replacingIcons) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mReplacingIcons = replacingIcons;
}
- @Deprecated
- public void showIconIsolatedLegacy(StatusBarIconView icon, boolean animated) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- if (animated) {
- mIsolatedIconForAnimation = icon != null ? icon : mIsolatedIcon;
- }
- mIsolatedIcon = icon;
- updateState();
- }
-
public void showIconIsolatedAnimated(StatusBarIconView icon,
@Nullable Runnable onAnimationEnd) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mIsolatedIconForAnimation = icon != null ? icon : mIsolatedIcon;
mIsolatedIconAnimationEndRunnable = onAnimationEnd;
showIconIsolated(icon);
}
public void showIconIsolated(StatusBarIconView icon) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mIsolatedIcon = icon;
updateState();
}
@@ -795,23 +688,7 @@
}
}
- /**
- * Set whether the device is on the lockscreen and which lockscreen mode the device is
- * configured to. Depending on these values, the layout of the AOD icons change.
- */
- public void setOnLockScreen(boolean onLockScreen) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mOnLockScreen = onLockScreen;
- }
-
- @Deprecated
- public void setInNotificationIconShelf(boolean inShelf) {
- NotificationIconContainerRefactor.assertInLegacyMode();
- mOverrideIconColor = inShelf;
- }
-
public void setOverrideIconColor(boolean override) {
- if (NotificationIconContainerRefactor.isUnexpectedlyInLegacyMode()) return;
mOverrideIconColor = override;
}
@@ -922,14 +799,9 @@
}
}
icon.setVisibleState(visibleState, animationsAllowed);
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (mOverrideIconColor) {
- icon.setIconColor(mThemedTextColorPrimary,
- /* animate= */ needsCannedAnimation && animationsAllowed);
- }
- } else {
- icon.setIconColor(mOverrideIconColor ? mThemedTextColorPrimary : iconColor,
- needsCannedAnimation && animationsAllowed);
+ if (mOverrideIconColor) {
+ icon.setIconColor(mThemedTextColorPrimary,
+ /* animate= */ needsCannedAnimation && animationsAllowed);
}
if (animate) {
animateTo(icon, animationProperties);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java
index 07c190d..5be4ba2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java
@@ -59,8 +59,6 @@
import com.android.systemui.statusbar.events.SystemStatusAnimationCallback;
import com.android.systemui.statusbar.events.SystemStatusAnimationScheduler;
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerStatusBarViewBinder;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
-import com.android.systemui.statusbar.phone.NotificationIconAreaController;
import com.android.systemui.statusbar.phone.NotificationIconContainer;
import com.android.systemui.statusbar.phone.PhoneStatusBarView;
import com.android.systemui.statusbar.phone.StatusBarHideIconsForBouncerManager;
@@ -140,7 +138,6 @@
private final OngoingCallController mOngoingCallController;
private final SystemStatusAnimationScheduler mAnimationScheduler;
private final StatusBarLocationPublisher mLocationPublisher;
- private final NotificationIconAreaController mNotificationIconAreaController;
private final ShadeExpansionStateManager mShadeExpansionStateManager;
private final StatusBarIconController mStatusBarIconController;
private final CarrierConfigTracker mCarrierConfigTracker;
@@ -237,7 +234,6 @@
OngoingCallController ongoingCallController,
SystemStatusAnimationScheduler animationScheduler,
StatusBarLocationPublisher locationPublisher,
- NotificationIconAreaController notificationIconAreaController,
ShadeExpansionStateManager shadeExpansionStateManager,
StatusBarIconController statusBarIconController,
DarkIconManager.Factory darkIconManagerFactory,
@@ -262,7 +258,6 @@
mOngoingCallController = ongoingCallController;
mAnimationScheduler = animationScheduler;
mLocationPublisher = locationPublisher;
- mNotificationIconAreaController = notificationIconAreaController;
mShadeExpansionStateManager = shadeExpansionStateManager;
mStatusBarIconController = statusBarIconController;
mCollapsedStatusBarViewModel = collapsedStatusBarViewModel;
@@ -313,18 +308,14 @@
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStatusBarWindowStateController.addListener(mStatusBarWindowStateListener);
- if (NotificationIconContainerRefactor.isEnabled()) {
- mDemoModeController.addCallback(mDemoModeCallback);
- }
+ mDemoModeController.addCallback(mDemoModeCallback);
}
@Override
public void onDestroy() {
super.onDestroy();
mStatusBarWindowStateController.removeListener(mStatusBarWindowStateListener);
- if (NotificationIconContainerRefactor.isEnabled()) {
- mDemoModeController.removeCallback(mDemoModeCallback);
- }
+ mDemoModeController.removeCallback(mDemoModeCallback);
}
@Override
@@ -471,11 +462,9 @@
mStartableStates.put(startable, Startable.State.STOPPED);
}
mDumpManager.unregisterDumpable(getClass().getSimpleName());
- if (NotificationIconContainerRefactor.isEnabled()) {
- if (mNicBindingDisposable != null) {
- mNicBindingDisposable.dispose();
- mNicBindingDisposable = null;
- }
+ if (mNicBindingDisposable != null) {
+ mNicBindingDisposable.dispose();
+ mNicBindingDisposable = null;
}
}
@@ -483,22 +472,12 @@
public void initNotificationIconArea() {
Trace.beginSection("CollapsedStatusBarFragment#initNotifIconArea");
ViewGroup notificationIconArea = mStatusBar.requireViewById(R.id.notification_icon_area);
- if (NotificationIconContainerRefactor.isEnabled()) {
- LayoutInflater.from(getContext())
- .inflate(R.layout.notification_icon_area, notificationIconArea, true);
- NotificationIconContainer notificationIcons =
- notificationIconArea.requireViewById(R.id.notificationIcons);
- mNotificationIconAreaInner = notificationIcons;
- mNicBindingDisposable = mNicViewBinder.bindWhileAttached(notificationIcons);
- } else {
- mNotificationIconAreaInner =
- mNotificationIconAreaController.getNotificationInnerAreaView();
- if (mNotificationIconAreaInner.getParent() != null) {
- ((ViewGroup) mNotificationIconAreaInner.getParent())
- .removeView(mNotificationIconAreaInner);
- }
- notificationIconArea.addView(mNotificationIconAreaInner);
- }
+ LayoutInflater.from(getContext())
+ .inflate(R.layout.notification_icon_area, notificationIconArea, true);
+ NotificationIconContainer notificationIcons =
+ notificationIconArea.requireViewById(R.id.notificationIcons);
+ mNotificationIconAreaInner = notificationIcons;
+ mNicBindingDisposable = mNicViewBinder.bindWhileAttached(notificationIcons);
updateNotificationIconAreaAndOngoingActivityChip(/* animate= */ false);
Trace.endSection();
diff --git a/packages/SystemUI/src/com/android/systemui/util/settings/SettingsProxyExt.kt b/packages/SystemUI/src/com/android/systemui/util/settings/SettingsProxyExt.kt
index 36468144..d757e33 100644
--- a/packages/SystemUI/src/com/android/systemui/util/settings/SettingsProxyExt.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/settings/SettingsProxyExt.kt
@@ -19,7 +19,6 @@
import android.annotation.UserIdInt
import android.database.ContentObserver
-import com.android.systemui.Flags
import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
@@ -40,21 +39,9 @@
}
}
- names.forEach { name ->
- if (Flags.settingsExtRegisterContentObserverOnBgThread()) {
- registerContentObserverForUser(name, observer, userId)
- } else {
- registerContentObserverForUserSync(name, observer, userId)
- }
- }
+ names.forEach { name -> registerContentObserverForUserSync(name, observer, userId) }
- awaitClose {
- if (Flags.settingsExtRegisterContentObserverOnBgThread()) {
- unregisterContentObserverAsync(observer)
- } else {
- unregisterContentObserverSync(observer)
- }
- }
+ awaitClose { unregisterContentObserverSync(observer) }
}
}
@@ -70,21 +57,9 @@
}
}
- names.forEach { name ->
- if (Flags.settingsExtRegisterContentObserverOnBgThread()) {
- registerContentObserver(name, observer)
- } else {
- registerContentObserverSync(name, observer)
- }
- }
+ names.forEach { name -> registerContentObserverSync(name, observer) }
- awaitClose {
- if (Flags.settingsExtRegisterContentObserverOnBgThread()) {
- unregisterContentObserverAsync(observer)
- } else {
- unregisterContentObserverSync(observer)
- }
- }
+ awaitClose { unregisterContentObserverSync(observer) }
}
}
}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
index 319b615..2bb9e68 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
@@ -55,7 +55,6 @@
import com.android.systemui.statusbar.StatusBarState;
import com.android.systemui.statusbar.lockscreen.LockscreenSmartspaceController;
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerAlwaysOnDisplayViewBinder;
-import com.android.systemui.statusbar.phone.NotificationIconAreaController;
import com.android.systemui.statusbar.phone.NotificationIconContainer;
import com.android.systemui.util.concurrency.FakeExecutor;
import com.android.systemui.util.settings.SecureSettings;
@@ -78,8 +77,6 @@
@Mock
KeyguardSliceViewController mKeyguardSliceViewController;
@Mock
- NotificationIconAreaController mNotificationIconAreaController;
- @Mock
LockscreenSmartspaceController mSmartspaceController;
@Mock
@@ -176,7 +173,6 @@
mStatusBarStateController,
mClockRegistry,
mKeyguardSliceViewController,
- mNotificationIconAreaController,
mSmartspaceController,
mock(NotificationIconContainerAlwaysOnDisplayViewBinder.class),
mKeyguardUnlockAnimationController,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
index 512d946..534f25c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
@@ -503,11 +503,13 @@
collectLastValue(kosmos.promptViewModel.iconViewModel.contentDescriptionId)
val shouldAnimateIconView by
collectLastValue(kosmos.promptViewModel.iconViewModel.shouldAnimateIconView)
+ val message by collectLastValue(kosmos.promptViewModel.message)
verifyIconSize()
kosmos.promptViewModel.showAuthenticated(
modality = testCase.authenticatedModality,
- dismissAfterDelay = DELAY
+ dismissAfterDelay = DELAY,
+ "TEST"
)
if (testCase.isFingerprintOnly) {
@@ -531,6 +533,7 @@
assertThat(iconContentDescriptionId)
.isEqualTo(R.string.biometric_dialog_face_icon_description_authenticated)
assertThat(shouldAnimateIconView).isEqualTo(true)
+ assertThat(message).isEqualTo(PromptMessage.Empty)
}
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
index ef1c927..27a1bb5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
@@ -24,7 +24,6 @@
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
import android.app.Notification;
import android.app.NotificationManager;
@@ -41,7 +40,6 @@
import com.android.systemui.statusbar.NotificationListener.NotificationHandler;
import com.android.systemui.statusbar.data.repository.NotificationListenerSettingsRepository;
import com.android.systemui.statusbar.domain.interactor.SilentNotificationStatusIconsVisibilityInteractor;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
import com.android.systemui.util.concurrency.FakeExecutor;
import com.android.systemui.util.time.FakeSystemClock;
@@ -149,30 +147,4 @@
verify(mNotificationHandler).onNotificationRankingUpdate(eq(ranking3));
verifyNoMoreInteractions(mNotificationHandler);
}
-
- @Test
- public void testOnConnectReadStatusBarSetting() {
- mSetFlagsRule.disableFlags(NotificationIconContainerRefactor.FLAG_NAME);
- NotificationListener.NotificationSettingsListener settingsListener =
- mock(NotificationListener.NotificationSettingsListener.class);
- mListener.addNotificationSettingsListener(settingsListener);
-
- when(mNotificationManager.shouldHideSilentStatusBarIcons()).thenReturn(true);
-
- mListener.onListenerConnected();
-
- verify(settingsListener).onStatusBarIconsBehaviorChanged(true);
- }
-
- @Test
- public void testOnStatusBarIconsBehaviorChanged() {
- mSetFlagsRule.disableFlags(NotificationIconContainerRefactor.FLAG_NAME);
- NotificationListener.NotificationSettingsListener settingsListener =
- mock(NotificationListener.NotificationSettingsListener.class);
- mListener.addNotificationSettingsListener(settingsListener);
-
- mListener.onSilentStatusBarIconsVisibilityChanged(true);
-
- verify(settingsListener).onStatusBarIconsBehaviorChanged(true);
- }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
index c7513de..ad6aca1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
@@ -34,10 +34,8 @@
import com.android.systemui.statusbar.notification.domain.interactor.ActiveNotificationsInteractor
import com.android.systemui.statusbar.notification.domain.interactor.RenderNotificationListInteractor
import com.android.systemui.statusbar.notification.footer.shared.FooterViewRefactor
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.stack.BUCKET_ALERTING
import com.android.systemui.statusbar.notification.stack.BUCKET_SILENT
-import com.android.systemui.statusbar.phone.NotificationIconAreaController
import com.android.systemui.statusbar.policy.SensitiveNotificationProtectionController
import com.android.systemui.util.mockito.eq
import com.android.systemui.util.mockito.withArgCaptor
@@ -47,8 +45,8 @@
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
-import org.mockito.MockitoAnnotations.initMocks
import org.mockito.Mockito.`when` as whenever
+import org.mockito.MockitoAnnotations.initMocks
@SmallTest
@RunWith(AndroidJUnit4::class)
@@ -61,10 +59,10 @@
@Mock private lateinit var pipeline: NotifPipeline
@Mock private lateinit var groupExpansionManagerImpl: GroupExpansionManagerImpl
- @Mock private lateinit var notificationIconAreaController: NotificationIconAreaController
@Mock private lateinit var renderListInteractor: RenderNotificationListInteractor
@Mock private lateinit var activeNotificationsInteractor: ActiveNotificationsInteractor
- @Mock private lateinit var sensitiveNotificationProtectionController:
+ @Mock
+ private lateinit var sensitiveNotificationProtectionController:
SensitiveNotificationProtectionController
@Mock private lateinit var stackController: NotifStackController
@Mock private lateinit var section: NotifSection
@@ -73,14 +71,12 @@
fun setUp() {
initMocks(this)
- whenever(sensitiveNotificationProtectionController.isSensitiveStateActive)
- .thenReturn(false)
+ whenever(sensitiveNotificationProtectionController.isSensitiveStateActive).thenReturn(false)
entry = NotificationEntryBuilder().setSection(section).build()
coordinator =
StackCoordinator(
groupExpansionManagerImpl,
- notificationIconAreaController,
renderListInteractor,
activeNotificationsInteractor,
sensitiveNotificationProtectionController,
@@ -92,15 +88,7 @@
}
@Test
- @DisableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- fun testUpdateNotificationIcons() {
- afterRenderListListener.onAfterRenderList(listOf(entry), stackController)
- verify(notificationIconAreaController).updateNotificationIcons(eq(listOf(entry)))
- }
-
- @Test
- @EnableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- fun testSetRenderedListOnInteractor_iconContainerFlagOn() {
+ fun testSetRenderedListOnInteractor() {
afterRenderListListener.onAfterRenderList(listOf(entry), stackController)
verify(renderListInteractor).setRenderedList(eq(listOf(entry)))
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
index c1f2cb77..e4945fc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
@@ -1,6 +1,5 @@
package com.android.systemui.statusbar.notification.stack
-import android.platform.test.annotations.DisableFlags
import android.service.notification.StatusBarNotification
import android.testing.TestableLooper.RunWithLooper
import android.view.LayoutInflater
@@ -21,7 +20,6 @@
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
import com.android.systemui.statusbar.notification.row.ExpandableView
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import com.android.systemui.statusbar.notification.stack.StackScrollAlgorithm.StackScrollAlgorithmState
import com.android.systemui.util.mockito.mock
import junit.framework.Assert.assertEquals
@@ -72,32 +70,6 @@
}
@Test
- @DisableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- fun testShadeWidth_BasedOnFractionToShade() {
- setFractionToShade(0f)
- setOnLockscreen(true)
-
- shelf.updateActualWidth(/* fractionToShade */ 0f, /* shortestWidth */ 10f)
- assertTrue(shelf.actualWidth == 10)
-
- shelf.updateActualWidth(/* fractionToShade */ 0.5f, /* shortestWidth */ 10f)
- assertTrue(shelf.actualWidth == 20)
-
- shelf.updateActualWidth(/* fractionToShade */ 1f, /* shortestWidth */ 10f)
- assertTrue(shelf.actualWidth == 30)
- }
-
- @Test
- @DisableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- fun testShelfIsLong_WhenNotOnLockscreen() {
- setFractionToShade(0f)
- setOnLockscreen(false)
-
- shelf.updateActualWidth(/* fraction */ 0f, /* shortestWidth */ 10f)
- assertTrue(shelf.actualWidth == 30)
- }
-
- @Test
fun testX_inViewForClick() {
val isXInView =
shelf.isXInView(/* localX */ 5f, /* slop */ 5f, /* left */ 0f, /* right */ 10f)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
index a6b2729..e9c16c2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
@@ -295,7 +295,6 @@
@Mock private Bubbles mBubbles;
@Mock private NoteTaskController mNoteTaskController;
@Mock private NotificationShadeWindowController mNotificationShadeWindowController;
- @Mock private NotificationIconAreaController mNotificationIconAreaController;
@Mock private NotificationShadeWindowViewController mNotificationShadeWindowViewController;
@Mock private Lazy<NotificationShadeWindowViewController>
mNotificationShadeWindowViewControllerLazy;
@@ -580,7 +579,6 @@
mDemoModeController,
mNotificationShadeDepthControllerLazy,
mStatusBarTouchableRegionManager,
- mNotificationIconAreaController,
mBrightnessSliderFactory,
mScreenOffAnimationController,
mWallpaperController,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
index 0d06b64..dd03ab3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
@@ -110,7 +110,6 @@
mNotificationRoundnessManager = mock(NotificationRoundnessManager.class);
when(mShadeViewController.getShadeHeadsUpTracker()).thenReturn(mShadeHeadsUpTracker);
mHeadsUpAppearanceController = new HeadsUpAppearanceController(
- mock(NotificationIconAreaController.class),
mHeadsUpManager,
mStatusbarStateController,
mPhoneStatusBarTransitions,
@@ -197,7 +196,6 @@
when(mStackScrollerController.getExpandedHeight()).thenReturn(expandedHeight);
HeadsUpAppearanceController newController = new HeadsUpAppearanceController(
- mock(NotificationIconAreaController.class),
mHeadsUpManager,
mStatusbarStateController,
mPhoneStatusBarTransitions,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
deleted file mode 100644
index 8dfbb37..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.statusbar.phone;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.platform.test.annotations.DisableFlags;
-import android.testing.TestableLooper;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-import androidx.test.filters.SmallTest;
-
-import com.android.systemui.Flags;
-import com.android.systemui.SysuiTestCase;
-import com.android.systemui.demomode.DemoModeController;
-import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.plugins.DarkIconDispatcher;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.NotificationListener;
-import com.android.systemui.statusbar.NotificationMediaManager;
-import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
-import com.android.systemui.statusbar.notification.collection.provider.SectionStyleProvider;
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor;
-import com.android.systemui.statusbar.window.StatusBarWindowController;
-import com.android.wm.shell.bubbles.Bubbles;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.Optional;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-@TestableLooper.RunWithLooper
-@DisableFlags(NotificationIconContainerRefactor.FLAG_NAME)
-public class LegacyNotificationIconAreaControllerImplTest extends SysuiTestCase {
-
- @Mock
- private NotificationListener mListener;
- @Mock
- StatusBarStateController mStatusBarStateController;
- @Mock
- NotificationWakeUpCoordinator mWakeUpCoordinator;
- @Mock
- KeyguardBypassController mKeyguardBypassController;
- @Mock
- NotificationMediaManager mNotificationMediaManager;
- @Mock
- DozeParameters mDozeParameters;
- @Mock
- SectionStyleProvider mSectionStyleProvider;
- @Mock
- DarkIconDispatcher mDarkIconDispatcher;
- @Mock
- StatusBarWindowController mStatusBarWindowController;
- @Mock
- ScreenOffAnimationController mScreenOffAnimationController;
- private LegacyNotificationIconAreaControllerImpl mController;
- @Mock
- private Bubbles mBubbles;
- @Mock private DemoModeController mDemoModeController;
- @Mock
- private NotificationIconContainer mAodIcons;
- @Mock
- private FeatureFlags mFeatureFlags;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- mController = new LegacyNotificationIconAreaControllerImpl(
- mContext,
- mStatusBarStateController,
- mWakeUpCoordinator,
- mKeyguardBypassController,
- mNotificationMediaManager,
- mListener,
- mDozeParameters,
- mSectionStyleProvider,
- Optional.of(mBubbles),
- mDemoModeController,
- mDarkIconDispatcher,
- mFeatureFlags,
- mStatusBarWindowController,
- mScreenOffAnimationController);
- }
-
- @Test
- public void testNotificationIcons_settingHideIcons() {
- mController.mSettingsListener.onStatusBarIconsBehaviorChanged(true);
-
- assertFalse(mController.shouldShouldLowPriorityIcons());
- }
-
- @Test
- public void testNotificationIcons_settingShowIcons() {
- mController.mSettingsListener.onStatusBarIconsBehaviorChanged(false);
-
- assertTrue(mController.shouldShouldLowPriorityIcons());
- }
-
- @Test
- @DisableFlags(Flags.FLAG_MIGRATE_CLOCKS_TO_BLUEPRINT)
- public void testAppearResetsTranslation() {
- mController.setupAodIcons(mAodIcons);
- when(mDozeParameters.shouldControlScreenOff()).thenReturn(false);
- mController.appearAodIcons();
- verify(mAodIcons).setTranslationY(0);
- verify(mAodIcons).setAlpha(1.0f);
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconContainerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconContainerTest.kt
index 9d97e5a..15958ef 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconContainerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconContainerTest.kt
@@ -23,7 +23,6 @@
import com.android.systemui.statusbar.StatusBarIconView
import com.android.systemui.statusbar.StatusBarIconView.STATE_DOT
import com.android.systemui.statusbar.StatusBarIconView.STATE_HIDDEN
-import com.android.systemui.statusbar.notification.shared.NotificationIconContainerRefactor
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
@@ -73,18 +72,6 @@
}
@Test
- fun calculateWidthFor_fiveIcons_widthForFourIcons() {
- mSetFlagsRule.disableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- iconContainer.setActualPaddingStart(10f)
- iconContainer.setActualPaddingEnd(10f)
- iconContainer.setIconSize(10)
- assertEquals(
- /* expected= */ iconContainer.calculateWidthFor(/* numIcons= */ 5f),
- /* actual= */ 60f
- )
- }
-
- @Test
fun calculateIconXTranslations_shortShelfOneIcon_atCorrectXWithoutOverflowDot() {
iconContainer.setActualPaddingStart(10f)
iconContainer.setActualPaddingEnd(10f)
@@ -213,19 +200,6 @@
}
@Test
- fun shouldForceOverflow_appearingAboveSpeedBump_true() {
- mSetFlagsRule.disableFlags(NotificationIconContainerRefactor.FLAG_NAME)
- val forceOverflow =
- iconContainer.shouldForceOverflow(
- /* i= */ 1,
- /* speedBumpIndex= */ 0,
- /* iconAppearAmount= */ 1f,
- /* maxVisibleIcons= */ 5
- )
- assertTrue(forceOverflow)
- }
-
- @Test
fun shouldForceOverflow_moreThanMaxVisible_true() {
val forceOverflow =
iconContainer.shouldForceOverflow(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
index 58ad835..bea027f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
@@ -39,7 +39,6 @@
import android.provider.Settings;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper.RunWithLooper;
-import android.view.LayoutInflater;
import android.view.View;
import androidx.test.filters.SmallTest;
@@ -64,7 +63,6 @@
import com.android.systemui.statusbar.events.SystemStatusAnimationScheduler;
import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconContainerStatusBarViewBinder;
import com.android.systemui.statusbar.phone.HeadsUpAppearanceController;
-import com.android.systemui.statusbar.phone.NotificationIconAreaController;
import com.android.systemui.statusbar.phone.StatusBarHideIconsForBouncerManager;
import com.android.systemui.statusbar.phone.StatusBarLocationPublisher;
import com.android.systemui.statusbar.phone.fragment.dagger.StatusBarFragmentComponent;
@@ -95,7 +93,6 @@
@RunWithLooper(setAsMainLooper = true)
@SmallTest
public class CollapsedStatusBarFragmentTest extends SysuiBaseFragmentTest {
- private NotificationIconAreaController mMockNotificationAreaController;
private ShadeExpansionStateManager mShadeExpansionStateManager;
private OngoingCallController mOngoingCallController;
private SystemStatusAnimationScheduler mAnimationScheduler;
@@ -931,13 +928,11 @@
mCollapsedStatusBarViewModel = new FakeCollapsedStatusBarViewModel();
mCollapsedStatusBarViewBinder = new FakeCollapsedStatusBarViewBinder();
- setUpNotificationIconAreaController();
return new CollapsedStatusBarFragment(
mStatusBarFragmentComponentFactory,
mOngoingCallController,
mAnimationScheduler,
mLocationPublisher,
- mMockNotificationAreaController,
mShadeExpansionStateManager,
mStatusBarIconController,
mIconManagerFactory,
@@ -970,14 +965,6 @@
.thenReturn(mHeadsUpAppearanceController);
}
- private void setUpNotificationIconAreaController() {
- mMockNotificationAreaController = mock(NotificationIconAreaController.class);
- View notificationAreaInner =
- LayoutInflater.from(mContext).inflate(R.layout.notification_icon_area, null);
- when(mMockNotificationAreaController.getNotificationInnerAreaView())
- .thenReturn(notificationAreaInner);
- }
-
/**
* Configure mocks to return values consistent with the secure camera animating itself launched
* over the keyguard.
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
index 550ecb3..19b32bc 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenContentViewModelKosmos.kt
@@ -20,7 +20,6 @@
import com.android.systemui.keyguard.domain.interactor.keyguardBlueprintInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardClockInteractor
import com.android.systemui.kosmos.Kosmos
-import com.android.systemui.kosmos.applicationCoroutineScope
import com.android.systemui.scene.domain.interactor.sceneContainerOcclusionInteractor
import com.android.systemui.shade.domain.interactor.shadeInteractor
import com.android.systemui.unfold.domain.interactor.unfoldTransitionInteractor
@@ -33,7 +32,6 @@
authController = authController,
touchHandling = keyguardTouchHandlingViewModel,
shadeInteractor = shadeInteractor,
- applicationScope = applicationCoroutineScope,
unfoldTransitionInteractor = unfoldTransitionInteractor,
occlusionInteractor = sceneContainerOcclusionInteractor,
)
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/ui/viewmodel/NotificationsShadeWindowModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/ui/viewmodel/NotificationsShadeWindowModelKosmos.kt
index cd4fab8..6252d44 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/ui/viewmodel/NotificationsShadeWindowModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/ui/viewmodel/NotificationsShadeWindowModelKosmos.kt
@@ -16,8 +16,14 @@
package com.android.systemui.shade.ui.viewmodel
+import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
import com.android.systemui.kosmos.Kosmos
val Kosmos.notificationShadeWindowModel: NotificationShadeWindowModel by
- Kosmos.Fixture { NotificationShadeWindowModel(keyguardTransitionInteractor) }
+ Kosmos.Fixture {
+ NotificationShadeWindowModel(
+ keyguardTransitionInteractor,
+ keyguardInteractor,
+ )
+ }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinderKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinderKosmos.kt
index ee3216b..bc1363a 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinderKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/NotificationListViewBinderKosmos.kt
@@ -29,22 +29,20 @@
import com.android.systemui.statusbar.notification.stack.ui.view.notificationStatsLogger
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.notificationListViewModel
import com.android.systemui.statusbar.notification.ui.viewbinder.headsUpNotificationViewBinder
-import com.android.systemui.statusbar.phone.notificationIconAreaController
import java.util.Optional
val Kosmos.notificationListViewBinder by Fixture {
NotificationListViewBinder(
- viewModel = notificationListViewModel,
backgroundDispatcher = testDispatcher,
+ hiderTracker = displaySwitchNotificationsHiderTracker,
configuration = configurationState,
falsingManager = falsingManager,
hunBinder = headsUpNotificationViewBinder,
- iconAreaController = notificationIconAreaController,
loggerOptional = Optional.of(notificationStatsLogger),
metricsLogger = metricsLogger,
- hiderTracker = displaySwitchNotificationsHiderTracker,
nicBinder = notificationIconContainerShelfViewBinder,
notificationActivityStarter = { notificationActivityStarter },
silentHeaderController = silentHeaderController,
+ viewModel = notificationListViewModel,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/DozeServiceHostKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/DozeServiceHostKosmos.kt
index 0b5a68e..4a6757d 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/DozeServiceHostKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/DozeServiceHostKosmos.kt
@@ -53,7 +53,6 @@
notificationShadeWindowController,
notificationWakeUpCoordinator,
authController,
- notificationIconAreaController,
shadeLockscreenInteractor,
dozeInteractor,
)
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerKosmos.kt
deleted file mode 100644
index d44e061..0000000
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerKosmos.kt
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.phone
-
-import com.android.systemui.kosmos.Kosmos
-import com.android.systemui.kosmos.Kosmos.Fixture
-import com.android.systemui.util.mockito.mock
-
-var Kosmos.notificationIconAreaController by Fixture { mock<NotificationIconAreaController>() }
diff --git a/ravenwood/Android.bp b/ravenwood/Android.bp
index 2de3c5e..4faf03c 100644
--- a/ravenwood/Android.bp
+++ b/ravenwood/Android.bp
@@ -280,10 +280,10 @@
src: "scripts/ravenwood-stats-checker.sh",
test_suites: ["general-tests"],
data: [
- ":framework-minus-apex.ravenwood-base{hoststubgen_framework-minus-apex_stats.csv}",
- ":framework-minus-apex.ravenwood-base{hoststubgen_framework-minus-apex_apis.csv}",
- ":framework-minus-apex.ravenwood-base{hoststubgen_framework-minus-apex_keep_all.txt}",
- ":framework-minus-apex.ravenwood-base{hoststubgen_framework-minus-apex_dump.txt}",
+ ":hoststubgen_framework-minus-apex_stats.csv",
+ ":hoststubgen_framework-minus-apex_apis.csv",
+ ":hoststubgen_framework-minus-apex_keep_all.txt",
+ ":hoststubgen_framework-minus-apex_dump.txt",
":services.core.ravenwood-base{hoststubgen_services.core_stats.csv}",
":services.core.ravenwood-base{hoststubgen_services.core_apis.csv}",
":services.core.ravenwood-base{hoststubgen_services.core_keep_all.txt}",
diff --git a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
index a380bc1..0047ec2 100644
--- a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
+++ b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
@@ -112,7 +112,8 @@
}
@AnyThread
- void initializeInternal(IBinder token, IInputMethodPrivilegedOperations privilegedOperations,
+ void initializeInternal(@NonNull IBinder token,
+ @NonNull IInputMethodPrivilegedOperations privilegedOperations,
@InputMethodNavButtonFlags int navigationBarFlags) {
final IInputMethod.InitParams params = new IInputMethod.InitParams();
params.token = token;
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 7992190..ea3d7d1 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -1070,13 +1070,15 @@
public void onUserUnlocking(@NonNull TargetUser user) {
// Called on ActivityManager thread. Do not block the calling thread.
final int userId = user.getUserIdentifier();
+ final var userData = mService.getUserData(userId);
+ final boolean userUnlocked = true;
SecureSettingsWrapper.onUserUnlocking(userId);
+ final var methodMap = userData.mRawInputMethodMap.get().toInputMethodMap(
+ AdditionalSubtypeMapRepository.get(userId), DirectBootAwareness.AUTO,
+ userUnlocked);
+ final var newSettings = InputMethodSettings.create(methodMap, userId);
+ InputMethodSettingsRepository.put(userId, newSettings);
mService.mIoHandler.post(() -> {
- final var userData = mService.getUserData(userId);
- final var methodMap = userData.mRawInputMethodMap.get().toInputMethodMap(
- AdditionalSubtypeMapRepository.get(userId), DirectBootAwareness.AUTO, true);
- final var newSettings = InputMethodSettings.create(methodMap, userId);
- InputMethodSettingsRepository.put(userId, newSettings);
synchronized (ImfLock.class) {
if (!mService.mSystemReady) {
return;
@@ -1142,16 +1144,18 @@
public void onUserStopped(@NonNull TargetUser user) {
final int userId = user.getUserIdentifier();
// Called on ActivityManager thread.
+
+ // Following operations should be trivial and fast enough, so do not dispatch them to
+ // the IO thread.
SecureSettingsWrapper.onUserStopped(userId);
- mService.mIoHandler.post(() -> {
- final var userData = mService.getUserData(userId);
- final var additionalSubtypeMap = AdditionalSubtypeMapRepository.get(userId);
- final var rawMethodMap = userData.mRawInputMethodMap.get();
- final var methodMap = rawMethodMap.toInputMethodMap(additionalSubtypeMap,
- DirectBootAwareness.AUTO, false /* userUnlocked */);
- InputMethodSettingsRepository.put(userId,
- InputMethodSettings.create(methodMap, userId));
- });
+ final var userData = mService.getUserData(userId);
+ final var additionalSubtypeMap = AdditionalSubtypeMapRepository.get(userId);
+ final var rawMethodMap = userData.mRawInputMethodMap.get();
+ final boolean userUnlocked = false; // Stopping a user also locks their storage.
+ final var methodMap = rawMethodMap.toInputMethodMap(additionalSubtypeMap,
+ DirectBootAwareness.AUTO, userUnlocked);
+ InputMethodSettingsRepository.put(userId,
+ InputMethodSettings.create(methodMap, userId));
}
}
@@ -1490,27 +1494,6 @@
});
}
- /**
- * Returns true iff the caller is identified to be the current input method with the token.
- *
- * @param token the window token given to the input method when it was started
- * @param userData {@link UserData} of the calling IME process
- * @return true if and only if non-null valid token is specified
- */
- @GuardedBy("ImfLock.class")
- private boolean calledWithValidTokenLocked(@NonNull IBinder token, @NonNull UserData userData) {
- if (token == null) {
- throw new InvalidParameterException("token must not be null.");
- }
- final var bindingController = userData.mBindingController;
- if (token != bindingController.getCurToken()) {
- Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
- + " uid:" + Binder.getCallingUid() + " token:" + token);
- return false;
- }
- return true;
- }
-
@BinderThread
@Nullable
@Override
@@ -2567,45 +2550,36 @@
}
@BinderThread
- private void updateStatusIcon(@NonNull IBinder token, String packageName,
- @DrawableRes int iconId, @NonNull UserData userData) {
+ @GuardedBy("ImfLock.class")
+ private void updateStatusIconLocked(String packageName, @DrawableRes int iconId,
+ @NonNull UserData userData) {
final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- // To minimize app compat risk, ignore background users' request for single-user mode.
- // TODO(b/357178609): generalize the logic and remove this special rule.
- if (!mConcurrentMultiUserModeEnabled && userId != mCurrentUserId) {
- return;
- }
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- final long ident = Binder.clearCallingIdentity();
+ // To minimize app compat risk, ignore background users' request for single-user mode.
+ // TODO(b/357178609): generalize the logic and remove this special rule.
+ if (!mConcurrentMultiUserModeEnabled && userId != mCurrentUserId) {
+ return;
+ }
+ if (iconId == 0) {
+ if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
+ hideStatusBarIconLocked(userId);
+ } else if (packageName != null) {
+ if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
+ final PackageManager userAwarePackageManager =
+ getPackageManagerForUser(mContext, userId);
+ ApplicationInfo applicationInfo = null;
try {
- if (iconId == 0) {
- if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
- hideStatusBarIconLocked(userId);
- } else if (packageName != null) {
- if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
- final PackageManager userAwarePackageManager =
- getPackageManagerForUser(mContext, userId);
- ApplicationInfo applicationInfo = null;
- try {
- applicationInfo = userAwarePackageManager.getApplicationInfo(packageName,
- PackageManager.ApplicationInfoFlags.of(0));
- } catch (PackageManager.NameNotFoundException e) {
- }
- final CharSequence contentDescription = applicationInfo != null
- ? userAwarePackageManager.getApplicationLabel(applicationInfo)
- : null;
- if (mStatusBarManagerInternal != null) {
- mStatusBarManagerInternal.setIcon(mSlotIme, packageName, iconId, 0,
- contentDescription != null
- ? contentDescription.toString() : null);
- mStatusBarManagerInternal.setIconVisibility(mSlotIme, true);
- }
- }
- } finally {
- Binder.restoreCallingIdentity(ident);
+ applicationInfo = userAwarePackageManager.getApplicationInfo(packageName,
+ PackageManager.ApplicationInfoFlags.of(0));
+ } catch (PackageManager.NameNotFoundException e) {
+ }
+ final CharSequence contentDescription = applicationInfo != null
+ ? userAwarePackageManager.getApplicationLabel(applicationInfo)
+ : null;
+ if (mStatusBarManagerInternal != null) {
+ mStatusBarManagerInternal.setIcon(mSlotIme, packageName, iconId, 0,
+ contentDescription != null
+ ? contentDescription.toString() : null);
+ mStatusBarManagerInternal.setIconVisibility(mSlotIme, true);
}
}
}
@@ -2746,29 +2720,25 @@
}
@BinderThread
+ @GuardedBy("ImfLock.class")
@SuppressWarnings("deprecation")
- private void setImeWindowStatus(@NonNull IBinder token, int vis, int backDisposition,
+ private void setImeWindowStatusLocked(int vis, int backDisposition,
@NonNull UserData userData) {
final int topFocusedDisplayId = mWindowManagerInternal.getTopFocusedDisplayId();
final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- final var bindingController = userData.mBindingController;
- // Skip update IME status when current token display is not same as focused display.
- // Note that we still need to update IME status when focusing external display
- // that does not support system decoration and fallback to show IME on default
- // display since it is intentional behavior.
- final int tokenDisplayId = bindingController.getCurTokenDisplayId();
- if (tokenDisplayId != topFocusedDisplayId && tokenDisplayId != FALLBACK_DISPLAY_ID) {
- return;
- }
- bindingController.setImeWindowVis(vis);
- bindingController.setBackDisposition(backDisposition);
- updateSystemUiLocked(vis, backDisposition, userId);
+ final var bindingController = userData.mBindingController;
+ // Skip update IME status when current token display is not same as focused display.
+ // Note that we still need to update IME status when focusing external display
+ // that does not support system decoration and fallback to show IME on default
+ // display since it is intentional behavior.
+ final int tokenDisplayId = bindingController.getCurTokenDisplayId();
+ if (tokenDisplayId != topFocusedDisplayId && tokenDisplayId != FALLBACK_DISPLAY_ID) {
+ return;
}
+ bindingController.setImeWindowVis(vis);
+ bindingController.setBackDisposition(backDisposition);
+ updateSystemUiLocked(vis, backDisposition, userId);
final boolean dismissImeOnBackKeyPressed;
switch (backDisposition) {
@@ -2787,19 +2757,14 @@
}
@BinderThread
- private void reportStartInput(@NonNull IBinder token, IBinder startInputToken,
- @NonNull UserData userData) {
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- final IBinder targetWindow = mImeTargetWindowMap.get(startInputToken);
- if (targetWindow != null) {
- mWindowManagerInternal.updateInputMethodTargetWindow(targetWindow);
- }
- final var visibilityStateComputer = userData.mVisibilityStateComputer;
- visibilityStateComputer.setLastImeTargetWindow(targetWindow);
+ @GuardedBy("ImfLock.class")
+ private void reportStartInputLocked(IBinder startInputToken, @NonNull UserData userData) {
+ final IBinder targetWindow = mImeTargetWindowMap.get(startInputToken);
+ if (targetWindow != null) {
+ mWindowManagerInternal.updateInputMethodTargetWindow(targetWindow);
}
+ final var visibilityStateComputer = userData.mVisibilityStateComputer;
+ visibilityStateComputer.setLastImeTargetWindow(targetWindow);
}
@GuardedBy("ImfLock.class")
@@ -2846,8 +2811,8 @@
final Boolean windowPerceptible = focusedWindowToken != null
? mFocusedWindowPerceptible.get(focusedWindowToken) : null;
- // TODO: Move this clearing calling identity block to setImeWindowStatus after making sure
- // all updateSystemUi happens on system privilege.
+ // TODO: Move this clearing calling identity block to setImeWindowStatusLocked after making
+ // sure all updateSystemUi happens on system privilege.
final long ident = Binder.clearCallingIdentity();
try {
if (windowPerceptible != null && !windowPerceptible) {
@@ -4115,17 +4080,6 @@
return new Pair<>(menuItems, selectedIndex);
}
- @BinderThread
- private void onImeSwitchButtonClickFromClient(@NonNull IBinder token, int displayId,
- @NonNull UserData userData) {
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- onImeSwitchButtonClickLocked(token, displayId, userData);
- }
- }
-
@IInputMethodManagerImpl.PermissionVerified(allOf = {
Manifest.permission.INTERACT_ACROSS_USERS_FULL,
Manifest.permission.WRITE_SECURE_SETTINGS})
@@ -4134,13 +4088,8 @@
synchronized (ImfLock.class) {
final int userId = resolveImeUserIdFromDisplayIdLocked(displayId);
final var userData = getUserData(userId);
- final var bindingController = userData.mBindingController;
- final var curToken = bindingController.getCurToken();
- if (curToken == null) {
- return;
- }
- onImeSwitchButtonClickLocked(curToken, displayId, userData);
+ onImeSwitchButtonClickLocked(displayId, userData);
}
}
@@ -4148,17 +4097,16 @@
* Handles a click on the IME switch button. Depending on the number of enabled IME subtypes,
* this will either switch to the next IME/subtype, or show the input method picker dialog.
*
- * @param token The token identifying the input method that triggered this.
* @param displayId The ID of the display where the input method picker dialog should be shown.
* @param userData The data of the user for which to switch IMEs or show the picker dialog.
*/
+ @BinderThread
@GuardedBy("ImfLock.class")
- private void onImeSwitchButtonClickLocked(@NonNull IBinder token, int displayId,
- @NonNull UserData userData) {
+ private void onImeSwitchButtonClickLocked(int displayId, @NonNull UserData userData) {
final int userId = userData.mUserId;
final var settings = InputMethodSettingsRepository.get(userId);
if (hasMultipleSubtypesForSwitcher(true /* nonAuxOnly */, settings)) {
- switchToNextInputMethodLocked(token, false /* onlyCurrentIme */, userData);
+ switchToNextInputMethodLocked(false /* onlyCurrentIme */, userData);
} else {
showInputMethodPickerFromSystem(
InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES, displayId);
@@ -4172,143 +4120,104 @@
}
@BinderThread
- private void setInputMethod(@NonNull IBinder token, String id, @NonNull UserData userData) {
- final int callingUid = Binder.getCallingUid();
- final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
- final InputMethodInfo imi = settings.getMethodMap().get(id);
- if (imi == null || !canCallerAccessInputMethod(
- imi.getPackageName(), callingUid, userId, settings)) {
- throw getExceptionForUnknownImeId(id);
- }
- setInputMethodWithSubtypeIdLocked(token, id, NOT_A_SUBTYPE_ID, userId);
- }
- }
-
- @BinderThread
- private void setInputMethodAndSubtype(@NonNull IBinder token, String id,
- InputMethodSubtype subtype, @NonNull UserData userData) {
- final int callingUid = Binder.getCallingUid();
- final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
- final InputMethodInfo imi = settings.getMethodMap().get(id);
- if (imi == null || !canCallerAccessInputMethod(
- imi.getPackageName(), callingUid, userId, settings)) {
- throw getExceptionForUnknownImeId(id);
- }
- if (subtype != null) {
- setInputMethodWithSubtypeIdLocked(token, id,
- SubtypeUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode()), userId);
- } else {
- setInputMethod(token, id, userData);
- }
- }
- }
-
- @BinderThread
- private boolean switchToPreviousInputMethod(@NonNull IBinder token,
+ @GuardedBy("ImfLock.class")
+ private void setInputMethodAndSubtypeLocked(String id, @Nullable InputMethodSubtype subtype,
@NonNull UserData userData) {
+ final int callingUid = Binder.getCallingUid();
final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return false;
- }
- final var bindingController = userData.mBindingController;
- final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
- final Pair<String, String> lastIme = settings.getLastInputMethodAndSubtype();
- final InputMethodInfo lastImi;
- if (lastIme != null) {
- lastImi = settings.getMethodMap().get(lastIme.first);
- } else {
- lastImi = null;
- }
- final var currentSubtype = bindingController.getCurrentSubtype();
- String targetLastImiId = null;
- int subtypeId = NOT_A_SUBTYPE_ID;
- if (lastIme != null && lastImi != null) {
- final boolean imiIdIsSame = lastImi.getId().equals(
- bindingController.getSelectedMethodId());
- final int lastSubtypeHash = Integer.parseInt(lastIme.second);
- final int currentSubtypeHash = currentSubtype == null ? NOT_A_SUBTYPE_ID
- : currentSubtype.hashCode();
- // If the last IME is the same as the current IME and the last subtype is not
- // defined, there is no need to switch to the last IME.
- if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
- targetLastImiId = lastIme.first;
- subtypeId = SubtypeUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
- }
- }
+ final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
+ final InputMethodInfo imi = settings.getMethodMap().get(id);
+ if (imi == null || !canCallerAccessInputMethod(
+ imi.getPackageName(), callingUid, userId, settings)) {
+ throw getExceptionForUnknownImeId(id);
+ }
+ final int subtypeId = subtype != null
+ ? SubtypeUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode())
+ : NOT_A_SUBTYPE_ID;
+ setInputMethodWithSubtypeIdLocked(id, subtypeId, userId);
+ }
- if (TextUtils.isEmpty(targetLastImiId)
- && !InputMethodUtils.canAddToLastInputMethod(currentSubtype)) {
- // This is a safety net. If the currentSubtype can't be added to the history
- // and the framework couldn't find the last ime, we will make the last ime be
- // the most applicable enabled keyboard subtype of the system imes.
- final List<InputMethodInfo> enabled = settings.getEnabledInputMethodList();
- if (enabled != null) {
- final int enabledCount = enabled.size();
- final String locale;
- if (currentSubtype != null
- && !TextUtils.isEmpty(currentSubtype.getLocale())) {
- locale = currentSubtype.getLocale();
- } else {
- locale = SystemLocaleWrapper.get(userId).get(0).toString();
- }
- for (int i = 0; i < enabledCount; ++i) {
- final InputMethodInfo imi = enabled.get(i);
- if (imi.getSubtypeCount() > 0 && imi.isSystem()) {
- InputMethodSubtype keyboardSubtype =
- SubtypeUtils.findLastResortApplicableSubtype(
- SubtypeUtils.getSubtypes(imi),
- SubtypeUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
- if (keyboardSubtype != null) {
- targetLastImiId = imi.getId();
- subtypeId = SubtypeUtils.getSubtypeIdFromHashCode(imi,
- keyboardSubtype.hashCode());
- if (keyboardSubtype.getLocale().equals(locale)) {
- break;
- }
+ @BinderThread
+ @GuardedBy("ImfLock.class")
+ private boolean switchToPreviousInputMethodLocked(@NonNull UserData userData) {
+ final int userId = userData.mUserId;
+ final var bindingController = userData.mBindingController;
+ final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
+ final Pair<String, String> lastIme = settings.getLastInputMethodAndSubtype();
+ final InputMethodInfo lastImi;
+ if (lastIme != null) {
+ lastImi = settings.getMethodMap().get(lastIme.first);
+ } else {
+ lastImi = null;
+ }
+ final var currentSubtype = bindingController.getCurrentSubtype();
+ String targetLastImiId = null;
+ int subtypeId = NOT_A_SUBTYPE_ID;
+ if (lastIme != null && lastImi != null) {
+ final boolean imiIdIsSame = lastImi.getId().equals(
+ bindingController.getSelectedMethodId());
+ final int lastSubtypeHash = Integer.parseInt(lastIme.second);
+ final int currentSubtypeHash = currentSubtype == null ? NOT_A_SUBTYPE_ID
+ : currentSubtype.hashCode();
+ // If the last IME is the same as the current IME and the last subtype is not
+ // defined, there is no need to switch to the last IME.
+ if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
+ targetLastImiId = lastIme.first;
+ subtypeId = SubtypeUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
+ }
+ }
+
+ if (TextUtils.isEmpty(targetLastImiId)
+ && !InputMethodUtils.canAddToLastInputMethod(currentSubtype)) {
+ // This is a safety net. If the currentSubtype can't be added to the history
+ // and the framework couldn't find the last ime, we will make the last ime be
+ // the most applicable enabled keyboard subtype of the system imes.
+ final List<InputMethodInfo> enabled = settings.getEnabledInputMethodList();
+ if (enabled != null) {
+ final int enabledCount = enabled.size();
+ final String locale;
+ if (currentSubtype != null
+ && !TextUtils.isEmpty(currentSubtype.getLocale())) {
+ locale = currentSubtype.getLocale();
+ } else {
+ locale = SystemLocaleWrapper.get(userId).get(0).toString();
+ }
+ for (int i = 0; i < enabledCount; ++i) {
+ final InputMethodInfo imi = enabled.get(i);
+ if (imi.getSubtypeCount() > 0 && imi.isSystem()) {
+ InputMethodSubtype keyboardSubtype =
+ SubtypeUtils.findLastResortApplicableSubtype(
+ SubtypeUtils.getSubtypes(imi),
+ SubtypeUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
+ if (keyboardSubtype != null) {
+ targetLastImiId = imi.getId();
+ subtypeId = SubtypeUtils.getSubtypeIdFromHashCode(imi,
+ keyboardSubtype.hashCode());
+ if (keyboardSubtype.getLocale().equals(locale)) {
+ break;
}
}
}
}
}
+ }
- if (!TextUtils.isEmpty(targetLastImiId)) {
- if (DEBUG) {
- Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
- + ", from: " + bindingController.getSelectedMethodId() + ", "
- + subtypeId);
- }
- setInputMethodWithSubtypeIdLocked(token, targetLastImiId, subtypeId, userId);
- return true;
- } else {
- return false;
+ if (!TextUtils.isEmpty(targetLastImiId)) {
+ if (DEBUG) {
+ Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
+ + ", from: " + bindingController.getSelectedMethodId() + ", "
+ + subtypeId);
}
+ setInputMethodWithSubtypeIdLocked(targetLastImiId, subtypeId, userId);
+ return true;
+ } else {
+ return false;
}
}
@BinderThread
- private boolean switchToNextInputMethod(@NonNull IBinder token, boolean onlyCurrentIme,
- @NonNull UserData userData) {
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return false;
- }
- return switchToNextInputMethodLocked(token, onlyCurrentIme, userData);
- }
- }
-
@GuardedBy("ImfLock.class")
- private boolean switchToNextInputMethodLocked(@Nullable IBinder token, boolean onlyCurrentIme,
+ private boolean switchToNextInputMethodLocked(boolean onlyCurrentIme,
@NonNull UserData userData) {
final var bindingController = userData.mBindingController;
final var currentImi = bindingController.getSelectedMethod();
@@ -4319,26 +4228,21 @@
if (nextSubtype == null) {
return false;
}
- setInputMethodWithSubtypeIdLocked(token, nextSubtype.mImi.getId(),
- nextSubtype.mSubtypeId, userData.mUserId);
+ setInputMethodWithSubtypeIdLocked(nextSubtype.mImi.getId(), nextSubtype.mSubtypeId,
+ userData.mUserId);
return true;
}
@BinderThread
- private boolean shouldOfferSwitchingToNextInputMethod(@NonNull IBinder token,
- @NonNull UserData userData) {
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return false;
- }
- final var bindingController = userData.mBindingController;
- final var currentImi = bindingController.getSelectedMethod();
- final ImeSubtypeListItem nextSubtype = userData.mSwitchingController
- .getNextInputMethodLocked(false /* onlyCurrentIme */, currentImi,
- bindingController.getCurrentSubtype(),
- MODE_AUTO, true /* forward */);
- return nextSubtype != null;
- }
+ @GuardedBy("ImfLock.class")
+ private boolean shouldOfferSwitchingToNextInputMethodLocked(@NonNull UserData userData) {
+ final var bindingController = userData.mBindingController;
+ final var currentImi = bindingController.getSelectedMethod();
+ final ImeSubtypeListItem nextSubtype = userData.mSwitchingController
+ .getNextInputMethodLocked(false /* onlyCurrentIme */, currentImi,
+ bindingController.getCurrentSubtype(),
+ MODE_AUTO, true /* forward */);
+ return nextSubtype != null;
}
@Override
@@ -4767,92 +4671,58 @@
}
@BinderThread
- private void notifyUserAction(@NonNull IBinder token, @NonNull UserData userData) {
+ @GuardedBy("ImfLock.class")
+ private void notifyUserActionLocked(@NonNull UserData userData) {
if (DEBUG) {
Slog.d(TAG, "Got the notification of a user action.");
}
- synchronized (ImfLock.class) {
- final var bindingController = userData.mBindingController;
- if (bindingController.getCurToken() != token) {
- if (DEBUG) {
- Slog.d(TAG, "Ignoring the user action notification from IMEs that are no longer"
- + " active.");
- }
- return;
- }
- final InputMethodInfo imi = bindingController.getSelectedMethod();
- if (imi != null) {
- userData.mSwitchingController.onUserActionLocked(imi,
- bindingController.getCurrentSubtype());
- }
+ final var bindingController = userData.mBindingController;
+ final InputMethodInfo imi = bindingController.getSelectedMethod();
+ if (imi != null) {
+ userData.mSwitchingController.onUserActionLocked(imi,
+ bindingController.getCurrentSubtype());
}
}
@BinderThread
- private void applyImeVisibility(IBinder token, IBinder windowToken, boolean setVisible,
+ @GuardedBy("ImfLock.class")
+ private void applyImeVisibilityLocked(IBinder windowToken, boolean setVisible,
@NonNull ImeTracker.Token statsToken, @NonNull UserData userData) {
try {
- Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.applyImeVisibility");
+ Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.applyImeVisibilityLocked");
final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- ImeTracker.forLogging().onFailed(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- return;
- }
- ImeTracker.forLogging().onProgress(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- final var visibilityStateComputer = userData.mVisibilityStateComputer;
- final IBinder requestToken = visibilityStateComputer.getWindowTokenFrom(
- windowToken, userId);
- mVisibilityApplier.applyImeVisibility(requestToken, statsToken,
- setVisible ? STATE_SHOW_IME : STATE_HIDE_IME,
- SoftInputShowHideReason.NOT_SET /* ignore reason */, userId);
- }
+ final var visibilityStateComputer = userData.mVisibilityStateComputer;
+ final IBinder requestToken = visibilityStateComputer.getWindowTokenFrom(
+ windowToken, userId);
+ mVisibilityApplier.applyImeVisibility(requestToken, statsToken,
+ setVisible ? STATE_SHOW_IME : STATE_HIDE_IME,
+ SoftInputShowHideReason.NOT_SET /* ignore reason */, userId);
} finally {
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
}
}
@BinderThread
- private void resetStylusHandwriting(int requestId) {
- synchronized (ImfLock.class) {
- final OptionalInt curRequest = mHwController.getCurrentRequestId();
- if (!curRequest.isPresent() || curRequest.getAsInt() != requestId) {
- Slog.w(TAG, "IME requested to finish handwriting with a mismatched requestId: "
- + requestId);
- }
- removeVirtualStylusIdForTestSessionLocked();
- scheduleResetStylusHandwriting();
+ @GuardedBy("ImfLock.class")
+ private void resetStylusHandwritingLocked(int requestId) {
+ final OptionalInt curRequest = mHwController.getCurrentRequestId();
+ if (!curRequest.isPresent() || curRequest.getAsInt() != requestId) {
+ Slog.w(TAG, "IME requested to finish handwriting with a mismatched requestId: "
+ + requestId);
}
+ removeVirtualStylusIdForTestSessionLocked();
+ scheduleResetStylusHandwriting();
}
@GuardedBy("ImfLock.class")
- private void setInputMethodWithSubtypeIdLocked(IBinder token, String id, int subtypeId,
+ private void setInputMethodWithSubtypeIdLocked(String id, int subtypeId,
@UserIdInt int userId) {
- final var bindingController = getInputMethodBindingController(userId);
- if (token == null) {
- if (mContext.checkCallingOrSelfPermission(
- android.Manifest.permission.WRITE_SECURE_SETTINGS)
- != PackageManager.PERMISSION_GRANTED) {
- throw new SecurityException(
- "Using null token requires permission "
- + android.Manifest.permission.WRITE_SECURE_SETTINGS);
- }
- } else if (bindingController.getCurToken() != token) {
- Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
- + " token: " + token);
- return;
- } else {
- // Called with current IME's token.
- final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
- if (settings.getMethodMap().get(id) != null
- && settings.getEnabledInputMethodListWithFilter(
- (info) -> info.getId().equals(id)).isEmpty()) {
- throw new IllegalStateException("Requested IME is not enabled: " + id);
- }
+ final InputMethodSettings settings = InputMethodSettingsRepository.get(userId);
+ if (settings.getMethodMap().get(id) != null
+ && settings.getEnabledInputMethodListWithFilter(
+ (info) -> info.getId().equals(id)).isEmpty()) {
+ throw new IllegalStateException("Requested IME is not enabled: " + id);
}
-
final long ident = Binder.clearCallingIdentity();
try {
setInputMethodLocked(id, subtypeId, userId);
@@ -4890,72 +4760,36 @@
}
@BinderThread
- private void hideMySoftInput(@NonNull IBinder token, @NonNull ImeTracker.Token statsToken,
+ @GuardedBy("ImfLock.class")
+ private void hideMySoftInputLocked(@NonNull ImeTracker.Token statsToken,
@InputMethodManager.HideFlags int flags, @SoftInputShowHideReason int reason,
@NonNull UserData userData) {
- try {
- Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.hideMySoftInput");
- final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- ImeTracker.forLogging().onFailed(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- return;
- }
- ImeTracker.forLogging().onProgress(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- final long ident = Binder.clearCallingIdentity();
- try {
- if (Flags.refactorInsetsController()) {
- userData.mCurClient.mClient.setImeVisibility(false, statsToken);
- // TODO we will loose the flags here
- setImeVisibilityOnFocusedWindowClient(false, userData, statsToken);
- } else {
- final var visibilityStateComputer = userData.mVisibilityStateComputer;
- hideCurrentInputLocked(visibilityStateComputer.getLastImeTargetWindow(),
- statsToken, flags, null /* resultReceiver */, reason, userId);
- }
- } finally {
- Binder.restoreCallingIdentity(ident);
- }
- }
- } finally {
- Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
+ final int userId = userData.mUserId;
+ if (Flags.refactorInsetsController()) {
+ userData.mCurClient.mClient.setImeVisibility(false, statsToken);
+ // TODO we will loose the flags here
+ setImeVisibilityOnFocusedWindowClient(false, userData, statsToken);
+ } else {
+ final var visibilityStateComputer = userData.mVisibilityStateComputer;
+ hideCurrentInputLocked(visibilityStateComputer.getLastImeTargetWindow(),
+ statsToken, flags, null /* resultReceiver */, reason, userId);
}
}
@BinderThread
- private void showMySoftInput(@NonNull IBinder token, @NonNull ImeTracker.Token statsToken,
+ @GuardedBy("ImfLock.class")
+ private void showMySoftInputLocked(@NonNull ImeTracker.Token statsToken,
@InputMethodManager.ShowFlags int flags, @SoftInputShowHideReason int reason,
@NonNull UserData userData) {
- try {
- Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.showMySoftInput");
- final int userId = userData.mUserId;
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- ImeTracker.forLogging().onFailed(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- return;
- }
- ImeTracker.forLogging().onProgress(statsToken,
- ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
- final long ident = Binder.clearCallingIdentity();
- try {
- if (Flags.refactorInsetsController()) {
- userData.mCurClient.mClient.setImeVisibility(true, statsToken);
- setImeVisibilityOnFocusedWindowClient(true, userData, statsToken);
- } else {
- final var visibilityStateComputer = userData.mVisibilityStateComputer;
- showCurrentInputLocked(visibilityStateComputer.getLastImeTargetWindow(),
- statsToken, flags, MotionEvent.TOOL_TYPE_UNKNOWN,
- null /* resultReceiver */, reason, userId);
- }
- } finally {
- Binder.restoreCallingIdentity(ident);
- }
- }
- } finally {
- Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
+ final int userId = userData.mUserId;
+ if (Flags.refactorInsetsController()) {
+ userData.mCurClient.mClient.setImeVisibility(true, statsToken);
+ setImeVisibilityOnFocusedWindowClient(true, userData, statsToken);
+ } else {
+ final var visibilityStateComputer = userData.mVisibilityStateComputer;
+ showCurrentInputLocked(visibilityStateComputer.getLastImeTargetWindow(),
+ statsToken, flags, MotionEvent.TOOL_TYPE_UNKNOWN,
+ null /* resultReceiver */, reason, userId);
}
}
@@ -5258,7 +5092,9 @@
private record HandwritingRequest(int requestId, int pid, @NonNull UserData userData) { }
@BinderThread
- private void onStylusHandwritingReady(int requestId, int pid, @NonNull UserData userData) {
+ @GuardedBy("ImfLock.class")
+ private void onStylusHandwritingReadyLocked(int requestId, int pid,
+ @NonNull UserData userData) {
mHandler.obtainMessage(MSG_START_HANDWRITING,
new HandwritingRequest(requestId, pid, userData)).sendToTarget();
}
@@ -6087,71 +5923,54 @@
}
@BinderThread
- private IInputContentUriToken createInputContentUriToken(@Nullable IBinder token,
- @Nullable Uri contentUri, @Nullable String packageName, @NonNull UserData userData) {
- if (token == null) {
- throw new NullPointerException("token");
- }
- if (packageName == null) {
- throw new NullPointerException("packageName");
- }
- if (contentUri == null) {
- throw new NullPointerException("contentUri");
- }
+ @GuardedBy("ImfLock.class")
+ @Nullable
+ private IInputContentUriToken createInputContentUriTokenLocked(@NonNull Uri contentUri,
+ @NonNull String packageName, @NonNull UserData userData) {
+ Objects.requireNonNull(packageName, "packageName must not be null");
+ Objects.requireNonNull(contentUri, "contentUri must not be null");
final String contentUriScheme = contentUri.getScheme();
if (!"content".equals(contentUriScheme)) {
throw new InvalidParameterException("contentUri must have content scheme");
}
- synchronized (ImfLock.class) {
- final int uid = Binder.getCallingUid();
- final var bindingController = userData.mBindingController;
- if (bindingController.getSelectedMethodId() == null) {
- return null;
- }
- if (bindingController.getCurToken() != token) {
- Slog.e(TAG, "Ignoring createInputContentUriToken mCurToken="
- + bindingController.getCurToken() + " token=" + token);
- return null;
- }
- // We cannot simply distinguish a bad IME that reports an arbitrary package name from
- // an unfortunate IME whose internal state is already obsolete due to the asynchronous
- // nature of our system. Let's compare it with our internal record.
- final var curPackageName = userData.mCurEditorInfo != null
- ? userData.mCurEditorInfo.packageName : null;
- if (!TextUtils.equals(curPackageName, packageName)) {
- Slog.e(TAG, "Ignoring createInputContentUriToken mCurEditorInfo.packageName="
- + curPackageName + " packageName=" + packageName);
- return null;
- }
- // This user ID can never be spoofed.
- final int appUserId = UserHandle.getUserId(userData.mCurClient.mUid);
- // This user ID may be invalid if "contentUri" embedded an invalid user ID.
- final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
- userData.mUserId);
- final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
- // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
- // actually has the right to grant a read permission for "contentUriWithoutUserId" that
- // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
- // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
- // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
- // actually allowed to "uid", which is guaranteed to be the IME's one.
- return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
- packageName, contentUriOwnerUserId, appUserId);
+ final int uid = Binder.getCallingUid();
+ final var bindingController = userData.mBindingController;
+ if (bindingController.getSelectedMethodId() == null) {
+ return null;
}
+ // We cannot simply distinguish a bad IME that reports an arbitrary package name from
+ // an unfortunate IME whose internal state is already obsolete due to the asynchronous
+ // nature of our system. Let's compare it with our internal record.
+ final var curPackageName = userData.mCurEditorInfo != null
+ ? userData.mCurEditorInfo.packageName : null;
+ if (!TextUtils.equals(curPackageName, packageName)) {
+ Slog.e(TAG, "Ignoring createInputContentUriTokenLocked mCurEditorInfo.packageName="
+ + curPackageName + " packageName=" + packageName);
+ return null;
+ }
+ // This user ID can never be spoofed.
+ final int appUserId = UserHandle.getUserId(userData.mCurClient.mUid);
+ // This user ID may be invalid if "contentUri" embedded an invalid user ID.
+ final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
+ userData.mUserId);
+ final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
+ // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
+ // actually has the right to grant a read permission for "contentUriWithoutUserId" that
+ // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
+ // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
+ // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
+ // actually allowed to "uid", which is guaranteed to be the IME's one.
+ return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
+ packageName, contentUriOwnerUserId, appUserId);
}
@BinderThread
- private void reportFullscreenMode(@NonNull IBinder token, boolean fullscreen,
- @NonNull UserData userData) {
- synchronized (ImfLock.class) {
- if (!calledWithValidTokenLocked(token, userData)) {
- return;
- }
- if (userData.mCurClient != null && userData.mCurClient.mClient != null) {
- userData.mInFullscreenMode = fullscreen;
- userData.mCurClient.mClient.reportFullscreenMode(fullscreen);
- }
+ @GuardedBy("ImfLock.class")
+ private void reportFullscreenModeLocked(boolean fullscreen, @NonNull UserData userData) {
+ if (userData.mCurClient != null && userData.mCurClient.mClient != null) {
+ userData.mInFullscreenMode = fullscreen;
+ userData.mCurClient.mClient.reportFullscreenMode(fullscreen);
}
}
@@ -6758,6 +6577,17 @@
out.print(imeId);
out.print(" selected for user #");
out.println(userId);
+
+ // Workaround for b/354782333.
+ final var settingsValue = SecureSettingsWrapper.getString(
+ Settings.Secure.DEFAULT_INPUT_METHOD, "", userId);
+ if (!TextUtils.equals(settingsValue, imeId)) {
+ Slog.w(TAG, "DEFAULT_INPUT_METHOD=" + settingsValue
+ + " is not updated. Fixing it up to " + imeId
+ + " See b/354782333.");
+ SecureSettingsWrapper.putString(
+ Settings.Secure.DEFAULT_INPUT_METHOD, imeId, userId);
+ }
}
hasFailed |= failedToSelectUnknownIme;
}
@@ -6944,13 +6774,14 @@
private static final class InputMethodPrivilegedOperationsImpl
extends IInputMethodPrivilegedOperations.Stub {
+ @NonNull
private final InputMethodManagerService mImms;
@NonNull
private final IBinder mToken;
@NonNull
private final UserData mUserData;
- InputMethodPrivilegedOperationsImpl(InputMethodManagerService imms,
+ InputMethodPrivilegedOperationsImpl(@NonNull InputMethodManagerService imms,
@NonNull IBinder token, @NonNull UserData userData) {
mImms = imms;
mToken = token;
@@ -6960,19 +6791,34 @@
@BinderThread
@Override
public void setImeWindowStatusAsync(int vis, int backDisposition) {
- mImms.setImeWindowStatus(mToken, vis, backDisposition, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.setImeWindowStatusLocked(vis, backDisposition, mUserData);
+ }
}
@BinderThread
@Override
public void reportStartInputAsync(IBinder startInputToken) {
- mImms.reportStartInput(mToken, startInputToken, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.reportStartInputLocked(startInputToken, mUserData);
+ }
}
@BinderThread
@Override
public void setHandwritingSurfaceNotTouchable(boolean notTouchable) {
- mImms.mHwController.setNotTouchable(notTouchable);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.mHwController.setNotTouchable(notTouchable);
+ }
}
@BinderThread
@@ -6981,8 +6827,14 @@
AndroidFuture future /* T=IBinder */) {
@SuppressWarnings("unchecked") final AndroidFuture<IBinder> typedFuture = future;
try {
- typedFuture.complete(mImms.createInputContentUriToken(
- mToken, contentUri, packageName, mUserData).asBinder());
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(null);
+ return;
+ }
+ typedFuture.complete(mImms.createInputContentUriTokenLocked(
+ contentUri, packageName, mUserData).asBinder());
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -6991,7 +6843,12 @@
@BinderThread
@Override
public void reportFullscreenModeAsync(boolean fullscreen) {
- mImms.reportFullscreenMode(mToken, fullscreen, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.reportFullscreenModeLocked(fullscreen, mUserData);
+ }
}
@BinderThread
@@ -6999,8 +6856,14 @@
public void setInputMethod(String id, AndroidFuture future /* T=Void */) {
@SuppressWarnings("unchecked") final AndroidFuture<Void> typedFuture = future;
try {
- mImms.setInputMethod(mToken, id, mUserData);
- typedFuture.complete(null);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(null);
+ return;
+ }
+ mImms.setInputMethodAndSubtypeLocked(id, null /* subtype */, mUserData);
+ typedFuture.complete(null);
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7012,8 +6875,14 @@
AndroidFuture future /* T=Void */) {
@SuppressWarnings("unchecked") final AndroidFuture<Void> typedFuture = future;
try {
- mImms.setInputMethodAndSubtype(mToken, id, subtype, mUserData);
- typedFuture.complete(null);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(null);
+ return;
+ }
+ mImms.setInputMethodAndSubtypeLocked(id, subtype, mUserData);
+ typedFuture.complete(null);
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7026,8 +6895,25 @@
AndroidFuture future /* T=Void */) {
@SuppressWarnings("unchecked") final AndroidFuture<Void> typedFuture = future;
try {
- mImms.hideMySoftInput(mToken, statsToken, flags, reason, mUserData);
- typedFuture.complete(null);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ ImeTracker.forLogging().onFailed(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ typedFuture.complete(null);
+ return;
+ }
+ ImeTracker.forLogging().onProgress(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.hideMySoftInput");
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ mImms.hideMySoftInputLocked(statsToken, flags, reason, mUserData);
+ typedFuture.complete(null);
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
+ }
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7040,8 +6926,25 @@
AndroidFuture future /* T=Void */) {
@SuppressWarnings("unchecked") final AndroidFuture<Void> typedFuture = future;
try {
- mImms.showMySoftInput(mToken, statsToken, flags, reason, mUserData);
- typedFuture.complete(null);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ ImeTracker.forLogging().onFailed(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ typedFuture.complete(null);
+ return;
+ }
+ ImeTracker.forLogging().onProgress(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.showMySoftInput");
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ mImms.showMySoftInputLocked(statsToken, flags, reason, mUserData);
+ typedFuture.complete(null);
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
+ }
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7050,7 +6953,17 @@
@BinderThread
@Override
public void updateStatusIconAsync(String packageName, @DrawableRes int iconId) {
- mImms.updateStatusIcon(mToken, packageName, iconId, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ mImms.updateStatusIconLocked(packageName, iconId, mUserData);
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
}
@BinderThread
@@ -7058,7 +6971,13 @@
public void switchToPreviousInputMethod(AndroidFuture future /* T=Boolean */) {
@SuppressWarnings("unchecked") final AndroidFuture<Boolean> typedFuture = future;
try {
- typedFuture.complete(mImms.switchToPreviousInputMethod(mToken, mUserData));
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(false);
+ return;
+ }
+ typedFuture.complete(mImms.switchToPreviousInputMethodLocked(mUserData));
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7070,8 +6989,14 @@
AndroidFuture future /* T=Boolean */) {
@SuppressWarnings("unchecked") final AndroidFuture<Boolean> typedFuture = future;
try {
- typedFuture.complete(mImms.switchToNextInputMethod(mToken, onlyCurrentIme,
- mUserData));
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(false);
+ return;
+ }
+ typedFuture.complete(mImms.switchToNextInputMethodLocked(onlyCurrentIme,
+ mUserData));
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7082,8 +7007,14 @@
public void shouldOfferSwitchingToNextInputMethod(AndroidFuture future /* T=Boolean */) {
@SuppressWarnings("unchecked") final AndroidFuture<Boolean> typedFuture = future;
try {
- typedFuture.complete(mImms.shouldOfferSwitchingToNextInputMethod(mToken,
- mUserData));
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ typedFuture.complete(false);
+ return;
+ }
+ typedFuture.complete(mImms.shouldOfferSwitchingToNextInputMethodLocked(
+ mUserData));
+ }
} catch (Throwable e) {
typedFuture.completeExceptionally(e);
}
@@ -7092,39 +7023,68 @@
@BinderThread
@Override
public void onImeSwitchButtonClickFromClient(int displayId) {
- mImms.onImeSwitchButtonClickFromClient(mToken, displayId, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.onImeSwitchButtonClickLocked(displayId, mUserData);
+ }
}
@BinderThread
@Override
public void notifyUserActionAsync() {
- mImms.notifyUserAction(mToken, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.notifyUserActionLocked(mUserData);
+ }
}
@BinderThread
@Override
public void applyImeVisibilityAsync(IBinder windowToken, boolean setVisible,
@NonNull ImeTracker.Token statsToken) {
- mImms.applyImeVisibility(mToken, windowToken, setVisible, statsToken, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ ImeTracker.forLogging().onFailed(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ return;
+ }
+ ImeTracker.forLogging().onProgress(statsToken,
+ ImeTracker.PHASE_SERVER_CURRENT_ACTIVE_IME);
+ mImms.applyImeVisibilityLocked(windowToken, setVisible, statsToken, mUserData);
+ }
}
@BinderThread
@Override
public void onStylusHandwritingReady(int requestId, int pid) {
- mImms.onStylusHandwritingReady(requestId, pid, mUserData);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.onStylusHandwritingReadyLocked(requestId, pid, mUserData);
+ }
}
@BinderThread
@Override
public void resetStylusHandwriting(int requestId) {
- mImms.resetStylusHandwriting(requestId);
+ synchronized (ImfLock.class) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
+ return;
+ }
+ mImms.resetStylusHandwritingLocked(requestId);
+ }
}
@BinderThread
@Override
public void switchKeyboardLayoutAsync(int direction) {
synchronized (ImfLock.class) {
- if (!mImms.calledWithValidTokenLocked(mToken, mUserData)) {
+ if (!calledWithValidTokenLocked(mToken, mUserData)) {
return;
}
final long ident = Binder.clearCallingIdentity();
@@ -7135,5 +7095,25 @@
}
}
}
+
+ /**
+ * Returns true iff the caller is identified to be the current input method with the token.
+ *
+ * @param token the window token given to the input method when it was started
+ * @param userData {@link UserData} of the calling IME process
+ * @return true if and only if non-null valid token is specified
+ */
+ @GuardedBy("ImfLock.class")
+ private static boolean calledWithValidTokenLocked(@NonNull IBinder token,
+ @NonNull UserData userData) {
+ Objects.requireNonNull(token, "token must not be null");
+ final var bindingController = userData.mBindingController;
+ if (token != bindingController.getCurToken()) {
+ Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
+ + " uid:" + Binder.getCallingUid() + " token:" + token);
+ return false;
+ }
+ return true;
+ }
}
}
diff --git a/services/core/java/com/android/server/notification/ConditionProviders.java b/services/core/java/com/android/server/notification/ConditionProviders.java
index 3cc0457..a44e553 100644
--- a/services/core/java/com/android/server/notification/ConditionProviders.java
+++ b/services/core/java/com/android/server/notification/ConditionProviders.java
@@ -17,7 +17,7 @@
package com.android.server.notification;
import static android.service.notification.Condition.STATE_TRUE;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
import android.app.INotificationManager;
import android.app.NotificationManager;
@@ -326,7 +326,7 @@
// if user turned on the mode, ignore the update unless the app also wants the
// mode on. this will update the origin of the mode and let the owner turn it
// off when the context ends
- if (r.condition != null && r.condition.source == UPDATE_ORIGIN_USER) {
+ if (r.condition != null && r.condition.source == ORIGIN_USER_IN_SYSTEMUI) {
if (r.condition.state == STATE_TRUE && c.state == STATE_TRUE) {
r.condition = c;
}
diff --git a/services/core/java/com/android/server/notification/DefaultDeviceEffectsApplier.java b/services/core/java/com/android/server/notification/DefaultDeviceEffectsApplier.java
index d060f8f2..c8cb54f 100644
--- a/services/core/java/com/android/server/notification/DefaultDeviceEffectsApplier.java
+++ b/services/core/java/com/android/server/notification/DefaultDeviceEffectsApplier.java
@@ -31,7 +31,7 @@
import android.service.notification.DeviceEffectsApplier;
import android.service.notification.ZenDeviceEffects;
import android.service.notification.ZenModeConfig;
-import android.service.notification.ZenModeConfig.ConfigChangeOrigin;
+import android.service.notification.ZenModeConfig.ConfigOrigin;
import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
@@ -72,7 +72,7 @@
}
@Override
- public void apply(ZenDeviceEffects effects, @ConfigChangeOrigin int origin) {
+ public void apply(ZenDeviceEffects effects, @ConfigOrigin int origin) {
Binder.withCleanCallingIdentity(() -> {
if (mLastAppliedEffects.shouldSuppressAmbientDisplay()
!= effects.shouldSuppressAmbientDisplay()) {
@@ -120,15 +120,16 @@
mLastAppliedEffects = effects;
}
- private void updateOrScheduleNightMode(boolean useNightMode, @ConfigChangeOrigin int origin) {
+ private void updateOrScheduleNightMode(boolean useNightMode, @ConfigOrigin int origin) {
mPendingNightMode = useNightMode;
// Changing the theme can be disruptive for the user (Activities are likely recreated, may
// lose some state). Therefore we only apply the change immediately if the rule was
// activated manually, or we are initializing, or the screen is currently off/dreaming.
- if (origin == ZenModeConfig.UPDATE_ORIGIN_INIT
- || origin == ZenModeConfig.UPDATE_ORIGIN_INIT_USER
- || origin == ZenModeConfig.UPDATE_ORIGIN_USER
+ if (origin == ZenModeConfig.ORIGIN_INIT
+ || origin == ZenModeConfig.ORIGIN_INIT_USER
+ || origin == ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI
+ || origin == ZenModeConfig.ORIGIN_USER_IN_APP
|| !mPowerManager.isInteractive()) {
unregisterScreenOffReceiver();
updateNightModeImmediately(useNightMode);
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 4179edd..45b8da5 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -5771,16 +5771,20 @@
Binder.getCallingUid());
}
- @ZenModeConfig.ConfigChangeOrigin
+ @ZenModeConfig.ConfigOrigin
private int computeZenOrigin(boolean fromUser) {
// "fromUser" is introduced with MODES_API, so only consider it in that case.
- // (Non-MODES_API behavior should also not depend at all on UPDATE_ORIGIN_USER).
+ // (Non-MODES_API behavior should also not depend at all on ORIGIN_USER_IN_X).
if (android.app.Flags.modesApi() && fromUser) {
- return ZenModeConfig.UPDATE_ORIGIN_USER;
+ if (isCallerSystemOrSystemUi()) {
+ return ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
+ } else {
+ return ZenModeConfig.ORIGIN_USER_IN_APP;
+ }
} else if (isCallerSystemOrSystemUi()) {
- return ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI;
+ return ZenModeConfig.ORIGIN_SYSTEM;
} else {
- return ZenModeConfig.UPDATE_ORIGIN_APP;
+ return ZenModeConfig.ORIGIN_APP;
}
}
@@ -6137,7 +6141,7 @@
enforcePolicyAccess(pkg, "setNotificationPolicy");
enforceUserOriginOnlyFromSystem(fromUser, "setNotificationPolicy");
int callingUid = Binder.getCallingUid();
- @ZenModeConfig.ConfigChangeOrigin int origin = computeZenOrigin(fromUser);
+ @ZenModeConfig.ConfigOrigin int origin = computeZenOrigin(fromUser);
boolean shouldApplyAsImplicitRule = android.app.Flags.modesApi()
&& !canManageGlobalZenPolicy(pkg, callingUid);
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index c09504f..821722b 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -30,7 +30,6 @@
import static android.app.NotificationManager.IMPORTANCE_MAX;
import static android.app.NotificationManager.IMPORTANCE_NONE;
import static android.app.NotificationManager.IMPORTANCE_UNSPECIFIED;
-
import static android.os.UserHandle.USER_SYSTEM;
import static android.service.notification.Flags.notificationClassification;
@@ -1979,8 +1978,8 @@
(areChannelsBypassingDnd
? NotificationManager.Policy.STATE_CHANNELS_BYPASSING_DND : 0),
policy.priorityConversationSenders),
- fromSystemOrSystemUi ? ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI
- : ZenModeConfig.UPDATE_ORIGIN_APP,
+ fromSystemOrSystemUi ? ZenModeConfig.ORIGIN_SYSTEM
+ : ZenModeConfig.ORIGIN_APP,
callingUid);
}
diff --git a/services/core/java/com/android/server/notification/ZenModeConditions.java b/services/core/java/com/android/server/notification/ZenModeConditions.java
index 3650536..268d835 100644
--- a/services/core/java/com/android/server/notification/ZenModeConditions.java
+++ b/services/core/java/com/android/server/notification/ZenModeConditions.java
@@ -116,8 +116,8 @@
if (DEBUG) Log.d(TAG, "onServiceAdded " + component);
final int callingUid = Binder.getCallingUid();
mHelper.setConfig(mHelper.getConfig(), component,
- callingUid == Process.SYSTEM_UID ? ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI
- : ZenModeConfig.UPDATE_ORIGIN_APP,
+ callingUid == Process.SYSTEM_UID ? ZenModeConfig.ORIGIN_SYSTEM
+ : ZenModeConfig.ORIGIN_APP,
"zmc.onServiceAdded:" + component, callingUid);
}
@@ -128,8 +128,8 @@
if (config == null) return;
final int callingUid = Binder.getCallingUid();
mHelper.setAutomaticZenRuleState(id, condition,
- callingUid == Process.SYSTEM_UID ? ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI
- : ZenModeConfig.UPDATE_ORIGIN_APP,
+ callingUid == Process.SYSTEM_UID ? ZenModeConfig.ORIGIN_SYSTEM
+ : ZenModeConfig.ORIGIN_APP,
callingUid);
}
diff --git a/services/core/java/com/android/server/notification/ZenModeEventLogger.java b/services/core/java/com/android/server/notification/ZenModeEventLogger.java
index 4a82057..b03a54e 100644
--- a/services/core/java/com/android/server/notification/ZenModeEventLogger.java
+++ b/services/core/java/com/android/server/notification/ZenModeEventLogger.java
@@ -34,7 +34,7 @@
import android.service.notification.DNDPolicyProto;
import android.service.notification.ZenAdapters;
import android.service.notification.ZenModeConfig;
-import android.service.notification.ZenModeConfig.ConfigChangeOrigin;
+import android.service.notification.ZenModeConfig.ConfigOrigin;
import android.service.notification.ZenModeConfig.ZenRule;
import android.service.notification.ZenModeDiff;
import android.service.notification.ZenPolicy;
@@ -113,7 +113,7 @@
* @param origin The origin of the Zen change.
*/
public final void maybeLogZenChange(ZenModeInfo prevInfo, ZenModeInfo newInfo, int callingUid,
- @ConfigChangeOrigin int origin) {
+ @ConfigOrigin int origin) {
mChangeState.init(prevInfo, newInfo, callingUid, origin);
if (mChangeState.shouldLogChanges()) {
maybeReassignCallingUid();
@@ -250,11 +250,11 @@
ZenModeConfig mPrevConfig, mNewConfig;
NotificationManager.Policy mPrevPolicy, mNewPolicy;
int mCallingUid = Process.INVALID_UID;
- @ConfigChangeOrigin
- int mOrigin = ZenModeConfig.UPDATE_ORIGIN_UNKNOWN;
+ @ConfigOrigin
+ int mOrigin = ZenModeConfig.ORIGIN_UNKNOWN;
private void init(ZenModeInfo prevInfo, ZenModeInfo newInfo, int callingUid,
- @ConfigChangeOrigin int origin) {
+ @ConfigOrigin int origin) {
// previous & new may be the same -- that would indicate that zen mode hasn't changed.
mPrevZenMode = prevInfo.mZenMode;
mNewZenMode = newInfo.mZenMode;
@@ -484,7 +484,8 @@
*/
boolean getIsUserAction() {
if (Flags.modesApi()) {
- return mOrigin == ZenModeConfig.UPDATE_ORIGIN_USER;
+ return mOrigin == ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI
+ || mOrigin == ZenModeConfig.ORIGIN_USER_IN_APP;
}
// Approach for pre-MODES_API:
@@ -549,10 +550,10 @@
}
boolean isFromSystemOrSystemUi() {
- return mOrigin == ZenModeConfig.UPDATE_ORIGIN_INIT
- || mOrigin == ZenModeConfig.UPDATE_ORIGIN_INIT_USER
- || mOrigin == ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI
- || mOrigin == ZenModeConfig.UPDATE_ORIGIN_RESTORE_BACKUP;
+ return mOrigin == ZenModeConfig.ORIGIN_INIT
+ || mOrigin == ZenModeConfig.ORIGIN_INIT_USER
+ || mOrigin == ZenModeConfig.ORIGIN_SYSTEM
+ || mOrigin == ZenModeConfig.ORIGIN_RESTORE_BACKUP;
}
/**
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index 95d8bb9..b164a52 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -29,13 +29,14 @@
import static android.service.notification.Condition.STATE_FALSE;
import static android.service.notification.Condition.STATE_TRUE;
import static android.service.notification.NotificationServiceProto.ROOT_CONFIG;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_APP;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_INIT;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_INIT_USER;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_RESTORE_BACKUP;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_UNKNOWN;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_APP;
+import static android.service.notification.ZenModeConfig.ORIGIN_INIT;
+import static android.service.notification.ZenModeConfig.ORIGIN_INIT_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_RESTORE_BACKUP;
+import static android.service.notification.ZenModeConfig.ORIGIN_SYSTEM;
+import static android.service.notification.ZenModeConfig.ORIGIN_UNKNOWN;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_APP;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
import static com.android.internal.util.FrameworkStatsLog.DND_MODE_RULE;
import static com.android.internal.util.Preconditions.checkArgument;
@@ -95,7 +96,7 @@
import android.service.notification.ZenAdapters;
import android.service.notification.ZenDeviceEffects;
import android.service.notification.ZenModeConfig;
-import android.service.notification.ZenModeConfig.ConfigChangeOrigin;
+import android.service.notification.ZenModeConfig.ConfigOrigin;
import android.service.notification.ZenModeConfig.ZenRule;
import android.service.notification.ZenModeProto;
import android.service.notification.ZenPolicy;
@@ -294,7 +295,7 @@
// "update" config to itself, which will have no effect in the case where a config
// was read in via XML, but will initialize zen mode if nothing was read in and the
// config remains the default.
- updateConfigAndZenModeLocked(mConfig, UPDATE_ORIGIN_INIT, "init",
+ updateConfigAndZenModeLocked(mConfig, ORIGIN_INIT, "init",
true /*setRingerMode*/, Process.SYSTEM_UID /* callingUid */);
}
}
@@ -328,7 +329,7 @@
}
mDeviceEffectsApplier = deviceEffectsApplier;
}
- applyConsolidatedDeviceEffects(UPDATE_ORIGIN_INIT);
+ applyConsolidatedDeviceEffects(ORIGIN_INIT);
}
public void onUserSwitched(int user) {
@@ -368,7 +369,7 @@
config.user = user;
}
synchronized (mConfigLock) {
- setConfigLocked(config, null, UPDATE_ORIGIN_INIT_USER, reason,
+ setConfigLocked(config, null, ORIGIN_INIT_USER, reason,
Process.SYSTEM_UID);
}
cleanUpZenRules();
@@ -384,7 +385,7 @@
final int newZen = NotificationManager.zenModeFromInterruptionFilter(filter, -1);
if (newZen != -1) {
setManualZenMode(newZen, null,
- fromSystemOrSystemUi ? UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI : UPDATE_ORIGIN_APP,
+ fromSystemOrSystemUi ? ORIGIN_SYSTEM : ORIGIN_APP,
/* reason= */ "listener:" + (name != null ? name.flattenToShortString() : null),
/* caller= */ name != null ? name.getPackageName() : null,
callingUid);
@@ -447,8 +448,8 @@
}
public String addAutomaticZenRule(String pkg, AutomaticZenRule automaticZenRule,
- @ConfigChangeOrigin int origin, String reason, int callingUid) {
- requirePublicOrigin("addAutomaticZenRule", origin);
+ @ConfigOrigin int origin, String reason, int callingUid) {
+ checkManageRuleOrigin("addAutomaticZenRule", origin);
if (!ZenModeConfig.SYSTEM_AUTHORITY.equals(pkg)) {
PackageItemInfo component = getServiceInfo(automaticZenRule.getOwner());
if (component == null) {
@@ -497,7 +498,7 @@
@GuardedBy("mConfigLock")
private ZenRule maybeRestoreRemovedRule(ZenModeConfig config, ZenRule ruleToAdd,
- AutomaticZenRule azrToAdd, @ConfigChangeOrigin int origin) {
+ AutomaticZenRule azrToAdd, @ConfigOrigin int origin) {
if (!Flags.modesApi()) {
return ruleToAdd;
}
@@ -517,7 +518,7 @@
config.deletedRules.remove(deletedKey);
ruleToRestore.deletionInstant = null;
- if (origin != UPDATE_ORIGIN_APP) {
+ if (origin != ORIGIN_APP) {
return ruleToAdd; // Okay to create anew.
}
@@ -547,8 +548,8 @@
}
public boolean updateAutomaticZenRule(String ruleId, AutomaticZenRule automaticZenRule,
- @ConfigChangeOrigin int origin, String reason, int callingUid) {
- requirePublicOrigin("updateAutomaticZenRule", origin);
+ @ConfigOrigin int origin, String reason, int callingUid) {
+ checkManageRuleOrigin("updateAutomaticZenRule", origin);
if (ruleId == null) {
throw new IllegalArgumentException("ruleId cannot be null");
}
@@ -621,7 +622,7 @@
mContext.getString(R.string.zen_mode_implicit_deactivated),
STATE_FALSE);
setAutomaticZenRuleStateLocked(newConfig, Collections.singletonList(rule),
- deactivated, UPDATE_ORIGIN_APP, callingUid);
+ deactivated, ORIGIN_APP, callingUid);
}
} else {
// Either create a new rule with a default ZenPolicy, or update an existing rule's
@@ -647,7 +648,7 @@
mContext.getString(R.string.zen_mode_implicit_activated),
STATE_TRUE);
- setConfigLocked(newConfig, /* triggeringComponent= */ null, UPDATE_ORIGIN_APP,
+ setConfigLocked(newConfig, /* triggeringComponent= */ null, ORIGIN_APP,
"applyGlobalZenModeAsImplicitZenRule", callingUid);
}
}
@@ -701,7 +702,7 @@
/* updateBitmask= */ false,
isNew);
- setConfigLocked(newConfig, /* triggeringComponent= */ null, UPDATE_ORIGIN_APP,
+ setConfigLocked(newConfig, /* triggeringComponent= */ null, ORIGIN_APP,
"applyGlobalPolicyAsImplicitZenRule", callingUid);
}
}
@@ -788,9 +789,9 @@
return ruleId.startsWith(IMPLICIT_RULE_ID_PREFIX);
}
- boolean removeAutomaticZenRule(String id, @ConfigChangeOrigin int origin, String reason,
+ boolean removeAutomaticZenRule(String id, @ConfigOrigin int origin, String reason,
int callingUid) {
- requirePublicOrigin("removeAutomaticZenRule", origin);
+ checkManageRuleOrigin("removeAutomaticZenRule", origin);
ZenModeConfig newConfig;
synchronized (mConfigLock) {
if (mConfig == null) return false;
@@ -821,9 +822,9 @@
}
}
- boolean removeAutomaticZenRules(String packageName, @ConfigChangeOrigin int origin,
+ boolean removeAutomaticZenRules(String packageName, @ConfigOrigin int origin,
String reason, int callingUid) {
- requirePublicOrigin("removeAutomaticZenRules", origin);
+ checkManageRuleOrigin("removeAutomaticZenRules", origin);
ZenModeConfig newConfig;
synchronized (mConfigLock) {
if (mConfig == null) return false;
@@ -837,7 +838,7 @@
}
// If the system is clearing all rules this means DND access is revoked or the package
// was uninstalled, so also clear the preserved-deleted rules.
- if (origin == UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI) {
+ if (origin == ORIGIN_SYSTEM) {
for (int i = newConfig.deletedRules.size() - 1; i >= 0; i--) {
ZenRule rule = newConfig.deletedRules.get(newConfig.deletedRules.keyAt(i));
if (Objects.equals(rule.getPkg(), packageName)) {
@@ -850,7 +851,7 @@
}
private void maybePreserveRemovedRule(ZenModeConfig config, ZenRule ruleToRemove,
- @ConfigChangeOrigin int origin) {
+ @ConfigOrigin int origin) {
if (!Flags.modesApi()) {
return;
}
@@ -859,7 +860,7 @@
// We don't try to preserve system-owned rules because their conditionIds (used as
// deletedRuleKey) are not stable. This is almost moot anyway because an app cannot
// delete a system-owned rule.
- if (origin == UPDATE_ORIGIN_APP && !ruleToRemove.canBeUpdatedByApp()
+ if (origin == ORIGIN_APP && !ruleToRemove.canBeUpdatedByApp()
&& !PACKAGE_ANDROID.equals(ruleToRemove.pkg)) {
String deletedKey = ZenModeConfig.deletedRuleKey(ruleToRemove);
if (deletedKey != null) {
@@ -888,9 +889,9 @@
}
}
- void setAutomaticZenRuleState(String id, Condition condition, @ConfigChangeOrigin int origin,
+ void setAutomaticZenRuleState(String id, Condition condition, @ConfigOrigin int origin,
int callingUid) {
- requirePublicOrigin("setAutomaticZenRuleState", origin);
+ checkSetRuleStateOrigin("setAutomaticZenRuleState(String id)", origin);
ZenModeConfig newConfig;
synchronized (mConfigLock) {
if (mConfig == null) return;
@@ -911,8 +912,8 @@
}
void setAutomaticZenRuleState(Uri ruleDefinition, Condition condition,
- @ConfigChangeOrigin int origin, int callingUid) {
- requirePublicOrigin("setAutomaticZenRuleState", origin);
+ @ConfigOrigin int origin, int callingUid) {
+ checkSetRuleStateOrigin("setAutomaticZenRuleState(Uri ruleDefinition)", origin);
ZenModeConfig newConfig;
synchronized (mConfigLock) {
if (mConfig == null) return;
@@ -932,11 +933,13 @@
@GuardedBy("mConfigLock")
private void setAutomaticZenRuleStateLocked(ZenModeConfig config, List<ZenRule> rules,
- Condition condition, @ConfigChangeOrigin int origin, int callingUid) {
+ Condition condition, @ConfigOrigin int origin, int callingUid) {
if (rules == null || rules.isEmpty()) return;
- if (Flags.modesApi() && condition.source == SOURCE_USER_ACTION) {
- origin = UPDATE_ORIGIN_USER; // Although coming from app, it's actually a user action.
+ if (!Flags.modesUi()) {
+ if (Flags.modesApi() && condition.source == SOURCE_USER_ACTION) {
+ origin = ORIGIN_USER_IN_APP; // Although coming from app, it's actually from user.
+ }
}
for (ZenRule rule : rules) {
@@ -1062,7 +1065,7 @@
}
}
if (updated) {
- setConfigLocked(config, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ setConfigLocked(config, null, ORIGIN_SYSTEM,
"updateZenRulesOnLocaleChange", Process.SYSTEM_UID);
}
}
@@ -1119,11 +1122,11 @@
* </ul>
*
* <p>The rule's {@link ZenRule#condition} is cleared (meaning that an active rule will be
- * deactivated) unless the update has origin == {@link ZenModeConfig#UPDATE_ORIGIN_USER}.
+ * deactivated) unless the update has origin == {@link ZenModeConfig#ORIGIN_USER_IN_SYSTEMUI}.
*/
@GuardedBy("mConfigLock")
private boolean populateZenRule(String pkg, AutomaticZenRule azr, ZenRule rule,
- @ConfigChangeOrigin int origin, boolean isNew) {
+ @ConfigOrigin int origin, boolean isNew) {
if (Flags.modesApi()) {
boolean modified = false;
// These values can always be edited by the app, so we apply changes immediately.
@@ -1137,7 +1140,7 @@
// Allow updating the CPS backing system rules (e.g. for custom manual -> schedule)
if (Flags.modesUi()
- && (origin == UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI || origin == UPDATE_ORIGIN_USER)
+ && (origin == ORIGIN_SYSTEM || origin == ORIGIN_USER_IN_SYSTEMUI)
&& Objects.equals(rule.pkg, SystemZenRules.PACKAGE_ANDROID)
&& !Objects.equals(rule.component, azr.getOwner())) {
rule.component = azr.getOwner();
@@ -1151,7 +1154,7 @@
rule.disabledOrigin = origin;
} else if (azr.isEnabled()) {
// Enabling or previously enabled. Clear disabler.
- rule.disabledOrigin = UPDATE_ORIGIN_UNKNOWN;
+ rule.disabledOrigin = ORIGIN_UNKNOWN;
}
}
@@ -1166,7 +1169,7 @@
Flags.modesApi()
&& (Flags.modesUi() || isWatch)
&& !isNew
- && origin == UPDATE_ORIGIN_USER
+ && origin == ORIGIN_USER_IN_SYSTEMUI
&& rule.enabled == azr.isEnabled()
&& rule.conditionId != null
&& rule.condition != null
@@ -1232,7 +1235,7 @@
}
// Updates the bitmasks if the origin of the change is the user.
- boolean updateBitmask = (origin == UPDATE_ORIGIN_USER);
+ boolean updateBitmask = (origin == ORIGIN_USER_IN_SYSTEMUI);
if (updateBitmask && !TextUtils.equals(previousName, azr.getName())) {
rule.userModifiedFields |= AutomaticZenRule.FIELD_NAME;
@@ -1263,7 +1266,7 @@
// Updates the bitmask and values for all device effect fields, based on the origin.
modified |= updateZenDeviceEffects(rule, azr.getDeviceEffects(),
- origin == UPDATE_ORIGIN_APP, updateBitmask);
+ origin == ORIGIN_APP, updateBitmask);
return modified;
} else {
@@ -1297,8 +1300,8 @@
* change. (Note that regardless of origin, fields can always be updated if they're not already
* user modified.)
*/
- private static boolean doesOriginAlwaysUpdateValues(@ConfigChangeOrigin int origin) {
- return origin == UPDATE_ORIGIN_USER || origin == UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI;
+ private static boolean doesOriginAlwaysUpdateValues(@ConfigOrigin int origin) {
+ return origin == ORIGIN_USER_IN_SYSTEMUI || origin == ORIGIN_SYSTEM;
}
/**
@@ -1539,7 +1542,7 @@
: AUTOMATIC_RULE_STATUS_DISABLED);
}
- void setManualZenMode(int zenMode, Uri conditionId, @ConfigChangeOrigin int origin,
+ void setManualZenMode(int zenMode, Uri conditionId, @ConfigOrigin int origin,
String reason, @Nullable String caller, int callingUid) {
setManualZenMode(zenMode, conditionId, origin, reason, caller, true /*setRingerMode*/,
callingUid);
@@ -1547,7 +1550,7 @@
Settings.Secure.SHOW_ZEN_SETTINGS_SUGGESTION, 0);
}
- private void setManualZenMode(int zenMode, Uri conditionId, @ConfigChangeOrigin int origin,
+ private void setManualZenMode(int zenMode, Uri conditionId, @ConfigOrigin int origin,
String reason, @Nullable String caller, boolean setRingerMode, int callingUid) {
ZenModeConfig newConfig;
synchronized (mConfigLock) {
@@ -1564,8 +1567,8 @@
newConfig.manualRule.zenMode = zenMode;
newConfig.manualRule.condition = new Condition(newConfig.manualRule.conditionId, "",
zenMode == Global.ZEN_MODE_OFF ? STATE_FALSE : STATE_TRUE,
- origin == UPDATE_ORIGIN_USER ? SOURCE_USER_ACTION : SOURCE_UNKNOWN);
- if (zenMode == Global.ZEN_MODE_OFF && origin != UPDATE_ORIGIN_USER) {
+ origin == ORIGIN_USER_IN_SYSTEMUI ? SOURCE_USER_ACTION : SOURCE_UNKNOWN);
+ if (zenMode == Global.ZEN_MODE_OFF && origin != ORIGIN_USER_IN_SYSTEMUI) {
// User deactivation of DND means just turning off the manual DND rule.
// For API calls (different origin) keep old behavior of snoozing all rules.
for (ZenRule automaticRule : newConfig.automaticRules.values()) {
@@ -1602,7 +1605,7 @@
}
public void setManualZenRuleDeviceEffects(ZenDeviceEffects deviceEffects,
- @ConfigChangeOrigin int origin, String reason, int callingUid) {
+ @ConfigOrigin int origin, String reason, int callingUid) {
if (!Flags.modesUi()) {
return;
}
@@ -1752,7 +1755,7 @@
if (DEBUG) Log.d(TAG, reason);
synchronized (mConfigLock) {
setConfigLocked(config, null,
- forRestore ? UPDATE_ORIGIN_RESTORE_BACKUP : UPDATE_ORIGIN_INIT, reason,
+ forRestore ? ORIGIN_RESTORE_BACKUP : ORIGIN_INIT, reason,
Process.SYSTEM_UID);
}
}
@@ -1787,7 +1790,7 @@
/**
* Sets the global notification policy used for priority only do not disturb
*/
- public void setNotificationPolicy(Policy policy, @ConfigChangeOrigin int origin,
+ public void setNotificationPolicy(Policy policy, @ConfigOrigin int origin,
int callingUid) {
synchronized (mConfigLock) {
if (policy == null || mConfig == null) return;
@@ -1843,7 +1846,7 @@
}
if (!newConfig.equals(mConfig)) {
- setConfigLocked(newConfig, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ setConfigLocked(newConfig, null, ORIGIN_SYSTEM,
"cleanUpZenRules", Process.SYSTEM_UID);
}
}
@@ -1893,20 +1896,20 @@
@GuardedBy("mConfigLock")
private boolean setConfigLocked(ZenModeConfig config, ComponentName triggeringComponent,
- @ConfigChangeOrigin int origin, String reason, int callingUid) {
+ @ConfigOrigin int origin, String reason, int callingUid) {
return setConfigLocked(config, origin, reason, triggeringComponent, true /*setRingerMode*/,
callingUid);
}
void setConfig(ZenModeConfig config, ComponentName triggeringComponent,
- @ConfigChangeOrigin int origin, String reason, int callingUid) {
+ @ConfigOrigin int origin, String reason, int callingUid) {
synchronized (mConfigLock) {
setConfigLocked(config, triggeringComponent, origin, reason, callingUid);
}
}
@GuardedBy("mConfigLock")
- private boolean setConfigLocked(ZenModeConfig config, @ConfigChangeOrigin int origin,
+ private boolean setConfigLocked(ZenModeConfig config, @ConfigOrigin int origin,
String reason, ComponentName triggeringComponent, boolean setRingerMode,
int callingUid) {
final long identity = Binder.clearCallingIdentity();
@@ -1954,7 +1957,7 @@
* If logging is enabled, will also request logging of the outcome of this change if needed.
*/
@GuardedBy("mConfigLock")
- private void updateConfigAndZenModeLocked(ZenModeConfig config, @ConfigChangeOrigin int origin,
+ private void updateConfigAndZenModeLocked(ZenModeConfig config, @ConfigOrigin int origin,
String reason, boolean setRingerMode, int callingUid) {
final boolean logZenModeEvents = mFlagResolver.isEnabled(
SystemUiSystemPropertiesFlags.NotificationFlags.LOG_DND_STATE_EVENTS);
@@ -1963,7 +1966,7 @@
mZenMode, mConfig, mConsolidatedPolicy);
if (!config.equals(mConfig)) {
// Schedule broadcasts. Cannot be sent during boot, though.
- if (Flags.modesApi() && origin != UPDATE_ORIGIN_INIT) {
+ if (Flags.modesApi() && origin != ORIGIN_INIT) {
for (ZenRule rule : config.automaticRules.values()) {
ZenRule original = mConfig.automaticRules.get(rule.id);
if (original != null) {
@@ -2020,7 +2023,7 @@
@VisibleForTesting
@GuardedBy("mConfigLock")
- protected void evaluateZenModeLocked(@ConfigChangeOrigin int origin, String reason,
+ protected void evaluateZenModeLocked(@ConfigOrigin int origin, String reason,
boolean setRingerMode) {
if (DEBUG) Log.d(TAG, "evaluateZenMode");
if (mConfig == null) return;
@@ -2111,7 +2114,7 @@
}
@GuardedBy("mConfigLock")
- private void updateAndApplyConsolidatedPolicyAndDeviceEffects(@ConfigChangeOrigin int origin,
+ private void updateAndApplyConsolidatedPolicyAndDeviceEffects(@ConfigOrigin int origin,
String reason) {
synchronized (mConfigLock) {
if (mConfig == null) return;
@@ -2163,7 +2166,7 @@
}
}
- private void applyConsolidatedDeviceEffects(@ConfigChangeOrigin int source) {
+ private void applyConsolidatedDeviceEffects(@ConfigOrigin int source) {
if (!Flags.modesApi()) {
return;
}
@@ -2506,7 +2509,7 @@
}
if (newZen != -1) {
- setManualZenMode(newZen, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ setManualZenMode(newZen, null, ORIGIN_SYSTEM,
"ringerModeInternal", /* caller= */ null, /* setRingerMode= */ false,
Process.SYSTEM_UID);
}
@@ -2551,7 +2554,7 @@
break;
}
if (newZen != -1) {
- setManualZenMode(newZen, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ setManualZenMode(newZen, null, ORIGIN_SYSTEM,
"ringerModeExternal", caller, false /*setRingerMode*/, Process.SYSTEM_UID);
}
@@ -2708,15 +2711,33 @@
}
}
- /** Checks that the {@code origin} supplied to a ZenModeHelper "API" method makes sense. */
- private static void requirePublicOrigin(String method, @ConfigChangeOrigin int origin) {
+ /**
+ * Checks that the {@code origin} supplied to ZenModeHelper rule-management API methods
+ * ({@link #addAutomaticZenRule}, {@link #removeAutomaticZenRule}, etc, makes sense.
+ */
+ private static void checkManageRuleOrigin(String method, @ConfigOrigin int origin) {
if (!Flags.modesApi()) {
return;
}
- checkArgument(origin == UPDATE_ORIGIN_APP || origin == UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI
- || origin == UPDATE_ORIGIN_USER,
- "Expected one of UPDATE_ORIGIN_APP, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, or "
- + "UPDATE_ORIGIN_USER for %s, but received '%s'.",
+ checkArgument(origin == ORIGIN_APP || origin == ORIGIN_SYSTEM
+ || origin == ORIGIN_USER_IN_SYSTEMUI,
+ "Expected one of ORIGIN_APP, ORIGIN_SYSTEM, or "
+ + "ORIGIN_USER_IN_SYSTEMUI for %s, but received '%s'.",
+ method, origin);
+ }
+
+ /**
+ * Checks that the {@code origin} supplied to {@link #setAutomaticZenRuleState} overloads makes
+ * sense.
+ */
+ private static void checkSetRuleStateOrigin(String method, @ConfigOrigin int origin) {
+ if (!Flags.modesApi()) {
+ return;
+ }
+ checkArgument(origin == ORIGIN_APP || origin == ORIGIN_USER_IN_APP
+ || origin == ORIGIN_SYSTEM || origin == ORIGIN_USER_IN_SYSTEMUI,
+ "Expected one of ORIGIN_APP, ORIGIN_USER_IN_APP, ORIGIN_SYSTEM, or "
+ + "ORIGIN_USER_IN_SYSTEMUI for %s, but received '%s'.",
method, origin);
}
@@ -2841,7 +2862,7 @@
}
}
- private void postApplyDeviceEffects(@ConfigChangeOrigin int origin) {
+ private void postApplyDeviceEffects(@ConfigOrigin int origin) {
removeMessages(MSG_APPLY_EFFECTS);
sendMessage(obtainMessage(MSG_APPLY_EFFECTS, origin, 0));
}
@@ -2862,7 +2883,7 @@
updateRingerAndAudio(/* shouldApplyToRinger= */ false);
break;
case MSG_APPLY_EFFECTS:
- @ConfigChangeOrigin int origin = msg.arg1;
+ @ConfigOrigin int origin = msg.arg1;
applyConsolidatedDeviceEffects(origin);
break;
}
diff --git a/services/core/java/com/android/server/pm/AppDataHelper.java b/services/core/java/com/android/server/pm/AppDataHelper.java
index 8b72138..29f8243 100644
--- a/services/core/java/com/android/server/pm/AppDataHelper.java
+++ b/services/core/java/com/android/server/pm/AppDataHelper.java
@@ -127,7 +127,7 @@
}
// TODO(b/211761016): should we still create the profile dirs?
- if (ps.getPkg() != null && !shouldHaveAppStorage(ps.getPkg())) {
+ if (!shouldHaveAppStorage(ps)) {
Slog.w(TAG, "Skipping preparing app data for " + ps.getPackageName());
return;
}
@@ -172,19 +172,19 @@
}
private void prepareAppDataAndMigrate(@NonNull Installer.Batch batch,
- @NonNull AndroidPackage pkg, @UserIdInt int userId,
+ @NonNull PackageStateInternal psi, @UserIdInt int userId,
@StorageManager.StorageFlags int flags, boolean maybeMigrateAppData) {
- if (pkg == null) {
+ if (psi == null || psi.getPkg() == null) {
Slog.wtf(TAG, "Package was null!", new Throwable());
return;
}
- if (!shouldHaveAppStorage(pkg)) {
- Slog.w(TAG, "Skipping preparing app data for " + pkg.getPackageName());
+ if (!shouldHaveAppStorage(psi)) {
+ Slog.w(TAG, "Skipping preparing app data for " + psi.getPackageName());
return;
}
final PackageSetting ps;
synchronized (mPm.mLock) {
- ps = mPm.mSettings.getPackageLPr(pkg.getPackageName());
+ ps = mPm.mSettings.getPackageLPr(psi.getPackageName());
}
prepareAppData(batch, ps, Process.INVALID_UID, userId, flags).thenRun(() -> {
// Note: this code block is executed with the Installer lock
@@ -449,7 +449,7 @@
}
if (ps.getUserStateOrDefault(userId).isInstalled()) {
- prepareAppDataAndMigrate(batch, ps.getPkg(), userId, flags, migrateAppData);
+ prepareAppDataAndMigrate(batch, ps, userId, flags, migrateAppData);
preparedCount++;
}
}
@@ -484,8 +484,7 @@
+ " or was deleted without DELETE_KEEP_DATA",
PackageManagerException.INTERNAL_ERROR_STORAGE_INVALID_NOT_INSTALLED_FOR_USER);
}
- if (packageState.getPkg() != null
- && !shouldHaveAppStorage(packageState.getPkg())) {
+ if (!shouldHaveAppStorage(packageState)) {
throw PackageManagerException.ofInternalError(
"Package " + packageName + " shouldn't have storage",
PackageManagerException.INTERNAL_ERROR_STORAGE_INVALID_SHOULD_NOT_HAVE_STORAGE);
@@ -535,8 +534,7 @@
if (packageStateInternal != null
&& packageStateInternal.getUserStateOrDefault(
UserHandle.USER_SYSTEM).isInstalled()) {
- AndroidPackage pkg = packageStateInternal.getPkg();
- prepareAppDataAndMigrate(batch, pkg,
+ prepareAppDataAndMigrate(batch, packageStateInternal,
UserHandle.USER_SYSTEM, storageFlags, true /* maybeMigrateAppData */);
count++;
}
@@ -637,12 +635,16 @@
}
/**
- * Returns {@code true} if app's internal storage should be created for this {@code pkg}.
+ * Returns {@code true} if app's internal storage should be created for this {@code ps}.
*/
- private boolean shouldHaveAppStorage(AndroidPackage pkg) {
+ private boolean shouldHaveAppStorage(PackageStateInternal ps) {
+ if (ps.getPkg() == null) {
+ // Keeps the legacy behavior
+ return true;
+ }
PackageManager.Property noAppDataProp =
- pkg.getProperties().get(PackageManager.PROPERTY_NO_APP_DATA_STORAGE);
- return (noAppDataProp == null || !noAppDataProp.getBoolean()) && pkg.getUid() >= 0;
+ ps.getPkg().getProperties().get(PackageManager.PROPERTY_NO_APP_DATA_STORAGE);
+ return (noAppDataProp == null || !noAppDataProp.getBoolean()) && ps.getAppId() >= 0;
}
/**
diff --git a/services/core/java/com/android/server/pm/DeletePackageHelper.java b/services/core/java/com/android/server/pm/DeletePackageHelper.java
index b56e119..8398ffc 100644
--- a/services/core/java/com/android/server/pm/DeletePackageHelper.java
+++ b/services/core/java/com/android/server/pm/DeletePackageHelper.java
@@ -690,7 +690,13 @@
public void deletePackageVersionedInternal(VersionedPackage versionedPackage,
final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags,
final boolean allowSilentUninstall) {
- final int callingUid = Binder.getCallingUid();
+ deletePackageVersionedInternal(versionedPackage, observer, userId, deleteFlags,
+ Binder.getCallingUid(), allowSilentUninstall);
+ }
+
+ public void deletePackageVersionedInternal(VersionedPackage versionedPackage,
+ final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags,
+ final int callingUid, final boolean allowSilentUninstall) {
mPm.mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.DELETE_PACKAGES, null);
final Computer snapshot = mPm.snapshotComputer();
@@ -720,16 +726,22 @@
final String internalPackageName =
snapshot.resolveInternalPackageName(packageName, versionCode);
- final int uid = Binder.getCallingUid();
if (!isOrphaned(snapshot, internalPackageName)
&& !allowSilentUninstall
&& !isCallerAllowedToSilentlyUninstall(
- snapshot, uid, internalPackageName, userId)) {
+ snapshot, callingUid, internalPackageName, userId)) {
mPm.mHandler.post(() -> {
try {
final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
- intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
+ intent.putExtra(PackageInstaller.EXTRA_CALLBACK,
+ new PackageManager.UninstallCompleteCallback(observer.asBinder()));
+ if ((deleteFlags & PackageManager.DELETE_ARCHIVE) != 0) {
+ // Delete flags are passed to the uninstaller activity so it can be
+ // preserved in the follow-up uninstall operation after the user
+ // confirmation
+ intent.putExtra(PackageInstaller.EXTRA_DELETE_FLAGS, deleteFlags);
+ }
observer.onUserActionRequired(intent);
} catch (RemoteException re) {
}
@@ -738,7 +750,7 @@
}
final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
final int[] users = deleteAllUsers ? mUserManagerInternal.getUserIds() : new int[]{userId};
- if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
+ if (UserHandle.getUserId(callingUid) != userId || (deleteAllUsers && users.length > 1)) {
mPm.mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
"deletePackage for user " + userId);
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 7156795..be6fa14 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -1438,7 +1438,8 @@
if (mContext.checkPermission(Manifest.permission.DELETE_PACKAGES, callingPid, callingUid)
== PackageManager.PERMISSION_GRANTED) {
// Sweet, call straight through!
- mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
+ mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags,
+ callingUid);
} else if (canSilentlyInstallPackage) {
// Allow the device owner and affiliated profile owner to silently delete packages
// Need to clear the calling identity to get DELETE_PACKAGES permission
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 33ca8a8..20859da 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -3323,9 +3323,17 @@
}
public void deletePackageVersioned(VersionedPackage versionedPackage,
+ final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags,
+ final int callingUid) {
+ mDeletePackageHelper.deletePackageVersionedInternal(
+ versionedPackage, observer, userId, deleteFlags, callingUid,
+ /* allowSilentUninstall= */ false);
+ }
+
+ public void deletePackageVersioned(VersionedPackage versionedPackage,
final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
mDeletePackageHelper.deletePackageVersionedInternal(
- versionedPackage, observer, userId, deleteFlags, false);
+ versionedPackage, observer, userId, deleteFlags, /* allowSilentUninstall= */ false);
}
boolean isCallerVerifier(@NonNull Computer snapshot, int callingUid) {
diff --git a/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java b/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
index 3f9da82..eccbffb 100644
--- a/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
+++ b/services/core/java/com/android/server/vibrator/HapticFeedbackVibrationProvider.java
@@ -22,7 +22,6 @@
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorInfo;
-import android.os.vibrator.Flags;
import android.util.Slog;
import android.util.SparseArray;
import android.view.HapticFeedbackConstants;
@@ -348,7 +347,7 @@
predefinedEffectId = VibrationEffect.EFFECT_CLICK;
predefinedEffectFallback = true;
}
- if (Flags.keyboardCategoryEnabled() && mKeyboardVibrationFixedAmplitude > 0) {
+ if (mKeyboardVibrationFixedAmplitude > 0) {
if (mVibratorInfo.isPrimitiveSupported(primitiveId)) {
return VibrationEffect.startComposition()
.addPrimitive(primitiveId, mKeyboardVibrationFixedAmplitude)
@@ -361,10 +360,6 @@
private VibrationAttributes createKeyboardVibrationAttributes(
@HapticFeedbackConstants.PrivateFlags int privFlags) {
- // Use touch attribute when the keyboard category is disable.
- if (!Flags.keyboardCategoryEnabled()) {
- return TOUCH_VIBRATION_ATTRIBUTES;
- }
// Use touch attribute when the haptic is not apply to IME.
if ((privFlags & HapticFeedbackConstants.PRIVATE_FLAG_APPLY_INPUT_METHOD_SETTINGS) == 0) {
return TOUCH_VIBRATION_ATTRIBUTES;
diff --git a/services/core/java/com/android/server/vibrator/VibrationSettings.java b/services/core/java/com/android/server/vibrator/VibrationSettings.java
index fb92d60..f2f5eda 100644
--- a/services/core/java/com/android/server/vibrator/VibrationSettings.java
+++ b/services/core/java/com/android/server/vibrator/VibrationSettings.java
@@ -55,7 +55,6 @@
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.Vibrator.VibrationIntensity;
-import android.os.vibrator.Flags;
import android.os.vibrator.VibrationConfig;
import android.provider.Settings;
import android.util.IndentingPrintWriter;
@@ -533,8 +532,7 @@
return false;
}
- if (Flags.keyboardCategoryEnabled()
- && mVibrationConfig.isKeyboardVibrationSettingsSupported()) {
+ if (mVibrationConfig.isKeyboardVibrationSettingsSupported()) {
int category = callerInfo.attrs.getCategory();
if (usage == USAGE_TOUCH && category == CATEGORY_KEYBOARD) {
// Keyboard touch has a different user setting.
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/DefaultDeviceEffectsApplierTest.java b/services/tests/uiservicestests/src/com/android/server/notification/DefaultDeviceEffectsApplierTest.java
index 4bea95f..7933f7a 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/DefaultDeviceEffectsApplierTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/DefaultDeviceEffectsApplierTest.java
@@ -18,8 +18,8 @@
import static android.app.UiModeManager.MODE_ATTENTION_THEME_OVERLAY_NIGHT;
import static android.app.UiModeManager.MODE_ATTENTION_THEME_OVERLAY_OFF;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_APP;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_APP;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
import static com.google.common.truth.Truth.assertThat;
@@ -48,7 +48,6 @@
import android.os.PowerManager;
import android.platform.test.flag.junit.SetFlagsRule;
import android.service.notification.ZenDeviceEffects;
-import android.service.notification.ZenModeConfig;
import android.testing.TestableContext;
import androidx.test.InstrumentationRegistry;
@@ -78,27 +77,6 @@
@Mock UiModeManager mUiModeManager;
@Mock WallpaperManager mWallpaperManager;
- private enum ChangeOrigin {
- ORIGIN_UNKNOWN(ZenModeConfig.UPDATE_ORIGIN_UNKNOWN),
- ORIGIN_INIT(ZenModeConfig.UPDATE_ORIGIN_INIT),
- ORIGIN_INIT_USER(ZenModeConfig.UPDATE_ORIGIN_INIT_USER),
- ORIGIN_USER(ZenModeConfig.UPDATE_ORIGIN_USER),
- ORIGIN_APP(ZenModeConfig.UPDATE_ORIGIN_APP),
- ORIGIN_SYSTEM_OR_SYSTEMUI(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI),
- ORIGIN_RESTORE_BACKUP(ZenModeConfig.UPDATE_ORIGIN_RESTORE_BACKUP);
-
- private final int mValue;
-
- ChangeOrigin(@ZenModeConfig.ConfigChangeOrigin int value) {
- mValue = value;
- }
-
- @ZenModeConfig.ConfigChangeOrigin
- public int value() {
- return mValue;
- }
- }
-
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
@@ -123,7 +101,7 @@
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
.build();
- mApplier.apply(effects, UPDATE_ORIGIN_USER);
+ mApplier.apply(effects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(true));
verify(mColorDisplayManager).setSaturationLevel(eq(0));
@@ -141,14 +119,14 @@
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
.build();
- mApplier.apply(previousEffects, UPDATE_ORIGIN_USER);
+ mApplier.apply(previousEffects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(true));
verify(mColorDisplayManager).setSaturationLevel(eq(0));
verify(mWallpaperManager).setWallpaperDimAmount(eq(0.6f));
verify(mUiModeManager).setAttentionModeThemeOverlay(eq(MODE_ATTENTION_THEME_OVERLAY_NIGHT));
ZenDeviceEffects noEffects = new ZenDeviceEffects.Builder().build();
- mApplier.apply(noEffects, UPDATE_ORIGIN_USER);
+ mApplier.apply(noEffects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(false));
verify(mColorDisplayManager).setSaturationLevel(eq(100));
@@ -163,11 +141,11 @@
ZenDeviceEffects previousEffects = new ZenDeviceEffects.Builder()
.setShouldSuppressAmbientDisplay(true)
.build();
- mApplier.apply(previousEffects, UPDATE_ORIGIN_USER);
+ mApplier.apply(previousEffects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(true));
ZenDeviceEffects noEffects = new ZenDeviceEffects.Builder().build();
- mApplier.apply(noEffects, UPDATE_ORIGIN_USER);
+ mApplier.apply(noEffects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(false));
verifyZeroInteractions(mColorDisplayManager, mWallpaperManager, mUiModeManager);
@@ -186,7 +164,7 @@
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
.build();
- mApplier.apply(effects, UPDATE_ORIGIN_USER);
+ mApplier.apply(effects, ORIGIN_USER_IN_SYSTEMUI);
verify(mPowerManager).suppressAmbientDisplay(anyString(), eq(true));
// (And no crash from missing services).
@@ -207,7 +185,7 @@
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
.build();
- mApplier.apply(effects, UPDATE_ORIGIN_USER);
+ mApplier.apply(effects, ORIGIN_USER_IN_SYSTEMUI);
verifyNoMoreInteractions(mWallpaperManager);
}
@@ -220,7 +198,7 @@
.setShouldDimWallpaper(true)
.setShouldDisplayGrayscale(true)
.build();
- mApplier.apply(effects, UPDATE_ORIGIN_USER);
+ mApplier.apply(effects, ORIGIN_USER_IN_SYSTEMUI);
verify(mColorDisplayManager).setSaturationLevel(eq(0));
verify(mWallpaperManager).setWallpaperDimAmount(eq(0.6f));
@@ -234,12 +212,12 @@
mSetFlagsRule.enableFlags(android.app.Flags.FLAG_MODES_API);
mApplier.apply(new ZenDeviceEffects.Builder().setShouldDimWallpaper(true).build(),
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
verify(mWallpaperManager).setWallpaperDimAmount(eq(0.6f));
// Apply a second effect and remove the first one.
mApplier.apply(new ZenDeviceEffects.Builder().setShouldDisplayGrayscale(true).build(),
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
// Wallpaper dimming was undone, Grayscale was applied, nothing else was touched.
verify(mWallpaperManager).setWallpaperDimAmount(eq(0.0f));
@@ -259,7 +237,7 @@
when(mPowerManager.isInteractive()).thenReturn(true);
mApplier.apply(new ZenDeviceEffects.Builder().setShouldUseNightMode(true).build(),
- UPDATE_ORIGIN_APP);
+ ORIGIN_APP);
// Effect was not yet applied, but a broadcast receiver was registered.
verifyZeroInteractions(mUiModeManager);
@@ -278,7 +256,7 @@
@Test
public void apply_nightModeWithScreenOff_appliedImmediately(
- @TestParameter ChangeOrigin origin) {
+ @TestParameter ZenChangeOrigin origin) {
mSetFlagsRule.enableFlags(android.app.Flags.FLAG_MODES_API);
when(mPowerManager.isInteractive()).thenReturn(false);
@@ -292,9 +270,10 @@
}
@Test
- @TestParameters({"{origin: ORIGIN_USER}", "{origin: ORIGIN_INIT}",
- "{origin: ORIGIN_INIT_USER}"})
- public void apply_nightModeWithScreenOn_appliedImmediatelyBasedOnOrigin(ChangeOrigin origin) {
+ @TestParameters({"{origin: ORIGIN_USER_IN_SYSTEMUI}", "{origin: ORIGIN_USER_IN_APP}",
+ "{origin: ORIGIN_INIT}", "{origin: ORIGIN_INIT_USER}"})
+ public void apply_nightModeWithScreenOn_appliedImmediatelyBasedOnOrigin(
+ ZenChangeOrigin origin) {
mSetFlagsRule.enableFlags(android.app.Flags.FLAG_MODES_API);
when(mPowerManager.isInteractive()).thenReturn(true);
@@ -309,8 +288,9 @@
@Test
@TestParameters({"{origin: ORIGIN_APP}", "{origin: ORIGIN_RESTORE_BACKUP}",
- "{origin: ORIGIN_SYSTEM_OR_SYSTEMUI}", "{origin: ORIGIN_UNKNOWN}"})
- public void apply_nightModeWithScreenOn_willBeAppliedLaterBasedOnOrigin(ChangeOrigin origin) {
+ "{origin: ORIGIN_SYSTEM}", "{origin: ORIGIN_UNKNOWN}"})
+ public void apply_nightModeWithScreenOn_willBeAppliedLaterBasedOnOrigin(
+ ZenChangeOrigin origin) {
mSetFlagsRule.enableFlags(android.app.Flags.FLAG_MODES_API);
when(mPowerManager.isInteractive()).thenReturn(true);
@@ -342,7 +322,7 @@
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
.build();
- mApplier.apply(effects, UPDATE_ORIGIN_USER);
+ mApplier.apply(effects, ORIGIN_USER_IN_SYSTEMUI);
// No crashes
}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 1b999e4..4bb8017 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -10064,7 +10064,7 @@
// verify that zen mode helper gets passed in a package name of "android"
verify(mockZenModeHelper).addAutomaticZenRule(eq("android"), eq(rule),
- eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_SYSTEM), anyString(), anyInt());
}
@Test
@@ -10086,7 +10086,7 @@
// verify that zen mode helper gets passed in a package name of "android"
verify(mockZenModeHelper).addAutomaticZenRule(eq("android"), eq(rule),
- eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_SYSTEM), anyString(), anyInt());
}
@Test
@@ -10106,7 +10106,7 @@
// verify that zen mode helper gets passed in the package name from the arg, not the owner
verify(mockZenModeHelper).addAutomaticZenRule(
- eq("another.package"), eq(rule), eq(ZenModeConfig.UPDATE_ORIGIN_APP),
+ eq("another.package"), eq(rule), eq(ZenModeConfig.ORIGIN_APP),
anyString(), anyInt()); // doesn't count as a system/systemui call
}
@@ -10221,7 +10221,7 @@
mBinderService.addAutomaticZenRule(SOME_ZEN_RULE, "pkg", /* fromUser= */ true);
verify(zenModeHelper).addAutomaticZenRule(eq("pkg"), eq(SOME_ZEN_RULE),
- eq(ZenModeConfig.UPDATE_ORIGIN_USER), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI), anyString(), anyInt());
}
@Test
@@ -10233,7 +10233,7 @@
mBinderService.addAutomaticZenRule(SOME_ZEN_RULE, "pkg", /* fromUser= */ false);
verify(zenModeHelper).addAutomaticZenRule(eq("pkg"), eq(SOME_ZEN_RULE),
- eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_SYSTEM), anyString(), anyInt());
}
@Test
@@ -10245,7 +10245,7 @@
mBinderService.addAutomaticZenRule(SOME_ZEN_RULE, "pkg", /* fromUser= */ false);
verify(zenModeHelper).addAutomaticZenRule(eq("pkg"), eq(SOME_ZEN_RULE),
- eq(ZenModeConfig.UPDATE_ORIGIN_APP), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_APP), anyString(), anyInt());
}
@Test
@@ -10267,7 +10267,7 @@
mBinderService.updateAutomaticZenRule("id", SOME_ZEN_RULE, /* fromUser= */ true);
verify(zenModeHelper).updateAutomaticZenRule(eq("id"), eq(SOME_ZEN_RULE),
- eq(ZenModeConfig.UPDATE_ORIGIN_USER), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI), anyString(), anyInt());
}
@Test
@@ -10289,7 +10289,7 @@
mBinderService.removeAutomaticZenRule("id", /* fromUser= */ true);
verify(zenModeHelper).removeAutomaticZenRule(eq("id"),
- eq(ZenModeConfig.UPDATE_ORIGIN_USER), anyString(), anyInt());
+ eq(ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI), anyString(), anyInt());
}
@Test
@@ -10304,7 +10304,8 @@
@Test
@EnableFlags(android.app.Flags.FLAG_MODES_API)
- public void setAutomaticZenRuleState_conditionFromUser_mappedToOriginUser() throws Exception {
+ public void setAutomaticZenRuleState_fromAppWithConditionFromUser_originUserInApp()
+ throws Exception {
ZenModeHelper zenModeHelper = setUpMockZenTest();
mService.setCallerIsNormalPackage();
@@ -10313,12 +10314,12 @@
mBinderService.setAutomaticZenRuleState("id", withSourceUser);
verify(zenModeHelper).setAutomaticZenRuleState(eq("id"), eq(withSourceUser),
- eq(ZenModeConfig.UPDATE_ORIGIN_USER), anyInt());
+ eq(ZenModeConfig.ORIGIN_USER_IN_APP), anyInt());
}
@Test
@EnableFlags(android.app.Flags.FLAG_MODES_API)
- public void setAutomaticZenRuleState_fromAppWithConditionNotFromUser_mappedToOriginApp()
+ public void setAutomaticZenRuleState_fromAppWithConditionNotFromUser_originApp()
throws Exception {
ZenModeHelper zenModeHelper = setUpMockZenTest();
mService.setCallerIsNormalPackage();
@@ -10328,12 +10329,26 @@
mBinderService.setAutomaticZenRuleState("id", withSourceContext);
verify(zenModeHelper).setAutomaticZenRuleState(eq("id"), eq(withSourceContext),
- eq(ZenModeConfig.UPDATE_ORIGIN_APP), anyInt());
+ eq(ZenModeConfig.ORIGIN_APP), anyInt());
}
@Test
@EnableFlags(android.app.Flags.FLAG_MODES_API)
- public void setAutomaticZenRuleState_fromSystemWithConditionNotFromUser_mappedToOriginSystem()
+ public void setAutomaticZenRuleState_fromSystemWithConditionFromUser_originUserInSystemUi()
+ throws Exception {
+ ZenModeHelper zenModeHelper = setUpMockZenTest();
+ mService.isSystemUid = true;
+
+ Condition withSourceContext = new Condition(Uri.parse("uri"), "summary", STATE_TRUE,
+ SOURCE_USER_ACTION);
+ mBinderService.setAutomaticZenRuleState("id", withSourceContext);
+
+ verify(zenModeHelper).setAutomaticZenRuleState(eq("id"), eq(withSourceContext),
+ eq(ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI), anyInt());
+ }
+ @Test
+ @EnableFlags(android.app.Flags.FLAG_MODES_API)
+ public void setAutomaticZenRuleState_fromSystemWithConditionNotFromUser_originSystem()
throws Exception {
ZenModeHelper zenModeHelper = setUpMockZenTest();
mService.isSystemUid = true;
@@ -10343,7 +10358,7 @@
mBinderService.setAutomaticZenRuleState("id", withSourceContext);
verify(zenModeHelper).setAutomaticZenRuleState(eq("id"), eq(withSourceContext),
- eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyInt());
+ eq(ZenModeConfig.ORIGIN_SYSTEM), anyInt());
}
/** Prepares for a zen-related test that uses a mocked {@link ZenModeHelper}. */
@@ -15508,7 +15523,7 @@
mBinderService.setInterruptionFilter("package", INTERRUPTION_FILTER_PRIORITY, false);
verify(zenModeHelper).setManualZenMode(eq(ZEN_MODE_IMPORTANT_INTERRUPTIONS), eq(null),
- eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyString(), eq("package"),
+ eq(ZenModeConfig.ORIGIN_SYSTEM), anyString(), eq("package"),
anyInt());
}
@@ -15554,7 +15569,7 @@
if (canSetGlobalPolicy) {
verify(zenModeHelper).setManualZenMode(eq(ZEN_MODE_IMPORTANT_INTERRUPTIONS), eq(null),
- eq(ZenModeConfig.UPDATE_ORIGIN_APP), anyString(), eq("package"), anyInt());
+ eq(ZenModeConfig.ORIGIN_APP), anyString(), eq("package"), anyInt());
} else {
verify(zenModeHelper).applyGlobalZenModeAsImplicitZenRule(anyString(), anyInt(),
eq(ZEN_MODE_IMPORTANT_INTERRUPTIONS));
@@ -15594,7 +15609,7 @@
INTERRUPTION_FILTER_PRIORITY);
verify(mService.mZenModeHelper).setManualZenMode(eq(ZEN_MODE_IMPORTANT_INTERRUPTIONS),
- eq(null), eq(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI), anyString(),
+ eq(null), eq(ZenModeConfig.ORIGIN_SYSTEM), anyString(),
eq("pkg"), eq(mUid));
}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenChangeOrigin.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenChangeOrigin.java
new file mode 100644
index 0000000..5728788
--- /dev/null
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenChangeOrigin.java
@@ -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.server.notification;
+
+import android.service.notification.ZenModeConfig;
+
+/** Enum version of {@link ZenModeConfig.ConfigOrigin}, for test parameterization. */
+public enum ZenChangeOrigin {
+ ORIGIN_UNKNOWN(ZenModeConfig.ORIGIN_UNKNOWN),
+ ORIGIN_INIT(ZenModeConfig.ORIGIN_INIT),
+ ORIGIN_INIT_USER(ZenModeConfig.ORIGIN_INIT_USER),
+ ORIGIN_APP(ZenModeConfig.ORIGIN_APP),
+ ORIGIN_USER_IN_APP(ZenModeConfig.ORIGIN_USER_IN_APP),
+ ORIGIN_SYSTEM(ZenModeConfig.ORIGIN_SYSTEM),
+ ORIGIN_USER_IN_SYSTEMUI(ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI),
+ ORIGIN_RESTORE_BACKUP(ZenModeConfig.ORIGIN_RESTORE_BACKUP);
+
+ private final int mValue;
+
+ ZenChangeOrigin(@ZenModeConfig.ConfigOrigin int value) {
+ mValue = value;
+ }
+
+ /** Gets the {@link ZenModeConfig.ConfigOrigin} int value corresponding to the enum. */
+ @ZenModeConfig.ConfigOrigin
+ public int value() {
+ return mValue;
+ }
+}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenEnumTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenEnumTest.java
index 8add2f9..cdceb1f 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenEnumTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenEnumTest.java
@@ -20,12 +20,14 @@
import android.app.AutomaticZenRule;
import android.provider.Settings;
+import android.service.notification.ZenModeConfig;
import android.service.notification.ZenPolicy;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.os.dnd.ActiveRuleType;
+import com.android.os.dnd.ChangeOrigin;
import com.android.os.dnd.ChannelPolicy;
import com.android.os.dnd.ConversationType;
import com.android.os.dnd.PeopleType;
@@ -78,6 +80,11 @@
testEnum(ZenPolicy.class, "PEOPLE_TYPE", PeopleType.class, "PEOPLE");
}
+ @Test
+ public void testEnum_changeOrigin() {
+ testEnum(ZenModeConfig.class, "ORIGIN", ChangeOrigin.class, "ORIGIN");
+ }
+
/**
* Verifies that any constants (i.e. {@code public static final int} fields) named {@code
* <apiPrefix>_SOMETHING} in {@code apiClass} are present and have the same numerical value
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
index 3c3c2f3..b955a79 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
@@ -535,7 +535,7 @@
rule.triggerDescription = TRIGGER_DESC;
rule.deletionInstant = Instant.ofEpochMilli(1701790147000L);
if (Flags.modesUi()) {
- rule.disabledOrigin = ZenModeConfig.UPDATE_ORIGIN_USER;
+ rule.disabledOrigin = ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
}
Parcel parcel = Parcel.obtain();
@@ -650,7 +650,7 @@
rule.triggerDescription = TRIGGER_DESC;
rule.deletionInstant = Instant.ofEpochMilli(1701790147000L);
if (Flags.modesUi()) {
- rule.disabledOrigin = ZenModeConfig.UPDATE_ORIGIN_APP;
+ rule.disabledOrigin = ZenModeConfig.ORIGIN_APP;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
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 d7bae45..63cf106 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -46,6 +46,7 @@
import static android.app.NotificationManager.Policy.STATE_PRIORITY_CHANNELS_BLOCKED;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
+import static android.os.Process.SYSTEM_UID;
import static android.provider.Settings.Global.ZEN_MODE_ALARMS;
import static android.provider.Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
import static android.provider.Settings.Global.ZEN_MODE_NO_INTERRUPTIONS;
@@ -54,12 +55,12 @@
import static android.service.notification.Condition.SOURCE_USER_ACTION;
import static android.service.notification.Condition.STATE_FALSE;
import static android.service.notification.Condition.STATE_TRUE;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_APP;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_INIT;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_INIT_USER;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_UNKNOWN;
-import static android.service.notification.ZenModeConfig.UPDATE_ORIGIN_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_APP;
+import static android.service.notification.ZenModeConfig.ORIGIN_INIT;
+import static android.service.notification.ZenModeConfig.ORIGIN_INIT_USER;
+import static android.service.notification.ZenModeConfig.ORIGIN_UNKNOWN;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_APP;
+import static android.service.notification.ZenModeConfig.ORIGIN_USER_IN_SYSTEMUI;
import static android.service.notification.ZenPolicy.PEOPLE_TYPE_CONTACTS;
import static android.service.notification.ZenPolicy.PEOPLE_TYPE_NONE;
import static android.service.notification.ZenPolicy.PEOPLE_TYPE_STARRED;
@@ -131,7 +132,6 @@
import android.media.VolumePolicy;
import android.net.Uri;
import android.os.Parcel;
-import android.os.Process;
import android.os.SimpleClock;
import android.os.UserHandle;
import android.platform.test.annotations.DisableFlags;
@@ -186,9 +186,6 @@
import org.mockito.MockitoAnnotations;
import org.xmlpull.v1.XmlPullParserException;
-import platform.test.runner.parameterized.ParameterizedAndroidJunit4;
-import platform.test.runner.parameterized.Parameters;
-
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
@@ -208,6 +205,9 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4;
+import platform.test.runner.parameterized.Parameters;
+
@SmallTest
@SuppressLint("GuardedBy") // It's ok for this test to access guarded methods from the service.
@RunWith(ParameterizedAndroidJunit4.class)
@@ -338,27 +338,6 @@
mZenModeEventLogger.reset();
}
- private enum ChangeOrigin {
- ORIGIN_UNKNOWN(ZenModeConfig.UPDATE_ORIGIN_UNKNOWN),
- ORIGIN_INIT(ZenModeConfig.UPDATE_ORIGIN_INIT),
- ORIGIN_INIT_USER(ZenModeConfig.UPDATE_ORIGIN_INIT_USER),
- ORIGIN_USER(ZenModeConfig.UPDATE_ORIGIN_USER),
- ORIGIN_APP(ZenModeConfig.UPDATE_ORIGIN_APP),
- ORIGIN_SYSTEM_OR_SYSTEMUI(ZenModeConfig.UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI),
- ORIGIN_RESTORE_BACKUP(ZenModeConfig.UPDATE_ORIGIN_RESTORE_BACKUP);
-
- private final int mValue;
-
- ChangeOrigin(@ZenModeConfig.ConfigChangeOrigin int value) {
- mValue = value;
- }
-
- @ZenModeConfig.ConfigChangeOrigin
- public int value() {
- return mValue;
- }
- }
-
private XmlResourceParser getDefaultConfigParser() throws IOException, XmlPullParserException {
String xml = "<zen version=\"10\">\n"
+ "<allow alarms=\"true\" media=\"true\" system=\"false\" calls=\"true\" "
@@ -395,8 +374,8 @@
mZenModeHelper.writeXml(serializer, false, version, UserHandle.USER_ALL);
serializer.endDocument();
serializer.flush();
- mZenModeHelper.setConfig(new ZenModeConfig(), null, UPDATE_ORIGIN_INIT, "writing xml",
- Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(new ZenModeConfig(), null, ORIGIN_INIT, "writing xml",
+ SYSTEM_UID);
return baos;
}
@@ -411,8 +390,8 @@
serializer.flush();
ZenModeConfig newConfig = new ZenModeConfig();
newConfig.user = userId;
- mZenModeHelper.setConfig(newConfig, null, UPDATE_ORIGIN_INIT, "writing xml",
- Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(newConfig, null, ORIGIN_INIT, "writing xml",
+ SYSTEM_UID);
return baos;
}
@@ -705,13 +684,13 @@
.setInterruptionFilter(INTERRUPTION_FILTER_NONE)
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azr, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reason", Process.SYSTEM_UID);
+ azr, ZenModeConfig.ORIGIN_SYSTEM, "reason", SYSTEM_UID);
// Enable rule
mZenModeHelper.setAutomaticZenRuleState(ruleId,
new Condition(azr.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM,
+ SYSTEM_UID);
// Confirm that the consolidated policy doesn't allow anything
NotificationManager.Policy policy = mZenModeHelper.getConsolidatedNotificationPolicy();
@@ -739,13 +718,13 @@
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azr, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reason", Process.SYSTEM_UID);
+ azr, ZenModeConfig.ORIGIN_SYSTEM, "reason", SYSTEM_UID);
// Enable rule
mZenModeHelper.setAutomaticZenRuleState(ruleId,
new Condition(azr.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM,
+ SYSTEM_UID);
// Confirm that the consolidated policy allows only alarms and media and nothing else
NotificationManager.Policy policy = mZenModeHelper.getConsolidatedNotificationPolicy();
@@ -819,7 +798,7 @@
when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
// Set zen to priority-only with all notification sounds muted (so ringer will be muted)
Policy totalSilence = new Policy(0, 0, 0);
- mZenModeHelper.setNotificationPolicy(totalSilence, UPDATE_ORIGIN_APP, 1);
+ mZenModeHelper.setNotificationPolicy(totalSilence, ORIGIN_APP, 1);
mZenModeHelper.mZenMode = ZEN_MODE_IMPORTANT_INTERRUPTIONS;
// 2. verify ringer is unchanged
@@ -857,7 +836,7 @@
// in priority only mode:
// ringtone, notification and system streams are affected by ringer mode
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, Uri.EMPTY,
- UPDATE_ORIGIN_APP, "test", "caller", 1);
+ ORIGIN_APP, "test", "caller", 1);
ZenModeHelper.RingerModeDelegate ringerModeDelegateRingerMuted =
mZenModeHelper.new RingerModeDelegate();
@@ -873,9 +852,9 @@
// even when ringer is muted (since all ringer sounds cannot bypass DND),
// system stream is still affected by ringer mode
- mZenModeHelper.setNotificationPolicy(new Policy(0, 0, 0), UPDATE_ORIGIN_APP, 1);
+ mZenModeHelper.setNotificationPolicy(new Policy(0, 0, 0), ORIGIN_APP, 1);
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, Uri.EMPTY,
- UPDATE_ORIGIN_APP, "test", "caller", 1);
+ ORIGIN_APP, "test", "caller", 1);
ZenModeHelper.RingerModeDelegate ringerModeDelegateRingerNotMuted =
mZenModeHelper.new RingerModeDelegate();
@@ -983,7 +962,7 @@
when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT);
for (int i = 0; i < 3; i++) {
mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, Uri.EMPTY,
- UPDATE_ORIGIN_APP, "test", "caller", 1);
+ ORIGIN_APP, "test", "caller", 1);
}
verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL,
mZenModeHelper.TAG);
@@ -1008,7 +987,7 @@
for (int i = 0; i < 3; i++) {
// if zen doesn't change, zen should not reapply itself to the ringer
mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, Uri.EMPTY,
- UPDATE_ORIGIN_APP, "test", "caller", 1);
+ ORIGIN_APP, "test", "caller", 1);
}
verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL,
mZenModeHelper.TAG);
@@ -1033,7 +1012,7 @@
for (int i = 0; i < 3; i++) {
// if zen doesn't change, zen should not reapply itself to the ringer
mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, Uri.EMPTY,
- UPDATE_ORIGIN_APP, "test", "caller", 1);
+ ORIGIN_APP, "test", "caller", 1);
}
verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL,
mZenModeHelper.TAG);
@@ -1048,7 +1027,8 @@
reset(mAudioManager);
// Turn manual zen mode on
- mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
+ ORIGIN_APP,
null, "test", CUSTOM_PKG_UID);
// audio manager shouldn't do anything until the handler processes its messages
@@ -1076,14 +1056,14 @@
mZenModeHelper.setManualZenMode(
ZEN_MODE_IMPORTANT_INTERRUPTIONS,
null,
- UPDATE_ORIGIN_APP,
+ ORIGIN_APP,
null,
"test",
CUSTOM_PKG_UID);
mZenModeHelper.setManualZenMode(
ZEN_MODE_IMPORTANT_INTERRUPTIONS,
null,
- UPDATE_ORIGIN_APP,
+ ORIGIN_APP,
null,
"test",
CUSTOM_PKG_UID);
@@ -1108,15 +1088,15 @@
| PRIORITY_CATEGORY_MESSAGES | PRIORITY_CATEGORY_REPEAT_CALLERS
| PRIORITY_CATEGORY_CONVERSATIONS, PRIORITY_SENDERS_STARRED,
PRIORITY_SENDERS_STARRED, 0, CONVERSATION_SENDERS_ANYONE),
- UPDATE_ORIGIN_UNKNOWN,
+ ORIGIN_UNKNOWN,
1);
mZenModeHelper.setManualZenRuleDeviceEffects(new ZenDeviceEffects.Builder()
.setShouldDimWallpaper(true)
.setShouldDisplayGrayscale(true)
.setShouldUseNightMode(true)
- .build(), UPDATE_ORIGIN_UNKNOWN, "test", 1);
+ .build(), ORIGIN_UNKNOWN, "test", 1);
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, Uri.EMPTY,
- UPDATE_ORIGIN_UNKNOWN, "test", "me", 1);
+ ORIGIN_UNKNOWN, "test", "me", 1);
ZenModeConfig actual = mZenModeHelper.mConfig.copy();
@@ -1130,13 +1110,13 @@
| PRIORITY_CATEGORY_CONVERSATIONS, PRIORITY_SENDERS_STARRED,
PRIORITY_SENDERS_STARRED, SUPPRESSED_EFFECT_BADGE,
CONVERSATION_SENDERS_ANYONE),
- UPDATE_ORIGIN_UNKNOWN, 1);
+ ORIGIN_UNKNOWN, 1);
mZenModeHelper.setManualZenRuleDeviceEffects(new ZenDeviceEffects.Builder()
.setShouldDimWallpaper(true)
.setShouldDisplayGrayscale(true)
- .build(), UPDATE_ORIGIN_UNKNOWN, "test", 1);
+ .build(), ORIGIN_UNKNOWN, "test", 1);
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, Uri.EMPTY,
- UPDATE_ORIGIN_UNKNOWN, "test", "me", 1);
+ ORIGIN_UNKNOWN, "test", "me", 1);
ZenModeConfig expected = mZenModeHelper.mConfig.copy();
if (Flags.modesUi()) {
@@ -1157,7 +1137,7 @@
@Test
public void testProto() throws InvalidProtocolBufferException {
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- Flags.modesApi() ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ Flags.modesApi() ? ORIGIN_USER_IN_SYSTEMUI : ZenModeConfig.ORIGIN_SYSTEM,
null, "test", CUSTOM_PKG_UID);
mZenModeHelper.mConfig.automaticRules = new ArrayMap<>(); // no automatic rules
@@ -1381,7 +1361,7 @@
List<StatsEvent> events = new LinkedList<>();
mZenModeHelper.pullRules(events);
- mZenModeHelper.removeAutomaticZenRule(CUSTOM_RULE_ID, UPDATE_ORIGIN_APP, "test",
+ mZenModeHelper.removeAutomaticZenRule(CUSTOM_RULE_ID, ORIGIN_APP, "test",
CUSTOM_PKG_UID);
assertTrue(-1
== mZenModeHelper.mRulesUidCache.getOrDefault(CUSTOM_PKG_NAME + "|" + 0, -1));
@@ -1410,7 +1390,8 @@
public void testProtoWithManualRule() throws Exception {
setupZenConfig();
mZenModeHelper.mConfig.automaticRules = getCustomAutomaticRules();
- mZenModeHelper.setManualZenMode(INTERRUPTION_FILTER_PRIORITY, Uri.EMPTY, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setManualZenMode(INTERRUPTION_FILTER_PRIORITY, Uri.EMPTY,
+ ORIGIN_APP,
"test", "me", 1);
List<StatsEvent> events = new LinkedList<>();
@@ -1437,14 +1418,14 @@
Policy policy = new Policy(PRIORITY_CATEGORY_MEDIA | PRIORITY_CATEGORY_ALARMS, 0, 0);
config10.applyNotificationPolicy(policy);
config10.user = 10;
- mZenModeHelper.setConfig(config10, null, UPDATE_ORIGIN_INIT, "writeXml",
- Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(config10, null, ORIGIN_INIT, "writeXml",
+ SYSTEM_UID);
ZenModeConfig config11 = mZenModeHelper.mConfig.copy();
config11.user = 11;
policy = new Policy(0, 0, 0);
config11.applyNotificationPolicy(policy);
- mZenModeHelper.setConfig(config11, null, UPDATE_ORIGIN_INIT, "writeXml",
- Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(config11, null, ORIGIN_INIT, "writeXml",
+ SYSTEM_UID);
// Backup user 10 and reset values.
ByteArrayOutputStream baos = writeXmlAndPurgeForUser(null, 10);
@@ -2307,7 +2288,7 @@
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
// We need the package name to be something that's not "android" so there aren't any
// existing rules under that package.
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
assertNotNull(id);
}
@@ -2318,7 +2299,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
fail("allowed too many rules to be created");
} catch (IllegalArgumentException e) {
@@ -2339,7 +2320,7 @@
ZenModeConfig.toScheduleConditionId(si),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
assertNotNull(id);
}
@@ -2350,7 +2331,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
fail("allowed too many rules to be created");
} catch (IllegalArgumentException e) {
@@ -2371,7 +2352,7 @@
ZenModeConfig.toScheduleConditionId(si),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
assertNotNull(id);
}
@@ -2382,7 +2363,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, UPDATE_ORIGIN_APP,
+ String id = mZenModeHelper.addAutomaticZenRule("pkgname", zenRule, ORIGIN_APP,
"test", CUSTOM_PKG_UID);
fail("allowed too many rules to be created");
} catch (IllegalArgumentException e) {
@@ -2399,7 +2380,7 @@
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule("android", zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
assertTrue(id != null);
ZenModeConfig.ZenRule ruleInConfig = mZenModeHelper.mConfig.automaticRules.get(id);
@@ -2420,7 +2401,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule("android", zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
assertTrue(id != null);
ZenModeConfig.ZenRule ruleInConfig = mZenModeHelper.mConfig.automaticRules.get(id);
@@ -2446,7 +2427,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id1 = mZenModeHelper.addAutomaticZenRule("android", zenRule1,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// Zen rule with partially-filled policy: should get all of the filled fields set, and the
// rest filled with default state
@@ -2461,7 +2442,7 @@
.build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule("android", zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// rule 1 should exist
assertThat(id1).isNotNull();
@@ -2506,11 +2487,11 @@
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, UPDATE_ORIGIN_APP, "test",
+ String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, ORIGIN_APP, "test",
CUSTOM_PKG_UID);
mZenModeHelper.setAutomaticZenRuleState(zenRule.getConditionId(),
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_APP,
+ ORIGIN_APP,
CUSTOM_PKG_UID);
ZenModeConfig.ZenRule ruleInConfig = mZenModeHelper.mConfig.automaticRules.get(id);
@@ -2526,7 +2507,7 @@
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, UPDATE_ORIGIN_APP, "test",
+ String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, ORIGIN_APP, "test",
CUSTOM_PKG_UID);
AutomaticZenRule zenRule2 = new AutomaticZenRule("NEW",
@@ -2536,7 +2517,7 @@
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- mZenModeHelper.updateAutomaticZenRule(id, zenRule2, UPDATE_ORIGIN_APP, "", CUSTOM_PKG_UID);
+ mZenModeHelper.updateAutomaticZenRule(id, zenRule2, ORIGIN_APP, "", CUSTOM_PKG_UID);
ZenModeConfig.ZenRule ruleInConfig = mZenModeHelper.mConfig.automaticRules.get(id);
assertEquals("NEW", ruleInConfig.name);
@@ -2551,7 +2532,7 @@
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, UPDATE_ORIGIN_APP, "test",
+ String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, ORIGIN_APP, "test",
CUSTOM_PKG_UID);
assertTrue(id != null);
@@ -2559,7 +2540,7 @@
assertTrue(ruleInConfig != null);
assertEquals(zenRule.getName(), ruleInConfig.name);
- mZenModeHelper.removeAutomaticZenRule(id, UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id, ORIGIN_APP, "test", CUSTOM_PKG_UID);
assertNull(mZenModeHelper.mConfig.automaticRules.get(id));
}
@@ -2571,7 +2552,7 @@
ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
new ZenPolicy.Builder().build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
- String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, UPDATE_ORIGIN_APP, "test",
+ String id = mZenModeHelper.addAutomaticZenRule(null, zenRule, ORIGIN_APP, "test",
CUSTOM_PKG_UID);
assertTrue(id != null);
@@ -2579,7 +2560,7 @@
assertTrue(ruleInConfig != null);
assertEquals(zenRule.getName(), ruleInConfig.name);
- mZenModeHelper.removeAutomaticZenRules(mContext.getPackageName(), UPDATE_ORIGIN_APP, "test",
+ mZenModeHelper.removeAutomaticZenRules(mContext.getPackageName(), ORIGIN_APP, "test",
CUSTOM_PKG_UID);
assertNull(mZenModeHelper.mConfig.automaticRules.get(id));
}
@@ -2596,17 +2577,17 @@
sharedUri,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mPkg, zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
AutomaticZenRule zenRule2 = new AutomaticZenRule("name2",
new ComponentName(mPkg, "ScheduleConditionProvider"),
sharedUri,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mPkg, zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
Condition condition = new Condition(sharedUri, "", STATE_TRUE);
mZenModeHelper.setAutomaticZenRuleState(sharedUri, condition,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
for (ZenModeConfig.ZenRule rule : mZenModeHelper.mConfig.automaticRules.values()) {
if (rule.id.equals(id)) {
@@ -2621,7 +2602,7 @@
condition = new Condition(sharedUri, "", STATE_FALSE);
mZenModeHelper.setAutomaticZenRuleState(sharedUri, condition,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
for (ZenModeConfig.ZenRule rule : mZenModeHelper.mConfig.automaticRules.values()) {
if (rule.id.equals(id)) {
@@ -2656,7 +2637,7 @@
.setOwner(OWNER)
.setDeviceEffects(zde)
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getDeviceEffects()).isEqualTo(
@@ -2689,7 +2670,7 @@
.setOwner(OWNER)
.setDeviceEffects(zde)
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getDeviceEffects()).isEqualTo(zde);
@@ -2716,7 +2697,7 @@
.setOwner(OWNER)
.setDeviceEffects(zde)
.build(),
- UPDATE_ORIGIN_USER,
+ ORIGIN_USER_IN_SYSTEMUI,
"reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
@@ -2736,7 +2717,7 @@
.setOwner(OWNER)
.setDeviceEffects(original)
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
ZenDeviceEffects updateFromApp = new ZenDeviceEffects.Builder()
.setShouldUseNightMode(true) // Good
@@ -2748,7 +2729,7 @@
.setOwner(OWNER)
.setDeviceEffects(updateFromApp)
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getDeviceEffects()).isEqualTo(
@@ -2770,7 +2751,7 @@
.setOwner(OWNER)
.setDeviceEffects(original)
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
ZenDeviceEffects updateFromSystem = new ZenDeviceEffects.Builder()
.setShouldUseNightMode(true) // Good
@@ -2780,7 +2761,7 @@
new AutomaticZenRule.Builder("Rule", CONDITION_ID)
.setDeviceEffects(updateFromSystem)
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getDeviceEffects()).isEqualTo(updateFromSystem);
@@ -2797,7 +2778,7 @@
.setOwner(OWNER)
.setDeviceEffects(original)
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
ZenDeviceEffects updateFromUser = new ZenDeviceEffects.Builder()
.setShouldUseNightMode(true)
@@ -2810,7 +2791,7 @@
new AutomaticZenRule.Builder("Rule", CONDITION_ID)
.setDeviceEffects(updateFromUser)
.build(),
- UPDATE_ORIGIN_USER, "reasons", 0);
+ ORIGIN_USER_IN_SYSTEMUI, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
@@ -2829,13 +2810,13 @@
.allowCalls(ZenPolicy.PEOPLE_TYPE_NONE) // default is stars
.build())
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
mZenModeHelper.updateAutomaticZenRule(ruleId,
new AutomaticZenRule.Builder("Rule", CONDITION_ID)
// no zen policy
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getZenPolicy().getPriorityCategoryCalls())
@@ -2857,7 +2838,7 @@
.allowReminders(true)
.build())
.build(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", 0);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", 0);
mZenModeHelper.updateAutomaticZenRule(ruleId,
new AutomaticZenRule.Builder("Rule", CONDITION_ID)
@@ -2865,7 +2846,7 @@
.allowCalls(ZenPolicy.PEOPLE_TYPE_CONTACTS)
.build())
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
AutomaticZenRule savedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(savedRule.getZenPolicy().getPriorityCategoryCalls())
@@ -2893,7 +2874,8 @@
AutomaticZenRule bedtime = new AutomaticZenRule.Builder("Bedtime Mode (TM)", CONDITION_ID)
.setType(TYPE_BEDTIME)
.build();
- String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime, UPDATE_ORIGIN_APP,
+ String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime,
+ ORIGIN_APP,
"reason", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.keySet()).containsExactly(bedtimeRuleId);
@@ -2913,7 +2895,8 @@
AutomaticZenRule bedtime = new AutomaticZenRule.Builder("Bedtime Mode (TM)", CONDITION_ID)
.setType(TYPE_BEDTIME)
.build();
- String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime, UPDATE_ORIGIN_APP,
+ String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime,
+ ORIGIN_APP,
"reason", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.keySet()).containsExactly(
@@ -2934,7 +2917,8 @@
AutomaticZenRule bedtime = new AutomaticZenRule.Builder("Bedtime Mode (TM)", CONDITION_ID)
.setType(TYPE_BEDTIME)
.build();
- String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime, UPDATE_ORIGIN_APP,
+ String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule("pkg", bedtime,
+ ORIGIN_APP,
"reason", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.keySet()).containsExactly(
@@ -2948,15 +2932,15 @@
// note that caller=null because that's how it comes in from NMS.setZenMode
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", null, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "", null, SYSTEM_UID);
// confirm that setting zen mode via setManualZenMode changed the zen mode correctly
assertEquals(ZEN_MODE_IMPORTANT_INTERRUPTIONS, mZenModeHelper.mZenMode);
assertEquals(true, mZenModeHelper.mConfig.manualRule.allowManualInvocation);
// and also that it works to turn it back off again
- mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "", null, Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM,
+ "", null, SYSTEM_UID);
assertEquals(Global.ZEN_MODE_OFF, mZenModeHelper.mZenMode);
}
@@ -2965,28 +2949,29 @@
@EnableFlags(FLAG_MODES_API)
@DisableFlags(FLAG_MODES_UI)
public void setManualZenMode_off_snoozesActiveRules() {
- for (ChangeOrigin origin : ChangeOrigin.values()) {
+ for (ZenChangeOrigin origin : ZenChangeOrigin.values()) {
// Start with an active rule and an inactive rule.
mZenModeHelper.mConfig.automaticRules.clear();
AutomaticZenRule activeRule = new AutomaticZenRule.Builder("Test", CONDITION_ID)
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String activeRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- activeRule, UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(activeRuleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ activeRule, ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ mZenModeHelper.setAutomaticZenRuleState(activeRuleId, CONDITION_TRUE,
+ ORIGIN_APP,
CUSTOM_PKG_UID);
AutomaticZenRule inactiveRule = new AutomaticZenRule.Builder("Test", CONDITION_ID)
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String inactiveRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- inactiveRule, UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ inactiveRule, ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertWithMessage("Failure for origin " + origin.name())
.that(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
// User turns DND off.
mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, origin.value(),
- "snoozing", "systemui", Process.SYSTEM_UID);
+ "snoozing", "systemui", SYSTEM_UID);
assertWithMessage("Failure for origin " + origin.name())
.that(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
assertWithMessage("Failure for origin " + origin.name())
@@ -3000,30 +2985,31 @@
@Test
@EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
- public void setManualZenMode_off_doesNotSnoozeRulesIfFromUser() {
- for (ChangeOrigin origin : ChangeOrigin.values()) {
+ public void setManualZenMode_off_doesNotSnoozeRulesIfFromUserInSystemUi() {
+ for (ZenChangeOrigin origin : ZenChangeOrigin.values()) {
// Start with an active rule and an inactive rule
mZenModeHelper.mConfig.automaticRules.clear();
AutomaticZenRule activeRule = new AutomaticZenRule.Builder("Test", CONDITION_ID)
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String activeRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- activeRule, UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(activeRuleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ activeRule, ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ mZenModeHelper.setAutomaticZenRuleState(activeRuleId, CONDITION_TRUE,
+ ORIGIN_APP,
CUSTOM_PKG_UID);
AutomaticZenRule inactiveRule = new AutomaticZenRule.Builder("Test", CONDITION_ID)
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String inactiveRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- inactiveRule, UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ inactiveRule, ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
// User turns DND off.
mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, origin.value(),
- "snoozing", "systemui", Process.SYSTEM_UID);
+ "snoozing", "systemui", SYSTEM_UID);
ZenModeConfig config = mZenModeHelper.mConfig;
- if (origin == ChangeOrigin.ORIGIN_USER) {
+ if (origin == ZenChangeOrigin.ORIGIN_USER_IN_SYSTEMUI) {
// Other rule was unaffected.
assertWithMessage("Failure for origin " + origin.name()).that(
mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
@@ -3048,14 +3034,14 @@
// note that caller=null because that's how it comes in from NMS.setZenMode
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", null, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "", null, SYSTEM_UID);
// confirm that setting zen mode via setManualZenMode changed the zen mode correctly
assertEquals(ZEN_MODE_IMPORTANT_INTERRUPTIONS, mZenModeHelper.mZenMode);
// and also that it works to turn it back off again
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "",
- null, Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM, "",
+ null, SYSTEM_UID);
assertEquals(ZEN_MODE_OFF, mZenModeHelper.mZenMode);
}
@@ -3069,12 +3055,12 @@
// Turn zen mode on (to important_interruptions)
// Need to additionally call the looper in order to finish the post-apply-config process
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- Flags.modesApi() ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", null,
- Process.SYSTEM_UID);
+ Flags.modesApi() ? ORIGIN_USER_IN_SYSTEMUI : ZenModeConfig.ORIGIN_SYSTEM, "",
+ null, SYSTEM_UID);
// Now turn zen mode off, but via a different package UID -- this should get registered as
// "not an action by the user" because some other app is changing zen mode
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_APP, "", null,
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ORIGIN_APP, "", null,
CUSTOM_PKG_UID);
// In total, this should be 2 loggable changes
@@ -3100,11 +3086,11 @@
assertThat(mZenModeEventLogger.getFromSystemOrSystemUi(0)).isEqualTo(
!(Flags.modesUi() || Flags.modesApi()));
assertTrue(mZenModeEventLogger.getIsUserAction(0));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(0));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(0));
checkDndProtoMatchesSetupZenConfig(mZenModeEventLogger.getPolicyProto(0));
// change origin should be populated only under modes_ui
assertThat(mZenModeEventLogger.getChangeOrigin(0)).isEqualTo(
- (Flags.modesApi() && Flags.modesUi()) ? UPDATE_ORIGIN_USER : 0);
+ (Flags.modesApi() && Flags.modesUi()) ? ORIGIN_USER_IN_SYSTEMUI : 0);
// and from turning zen mode off:
// - event ID: DND_TURNED_OFF
@@ -3128,7 +3114,7 @@
checkDndProtoMatchesSetupZenConfig(mZenModeEventLogger.getPolicyProto(1));
}
assertThat(mZenModeEventLogger.getChangeOrigin(1)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_APP : 0);
+ Flags.modesUi() ? ORIGIN_APP : 0);
}
@Test
@@ -3145,7 +3131,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ ORIGIN_APP, "test", CUSTOM_PKG_UID);
// Event 1: Mimic the rule coming on automatically by setting the Condition to STATE_TRUE
// Note that pre-modes_ui, this event serves as a test that automatic changes to an app's
@@ -3153,14 +3139,14 @@
// modes_ui is true, we opt to trust the provided change origin.
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- Flags.modesUi() ? UPDATE_ORIGIN_APP : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
+ Flags.modesUi() ? ORIGIN_APP : ZenModeConfig.ORIGIN_SYSTEM,
CUSTOM_PKG_UID);
// Event 2: "User" turns off the automatic rule (sets it to not enabled)
zenRule.setEnabled(false);
mZenModeHelper.updateAutomaticZenRule(id, zenRule,
- Flags.modesApi() ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "",
- Process.SYSTEM_UID);
+ Flags.modesApi() ? ORIGIN_USER_IN_SYSTEMUI : ZenModeConfig.ORIGIN_SYSTEM, "",
+ SYSTEM_UID);
AutomaticZenRule systemRule = new AutomaticZenRule("systemRule",
null,
@@ -3169,18 +3155,18 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String systemId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), systemRule,
- Flags.modesApi() ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test",
- Process.SYSTEM_UID);
+ Flags.modesApi() ? ORIGIN_USER_IN_SYSTEMUI : ZenModeConfig.ORIGIN_SYSTEM, "test",
+ SYSTEM_UID);
// Event 3: turn on the system rule
mZenModeHelper.setAutomaticZenRuleState(systemId,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Event 4: "User" deletes the rule
mZenModeHelper.removeAutomaticZenRule(systemId,
- Flags.modesApi() ? UPDATE_ORIGIN_USER : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "",
- Process.SYSTEM_UID);
+ Flags.modesApi() ? ORIGIN_USER_IN_SYSTEMUI : ZenModeConfig.ORIGIN_SYSTEM, "",
+ SYSTEM_UID);
// In total, this represents 4 events
assertEquals(4, mZenModeEventLogger.numLoggedChanges());
@@ -3203,7 +3189,7 @@
assertEquals(CUSTOM_PKG_UID, mZenModeEventLogger.getPackageUid(0));
checkDndProtoMatchesDefaultZenConfig(mZenModeEventLogger.getPolicyProto(0));
assertThat(mZenModeEventLogger.getChangeOrigin(0)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_APP : 0);
+ Flags.modesUi() ? ORIGIN_APP : 0);
// When the automatic rule is disabled, this should turn off zen mode and also count as a
// user action. We don't care what the consolidated policy is when DND turns off.
@@ -3217,14 +3203,14 @@
assertEquals(0, mZenModeEventLogger.getNumRulesActive(1));
assertTrue(mZenModeEventLogger.getIsUserAction(1));
assertThat(mZenModeEventLogger.getPackageUid(1)).isEqualTo(
- Flags.modesUi() ? CUSTOM_PKG_UID : Process.SYSTEM_UID);
+ Flags.modesUi() ? CUSTOM_PKG_UID : SYSTEM_UID);
if (Flags.modesApi()) {
assertThat(mZenModeEventLogger.getPolicyProto(1)).isNull();
} else {
checkDndProtoMatchesSetupZenConfig(mZenModeEventLogger.getPolicyProto(1));
}
assertThat(mZenModeEventLogger.getChangeOrigin(1)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_USER : 0);
+ Flags.modesUi() ? ORIGIN_USER_IN_SYSTEMUI : 0);
// When the system rule is enabled, this counts as an automatic action that comes from the
// system and turns on DND
@@ -3233,9 +3219,9 @@
assertEquals(DNDProtoEnums.AUTOMATIC_RULE, mZenModeEventLogger.getChangedRuleType(2));
assertEquals(1, mZenModeEventLogger.getNumRulesActive(2));
assertFalse(mZenModeEventLogger.getIsUserAction(2));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(2));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(2));
assertThat(mZenModeEventLogger.getChangeOrigin(2)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI : 0);
+ Flags.modesUi() ? ZenModeConfig.ORIGIN_SYSTEM : 0);
// When the system rule is deleted, we consider this a user action that turns DND off
// (again)
@@ -3244,9 +3230,9 @@
assertEquals(DNDProtoEnums.AUTOMATIC_RULE, mZenModeEventLogger.getChangedRuleType(3));
assertEquals(0, mZenModeEventLogger.getNumRulesActive(3));
assertTrue(mZenModeEventLogger.getIsUserAction(3));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(3));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(3));
assertThat(mZenModeEventLogger.getChangeOrigin(3)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_USER : 0);
+ Flags.modesUi() ? ORIGIN_USER_IN_SYSTEMUI : 0);
}
@Test
@@ -3264,28 +3250,28 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ ORIGIN_APP, "test", CUSTOM_PKG_UID);
// Event 1: Mimic the rule coming on manually when the user turns it on in the app
// ("Turn on bedtime now" because user goes to bed earlier).
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE, SOURCE_USER_ACTION),
- UPDATE_ORIGIN_USER, CUSTOM_PKG_UID);
+ ORIGIN_USER_IN_APP, CUSTOM_PKG_UID);
// Event 2: App deactivates the rule automatically (it's 8 AM, bedtime schedule ends)
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_FALSE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Event 3: App activates the rule automatically (it's now 11 PM, bedtime schedule starts)
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Event 4: User deactivates the rule manually (they get up before 8 AM on the next day)
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_FALSE, SOURCE_USER_ACTION),
- UPDATE_ORIGIN_USER, CUSTOM_PKG_UID);
+ ORIGIN_USER_IN_APP, CUSTOM_PKG_UID);
// In total, this represents 4 events
assertEquals(4, mZenModeEventLogger.numLoggedChanges());
@@ -3301,7 +3287,7 @@
assertTrue(mZenModeEventLogger.getIsUserAction(0));
assertEquals(CUSTOM_PKG_UID, mZenModeEventLogger.getPackageUid(0));
assertThat(mZenModeEventLogger.getChangeOrigin(0)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_USER : 0);
+ Flags.modesUi() ? ORIGIN_USER_IN_APP : 0);
// Automatic rule turned off automatically by app:
// - event ID: DND_TURNED_OFF
@@ -3314,7 +3300,7 @@
assertFalse(mZenModeEventLogger.getIsUserAction(1));
assertEquals(CUSTOM_PKG_UID, mZenModeEventLogger.getPackageUid(1));
assertThat(mZenModeEventLogger.getChangeOrigin(1)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_APP : 0);
+ Flags.modesUi() ? ORIGIN_APP : 0);
// Automatic rule turned on automatically by app:
// - event ID: DND_TURNED_ON
@@ -3328,7 +3314,7 @@
assertFalse(mZenModeEventLogger.getIsUserAction(2));
assertEquals(CUSTOM_PKG_UID, mZenModeEventLogger.getPackageUid(2));
assertThat(mZenModeEventLogger.getChangeOrigin(2)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_APP : 0);
+ Flags.modesUi() ? ORIGIN_APP : 0);
// Automatic rule turned off automatically by the user:
// - event ID: DND_TURNED_ON
@@ -3341,7 +3327,7 @@
assertTrue(mZenModeEventLogger.getIsUserAction(3));
assertEquals(CUSTOM_PKG_UID, mZenModeEventLogger.getPackageUid(3));
assertThat(mZenModeEventLogger.getChangeOrigin(3)).isEqualTo(
- Flags.modesUi() ? UPDATE_ORIGIN_USER : 0);
+ Flags.modesUi() ? ORIGIN_USER_IN_APP : 0);
}
@Test
@@ -3352,21 +3338,21 @@
// First just turn zen mode on
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_USER, "", null, Process.SYSTEM_UID);
+ ORIGIN_USER_IN_SYSTEMUI, "", null, SYSTEM_UID);
// Now change the policy slightly; want to confirm that this'll be reflected in the logs
ZenModeConfig newConfig = mZenModeHelper.mConfig.copy();
mZenModeHelper.setNotificationPolicy(new Policy(PRIORITY_CATEGORY_ALARMS, 0, 0),
- UPDATE_ORIGIN_USER, Process.SYSTEM_UID);
+ ORIGIN_USER_IN_SYSTEMUI, SYSTEM_UID);
// Turn zen mode off; we want to make sure policy changes do not get logged when zen mode
// is off.
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "",
- null, Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM, "",
+ null, SYSTEM_UID);
// Change the policy again
mZenModeHelper.setNotificationPolicy(new Policy(PRIORITY_CATEGORY_REPEAT_CALLERS, 0, 0),
- UPDATE_ORIGIN_USER, Process.SYSTEM_UID);
+ ORIGIN_USER_IN_SYSTEMUI, SYSTEM_UID);
// Total events: we only expect ones for turning on, changing policy, and turning off
assertEquals(3, mZenModeEventLogger.numLoggedChanges());
@@ -3386,7 +3372,7 @@
mZenModeEventLogger.getEventId(1));
assertEquals(DNDProtoEnums.UNKNOWN_RULE, mZenModeEventLogger.getChangedRuleType(1));
assertTrue(mZenModeEventLogger.getIsUserAction(1));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
DNDPolicyProto dndProto = mZenModeEventLogger.getPolicyProto(1);
assertEquals(STATE_ALLOW, dndProto.getAlarms().getNumber());
assertEquals(STATE_DISALLOW, dndProto.getRepeatCallers().getNumber());
@@ -3410,7 +3396,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// Rule 2, same as rule 1
AutomaticZenRule zenRule2 = new AutomaticZenRule("name2",
@@ -3420,7 +3406,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// Rule 3, has stricter settings than the default settings
ZenModeConfig ruleConfig = mZenModeHelper.mConfig.copy();
@@ -3432,27 +3418,27 @@
ruleConfig.getZenPolicy(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id3 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule3,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// First: turn on rule 1
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Second: turn on rule 2
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Third: turn on rule 3
mZenModeHelper.setAutomaticZenRuleState(id3,
new Condition(zenRule3.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Fourth: Turn *off* rule 2
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_FALSE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// This should result in a total of four events
assertEquals(4, mZenModeEventLogger.numLoggedChanges());
@@ -3465,7 +3451,7 @@
assertEquals(ZEN_MODE_IMPORTANT_INTERRUPTIONS, mZenModeEventLogger.getNewZenMode(0));
assertEquals(1, mZenModeEventLogger.getNumRulesActive(0));
assertFalse(mZenModeEventLogger.getIsUserAction(0));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(0));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(0));
checkDndProtoMatchesDefaultZenConfig(mZenModeEventLogger.getPolicyProto(0));
// Event 2: rule 2 turns on. This should not change anything about the policy, so the only
@@ -3474,7 +3460,7 @@
mZenModeEventLogger.getEventId(1));
assertEquals(2, mZenModeEventLogger.getNumRulesActive(1));
assertFalse(mZenModeEventLogger.getIsUserAction(1));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
checkDndProtoMatchesDefaultZenConfig(mZenModeEventLogger.getPolicyProto(1));
// Event 3: rule 3 turns on. This should trigger a policy change, and be classified as such,
@@ -3484,7 +3470,7 @@
mZenModeEventLogger.getEventId(2));
assertEquals(3, mZenModeEventLogger.getNumRulesActive(2));
assertFalse(mZenModeEventLogger.getIsUserAction(2));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(2));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(2));
DNDPolicyProto dndProto = mZenModeEventLogger.getPolicyProto(2);
assertEquals(STATE_DISALLOW, dndProto.getReminders().getNumber());
assertEquals(STATE_DISALLOW, dndProto.getCalls().getNumber());
@@ -3508,7 +3494,7 @@
// Artificially turn zen mode "on". Re-evaluating zen mode should cause it to turn back off
// given that we don't have any zen rules active.
mZenModeHelper.mZenMode = ZEN_MODE_IMPORTANT_INTERRUPTIONS;
- mZenModeHelper.evaluateZenModeLocked(UPDATE_ORIGIN_UNKNOWN, "test", true);
+ mZenModeHelper.evaluateZenModeLocked(ORIGIN_UNKNOWN, "test", true);
// Check that the change actually took: zen mode should be off now
assertEquals(ZEN_MODE_OFF, mZenModeHelper.mZenMode);
@@ -3537,7 +3523,7 @@
manualRulePolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_APP, "test", Process.SYSTEM_UID);
+ ORIGIN_APP, "test", SYSTEM_UID);
// Rule 2, same as rule 1 but owned by the system
AutomaticZenRule zenRule2 = new AutomaticZenRule("name2",
@@ -3547,7 +3533,7 @@
manualRulePolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule2,
- UPDATE_ORIGIN_USER, "test", Process.SYSTEM_UID);
+ ORIGIN_USER_IN_SYSTEMUI, "test", SYSTEM_UID);
// Turn on rule 1; call looks like it's from the system. Because setting a condition is
// typically an automatic (non-user-initiated) action, expect the calling UID to be
@@ -3555,23 +3541,24 @@
// When modes_ui is true: we expect the change origin to be the source of truth.
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- Flags.modesUi() ? UPDATE_ORIGIN_APP : UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- Process.SYSTEM_UID);
+ Flags.modesUi() ? ORIGIN_APP : ZenModeConfig.ORIGIN_SYSTEM,
+ SYSTEM_UID);
// Second: turn on rule 2. This is a system-owned rule and the UID should not be modified
// (nor even looked up; the mock PackageManager won't handle "android" as input).
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Disable rule 1. Because this looks like a user action, the UID should not be modified
// from the system-provided one unless modes_ui is true.
zenRule.setEnabled(false);
mZenModeHelper.updateAutomaticZenRule(id, zenRule,
- UPDATE_ORIGIN_USER, "", Process.SYSTEM_UID);
+ ORIGIN_USER_IN_SYSTEMUI, "", SYSTEM_UID);
// Add a manual rule. Any manual rule changes should not get calling uids reassigned.
- mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
+ ORIGIN_APP,
"", null, CUSTOM_PKG_UID);
// Change rule 2's condition, but from some other UID. Since it doesn't look like it's from
@@ -3579,7 +3566,7 @@
// Note that this probably shouldn't be able to occur in real scenarios.
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_FALSE),
- UPDATE_ORIGIN_APP, 12345);
+ ORIGIN_APP, 12345);
// That was 5 events total
assertEquals(5, mZenModeEventLogger.numLoggedChanges());
@@ -3598,7 +3585,7 @@
mZenModeEventLogger.getEventId(1));
assertEquals(DNDProtoEnums.AUTOMATIC_RULE, mZenModeEventLogger.getChangedRuleType(1));
assertFalse(mZenModeEventLogger.getIsUserAction(1));
- assertEquals(Process.SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
+ assertEquals(SYSTEM_UID, mZenModeEventLogger.getPackageUid(1));
// Third event: disable rule 1. This looks like a user action so UID should be left alone.
// When modes_ui is true, we assign log this user action with the app that owns the rule.
@@ -3607,7 +3594,7 @@
assertEquals(DNDProtoEnums.AUTOMATIC_RULE, mZenModeEventLogger.getChangedRuleType(2));
assertTrue(mZenModeEventLogger.getIsUserAction(2));
assertThat(mZenModeEventLogger.getPackageUid(2)).isEqualTo(
- Flags.modesUi() ? CUSTOM_PKG_UID : Process.SYSTEM_UID);
+ Flags.modesUi() ? CUSTOM_PKG_UID : SYSTEM_UID);
// Fourth event: turns on manual mode. Doesn't change effective policy so this is just a
// change in active rules. Confirm that the package UID is left unchanged.
@@ -3636,29 +3623,30 @@
// Turn on zen mode with a manual rule with an enabler set. This should *not* count
// as a user action, and *should* get its UID reassigned.
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", CUSTOM_PKG_NAME, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "", CUSTOM_PKG_NAME, SYSTEM_UID);
assertEquals(1, mZenModeEventLogger.numLoggedChanges());
// Now change apps bypassing to true
ZenModeConfig newConfig = mZenModeHelper.mConfig.copy();
newConfig.areChannelsBypassingDnd = true;
mZenModeHelper.setNotificationPolicy(newConfig.toNotificationPolicy(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
assertEquals(2, mZenModeEventLogger.numLoggedChanges());
// and then back to false, all without changing anything else
newConfig.areChannelsBypassingDnd = false;
mZenModeHelper.setNotificationPolicy(newConfig.toNotificationPolicy(),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
assertEquals(3, mZenModeEventLogger.numLoggedChanges());
// Turn off manual mode, call from a package: don't reset UID even though enabler is set
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_APP, "",
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ORIGIN_APP, "",
CUSTOM_PKG_NAME, 12345);
assertEquals(4, mZenModeEventLogger.numLoggedChanges());
// And likewise when turning it back on again
- mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
+ ORIGIN_APP,
"", CUSTOM_PKG_NAME, 12345);
// These are 5 events in total.
@@ -3705,7 +3693,7 @@
// First just turn zen mode on
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", null, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "", null, SYSTEM_UID);
// Now change only the channels part of the policy; want to confirm that this'll be
// reflected in the logs
@@ -3716,7 +3704,7 @@
STATE_PRIORITY_CHANNELS_BLOCKED,
oldPolicy.priorityConversationSenders);
mZenModeHelper.setNotificationPolicy(newPolicy,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Total events: one for turning on, one for changing policy
assertThat(mZenModeEventLogger.numLoggedChanges()).isEqualTo(2);
@@ -3757,17 +3745,17 @@
null,
NotificationManager.INTERRUPTION_FILTER_ALL, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ ORIGIN_APP, "test", CUSTOM_PKG_UID);
// Event 1: App activates the rule automatically.
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Event 2: App deactivates the rule automatically.
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_FALSE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// In total, this represents 2 events.
assertEquals(2, mZenModeEventLogger.numLoggedChanges());
@@ -3798,7 +3786,8 @@
.setInterruptionFilter(INTERRUPTION_FILTER_ALL)
.setType(TYPE_BEDTIME)
.build();
- String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule(mPkg, bedtime, UPDATE_ORIGIN_APP,
+ String bedtimeRuleId = mZenModeHelper.addAutomaticZenRule(mPkg, bedtime,
+ ORIGIN_APP,
"reason", CUSTOM_PKG_UID);
// Create immersive rule
@@ -3806,27 +3795,28 @@
.setType(TYPE_IMMERSIVE)
.setZenPolicy(mZenModeHelper.mConfig.getZenPolicy()) // same as the manual rule
.build();
- String immersiveId = mZenModeHelper.addAutomaticZenRule(mPkg, immersive, UPDATE_ORIGIN_APP,
+ String immersiveId = mZenModeHelper.addAutomaticZenRule(mPkg, immersive,
+ ORIGIN_APP,
"reason", CUSTOM_PKG_UID);
// Event 1: Activate bedtime rule. This doesn't turn on notification filtering
mZenModeHelper.setAutomaticZenRuleState(bedtimeRuleId,
new Condition(bedtime.getConditionId(), "", STATE_TRUE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Event 2: turn on manual zen mode. Manual rule will have ACTIVE_RULE_TYPE_MANUAL
mZenModeHelper.setManualZenMode(ZEN_MODE_IMPORTANT_INTERRUPTIONS, null,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "", null, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "", null, SYSTEM_UID);
// Event 3: Turn immersive on
mZenModeHelper.setAutomaticZenRuleState(immersiveId,
new Condition(immersive.getConditionId(), "", STATE_TRUE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Event 4: Turn off bedtime mode, leaving just manual + immersive
mZenModeHelper.setAutomaticZenRuleState(bedtimeRuleId,
new Condition(bedtime.getConditionId(), "", STATE_FALSE, SOURCE_SCHEDULE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Total of 4 events
assertEquals(4, mZenModeEventLogger.numLoggedChanges());
@@ -3887,12 +3877,12 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable the rule
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
assertEquals(mZenModeHelper.getNotificationPolicy(),
mZenModeHelper.getConsolidatedNotificationPolicy());
@@ -3923,12 +3913,12 @@
null, // null policy
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable the rule
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// inspect the consolidated policy, which should match the device default settings.
assertThat(ZenAdapters.notificationPolicyToZenPolicy(mZenModeHelper.mConsolidatedPolicy))
@@ -3961,12 +3951,12 @@
customPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable the rule; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// since this is the only active rule, the consolidated policy should match the custom
// policy for every field specified, and take default values (from device default or
@@ -4006,12 +3996,12 @@
customPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable the rule; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// since this is the only active rule, the consolidated policy should match the custom
// policy for every field specified, and take default values (from either device default
@@ -4046,12 +4036,12 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable rule 1
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// custom policy for rule 2
ZenPolicy customPolicy = new ZenPolicy.Builder()
@@ -4070,12 +4060,12 @@
customPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable rule 2; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// now both rules should be on, and the consolidated policy should reflect the most
// restrictive option of each of the two
@@ -4107,12 +4097,12 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable rule 1
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// custom policy for rule 2
ZenPolicy customPolicy = new ZenPolicy.Builder()
@@ -4131,12 +4121,12 @@
customPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable rule 2; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// now both rules should be on, and the consolidated policy should reflect the most
// restrictive option of each of the two
@@ -4173,12 +4163,12 @@
customPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable the rule; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// confirm that channels make it through
assertTrue(mZenModeHelper.mConsolidatedPolicy.allowPriorityChannels());
@@ -4195,12 +4185,12 @@
strictPolicy,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String id2 = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), zenRule2,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// enable rule 2; this will update the consolidated policy
mZenModeHelper.setAutomaticZenRuleState(id2,
new Condition(zenRule2.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// rule 2 should override rule 1
assertFalse(mZenModeHelper.mConsolidatedPolicy.allowPriorityChannels());
@@ -4226,10 +4216,10 @@
.build(),
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
String rule1Id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRuleWithPriority, UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ zenRuleWithPriority, ORIGIN_APP, "test", CUSTOM_PKG_UID);
mZenModeHelper.setAutomaticZenRuleState(rule1Id,
new Condition(zenRuleWithPriority.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Rule 2: ALL, but somehow with a super strict ZenPolicy.
AutomaticZenRule zenRuleWithAll = new AutomaticZenRule("All",
@@ -4239,10 +4229,10 @@
new ZenPolicy.Builder().disallowAllSounds().build(),
NotificationManager.INTERRUPTION_FILTER_ALL, true);
String rule2Id = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRuleWithAll, UPDATE_ORIGIN_APP, "test", CUSTOM_PKG_UID);
+ zenRuleWithAll, ORIGIN_APP, "test", CUSTOM_PKG_UID);
mZenModeHelper.setAutomaticZenRuleState(rule2Id,
new Condition(zenRuleWithPriority.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
// Consolidated Policy should be default + rule1.
assertThat(mZenModeHelper.mConsolidatedPolicy.allowAlarms()).isEqualTo(
@@ -4321,7 +4311,7 @@
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(OWNER.getPackageName(), azr,
- UPDATE_ORIGIN_APP, "add", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add", CUSTOM_PKG_UID);
ZenModeConfig.ZenRule storedRule = mZenModeHelper.mConfig.automaticRules.get(ruleId);
@@ -4351,15 +4341,15 @@
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// Checks the name can be changed by the app because the user has not modified it.
AutomaticZenRule azrUpdate = new AutomaticZenRule.Builder(rule)
.setName("NewName")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_APP, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(rule.getName()).isEqualTo("NewName");
@@ -4368,16 +4358,16 @@
azrUpdate = new AutomaticZenRule.Builder(rule)
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
// ...but the app can still modify the name, because the name itself hasn't been modified
// by the user.
azrUpdate = new AutomaticZenRule.Builder(rule)
.setName("NewAppName")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_APP, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(rule.getName()).isEqualTo("NewAppName");
@@ -4385,8 +4375,8 @@
azrUpdate = new AutomaticZenRule.Builder(rule)
.setName("UserProvidedName")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(rule.getName()).isEqualTo("UserProvidedName");
@@ -4394,8 +4384,8 @@
azrUpdate = new AutomaticZenRule.Builder(rule)
.setName("NewAppName")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_APP, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(rule.getName()).isEqualTo("UserProvidedName");
}
@@ -4411,7 +4401,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// Modifies the filter, icon, zen policy, and device effects
@@ -4430,8 +4420,8 @@
.build();
// Update the rule with the AZR from origin user.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// UPDATE_ORIGIN_USER should change the bitmask and change the values.
@@ -4468,7 +4458,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// Modifies the icon, zen policy and device effects
@@ -4487,8 +4477,8 @@
.build();
// Update the rule with the AZR from origin systemUI.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "reason", Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ZenModeConfig.ORIGIN_SYSTEM,
+ "reason", SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI should change the value but NOT update the bitmask.
@@ -4518,7 +4508,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
ZenPolicy policy = new ZenPolicy.Builder()
@@ -4535,8 +4525,8 @@
// Since the rule is not already user modified, UPDATE_ORIGIN_APP can modify the rule.
// The bitmask is not modified.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azrUpdate, ORIGIN_APP, "reason",
+ SYSTEM_UID);
ZenRule storedRule = mZenModeHelper.mConfig.automaticRules.get(ruleId);
assertThat(storedRule.userModifiedFields).isEqualTo(0);
@@ -4551,7 +4541,7 @@
// Creates another rule, this time from user. This will have user modified bits set.
String ruleIdUser = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_USER, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_USER_IN_SYSTEMUI, "reason", SYSTEM_UID);
storedRule = mZenModeHelper.mConfig.automaticRules.get(ruleIdUser);
int ruleModifiedFields = storedRule.userModifiedFields;
int rulePolicyModifiedFields = storedRule.zenPolicyUserModifiedFields;
@@ -4559,8 +4549,8 @@
// Zen rule update coming from the app again. This cannot fully update the rule, because
// the rule is already considered user modified.
- mZenModeHelper.updateAutomaticZenRule(ruleIdUser, azrUpdate, UPDATE_ORIGIN_APP,
- "reason", Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleIdUser, azrUpdate, ORIGIN_APP,
+ "reason", SYSTEM_UID);
AutomaticZenRule ruleUser = mZenModeHelper.getAutomaticZenRule(ruleIdUser);
// The app can only change the value if the rule is not already user modified,
@@ -4591,7 +4581,7 @@
.build())
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// The values are modified but the bitmask is not.
@@ -4613,7 +4603,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule azr = new AutomaticZenRule.Builder(azrBase)
// Sets Device Effects to null
@@ -4622,8 +4612,8 @@
// Zen rule update coming from app, but since the rule isn't already
// user modified, it can be updated.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azr, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azr, ORIGIN_APP, "reason",
+ SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// When AZR's ZenDeviceEffects is null, the updated rule's device effects are kept.
@@ -4639,7 +4629,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
AutomaticZenRule azr = new AutomaticZenRule.Builder(azrBase)
@@ -4649,8 +4639,8 @@
// Zen rule update coming from app, but since the rule isn't already
// user modified, it can be updated.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azr, UPDATE_ORIGIN_APP, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azr, ORIGIN_APP, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// When AZR's ZenPolicy is null, we expect the updated rule's policy to be unchanged
@@ -4671,7 +4661,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// Create a fully populated ZenPolicy.
@@ -4700,8 +4690,8 @@
// Applies the update to the rule.
// Default config defined in getDefaultConfigParser() is used as the original rule.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azr, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azr, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// New ZenPolicy differs from the default config
@@ -4732,7 +4722,7 @@
.build();
// Adds the rule using the app, to avoid having any user modified bits set.
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- azrBase, UPDATE_ORIGIN_APP, "reason", Process.SYSTEM_UID);
+ azrBase, ORIGIN_APP, "reason", SYSTEM_UID);
AutomaticZenRule rule = mZenModeHelper.getAutomaticZenRule(ruleId);
ZenDeviceEffects deviceEffects = new ZenDeviceEffects.Builder()
@@ -4743,8 +4733,8 @@
.build();
// Applies the update to the rule.
- mZenModeHelper.updateAutomaticZenRule(ruleId, azr, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, azr, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
rule = mZenModeHelper.getAutomaticZenRule(ruleId);
// New ZenDeviceEffects is used; all fields considered set, since previously were null.
@@ -4769,7 +4759,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
CountDownLatch latch = new CountDownLatch(1);
final int[] actualStatus = new int[1];
@@ -4785,8 +4775,8 @@
mZenModeHelper.addCallback(callback);
zenRule.setEnabled(false);
- mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "", Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, ZenModeConfig.ORIGIN_SYSTEM,
+ "", SYSTEM_UID);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
assertEquals(AUTOMATIC_RULE_STATUS_DISABLED, actualStatus[0]);
@@ -4804,7 +4794,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, false);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
CountDownLatch latch = new CountDownLatch(1);
final int[] actualStatus = new int[1];
@@ -4820,8 +4810,8 @@
mZenModeHelper.addCallback(callback);
zenRule.setEnabled(true);
- mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "", Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, ZenModeConfig.ORIGIN_SYSTEM,
+ "", SYSTEM_UID);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
assertEquals(AUTOMATIC_RULE_STATUS_ENABLED, actualStatus[0]);
@@ -4840,7 +4830,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
CountDownLatch latch = new CountDownLatch(1);
final int[] actualStatus = new int[1];
@@ -4857,7 +4847,7 @@
mZenModeHelper.setAutomaticZenRuleState(createdId,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
if (CompatChanges.isChangeEnabled(ZenModeHelper.SEND_ACTIVATION_AZR_STATUSES)) {
@@ -4880,7 +4870,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
CountDownLatch latch = new CountDownLatch(1);
final int[] actualStatus = new int[2];
@@ -4899,10 +4889,10 @@
mZenModeHelper.setAutomaticZenRuleState(createdId,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
- mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- null, "", Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM,
+ null, "", SYSTEM_UID);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
if (CompatChanges.isChangeEnabled(ZenModeHelper.SEND_ACTIVATION_AZR_STATUSES)) {
@@ -4925,7 +4915,7 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
CountDownLatch latch = new CountDownLatch(1);
final int[] actualStatus = new int[2];
@@ -4944,11 +4934,11 @@
mZenModeHelper.setAutomaticZenRuleState(createdId,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
mZenModeHelper.setAutomaticZenRuleState(createdId,
new Condition(zenRule.getConditionId(), "", STATE_FALSE),
- UPDATE_ORIGIN_APP, Process.SYSTEM_UID);
+ ORIGIN_APP, SYSTEM_UID);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
if (CompatChanges.isChangeEnabled(ZenModeHelper.SEND_ACTIVATION_AZR_STATUSES)) {
@@ -4970,21 +4960,21 @@
null,
NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
final String createdId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "test", Process.SYSTEM_UID);
+ zenRule, ZenModeConfig.ORIGIN_SYSTEM, "test", SYSTEM_UID);
// Event 1: Mimic the rule coming on automatically by setting the Condition to STATE_TRUE
mZenModeHelper.setAutomaticZenRuleState(createdId,
new Condition(zenRule.getConditionId(), "", STATE_TRUE),
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, SYSTEM_UID);
// Event 2: Snooze rule by turning off DND
- mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "", null, Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(Global.ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM,
+ "", null, SYSTEM_UID);
// Event 3: "User" turns off the automatic rule (sets it to not enabled)
zenRule.setEnabled(false);
- mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "", Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(createdId, zenRule, ZenModeConfig.ORIGIN_SYSTEM,
+ "", SYSTEM_UID);
assertEquals(false, mZenModeHelper.mConfig.automaticRules.get(createdId).snoozing);
}
@@ -4997,16 +4987,16 @@
.setConfigurationActivity(new ComponentName(mPkg, "cls"))
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, UPDATE_ORIGIN_APP, "reason",
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
AutomaticZenRule updateWithDiff = new AutomaticZenRule.Builder(rule)
.setTriggerDescription("Whenever")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, UPDATE_ORIGIN_APP, "reason",
+ mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
@@ -5021,14 +5011,14 @@
.setConfigurationActivity(new ComponentName(mPkg, "cls"))
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, UPDATE_ORIGIN_APP, "reason",
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
AutomaticZenRule updateUnchanged = new AutomaticZenRule.Builder(rule).build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, updateUnchanged, UPDATE_ORIGIN_APP, "reason",
+ mZenModeHelper.updateAutomaticZenRule(ruleId, updateUnchanged, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
@@ -5044,17 +5034,17 @@
.setConfigurationActivity(new ComponentName(mPkg, "cls"))
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, UPDATE_ORIGIN_APP, "reason",
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
AutomaticZenRule updateWithDiff = new AutomaticZenRule.Builder(rule)
.setTriggerDescription("Whenever")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, UPDATE_ORIGIN_USER, "reason",
- CUSTOM_PKG_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).condition).isEqualTo(
@@ -5074,15 +5064,15 @@
.build();
String ruleId =
mZenModeHelper.addAutomaticZenRule(
- mPkg, rule, UPDATE_ORIGIN_APP, "reason", CUSTOM_PKG_UID);
+ mPkg, rule, ORIGIN_APP, "reason", CUSTOM_PKG_UID);
mZenModeHelper.setAutomaticZenRuleState(
- ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ruleId, CONDITION_TRUE, ORIGIN_APP, CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
AutomaticZenRule updateWithDiff =
new AutomaticZenRule.Builder(rule).setTriggerDescription("Whenever").build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, UPDATE_ORIGIN_USER, "reason",
- CUSTOM_PKG_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, updateWithDiff, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).condition).isEqualTo(
@@ -5097,18 +5087,18 @@
.setConfigurationActivity(new ComponentName(mPkg, "cls"))
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, UPDATE_ORIGIN_APP, "reason",
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, rule, ORIGIN_APP, "reason",
CUSTOM_PKG_UID);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
mZenModeHelper.updateAutomaticZenRule(ruleId,
- new AutomaticZenRule.Builder(rule).setEnabled(false).build(), UPDATE_ORIGIN_USER,
- "disable", CUSTOM_PKG_UID);
+ new AutomaticZenRule.Builder(rule).setEnabled(false).build(),
+ ORIGIN_USER_IN_SYSTEMUI, "disable", SYSTEM_UID);
mZenModeHelper.updateAutomaticZenRule(ruleId,
- new AutomaticZenRule.Builder(rule).setEnabled(true).build(), UPDATE_ORIGIN_USER,
- "enable", CUSTOM_PKG_UID);
+ new AutomaticZenRule.Builder(rule).setEnabled(true).build(),
+ ORIGIN_USER_IN_SYSTEMUI, "enable", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).condition).isNull();
@@ -5123,13 +5113,13 @@
.setOwner(new ComponentName("android", "some.old.cps"))
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule("android", original,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reason", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "reason", SYSTEM_UID);
AutomaticZenRule update = new AutomaticZenRule.Builder("Rule", Uri.EMPTY)
.setOwner(new ComponentName("android", "brand.new.cps"))
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, update, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, update, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
AutomaticZenRule result = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(result).isNotNull();
@@ -5143,13 +5133,13 @@
.setOwner(new ComponentName(mContext.getPackageName(), "old.third.party.cps"))
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), original,
- UPDATE_ORIGIN_APP, "reason", CUSTOM_PKG_UID);
+ ORIGIN_APP, "reason", CUSTOM_PKG_UID);
AutomaticZenRule update = new AutomaticZenRule.Builder("Rule", Uri.EMPTY)
.setOwner(new ComponentName(mContext.getPackageName(), "new.third.party.cps"))
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, update, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, update, ORIGIN_USER_IN_SYSTEMUI, "reason",
+ SYSTEM_UID);
AutomaticZenRule result = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(result).isNotNull();
@@ -5166,24 +5156,24 @@
.setShouldSuppressAmbientDisplay(true)
.setShouldDimWallpaper(true)
.build());
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(any(), eq(UPDATE_ORIGIN_APP));
+ verify(mDeviceEffectsApplier).apply(any(), eq(ORIGIN_APP));
// Now delete the (currently active!) rule. For example, assume this is done from settings.
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_USER, "remove",
- Process.SYSTEM_UID);
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_USER_IN_SYSTEMUI, "remove",
+ SYSTEM_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_USER));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_USER_IN_SYSTEMUI));
}
@Test
@EnableFlags(FLAG_MODES_API)
public void testDeviceEffects_applied() {
mZenModeHelper.setDeviceEffectsApplier(mDeviceEffectsApplier);
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_INIT));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_INIT));
ZenDeviceEffects effects = new ZenDeviceEffects.Builder()
.setShouldSuppressAmbientDisplay(true)
@@ -5192,11 +5182,11 @@
String ruleId = addRuleWithEffects(effects);
verifyNoMoreInteractions(mDeviceEffectsApplier);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(eq(effects), eq(UPDATE_ORIGIN_APP));
+ verify(mDeviceEffectsApplier).apply(eq(effects), eq(ORIGIN_APP));
}
@Test
@@ -5206,30 +5196,30 @@
ZenDeviceEffects zde = new ZenDeviceEffects.Builder().setShouldUseNightMode(true).build();
String ruleId = addRuleWithEffects(zde);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(eq(zde), eq(UPDATE_ORIGIN_APP));
+ verify(mDeviceEffectsApplier).apply(eq(zde), eq(ORIGIN_APP));
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_FALSE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_FALSE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_APP));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_APP));
}
@Test
@EnableFlags(FLAG_MODES_API)
public void testDeviceEffects_changeToConsolidatedEffects_applied() {
mZenModeHelper.setDeviceEffectsApplier(mDeviceEffectsApplier);
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_INIT));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_INIT));
String ruleId = addRuleWithEffects(
new ZenDeviceEffects.Builder()
.setShouldDisplayGrayscale(true)
.addExtraEffect("ONE")
.build());
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
verify(mDeviceEffectsApplier).apply(
@@ -5237,7 +5227,7 @@
.setShouldDisplayGrayscale(true)
.addExtraEffect("ONE")
.build()),
- eq(UPDATE_ORIGIN_APP));
+ eq(ORIGIN_APP));
// Now create and activate a second rule that adds more effects.
String secondRuleId = addRuleWithEffects(
@@ -5245,7 +5235,7 @@
.setShouldDimWallpaper(true)
.addExtraEffect("TWO")
.build());
- mZenModeHelper.setAutomaticZenRuleState(secondRuleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(secondRuleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
@@ -5255,28 +5245,28 @@
.setShouldDimWallpaper(true)
.setExtraEffects(ImmutableSet.of("ONE", "TWO"))
.build()),
- eq(UPDATE_ORIGIN_APP));
+ eq(ORIGIN_APP));
}
@Test
@EnableFlags(FLAG_MODES_API)
public void testDeviceEffects_noChangeToConsolidatedEffects_notApplied() {
mZenModeHelper.setDeviceEffectsApplier(mDeviceEffectsApplier);
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_INIT));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_INIT));
ZenDeviceEffects zde = new ZenDeviceEffects.Builder()
.setShouldUseNightMode(true)
.addExtraEffect("extra_effect")
.build();
String ruleId = addRuleWithEffects(zde);
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
- verify(mDeviceEffectsApplier).apply(eq(zde), eq(UPDATE_ORIGIN_APP));
+ verify(mDeviceEffectsApplier).apply(eq(zde), eq(ORIGIN_APP));
// Now create and activate a second rule that doesn't add any more effects.
String secondRuleId = addRuleWithEffects(zde);
- mZenModeHelper.setAutomaticZenRuleState(secondRuleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(secondRuleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
@@ -5290,20 +5280,20 @@
String ruleId = addRuleWithEffects(zde);
verify(mDeviceEffectsApplier, never()).apply(any(), anyInt());
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
mTestableLooper.processAllMessages();
verify(mDeviceEffectsApplier, never()).apply(any(), anyInt());
mZenModeHelper.setDeviceEffectsApplier(mDeviceEffectsApplier);
- verify(mDeviceEffectsApplier).apply(eq(zde), eq(UPDATE_ORIGIN_INIT));
+ verify(mDeviceEffectsApplier).apply(eq(zde), eq(ORIGIN_INIT));
}
@Test
@EnableFlags(FLAG_MODES_API)
public void testDeviceEffects_onUserSwitch_appliedImmediately() {
mZenModeHelper.setDeviceEffectsApplier(mDeviceEffectsApplier);
- verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(UPDATE_ORIGIN_INIT));
+ verify(mDeviceEffectsApplier).apply(eq(NO_EFFECTS), eq(ORIGIN_INIT));
// Initialize default configurations (default rules) for both users.
mZenModeHelper.onUserSwitched(1);
@@ -5324,7 +5314,7 @@
mTestableLooper.processAllMessages();
verify(mDeviceEffectsApplier).apply(eq(user1Rule.zenDeviceEffects),
- eq(UPDATE_ORIGIN_INIT_USER));
+ eq(ORIGIN_INIT_USER));
}
private String addRuleWithEffects(ZenDeviceEffects effects) {
@@ -5332,7 +5322,7 @@
.setDeviceEffects(effects)
.build();
return mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "reasons", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "reasons", SYSTEM_UID);
}
@Test
@@ -5346,7 +5336,7 @@
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(false).build())
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRule(ruleId).getCreationTime()).isEqualTo(1000);
// User customizes it.
@@ -5354,12 +5344,12 @@
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(true).build())
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, UPDATE_ORIGIN_USER, "userUpdate",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, ORIGIN_USER_IN_SYSTEMUI,
+ "userUpdate", SYSTEM_UID);
// App deletes it.
mTestClock.advanceByMillis(1000);
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_APP, "delete it",
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_APP, "delete it",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(1);
@@ -5367,7 +5357,7 @@
// App adds it again.
mTestClock.advanceByMillis(1000);
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
// Verify that the rule was restored:
// - id and creation time is the same as the original one.
@@ -5401,12 +5391,12 @@
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(false).build())
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRule(ruleId).getCreationTime()).isEqualTo(1000);
// App deletes it.
mTestClock.advanceByMillis(1000);
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_APP, "delete it",
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_APP, "delete it",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(0);
@@ -5414,7 +5404,7 @@
// App adds it again.
mTestClock.advanceByMillis(1000);
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
// Verify that the rule was recreated. This means id and creation time are new.
AutomaticZenRule finalRule = mZenModeHelper.getAutomaticZenRule(newRuleId);
@@ -5433,7 +5423,7 @@
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(false).build())
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRule(ruleId).getCreationTime()).isEqualTo(1000);
// User customizes it.
@@ -5442,12 +5432,12 @@
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(true).build())
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, UPDATE_ORIGIN_USER, "userUpdate",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, ORIGIN_USER_IN_SYSTEMUI,
+ "userUpdate", SYSTEM_UID);
// App deletes it.
mTestClock.advanceByMillis(1000);
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_APP, "delete it",
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_APP, "delete it",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(1);
@@ -5455,7 +5445,7 @@
// User creates it again (unusual case, but ok).
mTestClock.advanceByMillis(1000);
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_USER, "add it anew", CUSTOM_PKG_UID);
+ ORIGIN_USER_IN_SYSTEMUI, "add it anew", SYSTEM_UID);
// Verify that the rule was recreated. This means id and creation time are new, and the rule
// matches the latest data supplied to addAZR.
@@ -5481,7 +5471,7 @@
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(false).build())
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRule(ruleId).getCreationTime()).isEqualTo(1000);
// User customizes it.
@@ -5490,20 +5480,20 @@
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.setZenPolicy(new ZenPolicy.Builder().allowRepeatCallers(true).build())
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, UPDATE_ORIGIN_USER, "userUpdate",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, ORIGIN_USER_IN_SYSTEMUI,
+ "userUpdate", SYSTEM_UID);
// User deletes it.
mTestClock.advanceByMillis(1000);
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_USER, "delete it",
- CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_USER_IN_SYSTEMUI, "delete it",
+ SYSTEM_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(0);
// App creates it again.
mTestClock.advanceByMillis(1000);
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
// Verify that the rule was recreated. This means id and creation time are new.
AutomaticZenRule finalRule = mZenModeHelper.getAutomaticZenRule(newRuleId);
@@ -5520,29 +5510,34 @@
// Start with a bunch of customized rules where conditionUris are not unique.
String id1 = mZenModeHelper.addAutomaticZenRule("pkg1",
- new AutomaticZenRule.Builder("Test1", Uri.parse("uri1")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test1", Uri.parse("uri1")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
String id2 = mZenModeHelper.addAutomaticZenRule("pkg1",
- new AutomaticZenRule.Builder("Test2", Uri.parse("uri2")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test2", Uri.parse("uri2")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
String id3 = mZenModeHelper.addAutomaticZenRule("pkg1",
- new AutomaticZenRule.Builder("Test3", Uri.parse("uri2")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test3", Uri.parse("uri2")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
String id4 = mZenModeHelper.addAutomaticZenRule("pkg2",
- new AutomaticZenRule.Builder("Test4", Uri.parse("uri1")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test4", Uri.parse("uri1")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
String id5 = mZenModeHelper.addAutomaticZenRule("pkg2",
- new AutomaticZenRule.Builder("Test5", Uri.parse("uri1")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test5", Uri.parse("uri1")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
for (ZenRule zenRule : mZenModeHelper.mConfig.automaticRules.values()) {
zenRule.userModifiedFields = AutomaticZenRule.FIELD_INTERRUPTION_FILTER;
}
- mZenModeHelper.removeAutomaticZenRule(id1, UPDATE_ORIGIN_APP, "begone", CUSTOM_PKG_UID);
- mZenModeHelper.removeAutomaticZenRule(id2, UPDATE_ORIGIN_APP, "begone", CUSTOM_PKG_UID);
- mZenModeHelper.removeAutomaticZenRule(id3, UPDATE_ORIGIN_APP, "begone", CUSTOM_PKG_UID);
- mZenModeHelper.removeAutomaticZenRule(id4, UPDATE_ORIGIN_APP, "begone", CUSTOM_PKG_UID);
- mZenModeHelper.removeAutomaticZenRule(id5, UPDATE_ORIGIN_APP, "begone", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id1, ORIGIN_APP, "begone", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id2, ORIGIN_APP, "begone", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id3, ORIGIN_APP, "begone", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id4, ORIGIN_APP, "begone", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id5, ORIGIN_APP, "begone", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.deletedRules.keySet())
.containsExactly("pkg1|uri1", "pkg1|uri2", "pkg2|uri1");
@@ -5557,17 +5552,19 @@
mZenModeHelper.mConfig.automaticRules.clear();
mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- new AutomaticZenRule.Builder("Test1", Uri.parse("uri1")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test1", Uri.parse("uri1")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
- new AutomaticZenRule.Builder("Test2", Uri.parse("uri2")).build(), UPDATE_ORIGIN_APP,
+ new AutomaticZenRule.Builder("Test2", Uri.parse("uri2")).build(),
+ ORIGIN_APP,
"add it", CUSTOM_PKG_UID);
for (ZenRule zenRule : mZenModeHelper.mConfig.automaticRules.values()) {
zenRule.userModifiedFields = AutomaticZenRule.FIELD_INTERRUPTION_FILTER;
}
- mZenModeHelper.removeAutomaticZenRules(mContext.getPackageName(), UPDATE_ORIGIN_APP,
+ mZenModeHelper.removeAutomaticZenRules(mContext.getPackageName(), ORIGIN_APP,
"begone", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(2);
@@ -5586,7 +5583,7 @@
mZenModeHelper.mConfig.deletedRules.put(ZenModeConfig.deletedRuleKey(pkg2Rule), pkg2Rule);
mZenModeHelper.removeAutomaticZenRules("pkg1",
- UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI, "goodbye pkg1", Process.SYSTEM_UID);
+ ZenModeConfig.ORIGIN_SYSTEM, "goodbye pkg1", SYSTEM_UID);
// Preserved rules from pkg1 are gone; those from pkg2 are still there.
assertThat(mZenModeHelper.mConfig.deletedRules.values().stream().map(r -> r.pkg)
@@ -5603,23 +5600,23 @@
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
// User customizes it.
AutomaticZenRule userUpdate = new AutomaticZenRule.Builder(rule)
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, UPDATE_ORIGIN_USER, "userUpdate",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, ORIGIN_USER_IN_SYSTEMUI,
+ "userUpdate", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
// App activates it.
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
// App deletes it.
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_APP, "delete it",
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_APP, "delete it",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(1);
@@ -5627,7 +5624,7 @@
// App adds it again.
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
// The rule is restored...
assertThat(newRuleId).isEqualTo(ruleId);
@@ -5652,35 +5649,35 @@
.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY)
.build();
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it", CUSTOM_PKG_UID);
// User customizes it.
AutomaticZenRule userUpdate = new AutomaticZenRule.Builder(rule)
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, UPDATE_ORIGIN_USER, "userUpdate",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdate, ORIGIN_USER_IN_SYSTEMUI,
+ "userUpdate", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
// App activates it.
- mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(ruleId, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
// User snoozes it.
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_SYSTEM_OR_SYSTEMUI,
- "snoozing", "systemui", Process.SYSTEM_UID);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ZenModeConfig.ORIGIN_SYSTEM,
+ "snoozing", "systemui", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_OFF);
// App deletes it.
- mZenModeHelper.removeAutomaticZenRule(ruleId, UPDATE_ORIGIN_APP, "delete it",
+ mZenModeHelper.removeAutomaticZenRule(ruleId, ORIGIN_APP, "delete it",
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(0);
assertThat(mZenModeHelper.mConfig.deletedRules).hasSize(1);
// App adds it again.
String newRuleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(), rule,
- UPDATE_ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
+ ORIGIN_APP, "add it again", CUSTOM_PKG_UID);
// The rule is restored...
assertThat(newRuleId).isEqualTo(ruleId);
@@ -5762,20 +5759,20 @@
.setConfigurationActivity(
new ComponentName(mContext.getPackageName(), "Blah"))
.build(),
- UPDATE_ORIGIN_APP, "reasons", CUSTOM_PKG_UID);
+ ORIGIN_APP, "reasons", CUSTOM_PKG_UID);
// Null condition -> STATE_FALSE
assertThat(mZenModeHelper.getAutomaticZenRuleState(id)).isEqualTo(Condition.STATE_FALSE);
- mZenModeHelper.setAutomaticZenRuleState(id, CONDITION_TRUE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(id, CONDITION_TRUE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRuleState(id)).isEqualTo(Condition.STATE_TRUE);
- mZenModeHelper.setAutomaticZenRuleState(id, CONDITION_FALSE, UPDATE_ORIGIN_APP,
+ mZenModeHelper.setAutomaticZenRuleState(id, CONDITION_FALSE, ORIGIN_APP,
CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRuleState(id)).isEqualTo(Condition.STATE_FALSE);
- mZenModeHelper.removeAutomaticZenRule(id, UPDATE_ORIGIN_APP, "", CUSTOM_PKG_UID);
+ mZenModeHelper.removeAutomaticZenRule(id, ORIGIN_APP, "", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getAutomaticZenRuleState(id)).isEqualTo(Condition.STATE_UNKNOWN);
}
@@ -5788,7 +5785,7 @@
systemRule.condition = new Condition(systemRule.conditionId, "on", Condition.STATE_TRUE);
ZenModeConfig config = mZenModeHelper.mConfig.copy();
config.automaticRules.put("systemRule", systemRule);
- mZenModeHelper.setConfig(config, null, UPDATE_ORIGIN_INIT, "", Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(config, null, ORIGIN_INIT, "", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
assertThat(mZenModeHelper.getAutomaticZenRuleState("systemRule")).isEqualTo(
@@ -5805,13 +5802,13 @@
otherRule.condition = new Condition(otherRule.conditionId, "on", Condition.STATE_TRUE);
ZenModeConfig config = mZenModeHelper.mConfig.copy();
config.automaticRules.put("otherRule", otherRule);
- mZenModeHelper.setConfig(config, null, UPDATE_ORIGIN_INIT, "", Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(config, null, ORIGIN_INIT, "", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
// Should be ignored.
mZenModeHelper.setAutomaticZenRuleState("otherRule",
new Condition(otherRule.conditionId, "off", Condition.STATE_FALSE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
}
@@ -5826,13 +5823,13 @@
otherRule.condition = new Condition(otherRule.conditionId, "on", Condition.STATE_TRUE);
ZenModeConfig config = mZenModeHelper.mConfig.copy();
config.automaticRules.put("otherRule", otherRule);
- mZenModeHelper.setConfig(config, null, UPDATE_ORIGIN_INIT, "", Process.SYSTEM_UID);
+ mZenModeHelper.setConfig(config, null, ORIGIN_INIT, "", SYSTEM_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
// Should be ignored.
mZenModeHelper.setAutomaticZenRuleState(otherRule.conditionId,
new Condition(otherRule.conditionId, "off", Condition.STATE_FALSE),
- UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ ORIGIN_APP, CUSTOM_PKG_UID);
assertThat(mZenModeHelper.getZenMode()).isEqualTo(ZEN_MODE_ALARMS);
}
@@ -5851,7 +5848,7 @@
});
Policy totalSilencePolicy = new Policy(0, 0, 0);
- mZenModeHelper.setNotificationPolicy(totalSilencePolicy, UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ mZenModeHelper.setNotificationPolicy(totalSilencePolicy, ORIGIN_APP, CUSTOM_PKG_UID);
Policy callbackPolicy = futurePolicy.get(1, TimeUnit.SECONDS);
assertThat(callbackPolicy.allowReminders()).isFalse();
@@ -5874,9 +5871,9 @@
.setOwner(OWNER)
.setInterruptionFilter(INTERRUPTION_FILTER_NONE)
.build(),
- UPDATE_ORIGIN_APP, "reasons", 0);
+ ORIGIN_APP, "reasons", 0);
mZenModeHelper.setAutomaticZenRuleState(totalSilenceRuleId,
- new Condition(CONDITION_ID, "", STATE_TRUE), UPDATE_ORIGIN_APP, CUSTOM_PKG_UID);
+ new Condition(CONDITION_ID, "", STATE_TRUE), ORIGIN_APP, CUSTOM_PKG_UID);
Policy callbackPolicy = futureConsolidatedPolicy.get(1, TimeUnit.SECONDS);
assertThat(callbackPolicy.allowMedia()).isFalse();
@@ -5905,7 +5902,7 @@
mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(CUSTOM_PKG_NAME, CUSTOM_PKG_UID,
ZEN_MODE_IMPORTANT_INTERRUPTIONS);
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_APP, "test", "test", 0);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ORIGIN_APP, "test", "test", 0);
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(CUSTOM_PKG_NAME, CUSTOM_PKG_UID,
@@ -5937,8 +5934,8 @@
AutomaticZenRule userUpdateRule = new AutomaticZenRule.Builder(rule)
.setInterruptionFilter(INTERRUPTION_FILTER_ALARMS)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
// From app, call "setInterruptionFilter" again.
mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(pkg, CUSTOM_PKG_UID,
@@ -5969,8 +5966,8 @@
AutomaticZenRule userUpdateRule = new AutomaticZenRule.Builder(rule)
.setName("Renamed")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
// From app, call "setInterruptionFilter" again.
mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(pkg, CUSTOM_PKG_UID,
@@ -6020,7 +6017,7 @@
assertThat(mZenModeHelper.mConfig.automaticRules).hasSize(1);
assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).snoozing).isFalse();
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, UPDATE_ORIGIN_APP, "test", "test", 0);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, null, ORIGIN_APP, "test", "test", 0);
assertThat(mZenModeHelper.mConfig.automaticRules.valueAt(0).snoozing).isTrue();
mZenModeHelper.applyGlobalZenModeAsImplicitZenRule(CUSTOM_PKG_NAME, CUSTOM_PKG_UID,
@@ -6121,8 +6118,8 @@
AutomaticZenRule userUpdateRule = new AutomaticZenRule.Builder(rule)
.setZenPolicy(userUpdateZenPolicy)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
// From app, call "setNotificationPolicy" again.
Policy appUpdatePolicy = new Policy(PRIORITY_CATEGORY_SYSTEM, 0, 0);
@@ -6159,8 +6156,8 @@
AutomaticZenRule userUpdateRule = new AutomaticZenRule.Builder(rule)
.setName("Rule renamed, not touching policy")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, UPDATE_ORIGIN_USER, "reason",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, userUpdateRule, ORIGIN_USER_IN_SYSTEMUI,
+ "reason", SYSTEM_UID);
// From app, call "setNotificationPolicy" again.
Policy appUpdatePolicy = new Policy(PRIORITY_CATEGORY_SYSTEM, 0, 0);
@@ -6215,7 +6212,7 @@
// If the policy then changes afterwards, it should inherit updates because user cannot
// edit the policy in the UI.
mZenModeHelper.setNotificationPolicy(new Policy(PRIORITY_CATEGORY_ALARMS, 0, 0),
- UPDATE_ORIGIN_APP, 1);
+ ORIGIN_APP, 1);
Policy readPolicy = mZenModeHelper.getNotificationPolicyFromImplicitZenRule(
CUSTOM_PKG_NAME);
@@ -6228,7 +6225,7 @@
@EnableFlags(FLAG_MODES_API)
public void getNotificationPolicyFromImplicitZenRule_noImplicitRule_returnsGlobalPolicy() {
Policy policy = new Policy(PRIORITY_CATEGORY_CALLS, PRIORITY_SENDERS_STARRED, 0);
- mZenModeHelper.setNotificationPolicy(policy, UPDATE_ORIGIN_USER, 1);
+ mZenModeHelper.setNotificationPolicy(policy, ORIGIN_APP, CUSTOM_PKG_UID);
Policy readPolicy = mZenModeHelper.getNotificationPolicyFromImplicitZenRule(
CUSTOM_PKG_NAME);
@@ -6264,7 +6261,7 @@
ZEN_MODE_IMPORTANT_INTERRUPTIONS, previousManualZenPolicy);
Policy newManualPolicy = new Policy(PRIORITY_CATEGORY_EVENTS, 0, 0);
- mZenModeHelper.setNotificationPolicy(newManualPolicy, UPDATE_ORIGIN_USER, 0);
+ mZenModeHelper.setNotificationPolicy(newManualPolicy, ORIGIN_APP, CUSTOM_PKG_UID);
ZenPolicy newManualZenPolicy = ZenAdapters.notificationPolicyToZenPolicy(newManualPolicy);
// Only app rules with default or same-as-manual policies were updated.
@@ -6294,7 +6291,7 @@
String ruleId = mZenModeHelper.addAutomaticZenRule(mContext.getPackageName(),
new AutomaticZenRule.Builder("Rule", CONDITION_ID).setIconResId(resourceId).build(),
- UPDATE_ORIGIN_APP, "reason", CUSTOM_PKG_UID);
+ ORIGIN_APP, "reason", CUSTOM_PKG_UID);
AutomaticZenRule storedRule = mZenModeHelper.getAutomaticZenRule(ruleId);
assertThat(storedRule.getIconResId()).isEqualTo(0);
@@ -6306,7 +6303,8 @@
ZenDeviceEffects effects = new ZenDeviceEffects.Builder()
.setShouldDimWallpaper(true)
.build();
- mZenModeHelper.setManualZenRuleDeviceEffects(effects, UPDATE_ORIGIN_USER, "settings", 1000);
+ mZenModeHelper.setManualZenRuleDeviceEffects(effects, ORIGIN_USER_IN_SYSTEMUI, "settings",
+ SYSTEM_UID);
assertThat(mZenModeHelper.getConfig().manualRule).isNotNull();
assertThat(mZenModeHelper.getConfig().isManualActive()).isFalse();
@@ -6316,13 +6314,14 @@
@Test
@EnableFlags({FLAG_MODES_API, FLAG_MODES_UI})
public void setManualZenRuleDeviceEffects_preexistingMode() {
- mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, Uri.EMPTY, UPDATE_ORIGIN_USER,
- "create manual rule", "settings", 1000);
+ mZenModeHelper.setManualZenMode(ZEN_MODE_OFF, Uri.EMPTY, ORIGIN_USER_IN_SYSTEMUI,
+ "create manual rule", "settings", SYSTEM_UID);
ZenDeviceEffects effects = new ZenDeviceEffects.Builder()
.setShouldDimWallpaper(true)
.build();
- mZenModeHelper.setManualZenRuleDeviceEffects(effects, UPDATE_ORIGIN_USER, "settings", 1000);
+ mZenModeHelper.setManualZenRuleDeviceEffects(effects, ORIGIN_USER_IN_SYSTEMUI, "settings",
+ SYSTEM_UID);
assertThat(mZenModeHelper.getConfig().manualRule).isNotNull();
assertThat(mZenModeHelper.getConfig().isManualActive()).isFalse();
@@ -6337,11 +6336,12 @@
.setEnabled(false)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsDisabled, UPDATE_ORIGIN_APP,
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsDisabled,
+ ORIGIN_APP,
"new", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_APP);
+ ORIGIN_APP);
}
@Test
@@ -6351,19 +6351,20 @@
.setOwner(new ComponentName(mPkg, "SomeProvider"))
.setEnabled(true)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled, UPDATE_ORIGIN_APP,
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled,
+ ORIGIN_APP,
"new", CUSTOM_PKG_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_UNKNOWN);
+ ORIGIN_UNKNOWN);
AutomaticZenRule nowDisabled = new AutomaticZenRule.Builder(startsEnabled)
.setEnabled(false)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, UPDATE_ORIGIN_USER, "off",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, ORIGIN_USER_IN_SYSTEMUI, "off",
+ SYSTEM_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
}
@Test
@@ -6373,26 +6374,27 @@
.setOwner(new ComponentName(mPkg, "SomeProvider"))
.setEnabled(true)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled, UPDATE_ORIGIN_APP,
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled,
+ ORIGIN_APP,
"new", CUSTOM_PKG_UID);
AutomaticZenRule nowDisabled = new AutomaticZenRule.Builder(startsEnabled)
.setEnabled(false)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, UPDATE_ORIGIN_USER, "off",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, ORIGIN_USER_IN_SYSTEMUI, "off",
+ SYSTEM_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
// Now update it again, for an unrelated reason with a different origin.
AutomaticZenRule nowRenamed = new AutomaticZenRule.Builder(nowDisabled)
.setName("Fancy pants rule")
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, nowRenamed, UPDATE_ORIGIN_APP, "update",
+ mZenModeHelper.updateAutomaticZenRule(ruleId, nowRenamed, ORIGIN_APP, "update",
CUSTOM_PKG_UID);
// Identity of the disabler is preserved.
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
}
@Test
@@ -6402,26 +6404,27 @@
.setOwner(new ComponentName(mPkg, "SomeProvider"))
.setEnabled(true)
.build();
- String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled, UPDATE_ORIGIN_APP,
+ String ruleId = mZenModeHelper.addAutomaticZenRule(mPkg, startsEnabled,
+ ORIGIN_APP,
"new", CUSTOM_PKG_UID);
AutomaticZenRule nowDisabled = new AutomaticZenRule.Builder(startsEnabled)
.setEnabled(false)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, UPDATE_ORIGIN_USER, "off",
- Process.SYSTEM_UID);
+ mZenModeHelper.updateAutomaticZenRule(ruleId, nowDisabled, ORIGIN_USER_IN_SYSTEMUI, "off",
+ SYSTEM_UID);
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_USER);
+ ORIGIN_USER_IN_SYSTEMUI);
// Now enable it again
AutomaticZenRule nowEnabled = new AutomaticZenRule.Builder(nowDisabled)
.setEnabled(true)
.build();
- mZenModeHelper.updateAutomaticZenRule(ruleId, nowEnabled, UPDATE_ORIGIN_APP, "on",
+ mZenModeHelper.updateAutomaticZenRule(ruleId, nowEnabled, ORIGIN_APP, "on",
CUSTOM_PKG_UID);
// Identity of the disabler was cleared.
assertThat(mZenModeHelper.mConfig.automaticRules.get(ruleId).disabledOrigin).isEqualTo(
- UPDATE_ORIGIN_UNKNOWN);
+ ORIGIN_UNKNOWN);
}
private static void addZenRule(ZenModeConfig config, String id, String ownerPkg, int zenMode,
@@ -6494,7 +6497,7 @@
SUPPRESSED_EFFECT_BADGE,
0,
CONVERSATION_SENDERS_IMPORTANT);
- mZenModeHelper.setNotificationPolicy(customPolicy, UPDATE_ORIGIN_UNKNOWN, 1);
+ mZenModeHelper.setNotificationPolicy(customPolicy, ORIGIN_UNKNOWN, 1);
if (!Flags.modesUi()) {
mZenModeHelper.mConfig.manualRule = null;
}
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java b/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
index 4f75931..240bd1e 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/HapticFeedbackVibrationProviderTest.java
@@ -50,7 +50,6 @@
import android.os.VibrationAttributes;
import android.os.VibrationEffect;
import android.os.VibratorInfo;
-import android.os.vibrator.Flags;
import android.platform.test.flag.junit.SetFlagsRule;
import android.util.AtomicFile;
import android.util.SparseArray;
@@ -256,22 +255,7 @@
}
@Test
- public void testKeyboardHaptic_fixAmplitude_keyboardCategoryOff_defaultVibrationReturned() {
- mSetFlagsRule.disableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
- mockVibratorPrimitiveSupport(PRIMITIVE_CLICK, PRIMITIVE_TICK);
- mockKeyboardVibrationFixedAmplitude(KEYBOARD_VIBRATION_FIXED_AMPLITUDE);
-
- HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
-
- assertThat(hapticProvider.getVibrationForHapticFeedback(KEYBOARD_TAP))
- .isEqualTo(VibrationEffect.get(EFFECT_CLICK, true /* fallback */));
- assertThat(hapticProvider.getVibrationForHapticFeedback(KEYBOARD_RELEASE))
- .isEqualTo(VibrationEffect.get(EFFECT_TICK, false /* fallback */));
- }
-
- @Test
public void testKeyboardHaptic_fixAmplitude_keyboardCategoryOn_keyboardVibrationReturned() {
- mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
mockVibratorPrimitiveSupport(PRIMITIVE_CLICK, PRIMITIVE_TICK);
mockKeyboardVibrationFixedAmplitude(KEYBOARD_VIBRATION_FIXED_AMPLITUDE);
@@ -346,24 +330,7 @@
}
@Test
- public void testVibrationAttribute_keyboardCategoryOff_isIme_useTouchUsage() {
- mSetFlagsRule.disableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
- HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
-
- for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
- VibrationAttributes attrs = hapticProvider.getVibrationAttributesForHapticFeedback(
- effectId, /* flags */ 0,
- HapticFeedbackConstants.PRIVATE_FLAG_APPLY_INPUT_METHOD_SETTINGS);
- assertWithMessage("Expected USAGE_TOUCH for effect " + effectId)
- .that(attrs.getUsage()).isEqualTo(USAGE_TOUCH);
- assertWithMessage("Expected no CATEGORY_KEYBOARD for effect " + effectId)
- .that(attrs.getCategory()).isEqualTo(CATEGORY_UNKNOWN);
- }
- }
-
- @Test
public void testVibrationAttribute_keyboardCategoryOn_notIme_useTouchUsage() {
- mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
@@ -378,7 +345,6 @@
@Test
public void testVibrationAttribute_keyboardCategoryOn_isIme_useImeFeedbackUsage() {
- mSetFlagsRule.enableFlags(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED);
HapticFeedbackVibrationProvider hapticProvider = createProviderWithDefaultCustomizations();
for (int effectId : KEYBOARD_FEEDBACK_CONSTANTS) {
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java b/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java
index 8d4a6aa..72ef888 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java
@@ -70,9 +70,7 @@
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.test.TestLooper;
-import android.os.vibrator.Flags;
import android.os.vibrator.VibrationConfig;
-import android.platform.test.annotations.RequiresFlagsEnabled;
import android.platform.test.flag.junit.CheckFlagsRule;
import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.provider.Settings;
@@ -602,7 +600,6 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED)
public void shouldIgnoreVibration_withKeyboardSettingsOff_shouldIgnoreKeyboardVibration() {
setUserSetting(Settings.System.HAPTIC_FEEDBACK_INTENSITY, VIBRATION_INTENSITY_MEDIUM);
setUserSetting(Settings.System.KEYBOARD_VIBRATION_ENABLED, 0 /* OFF*/);
@@ -627,7 +624,6 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED)
public void shouldIgnoreVibration_withKeyboardSettingsOn_shouldNotIgnoreKeyboardVibration() {
setUserSetting(Settings.System.HAPTIC_FEEDBACK_INTENSITY, VIBRATION_INTENSITY_OFF);
setUserSetting(Settings.System.KEYBOARD_VIBRATION_ENABLED, 1 /* ON */);
@@ -645,7 +641,6 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_KEYBOARD_CATEGORY_ENABLED)
public void shouldIgnoreVibration_notSupportKeyboardVibration_ignoresKeyboardTouchVibration() {
setUserSetting(Settings.System.HAPTIC_FEEDBACK_INTENSITY, VIBRATION_INTENSITY_OFF);
setUserSetting(Settings.System.KEYBOARD_VIBRATION_ENABLED, 1 /* ON */);
diff --git a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
index 4a9d5c7..f339d29 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
@@ -218,16 +218,6 @@
}
@Test
- public void testPerformDrag_NullDataToOtherUser() {
- final WindowState otherUsersWindow =
- createDropTargetWindow("Other user's window", 1 * UserHandle.PER_USER_RANGE);
- doReturn(otherUsersWindow).when(mDisplayContent).getTouchableWinAtPointLocked(10, 10);
-
- doDragAndDrop(View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ, null, 10, 10);
- mToken = otherUsersWindow.mClient.asBinder();
- }
-
- @Test
public void testPrivateInterceptGlobalDragDropFlagChecksPermission() {
DisplayPolicy policy = mDisplayContent.getDisplayPolicy();
WindowManager.LayoutParams attrs = new WindowManager.LayoutParams();
diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
index b92af87..1e39f0b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
@@ -139,7 +139,6 @@
private ActivityTaskManagerService mAtmService;
private WindowManagerService mWmService;
private InputManagerService mImService;
- private InputChannel mInputChannel;
private Runnable mOnBeforeServicesCreated;
/**
* Spied {@link SurfaceControl.Transaction} class than can be used to verify calls.
@@ -326,12 +325,15 @@
// InputManagerService
mImService = mock(InputManagerService.class);
- // InputChannel cannot be mocked because it may pass to InputEventReceiver.
- final InputChannel[] inputChannels = InputChannel.openInputChannelPair(TAG);
- inputChannels[0].dispose();
- mInputChannel = inputChannels[1];
- doReturn(mInputChannel).when(mImService).monitorInput(anyString(), anyInt());
- doReturn(mInputChannel).when(mImService).createInputChannel(anyString());
+ // InputChannel cannot be mocked because it may be passed to InputEventReceiver.
+ Answer<InputChannel> newInputChannel = invocation -> {
+ String name = invocation.getArgument(0);
+ final InputChannel[] channels = InputChannel.openInputChannelPair(name);
+ channels[0].dispose();
+ return channels[1];
+ };
+ when(mImService.monitorInput(anyString(), anyInt())).thenAnswer(newInputChannel);
+ when(mImService.createInputChannel(anyString())).thenAnswer(newInputChannel);
// StatusBarManagerInternal
final StatusBarManagerInternal sbmi = mock(StatusBarManagerInternal.class);
@@ -464,9 +466,6 @@
SurfaceAnimationThread.dispose();
AnimationThread.dispose();
UiThread.dispose();
- if (mInputChannel != null) {
- mInputChannel.dispose();
- }
tearDownLocalServices();
// Reset priority booster because animation thread has been changed.
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
index 73cfd3f..5dde265 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
@@ -85,6 +85,8 @@
errors,
stats,
policyFileRemapper,
+ options.numShards.get,
+ options.shard.get,
)
// Dump statistics, if specified.
@@ -213,6 +215,8 @@
errors: HostStubGenErrors,
stats: HostStubGenStats,
remapper: Remapper?,
+ numShards: Int,
+ shard: Int,
) {
log.i("Converting %s into [stub: %s, impl: %s] ...", inJar, outStubJar, outImplJar)
log.i("ASM CheckClassAdapter is %s", if (enableChecker) "enabled" else "disabled")
@@ -221,17 +225,32 @@
val packageRedirector = PackageRedirectRemapper(options.packageRedirects)
+ var itemIndex = 0
+ var numItemsProcessed = 0
+ var numItems = -1 // == Unknown
+
log.withIndent {
// Open the input jar file and process each entry.
ZipFile(inJar).use { inZip ->
+
+ numItems = inZip.size()
+ val shardStart = numItems * shard / numShards
+ val shardNextStart = numItems * (shard + 1) / numShards
+
maybeWithZipOutputStream(outStubJar) { stubOutStream ->
maybeWithZipOutputStream(outImplJar) { implOutStream ->
val inEntries = inZip.entries()
while (inEntries.hasMoreElements()) {
val entry = inEntries.nextElement()
+ val inShard = (shardStart <= itemIndex) && (itemIndex < shardNextStart)
+ itemIndex++
+ if (!inShard) {
+ continue
+ }
convertSingleEntry(inZip, entry, stubOutStream, implOutStream,
filter, packageRedirector, remapper,
enableChecker, classes, errors, stats)
+ numItemsProcessed++
}
log.i("Converted all entries.")
}
@@ -241,7 +260,8 @@
}
}
val end = System.currentTimeMillis()
- log.i("Done transforming the jar in %.1f second(s).", (end - start) / 1000.0)
+ log.i("Done transforming the jar in %.1f second(s). %d / %d item(s) processed.",
+ (end - start) / 1000.0, numItemsProcessed, numItems)
}
private fun <T> maybeWithZipOutputStream(filename: String?, block: (ZipOutputStream?) -> T): T {
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
index e192516..2f833a8 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
@@ -112,6 +112,9 @@
var statsFile: SetOnce<String?> = SetOnce(null),
var apiListFile: SetOnce<String?> = SetOnce(null),
+
+ var numShards: SetOnce<Int> = SetOnce(1),
+ var shard: SetOnce<Int> = SetOnce(0),
) {
companion object {
@@ -162,6 +165,13 @@
fun SetOnce<String?>.setNextStringArg(): String = nextArg().also { this.set(it) }
fun MutableSet<String>.addUniqueAnnotationArg(): String =
nextArg().also { this += ensureUniqueAnnotation(it) }
+ fun SetOnce<Int>.setNextIntArg(): String = nextArg().also {
+ try {
+ this.set(it.toInt())
+ } catch (e: NumberFormatException) {
+ throw ArgumentsException("Invalid integer for $arg: $it")
+ }
+ }
try {
when (arg) {
@@ -259,6 +269,9 @@
"--stats-file" -> ret.statsFile.setNextStringArg()
"--supported-api-list-file" -> ret.apiListFile.setNextStringArg()
+ "--num-shards" -> ret.numShards.setNextIntArg()
+ "--shard-index" -> ret.shard.setNextIntArg()
+
else -> throw ArgumentsException("Unknown option: $arg")
}
} catch (e: SetOnce.SetMoreThanOnceException) {
@@ -396,6 +409,8 @@
enableNonStubMethodCallDetection=$enableNonStubMethodCallDetection,
statsFile=$statsFile,
apiListFile=$apiListFile,
+ numShards=$numShards,
+ shard=$shard,
}
""".trimIndent()
}