diff options
| author | 2023-03-29 12:22:45 -0400 | |
|---|---|---|
| committer | 2023-04-06 17:27:57 -0400 | |
| commit | 0bf4481951a1dcf3d0033293ebe8fe96096e5c7a (patch) | |
| tree | f8756883c64c72c56746da15d7d0b0f789109e45 | |
| parent | 37e84cec827e8eb43266ea24e423dde93eb5ca5e (diff) | |
Separate diffing functionality into a separate class.
This creates ZenModeDiff with subclasses for diffs on ZenModeConfig and ZenRule. The new class allows for both emitting a string describing the diffs as well as reading what the diffs were after the fact (which the previous implementation did not allow).
Bug: 259261349
Test: ZenModeDiffTest, adb shell dumpsys notification
Change-Id: I8d51a8dc6c0edf548e1ef8ba350d9302d9ca7a86
5 files changed, 875 insertions, 188 deletions
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java index 402da28b3c5c..828c062d955d 100644 --- a/core/java/android/service/notification/ZenModeConfig.java +++ b/core/java/android/service/notification/ZenModeConfig.java @@ -45,7 +45,6 @@ import android.provider.Settings.Global; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.ArrayMap; -import android.util.ArraySet; import android.util.PluralsMessageFormatter; import android.util.Slog; import android.util.proto.ProtoOutputStream; @@ -59,7 +58,6 @@ import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; @@ -310,86 +308,6 @@ public class ZenModeConfig implements Parcelable { return buffer.toString(); } - public Diff diff(ZenModeConfig to) { - final Diff d = new Diff(); - if (to == null) { - return d.addLine("config", "delete"); - } - if (user != to.user) { - d.addLine("user", user, to.user); - } - if (allowAlarms != to.allowAlarms) { - d.addLine("allowAlarms", allowAlarms, to.allowAlarms); - } - if (allowMedia != to.allowMedia) { - d.addLine("allowMedia", allowMedia, to.allowMedia); - } - if (allowSystem != to.allowSystem) { - d.addLine("allowSystem", allowSystem, to.allowSystem); - } - if (allowCalls != to.allowCalls) { - d.addLine("allowCalls", allowCalls, to.allowCalls); - } - if (allowReminders != to.allowReminders) { - d.addLine("allowReminders", allowReminders, to.allowReminders); - } - if (allowEvents != to.allowEvents) { - d.addLine("allowEvents", allowEvents, to.allowEvents); - } - if (allowRepeatCallers != to.allowRepeatCallers) { - d.addLine("allowRepeatCallers", allowRepeatCallers, to.allowRepeatCallers); - } - if (allowMessages != to.allowMessages) { - d.addLine("allowMessages", allowMessages, to.allowMessages); - } - if (allowCallsFrom != to.allowCallsFrom) { - d.addLine("allowCallsFrom", allowCallsFrom, to.allowCallsFrom); - } - if (allowMessagesFrom != to.allowMessagesFrom) { - d.addLine("allowMessagesFrom", allowMessagesFrom, to.allowMessagesFrom); - } - if (suppressedVisualEffects != to.suppressedVisualEffects) { - d.addLine("suppressedVisualEffects", suppressedVisualEffects, - to.suppressedVisualEffects); - } - final ArraySet<String> allRules = new ArraySet<>(); - addKeys(allRules, automaticRules); - addKeys(allRules, to.automaticRules); - final int N = allRules.size(); - for (int i = 0; i < N; i++) { - final String rule = allRules.valueAt(i); - final ZenRule fromRule = automaticRules != null ? automaticRules.get(rule) : null; - final ZenRule toRule = to.automaticRules != null ? to.automaticRules.get(rule) : null; - ZenRule.appendDiff(d, "automaticRule[" + rule + "]", fromRule, toRule); - } - ZenRule.appendDiff(d, "manualRule", manualRule, to.manualRule); - - if (areChannelsBypassingDnd != to.areChannelsBypassingDnd) { - d.addLine("areChannelsBypassingDnd", areChannelsBypassingDnd, - to.areChannelsBypassingDnd); - } - return d; - } - - public static Diff diff(ZenModeConfig from, ZenModeConfig to) { - if (from == null) { - final Diff d = new Diff(); - if (to != null) { - d.addLine("config", "insert"); - } - return d; - } - return from.diff(to); - } - - private static <T> void addKeys(ArraySet<T> set, ArrayMap<T, ?> map) { - if (map != null) { - for (int i = 0; i < map.size(); i++) { - set.add(map.keyAt(i)); - } - } - } - public boolean isValid() { if (!isValidManualRule(manualRule)) return false; final int N = automaticRules.size(); @@ -1922,66 +1840,6 @@ public class ZenModeConfig implements Parcelable { proto.end(token); } - private static void appendDiff(Diff d, String item, ZenRule from, ZenRule to) { - if (d == null) return; - if (from == null) { - if (to != null) { - d.addLine(item, "insert"); - } - return; - } - from.appendDiff(d, item, to); - } - - private void appendDiff(Diff d, String item, ZenRule to) { - if (to == null) { - d.addLine(item, "delete"); - return; - } - if (enabled != to.enabled) { - d.addLine(item, "enabled", enabled, to.enabled); - } - if (snoozing != to.snoozing) { - d.addLine(item, "snoozing", snoozing, to.snoozing); - } - if (!Objects.equals(name, to.name)) { - d.addLine(item, "name", name, to.name); - } - if (zenMode != to.zenMode) { - d.addLine(item, "zenMode", zenMode, to.zenMode); - } - if (!Objects.equals(conditionId, to.conditionId)) { - d.addLine(item, "conditionId", conditionId, to.conditionId); - } - if (!Objects.equals(condition, to.condition)) { - d.addLine(item, "condition", condition, to.condition); - } - if (!Objects.equals(component, to.component)) { - d.addLine(item, "component", component, to.component); - } - if (!Objects.equals(configurationActivity, to.configurationActivity)) { - d.addLine(item, "configActivity", configurationActivity, to.configurationActivity); - } - if (!Objects.equals(id, to.id)) { - d.addLine(item, "id", id, to.id); - } - if (creationTime != to.creationTime) { - d.addLine(item, "creationTime", creationTime, to.creationTime); - } - if (!Objects.equals(enabler, to.enabler)) { - d.addLine(item, "enabler", enabler, to.enabler); - } - if (!Objects.equals(zenPolicy, to.zenPolicy)) { - d.addLine(item, "zenPolicy", zenPolicy, to.zenPolicy); - } - if (modified != to.modified) { - d.addLine(item, "modified", modified, to.modified); - } - if (!Objects.equals(pkg, to.pkg)) { - d.addLine(item, "pkg", pkg, to.pkg); - } - } - @Override public boolean equals(@Nullable Object o) { if (!(o instanceof ZenRule)) return false; @@ -2040,40 +1898,6 @@ public class ZenModeConfig implements Parcelable { }; } - public static class Diff { - private final ArrayList<String> lines = new ArrayList<>(); - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Diff["); - final int N = lines.size(); - for (int i = 0; i < N; i++) { - if (i > 0) { - sb.append(",\n"); - } - sb.append(lines.get(i)); - } - return sb.append(']').toString(); - } - - private Diff addLine(String item, String action) { - lines.add(item + ":" + action); - return this; - } - - public Diff addLine(String item, String subitem, Object from, Object to) { - return addLine(item + "." + subitem, from, to); - } - - public Diff addLine(String item, Object from, Object to) { - return addLine(item, from + "->" + to); - } - - public boolean isEmpty() { - return lines.isEmpty(); - } - } - /** * Determines whether dnd behavior should mute all ringer-controlled sounds * This includes notification, ringer and system sounds diff --git a/core/java/android/service/notification/ZenModeDiff.java b/core/java/android/service/notification/ZenModeDiff.java new file mode 100644 index 000000000000..c7b89eb284b6 --- /dev/null +++ b/core/java/android/service/notification/ZenModeDiff.java @@ -0,0 +1,542 @@ +/* + * Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.service.notification; + +import android.annotation.IntDef; +import android.annotation.Nullable; +import android.util.ArrayMap; +import android.util.ArraySet; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Objects; +import java.util.Set; + +/** + * ZenModeDiff is a utility class meant to encapsulate the diff between ZenModeConfigs and their + * subcomponents (automatic and manual ZenRules). + * @hide + */ +public class ZenModeDiff { + /** + * Enum representing whether the existence of a config or rule has changed (added or removed, + * or "none" meaning there is no change, which may either mean both null, or there exists a + * diff in fields rather than add/remove). + */ + @IntDef(value = { + NONE, + ADDED, + REMOVED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface ExistenceChange{} + + public static final int NONE = 0; + public static final int ADDED = 1; + public static final int REMOVED = 2; + + /** + * Diff class representing an individual field diff. + * @param <T> The type of the field. + */ + public static class FieldDiff<T> { + private final T mFrom; + private final T mTo; + + /** + * Constructor to create a FieldDiff object with the given values. + * @param from from (old) value + * @param to to (new) value + */ + public FieldDiff(@Nullable T from, @Nullable T to) { + mFrom = from; + mTo = to; + } + + /** + * Get the "from" value + */ + public T from() { + return mFrom; + } + + /** + * Get the "to" value + */ + public T to() { + return mTo; + } + + /** + * Get the string representation of this field diff, in the form of "from->to". + */ + @Override + public String toString() { + return mFrom + "->" + mTo; + } + + /** + * Returns whether this represents an actual diff. + */ + public boolean hasDiff() { + // note that Objects.equals handles null values gracefully. + return !Objects.equals(mFrom, mTo); + } + } + + /** + * Base diff class that contains info about whether something was added, and a set of named + * fields that changed. + * Extend for diffs of specific types of objects. + */ + private abstract static class BaseDiff { + // Whether the diff was added or removed + @ExistenceChange private int mExists = NONE; + + // Map from field name to diffs for any standalone fields in the object. + private ArrayMap<String, FieldDiff> mFields = new ArrayMap<>(); + + // Functions for actually diffing objects and string representations have to be implemented + // by subclasses. + + /** + * Return whether this diff represents any changes. + */ + public abstract boolean hasDiff(); + + /** + * Return a string representation of the diff. + */ + public abstract String toString(); + + /** + * Constructor that takes the two objects meant to be compared. This constructor sets + * whether there is an existence change (added or removed). + * @param from previous Object + * @param to new Object + */ + BaseDiff(Object from, Object to) { + if (from == null) { + if (to != null) { + mExists = ADDED; + } + // If both are null, there isn't an existence change; callers/inheritors must handle + // the both null case. + } else if (to == null) { + // in this case, we know that from != null + mExists = REMOVED; + } + + // Subclasses should implement the actual diffing functionality in their own + // constructors. + } + + /** + * Add a diff for a specific field to the map. + * @param name field name + * @param diff FieldDiff object representing the diff + */ + final void addField(String name, FieldDiff diff) { + mFields.put(name, diff); + } + + /** + * Returns whether this diff represents a config being newly added. + */ + public final boolean wasAdded() { + return mExists == ADDED; + } + + /** + * Returns whether this diff represents a config being removed. + */ + public final boolean wasRemoved() { + return mExists == REMOVED; + } + + /** + * Returns whether this diff represents an object being either added or removed. + */ + public final boolean hasExistenceChange() { + return mExists != NONE; + } + + /** + * Returns whether there are any individual field diffs. + */ + public final boolean hasFieldDiffs() { + return mFields.size() > 0; + } + + /** + * Returns the diff for the specific named field if it exists + */ + public final FieldDiff getDiffForField(String name) { + return mFields.getOrDefault(name, null); + } + + /** + * Get the set of all field names with some diff. + */ + public final Set<String> fieldNamesWithDiff() { + return mFields.keySet(); + } + } + + /** + * Diff class representing a diff between two ZenModeConfigs. + */ + public static class ConfigDiff extends BaseDiff { + // Rules. Automatic rule map is keyed by the rule name. + private final ArrayMap<String, RuleDiff> mAutomaticRulesDiff = new ArrayMap<>(); + private RuleDiff mManualRuleDiff; + + // Helpers for string generation + private static final String ALLOW_CALLS_FROM_FIELD = "allowCallsFrom"; + private static final String ALLOW_MESSAGES_FROM_FIELD = "allowMessagesFrom"; + private static final String ALLOW_CONVERSATIONS_FROM_FIELD = "allowConversationsFrom"; + private static final Set<String> PEOPLE_TYPE_FIELDS = + Set.of(ALLOW_CALLS_FROM_FIELD, ALLOW_MESSAGES_FROM_FIELD); + + /** + * Create a diff that contains diffs between the "from" and "to" ZenModeConfigs. + * + * @param from previous ZenModeConfig + * @param to new ZenModeConfig + */ + public ConfigDiff(ZenModeConfig from, ZenModeConfig to) { + super(from, to); + // If both are null skip + if (from == null && to == null) { + return; + } + if (hasExistenceChange()) { + // either added or removed; return here. otherwise (they're not both null) there's + // field diffs. + return; + } + + // Now we compare all the fields, knowing there's a diff and that neither is null + if (from.user != to.user) { + addField("user", new FieldDiff<>(from.user, to.user)); + } + if (from.allowAlarms != to.allowAlarms) { + addField("allowAlarms", new FieldDiff<>(from.allowAlarms, to.allowAlarms)); + } + if (from.allowMedia != to.allowMedia) { + addField("allowMedia", new FieldDiff<>(from.allowMedia, to.allowMedia)); + } + if (from.allowSystem != to.allowSystem) { + addField("allowSystem", new FieldDiff<>(from.allowSystem, to.allowSystem)); + } + if (from.allowCalls != to.allowCalls) { + addField("allowCalls", new FieldDiff<>(from.allowCalls, to.allowCalls)); + } + if (from.allowReminders != to.allowReminders) { + addField("allowReminders", + new FieldDiff<>(from.allowReminders, to.allowReminders)); + } + if (from.allowEvents != to.allowEvents) { + addField("allowEvents", new FieldDiff<>(from.allowEvents, to.allowEvents)); + } + if (from.allowRepeatCallers != to.allowRepeatCallers) { + addField("allowRepeatCallers", + new FieldDiff<>(from.allowRepeatCallers, to.allowRepeatCallers)); + } + if (from.allowMessages != to.allowMessages) { + addField("allowMessages", + new FieldDiff<>(from.allowMessages, to.allowMessages)); + } + if (from.allowConversations != to.allowConversations) { + addField("allowConversations", + new FieldDiff<>(from.allowConversations, to.allowConversations)); + } + if (from.allowCallsFrom != to.allowCallsFrom) { + addField("allowCallsFrom", + new FieldDiff<>(from.allowCallsFrom, to.allowCallsFrom)); + } + if (from.allowMessagesFrom != to.allowMessagesFrom) { + addField("allowMessagesFrom", + new FieldDiff<>(from.allowMessagesFrom, to.allowMessagesFrom)); + } + if (from.allowConversationsFrom != to.allowConversationsFrom) { + addField("allowConversationsFrom", + new FieldDiff<>(from.allowConversationsFrom, to.allowConversationsFrom)); + } + if (from.suppressedVisualEffects != to.suppressedVisualEffects) { + addField("suppressedVisualEffects", + new FieldDiff<>(from.suppressedVisualEffects, to.suppressedVisualEffects)); + } + if (from.areChannelsBypassingDnd != to.areChannelsBypassingDnd) { + addField("areChannelsBypassingDnd", + new FieldDiff<>(from.areChannelsBypassingDnd, to.areChannelsBypassingDnd)); + } + + // Compare automatic and manual rules + final ArraySet<String> allRules = new ArraySet<>(); + addKeys(allRules, from.automaticRules); + addKeys(allRules, to.automaticRules); + final int num = allRules.size(); + for (int i = 0; i < num; i++) { + final String rule = allRules.valueAt(i); + final ZenModeConfig.ZenRule + fromRule = from.automaticRules != null ? from.automaticRules.get(rule) + : null; + final ZenModeConfig.ZenRule + toRule = to.automaticRules != null ? to.automaticRules.get(rule) : null; + RuleDiff ruleDiff = new RuleDiff(fromRule, toRule); + if (ruleDiff.hasDiff()) { + mAutomaticRulesDiff.put(rule, ruleDiff); + } + } + // If there's no diff this may turn out to be null, but that's also fine + RuleDiff manualRuleDiff = new RuleDiff(from.manualRule, to.manualRule); + if (manualRuleDiff.hasDiff()) { + mManualRuleDiff = manualRuleDiff; + } + } + + private static <T> void addKeys(ArraySet<T> set, ArrayMap<T, ?> map) { + if (map != null) { + for (int i = 0; i < map.size(); i++) { + set.add(map.keyAt(i)); + } + } + } + + /** + * Returns whether this diff object contains any diffs in any field. + */ + @Override + public boolean hasDiff() { + return hasExistenceChange() + || hasFieldDiffs() + || mManualRuleDiff != null + || mAutomaticRulesDiff.size() > 0; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Diff["); + if (!hasDiff()) { + sb.append("no changes"); + } + + // If added or deleted, then that's just the end of it + if (hasExistenceChange()) { + if (wasAdded()) { + sb.append("added"); + } else if (wasRemoved()) { + sb.append("removed"); + } + } + + // Handle top-level field change + boolean first = true; + for (String key : fieldNamesWithDiff()) { + FieldDiff diff = getDiffForField(key); + if (diff == null) { + // this shouldn't happen, but + continue; + } + if (first) { + first = false; + } else { + sb.append(",\n"); + } + + // Some special handling for people- and conversation-type fields for readability + if (PEOPLE_TYPE_FIELDS.contains(key)) { + sb.append(key); + sb.append(":"); + sb.append(ZenModeConfig.sourceToString((int) diff.from())); + sb.append("->"); + sb.append(ZenModeConfig.sourceToString((int) diff.to())); + } else if (key.equals(ALLOW_CONVERSATIONS_FROM_FIELD)) { + sb.append(key); + sb.append(":"); + sb.append(ZenPolicy.conversationTypeToString((int) diff.from())); + sb.append("->"); + sb.append(ZenPolicy.conversationTypeToString((int) diff.to())); + } else { + sb.append(key); + sb.append(":"); + sb.append(diff); + } + } + + // manual rule + if (mManualRuleDiff != null && mManualRuleDiff.hasDiff()) { + if (first) { + first = false; + } else { + sb.append(",\n"); + } + sb.append("manualRule:"); + sb.append(mManualRuleDiff); + } + + // automatic rules + for (String rule : mAutomaticRulesDiff.keySet()) { + RuleDiff diff = mAutomaticRulesDiff.get(rule); + if (diff != null && diff.hasDiff()) { + if (first) { + first = false; + } else { + sb.append(",\n"); + } + sb.append("automaticRule["); + sb.append(rule); + sb.append("]:"); + sb.append(diff); + } + } + + return sb.append(']').toString(); + } + + /** + * Get the diff in manual rule, if it exists. + */ + public RuleDiff getManualRuleDiff() { + return mManualRuleDiff; + } + + /** + * Get the full map of automatic rule diffs, or null if there are no diffs. + */ + public ArrayMap<String, RuleDiff> getAllAutomaticRuleDiffs() { + return (mAutomaticRulesDiff.size() > 0) ? mAutomaticRulesDiff : null; + } + } + + /** + * Diff class representing a change between two ZenRules. + */ + public static class RuleDiff extends BaseDiff { + /** + * Create a RuleDiff representing the difference between two ZenRule objects. + * @param from previous ZenRule + * @param to new ZenRule + * @return The diff between the two given ZenRules + */ + public RuleDiff(ZenModeConfig.ZenRule from, ZenModeConfig.ZenRule to) { + super(from, to); + // Short-circuit the both-null case + if (from == null && to == null) { + return; + } + // Return if the diff was added or removed + if (hasExistenceChange()) { + return; + } + + if (from.enabled != to.enabled) { + addField("enabled", new FieldDiff<>(from.enabled, to.enabled)); + } + if (from.snoozing != to.snoozing) { + addField("snoozing", new FieldDiff<>(from.snoozing, to.snoozing)); + } + if (!Objects.equals(from.name, to.name)) { + addField("name", new FieldDiff<>(from.name, to.name)); + } + if (from.zenMode != to.zenMode) { + addField("zenMode", new FieldDiff<>(from.zenMode, to.zenMode)); + } + if (!Objects.equals(from.conditionId, to.conditionId)) { + addField("conditionId", new FieldDiff<>(from.conditionId, to.conditionId)); + } + if (!Objects.equals(from.condition, to.condition)) { + addField("condition", new FieldDiff<>(from.condition, to.condition)); + } + if (!Objects.equals(from.component, to.component)) { + addField("component", new FieldDiff<>(from.component, to.component)); + } + if (!Objects.equals(from.configurationActivity, to.configurationActivity)) { + addField("configurationActivity", new FieldDiff<>( + from.configurationActivity, to.configurationActivity)); + } + if (!Objects.equals(from.id, to.id)) { + addField("id", new FieldDiff<>(from.id, to.id)); + } + if (from.creationTime != to.creationTime) { + addField("creationTime", + new FieldDiff<>(from.creationTime, to.creationTime)); + } + if (!Objects.equals(from.enabler, to.enabler)) { + addField("enabler", new FieldDiff<>(from.enabler, to.enabler)); + } + if (!Objects.equals(from.zenPolicy, to.zenPolicy)) { + addField("zenPolicy", new FieldDiff<>(from.zenPolicy, to.zenPolicy)); + } + if (from.modified != to.modified) { + addField("modified", new FieldDiff<>(from.modified, to.modified)); + } + if (!Objects.equals(from.pkg, to.pkg)) { + addField("pkg", new FieldDiff<>(from.pkg, to.pkg)); + } + } + + /** + * Returns whether this object represents an actual diff. + */ + @Override + public boolean hasDiff() { + return hasExistenceChange() || hasFieldDiffs(); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ZenRuleDiff{"); + // If there's no diff, probably we haven't actually let this object continue existing + // but might as well handle this case. + if (!hasDiff()) { + sb.append("no changes"); + } + + // If added or deleted, then that's just the end of it + if (hasExistenceChange()) { + if (wasAdded()) { + sb.append("added"); + } else if (wasRemoved()) { + sb.append("removed"); + } + } + + // Go through all of the individual fields + boolean first = true; + for (String key : fieldNamesWithDiff()) { + FieldDiff diff = getDiffForField(key); + if (diff == null) { + // this shouldn't happen, but + continue; + } + if (first) { + first = false; + } else { + sb.append(", "); + } + + sb.append(key); + sb.append(":"); + sb.append(diff); + } + + return sb.append("}").toString(); + } + } +} diff --git a/services/core/java/com/android/server/notification/ZenLog.java b/services/core/java/com/android/server/notification/ZenLog.java index 35b94e7ccd63..88d23ce3f9a1 100644 --- a/services/core/java/com/android/server/notification/ZenLog.java +++ b/services/core/java/com/android/server/notification/ZenLog.java @@ -27,6 +27,7 @@ import android.service.notification.Condition; import android.service.notification.IConditionProvider; import android.service.notification.NotificationListenerService; import android.service.notification.ZenModeConfig; +import android.service.notification.ZenModeDiff; import android.util.Log; import android.util.Slog; @@ -146,13 +147,13 @@ public class ZenLog { public static void traceConfig(String reason, ZenModeConfig oldConfig, ZenModeConfig newConfig) { - ZenModeConfig.Diff diff = ZenModeConfig.diff(oldConfig, newConfig); - if (diff.isEmpty()) { + ZenModeDiff.ConfigDiff diff = new ZenModeDiff.ConfigDiff(oldConfig, newConfig); + if (diff == null || !diff.hasDiff()) { append(TYPE_CONFIG, reason + " no changes"); } else { append(TYPE_CONFIG, reason + ",\n" + (newConfig != null ? newConfig.toString() : null) - + ",\n" + ZenModeConfig.diff(oldConfig, newConfig)); + + ",\n" + diff); } } diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeDiffTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeDiffTest.java new file mode 100644 index 000000000000..bcd807ab6d2f --- /dev/null +++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeDiffTest.java @@ -0,0 +1,319 @@ +/* + * Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.notification; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; + +import android.content.ComponentName; +import android.net.Uri; +import android.provider.Settings; +import android.service.notification.Condition; +import android.service.notification.ZenModeConfig; +import android.service.notification.ZenModeDiff; +import android.service.notification.ZenPolicy; +import android.testing.AndroidTestingRunner; +import android.testing.TestableLooper; +import android.util.ArrayMap; + +import androidx.test.filters.SmallTest; + +import com.android.server.UiServiceTestCase; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +@SmallTest +@RunWith(AndroidTestingRunner.class) +@TestableLooper.RunWithLooper +public class ZenModeDiffTest extends UiServiceTestCase { + // version is not included in the diff; manual & automatic rules have special handling + public static final Set<String> ZEN_MODE_CONFIG_EXEMPT_FIELDS = + Set.of("version", "manualRule", "automaticRules"); + + @Test + public void testRuleDiff_addRemoveSame() { + // Test add, remove, and both sides same + ZenModeConfig.ZenRule r = makeRule(); + + // Both sides same rule + ZenModeDiff.RuleDiff dSame = new ZenModeDiff.RuleDiff(r, r); + assertFalse(dSame.hasDiff()); + + // from existent rule to null: expect deleted + ZenModeDiff.RuleDiff deleted = new ZenModeDiff.RuleDiff(r, null); + assertTrue(deleted.hasDiff()); + assertTrue(deleted.wasRemoved()); + + // from null to new rule: expect added + ZenModeDiff.RuleDiff added = new ZenModeDiff.RuleDiff(null, r); + assertTrue(added.hasDiff()); + assertTrue(added.wasAdded()); + } + + @Test + public void testRuleDiff_fieldDiffs() throws Exception { + // Start these the same + ZenModeConfig.ZenRule r1 = makeRule(); + ZenModeConfig.ZenRule r2 = makeRule(); + + // maps mapping field name -> expected output value as we set diffs + ArrayMap<String, Object> expectedFrom = new ArrayMap<>(); + ArrayMap<String, Object> expectedTo = new ArrayMap<>(); + List<Field> fieldsForDiff = getFieldsForDiffCheck( + ZenModeConfig.ZenRule.class, Set.of()); // actually no exempt fields for ZenRule + generateFieldDiffs(r1, r2, fieldsForDiff, expectedFrom, expectedTo); + + ZenModeDiff.RuleDiff d = new ZenModeDiff.RuleDiff(r1, r2); + assertTrue(d.hasDiff()); + + // Now diff them and check that each of the fields has a diff + for (Field f : fieldsForDiff) { + String name = f.getName(); + assertNotNull("diff not found for field: " + name, d.getDiffForField(name)); + assertTrue(d.getDiffForField(name).hasDiff()); + assertTrue("unexpected field: " + name, expectedFrom.containsKey(name)); + assertTrue("unexpected field: " + name, expectedTo.containsKey(name)); + assertEquals(expectedFrom.get(name), d.getDiffForField(name).from()); + assertEquals(expectedTo.get(name), d.getDiffForField(name).to()); + } + } + + @Test + public void testConfigDiff_addRemoveSame() { + // Default config, will test add, remove, and no change + ZenModeConfig c = new ZenModeConfig(); + + ZenModeDiff.ConfigDiff dSame = new ZenModeDiff.ConfigDiff(c, c); + assertFalse(dSame.hasDiff()); + + ZenModeDiff.ConfigDiff added = new ZenModeDiff.ConfigDiff(null, c); + assertTrue(added.hasDiff()); + assertTrue(added.wasAdded()); + + ZenModeDiff.ConfigDiff removed = new ZenModeDiff.ConfigDiff(c, null); + assertTrue(removed.hasDiff()); + assertTrue(removed.wasRemoved()); + } + + @Test + public void testConfigDiff_fieldDiffs() throws Exception { + // these two start the same + ZenModeConfig c1 = new ZenModeConfig(); + ZenModeConfig c2 = new ZenModeConfig(); + + // maps mapping field name -> expected output value as we set diffs + ArrayMap<String, Object> expectedFrom = new ArrayMap<>(); + ArrayMap<String, Object> expectedTo = new ArrayMap<>(); + List<Field> fieldsForDiff = getFieldsForDiffCheck( + ZenModeConfig.class, ZEN_MODE_CONFIG_EXEMPT_FIELDS); + generateFieldDiffs(c1, c2, fieldsForDiff, expectedFrom, expectedTo); + + ZenModeDiff.ConfigDiff d = new ZenModeDiff.ConfigDiff(c1, c2); + assertTrue(d.hasDiff()); + + // Now diff them and check that each of the fields has a diff + for (Field f : fieldsForDiff) { + String name = f.getName(); + assertNotNull("diff not found for field: " + name, d.getDiffForField(name)); + assertTrue(d.getDiffForField(name).hasDiff()); + assertTrue("unexpected field: " + name, expectedFrom.containsKey(name)); + assertTrue("unexpected field: " + name, expectedTo.containsKey(name)); + assertEquals(expectedFrom.get(name), d.getDiffForField(name).from()); + assertEquals(expectedTo.get(name), d.getDiffForField(name).to()); + } + } + + @Test + public void testConfigDiff_specialSenders() { + // these two start the same + ZenModeConfig c1 = new ZenModeConfig(); + ZenModeConfig c2 = new ZenModeConfig(); + + // set c1 and c2 to have some different senders + c1.allowMessagesFrom = ZenModeConfig.SOURCE_STAR; + c2.allowMessagesFrom = ZenModeConfig.SOURCE_CONTACT; + c1.allowConversationsFrom = ZenPolicy.CONVERSATION_SENDERS_IMPORTANT; + c2.allowConversationsFrom = ZenPolicy.CONVERSATION_SENDERS_NONE; + + ZenModeDiff.ConfigDiff d = new ZenModeDiff.ConfigDiff(c1, c2); + assertTrue(d.hasDiff()); + + // Diff in top-level fields + assertTrue(d.getDiffForField("allowMessagesFrom").hasDiff()); + assertTrue(d.getDiffForField("allowConversationsFrom").hasDiff()); + + // Bonus testing of stringification of people senders and conversation senders + assertTrue(d.toString().contains("allowMessagesFrom:stars->contacts")); + assertTrue(d.toString().contains("allowConversationsFrom:important->none")); + } + + @Test + public void testConfigDiff_hasRuleDiffs() { + // two default configs + ZenModeConfig c1 = new ZenModeConfig(); + ZenModeConfig c2 = new ZenModeConfig(); + + // two initially-identical rules + ZenModeConfig.ZenRule r1 = makeRule(); + ZenModeConfig.ZenRule r2 = makeRule(); + + // one that will become a manual rule + ZenModeConfig.ZenRule m = makeRule(); + + // Add r1 to c1, but not r2 to c2 yet -- expect a rule to be deleted + c1.automaticRules.put(r1.id, r1); + ZenModeDiff.ConfigDiff deleteRule = new ZenModeDiff.ConfigDiff(c1, c2); + assertTrue(deleteRule.hasDiff()); + assertNotNull(deleteRule.getAllAutomaticRuleDiffs()); + assertTrue(deleteRule.getAllAutomaticRuleDiffs().containsKey("ruleId")); + assertTrue(deleteRule.getAllAutomaticRuleDiffs().get("ruleId").wasRemoved()); + + // Change r2 a little, add r2 to c2 as an automatic rule and m as a manual rule + r2.component = null; + r2.pkg = "different"; + c2.manualRule = m; + c2.automaticRules.put(r2.id, r2); + + // Expect diffs in both manual rule (added) and automatic rule (changed) + ZenModeDiff.ConfigDiff changed = new ZenModeDiff.ConfigDiff(c1, c2); + assertTrue(changed.hasDiff()); + assertTrue(changed.getManualRuleDiff().hasDiff()); + + ArrayMap<String, ZenModeDiff.RuleDiff> automaticDiffs = changed.getAllAutomaticRuleDiffs(); + assertNotNull(automaticDiffs); + assertTrue(automaticDiffs.containsKey("ruleId")); + assertNotNull(automaticDiffs.get("ruleId").getDiffForField("component")); + assertNull(automaticDiffs.get("ruleId").getDiffForField("component").to()); + assertNotNull(automaticDiffs.get("ruleId").getDiffForField("pkg")); + assertEquals("different", automaticDiffs.get("ruleId").getDiffForField("pkg").to()); + } + + // Helper methods for working with configs, policies, rules + // Just makes a zen rule with fields filled in + private ZenModeConfig.ZenRule makeRule() { + ZenModeConfig.ZenRule rule = new ZenModeConfig.ZenRule(); + rule.configurationActivity = new ComponentName("a", "a"); + rule.component = new ComponentName("b", "b"); + rule.conditionId = new Uri.Builder().scheme("hello").build(); + rule.condition = new Condition(rule.conditionId, "", Condition.STATE_TRUE); + rule.enabled = true; + rule.creationTime = 123; + rule.id = "ruleId"; + rule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; + rule.modified = false; + rule.name = "name"; + rule.snoozing = true; + rule.pkg = "a"; + return rule; + } + + // Get the fields on which we would want to check a diff. The requirements are: not final or/ + // static (as these should/can never change), and not in a specific list that's exempted. + private List<Field> getFieldsForDiffCheck(Class c, Set<String> exemptNames) + throws SecurityException { + Field[] fields = c.getDeclaredFields(); + ArrayList<Field> out = new ArrayList<>(); + + for (Field field : fields) { + // Check for exempt reasons + int m = field.getModifiers(); + if (Modifier.isFinal(m) + || Modifier.isStatic(m) + || exemptNames.contains(field.getName())) { + continue; + } + out.add(field); + } + return out; + } + + // Generate a set of generic diffs for the specified two objects and the fields to generate + // diffs for, and store the results in the provided expectation maps to be able to check the + // output later. + private void generateFieldDiffs(Object a, Object b, List<Field> fields, + ArrayMap<String, Object> expectedA, ArrayMap<String, Object> expectedB) + throws Exception { + // different classes passed in means bad input + assertEquals(a.getClass(), b.getClass()); + + // Loop through fields for which we want to check diffs, set a diff and keep track of + // what we set. + for (Field f : fields) { + f.setAccessible(true); + // Just double-check also that the fields actually are for the class declared + assertEquals(f.getDeclaringClass(), a.getClass()); + Class t = f.getType(); + // handle the full set of primitive types first + if (boolean.class.equals(t)) { + f.setBoolean(a, true); + expectedA.put(f.getName(), true); + f.setBoolean(b, false); + expectedB.put(f.getName(), false); + } else if (int.class.equals(t)) { + // these are not actually valid going to be valid for arbitrary int enum fields, but + // we just put something in there regardless. + f.setInt(a, 2); + expectedA.put(f.getName(), 2); + f.setInt(b, 1); + expectedB.put(f.getName(), 1); + } else if (long.class.equals(t)) { + f.setLong(a, 200L); + expectedA.put(f.getName(), 200L); + f.setLong(b, 100L); + expectedB.put(f.getName(), 100L); + } else if (t.isPrimitive()) { + // This method doesn't yet handle other primitive types. If the relevant diff + // classes gain new fields of these types, please add another clause here. + fail("primitive type not handled by generateFieldDiffs: " + t.getName()); + } else if (String.class.equals(t)) { + f.set(a, "string1"); + expectedA.put(f.getName(), "string1"); + f.set(b, "string2"); + expectedB.put(f.getName(), "string2"); + } else { + // catch-all for other types: have the field be "added" + f.set(a, null); + expectedA.put(f.getName(), null); + try { + f.set(b, t.getDeclaredConstructor().newInstance()); + expectedB.put(f.getName(), t.getDeclaredConstructor().newInstance()); + } catch (Exception e) { + // No default constructor, or blithely attempting to construct something doesn't + // work for some reason. If the default value isn't null, then keep it. + if (f.get(b) != null) { + expectedB.put(f.getName(), f.get(b)); + } else { + // If we can't even rely on that, fail. Have the test-writer special case + // something, as this is not able to be genericized. + fail("could not generically construct value for field: " + f.getName()); + } + } + } + } + } +} 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 6f9798ea7d69..b2a54010e75e 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java @@ -69,8 +69,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.annotation.NonNull; -import android.annotation.Nullable; import android.app.AppGlobals; import android.app.AppOpsManager; import android.app.AutomaticZenRule; @@ -78,7 +76,6 @@ import android.app.NotificationManager; import android.app.NotificationManager.Policy; import android.content.ComponentName; import android.content.ContentResolver; -import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; @@ -90,7 +87,6 @@ import android.media.AudioManagerInternal; import android.media.AudioSystem; import android.media.VolumePolicy; import android.net.Uri; -import android.os.Binder; import android.os.Process; import android.os.UserHandle; import android.provider.Settings; @@ -98,6 +94,7 @@ import android.provider.Settings.Global; import android.service.notification.Condition; import android.service.notification.ZenModeConfig; import android.service.notification.ZenModeConfig.ScheduleInfo; +import android.service.notification.ZenModeDiff; import android.service.notification.ZenPolicy; import android.test.suitebuilder.annotation.SmallTest; import android.testing.AndroidTestingRunner; @@ -877,7 +874,8 @@ public class ZenModeHelperTest extends UiServiceTestCase { mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL); assertEquals("Config mismatch: current vs expected: " - + mZenModeHelperSpy.mConfig.diff(expected), expected, mZenModeHelperSpy.mConfig); + + new ZenModeDiff.ConfigDiff(mZenModeHelperSpy.mConfig, expected), expected, + mZenModeHelperSpy.mConfig); } @Test @@ -1046,7 +1044,8 @@ public class ZenModeHelperTest extends UiServiceTestCase { ZenModeConfig actual = mZenModeHelperSpy.mConfigs.get(10); assertEquals( - "Config mismatch: current vs expected: " + actual.diff(config10), config10, actual); + "Config mismatch: current vs expected: " + + new ZenModeDiff.ConfigDiff(actual, config10), config10, actual); assertNotEquals("Expected config mismatch", config11, mZenModeHelperSpy.mConfigs.get(11)); } @@ -1062,7 +1061,8 @@ public class ZenModeHelperTest extends UiServiceTestCase { mZenModeHelperSpy.readXml(parser, true, UserHandle.USER_SYSTEM); assertEquals("Config mismatch: current vs original: " - + mZenModeHelperSpy.mConfig.diff(original), original, mZenModeHelperSpy.mConfig); + + new ZenModeDiff.ConfigDiff(mZenModeHelperSpy.mConfig, original), + original, mZenModeHelperSpy.mConfig); assertEquals(original.hashCode(), mZenModeHelperSpy.mConfig.hashCode()); } @@ -1083,8 +1083,9 @@ public class ZenModeHelperTest extends UiServiceTestCase { ZenModeConfig actual = mZenModeHelperSpy.mConfigs.get(10); expected.user = 10; - assertEquals( - "Config mismatch: current vs original: " + actual.diff(expected), expected, actual); + assertEquals("Config mismatch: current vs original: " + + new ZenModeDiff.ConfigDiff(actual, expected), + expected, actual); assertEquals(expected.hashCode(), actual.hashCode()); expected.user = 0; assertNotEquals(expected, mZenModeHelperSpy.mConfig); |