From a708578e06acba4b95b1e91b684e3ac38b969315 Mon Sep 17 00:00:00 2001 From: ajp_anton Date: Fri, 16 Oct 2026 19:34:59 +0000 Subject: [PATCH] Remove notification features now owned by Notifications Master Retain statusbar notification containers and source validation while removing notification filtering, Cards rendering, debug notification generation, native icon-limit overrides, and migrated AOD/battery options. Leave external Cards notification views untouched and classify OneUI AOD sources by their view roles. Remove obsolete settings, UI, resources, and permissions. --- README.md | 14 +- app/src/main/AndroidManifest.xml | 18 - .../platform/SystemUiCapabilities.java | 4 - .../runtime/NotificationKeyReflection.java | 14 +- .../runtime/features/RuntimeContext.java | 2 +- .../features/StandaloneFeatureRegistry.java | 8 +- .../DebugNotificationAutoGroupController.java | 164 ---- .../DebugNotificationAutoGroupFeature.java | 25 - .../AodBottomBatteryFallbackController.java | 346 ------- .../misc/AodCallVisibilityController.java | 199 ---- .../misc/BatteryIndicationController.java | 123 --- .../features/misc/BatteryStatusAccess.java | 55 -- .../runtime/features/misc/MiscFeature.java | 51 - ...ckUnlockedNotificationIconsController.java | 278 ------ ...StockUnlockedNotificationIconsFeature.java | 34 - .../LockscreenCardsNotificationRowFilter.java | 378 -------- .../layout/StockLayoutCanvasController.java | 722 ++------------ .../NotificationUnreadTracker.java | 3 +- ...va => AodNotificationIconSourceStore.java} | 318 +----- .../render/DebugBoundsOverlayController.java | 6 +- ...kscreenCardsNotificationStripRenderer.java | 607 ------------ .../render/NotificationSeenAppReporter.java | 56 -- .../runtime/render/OwnedIconHostManager.java | 16 +- ...tIconFilter.java => StatusIconFilter.java} | 90 +- .../runtime/render/UnlockedLayoutPlanner.java | 21 +- .../render/UnlockedStockSourceCollector.java | 18 +- .../shell/debug/DebugBootReceiver.java | 16 - .../DebugNotificationDeleteReceiver.java | 28 - .../shell/debug/DebugNotifications.java | 419 -------- .../NotificationDisplayStyleSettings.java | 92 -- .../shell/settings/AppIconRules.java | 548 ----------- .../shell/settings/SbtDefaults.java | 50 - .../shell/settings/SbtSettings.java | 227 +---- .../shell/settings/SbtSettingsProvider.java | 103 -- .../ui/BlockAppNotificationIconsFragment.java | 156 --- .../shell/ui/HiddenAppsUiSupport.java | 910 ------------------ .../shell/ui/IconsDebugFragment.java | 98 -- .../shell/ui/LayoutFragment.java | 4 - .../shell/ui/LayoutHomeFragment.java | 33 +- .../shell/ui/LayoutSectionCopySupport.java | 167 +--- .../shell/ui/LockedNotificationModeUi.java | 151 +-- .../shell/ui/LockedSceneLayoutFragment.java | 87 +- .../statusbartweak/shell/ui/MainActivity.java | 8 - .../statusbartweak/shell/ui/MiscFragment.java | 46 - .../shell/ui/SystemIconsFragment.java | 6 +- .../res/layout/dialog_hidden_app_config.xml | 203 ---- .../fragment_block_app_notification_icons.xml | 85 -- .../main/res/layout/fragment_icons_debug.xml | 127 --- app/src/main/res/layout/fragment_misc.xml | 93 -- app/src/main/res/layout/item_hidden_app.xml | 124 --- .../layout/item_hidden_app_exception_rule.xml | 212 ---- app/src/main/res/menu/drawer_menu.xml | 8 - app/src/main/res/values/colors.xml | 1 - app/src/main/res/values/strings.xml | 51 +- .../render/SnapshotIconFilterTest.java | 90 -- .../runtime/render/StatusIconFilterTest.java | 35 + .../shell/settings/SbtSettingsTest.java | 7 - 57 files changed, 199 insertions(+), 7556 deletions(-) delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupController.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupFeature.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodBottomBatteryFallbackController.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodCallVisibilityController.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryIndicationController.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryStatusAccess.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/MiscFeature.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsController.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsFeature.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/LockscreenCardsNotificationRowFilter.java rename app/src/main/java/se/ajpanton/statusbartweak/runtime/render/{LockscreenCardsNotificationIconSourceStore.java => AodNotificationIconSourceStore.java} (55%) delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationStripRenderer.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/render/NotificationSeenAppReporter.java rename app/src/main/java/se/ajpanton/statusbartweak/runtime/render/{SnapshotIconFilter.java => StatusIconFilter.java} (64%) delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugBootReceiver.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotificationDeleteReceiver.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotifications.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/debug/NotificationDisplayStyleSettings.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/settings/AppIconRules.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BlockAppNotificationIconsFragment.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/ui/HiddenAppsUiSupport.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/shell/ui/MiscFragment.java delete mode 100644 app/src/main/res/layout/dialog_hidden_app_config.xml delete mode 100644 app/src/main/res/layout/fragment_block_app_notification_icons.xml delete mode 100644 app/src/main/res/layout/fragment_misc.xml delete mode 100644 app/src/main/res/layout/item_hidden_app.xml delete mode 100644 app/src/main/res/layout/item_hidden_app_exception_rule.xml delete mode 100644 app/src/test/java/se/ajpanton/statusbartweak/runtime/render/SnapshotIconFilterTest.java create mode 100644 app/src/test/java/se/ajpanton/statusbartweak/runtime/render/StatusIconFilterTest.java diff --git a/README.md b/README.md index c7d5c2b..88709fe 100644 --- a/README.md +++ b/README.md @@ -20,12 +20,10 @@ decisions, physical device testing, and final behaviour are still manually revie supported by the SystemUI build. - Independent placement of clock, carrier text, notification icons, status icons, and Samsung status chips. -- Separate notification display handling for Samsung's cards, icons, and dot - modes. +- Custom notification-icon containers in the unlocked statusbar and in + lockscreen/AOD icon modes. - Configurable icon sizes, vertical offsets, ordering, spacing, truncation, and cutout handling. -- Hide selected notification icons by app, separately for AOD, lockscreen, and - unlocked mode. - Hide selected status icons such as NFC, Bluetooth, hotspot, location, VPN, battery, and similar SystemUI indicators. - Optional custom clock text with multi-line formatting, colours, font families, @@ -33,8 +31,8 @@ decisions, physical device testing, and final behaviour are still manually revie - Battery bar with configurable position, alignment, thickness, colours, and threshold colours. - Controls for Samsung status chips such as media, navigation, and call chips. -- Debug tools for generating test notifications, visualizing layout containers, - and restarting SystemUI during development. +- Debug tools for visualizing layout containers and restarting SystemUI during + development. ## Custom Clock Text @@ -84,9 +82,7 @@ expose the required hardware or state for real verification. | Custom lockscreen statusbar layout | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Custom AOD statusbar layout | ✅ | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | | Notification icons mode | ✅ | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | -| Notification cards mode | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Notification dot mode and read-state behavior | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| Hide notification icons by app | ✅ | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | | Hide status icons | ✅ | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | ✅ AOD experimental | | Dual-SIM status icon handling | ✅ | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | | Samsung status chips: media/navigation/call | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | @@ -102,7 +98,7 @@ expose the required hardware or state for real verification. | Camera cutout and under-display-camera handling | ✅ | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | ⚠️ Experimental | | Rotation and fold/unfold handling | ✅ | ✅ rotation verified | ✅ rotation verified | ✅ rotation verified | ✅ rotation verified | ✅ rotation verified | ✅ rotation verified | ✅ rotation verified | | Drawer scrolling and background-work performance | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Debug visualizers and debug notifications | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Debug visualizers | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | Current emulator targets use rooted LSPosed snapshots. They are useful for compatibility work, but hardware-specific entries remain marked as experimental diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index dc5e2d1..7779ec0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,13 +2,6 @@ - - - - - - - - - - - - = 0) { normalized = normalized.substring(0, slash); } - return AppIconRules.isValidPackageName(normalized) ? normalized : null; + return isValidPackageName(normalized) ? normalized : null; } private static String packageFromPipeNotificationKey(String key) { @@ -105,7 +103,15 @@ public final class NotificationKeyReflection { return null; } String packageName = key.substring(firstPipe + 1, secondPipe); - return AppIconRules.isValidPackageName(packageName) ? packageName : null; + return isValidPackageName(packageName) ? packageName : null; + } + + public static boolean isValidPackageName(String packageName) { + if (packageName == null) { + return false; + } + String value = packageName.trim(); + return !value.isEmpty() && value.indexOf('.') > 0 && value.indexOf('|') < 0; } private static String nonEmptyStringFromMethod(Object target, String methodName) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeContext.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeContext.java index 899946f..830495a 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeContext.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeContext.java @@ -10,7 +10,7 @@ import se.ajpanton.statusbartweak.runtime.mode.ModeStateRepository; /** * Shared runtime services for independently rebuilt features. * - * Standalone slices such as Battery Bar, Misc, and Status Chips should depend + * Standalone slices such as Battery Bar and Status Chips should depend * on this narrow context instead of reaching back into one large controller. */ public final class RuntimeContext { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/StandaloneFeatureRegistry.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/StandaloneFeatureRegistry.java index 5a9f917..8178c8b 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/StandaloneFeatureRegistry.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/StandaloneFeatureRegistry.java @@ -6,9 +6,6 @@ import io.github.libxposed.api.XposedModuleInterface; import se.ajpanton.statusbartweak.runtime.features.battery.BatteryBarFeature; import se.ajpanton.statusbartweak.runtime.features.chips.StatusChipsFeature; import se.ajpanton.statusbartweak.runtime.features.clock.ClockFeature; -import se.ajpanton.statusbartweak.runtime.features.debug.DebugNotificationAutoGroupFeature; -import se.ajpanton.statusbartweak.runtime.features.misc.MiscFeature; -import se.ajpanton.statusbartweak.runtime.features.notifications.StockUnlockedNotificationIconsFeature; import se.ajpanton.statusbartweak.runtime.layout.StockLayoutCanvasFeature; import se.ajpanton.statusbartweak.runtime.mode.SystemUiStatusBarStateFeature; @@ -27,11 +24,8 @@ public final class StandaloneFeatureRegistry { new SystemUiStatusBarStateFeature(), new StockLayoutCanvasFeature(), new ClockFeature(), - new StockUnlockedNotificationIconsFeature(), new BatteryBarFeature(), - new MiscFeature(), - new StatusChipsFeature(), - new DebugNotificationAutoGroupFeature() + new StatusChipsFeature() ); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupController.java deleted file mode 100644 index 951781e..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupController.java +++ /dev/null @@ -1,164 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.debug; - -import android.app.Notification; -import android.os.Bundle; -import android.service.notification.StatusBarNotification; - -import java.lang.reflect.Method; - -import io.github.libxposed.api.XposedInterface; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -final class DebugNotificationAutoGroupController { - private static final String CLASS_GROUP_HELPER = - "com.android.server.notification.GroupHelper"; - private static final String CLASS_NOTIFICATION_RECORD = - "com.android.server.notification.NotificationRecord"; - private static final String CLASS_NOTIFICATION_MANAGER_SERVICE = - "com.android.server.notification.NotificationManagerService"; - private static final String EXTRA_DEBUG_NOTIFICATION = "sbt_debug_notification"; - - private final RuntimeContext runtimeContext; - private boolean hooksInstalled; - - DebugNotificationAutoGroupController(RuntimeContext runtimeContext) { - this.runtimeContext = runtimeContext; - } - - void install(ClassLoader classLoader) { - if (hooksInstalled) { - return; - } - Class groupHelper = ReflectionSupport.findClassIfExists(CLASS_GROUP_HELPER, classLoader); - Class recordClass = ReflectionSupport.findClassIfExists(CLASS_NOTIFICATION_RECORD, classLoader); - Class nmsClass = ReflectionSupport.findClassIfExists( - CLASS_NOTIFICATION_MANAGER_SERVICE, - classLoader); - if (groupHelper == null || recordClass == null || nmsClass == null) { - runtimeContext.logWarning("Debug notification autogroup hook target missing", null); - return; - } - - XposedInterface.Hooker blockDebugGrouping = chain -> { - if (chain.getArgs().isEmpty() || !isOurNotificationRecord(chain.getArg(0))) { - return chain.proceed(); - } - if (chain.getExecutable() instanceof Method method - && method.getReturnType() == Boolean.TYPE) { - return false; - } - return null; - }; - hookIfExists(groupHelper, "onNotificationPosted", blockDebugGrouping); - hookIfExists(groupHelper, "onNotificationRemoved", blockDebugGrouping); - hookIfExists(groupHelper, "maybeGroup", blockDebugGrouping); - hookIfExists(groupHelper, "maybeUngroup", blockDebugGrouping); - hookIfExists(groupHelper, "autoGroup", blockDebugGrouping); - hookIfExists(groupHelper, "autogroup", blockDebugGrouping); - hookIfExists(groupHelper, "maybeAutoGroup", blockDebugGrouping); - hookIfExists(groupHelper, "shouldAutoGroup", blockDebugGrouping); - hookIfExists(groupHelper, "isEligibleForAutoGroup", blockDebugGrouping); - - hookIfExists(recordClass, "setOverrideGroupKey", chain -> { - if (isOurNotificationRecord(chain.getThisObject())) { - return null; - } - return chain.proceed(); - }); - - XposedInterface.Hooker dropAutoSummary = chain -> { - NotificationInfo info = extractNotificationInfo(chain.getArgs().toArray()); - if (info != null - && SbtSettings.MODULE_PACKAGE.equals(info.packageName) - && !info.isDebugNotification) { - return null; - } - return chain.proceed(); - }; - hookIfExists(nmsClass, "enqueueNotificationInternal", dropAutoSummary); - hookIfExists(nmsClass, "enqueueNotificationInternalLocked", dropAutoSummary); - hooksInstalled = true; - } - - private void hookIfExists(Class type, String methodName, XposedInterface.Hooker hooker) { - for (Method method : type.getDeclaredMethods()) { - if (!methodName.equals(method.getName())) { - continue; - } - method.setAccessible(true); - runtimeContext.getFramework().hook(method).intercept(hooker); - } - } - - private NotificationInfo extractNotificationInfo(Object[] args) { - StatusBarNotification sbn = null; - Notification notification = null; - String packageName = null; - - for (Object arg : args) { - if (arg instanceof StatusBarNotification statusBarNotification) { - sbn = statusBarNotification; - packageName = sbn.getPackageName(); - notification = sbn.getNotification(); - break; - } - if (arg instanceof Notification candidateNotification && notification == null) { - notification = candidateNotification; - } - if (arg instanceof String candidatePackage && packageName == null) { - packageName = candidatePackage; - } - if (arg != null && arg.getClass().getName().contains("NotificationRecord")) { - Object sbnObj = ReflectionSupport.invokeMethod(arg, "getSbn"); - if (sbnObj instanceof StatusBarNotification statusBarNotification) { - sbn = statusBarNotification; - packageName = sbn.getPackageName(); - notification = sbn.getNotification(); - break; - } - Object packageObj = ReflectionSupport.invokeMethod(arg, "getPackageName"); - if (packageObj instanceof String stringPackage) { - packageName = stringPackage; - } - Object notificationObj = ReflectionSupport.invokeMethod(arg, "getNotification"); - if (notificationObj instanceof Notification candidateNotification) { - notification = candidateNotification; - } - } - } - - if (notification == null && sbn != null) { - notification = sbn.getNotification(); - } - if (packageName == null || notification == null) { - return null; - } - Bundle extras = notification.extras; - boolean isDebug = extras != null && extras.getBoolean(EXTRA_DEBUG_NOTIFICATION, false); - return new NotificationInfo(packageName, isDebug); - } - - private boolean isOurNotificationRecord(Object record) { - if (record == null) { - return false; - } - Object sbnObj = ReflectionSupport.invokeMethod(record, "getSbn"); - if (sbnObj instanceof StatusBarNotification sbn) { - return SbtSettings.MODULE_PACKAGE.equals(sbn.getPackageName()); - } - if (sbnObj != null) { - Object packageObj = ReflectionSupport.invokeMethod(sbnObj, "getPackageName"); - if (packageObj instanceof String packageName) { - return SbtSettings.MODULE_PACKAGE.equals(packageName); - } - } - Object packageObj = ReflectionSupport.invokeMethod(record, "getPackageName"); - return packageObj instanceof String packageName - && SbtSettings.MODULE_PACKAGE.equals(packageName); - } - - private record NotificationInfo(String packageName, boolean isDebugNotification) { - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupFeature.java deleted file mode 100644 index 3f89982..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/debug/DebugNotificationAutoGroupFeature.java +++ /dev/null @@ -1,25 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.debug; - -import io.github.libxposed.api.XposedModuleInterface; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; - -public final class DebugNotificationAutoGroupFeature implements RuntimeFeature { - private DebugNotificationAutoGroupController controller; - - @Override - public String getName() { - return "debug-notification-autogroup"; - } - - @Override - public void onSystemServerStarting( - RuntimeContext context, - XposedModuleInterface.SystemServerStartingParam param - ) { - if (controller == null) { - controller = new DebugNotificationAutoGroupController(context); - } - controller.install(param.getClassLoader()); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodBottomBatteryFallbackController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodBottomBatteryFallbackController.java deleted file mode 100644 index 966e306..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodBottomBatteryFallbackController.java +++ /dev/null @@ -1,346 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.misc; - -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; -import android.widget.TextView; - -import java.text.NumberFormat; -import java.util.HashSet; -import java.util.Set; - -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; -import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; - -final class AodBottomBatteryFallbackController { - - private static final int OVERRIDE_TAG_KEY = 0x7f0b0a01; - private static final int VISIBILITY_TAG_KEY = 0x7f0b0a02; - private static final long[] INDICATION_RETRY_DELAYS_MS = new long[] {96L, 224L, 480L}; - - private final RuntimeContext runtimeContext; - private Object currentManager; - private FrameLayout currentHost; - private final Set pendingRetries = new HashSet<>(); - - AodBottomBatteryFallbackController(RuntimeContext runtimeContext) { - this.runtimeContext = runtimeContext; - } - - void install(ClassLoader classLoader) { - hookSetBottomArea(classLoader); - hookDozing(classLoader); - hookBatteryRefresh(classLoader); - } - - private void hookSetBottomArea(ClassLoader classLoader) { - Class callbackClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.doze.PluginAODManager$6", - classLoader - ); - if (callbackClass == null) { - return; - } - XposedHookSupport.hookAllMethods(runtimeContext.getFramework(), callbackClass, "setBottomArea", chain -> { - Object result = chain.proceed(); - View addedView = chain.getArgs().isEmpty() && !(result instanceof View) - ? null - : (chain.getArgs().isEmpty() ? null : (chain.getArg(0) instanceof View view ? view : null)); - currentManager = resolveManager(chain.getThisObject()); - currentHost = resolveBottomDozeAreaFromManager(currentManager); - updateFallback(currentHost, addedView); - return result; - }); - } - - private void hookDozing(ClassLoader classLoader) { - Class managerClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.doze.PluginAODManager", - classLoader - ); - if (managerClass == null) { - return; - } - XposedHookSupport.hookAllMethods(runtimeContext.getFramework(), managerClass, "setIsDozing", chain -> { - Object result = chain.proceed(); - currentManager = chain.getThisObject(); - currentHost = resolveBottomDozeAreaFromManager(currentManager); - boolean dozing = chain.getArgs().size() > 0 - && chain.getArg(0) instanceof Boolean bool - && bool; - View target = currentHost != null && currentHost.getChildCount() > 0 - ? currentHost.getChildAt(0) - : null; - if (!dozing) { - clearAll(currentHost, target); - return result; - } - updateFallback(currentHost, target); - return result; - }); - } - - private void hookBatteryRefresh(ClassLoader classLoader) { - Class callbackClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.statusbar.KeyguardSecIndicationController$SecKeyguardCallback", - classLoader - ); - if (callbackClass == null) { - return; - } - XposedHookSupport.hookAllMethods(runtimeContext.getFramework(), callbackClass, "onRefreshBatteryInfo", chain -> { - Object result = chain.proceed(); - if (currentManager == null || currentHost == null) { - return result; - } - View target = currentHost.getChildCount() > 0 ? currentHost.getChildAt(0) : null; - updateFallback(currentHost, target); - return result; - }); - } - - private void updateFallback(FrameLayout host, View addedView) { - if (host == null) { - return; - } - BatteryStatusAccess.BatteryState batteryState = resolveVisibleBatteryState(host); - if (batteryState == null) { - clearAll(host, addedView); - return; - } - CharSequence text = buildBatteryPercentageText(batteryState); - if (text == null || text.length() == 0) { - clearAll(host, addedView); - return; - } - if (canApplyIndicationOnlyFallback(host, addedView)) { - clearIndicationOnlyFallback(addedView, host); - cancelRetries(host); - applyIndicationOnlyFallback(host, addedView, text.toString()); - scheduleIndicationOnlyRetries(host, addedView, text.toString()); - return; - } - clearAll(host, addedView); - } - - private void clearAll(FrameLayout host, View addedView) { - cancelRetries(host); - clearIndicationOnlyFallback(addedView, host); - } - - private BatteryStatusAccess.BatteryState resolveVisibleBatteryState(View host) { - if (host == null) { - return null; - } - if (!RuntimeSettingsCache.get(host.getContext()).batteryAodUnpluggedPercent) { - return null; - } - BatteryStatusAccess.BatteryState state = - BatteryStatusAccess.getCurrentBatteryState(host.getContext()); - if (state == null || state.plugged() || state.charged()) { - return null; - } - return state; - } - - private CharSequence buildBatteryPercentageText(BatteryStatusAccess.BatteryState state) { - if (state == null || state.level() < 0) { - return null; - } - return NumberFormat.getPercentInstance().format(state.level() / 100.0d); - } - - private boolean canApplyIndicationOnlyFallback(FrameLayout host, View addedView) { - Object component = getChargingComponent(resolvePluginRoot(addedView, host)); - return resolveNativeTextView(component, "d") != null; - } - - private boolean applyIndicationOnlyFallback(FrameLayout host, View addedView, String text) { - Object component = getChargingComponent(resolvePluginRoot(addedView, host)); - if (component == null) { - return false; - } - TextView indicationText = resolveNativeTextView(component, "d"); - if (indicationText == null) { - return false; - } - TextView remainingText = resolveNativeTextView(component, "k"); - View batteryContainer = resolveNativeBatteryContainer(component); - View hostView = resolveNativeHostView(component); - View infoHolder = getObjectFieldAs(hostView, "b", View.class); - View usbContainer = getObjectFieldAs(hostView, "l", View.class); - - rememberAndApplyText(indicationText, text); - rememberAndApplyVisibility(indicationText, View.VISIBLE); - rememberAndApplyVisibility(remainingText, View.GONE); - rememberAndApplyVisibility(batteryContainer, View.GONE); - rememberAndApplyVisibility(usbContainer, View.GONE); - - forceViewChainVisible(indicationText); - forceViewChainVisible(infoHolder); - forceViewChainVisible(hostView); - return true; - } - - private void clearIndicationOnlyFallback(View addedView, FrameLayout host) { - Object component = getChargingComponent(resolvePluginRoot(addedView, host)); - if (component == null) { - return; - } - restoreRememberedText(resolveNativeTextView(component, "d")); - restoreRememberedVisibility(resolveNativeTextView(component, "k")); - restoreRememberedVisibility(resolveNativeBatteryContainer(component)); - restoreRememberedVisibility(getObjectFieldAs(resolveNativeHostView(component), "l", View.class)); - } - - private void scheduleIndicationOnlyRetries(FrameLayout host, View addedView, String text) { - for (long delayMs : INDICATION_RETRY_DELAYS_MS) { - Runnable retry = new Runnable() { - @Override - public void run() { - pendingRetries.remove(this); - if (currentManager == null || currentHost != host) { - return; - } - if (resolveVisibleBatteryState(host) == null) { - clearAll(host, addedView); - return; - } - applyIndicationOnlyFallback(host, addedView, text); - } - }; - pendingRetries.add(retry); - host.postDelayed(retry, delayMs); - } - } - - private void cancelRetries(FrameLayout host) { - if (host == null) { - pendingRetries.clear(); - return; - } - for (Runnable pending : pendingRetries) { - host.removeCallbacks(pending); - } - pendingRetries.clear(); - } - - private View resolvePluginRoot(View source, FrameLayout host) { - if (source instanceof ViewGroup) { - return source; - } - if (host != null && host.getChildCount() > 0) { - return host.getChildAt(0); - } - return null; - } - - private Object getChargingComponent(Object root) { - return BatteryStatusAccess.getObjectField(root, "p"); - } - - private TextView resolveNativeTextView(Object component, String fieldName) { - View hostView = resolveNativeHostView(component); - return getObjectFieldAs(hostView, fieldName, TextView.class); - } - - private ViewGroup resolveNativeBatteryContainer(Object component) { - View hostView = resolveNativeHostView(component); - return getObjectFieldAs(hostView, "c", ViewGroup.class); - } - - private View resolveNativeHostView(Object component) { - return getObjectFieldAs(component, "c", View.class); - } - - private void rememberAndApplyText(TextView view, String text) { - if (view == null) { - return; - } - if (!(view.getTag(OVERRIDE_TAG_KEY) instanceof Object[])) { - view.setTag(OVERRIDE_TAG_KEY, new Object[] {view.getText(), view.getVisibility()}); - } - view.setText(text); - view.setVisibility(View.VISIBLE); - } - - private void restoreRememberedText(TextView view) { - if (view == null) { - return; - } - Object tag = view.getTag(OVERRIDE_TAG_KEY); - if (!(tag instanceof Object[] saved)) { - return; - } - view.setText(saved.length > 0 && saved[0] instanceof CharSequence sequence ? sequence : ""); - view.setVisibility(saved.length > 1 && saved[1] instanceof Integer integer ? integer : View.VISIBLE); - view.setTag(OVERRIDE_TAG_KEY, null); - } - - private void rememberAndApplyVisibility(View view, int visibility) { - if (view == null) { - return; - } - if (!(view.getTag(VISIBILITY_TAG_KEY) instanceof Integer)) { - view.setTag(VISIBILITY_TAG_KEY, view.getVisibility()); - } - view.setVisibility(visibility); - } - - private void restoreRememberedVisibility(View view) { - if (view == null) { - return; - } - Object tag = view.getTag(VISIBILITY_TAG_KEY); - if (!(tag instanceof Integer integer)) { - return; - } - view.setVisibility(integer); - view.setTag(VISIBILITY_TAG_KEY, null); - } - - private void forceViewChainVisible(View view) { - View current = view; - while (current != null) { - current.setVisibility(View.VISIBLE); - current.setAlpha(1f); - current.setTranslationX(0f); - current.setTranslationY(0f); - current.setScaleX(1f); - current.setScaleY(1f); - current.requestLayout(); - current.invalidate(); - Object parent = current.getParent(); - current = parent instanceof View next ? next : null; - } - } - - private Object resolveManager(Object callback) { - return BatteryStatusAccess.getObjectField(callback, "this$0"); - } - - private FrameLayout resolveBottomDozeAreaFromManager(Object manager) { - if (manager == null) { - return null; - } - try { - Object panelLazy = ReflectionSupport.getFieldValue(manager, "mPanelViewControllerLazy"); - Object panel = ReflectionSupport.invokeMethod(panelLazy, "get"); - Object bottomController = ReflectionSupport.getFieldValue(panel, "mKeyguardSecBottomAreaViewController"); - Object bottomView = ReflectionSupport.invokeMethod(bottomController, "getView"); - Object delegate = ReflectionSupport.getFieldValue(bottomView, "bottomDozeArea$delegate"); - Object host = ReflectionSupport.invokeMethod(delegate, "getValue"); - return host instanceof FrameLayout frameLayout ? frameLayout : null; - } catch (Throwable ignored) { - return null; - } - } - - private T getObjectFieldAs(Object target, String fieldName, Class cls) { - Object value = BatteryStatusAccess.getObjectField(target, fieldName); - return cls.isInstance(value) ? cls.cast(value) : null; - } - -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodCallVisibilityController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodCallVisibilityController.java deleted file mode 100644 index d6b4324..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/AodCallVisibilityController.java +++ /dev/null @@ -1,199 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.misc; - -import android.Manifest; -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.pm.PackageManager; -import android.media.AudioManager; -import android.telecom.TelecomManager; -import android.telephony.TelephonyManager; - -import io.github.libxposed.api.XposedInterface; -import se.ajpanton.statusbartweak.runtime.SystemContextProvider; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; -import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; - -final class AodCallVisibilityController { - - private static final int PLUGIN_KEY_PHONE_STATE = 0x2; - - private final RuntimeContext runtimeContext; - - AodCallVisibilityController(RuntimeContext runtimeContext) { - this.runtimeContext = runtimeContext; - } - - void install(ClassLoader classLoader) { - hookSuppressAmbientDisplay(classLoader); - hookFrontScrim(classLoader); - hookAlwaysOnSuppressedChanged(classLoader); - hookDozeMachineStateOverrides(classLoader); - hookPluginPhoneStateReadOverride(classLoader); - } - - private void hookSuppressAmbientDisplay(ClassLoader classLoader) { - hookBooleanVoidMethod( - classLoader, - "com.android.systemui.statusbar.phone.CentralSurfacesCommandQueueCallbacks", - "suppressAmbientDisplay" - ); - hookBooleanVoidMethod( - classLoader, - "com.android.systemui.statusbar.CommandQueue", - "suppressAmbientDisplay" - ); - } - - private void hookFrontScrim(ClassLoader classLoader) { - hookBooleanVoidMethod( - classLoader, - "com.android.systemui.statusbar.phone.SecLsScrimControlHelper", - "setFrontScrimToBlack" - ); - } - - private void hookAlwaysOnSuppressedChanged(ClassLoader classLoader) { - hookBooleanVoidMethod( - classLoader, - "com.android.systemui.doze.DozeSuppressor$1", - "onAlwaysOnSuppressedChanged" - ); - hookBooleanVoidMethod( - classLoader, - "com.android.systemui.doze.AODUi$1", - "onAlwaysOnSuppressedChanged" - ); - } - - private void hookDozeMachineStateOverrides(ClassLoader classLoader) { - Class dozeMachineClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.doze.DozeMachine", - classLoader - ); - if (dozeMachineClass == null) { - return; - } - XposedInterface framework = runtimeContext.getFramework(); - for (String methodName : new String[]{"requestState", "transitionTo"}) { - XposedHookSupport.hookAllMethods(framework, dozeMachineClass, methodName, chain -> { - Object state = chain.getArgs().isEmpty() ? null : chain.getArg(0); - if (!(state instanceof Enum target) || !shouldForceAodForCall()) { - return chain.proceed(); - } - Enum replacement = overrideDozeState(target); - if (replacement == null) { - return chain.proceed(); - } - Object[] args = chain.getArgs().toArray(); - args[0] = replacement; - return chain.proceed(args); - }); - } - } - - private void hookPluginPhoneStateReadOverride(ClassLoader classLoader) { - Class configClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.plugins.aod.PluginAODSystemUIConfiguration", - classLoader - ); - if (configClass == null) { - return; - } - XposedHookSupport.hookAllMethods(runtimeContext.getFramework(), configClass, "get", chain -> { - Object result = chain.proceed(); - if (!shouldForceAodForCall() || chain.getArgs().size() < 2) { - return result; - } - Object keyObj = chain.getArg(0); - if (!(keyObj instanceof Integer key) || key != PLUGIN_KEY_PHONE_STATE) { - return result; - } - int phoneState = result instanceof Integer integer - ? integer - : (chain.getArg(1) instanceof Integer fallback ? fallback : TelephonyManager.CALL_STATE_IDLE); - if (phoneState == TelephonyManager.CALL_STATE_IDLE) { - return result; - } - return TelephonyManager.CALL_STATE_IDLE; - }); - } - - private void hookBooleanVoidMethod(ClassLoader classLoader, String className, String methodName) { - Class targetClass = ReflectionSupport.findClassIfExists(className, classLoader); - if (targetClass == null) { - return; - } - XposedHookSupport.hookAllMethods(runtimeContext.getFramework(), targetClass, methodName, chain -> { - if (chain.getArgs().isEmpty() || !(chain.getArg(0) instanceof Boolean booleanArg)) { - return chain.proceed(); - } - if (!booleanArg || !shouldForceAodForCall()) { - return chain.proceed(); - } - Object[] args = chain.getArgs().toArray(); - args[0] = false; - return chain.proceed(args); - }); - } - - private Enum overrideDozeState(Enum requested) { - String stateName = requested.name(); - if (!"DOZE".equals(stateName) && !"FINISH".equals(stateName)) { - return null; - } - try { - @SuppressWarnings({"rawtypes", "unchecked"}) - Enum dozeAod = Enum.valueOf((Class) requested.getDeclaringClass(), "DOZE_AOD"); - return dozeAod; - } catch (Throwable ignored) { - return null; - } - } - - private boolean shouldForceAodForCall() { - Context context = SystemContextProvider.currentApplication(); - if (context == null) { - return false; - } - if (!RuntimeSettingsCache.get(context).keepAodVisibleDuringCall) { - return false; - } - return isInCallLikeState(context); - } - - @SuppressLint("MissingPermission") - @SuppressWarnings("deprecation") - private boolean isInCallLikeState(Context context) { - if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) - == PackageManager.PERMISSION_GRANTED) { - try { - TelecomManager telecomManager = context.getSystemService(TelecomManager.class); - if (telecomManager != null && telecomManager.isInCall()) { - return true; - } - } catch (Throwable ignored) { - } - try { - TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class); - if (telephonyManager != null - && telephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { - return true; - } - } catch (Throwable ignored) { - } - } - try { - AudioManager audioManager = context.getSystemService(AudioManager.class); - if (audioManager == null) { - return false; - } - int mode = audioManager.getMode(); - return mode == AudioManager.MODE_IN_CALL || mode == AudioManager.MODE_IN_COMMUNICATION; - } catch (Throwable ignored) { - return false; - } - } - -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryIndicationController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryIndicationController.java deleted file mode 100644 index d2b7e7b..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryIndicationController.java +++ /dev/null @@ -1,123 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.misc; - -import android.content.Context; -import android.content.res.ColorStateList; - -import java.text.NumberFormat; - -import io.github.libxposed.api.XposedInterface; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; -import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; - -final class BatteryIndicationController { - - private final RuntimeContext runtimeContext; - private Object batteryEvent; - private Object batteryRestingEvent; - - BatteryIndicationController(RuntimeContext runtimeContext) { - this.runtimeContext = runtimeContext; - } - - void install(ClassLoader classLoader) { - initEventTypes(classLoader); - hookAddInitialIndication(classLoader); - } - - private void initEventTypes(ClassLoader classLoader) { - Class eventTypeClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.statusbar.IndicationEventType", - classLoader - ); - if (eventTypeClass == null) { - return; - } - batteryEvent = ReflectionSupport.getStaticFieldValue(eventTypeClass, "BATTERY"); - batteryRestingEvent = ReflectionSupport.getStaticFieldValue(eventTypeClass, "BATTERY_RESTING"); - } - - private void hookAddInitialIndication(ClassLoader classLoader) { - Class controllerClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.statusbar.KeyguardSecIndicationController", - classLoader - ); - if (controllerClass == null) { - return; - } - XposedHookSupport.hookAllMethods( - runtimeContext.getFramework(), - controllerClass, - "addInitialIndication", - chain -> { - Object result = chain.proceed(); - Object controller = chain.getThisObject(); - BatteryStatusAccess.BatteryState batteryState = resolveVisibleBatteryState(controller); - CharSequence text = buildBatteryPercentageText(batteryState); - if (text == null || text.length() == 0) { - return result; - } - ColorStateList color = null; - Object colorField = ReflectionSupport.getFieldValue(controller, "mInitialTextColorState"); - if (colorField instanceof ColorStateList colorStateList) { - color = colorStateList; - } - ReflectionSupport.invokeMethod( - controller, - "addIndicationTimeout", - new Class[] { - batteryEvent != null ? batteryEvent.getClass() : Object.class, - CharSequence.class, - ColorStateList.class, - boolean.class - }, - batteryEvent, - text, - color, - false - ); - ReflectionSupport.invokeMethod( - controller, - "addIndication", - new Class[] { - batteryRestingEvent != null ? batteryRestingEvent.getClass() : Object.class, - CharSequence.class - }, - batteryRestingEvent, - text - ); - return result; - } - ); - } - - private BatteryStatusAccess.BatteryState resolveVisibleBatteryState(Object controller) { - if (controller == null) { - return null; - } - Context context = BatteryStatusAccess.getContextField(controller, "mContext"); - if (context == null) { - return null; - } - if (!RuntimeSettingsCache.get(context).batteryLockscreenUnpluggedPercent) { - return null; - } - if (BatteryStatusAccess.getBooleanField(controller, "mDozing", false)) { - return null; - } - BatteryStatusAccess.BatteryState state = BatteryStatusAccess.getCurrentBatteryState(context); - if (state == null || state.plugged() || state.charged()) { - return null; - } - return state; - } - - private CharSequence buildBatteryPercentageText(BatteryStatusAccess.BatteryState state) { - if (state == null || state.level() < 0) { - return null; - } - NumberFormat format = NumberFormat.getPercentInstance(); - return format.format(state.level() / 100.0d); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryStatusAccess.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryStatusAccess.java deleted file mode 100644 index 8727217..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/BatteryStatusAccess.java +++ /dev/null @@ -1,55 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.misc; - -import android.content.Context; -import android.content.Intent; -import android.os.BatteryManager; - -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport; - -final class BatteryStatusAccess { - - private BatteryStatusAccess() { - } - - static BatteryState getCurrentBatteryState(Context context) { - if (context == null) { - return null; - } - Intent batteryIntent = BroadcastReceiverSupport.readExportedSticky( - context, - BroadcastReceiverSupport.filter(Intent.ACTION_BATTERY_CHANGED)); - if (batteryIntent == null) { - return null; - } - int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); - int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); - if (level < 0 || scale <= 0) { - return null; - } - int percent = Math.round((level * 100f) / scale); - int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); - boolean plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 - || status == BatteryManager.BATTERY_STATUS_CHARGING - || status == BatteryManager.BATTERY_STATUS_FULL; - boolean charged = status == BatteryManager.BATTERY_STATUS_FULL || percent >= 100; - return new BatteryState(percent, plugged, charged); - } - - static Context getContextField(Object target, String fieldName) { - Object value = ReflectionSupport.getFieldValue(target, fieldName); - return value instanceof Context context ? context : null; - } - - static boolean getBooleanField(Object target, String fieldName, boolean fallback) { - Object value = ReflectionSupport.getFieldValue(target, fieldName); - return value instanceof Boolean bool ? bool : fallback; - } - - static Object getObjectField(Object target, String fieldName) { - return ReflectionSupport.getFieldValue(target, fieldName); - } - - record BatteryState(int level, boolean plugged, boolean charged) { - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/MiscFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/MiscFeature.java deleted file mode 100644 index 29cab45..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/misc/MiscFeature.java +++ /dev/null @@ -1,51 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.misc; - -import io.github.libxposed.api.XposedModuleInterface; -import se.ajpanton.statusbartweak.platform.SystemUiCapabilities; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; - -/** - * Reserved home for Misc runtime behaviours that stay outside the icon - * placement engine. - */ -public final class MiscFeature implements RuntimeFeature { - - private AodCallVisibilityController aodCallVisibilityController; - private BatteryIndicationController batteryIndicationController; - private AodBottomBatteryFallbackController aodBottomBatteryFallbackController; - - @Override - public String getName() { - return "misc"; - } - - @Override - public void onPackageReady( - RuntimeContext context, - XposedModuleInterface.PackageReadyParam param - ) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } - installControllers(context, param.getClassLoader()); - } - - private void installControllers(RuntimeContext context, ClassLoader classLoader) { - if (!SystemUiCapabilities.supportsSamsungAodMiscControllers()) { - return; - } - if (aodCallVisibilityController == null) { - aodCallVisibilityController = new AodCallVisibilityController(context); - } - if (batteryIndicationController == null) { - batteryIndicationController = new BatteryIndicationController(context); - } - if (aodBottomBatteryFallbackController == null) { - aodBottomBatteryFallbackController = new AodBottomBatteryFallbackController(context); - } - aodCallVisibilityController.install(classLoader); - batteryIndicationController.install(classLoader); - aodBottomBatteryFallbackController.install(classLoader); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsController.java deleted file mode 100644 index a661625..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsController.java +++ /dev/null @@ -1,278 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.notifications; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewParent; - -import java.util.Collections; -import java.util.Set; -import java.util.WeakHashMap; - -import se.ajpanton.statusbartweak.runtime.ViewIdNames; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; -import se.ajpanton.statusbartweak.runtime.mode.SceneKey; -import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport; -import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; -import se.ajpanton.statusbartweak.shell.settings.SbtDefaults; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -final class StockUnlockedNotificationIconsController { - - private static final String CONTAINER_CLASS_NAME = - "com.android.systemui.statusbar.phone.NotificationIconContainer"; - private static final int INFINITE_ICON_LIMIT = 1000; - - private final RuntimeContext runtimeContext; - private final Set trackedContainers = - Collections.newSetFromMap(new WeakHashMap<>()); - private final WeakHashMap stockMaxStaticIcons = new WeakHashMap<>(); - - private boolean hooksInstalled; - private boolean receiverRegistered; - - StockUnlockedNotificationIconsController(RuntimeContext runtimeContext) { - this.runtimeContext = runtimeContext; - } - - void install(ClassLoader classLoader) { - if (hooksInstalled || classLoader == null) { - return; - } - Class containerClass = ReflectionSupport.findClassIfExists(CONTAINER_CLASS_NAME, classLoader); - if (containerClass == null) { - return; - } - XposedHookSupport.hookAllMethodsIfExists(runtimeContext.getFramework(), containerClass, "onAttachedToWindow", chain -> { - Object result = chain.proceed(); - if (chain.getThisObject() instanceof View view) { - if (shouldManageContainer(view)) { - trackContainer(view); - view.post(() -> refreshContainer(view)); - } - } - return result; - }); - XposedHookSupport.hookAllMethodsIfExists(runtimeContext.getFramework(), containerClass, "calculateIconXTranslations", chain -> { - if (chain.getThisObject() instanceof View view) { - if (shouldManageContainer(view)) { - trackContainer(view); - applyLimitIfNeeded(view); - } - } - return chain.proceed(); - }); - XposedHookSupport.hookAllMethodsIfExists(runtimeContext.getFramework(), containerClass, "onLayout", chain -> { - Object result = chain.proceed(); - if (chain.getThisObject() instanceof View view) { - if (shouldManageContainer(view)) { - trackContainer(view); - if (isFeatureEnabled(view.getContext())) { - enforceParentWidth(view); - } - } - } - return result; - }); - XposedHookSupport.hookAllMethodsIfExists(runtimeContext.getFramework(), containerClass, "shouldForceOverflow", chain -> { - if (!(chain.getThisObject() instanceof View view)) { - return chain.proceed(); - } - if (!shouldManageContainer(view)) { - return chain.proceed(); - } - trackContainer(view); - if (chain.getArgs().size() < 4 || !isFeatureEnabled(view.getContext())) { - return chain.proceed(); - } - int override = resolveUnlockedLimit(view.getContext()); - if (override <= 0) { - return chain.proceed(); - } - applyOverrideToContainer(view, override); - int index = chain.getArg(0) instanceof Integer value ? value : -1; - int speedBumpIndex = chain.getArg(1) instanceof Integer value ? value : -1; - float appear = chain.getArg(2) instanceof Float value ? value : 0f; - return (speedBumpIndex != -1 && index >= speedBumpIndex && appear > 0f) - || index >= override; - }); - hooksInstalled = true; - } - - private void trackContainer(View view) { - trackedContainers.add(view); - captureStockMaxStaticIcons(view); - registerReceiverIfNeeded(view.getContext()); - } - - private void captureStockMaxStaticIcons(View view) { - if (stockMaxStaticIcons.containsKey(view)) { - return; - } - Object value = ReflectionSupport.getFieldValue(view, "mMaxStaticIcons"); - if (value instanceof Integer integer) { - stockMaxStaticIcons.put(view, integer); - } - } - - private void registerReceiverIfNeeded(Context context) { - if (receiverRegistered || context == null) { - return; - } - BroadcastReceiver receiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - refreshTrackedContainers(); - } - }; - BroadcastReceiverSupport.registerExportedOnApplicationContext( - context, - receiver, - BroadcastReceiverSupport.filter( - SbtSettings.ACTION_SETTINGS_CHANGED, - Intent.ACTION_USER_UNLOCKED)); - receiverRegistered = true; - } - - private void refreshTrackedContainers() { - for (View view : trackedContainers) { - if (shouldManageContainer(view)) { - view.post(() -> refreshContainer(view)); - } - } - } - - private void refreshContainer(View view) { - applyLimitIfNeeded(view); - forceLayout(view); - tryRecalculateIcons(view); - } - - private void applyLimitIfNeeded(View view) { - captureStockMaxStaticIcons(view); - if (!isFeatureEnabled(view.getContext())) { - restoreStockLimit(view); - return; - } - int override = resolveUnlockedLimit(view.getContext()); - if (override <= 0) { - restoreStockLimit(view); - return; - } - applyOverrideToContainer(view, override); - enforceParentWidth(view); - } - - private void restoreStockLimit(View view) { - Integer stock = stockMaxStaticIcons.get(view); - if (stock != null) { - ReflectionSupport.setFieldValue(view, "mMaxStaticIcons", stock); - } - } - - private void applyOverrideToContainer(View view, int override) { - ReflectionSupport.setFieldValue(view, "mMaxStaticIcons", override); - } - - private void enforceParentWidth(View view) { - ViewParent parent = view.getParent(); - int depth = 0; - while (parent instanceof View && depth < 3) { - View parentView = (View) parent; - String name = parentView.getClass().getName(); - if (name.contains("AlphaOptimizedLinearLayout") - || name.contains("AlphaOptimizedFrameLayout")) { - ViewGroup.LayoutParams lp = parentView.getLayoutParams(); - if (lp != null && (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT || lp.width == 0)) { - lp.width = ViewGroup.LayoutParams.MATCH_PARENT; - parentView.setLayoutParams(lp); - parentView.requestLayout(); - } - } - parent = parentView.getParent(); - depth++; - } - } - - private void forceLayout(View view) { - view.forceLayout(); - view.requestLayout(); - view.invalidate(); - ViewParent parent = view.getParent(); - if (parent instanceof View parentView) { - parentView.requestLayout(); - parentView.invalidate(); - } - } - - private void tryRecalculateIcons(View view) { - ReflectionSupport.invokeMethod(view, "calculateIconXTranslations"); - ReflectionSupport.invokeMethod(view, "applyIconStates"); - ReflectionSupport.invokeMethod(view, "onNotificationInfoUpdated"); - } - - private boolean isFeatureEnabled(Context context) { - SbtSettings settings = RuntimeSettingsCache.get(context); - return !settings.clockEnabled; - } - - private int resolveUnlockedLimit(Context context) { - SbtSettings settings = RuntimeSettingsCache.get(context); - if (settings.clockEnabled) { - return -1; - } - int value = settings.unlockedMaxIconsPerRow; - if (value == Integer.MAX_VALUE || value == 0) { - return INFINITE_ICON_LIMIT; - } - if (value < SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_MIN) { - return SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT; - } - return value; - } - - private boolean isKeyguardContainer(Object container) { - return ReflectionSupport.getBooleanField(container, "mOnKeyguardStatusBar", false); - } - - private boolean shouldManageContainer(View view) { - if (!isFeatureEnabled(view.getContext())) { - return false; - } - if (!isUnlockedScene()) { - return false; - } - if (isKeyguardContainer(view)) { - return false; - } - ViewParent parent = view.getParent(); - boolean inUnlockedStatusBarIconArea = false; - int depth = 0; - while (parent instanceof View parentView && depth < 8) { - String idName = ViewIdNames.idName(parentView); - if (idName.equals("notification_icon_area") - || idName.equals("notification_icon_area_inner")) { - inUnlockedStatusBarIconArea = true; - } - String className = parentView.getClass().getName(); - if (className.contains("KeyguardRootView") - || className.contains("NotificationShelf") - || className.contains("NotificationStackScrollLayout")) { - return false; - } - parent = parentView.getParent(); - depth++; - } - return inUnlockedStatusBarIconArea; - } - - private boolean isUnlockedScene() { - SceneKey scene = runtimeContext.getModeStateRepository().getActiveScene(); - return scene != null && scene.isUnlocked(); - } - -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsFeature.java deleted file mode 100644 index d5e37b0..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/notifications/StockUnlockedNotificationIconsFeature.java +++ /dev/null @@ -1,34 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.features.notifications; - -import io.github.libxposed.api.XposedModuleInterface; -import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; -import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; - -/** - * Keeps the original simple unlocked stock-icon count override available while - * the rewritten custom layout engine is still disabled. - */ -public final class StockUnlockedNotificationIconsFeature implements RuntimeFeature { - - private StockUnlockedNotificationIconsController controller; - - @Override - public String getName() { - return "stock-unlocked-notification-icons"; - } - - @Override - public void onPackageReady(RuntimeContext context, XposedModuleInterface.PackageReadyParam param) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } - installController(context, param.getClassLoader()); - } - - private void installController(RuntimeContext context, ClassLoader classLoader) { - if (controller == null) { - controller = new StockUnlockedNotificationIconsController(context); - } - controller.install(classLoader); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/LockscreenCardsNotificationRowFilter.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/LockscreenCardsNotificationRowFilter.java deleted file mode 100644 index b151a39..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/LockscreenCardsNotificationRowFilter.java +++ /dev/null @@ -1,378 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.layout; - -import android.app.KeyguardManager; -import android.app.Notification; -import android.content.Context; -import android.os.Bundle; -import android.os.Parcelable; -import android.service.notification.StatusBarNotification; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; -import se.ajpanton.statusbartweak.runtime.mode.NotificationDisplayStyle; -import se.ajpanton.statusbartweak.runtime.mode.SystemNotificationDisplayStyleDetector; -import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -final class LockscreenCardsNotificationRowFilter { - private static final String MODE_LOCK = "LOCK"; - - private final Map hiddenRows = new WeakHashMap<>(); - - boolean apply(ViewGroup stack, boolean allowAfterKeyguardUnlock) { - if (stack == null) { - return false; - } - Context context = stack.getContext(); - boolean active = isActive(context, allowAfterKeyguardUnlock); - boolean changed = false; - int childCount = stack.getChildCount(); - for (int i = 0; i < childCount; i++) { - View child = stack.getChildAt(i); - if (!isNotificationRow(child)) { - continue; - } - if (active && shouldHideRow(context, child, allowAfterKeyguardUnlock)) { - changed |= hideRow(child); - } else { - changed |= restoreRow(child); - } - } - if (changed) { - requestLayout(stack); - } - return changed; - } - - boolean applyRow(View row, boolean allowAfterKeyguardUnlock) { - if (!isNotificationRow(row)) { - return false; - } - Context context = row.getContext(); - boolean active = isActive(context, allowAfterKeyguardUnlock); - boolean changed; - if (active && shouldHideRow(context, row, allowAfterKeyguardUnlock)) { - changed = hideRow(row); - } else { - changed = restoreRow(row); - } - if (changed) { - requestLayout(row); - } - return changed; - } - - void restoreRemovedRow(View row) { - restoreRow(row); - } - - void restoreAll() { - if (hiddenRows.isEmpty()) { - return; - } - ArrayList rows = new ArrayList<>(hiddenRows.keySet()); - for (View row : rows) { - restoreRow(row); - } - } - - boolean hasHiddenRows() { - return !hiddenRows.isEmpty(); - } - - void suppressHiddenRows() { - if (hiddenRows.isEmpty()) { - return; - } - ArrayList rows = new ArrayList<>(hiddenRows.keySet()); - for (View row : rows) { - if (row == null || !row.isAttachedToWindow() || !isNotificationRow(row)) { - hiddenRows.remove(row); - continue; - } - hideRow(row); - } - } - - private boolean isActive(Context context, boolean allowAfterKeyguardUnlock) { - if (context == null) { - return false; - } - SbtSettings settings = RuntimeSettingsCache.get(context); - if (!settings.clockEnabled) { - return false; - } - if (settings.appIconBlockedModes.isEmpty() && settings.appIconExceptionRules.isEmpty()) { - return false; - } - if (SystemNotificationDisplayStyleDetector.read(context) != NotificationDisplayStyle.CARDS) { - return false; - } - KeyguardManager keyguard = context.getSystemService(KeyguardManager.class); - if (!allowAfterKeyguardUnlock && (keyguard == null || !keyguard.isKeyguardLocked())) { - return false; - } - return true; - } - - boolean shouldHideEntry(Context context, Object entry) { - return shouldHideEntry(context, entry, false); - } - - private boolean shouldHideEntry(Context context, Object entry, boolean allowAfterKeyguardUnlock) { - if (!isActive(context, allowAfterKeyguardUnlock)) { - return false; - } - SbtSettings settings = RuntimeSettingsCache.get(context); - String packageName = packageFor(entry); - if (!AppIconRules.isValidPackageName(packageName)) { - return false; - } - String text = matchText(null, entry); - AppIconRules.ExceptionRule exceptionRule = - matchingExceptionRule(text, settings.appIconExceptionRules.get(packageName)); - return exceptionRule != null - ? exceptionRule.blocksMode(MODE_LOCK) - : AppIconRules.isBlocked(settings.appIconBlockedModes, packageName, MODE_LOCK); - } - - private boolean shouldHideRow(Context context, View row, boolean allowAfterKeyguardUnlock) { - Object entry = NotificationKeyReflection.entryForRow(row); - if (shouldHideEntry(context, entry, allowAfterKeyguardUnlock)) { - return true; - } - SbtSettings settings = RuntimeSettingsCache.get(context); - String packageName = packageFor(row); - if (!AppIconRules.isValidPackageName(packageName)) { - return false; - } - String text = matchText(row, entry); - AppIconRules.ExceptionRule exceptionRule = - matchingExceptionRule(text, settings.appIconExceptionRules.get(packageName)); - if (exceptionRule != null) { - return exceptionRule.blocksMode(MODE_LOCK); - } - return AppIconRules.isBlocked(settings.appIconBlockedModes, packageName, MODE_LOCK); - } - - private boolean hideRow(View row) { - if (row == null) { - return false; - } - if (row.getVisibility() == View.GONE && row.getAlpha() == 0f) { - return false; - } - hiddenRows.computeIfAbsent(row, ignored -> new HiddenRowState(View.VISIBLE, 1f)); - boolean changed = false; - if (row.getVisibility() != View.GONE) { - row.setVisibility(View.GONE); - changed = true; - } - if (row.getAlpha() != 0f) { - row.setAlpha(0f); - changed = true; - } - return changed; - } - - private boolean restoreRow(View row) { - if (row == null) { - return false; - } - HiddenRowState state = hiddenRows.remove(row); - if (state == null) { - return false; - } - boolean changed = false; - if (row.getVisibility() != state.visibility) { - row.setVisibility(state.visibility); - changed = true; - } - if (row.getAlpha() != state.alpha) { - row.setAlpha(state.alpha); - changed = true; - } - changed |= normalizeRowState(row); - requestLayout(row); - return changed; - } - - private boolean normalizeRowState(View row) { - boolean changed = false; - changed |= setBooleanField(row, "mWillBeGone", false); - changed |= setBooleanField(row, "mInShelf", false); - changed |= setBooleanField(row, "mTransformingInShelf", false); - Object viewState = ReflectionSupport.getFieldValue(row, "mViewState"); - if (viewState != null) { - changed |= setBooleanField(viewState, "hidden", false); - changed |= setBooleanField(viewState, "gone", false); - } - return changed; - } - - private boolean setBooleanField(Object target, String fieldName, boolean value) { - Object current = ReflectionSupport.getFieldValue(target, fieldName); - if (!(current instanceof Boolean) || (Boolean) current == value) { - return false; - } - ReflectionSupport.setFieldValue(target, fieldName, value); - return true; - } - - private void requestLayout(View view) { - if (view == null) { - return; - } - view.requestLayout(); - view.invalidate(); - Object parent = view.getParent(); - if (parent instanceof View parentView) { - parentView.requestLayout(); - parentView.invalidate(); - } - } - - private static boolean isNotificationRow(View view) { - return view != null && view.getClass().getName().contains("ExpandableNotificationRow"); - } - - private String packageFor(Object target) { - if (target == null) { - return null; - } - StatusBarNotification sbn = NotificationReflection.statusBarNotification(target); - if (sbn != null && AppIconRules.isValidPackageName(sbn.getPackageName())) { - return sbn.getPackageName(); - } - String key = NotificationKeyReflection.rowFilterKey(target); - String fromKey = NotificationKeyReflection.packageFromNotificationKey(key); - if (AppIconRules.isValidPackageName(fromKey)) { - return fromKey; - } - Object packageName = ReflectionSupport.invokeMethod(target, "getPackageName"); - if (packageName instanceof String string && AppIconRules.isValidPackageName(string)) { - return string; - } - packageName = ReflectionSupport.getFieldValue(target, "packageName"); - if (packageName instanceof String string && AppIconRules.isValidPackageName(string)) { - return string; - } - packageName = ReflectionSupport.getFieldValue(target, "mPackageName"); - if (packageName instanceof String string && AppIconRules.isValidPackageName(string)) { - return string; - } - if (target instanceof View view) { - Object entry = NotificationKeyReflection.entryForRow(view); - String fromEntry = packageFor(entry); - if (AppIconRules.isValidPackageName(fromEntry)) { - return fromEntry; - } - CharSequence description = view.getContentDescription(); - if (description != null) { - String fromDescription = NotificationKeyReflection.packageFromNotificationKey( - description.toString()); - if (AppIconRules.isValidPackageName(fromDescription)) { - return fromDescription; - } - } - } - return null; - } - - private String matchText(View row, Object entry) { - StringBuilder out = new StringBuilder(); - append(out, NotificationKeyReflection.rowFilterKey(entry)); - append(out, NotificationKeyReflection.rowFilterKey(row)); - appendNotification(out, NotificationReflection.statusBarNotification(entry)); - appendNotification(out, NotificationReflection.statusBarNotification(row)); - if (row != null) { - append(out, row.getContentDescription()); - } - return out.toString(); - } - - @SuppressWarnings("deprecation") - private void appendNotification(StringBuilder out, StatusBarNotification sbn) { - if (sbn == null) { - return; - } - append(out, sbn.getKey()); - append(out, sbn.getPackageName()); - Notification notification = sbn.getNotification(); - Bundle extras = notification != null ? notification.extras : null; - if (extras == null) { - return; - } - append(out, extras.getCharSequence(Notification.EXTRA_TITLE)); - append(out, extras.getCharSequence(Notification.EXTRA_TITLE_BIG)); - append(out, extras.getCharSequence(Notification.EXTRA_TEXT)); - append(out, extras.getCharSequence(Notification.EXTRA_BIG_TEXT)); - append(out, extras.getCharSequence(Notification.EXTRA_SUB_TEXT)); - append(out, extras.getCharSequence(Notification.EXTRA_SUMMARY_TEXT)); - append(out, extras.getCharSequence(Notification.EXTRA_INFO_TEXT)); - CharSequence[] lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES); - if (lines != null) { - for (CharSequence line : lines) { - append(out, line); - } - } - Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES); - if (messages != null) { - for (Parcelable message : messages) { - append(out, message != null ? message.toString() : null); - } - } - } - - private void append(StringBuilder out, CharSequence text) { - if (out == null || text == null || text.length() == 0) { - return; - } - if (out.length() > 0) { - out.append('\n'); - } - out.append(text); - } - - private AppIconRules.ExceptionRule matchingExceptionRule( - String text, - ArrayList rules - ) { - if (rules == null || rules.isEmpty()) { - return null; - } - String candidateText = text != null ? text : ""; - for (AppIconRules.ExceptionRule rule : rules) { - if (rule == null || rule.regex == null || rule.regex.trim().isEmpty()) { - continue; - } - try { - if (Pattern.compile(rule.regex).matcher(candidateText).find()) { - return rule; - } - } catch (PatternSyntaxException ignored) { - // Invalid user regexes are ignored instead of blocking every card. - } - } - return null; - } - - private static final class HiddenRowState { - final int visibility; - final float alpha; - - HiddenRowState(int visibility, float alpha) { - this.visibility = visibility; - this.alpha = alpha; - } - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasController.java index 2ffb13e..1313f0c 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasController.java @@ -48,8 +48,7 @@ import se.ajpanton.statusbartweak.runtime.mode.NotificationDisplayStyle; import se.ajpanton.statusbartweak.runtime.mode.SystemNotificationDisplayStyleDetector; import se.ajpanton.statusbartweak.runtime.render.AodStatusbarSourceStore; import se.ajpanton.statusbartweak.runtime.render.DebugBoundsOverlayController; -import se.ajpanton.statusbartweak.runtime.render.LockscreenCardsNotificationIconSourceStore; -import se.ajpanton.statusbartweak.runtime.render.LockscreenCardsNotificationStripRenderer; +import se.ajpanton.statusbartweak.runtime.render.AodNotificationIconSourceStore; import se.ajpanton.statusbartweak.runtime.notifications.NotificationActiveKeyStore; import se.ajpanton.statusbartweak.runtime.notifications.NotificationUnreadTracker; import se.ajpanton.statusbartweak.runtime.render.OwnedIconHostManager; @@ -57,7 +56,6 @@ import se.ajpanton.statusbartweak.runtime.render.StatusChipCallSupport; import se.ajpanton.statusbartweak.runtime.render.UnlockedIconSnapshotRenderController; import se.ajpanton.statusbartweak.runtime.render.UnlockedIconSnapshotRenderController.RenderResult; import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; final class StockLayoutCanvasController { @@ -98,8 +96,7 @@ final class StockLayoutCanvasController { private static final Set TARGET_CLASS_SUBSTRINGS = Set.of( "QSClockIndicatorView", - "statusbar.policy.Clock", - "SecShelfNotificationIconContainer" + "statusbar.policy.Clock" ); private static final Set LAYOUT_OFF_UNLOCKED_ONLY_IDS = Set.of( @@ -116,11 +113,7 @@ final class StockLayoutCanvasController { private final Map rootGeometries = new WeakHashMap<>(); private final Map debugOverlaySignatures = new WeakHashMap<>(); private final Map settingsIdentityByRoot = new WeakHashMap<>(); - private final Map lockscreenCardsRowFilterSignatures = new WeakHashMap<>(); - private final Map lockscreenCardsNotificationRenderGenerationByRoot = - new WeakHashMap<>(); private final Map clockTimeBucketByRoot = new WeakHashMap<>(); - private final Map aodCardsNotificationRenderGenerationByRoot = new WeakHashMap<>(); private final Map aodSourceGeometryByView = new WeakHashMap<>(); private final Map aodNotificationWidgetSteadyWidths = new WeakHashMap<>(); private final Map aodNotificationIconOnlyAreaSteadyLefts = new WeakHashMap<>(); @@ -132,6 +125,8 @@ final class StockLayoutCanvasController { new WeakHashMap<>(); private final Set confirmedAodPluginViews = Collections.newSetFromMap(new WeakHashMap<>()); + private final Set confirmedAodNotificationPluginViews = + Collections.newSetFromMap(new WeakHashMap<>()); private final Map aodPluginVisualAlphaByView = new WeakHashMap<>(); private final Set layoutOffCleanedRoots = Collections.newSetFromMap(new WeakHashMap<>()); @@ -185,9 +180,6 @@ final class StockLayoutCanvasController { private final OwnedIconHostManager ownedIconHostManager = new OwnedIconHostManager(); private final DebugBoundsOverlayController debugBoundsOverlayController = new DebugBoundsOverlayController(); - private final LockscreenCardsNotificationStripRenderer lockscreenCardsNotificationStripRenderer; - private final LockscreenCardsNotificationRowFilter lockscreenCardsNotificationRowFilter = - new LockscreenCardsNotificationRowFilter(); private final UnlockedIconSnapshotRenderController unlockedIconRenderController; // The keyguard carrier text lives outside the statusbar root on this device. // Keep a weak source reference so the lockscreen statusbar can render it when @@ -212,8 +204,6 @@ final class StockLayoutCanvasController { this::isLockscreenScene, this::shouldUseDarkLockscreenStatusbarTint, this::scheduleUnlockedAppearanceRefreshForAllRoots); - lockscreenCardsNotificationStripRenderer = - new LockscreenCardsNotificationStripRenderer(); unlockedIconRenderController = new UnlockedIconSnapshotRenderController(); runtimeContext.getModeStateRepository().addSceneListener(this::scheduleSceneRefresh); runtimeContext.getModeStateRepository().addSystemUiStatusBarStateListener( @@ -225,8 +215,7 @@ final class StockLayoutCanvasController { return; } installPluginManagerHooks(classLoader); - installCardsNotificationIconSourceHook(classLoader); - installLockscreenCardsNotificationRowFilterHook(classLoader); + installNotificationIconSourceHook(classLoader); installUnlockedAppearanceInvalidationHooks(classLoader); installNotificationCollectionHooks(classLoader); statusIconModelTracker.installHooks(classLoader); @@ -657,39 +646,6 @@ final class StockLayoutCanvasController { }); } - private void installLockscreenCardsNotificationRowFilterHook(ClassLoader classLoader) { - Class stackClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout", - classLoader); - if (stackClass != null) { - XposedHookSupport.hookAllMethodsIfExists( - runtimeContext.getFramework(), - stackClass, - "onViewAdded", - chain -> { - Object result = chain.proceed(); - List args = chain.getArgs(); - if (!args.isEmpty() && args.get(0) instanceof View row) { - applyLockscreenCardsNotificationRowFilterRow(row, false); - } - return result; - }); - XposedHookSupport.hookAllMethodsIfExists( - runtimeContext.getFramework(), - stackClass, - "onViewRemoved", - chain -> { - Object result = chain.proceed(); - List args = chain.getArgs(); - if (!args.isEmpty() && args.get(0) instanceof View row) { - lockscreenCardsNotificationRowFilter.restoreRemovedRow(row); - } - return result; - }); - } - - } - private void installUnlockedAppearanceInvalidationHooks(ClassLoader classLoader) { Class darkIconDispatcherClass = ReflectionSupport.findClassIfExists( "com.android.systemui.statusbar.phone.DarkIconDispatcherImpl", @@ -929,7 +885,7 @@ final class StockLayoutCanvasController { }); } - private void installCardsNotificationIconSourceHook(ClassLoader classLoader) { + private void installNotificationIconSourceHook(ClassLoader classLoader) { Class controllerClass = ReflectionSupport.findClassIfExists( CLASS_LEGACY_NOTIFICATION_ICON_AREA_CONTROLLER, classLoader); @@ -967,44 +923,16 @@ final class StockLayoutCanvasController { } @SuppressWarnings("unchecked") Function original = (Function) args.get(functionIndex); - if (!isCardsNotificationIconSourceContainer(container)) { - Function wrapped = entryObj -> { - recordNotificationEntry(entryObj); - return original.apply(entryObj); - }; - Object[] newArgs = args.toArray(new Object[0]); - newArgs[functionIndex] = wrapped; - Object result = chain.proceed(newArgs); - requestUnlockedLayoutRefreshFromSource(container); - return result; + if (isNotificationShelfIconSourceContainer(container)) { + return chain.proceed(); } - ArrayList captured = - new ArrayList<>(); Function wrapped = entryObj -> { - String key = NotificationKeyReflection.keyForEntry(entryObj); - if (!runtimeContext.getModeStateRepository().isSystemUiShadeLocked() - && lockscreenCardsNotificationRowFilter.shouldHideEntry( - container.getContext(), - entryObj)) { - return null; - } - Object result = original.apply(entryObj); recordNotificationEntry(entryObj); - if (result == null) { - result = fallbackStatusBarIcon(entryObj); - } - if (result instanceof View view && !isStockOverflowDotView(view)) { - if (key == null) { - key = NotificationKeyReflection.keyForIconView(view); - } - captured.add(LockscreenCardsNotificationIconSourceStore.source(view, key)); - } - return result; + return original.apply(entryObj); }; Object[] newArgs = args.toArray(new Object[0]); newArgs[functionIndex] = wrapped; Object result = chain.proceed(newArgs); - LockscreenCardsNotificationIconSourceStore.put(container, captured); requestUnlockedLayoutRefreshFromSource(container); return result; }); @@ -1084,8 +1012,9 @@ final class StockLayoutCanvasController { if (!isLayoutEnabled(view.getContext())) { return result; } - updateAodNotificationPackageSources(view); - applyConfirmedAodPluginPolicy(view); + if (applyConfirmedAodNotificationPluginPolicy(view)) { + updateAodNotificationPackageSources(view); + } } return result; }); @@ -1150,7 +1079,7 @@ final class StockLayoutCanvasController { viewFingerprintCacheByImageView.clear(); NotificationActiveKeyStore.replace(Collections.emptySet()); NotificationUnreadTracker.retainActiveKeys(Collections.emptySet()); - LockscreenCardsNotificationIconSourceStore.clearAodSources(); + AodNotificationIconSourceStore.clearAodSources(); markKnownAodNotificationRootsDirty(); updateKnownAodNotificationSources(); return; @@ -1163,13 +1092,13 @@ final class StockLayoutCanvasController { if (sbn != null && sbn.getKey() != null) { activeKeys.add(sbn.getKey()); } - if (sbn != null && AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn != null && NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { packages.add(sbn.getPackageName()); } } updateActiveNotificationKeys(activeNotificationIconKeys(notifications)); changed |= NotificationUnreadTracker.retainActiveKeys(activeKeys); - LockscreenCardsNotificationIconSourceStore.putAodNotificationPackages(packages); + AodNotificationIconSourceStore.putAodNotificationPackages(packages); latestAodNotifications = notifications; pruneNotificationFingerprintCache(notifications); if (changed) { @@ -1297,7 +1226,7 @@ final class StockLayoutCanvasController { Object entry ) { StatusBarNotification sbn = NotificationReflection.statusBarNotificationEntry(entry); - if (sbn == null || !AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn == null || !NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { return; } notifications.add(sbn); @@ -1314,7 +1243,8 @@ final class StockLayoutCanvasController { return; } for (StatusBarNotification sbn : notifications) { - if (sbn != null && sbn.getKey() != null && AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn != null && sbn.getKey() != null + && NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { NotificationUnreadTracker.record(sbn); } } @@ -1335,7 +1265,7 @@ final class StockLayoutCanvasController { return keys; } for (StatusBarNotification sbn : notifications) { - if (sbn == null || !AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn == null || !NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { continue; } if (sbn.getKey() != null) { @@ -1393,7 +1323,6 @@ final class StockLayoutCanvasController { } SbtSettings settings = RuntimeSettingsCache.get(root.getContext()); if (!settings.clockEnabled) { - lockscreenCardsNotificationRowFilter.restoreAll(); return; } SceneKey activeScene = runtimeContext.getModeStateRepository().getActiveScene(); @@ -1407,23 +1336,6 @@ final class StockLayoutCanvasController { restorePreparedAodNotificationWidgetWidths(root); } } - if (activeScene.isLockscreen() - && activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS - && isNotificationShadeWindowRoot(root)) { - boolean applied = applyLockscreenCardsNotificationRowFilterInTreeIfNeeded( - root, - settings, - activeScene, - true); - if (!applied && lockscreenCardsNotificationRowFilter.hasHiddenRows()) { - lockscreenCardsNotificationRowFilter.suppressHiddenRows(); - } - } else if (activeScene.isUnlocked() && isNotificationShadeWindowRoot(root)) { - lockscreenCardsNotificationRowFilter.restoreAll(); - } else if (activeScene.isAod() - && activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { - lockscreenCardsNotificationRowFilter.suppressHiddenRows(); - } } private Float reflectedExpansion(Object target) { @@ -1536,45 +1448,14 @@ final class StockLayoutCanvasController { if (hasVisibleConfirmedAodPluginView()) { hideConfirmedAodPluginViews(); } - hideLockscreenCardsNotificationHost(root); - if (activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS - && isAodLayoutRoot(root, activeScene)) { - renderAodCardsNotificationStripIfNeeded(root, settings, activeScene); - } else { - removeAodCardsNotificationHost(root); - } syncAodOwnedHostVisualState(root); return; } aodBeforeDrawSignatureByRoot.remove(root); - removeAodCardsNotificationHost(root); if (activeScene != null && !activeScene.isUnlocked()) { hideTrackedLockedStatusBarIconSurfaces(null); } - if (activeScene != null - && activeScene.isLockscreen() - && activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS - && canContainLockedStatusBarIconSurfaces(root)) { - if (isNotificationShadeWindowRoot(root)) { - applyLockscreenCardsNotificationRowFilterInTreeIfNeeded( - root, - settings, - activeScene, - true); - } - renderLockscreenCardsNotificationStripIfNeeded(root, settings, activeScene); - } else if (activeScene != null - && activeScene.isAod() - && activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { - lockscreenCardsRowFilterSignatures.remove(root); - lockscreenCardsNotificationRowFilter.suppressHiddenRows(); - } else { - lockscreenCardsRowFilterSignatures.remove(root); - if (activeScene != null && activeScene.isUnlocked()) { - lockscreenCardsNotificationRowFilter.restoreAll(); - } - } if (!isUnlockedStatusBarRoot(root)) { return; } @@ -1599,15 +1480,6 @@ final class StockLayoutCanvasController { result = 31 * result + aodNotificationSourceGeneration; result = 31 * result + Float.floatToIntBits(aodVisualAlphaForRoot(root)); result = 31 * result + aodPluginVisibilitySignature(root); - if (activeScene != null - && activeScene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { - Bounds sourceBounds = LockscreenCardsNotificationIconSourceStore - .sourceContainerBoundsForRoot(root); - result = 31 * result + (sourceBounds != null ? sourceBounds.signature() : 0); - result = 31 * result - + (LockscreenCardsNotificationIconSourceStore - .sourceContainerHasHiddenAncestorForRoot(root) ? 1 : 0); - } return result; } @@ -1868,6 +1740,7 @@ final class StockLayoutCanvasController { while (!staleViews.isEmpty()) { View stale = staleViews.removeFirst(); confirmedAodPluginViews.remove(stale); + confirmedAodNotificationPluginViews.remove(stale); aodPluginVisualAlphaByView.remove(stale); aodVisualAlphaGeneration++; aodBeforeDrawSignatureByRoot.clear(); @@ -1980,7 +1853,6 @@ final class StockLayoutCanvasController { Integer previous = settingsIdentityByRoot.put(root, identity); if (previous != null && previous != identity) { dirtyUnlockedLayoutRoots.add(root); - lockscreenCardsRowFilterSignatures.remove(root); } } @@ -2470,8 +2342,6 @@ final class StockLayoutCanvasController { if (aodScene && statusBarRoot && !aodLayoutRoot) { removeSharedLayoutHosts(root); unlockedIconRenderController.clearRoot(root); - removeLockscreenCardsNotificationHost(root); - removeAodCardsNotificationHost(root); removeDebugOverlay(root); return; } @@ -2479,17 +2349,11 @@ final class StockLayoutCanvasController { if (activeScene != null && activeScene.isUnlocked() && isNotificationShadeWindowRoot(root)) { - hideUnlockedShadeShelfIconSurfaces(root); removeSharedLayoutHosts(root); } else if (activeScene != null && activeScene.isLockscreen() && canContainLockedStatusBarIconSurfaces(root)) { removeUnlockedLayoutHosts(root); - removeAodCardsNotificationHost(root); - if (activeScene.notificationDisplayStyle() != NotificationDisplayStyle.CARDS - && hasLockscreenCardsNotificationHost(root)) { - removeLockscreenCardsNotificationHost(root); - } hideOrDiscoverLockedStatusBarIconSurfaces(root); } else { removeSharedLayoutHosts(root); @@ -2667,7 +2531,7 @@ final class StockLayoutCanvasController { if (isLayoutOffCleanupNoOp(root)) { return; } - cleanupLayoutOffRoot(root, activeScene); + cleanupLayoutOffRoot(root); } private boolean isLayoutOffCleanupNoOp(View root) { @@ -2675,7 +2539,6 @@ final class StockLayoutCanvasController { && trackedStatusChipSources.isEmpty() && trackedUnlockedStockSurfaces.isEmpty() && trackedLockedStatusBarIconSurfaces.isEmpty() - && !lockscreenCardsNotificationRowFilter.hasHiddenRows() && !unlockedHostsByRoot.containsKey(root) && !hasDirectOwnedLayoutHost(root); } @@ -2688,9 +2551,7 @@ final class StockLayoutCanvasController { || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_NOTIFICATION_HOST) != null || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_CLOCK_HOST) != null || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_CARRIER_HOST) != null - || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_CHIP_HOST) != null - || findDirectOwnedHost(group, OwnedIconHostManager.TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST) != null - || findDirectOwnedHost(group, OwnedIconHostManager.TAG_AOD_CARDS_NOTIFICATION_HOST) != null; + || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_CHIP_HOST) != null; } private boolean hasDirectUnlockedLayoutHost(View root) { @@ -2704,13 +2565,6 @@ final class StockLayoutCanvasController { || findDirectOwnedHost(group, OwnedIconHostManager.TAG_UNLOCKED_CHIP_HOST) != null; } - private boolean hasLockscreenCardsNotificationHost(View root) { - return root instanceof ViewGroup group - && findDirectOwnedHost( - group, - OwnedIconHostManager.TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST) != null; - } - private void applyDebugOverlay( View root, boolean layoutEnabled, @@ -2832,51 +2686,6 @@ final class StockLayoutCanvasController { }); } - private void hideUnlockedShadeShelfIconSurfaces(View root) { - if (root == null) { - return; - } - boolean foundTracked = hideTrackedUnlockedShadeShelfIconSurfaces(root); - if (foundTracked) { - return; - } - walkTree(root, view -> { - if (isUnlockedShadeShelfIconSurface(view)) { - trackedUnlockedStockSurfaces.add(view); - hideView(view, false); - } - }); - } - - private boolean hideTrackedUnlockedShadeShelfIconSurfaces(View root) { - if (trackedUnlockedStockSurfaces.isEmpty()) { - return false; - } - boolean foundIconSurfaceInRoot = false; - ArrayDeque staleViews = new ArrayDeque<>(); - for (View view : trackedUnlockedStockSurfaces) { - if (view == null || !view.isAttachedToWindow()) { - staleViews.add(view); - continue; - } - if (!isDescendantOf(view, root)) { - continue; - } - if (!isUnlockedShadeShelfIconSurface(view)) { - continue; - } - foundIconSurfaceInRoot |= isCardsNotificationIconSurface(view); - hideView(view, false); - } - removeStaleViews(trackedUnlockedStockSurfaces, staleViews); - return foundIconSurfaceInRoot; - } - - private boolean isUnlockedShadeShelfIconSurface(View view) { - return isCardsNotificationIconSurface(view) - || isCardsNotificationShelfBackgroundSurface(view); - } - private boolean hasTrackedUnlockedStockSurfaces(View root) { if (trackedUnlockedStockSurfaces.isEmpty()) { return false; @@ -2899,6 +2708,12 @@ final class StockLayoutCanvasController { staleViews.add(view); continue; } + if (isCardsNotificationScene() + && confirmedAodNotificationPluginViews.contains(view)) { + restoreView(view); + staleViews.add(view); + continue; + } hideView(view, keepConfirmedAodPluginViewLaidOut(view)); } removeStaleAodPluginViews(staleViews); @@ -3525,8 +3340,6 @@ final class StockLayoutCanvasController { String viewClassName = view.getClass().getName(); boolean carrierSurface = idName.toLowerCase(Locale.ROOT).contains("carrier") || viewClassName.toLowerCase(Locale.ROOT).contains("carrier"); - boolean shelfSurface = isCardsNotificationIconSurface(view); - boolean shelfBackgroundSurface = isCardsNotificationShelfBackgroundSurface(view); boolean shadeIconOnlySurface = "keyguard_icononly_container_view".equals(idName); boolean clockSurface = "clock".equals(idName) || "left_clock_container".equals(idName) @@ -3541,9 +3354,7 @@ final class StockLayoutCanvasController { || "notification_icon_area".equals(idName) || "notification_icon_area_inner".equals(idName) || "notificationIcons".equals(idName) - || "keyguard_icononly_container_view".equals(idName) - || shelfSurface - || shelfBackgroundSurface)) { + || "keyguard_icononly_container_view".equals(idName))) { return false; } Object current = view; @@ -3560,12 +3371,6 @@ final class StockLayoutCanvasController { if (carrierSurface && className.contains("NotificationShadeWindowView")) { return true; } - if (shelfSurface && className.contains("NotificationShadeWindowView")) { - return true; - } - if (shelfBackgroundSurface && className.contains("NotificationShadeWindowView")) { - return true; - } if (shadeIconOnlySurface && className.contains("NotificationShadeWindowView")) { return true; } @@ -3574,57 +3379,10 @@ final class StockLayoutCanvasController { return false; } - private boolean isCardsNotificationIconSurface(View view) { - if (view == null) { - return false; - } - String idName = ViewIdNames.idName(view); - String className = view.getClass().getName(); - return className.contains("SecShelfNotificationIconContainer") - || "keyguard_icononly_container_view".equals(idName); - } - - private boolean isCardsNotificationShelfBackgroundSurface(View view) { - if (view == null) { - return false; - } - String className = view.getClass().getName(); - return className.contains("NotificationShelfBackground") - && hasAncestorClass(view, "NotificationShelf"); - } - - private boolean hasAncestorClass(View view, String classNamePart) { - Object current = view != null ? view.getParent() : null; - while (current instanceof View currentView) { - if (currentView.getClass().getName().contains(classNamePart)) { - return true; - } - current = currentView.getParent(); - } - return false; - } - - private boolean isCardsNotificationIconSourceContainer(View view) { + private boolean isNotificationShelfIconSourceContainer(View view) { return view != null && view.getClass().getName().contains("SecShelfNotificationIconContainer"); } - private Object fallbackStatusBarIcon(Object entryObj) { - Object icons = ReflectionSupport.getFieldValue(entryObj, "mIcons"); - return icons != null ? ReflectionSupport.getFieldValue(icons, "mStatusBarIcon") : null; - } - - private boolean isStockOverflowDotView(View view) { - if (view == null) { - return false; - } - String idName = ViewIdNames.idName(view).toLowerCase(Locale.ROOT); - String className = view.getClass().getName().toLowerCase(Locale.ROOT); - return idName.contains("overflow") - || idName.contains("dot") - || className.contains("overflow") - || className.contains("dot"); - } - private boolean isCarrierView(View view) { if (view == null) { return false; @@ -4003,8 +3761,6 @@ final class StockLayoutCanvasController { dirtyUnlockedLayoutRoots.remove(root); settingsIdentityByRoot.remove(root); aodBeforeDrawSignatureByRoot.remove(root); - lockscreenCardsRowFilterSignatures.remove(root); - lockscreenCardsNotificationRenderGenerationByRoot.remove(root); clearUnlockedClockRefreshState(root); removeDebugOverlay(root); root.requestLayout(); @@ -4045,16 +3801,21 @@ final class StockLayoutCanvasController { } View statusContainer = castView(ReflectionSupport.getFieldValue(controller, "c")); View statusContainerEnd = castView(ReflectionSupport.getFieldValue(controller, "e")); - View notificationContainer = castView(ReflectionSupport.getFieldValue(controller, "d")); + View primaryContainer = castView(ReflectionSupport.getFieldValue(controller, "d")); if (!runtimeContext.getModeStateRepository().isLayoutEnabled()) { return; } - if (!shouldApplyLayoutPolicy(notificationContainer, statusContainer, statusContainerEnd)) { + if (!shouldApplyLayoutPolicy(primaryContainer, statusContainer, statusContainerEnd)) { return; } markAodLayoutDirty(statusContainer); markAodLayoutDirty(statusContainerEnd); - applyConfirmedAodPluginPolicy(notificationContainer); + if (isAodStatusbarPluginContainerView(primaryContainer)) { + markAodLayoutDirty(primaryContainer); + applyConfirmedAodPluginPolicy(primaryContainer); + } else { + applyConfirmedAodNotificationPluginPolicy(primaryContainer); + } applyConfirmedAodPluginPolicy(statusContainer); applyConfirmedAodPluginPolicy(statusContainerEnd); } @@ -4188,8 +3949,9 @@ final class StockLayoutCanvasController { } captureAodPackagesFromNotificationCallback( ReflectionSupport.getFieldValue(controller, "notificationCallback")); - updateAodNotificationPackageSources(container); - applyConfirmedAodPluginPolicy(container); + if (applyConfirmedAodNotificationPluginPolicy(container)) { + updateAodNotificationPackageSources(container); + } } private void installAodNotificationListenerHooks(Object controller) { @@ -4247,7 +4009,7 @@ final class StockLayoutCanvasController { } if (!isLayoutEnabled(container.getContext())) { knownAodNotificationContainers.remove(container); - LockscreenCardsNotificationIconSourceStore.clearAodSources(container); + AodNotificationIconSourceStore.clearAodSources(container); return; } boolean changed = refreshAodNotificationSources(container); @@ -4271,7 +4033,7 @@ final class StockLayoutCanvasController { continue; } if (!isLayoutEnabled(container.getContext())) { - LockscreenCardsNotificationIconSourceStore.clearAodSources(container); + AodNotificationIconSourceStore.clearAodSources(container); continue; } boolean changed = refreshAodNotificationSources(container); @@ -4289,10 +4051,10 @@ final class StockLayoutCanvasController { } boolean changed = false; if (!packages.isEmpty()) { - changed |= LockscreenCardsNotificationIconSourceStore.putPackages(container, packages); + changed |= AodNotificationIconSourceStore.putPackages(container, packages); } changed |= prepareAodNotificationIconSources(container); - changed |= LockscreenCardsNotificationIconSourceStore.putAodDrawables( + changed |= AodNotificationIconSourceStore.putAodDrawables( container, latestAodIconImageViews); return changed; @@ -4329,7 +4091,7 @@ final class StockLayoutCanvasController { private ArrayList aodNotificationPackages() { ArrayList result = new ArrayList<>(); for (StatusBarNotification sbn : latestAodNotifications) { - if (sbn != null && AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn != null && NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { result.add(sbn.getPackageName()); } } @@ -4390,7 +4152,7 @@ final class StockLayoutCanvasController { || sbn == null || sbn.getNotification() == null || sbn.getNotification().getSmallIcon() == null - || !AppIconRules.isValidPackageName(sbn.getPackageName())) { + || !NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { return null; } String cacheKey = notificationFingerprintCacheKey(sbn); @@ -4569,20 +4331,8 @@ final class StockLayoutCanvasController { if (view == null) { return; } - if (isKeyguardIconOnlyLayoutAncestor(view)) { - if (confirmedAodPluginViews.remove(view)) { - aodVisualAlphaGeneration++; - aodBeforeDrawSignatureByRoot.clear(); - } - restoreView(view); - return; - } - if (!isLayoutEnabled(view.getContext())) { - if (confirmedAodPluginViews.remove(view)) { - aodVisualAlphaGeneration++; - aodBeforeDrawSignatureByRoot.clear(); - } - restoreView(view); + if (isKeyguardIconOnlyLayoutAncestor(view) || !isLayoutEnabled(view.getContext())) { + restoreConfirmedAodPluginView(view); return; } boolean added = confirmedAodPluginViews.add(view); @@ -4594,6 +4344,42 @@ final class StockLayoutCanvasController { hideView(view, keepConfirmedAodPluginViewLaidOut(view)); } + private boolean applyConfirmedAodNotificationPluginPolicy(View view) { + if (view == null) { + return false; + } + if (isCardsNotificationScene()) { + restoreConfirmedAodPluginView(view); + return false; + } + SceneKey scene = runtimeContext.getModeStateRepository().getActiveScene(); + if (scene == null || (!scene.isAod() && !scene.isLockscreen())) { + restoreConfirmedAodPluginView(view); + return false; + } + confirmedAodNotificationPluginViews.add(view); + applyConfirmedAodPluginPolicy(view); + return true; + } + + private boolean isCardsNotificationScene() { + SceneKey scene = runtimeContext.getModeStateRepository().getActiveScene(); + return scene != null + && (scene.isAod() || scene.isLockscreen()) + && scene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS; + } + + private void restoreConfirmedAodPluginView(View view) { + boolean removed = confirmedAodPluginViews.remove(view); + removed |= confirmedAodNotificationPluginViews.remove(view); + if (removed) { + aodVisualAlphaGeneration++; + aodBeforeDrawSignatureByRoot.clear(); + } + restoreView(view); + } + + private boolean keepConfirmedAodPluginViewLaidOut(View view) { return isKeyguardIconOnlyContainerView(view) || isAodStatusbarPluginContainerView(view); } @@ -4700,17 +4486,13 @@ final class StockLayoutCanvasController { return true; } - private void restoreAllHiddenViews(View root, SceneKey activeScene) { + private void restoreAllHiddenViews() { ArrayDeque views = new ArrayDeque<>(hiddenViewStates.keySet()); while (!views.isEmpty()) { View view = views.removeFirst(); if (forgetInactiveTrackedStatusChip(view)) { continue; } - if (shouldDeferLayoutOffRestore(root, activeScene, view)) { - keepViewHidden(view); - continue; - } restoreView(view); } } @@ -4737,16 +4519,16 @@ final class StockLayoutCanvasController { statusChipLifecycleLayoutSignatureByView.remove(view); } - private void cleanupLayoutOffRoot(View root, SceneKey activeScene) { - lockscreenCardsNotificationRowFilter.restoreAll(); + private void cleanupLayoutOffRoot(View root) { if (!hiddenViewStates.isEmpty()) { - restoreAllHiddenViews(root, activeScene); + restoreAllHiddenViews(); } clearTrackedStatusChipState(); trackedLockedStatusBarIconSurfaces.clear(); lockedStatusBarIconSurfaceReadyRoots.clear(); trackedUnlockedStockSurfaces.clear(); confirmedAodPluginViews.clear(); + confirmedAodNotificationPluginViews.clear(); aodPluginVisualAlphaByView.clear(); aodBeforeDrawSignatureByRoot.clear(); aodVisualAlphaGeneration++; @@ -4755,57 +4537,26 @@ final class StockLayoutCanvasController { latestAodIconImageViews = new ArrayList<>(); latestAodNotifications = new ArrayList<>(); AodStatusbarSourceStore.clear(); - LockscreenCardsNotificationIconSourceStore.clearAodSources(); + AodNotificationIconSourceStore.clearAodSources(); aodNotificationWidgetSteadyWidths.clear(); aodNotificationIconOnlyAreaSteadyLefts.clear(); originalAodNotificationWidgetLayoutWidths.clear(); pendingUnlockedAppearanceRefreshRoots.remove(root); dirtyUnlockedLayoutRoots.remove(root); settingsIdentityByRoot.remove(root); - lockscreenCardsRowFilterSignatures.remove(root); clearUnlockedClockRefreshState(root); if (!isUnlockedStatusBarRoot(root) || !layoutOffCleanedRoots.add(root)) { unlockedHostsByRoot.remove(root); rootGeometries.remove(root); unlockedIconRenderController.clearRoot(root); - removeLockscreenCardsNotificationHost(root); - removeAodCardsNotificationHost(root); ownedIconHostManager.removeOwnedHosts(root); return; } rootGeometries.remove(root); unlockedIconRenderController.clearAll(); - removeAodCardsNotificationHost(root); ownedIconHostManager.removeOwnedHosts(root); } - private boolean shouldDeferLayoutOffRestore( - View root, - SceneKey activeScene, - View view - ) { - return shouldKeepUnlockedShadeShelfOwnedByCustomLayout(root, activeScene, view); - } - - private void keepViewHidden(View view) { - hideView(view, false); - } - - private boolean shouldKeepUnlockedShadeShelfOwnedByCustomLayout( - View root, - SceneKey activeScene, - View view - ) { - if (root == null - || activeScene == null - || !activeScene.isUnlocked() - || !isDescendantOfNotificationShadeWindow(view)) { - return false; - } - return (isCardsNotificationIconSurface(view) || isCardsNotificationShelfBackgroundSurface(view)) - && hasAncestorClass(view, "NotificationShelf"); - } - private void clearTrackedStatusChipState() { trackedStatusChipSources.clear(); statusChipContentSignatureByRoot.clear(); @@ -4827,8 +4578,6 @@ final class StockLayoutCanvasController { } private void removeSharedLayoutHosts(View root) { - removeLockscreenCardsNotificationHost(root); - removeAodCardsNotificationHost(root); ownedIconHostManager.removeOwnedHosts(root); unlockedHostsByRoot.remove(root); pendingUnlockedAppearanceRefreshRoots.remove(root); @@ -4897,296 +4646,6 @@ final class StockLayoutCanvasController { } } - private void renderLockscreenCardsNotificationStripIfNeeded( - View root, - SbtSettings settings, - SceneKey activeScene - ) { - if (root == null - || settings == null - || activeScene == null - || !activeScene.isLockscreen() - || activeScene.notificationDisplayStyle() != NotificationDisplayStyle.CARDS - || !isNotificationShadeWindowRoot(root)) { - removeLockscreenCardsNotificationHost(root); - lockscreenCardsNotificationRenderGenerationByRoot.remove(root); - return; - } - if (runtimeContext.getModeStateRepository().isSystemUiShadeLocked() - || hasVisibleLockscreenShadeHeader(root)) { - removeLockscreenCardsNotificationHost(root); - lockscreenCardsNotificationRenderGenerationByRoot.remove(root); - return; - } - View visibleBouncerSurface = findVisibleBouncerSurface(root); - if (visibleBouncerSurface != null) { - removeLockscreenCardsNotificationHost(root); - lockscreenCardsNotificationRenderGenerationByRoot.remove(root); - return; - } - View host = ownedIconHostManager.ensureLockscreenCardsNotificationHost(root); - if (host instanceof ViewGroup hostGroup) { - if (host.getVisibility() != View.VISIBLE) { - host.setVisibility(View.VISIBLE); - } - setHostAlpha(host, 1f); - int settingsId = System.identityHashCode(settings); - int rootWidth = root.getWidth(); - int rootHeight = root.getHeight(); - int activeKeyGeneration = NotificationActiveKeyStore.generation(); - int sourceSignature = - LockscreenCardsNotificationIconSourceStore.lightweightSourceSignatureForRoot(root); - int generation = settingsId; - generation = 31 * generation + rootWidth; - generation = 31 * generation + rootHeight; - generation = 31 * generation + activeKeyGeneration; - generation = 31 * generation + sourceSignature; - Integer previous = lockscreenCardsNotificationRenderGenerationByRoot.get(root); - boolean shouldRender = previous == null - || previous != generation - || hostGroup.getChildCount() <= 0; - if (shouldRender) { - lockscreenCardsNotificationRenderGenerationByRoot.put(root, generation); - lockscreenCardsNotificationStripRenderer.render(root, hostGroup, settings, activeScene); - } - bringToFrontIfNeeded(host); - } - } - - private boolean hasVisibleLockscreenShadeHeader(View root) { - if (root == null || !isNotificationShadeWindowRoot(root)) { - return false; - } - final boolean[] found = {false}; - walkTree(root, view -> { - if (found[0] || !(view instanceof TextView textView)) { - return; - } - if (!textView.isShown() || textView.getAlpha() <= 0f) { - return; - } - String idName = ViewIdNames.idName(textView); - String className = textView.getClass().getName(); - if ("header_clock".equals(idName) || className.contains("QSClockHeaderView")) { - found[0] = true; - } - }); - return found[0]; - } - - private void renderAodCardsNotificationStripIfNeeded( - View root, - SbtSettings settings, - SceneKey activeScene - ) { - if (root == null - || settings == null - || activeScene == null - || !activeScene.isAod() - || activeScene.notificationDisplayStyle() != NotificationDisplayStyle.CARDS) { - removeAodCardsNotificationHost(root); - return; - } - View host = ownedIconHostManager.ensureAodCardsNotificationHost(root); - if (host instanceof ViewGroup hostGroup) { - int generation = System.identityHashCode(settings); - generation = 31 * generation + root.getWidth(); - generation = 31 * generation + root.getHeight(); - generation = 31 * generation + aodNotificationSourceGeneration; - generation = 31 * generation + latestAodIconImageViews.size(); - generation = 31 * generation + latestAodNotifications.size(); - Bounds sourceBounds = LockscreenCardsNotificationIconSourceStore - .sourceContainerBoundsForRoot(root); - boolean hiddenSource = LockscreenCardsNotificationIconSourceStore - .sourceContainerHasHiddenAncestorForRoot(root); - if (hiddenSource) { - // Samsung hides the cards icon source during the clock/date handoff. - // Keep our mirror hidden too instead of following its transient translation. - setHostAlpha(host, 0f); - return; - } - generation = 31 * generation + (sourceBounds != null ? sourceBounds.signature() : 0); - Integer previous = aodCardsNotificationRenderGenerationByRoot.get(root); - boolean dirty = dirtyUnlockedLayoutRoots.contains(root); - boolean shouldRender = previous == null - || previous != generation - || dirty - || hostGroup.getChildCount() <= 0; - if (shouldRender) { - aodCardsNotificationRenderGenerationByRoot.put(root, generation); - lockscreenCardsNotificationStripRenderer.render(root, hostGroup, settings, activeScene); - } - setHostAlpha(host, aodVisualAlphaForRoot(root)); - bringToFrontIfNeeded(host); - } - } - - private void bringToFrontIfNeeded(View view) { - if (view == null || !(view.getParent() instanceof ViewGroup group)) { - return; - } - int childCount = group.getChildCount(); - if (childCount <= 0 || group.getChildAt(childCount - 1) == view) { - return; - } - view.bringToFront(); - } - - private void applyLockscreenCardsNotificationRowFilter(ViewGroup stack, boolean allowAfterKeyguardUnlock) { - if (stack == null) { - return; - } - if (runtimeContext.getModeStateRepository().isSystemUiShadeLocked()) { - lockscreenCardsNotificationRowFilter.restoreAll(); - return; - } - lockscreenCardsNotificationRowFilter.apply(stack, allowAfterKeyguardUnlock); - } - - private void applyLockscreenCardsNotificationRowFilterRow(View row, boolean allowAfterKeyguardUnlock) { - if (row == null) { - return; - } - if (runtimeContext.getModeStateRepository().isSystemUiShadeLocked()) { - lockscreenCardsNotificationRowFilter.restoreRemovedRow(row); - return; - } - lockscreenCardsNotificationRowFilter.applyRow(row, allowAfterKeyguardUnlock); - } - - private boolean applyLockscreenCardsNotificationRowFilterInTreeIfNeeded( - View root, - SbtSettings settings, - SceneKey activeScene, - boolean allowAfterKeyguardUnlock) { - int signature = lockscreenCardsRowFilterSignature(root, settings, activeScene); - Integer previous = lockscreenCardsRowFilterSignatures.put(root, signature); - if (previous != null && previous == signature) { - return false; - } - applyLockscreenCardsNotificationRowFilterInTree(root, allowAfterKeyguardUnlock); - return true; - } - - private int lockscreenCardsRowFilterSignature( - View root, - SbtSettings settings, - SceneKey activeScene) { - int result = 17; - result = 31 * result + System.identityHashCode(settings); - result = 31 * result + (activeScene != null ? activeScene.hashCode() : 0); - result = 31 * result - + (runtimeContext.getModeStateRepository().isSystemUiShadeLocked() ? 1 : 0); - result = 31 * result + root.getWidth(); - result = 31 * result + root.getHeight(); - return result; - } - - private void applyLockscreenCardsNotificationRowFilterInTree(View root, boolean allowAfterKeyguardUnlock) { - if (!(root instanceof ViewGroup group)) { - return; - } - ArrayDeque queue = new ArrayDeque<>(); - queue.add(group); - while (!queue.isEmpty()) { - View view = queue.removeFirst(); - if (view instanceof ViewGroup viewGroup) { - if (viewGroup.getClass().getName().contains("NotificationStackScrollLayout")) { - applyLockscreenCardsNotificationRowFilter(viewGroup, allowAfterKeyguardUnlock); - return; - } - for (int i = 0; i < viewGroup.getChildCount(); i++) { - View child = viewGroup.getChildAt(i); - if (child != null) { - queue.addLast(child); - } - } - } - } - } - - private View findVisibleBouncerSurface(View root) { - if (root == null) { - return null; - } - ArrayDeque queue = new ArrayDeque<>(); - queue.add(root); - while (!queue.isEmpty()) { - View view = queue.removeFirst(); - if (view != root && isVisibleBouncerSurface(view)) { - return view; - } - if (view instanceof ViewGroup group) { - for (int i = 0; i < group.getChildCount(); i++) { - View child = group.getChildAt(i); - if (child != null) { - queue.addLast(child); - } - } - } - } - return null; - } - - private boolean isVisibleBouncerSurface(View view) { - if (view == null || view.getVisibility() != View.VISIBLE || view.getAlpha() <= 0f) { - return false; - } - if (view.getWidth() <= 0 || view.getHeight() <= 0) { - return false; - } - String idName = ViewIdNames.idName(view).toLowerCase(Locale.ROOT); - String className = view.getClass().getName().toLowerCase(Locale.ROOT); - return idName.contains("bouncer") - || idName.contains("keyguard_security") - || idName.contains("keyguard_pin") - || idName.contains("keyguard_password") - || idName.contains("keyguard_pattern") - || className.contains("bouncer") - || className.contains("keyguardsecurity") - || className.contains("keyguardpin") - || className.contains("keyguardpassword") - || className.contains("keyguardpattern"); - } - - private void hideLockscreenCardsNotificationHost(View root) { - View host = root instanceof ViewGroup group - ? findDirectOwnedHost(group, OwnedIconHostManager.TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST) - : null; - if (host == null) { - return; - } - if (host.getVisibility() != View.INVISIBLE) { - host.setVisibility(View.INVISIBLE); - } - setHostAlpha(host, 0f); - } - - private void removeLockscreenCardsNotificationHost(View root) { - View host = root instanceof ViewGroup group - ? findDirectOwnedHost(group, OwnedIconHostManager.TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST) - : null; - if (host == null) { - return; - } - lockscreenCardsNotificationRenderGenerationByRoot.remove(root); - if (host instanceof ViewGroup hostGroup) { - lockscreenCardsNotificationStripRenderer.clear(hostGroup); - } - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST); - } - - private void removeAodCardsNotificationHost(View root) { - View host = root instanceof ViewGroup group - ? findDirectOwnedHost(group, OwnedIconHostManager.TAG_AOD_CARDS_NOTIFICATION_HOST) - : null; - if (host instanceof ViewGroup hostGroup) { - lockscreenCardsNotificationStripRenderer.clear(hostGroup); - } - aodCardsNotificationRenderGenerationByRoot.remove(root); - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_AOD_CARDS_NOTIFICATION_HOST); - } - private View findDirectOwnedHost(ViewGroup root, String tag) { if (root == null || tag == null) { return null; @@ -5238,7 +4697,6 @@ final class StockLayoutCanvasController { pendingUnlockedAppearanceRefreshRoots.remove(root); dirtyUnlockedLayoutRoots.remove(root); settingsIdentityByRoot.remove(root); - lockscreenCardsRowFilterSignatures.remove(root); clearUnlockedClockRefreshState(root); return null; } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/notifications/NotificationUnreadTracker.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/notifications/NotificationUnreadTracker.java index 6fa6168..b3ef7ca 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/notifications/NotificationUnreadTracker.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/notifications/NotificationUnreadTracker.java @@ -9,7 +9,6 @@ import java.util.Objects; import java.util.Set; import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; public final class NotificationUnreadTracker { private static final HashMap STATE_BY_KEY = new HashMap<>(); @@ -31,7 +30,7 @@ public final class NotificationUnreadTracker { } public static synchronized boolean record(StatusBarNotification sbn) { - if (sbn == null || !AppIconRules.isValidPackageName(sbn.getPackageName())) { + if (sbn == null || !NotificationKeyReflection.isValidPackageName(sbn.getPackageName())) { return false; } String key = sbn.getKey(); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationIconSourceStore.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java similarity index 55% rename from app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationIconSourceStore.java rename to app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java index 38fdba2..398f359 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationIconSourceStore.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java @@ -6,21 +6,15 @@ import android.widget.ImageView; import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.IdentityHashMap; -import java.util.Locale; import java.util.Set; import java.util.WeakHashMap; import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection; import se.ajpanton.statusbartweak.runtime.ViewIdNames; -import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; import se.ajpanton.statusbartweak.runtime.layoutsolver.StatusBarLayoutSolver.Bounds; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; -public final class LockscreenCardsNotificationIconSourceStore { - private static final WeakHashMap> SOURCES_BY_CONTAINER = - new WeakHashMap<>(); +public final class AodNotificationIconSourceStore { private static final WeakHashMap> PACKAGES_BY_CONTAINER = new WeakHashMap<>(); private static final WeakHashMap> AOD_DRAWABLES_BY_CONTAINER = @@ -29,36 +23,7 @@ public final class LockscreenCardsNotificationIconSourceStore { private static final int VIRTUAL_ICON_SIZE_PX = 39; private static int generation; - private LockscreenCardsNotificationIconSourceStore() { - } - - public static void put(ViewGroup container, ArrayList sources) { - if (container == null || sources == null || sources.isEmpty()) { - if (container != null) { - if (SOURCES_BY_CONTAINER.remove(container) != null) { - bumpGeneration(); - } - } - return; - } - ArrayList attached = new ArrayList<>(); - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - for (SourceEntry source : sources) { - if (source == null || source.view == null || !seen.add(source.view)) { - continue; - } - attached.add(source); - } - if (attached.isEmpty()) { - if (SOURCES_BY_CONTAINER.remove(container) != null) { - bumpGeneration(); - } - } else if (!sameSourceEntries(SOURCES_BY_CONTAINER.get(container), attached)) { - SOURCES_BY_CONTAINER.put(container, attached); - bumpGeneration(); - } else { - SOURCES_BY_CONTAINER.put(container, attached); - } + private AodNotificationIconSourceStore() { } public static boolean putPackages(ViewGroup container, ArrayList packages) { @@ -75,7 +40,7 @@ public final class LockscreenCardsNotificationIconSourceStore { ArrayList valid = new ArrayList<>(); boolean hasValid = false; for (String pkg : packages) { - if (AppIconRules.isValidPackageName(pkg)) { + if (NotificationKeyReflection.isValidPackageName(pkg)) { valid.add(pkg); hasValid = true; } else { @@ -164,7 +129,8 @@ public final class LockscreenCardsNotificationIconSourceStore { AOD_NOTIFICATION_PACKAGES.clear(); if (packages != null && !packages.isEmpty()) { for (String pkg : packages) { - if (AppIconRules.isValidPackageName(pkg) && !AOD_NOTIFICATION_PACKAGES.contains(pkg)) { + if (NotificationKeyReflection.isValidPackageName(pkg) + && !AOD_NOTIFICATION_PACKAGES.contains(pkg)) { AOD_NOTIFICATION_PACKAGES.add(pkg); } } @@ -182,48 +148,6 @@ public final class LockscreenCardsNotificationIconSourceStore { generation++; } - private static boolean sameSourceEntries( - ArrayList previous, - ArrayList current - ) { - if (previous == current) { - return true; - } - if (previous == null || current == null || previous.size() != current.size()) { - return false; - } - for (int i = 0; i < previous.size(); i++) { - SourceEntry oldEntry = previous.get(i); - SourceEntry newEntry = current.get(i); - if (oldEntry == newEntry) { - continue; - } - if (oldEntry == null || newEntry == null) { - return false; - } - if (oldEntry.view != newEntry.view) { - return false; - } - if (oldEntry.key == null ? newEntry.key != null : !oldEntry.key.equals(newEntry.key)) { - return false; - } - } - return true; - } - - public static int lightweightSourceSignatureForRoot(View root) { - int result = 17; - result = 31 * result + generation(); - ViewGroup container = sourceContainerForRoot(root); - Bounds bounds = sourceBoundsRelativeTo(root, container); - if (isZeroSizeDotContainer(container, bounds)) { - bounds = new Bounds(bounds.left, bounds.top, VIRTUAL_ICON_SIZE_PX, VIRTUAL_ICON_SIZE_PX); - } - result = 31 * result + (bounds != null ? bounds.signature() : 0); - result = 31 * result + (sourceContainerHasHiddenAncestor(root, container) ? 1 : 0); - return result; - } - private static boolean sameViews(ArrayList previous, ArrayList current) { if (previous == current) { return true; @@ -259,33 +183,6 @@ public final class LockscreenCardsNotificationIconSourceStore { return result; } } - ArrayList views = SOURCES_BY_CONTAINER.get(container); - if (views != null && !views.isEmpty()) { - int skipCards = visibleShelfStartIndex(container, views); - HashSet visibleCardKeys = visibleCardKeys(root, container); - for (int i = 0; i < views.size(); i++) { - if (i < skipCards) { - continue; - } - SourceEntry entry = views.get(i); - if (entry.key != null && visibleCardKeys.contains(entry.key)) { - continue; - } - View view = entry.view; - if (view == null || !view.isAttachedToWindow()) { - continue; - } - int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth(); - int height = view.getHeight() > 0 ? view.getHeight() : view.getMeasuredHeight(); - if (width <= 0 || height <= 0) { - continue; - } - result.add(new SnapshotSource(view, SnapshotMode.NOTIFICATION_DRAWABLE, entry.key)); - } - } - if (!result.isEmpty()) { - return result; - } ArrayList packages = PACKAGES_BY_CONTAINER.get(container); if (packages != null) { Bounds containerBounds = sourceBoundsRelativeTo(root, container); @@ -293,7 +190,7 @@ public final class LockscreenCardsNotificationIconSourceStore { int size = VIRTUAL_ICON_SIZE_PX; for (int i = 0; i < packages.size(); i++) { String pkg = packages.get(i); - if (!AppIconRules.isValidPackageName(pkg)) { + if (!NotificationKeyReflection.isValidPackageName(pkg)) { continue; } result.add(new SnapshotSource( @@ -309,7 +206,7 @@ public final class LockscreenCardsNotificationIconSourceStore { private static String aodDrawableKey(ArrayList packages, int index, View view) { if (packages != null && index >= 0 && index < packages.size()) { String pkg = packages.get(index); - if (AppIconRules.isValidPackageName(pkg)) { + if (NotificationKeyReflection.isValidPackageName(pkg)) { return pkg + "@aod" + index; } } @@ -406,10 +303,6 @@ public final class LockscreenCardsNotificationIconSourceStore { if (container != null) { return container; } - container = sourceContainerForRoot(root, SOURCES_BY_CONTAINER.keySet()); - if (container != null) { - return container; - } return sourceContainerForRoot(root, PACKAGES_BY_CONTAINER.keySet()); } @@ -433,26 +326,6 @@ public final class LockscreenCardsNotificationIconSourceStore { return bounds; } - public static boolean sourceContainerHasHiddenAncestorForRoot(View root) { - ViewGroup container = sourceContainerForRoot(root); - return sourceContainerHasHiddenAncestor(root, container); - } - - private static boolean sourceContainerHasHiddenAncestor(View root, ViewGroup container) { - if (container == null) { - return false; - } - View current = container; - while (current != null && current != root) { - if (current.getVisibility() != View.VISIBLE) { - return true; - } - Object parent = current.getParent(); - current = parent instanceof View ? (View) parent : null; - } - return current != root; - } - public static Bounds sourceContainerBoundsForAodIconsRoot(View root) { ViewGroup container = sourceContainerForAodIconsRoot(root); Bounds bounds = sourceBoundsRelativeTo(root, container); @@ -538,182 +411,7 @@ public final class LockscreenCardsNotificationIconSourceStore { } private static boolean hasSources(ViewGroup container) { - return SOURCES_BY_CONTAINER.containsKey(container) - || AOD_DRAWABLES_BY_CONTAINER.containsKey(container) + return AOD_DRAWABLES_BY_CONTAINER.containsKey(container) || PACKAGES_BY_CONTAINER.containsKey(container); } - - private static HashSet visibleCardKeys(View root, View shelf) { - HashSet result = new HashSet<>(); - if (!(root instanceof ViewGroup group)) { - return result; - } - int shelfTop = Integer.MAX_VALUE; - if (shelf != null) { - Bounds shelfBounds = ViewGeometry.boundsRelativeTo(root, shelf); - if (shelfBounds != null) { - shelfTop = shelfBounds.top; - } - } - ArrayList stack = new ArrayList<>(); - stack.add(group); - for (int i = 0; i < stack.size(); i++) { - View view = stack.get(i); - if (isNotificationRow(view) && isVisibleCardRow(view)) { - Bounds rowBounds = ViewGeometry.boundsRelativeTo(root, view); - if (rowBounds != null && rowBounds.top < shelfTop) { - String key = keyForRow(view); - if (key != null && !key.isEmpty()) { - result.add(key); - } - } - } - if (view instanceof ViewGroup viewGroup) { - for (int child = 0; child < viewGroup.getChildCount(); child++) { - View childView = viewGroup.getChildAt(child); - if (childView != null) { - stack.add(childView); - } - } - } - } - return result; - } - - private static int visibleShelfStartIndex(ViewGroup container, ArrayList entries) { - if (container == null || entries == null || entries.isEmpty()) { - return 0; - } - ArrayList visibleShelfIcons = visibleShelfIcons(container); - for (View icon : visibleShelfIcons) { - String key = NotificationKeyReflection.keyForIconView(icon); - for (int i = 0; i < entries.size(); i++) { - SourceEntry entry = entries.get(i); - if (entry == null) { - continue; - } - if (entry.view == icon) { - return i; - } - if (key != null && entry.key != null && key.equals(entry.key)) { - return i; - } - } - } - return 0; - } - - private static ArrayList visibleShelfIcons(ViewGroup container) { - ArrayList result = new ArrayList<>(); - ArrayList stack = new ArrayList<>(); - stack.add(container); - for (int i = 0; i < stack.size(); i++) { - View view = stack.get(i); - if (view != container && isVisibleShelfIcon(view)) { - result.add(view); - continue; - } - if (view instanceof ViewGroup group) { - for (int child = 0; child < group.getChildCount(); child++) { - View childView = group.getChildAt(child); - if (childView != null) { - stack.add(childView); - } - } - } - } - return result; - } - - private static boolean isVisibleShelfIcon(View view) { - if (view == null || view.getVisibility() != View.VISIBLE) { - return false; - } - if (isOverflowDotCandidate(view)) { - return false; - } - int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth(); - int height = view.getHeight() > 0 ? view.getHeight() : view.getMeasuredHeight(); - if (width <= 0 || height <= 0) { - return false; - } - String className = view.getClass().getName(); - return className.contains("StatusBarIconView") - || className.contains("IconView") - || view instanceof android.widget.ImageView; - } - - private static boolean isOverflowDotCandidate(View view) { - String idName = ViewIdNames.idName(view).toLowerCase(Locale.ROOT); - String className = view.getClass().getName().toLowerCase(Locale.ROOT); - return idName.contains("overflow") - || idName.contains("dot") - || className.contains("overflow") - || className.contains("dot"); - } - - public static SourceEntry source(View view, String key) { - return new SourceEntry(view, key); - } - - private static String keyForRow(View view) { - Object entry = NotificationKeyReflection.primaryEntryForRow(view); - String key = NotificationKeyReflection.keyForEntry(entry); - if (key != null && !key.isEmpty()) { - return key; - } - return NotificationKeyReflection.keyForIconView(view); - } - - private static boolean isNotificationRow(View view) { - if (view == null) { - return false; - } - String className = view.getClass().getName(); - return className.contains("ExpandableNotificationRow"); - } - - private static boolean isVisibleCardRow(View view) { - if (view == null || view.getVisibility() == View.GONE) { - return false; - } - if (!view.isShown() || ViewGeometry.effectiveAlpha(view) <= 0.05f) { - return false; - } - if (ReflectionSupport.getBooleanField(view, "mInShelf", false) - || ReflectionSupport.getBooleanField(view, "mTransformingInShelf", false)) { - return false; - } - Object viewState = ReflectionSupport.getFieldValue(view, "mViewState"); - if (viewState != null - && (ReflectionSupport.getBooleanField(viewState, "hidden", false) - || ReflectionSupport.getBooleanField(viewState, "gone", false))) { - return false; - } - int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth(); - int height = view.getHeight() > 0 ? view.getHeight() : view.getMeasuredHeight(); - return width > 0 && height > 0 && actualHeight(view, height) > 0; - } - - private static int actualHeight(View view, int fallback) { - Object methodValue = ReflectionSupport.invokeMethod(view, "getActualHeight"); - if (methodValue instanceof Integer integer && integer > 0) { - return integer; - } - Object fieldValue = ReflectionSupport.getFieldValue(view, "mActualHeight"); - if (fieldValue instanceof Integer integer && integer > 0) { - return integer; - } - return fallback; - } - - public static final class SourceEntry { - final View view; - final String key; - - private SourceEntry(View view, String key) { - this.view = view; - this.key = key; - } - } } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/DebugBoundsOverlayController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/DebugBoundsOverlayController.java index 2fce871..fff6a3a 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/DebugBoundsOverlayController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/DebugBoundsOverlayController.java @@ -250,15 +250,15 @@ public final class DebugBoundsOverlayController { && scene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { return null; } - return LockscreenCardsNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root); + return AodNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root); } private ViewGroup aodNotificationContainer(View root, SceneKey scene) { if (scene != null && scene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { - return LockscreenCardsNotificationIconSourceStore.sourceContainerForRoot(root); + return AodNotificationIconSourceStore.sourceContainerForRoot(root); } - return LockscreenCardsNotificationIconSourceStore.sourceContainerForAodIconsRoot(root); + return AodNotificationIconSourceStore.sourceContainerForAodIconsRoot(root); } private boolean isUsableAodAnchor(View root, Bounds bounds) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationStripRenderer.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationStripRenderer.java deleted file mode 100644 index cfd66e8..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/LockscreenCardsNotificationStripRenderer.java +++ /dev/null @@ -1,607 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.render; - -import android.graphics.Color; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.GradientDrawable; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Locale; -import java.util.WeakHashMap; - -import se.ajpanton.statusbartweak.runtime.ViewIdNames; -import se.ajpanton.statusbartweak.runtime.layoutsolver.StatusBarLayoutSolver.Bounds; -import se.ajpanton.statusbartweak.runtime.mode.NotificationDisplayStyle; -import se.ajpanton.statusbartweak.runtime.mode.SceneKey; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -/** - * Mirrors Samsung's cards-mode shelf/icon-only notification strip into an owned - * host. The stock shelf already represents notifications not currently shown as - * cards, so this renderer treats it as the source list and only owns placement. - */ -public final class LockscreenCardsNotificationStripRenderer { - private static final int DEFAULT_PILL_COLOR = 0xAA202124; - private static final String PILL_BACKGROUND_TAG = "statusbartweak.cards.notification.pill"; - - private final SnapshotRenderer renderer = new SnapshotRenderer(false, false, false); - private final WeakHashMap> pillViewsByHost = new WeakHashMap<>(); - private final WeakHashMap aodInitialStatusbarHeightByRoot = new WeakHashMap<>(); - private final NotificationSeenAppReporter seenAppReporter = new NotificationSeenAppReporter(); - - public RenderResult render( - View root, - ViewGroup host, - SbtSettings settings, - SceneKey scene - ) { - if (root != null && (scene == null || !scene.isAod())) { - aodInitialStatusbarHeightByRoot.remove(root); - } - if (root == null - || host == null - || settings == null - || scene == null - || scene.notificationDisplayStyle() != NotificationDisplayStyle.CARDS - || !(scene.isLockscreen() || scene.isAod()) - || maxRows(settings, scene) <= 0) { - clear(host); - return RenderResult.empty(); - } - ViewGroup sourceRoot = scene.isAod() - ? LockscreenCardsNotificationIconSourceStore.sourceContainerForRoot(root) - : findSourceRoot(root); - if (sourceRoot == null && scene.isAod()) { - sourceRoot = findSourceRoot(root); - } - if (sourceRoot == null && !scene.isAod()) { - clear(host); - return RenderResult.empty(); - } - if (!scene.isAod() && hasHiddenShelfAncestor(sourceRoot, root)) { - clear(host); - return RenderResult.empty(); - } - if (sourceRoot != null) { - syncHostAnimation(host, sourceRoot); - } - ArrayList sources = scene.isAod() - ? LockscreenCardsNotificationIconSourceStore.snapshotSourcesForRoot(root) - : new ArrayList<>(); - if (sources.isEmpty() && sourceRoot != null) { - sources = LockscreenCardsNotificationIconSourceStore.snapshotSources(sourceRoot, root); - } - if (sources.isEmpty() && sourceRoot != null) { - sources = collectSources(sourceRoot); - } - if (sources.isEmpty()) { - clear(host); - return RenderResult.empty(); - } - ArrayList unfilteredPlacements = renderer.rawPlacements(root, sources); - seenAppReporter.report(root.getContext(), unfilteredPlacements); - ArrayList placements = SnapshotIconFilter.notificationPlacements( - unfilteredPlacements, - settings, - scene); - Bounds sourceBounds = scene.isAod() - ? LockscreenCardsNotificationIconSourceStore.sourceContainerBoundsForRoot(root) - : null; - if (sourceBounds == null && sourceRoot != null) { - sourceBounds = ViewGeometry.boundsRelativeTo(root, sourceRoot); - } - int statusbarHeight = statusbarHeight(root, sourceBounds, scene); - int iconHeight = iconHeightPx( - statusbarHeight, - cardsIconHeightSteps(settings, scene), - representativeHeight(placements)); - StripLayout layout = layoutPlacements(root, sourceBounds, placements, settings, scene, iconHeight); - if (scene.isAod()) { - clearPills(host); - } else { - renderPills(host, layout.rowBounds, - sourceRoot != null ? resolvePillColor(sourceRoot) : DEFAULT_PILL_COLOR); - } - Bounds renderedBounds = renderer.renderPlacements(host, layout.placements); - return new RenderResult(sourceRoot, renderedBounds); - } - - public void clear(ViewGroup host) { - renderer.clear(host); - clearPills(host); - } - - private ViewGroup findSourceRoot(View root) { - if (!(root instanceof ViewGroup group)) { - return null; - } - ArrayDeque queue = new ArrayDeque<>(); - queue.add(group); - ViewGroup shelf = null; - ViewGroup iconOnly = null; - while (!queue.isEmpty()) { - View view = queue.removeFirst(); - if (view instanceof ViewGroup candidate) { - if (isShelfIconContainer(candidate)) { - shelf = candidate; - } else if (isIconOnlyContainer(candidate) && iconOnly == null) { - iconOnly = candidate; - } - for (int i = 0; i < candidate.getChildCount(); i++) { - View child = candidate.getChildAt(i); - if (child != null) { - queue.addLast(child); - } - } - } - } - return shelf != null ? shelf : iconOnly; - } - - private boolean hasHiddenShelfAncestor(View sourceRoot, View root) { - Object current = sourceRoot != null ? sourceRoot.getParent() : null; - while (current instanceof View currentView) { - if (currentView == root) { - return false; - } - if (currentView.getClass().getName().contains("NotificationShelf")) { - return currentView.getVisibility() != View.VISIBLE || currentView.getAlpha() <= 0f; - } - current = currentView.getParent(); - } - return false; - } - - private void syncHostAnimation(ViewGroup host, View sourceRoot) { - if (host == null || sourceRoot == null) { - return; - } - float alpha = ViewGeometry.effectiveAncestorAlpha(sourceRoot); - if (host.getAlpha() != alpha) { - host.setAlpha(alpha); - } - } - - private ArrayList collectSources(ViewGroup sourceRoot) { - ArrayList result = new ArrayList<>(); - ArrayDeque queue = new ArrayDeque<>(); - queue.add(sourceRoot); - while (!queue.isEmpty()) { - View view = queue.removeFirst(); - if (view != sourceRoot && isNotificationIconCandidate(view)) { - result.add(new SnapshotSource(view, SnapshotMode.NOTIFICATION_DRAWABLE)); - continue; - } - if (view instanceof ViewGroup group) { - for (int i = 0; i < group.getChildCount(); i++) { - View child = group.getChildAt(i); - if (child != null) { - queue.addLast(child); - } - } - } - } - return result; - } - - private StripLayout layoutPlacements( - View root, - Bounds sourceBounds, - ArrayList placements, - SbtSettings settings, - SceneKey scene, - int iconHeight - ) { - ArrayList result = new ArrayList<>(); - ArrayList rowBounds = new ArrayList<>(); - if (placements == null || placements.isEmpty()) { - return new StripLayout(result, rowBounds); - } - int maxPerRow = Math.max(1, maxIconsPerRow(settings, scene)); - int maxRows = Math.max(0, maxRows(settings, scene)); - int capacity = maxPerRow * maxRows; - if (capacity <= 0) { - return new StripLayout(result, rowBounds); - } - boolean showDot = placements.size() > capacity; - int iconSlots = showDot ? Math.max(0, capacity - 1) : Math.min(capacity, placements.size()); - int visible = iconSlots + (showDot ? 1 : 0); - int iconWidth = iconHeight; - int top = sourceBounds != null ? sourceBounds.top : placements.get(0).bounds.top; - int centerX = sourceBounds != null - ? sourceBounds.left + sourceBounds.width / 2 - : root.getWidth() / 2; - int availableWidth = limitToWidth(settings, scene) - ? Math.max(0, root.getWidth()) - : Integer.MAX_VALUE; - int index = 0; - int[] rowCounts = rowCounts(visible, maxPerRow, maxRows, evenDistribution(settings, scene)); - int dotColor = dotColor(placements); - int rowGap = dp(root, 8); - for (int row = 0; row < rowCounts.length && index < visible; row++) { - int count = rowCounts[row]; - if (count <= 0) { - continue; - } - int rowWidth = count * iconWidth; - int left = centerX - rowWidth / 2; - if (availableWidth != Integer.MAX_VALUE) { - left = Math.max(0, Math.min(left, Math.max(0, availableWidth - rowWidth))); - } - int y = top + row * (iconHeight + rowGap); - rowBounds.add(new Bounds(left, y, rowWidth, iconHeight)); - for (int col = 0; col < count && index < visible; col++, index++) { - boolean dotSlot = showDot && index == visible - 1; - SnapshotPlacement placement = dotSlot - ? dotPlacement(iconWidth, iconHeight, dotColor) - : placements.get(index); - result.add(new SnapshotPlacement( - placement.source, - new Bounds(left + col * iconWidth, y, iconWidth, iconHeight), - placement.key, - placement.signal, - placement.overflowDot, - placement.overflowDotColor, - placement.heldSignal, - new Bounds(0, 0, iconWidth, iconHeight), - 0)); - } - } - return new StripLayout(result, rowBounds); - } - - private int maxIconsPerRow(SbtSettings settings, SceneKey scene) { - return scene != null && scene.isAod() - ? settings.cardsAodMaxIconsPerRow - : settings.cardsLockMaxIconsPerRow; - } - - private int maxRows(SbtSettings settings, SceneKey scene) { - return scene != null && scene.isAod() - ? settings.cardsAodMaxRows - : settings.cardsLockMaxRows; - } - - private boolean evenDistribution(SbtSettings settings, SceneKey scene) { - return scene != null && scene.isAod() - ? settings.cardsAodEvenDistribution - : settings.cardsLockEvenDistribution; - } - - private boolean limitToWidth(SbtSettings settings, SceneKey scene) { - return scene != null && scene.isAod() - ? settings.cardsAodLimitToWidth - : settings.cardsLockLimitToWidth; - } - - private int[] rowCounts( - int slots, - int maxPerRow, - int maxRows, - boolean evenDistribution - ) { - if (slots <= 0 || maxPerRow <= 0 || maxRows <= 0) { - return new int[0]; - } - int rowCount = Math.min(maxRows, (slots + maxPerRow - 1) / maxPerRow); - int[] result = new int[rowCount]; - if (evenDistribution && rowCount > 1) { - int base = slots / rowCount; - int remainder = slots % rowCount; - for (int row = 0; row < rowCount; row++) { - result[row] = base + (row < remainder ? 1 : 0); - } - return result; - } - int remaining = slots; - for (int row = 0; row < rowCount; row++) { - result[row] = Math.min(maxPerRow, remaining); - remaining -= result[row]; - } - return result; - } - - private SnapshotPlacement dotPlacement(int width, int height, int color) { - return new SnapshotPlacement( - null, - new Bounds(0, 0, Math.max(1, width), Math.max(1, height)), - SnapshotKeys.OVERFLOW_DOT + ":cards_notifications", - false, - true, - color, - null, - new Bounds(0, 0, Math.max(1, width), Math.max(1, height)), - 0); - } - - private int dotColor(ArrayList placements) { - if (placements != null) { - for (SnapshotPlacement placement : placements) { - if (placement == null || placement.source == null) { - continue; - } - int color = SnapshotAppearanceSignature.preferredColor(placement.source.view(), Color.TRANSPARENT); - if (Color.alpha(color) != 0) { - return color; - } - } - } - return Color.WHITE; - } - - private void renderPills(ViewGroup host, ArrayList rowBounds, int color) { - if (host == null || rowBounds == null || rowBounds.isEmpty()) { - clearPills(host); - return; - } - ArrayList pills = pillViewsByHost.get(host); - if (pills == null) { - pills = new ArrayList<>(); - pillViewsByHost.put(host, pills); - } - while (pills.size() < rowBounds.size()) { - View pill = new View(host.getContext()); - pill.setTag(PILL_BACKGROUND_TAG); - pill.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - pills.add(pill); - } - int horizontalPadding = dp(host, 8); - int verticalPadding = dp(host, 3); - for (int i = 0; i < pills.size(); i++) { - View pill = pills.get(i); - if (i >= rowBounds.size()) { - if (pill.getParent() == host) { - host.removeView(pill); - } - continue; - } - Bounds row = rowBounds.get(i); - int left = row.left - horizontalPadding; - int top = row.top - verticalPadding; - int width = Math.max(1, row.width + horizontalPadding * 2); - int height = Math.max(1, row.height + verticalPadding * 2); - GradientDrawable background = new GradientDrawable(); - background.setColor(color); - background.setCornerRadius(height / 2f); - pill.setBackground(background); - if (pill.getParent() != host) { - host.addView(pill, Math.min(i, host.getChildCount())); - } else { - host.removeView(pill); - host.addView(pill, Math.min(i, host.getChildCount())); - } - if (applyPillLayoutParamsIfChanged(host, pill, left, top, width, height)) { - host.requestLayout(); - } - if (pill.getVisibility() != View.VISIBLE) { - pill.setVisibility(View.VISIBLE); - } - if (pill.getAlpha() != 1f) { - pill.setAlpha(1f); - } - if (pill.getLeft() != left - || pill.getTop() != top - || pill.getRight() != left + width - || pill.getBottom() != top + height) { - pill.layout(left, top, left + width, top + height); - } - } - host.invalidate(); - } - - private void clearPills(ViewGroup host) { - if (host == null) { - return; - } - ArrayList pills = pillViewsByHost.remove(host); - if (pills == null) { - return; - } - for (View pill : pills) { - if (pill != null && pill.getParent() == host) { - host.removeView(pill); - } - } - host.invalidate(); - } - - private int resolvePillColor(View sourceRoot) { - View backgroundSource = findShelfBackground(sourceRoot); - int color = backgroundColor(backgroundSource); - if (Color.alpha(color) != 0) { - return color; - } - color = backgroundColor(sourceRoot); - return Color.alpha(color) != 0 ? color : DEFAULT_PILL_COLOR; - } - - private View findShelfBackground(View root) { - if (!(root instanceof ViewGroup group)) { - return null; - } - ArrayDeque queue = new ArrayDeque<>(); - queue.add(group); - while (!queue.isEmpty()) { - View view = queue.removeFirst(); - String className = view.getClass().getName(); - String idName = ViewIdNames.idName(view); - if (className.contains("NotificationShelfBackground") - || idName.toLowerCase(Locale.ROOT).contains("background")) { - return view; - } - if (view instanceof ViewGroup childGroup) { - for (int i = 0; i < childGroup.getChildCount(); i++) { - View child = childGroup.getChildAt(i); - if (child != null) { - queue.addLast(child); - } - } - } - } - return null; - } - - private int backgroundColor(View view) { - if (view == null) { - return Color.TRANSPARENT; - } - Drawable background = view.getBackground(); - if (background instanceof ColorDrawable colorDrawable) { - return colorDrawable.getColor(); - } - return Color.TRANSPARENT; - } - - private int dp(View view, int value) { - float density = view.getResources().getDisplayMetrics().density; - return Math.max(0, Math.round(value * density)); - } - - private boolean applyPillLayoutParamsIfChanged( - ViewGroup host, - View pill, - int left, - int top, - int width, - int height - ) { - ViewGroup.LayoutParams current = pill.getLayoutParams(); - if (current != null - && current.width == width - && current.height == height - && current instanceof ViewGroup.MarginLayoutParams marginParams - && marginParams.leftMargin == left - && marginParams.topMargin == top) { - return false; - } - pill.setLayoutParams(layoutParamsFor(host, left, top, width, height)); - return true; - } - - private ViewGroup.LayoutParams layoutParamsFor( - ViewGroup host, - int left, - int top, - int width, - int height - ) { - if (host instanceof FrameLayout) { - FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height); - params.leftMargin = left; - params.topMargin = top; - return params; - } - ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width, height); - params.leftMargin = left; - params.topMargin = top; - return params; - } - - private int representativeHeight(ArrayList placements) { - for (SnapshotPlacement placement : placements) { - if (placement != null && placement.bounds != null && placement.bounds.height > 0) { - return placement.bounds.height; - } - } - return 1; - } - - private int cardsIconHeightSteps(SbtSettings settings, SceneKey scene) { - return scene != null && scene.isAod() - ? settings.cardsAodIconHeightSteps - : settings.cardsLockIconHeightSteps; - } - - private int iconHeightPx(int statusbarHeight, int steps, int fallbackHeight) { - if (statusbarHeight <= 0) { - return Math.max(1, fallbackHeight); - } - return Math.max(1, Math.round((float) statusbarHeight * Math.max(1, steps) / 100f)); - } - - private int statusbarHeight(View root, Bounds sourceBounds, SceneKey scene) { - int sharedHeight = StatusbarHeightStore.get(root); - if (sharedHeight > 0) { - return sharedHeight; - } - Bounds statusBounds = StatusbarHeightSource.bounds(root, scene, null); - if (statusBounds != null && statusBounds.top >= 0 && statusBounds.height > 0) { - int height = Math.max(1, statusBounds.top + statusBounds.height); - if (scene != null && scene.isAod() && root != null) { - Integer stored = aodInitialStatusbarHeightByRoot.get(root); - if (stored != null && stored > 0) { - return stored; - } - aodInitialStatusbarHeightByRoot.put(root, height); - } else { - StatusbarHeightStore.put(root, height); - } - return height; - } - if (scene != null && scene.isAod() && root != null) { - Integer stored = aodInitialStatusbarHeightByRoot.get(root); - if (stored != null && stored > 0) { - return stored; - } - } - if (sourceBounds != null && sourceBounds.top >= 0 && sourceBounds.height > 0) { - return Math.max(1, sourceBounds.top + sourceBounds.height); - } - return Math.max(1, root != null ? root.getHeight() : 1); - } - - private boolean isShelfIconContainer(View view) { - String className = view.getClass().getName(); - return className.contains("SecShelfNotificationIconContainer"); - } - - private boolean isIconOnlyContainer(View view) { - String idName = ViewIdNames.idName(view); - return "keyguard_icononly_container_view".equals(idName) - || "notification_icononly_container".equals(idName) - || "notification_icononly_area".equals(idName) - || "common_notification_widget".equals(idName); - } - - private boolean isNotificationIconCandidate(View view) { - if (view == null || view instanceof TextView || view.getVisibility() != View.VISIBLE) { - return false; - } - int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth(); - int height = view.getHeight() > 0 ? view.getHeight() : view.getMeasuredHeight(); - if (width <= 0 || height <= 0 || isOverflowDotCandidate(view)) { - return false; - } - String className = view.getClass().getName(); - return className.contains("StatusBarIconView") - || className.contains("IconView") - || view instanceof ImageView; - } - - private boolean isOverflowDotCandidate(View view) { - String idName = ViewIdNames.idName(view).toLowerCase(Locale.ROOT); - String className = view.getClass().getName().toLowerCase(Locale.ROOT); - return idName.contains("overflow") - || idName.contains("dot") - || className.contains("overflow") - || className.contains("dot"); - } - - public record RenderResult(View sourceRoot, Bounds renderedBounds) { - static RenderResult empty() { - return new RenderResult(null, null); - } - } - - private record StripLayout( - ArrayList placements, - ArrayList rowBounds - ) { - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/NotificationSeenAppReporter.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/NotificationSeenAppReporter.java deleted file mode 100644 index 582bc6c..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/NotificationSeenAppReporter.java +++ /dev/null @@ -1,56 +0,0 @@ -package se.ajpanton.statusbartweak.runtime.render; - -import android.content.Context; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -final class NotificationSeenAppReporter { - private static final long MIN_REPORT_INTERVAL_MS = 60_000L; - - private final Map lastReportedMs = new HashMap<>(); - private final Map> activeKeysByPackage = new HashMap<>(); - - void report(Context context, ArrayList placements) { - if (context == null || placements == null || placements.isEmpty()) { - activeKeysByPackage.clear(); - SbtSettings.setActiveIconApps(context, java.util.Collections.emptySet()); - return; - } - long now = System.currentTimeMillis(); - HashMap> currentKeysByPackage = new HashMap<>(); - HashSet reportedThisPass = new HashSet<>(); - for (SnapshotPlacement placement : placements) { - String key = placement != null ? placement.key : null; - String packageName = SnapshotIconFilter.notificationPackage(key); - if (packageName == null || key == null) { - continue; - } - currentKeysByPackage - .computeIfAbsent(packageName, ignored -> new HashSet<>()) - .add(key); - if (wasAlreadyActive(packageName, key) || !reportedThisPass.add(packageName)) { - continue; - } - Long lastReported = lastReportedMs.get(packageName); - if (lastReported != null && now - lastReported < MIN_REPORT_INTERVAL_MS) { - continue; - } - lastReportedMs.put(packageName, now); - SbtSettings.noteSeenIconApp(context, packageName, now); - } - activeKeysByPackage.clear(); - activeKeysByPackage.putAll(currentKeysByPackage); - SbtSettings.setActiveIconApps(context, currentKeysByPackage.keySet()); - } - - private boolean wasAlreadyActive(String packageName, String key) { - Set activeKeys = activeKeysByPackage.get(packageName); - return activeKeys != null && activeKeys.contains(key); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/OwnedIconHostManager.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/OwnedIconHostManager.java index 1685962..21c52de 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/OwnedIconHostManager.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/OwnedIconHostManager.java @@ -26,18 +26,12 @@ public final class OwnedIconHostManager { "statusbartweak.unlocked.carrier.host"; public static final String TAG_UNLOCKED_CHIP_HOST = "statusbartweak.unlocked.chip.host"; - public static final String TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST = - "statusbartweak.lockscreen.cards.notification.host"; - public static final String TAG_AOD_CARDS_NOTIFICATION_HOST = - "statusbartweak.aod.cards.notification.host"; private static final String[] OWNED_HOST_TAGS = { TAG_UNLOCKED_STATUS_HOST, TAG_UNLOCKED_NOTIFICATION_HOST, TAG_UNLOCKED_CLOCK_HOST, TAG_UNLOCKED_CARRIER_HOST, - TAG_UNLOCKED_CHIP_HOST, - TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST, - TAG_AOD_CARDS_NOTIFICATION_HOST + TAG_UNLOCKED_CHIP_HOST }; private static final String[] UNLOCKED_HOST_ORDER = { TAG_UNLOCKED_STATUS_HOST, @@ -67,14 +61,6 @@ public final class OwnedIconHostManager { return ensureHost(root, TAG_UNLOCKED_CARRIER_HOST); } - public FrameLayout ensureLockscreenCardsNotificationHost(View root) { - return ensureHost(root, TAG_LOCKSCREEN_CARDS_NOTIFICATION_HOST); - } - - public FrameLayout ensureAodCardsNotificationHost(View root) { - return ensureHost(root, TAG_AOD_CARDS_NOTIFICATION_HOST); - } - private FrameLayout ensureHost(View root, String tag) { Objects.requireNonNull(tag, "tag"); if (!(root instanceof ViewGroup parent)) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotIconFilter.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/StatusIconFilter.java similarity index 64% rename from app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotIconFilter.java rename to app/src/main/java/se/ajpanton/statusbartweak/runtime/render/StatusIconFilter.java index e67b139..47e883d 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotIconFilter.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/StatusIconFilter.java @@ -5,18 +5,14 @@ import android.view.View; import java.util.ArrayList; import java.util.Locale; import java.util.Map; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; -import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection; import se.ajpanton.statusbartweak.runtime.ViewIdNames; import se.ajpanton.statusbartweak.runtime.mode.SceneKey; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; import se.ajpanton.statusbartweak.shell.settings.SystemIconRules; -final class SnapshotIconFilter { - private SnapshotIconFilter() { +final class StatusIconFilter { + private StatusIconFilter() { } static ArrayList statusPlacements( @@ -45,57 +41,6 @@ final class SnapshotIconFilter { return filtered; } - static ArrayList notificationPlacements( - ArrayList placements, - SbtSettings settings, - SceneKey scene - ) { - String mode = modeName(scene); - if (placements == null - || placements.isEmpty() - || settings == null - || mode == null) { - return placements != null ? placements : new ArrayList<>(); - } - ArrayList filtered = new ArrayList<>(placements.size()); - for (SnapshotPlacement placement : placements) { - String pkg = notificationPackage(placement != null ? placement.key : null); - if (pkg == null - || !isNotificationBlocked( - placement, - pkg, - settings.appIconBlockedModes, - settings.appIconExceptionRules, - mode)) { - filtered.add(placement); - } - } - return filtered; - } - - static String notificationPackage(String key) { - return NotificationKeyReflection.packageFromNotificationKey(key); - } - - static boolean isNotificationBlocked( - SnapshotPlacement placement, - String pkg, - Map blockedModes, - Map> exceptionRules, - String mode - ) { - if (!AppIconRules.isValidPackageName(pkg) || mode == null) { - return false; - } - AppIconRules.ExceptionRule matchingRule = matchingExceptionRule( - placement, - exceptionRules != null ? exceptionRules.get(pkg) : null); - if (matchingRule != null) { - return matchingRule.blocksMode(mode); - } - return AppIconRules.isBlocked(blockedModes, pkg, mode); - } - static boolean isStatusBlocked( SnapshotPlacement placement, Map blockedModes, @@ -118,37 +63,6 @@ final class SnapshotIconFilter { && SnapshotKeys.CHARGING_BATTERY_CHIP.equals(placement.key); } - private static AppIconRules.ExceptionRule matchingExceptionRule( - SnapshotPlacement placement, - ArrayList rules - ) { - if (rules == null || rules.isEmpty()) { - return null; - } - String text = notificationMatchText(placement); - for (AppIconRules.ExceptionRule rule : rules) { - if (rule == null || rule.regex == null || rule.regex.trim().isEmpty()) { - continue; - } - try { - if (Pattern.compile(rule.regex).matcher(text).find()) { - return rule; - } - } catch (PatternSyntaxException ignored) { - // Invalid user regexes are ignored instead of blocking all icons. - } - } - return null; - } - - private static String notificationMatchText(SnapshotPlacement placement) { - StringBuilder sb = new StringBuilder(); - append(sb, placement != null ? placement.key : null); - View view = placement != null && placement.source != null ? placement.source.view() : null; - appendViewText(sb, view); - return sb.toString(); - } - private static String statusMatchText(SnapshotPlacement placement) { StringBuilder sb = new StringBuilder(); append(sb, placement.key); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedLayoutPlanner.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedLayoutPlanner.java index a8f71fb..ec99b4c 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedLayoutPlanner.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedLayoutPlanner.java @@ -30,8 +30,6 @@ final class UnlockedLayoutPlanner { private final SnapshotRenderer chipRenderer; private final UnlockedChipPlacementController chipPlacementController; private final TextVerticalOffsetScaler textOffsetScaler; - private final NotificationSeenAppReporter notificationSeenAppReporter = - new NotificationSeenAppReporter(); private final WeakHashMap aodStatusRightInsetByRoot = new WeakHashMap<>(); private final WeakHashMap aodInitialStatusbarHeightByRoot = new WeakHashMap<>(); private final Map recentNonAodEdgesByRootWidth = new LinkedHashMap<>(); @@ -127,7 +125,7 @@ final class UnlockedLayoutPlanner { } if (statusCount > 0) { ArrayList rawPlacements = - SnapshotIconFilter.statusPlacements( + StatusIconFilter.statusPlacements( statusRenderer.rawPlacements( root, collectedIcons.statusIcons, @@ -173,18 +171,13 @@ final class UnlockedLayoutPlanner { int notificationCount = notificationCountForScene(settings, scene); Bounds notificationRowBounds = null; if (notificationCount > 0) { - ArrayList unfilteredPlacements = + ArrayList rawNotificationPlacements = notificationRenderer.rawPlacements(root, collectedIcons.notificationIcons); - notificationSeenAppReporter.report( - root != null ? root.getContext() : null, - unfilteredPlacements); - ArrayList filteredPlacements = - SnapshotIconFilter.notificationPlacements(unfilteredPlacements, settings, scene); if (isDotNotificationScene(scene)) { - filteredPlacements = unreadNotificationPlacements(filteredPlacements); + rawNotificationPlacements = unreadNotificationPlacements(rawNotificationPlacements); } ArrayList rawPlacements = resizePlacementsToHeight( - filteredPlacements, + rawNotificationPlacements, iconHeightPx(statusbarHeight, notificationIconHeightSteps(settings, scene))); notificationRowBounds = placementBounds(rawPlacements); boolean dotNotificationScene = isDotNotificationScene(scene); @@ -1596,15 +1589,15 @@ final class UnlockedLayoutPlanner { && scene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { return null; } - return LockscreenCardsNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root); + return AodNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root); } private ViewGroup aodNotificationContainer(View root, SceneKey scene) { if (scene != null && scene.notificationDisplayStyle() == NotificationDisplayStyle.CARDS) { - return LockscreenCardsNotificationIconSourceStore.sourceContainerForRoot(root); + return AodNotificationIconSourceStore.sourceContainerForRoot(root); } - return LockscreenCardsNotificationIconSourceStore.sourceContainerForAodIconsRoot(root); + return AodNotificationIconSourceStore.sourceContainerForAodIconsRoot(root); } private boolean isPlausibleAodStatusAnchor( diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedStockSourceCollector.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedStockSourceCollector.java index e199cf0..2cbf3fe 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedStockSourceCollector.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedStockSourceCollector.java @@ -85,11 +85,11 @@ final class UnlockedStockSourceCollector { if (scene != null && scene.isAod()) { if (isAodIconNotificationStyle(scene, settings)) { notificationIcons.addAll( - LockscreenCardsNotificationIconSourceStore.snapshotSourcesForAodIconsRoot(root)); + AodNotificationIconSourceStore.snapshotSourcesForAodIconsRoot(root)); if (notificationIcons.isEmpty() && scene.notificationDisplayStyle() == NotificationDisplayStyle.DOT) { notificationIcons.addAll( - LockscreenCardsNotificationIconSourceStore + AodNotificationIconSourceStore .snapshotAodNotificationPackageSources(root)); } if (notificationIcons.isEmpty() @@ -127,8 +127,8 @@ final class UnlockedStockSourceCollector { boolean iconMode = scene != null && isAodIconNotificationStyle(scene, settings); View excludedNotificationContainer = iconMode - ? LockscreenCardsNotificationIconSourceStore.sourceContainerForAodIconsRoot(root) - : LockscreenCardsNotificationIconSourceStore.sourceContainerForRoot(root); + ? AodNotificationIconSourceStore.sourceContainerForAodIconsRoot(root) + : AodNotificationIconSourceStore.sourceContainerForRoot(root); for (View source : AodStatusbarSourceStore.statusSourcesForRoot( root, excludedNotificationContainer)) { @@ -268,11 +268,11 @@ final class UnlockedStockSourceCollector { boolean iconMode = scene != null && isAodIconNotificationStyle(scene, settings); View notificationContainer = iconMode - ? LockscreenCardsNotificationIconSourceStore.sourceContainerForAodIconsRoot(root) - : LockscreenCardsNotificationIconSourceStore.sourceContainerForRoot(root); + ? AodNotificationIconSourceStore.sourceContainerForAodIconsRoot(root) + : AodNotificationIconSourceStore.sourceContainerForRoot(root); Bounds notificationBounds = iconMode - ? LockscreenCardsNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root) - : LockscreenCardsNotificationIconSourceStore.sourceContainerBoundsForRoot(root); + ? AodNotificationIconSourceStore.sourceContainerBoundsForAodIconsRoot(root) + : AodNotificationIconSourceStore.sourceContainerBoundsForRoot(root); if (!iconMode && notificationBounds == null) { notificationBounds = ViewGeometry.boundsRelativeTo( root, @@ -1753,8 +1753,6 @@ final class UnlockedStockSourceCollector { settings.layoutStatusVerticalOffsetPx, settings.systemIconBlockedModes, settings.systemIconDualSimSignalMode, - settings.appIconBlockedModes, - settings.appIconExceptionRules, settings.statusChipsHideAll, settings.statusChipsHideMediaUnlocked, settings.statusChipsHideNavUnlocked, diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugBootReceiver.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugBootReceiver.java deleted file mode 100644 index 1c945cb..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugBootReceiver.java +++ /dev/null @@ -1,16 +0,0 @@ -package se.ajpanton.statusbartweak.shell.debug; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -public final class DebugBootReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (Intent.ACTION_BOOT_COMPLETED.equals(action) - || Intent.ACTION_MY_PACKAGE_REPLACED.equals(action)) { - DebugNotifications.applyPending(context); - } - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotificationDeleteReceiver.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotificationDeleteReceiver.java deleted file mode 100644 index 84bf39e..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotificationDeleteReceiver.java +++ /dev/null @@ -1,28 +0,0 @@ -package se.ajpanton.statusbartweak.shell.debug; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -public final class DebugNotificationDeleteReceiver extends BroadcastReceiver { - private static final String ACTION = "se.ajpanton.statusbartweak.DEBUG_DELETE"; - private static final String EXTRA_NUMBER = "number"; - - static Intent newIntent(Context context, int number) { - Intent intent = new Intent(context, DebugNotificationDeleteReceiver.class); - intent.setAction(ACTION); - intent.putExtra(EXTRA_NUMBER, number); - return intent; - } - - @Override - public void onReceive(Context context, Intent intent) { - if (!ACTION.equals(intent.getAction())) { - return; - } - int number = intent.getIntExtra(EXTRA_NUMBER, 0); - if (number > 0 && number <= DebugNotifications.getDesiredCount(context)) { - DebugNotifications.applyPending(context); - } - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotifications.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotifications.java deleted file mode 100644 index e933f39..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/DebugNotifications.java +++ /dev/null @@ -1,419 +0,0 @@ -package se.ajpanton.statusbartweak.shell.debug; - -import android.Manifest; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.drawable.Icon; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.SystemClock; -import android.service.notification.StatusBarNotification; - -import java.util.Locale; - -import se.ajpanton.statusbartweak.shell.ui.MainActivity; - -public final class DebugNotifications { - private static final String PREFS = "sbt_debug_notifications"; - private static final String KEY_DESIRED = "debug_icon_count"; - private static final String KEY_CYCLE_ENABLED = "debug_icon_cycle_enabled"; - private static final String KEY_CYCLE_CURRENT = "debug_icon_cycle_current"; - private static final String KEY_CYCLE_DIRECTION = "debug_icon_cycle_direction"; - private static final String KEY_BOOT_EPOCH = "debug_boot_epoch"; - private static final String KEY_RECOVERY_USED = "debug_autogroup_recovery_used"; - - private static final int MIN_COUNT = 0; - private static final int MAX_COUNT = 50; - private static final int DEBUG_ID_BASE = 10_000; - private static final long AUTO_GROUP_CHECK_DELAY_MS = 3_500L; - private static final long BOOT_EPOCH_TOLERANCE_MS = 5_000L; - private static final long CYCLE_STEP_MS = 2_000L; - - private static final String CHANNEL_ID = "sbt_debug_icons"; - private static final String CHANNEL_NAME = "Debug Icons"; - private static final String GROUP_PREFIX = "sbt_debug_"; - private static final String SHORTCUT_PREFIX = "sbt_debug_shortcut_"; - private static final String EXTRA_DEBUG_NOTIFICATION = "sbt_debug_notification"; - private static final String EXTRA_DEBUG_NUMBER = "sbt_debug_number"; - - private static final Handler RECOVERY_HANDLER = new Handler(Looper.getMainLooper()); - private static final Handler CYCLE_HANDLER = new Handler(Looper.getMainLooper()); - private static Runnable recoveryRunnable; - private static Runnable cycleRunnable; - private static boolean recoveryInProgress; - - private DebugNotifications() { - } - - public static int getDesiredCount(Context context) { - return prefs(context).getInt(KEY_DESIRED, 0); - } - - public static int clampCount(int value) { - return Math.min(MAX_COUNT, Math.max(MIN_COUNT, value)); - } - - public static boolean isCycleEnabled(Context context) { - return prefs(context).getBoolean(KEY_CYCLE_ENABLED, false); - } - - public static void setCycleEnabled(Context context, boolean enabled) { - SharedPreferences prefs = prefs(context); - SharedPreferences.Editor edit = prefs.edit().putBoolean(KEY_CYCLE_ENABLED, enabled); - if (enabled) { - edit.putInt(KEY_CYCLE_CURRENT, 0); - edit.putInt(KEY_CYCLE_DIRECTION, 1); - } - edit.putBoolean(KEY_RECOVERY_USED, false); - edit.apply(); - applyPending(context); - } - - public static void setDesiredCount(Context context, int desiredCount) { - prefs(context) - .edit() - .putInt(KEY_DESIRED, clampCount(desiredCount)) - .putBoolean(KEY_RECOVERY_USED, false) - .apply(); - applyPending(context); - } - - public static boolean hasPostNotificationsPermission(Context context) { - return context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) - == PackageManager.PERMISSION_GRANTED; - } - - public static void applyPending(Context context) { - if (!hasPostNotificationsPermission(context)) { - return; - } - Context appContext = context.getApplicationContext(); - SharedPreferences prefs = prefs(appContext); - ensureBootEpoch(prefs); - int configured = clampCount(prefs.getInt(KEY_DESIRED, 0)); - int desired = resolveDesiredVisibleCount(prefs, configured); - NotificationManager nm = appContext.getSystemService(NotificationManager.class); - ensureChannel(nm); - cancelDebugNotificationsAbove(appContext, nm, desired); - cleanupAutoGroupSummaries(appContext, nm); - - postDebugNotifications(appContext, nm, desired); - if (desired > 0) { - scheduleAutoGroupRecovery(appContext); - } else { - cancelAutoGroupRecovery(); - } - syncCycleScheduler(appContext, prefs, configured); - } - - private static SharedPreferences prefs(Context context) { - return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); - } - - private static void ensureChannel(NotificationManager nm) { - NotificationChannel channel = new NotificationChannel( - CHANNEL_ID, - CHANNEL_NAME, - NotificationManager.IMPORTANCE_LOW - ); - channel.setDescription("Debug notification icons for StatusBarTweak"); - channel.setShowBadge(false); - channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - nm.createNotificationChannel(channel); - } - - private static Notification buildDebugNotification(Context context, int number) { - Intent openIntent = MainActivity.newOpenDebugIntent(context); - Intent deleteIntent = DebugNotificationDeleteReceiver.newIntent(context, number); - int flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE; - Bundle extras = new Bundle(); - extras.putBoolean(EXTRA_DEBUG_NOTIFICATION, true); - extras.putInt(EXTRA_DEBUG_NUMBER, number); - - Notification notification = new Notification.Builder(context, CHANNEL_ID) - .setSmallIcon(createNumberIcon(context, number)) - .setContentTitle("Debug icon " + number) - .setContentText("StatusBarTweak") - .setShowWhen(false) - .setOngoing(true) - .setOnlyAlertOnce(true) - .setCategory(Notification.CATEGORY_STATUS) - .setGroup(GROUP_PREFIX + number) - .setSortKey(String.format(Locale.ROOT, "%02d", number)) - .setShortcutId(SHORTCUT_PREFIX + number) - .setContentIntent(PendingIntent.getActivity(context, 0, openIntent, flags)) - .setDeleteIntent(PendingIntent.getBroadcast(context, number, deleteIntent, flags)) - .addExtras(extras) - .build(); - notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; - return notification; - } - - private static Icon createNumberIcon(Context context, int number) { - int sizePx = dpToPx(context, 48); - Bitmap bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - - Paint bg = new Paint(Paint.ANTI_ALIAS_FLAG); - float hue = (number * 37f) % 360f; - bg.setColor(Color.HSVToColor(new float[]{hue, 0.6f, 0.9f})); - canvas.drawRect(0, 0, sizePx, sizePx, bg); - - Paint text = new Paint(Paint.ANTI_ALIAS_FLAG); - text.setColor(Color.WHITE); - text.setTextAlign(Paint.Align.CENTER); - text.setFakeBoldText(true); - String label = String.valueOf(number); - text.setTextSize(sizePx * (label.length() >= 2 ? 0.45f : 0.6f)); - - Rect bounds = new Rect(); - text.getTextBounds(label, 0, label.length(), bounds); - canvas.drawText(label, sizePx / 2f, sizePx / 2f - bounds.exactCenterY(), text); - return Icon.createWithBitmap(bitmap); - } - - private static void cancelDebugNotificationsAbove( - Context context, - NotificationManager nm, - int desired - ) { - for (StatusBarNotification sbn : nm.getActiveNotifications()) { - if (!isOwnNotification(context, sbn)) { - continue; - } - int debugNumber = sbn.getId() - DEBUG_ID_BASE; - if (debugNumber > desired && debugNumber >= 1 && debugNumber <= MAX_COUNT) { - cancel(nm, sbn); - } - } - } - - private static void cleanupAutoGroupSummaries(Context context, NotificationManager nm) { - for (StatusBarNotification sbn : nm.getActiveNotifications()) { - if (isDebugAutoGroupSummary(context, sbn)) { - cancel(nm, sbn); - } - } - } - - private static void scheduleAutoGroupRecovery(Context context) { - SharedPreferences prefs = prefs(context); - ensureBootEpoch(prefs); - if (prefs.getBoolean(KEY_RECOVERY_USED, false) || recoveryInProgress) { - return; - } - Context appContext = context.getApplicationContext(); - cancelAutoGroupRecovery(); - recoveryRunnable = () -> runAutoGroupRecovery(appContext); - RECOVERY_HANDLER.postDelayed(recoveryRunnable, AUTO_GROUP_CHECK_DELAY_MS); - } - - private static void runAutoGroupRecovery(Context appContext) { - if (recoveryInProgress || appContext == null || !hasPostNotificationsPermission(appContext)) { - return; - } - SharedPreferences prefs = prefs(appContext); - ensureBootEpoch(prefs); - if (prefs.getBoolean(KEY_RECOVERY_USED, false)) { - return; - } - int configured = clampCount(prefs.getInt(KEY_DESIRED, 0)); - int desired = resolveDesiredVisibleCount(prefs, configured); - if (desired <= 0) { - return; - } - NotificationManager nm = appContext.getSystemService(NotificationManager.class); - if (nm == null || !hasAutoGroupSummary(appContext, nm)) { - return; - } - recoveryInProgress = true; - try { - prefs.edit().putBoolean(KEY_RECOVERY_USED, true).apply(); - cancelDebugNotificationsAndSummaries(appContext, nm); - postDebugNotifications(appContext, nm, desired); - } finally { - recoveryInProgress = false; - } - } - - private static void postDebugNotifications( - Context context, - NotificationManager nm, - int desired - ) { - for (int i = 1; i <= desired; i++) { - nm.notify(DEBUG_ID_BASE + i, buildDebugNotification(context, i)); - } - } - - private static void cancelAutoGroupRecovery() { - if (recoveryRunnable != null) { - RECOVERY_HANDLER.removeCallbacks(recoveryRunnable); - recoveryRunnable = null; - } - } - - private static boolean hasAutoGroupSummary(Context context, NotificationManager nm) { - for (StatusBarNotification sbn : nm.getActiveNotifications()) { - if (isDebugAutoGroupSummary(context, sbn)) { - return true; - } - } - return false; - } - - private static void cancelDebugNotificationsAndSummaries(Context context, NotificationManager nm) { - for (StatusBarNotification sbn : nm.getActiveNotifications()) { - if (!isOwnNotification(context, sbn)) { - continue; - } - if (isDebugId(sbn.getId()) || isDebugAutoGroupSummary(context, sbn)) { - cancel(nm, sbn); - } - } - } - - private static void ensureBootEpoch(SharedPreferences prefs) { - long bootEpoch = System.currentTimeMillis() - SystemClock.elapsedRealtime(); - long stored = prefs.getLong(KEY_BOOT_EPOCH, -1L); - if (stored <= 0L || Math.abs(stored - bootEpoch) > BOOT_EPOCH_TOLERANCE_MS) { - prefs.edit() - .putLong(KEY_BOOT_EPOCH, bootEpoch) - .putBoolean(KEY_RECOVERY_USED, false) - .apply(); - } - } - - private static boolean isDebugNotification(Notification notification) { - Bundle extras = notification.extras; - return extras != null && extras.getBoolean(EXTRA_DEBUG_NOTIFICATION, false); - } - - private static boolean isDebugId(int id) { - int debugNumber = id - DEBUG_ID_BASE; - return debugNumber >= 1 && debugNumber <= MAX_COUNT; - } - - private static boolean isDebugAutoGroupSummary(Context context, StatusBarNotification sbn) { - if (!isOwnNotification(context, sbn) || isDebugId(sbn.getId())) { - return false; - } - Notification notification = sbn.getNotification(); - if (notification == null || isDebugNotification(notification)) { - return false; - } - String group = notification.getGroup(); - return group == null || !group.startsWith(GROUP_PREFIX); - } - - private static boolean isOwnNotification(Context context, StatusBarNotification sbn) { - return context.getPackageName().equals(sbn.getPackageName()); - } - - private static void cancel(NotificationManager nm, StatusBarNotification sbn) { - if (sbn.getTag() != null) { - nm.cancel(sbn.getTag(), sbn.getId()); - } else { - nm.cancel(sbn.getId()); - } - } - - private static int resolveDesiredVisibleCount(SharedPreferences prefs, int configuredCount) { - if (!prefs.getBoolean(KEY_CYCLE_ENABLED, false)) { - return configuredCount; - } - int current = clampCount(prefs.getInt(KEY_CYCLE_CURRENT, 0)); - if (current > configuredCount) { - current = configuredCount; - prefs.edit().putInt(KEY_CYCLE_CURRENT, current).apply(); - } - return current; - } - - private static void syncCycleScheduler( - Context appContext, - SharedPreferences prefs, - int configuredCount - ) { - if (!prefs.getBoolean(KEY_CYCLE_ENABLED, false) || configuredCount <= 0) { - stopCycleScheduler(); - return; - } - startCycleScheduler(appContext); - } - - private static void startCycleScheduler(Context appContext) { - if (cycleRunnable != null) { - return; - } - cycleRunnable = new Runnable() { - @Override - public void run() { - if (!advanceCycleAndApply(appContext)) { - stopCycleScheduler(); - return; - } - CYCLE_HANDLER.postDelayed(this, CYCLE_STEP_MS); - } - }; - CYCLE_HANDLER.postDelayed(cycleRunnable, CYCLE_STEP_MS); - } - - private static void stopCycleScheduler() { - if (cycleRunnable != null) { - CYCLE_HANDLER.removeCallbacks(cycleRunnable); - cycleRunnable = null; - } - } - - private static boolean advanceCycleAndApply(Context appContext) { - SharedPreferences prefs = prefs(appContext); - if (!prefs.getBoolean(KEY_CYCLE_ENABLED, false)) { - return false; - } - int configured = clampCount(prefs.getInt(KEY_DESIRED, 0)); - if (configured <= 0) { - prefs.edit() - .putInt(KEY_CYCLE_CURRENT, 0) - .putInt(KEY_CYCLE_DIRECTION, 1) - .apply(); - applyPending(appContext); - return false; - } - - int current = Math.min(clampCount(prefs.getInt(KEY_CYCLE_CURRENT, 0)), configured); - int direction = prefs.getInt(KEY_CYCLE_DIRECTION, 1); - direction = direction == -1 ? -1 : 1; - current += direction; - if (current >= configured) { - current = configured; - direction = -1; - } else if (current <= 0) { - current = 0; - direction = 1; - } - - prefs.edit() - .putInt(KEY_CYCLE_CURRENT, current) - .putInt(KEY_CYCLE_DIRECTION, direction) - .apply(); - applyPending(appContext); - return true; - } - - private static int dpToPx(Context context, int dp) { - return (int) (dp * context.getResources().getDisplayMetrics().density + 0.5f); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/NotificationDisplayStyleSettings.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/NotificationDisplayStyleSettings.java deleted file mode 100644 index 6098939..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/debug/NotificationDisplayStyleSettings.java +++ /dev/null @@ -1,92 +0,0 @@ -package se.ajpanton.statusbartweak.shell.debug; - -import android.content.ContentResolver; -import android.content.Context; -import android.provider.Settings; -import android.text.TextUtils; - -import java.io.IOException; - -public final class NotificationDisplayStyleSettings { - private static final String KEY_LOCKSCREEN_MINIMIZING_NOTIFICATION = - "lockscreen_minimizing_notification"; - - private NotificationDisplayStyleSettings() { - } - - public static State read(Context context) { - ContentResolver resolver = context != null ? context.getContentResolver() : null; - Integer minimizing = getSystemInt(resolver, KEY_LOCKSCREEN_MINIMIZING_NOTIFICATION); - return new State(minimizing, styleFor(minimizing)); - } - - public static boolean write(Context context, Style style) { - if (context == null || style == null || style == Style.UNKNOWN) { - return false; - } - int minimizing = switch (style) { - case CARDS -> 0; - case ICONS -> 1; - case DOT -> 2; - case UNKNOWN -> -1; - }; - if (minimizing < 0) { - return false; - } - return runRootCommand( - "settings put system " + KEY_LOCKSCREEN_MINIMIZING_NOTIFICATION + " " + minimizing); - } - - private static Style styleFor(Integer minimizing) { - if (minimizing == null) { - return Style.UNKNOWN; - } - return switch (minimizing) { - case 0 -> Style.CARDS; - case 1 -> Style.ICONS; - case 2 -> Style.DOT; - default -> Style.UNKNOWN; - }; - } - - private static Integer getSystemInt(ContentResolver resolver, String key) { - if (resolver == null || TextUtils.isEmpty(key)) { - return null; - } - try { - return Settings.System.getInt(resolver, key); - } catch (Settings.SettingNotFoundException ignored) { - return null; - } - } - - private static boolean runRootCommand(String command) { - if (TextUtils.isEmpty(command)) { - return false; - } - try { - Process process = new ProcessBuilder("su", "-c", command) - .redirectErrorStream(true) - .start(); - return process.waitFor() == 0; - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - return false; - } catch (IOException | SecurityException ignored) { - return false; - } - } - - public enum Style { - UNKNOWN, - CARDS, - ICONS, - DOT - } - - public record State( - Integer minimizingNotification, - Style style - ) { - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/AppIconRules.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/AppIconRules.java deleted file mode 100644 index 1ca64e2..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/AppIconRules.java +++ /dev/null @@ -1,548 +0,0 @@ -package se.ajpanton.statusbartweak.shell.settings; - -import android.content.SharedPreferences; -import android.util.Base64; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.regex.Pattern; - -public final class AppIconRules { - private static final Pattern PACKAGE_NAME_PATTERN = - Pattern.compile("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$"); - - public static final String PREF_KEY_BLOCKED_MODES = "app_icon_blocked_modes"; - public static final String PREF_KEY_EXCEPTION_RULES = "app_icon_exception_rules"; - public static final String PREF_KEY_SEEN_SESSION = "app_icon_seen_session"; - public static final String PREF_KEY_ACTIVE_SESSION = "app_icon_active_session"; - - public static final String EXTRA_PACKAGE = "package"; - public static final String EXTRA_FIRST_SEEN_MS = "first_seen_ms"; - public static final String EXTRA_LAST_SEEN_MS = "last_seen_ms"; - public static final String EXTRA_LAST_SEEN_TIMEZONE_OFFSET_MINUTES = - "last_seen_timezone_offset_minutes"; - - public static final int MODE_AOD = 1; - public static final int MODE_LOCK = 1 << 1; - public static final int MODE_UNLOCK = 1 << 2; - private static final int ALL_MODES = MODE_AOD | MODE_LOCK | MODE_UNLOCK; - private static final String MODE_NAME_AOD = "AOD"; - private static final String MODE_NAME_LOCK = "LOCK"; - private static final String MODE_NAME_UNLOCK = "UNLOCK"; - private static final String MODE_NAME_UNKNOWN = "UNKNOWN"; - - private AppIconRules() { - } - - public static int modeMask(String mode) { - String normalized = normalizeModeName(mode); - if (MODE_NAME_AOD.equals(normalized)) { - return MODE_AOD; - } - if (MODE_NAME_LOCK.equals(normalized)) { - return MODE_LOCK; - } - if (MODE_NAME_UNLOCK.equals(normalized)) { - return MODE_UNLOCK; - } - return 0; - } - - public static boolean isValidPackageName(String pkg) { - if (pkg == null || pkg.isEmpty()) { - return false; - } - return PACKAGE_NAME_PATTERN.matcher(pkg).matches(); - } - - public static Map loadBlockedModes(SharedPreferences prefs) { - return parseBlockedModes(readStringSet(prefs, PREF_KEY_BLOCKED_MODES)); - } - - public static void saveBlockedModes(SharedPreferences prefs, Map map) { - writeStringSet(prefs, PREF_KEY_BLOCKED_MODES, encodeBlockedModes(map)); - } - - public static Map loadSeenSession(SharedPreferences prefs) { - return parseSeenSession(readStringSet(prefs, PREF_KEY_SEEN_SESSION)); - } - - public static Map> loadExceptionRules(SharedPreferences prefs) { - return parseExceptionRules(readStringSet(prefs, PREF_KEY_EXCEPTION_RULES)); - } - - public static void saveExceptionRules(SharedPreferences prefs, Map> map) { - writeStringSet(prefs, PREF_KEY_EXCEPTION_RULES, encodeExceptionRules(map)); - } - - public static void saveSeenSession(SharedPreferences prefs, Map map) { - writeStringSet(prefs, PREF_KEY_SEEN_SESSION, encodeSeenSession(map)); - } - - public static void clearSeenSession(SharedPreferences prefs) { - if (prefs == null) { - return; - } - prefs.edit().remove(PREF_KEY_SEEN_SESSION).apply(); - } - - public static Set loadActiveSession(SharedPreferences prefs) { - HashSet out = new HashSet<>(); - for (String pkg : readStringSet(prefs, PREF_KEY_ACTIVE_SESSION)) { - if (isValidPackageName(pkg)) { - out.add(pkg); - } - } - return out; - } - - public static void saveActiveSession(SharedPreferences prefs, Set packages) { - HashSet out = new HashSet<>(); - if (packages != null) { - for (String pkg : packages) { - if (isValidPackageName(pkg)) { - out.add(pkg); - } - } - } - writeStringSet(prefs, PREF_KEY_ACTIVE_SESSION, out); - } - - private static Set readStringSet(SharedPreferences prefs, String key) { - if (prefs == null) { - return Collections.emptySet(); - } - return prefs.getStringSet(key, Collections.emptySet()); - } - - private static void writeStringSet(SharedPreferences prefs, String key, Set value) { - if (prefs == null) { - return; - } - prefs.edit().putStringSet(key, value).apply(); - } - - public static boolean noteSeen(Map seen, - String pkg, - long seenMs, - int timezoneOffsetMinutes) { - if (seen == null || !isValidPackageName(pkg)) { - return false; - } - if (seenMs <= 0L) { - seenMs = System.currentTimeMillis(); - } - SeenApp existing = seen.get(pkg); - if (existing == null) { - seen.put(pkg, new SeenApp(pkg, seenMs, seenMs, timezoneOffsetMinutes)); - return true; - } - long firstSeenMs = existing.firstSeenMs > 0L - ? Math.min(existing.firstSeenMs, seenMs) - : seenMs; - long lastSeenMs = existing.lastSeenMs; - int lastSeenOffsetMinutes = existing.lastSeenTimezoneOffsetMinutes; - if (lastSeenMs <= 0L || seenMs >= lastSeenMs) { - lastSeenMs = seenMs; - lastSeenOffsetMinutes = timezoneOffsetMinutes; - } - if (firstSeenMs == existing.firstSeenMs - && lastSeenMs == existing.lastSeenMs - && lastSeenOffsetMinutes == existing.lastSeenTimezoneOffsetMinutes) { - return false; - } - seen.put(pkg, new SeenApp(pkg, firstSeenMs, lastSeenMs, lastSeenOffsetMinutes)); - return true; - } - - public static boolean isBlocked(Map masks, String pkg, String mode) { - if (masks == null || !isValidPackageName(pkg)) { - return false; - } - Integer mask = masks.get(pkg); - if (mask == null) { - return false; - } - int modeMask = modeMask(mode); - if (modeMask == 0) { - return false; - } - return (mask & modeMask) != 0; - } - - public static void setModeBlocked(Map masks, - String pkg, - boolean blockAod, - boolean blockLock, - boolean blockUnlock) { - if (masks == null || !isValidPackageName(pkg)) { - return; - } - int mask = 0; - if (blockAod) { - mask |= MODE_AOD; - } - if (blockLock) { - mask |= MODE_LOCK; - } - if (blockUnlock) { - mask |= MODE_UNLOCK; - } - if (mask == 0) { - masks.remove(pkg); - return; - } - masks.put(pkg, mask); - } - - public static ArrayList copyExceptionRules(List source) { - ArrayList out = new ArrayList<>(); - if (source == null) { - return out; - } - for (ExceptionRule rule : source) { - if (rule == null || rule.regex == null) { - continue; - } - String regex = rule.regex.trim(); - if (regex.isEmpty()) { - continue; - } - out.add(new ExceptionRule(regex, sanitizeModeMask(rule.modeMask))); - } - return out; - } - - public static void setExceptionRules(Map> rulesByPackage, - String pkg, - List rules) { - if (rulesByPackage == null || !isValidPackageName(pkg)) { - return; - } - ArrayList copy = copyExceptionRules(rules); - if (copy.isEmpty()) { - rulesByPackage.remove(pkg); - return; - } - rulesByPackage.put(pkg, copy); - } - - public static Map parseBlockedModes(Set rawSet) { - Map out = new HashMap<>(); - if (rawSet == null || rawSet.isEmpty()) { - return out; - } - for (String entry : snapshot(rawSet)) { - if (entry == null || entry.isEmpty()) { - continue; - } - String[] parts = entry.split("\\|", -1); - if (parts.length != 4) { - continue; - } - String pkg = parts[0]; - if (!isValidPackageName(pkg)) { - continue; - } - int mask = 0; - if ("1".equals(parts[1])) { - mask |= MODE_AOD; - } - if ("1".equals(parts[2])) { - mask |= MODE_LOCK; - } - if ("1".equals(parts[3])) { - mask |= MODE_UNLOCK; - } - if (mask != 0) { - out.put(pkg, mask); - } - } - return out; - } - - public static Set encodeBlockedModes(Map map) { - Set out = new HashSet<>(); - if (map == null || map.isEmpty()) { - return out; - } - for (Map.Entry e : map.entrySet()) { - String pkg = e.getKey(); - Integer maskObj = e.getValue(); - if (!isValidPackageName(pkg) || maskObj == null) { - continue; - } - int mask = maskObj; - if (mask == 0) { - continue; - } - String entry = pkg + "|" - + (((mask & MODE_AOD) != 0) ? "1" : "0") + "|" - + (((mask & MODE_LOCK) != 0) ? "1" : "0") + "|" - + (((mask & MODE_UNLOCK) != 0) ? "1" : "0"); - out.add(entry); - } - return out; - } - - public static Map> parseExceptionRules(Set rawSet) { - Map> staged = new HashMap<>(); - if (rawSet == null || rawSet.isEmpty()) { - return new HashMap<>(); - } - for (String entry : snapshot(rawSet)) { - if (entry == null || entry.isEmpty()) { - continue; - } - String[] parts = entry.split("\\|", 4); - if (parts.length != 4) { - continue; - } - String pkg = parts[0]; - if (!isValidPackageName(pkg)) { - continue; - } - int index; - int modeMask; - try { - index = Integer.parseInt(parts[1]); - modeMask = Integer.parseInt(parts[2]); - } catch (NumberFormatException ignored) { - continue; - } - if (index < 0) { - continue; - } - modeMask = sanitizeModeMask(modeMask); - String regex; - try { - byte[] decoded = Base64.decode(parts[3], Base64.NO_WRAP); - regex = new String(decoded, StandardCharsets.UTF_8).trim(); - } catch (IllegalArgumentException ignored) { - continue; - } - if (regex.isEmpty()) { - continue; - } - staged.computeIfAbsent(pkg, key -> new ArrayList<>()) - .add(new IndexedExceptionRule(index, new ExceptionRule(regex, modeMask))); - } - Map> out = new HashMap<>(); - for (Map.Entry> e : staged.entrySet()) { - ArrayList stagedList = e.getValue(); - stagedList.sort((a, b) -> Integer.compare(a.index, b.index)); - ArrayList rules = new ArrayList<>(stagedList.size()); - for (IndexedExceptionRule indexed : stagedList) { - rules.add(indexed.rule); - } - if (!rules.isEmpty()) { - out.put(e.getKey(), rules); - } - } - return out; - } - - public static Set encodeExceptionRules(Map> map) { - Set out = new HashSet<>(); - if (map == null || map.isEmpty()) { - return out; - } - for (Map.Entry> e : map.entrySet()) { - String pkg = e.getKey(); - if (!isValidPackageName(pkg) || e.getValue() == null) { - continue; - } - ArrayList rules = e.getValue(); - for (int i = 0; i < rules.size(); i++) { - ExceptionRule rule = rules.get(i); - if (rule == null || rule.regex == null) { - continue; - } - String regex = rule.regex.trim(); - if (regex.isEmpty()) { - continue; - } - String encodedRegex = Base64.encodeToString( - regex.getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP); - int modeMask = sanitizeModeMask(rule.modeMask); - out.add(pkg + "|" + i + "|" + modeMask + "|" + encodedRegex); - } - } - return out; - } - - private static int sanitizeModeMask(int mask) { - return mask & ALL_MODES; - } - - private static HashSet snapshot(Set rawSet) { - return new HashSet<>(rawSet); - } - - private static String normalizeModeName(String mode) { - if (mode == null) { - return MODE_NAME_UNKNOWN; - } - String normalized = mode.trim().toUpperCase(Locale.ROOT); - if (normalized.isEmpty()) { - return MODE_NAME_UNKNOWN; - } - if (MODE_NAME_AOD.equals(normalized)) { - return MODE_NAME_AOD; - } - if (MODE_NAME_LOCK.equals(normalized) || "LOCKSCREEN".equals(normalized)) { - return MODE_NAME_LOCK; - } - if (MODE_NAME_UNLOCK.equals(normalized) || "UNLOCKED".equals(normalized)) { - return MODE_NAME_UNLOCK; - } - return MODE_NAME_UNKNOWN; - } - - public static Map parseSeenSession(Set rawSet) { - Map out = new HashMap<>(); - if (rawSet == null || rawSet.isEmpty()) { - return out; - } - for (String entry : snapshot(rawSet)) { - if (entry == null || entry.isEmpty()) { - continue; - } - String[] parts = entry.split("\\|", -1); - if (parts.length != 4) { - continue; - } - String pkg = parts[0]; - if (!isValidPackageName(pkg)) { - continue; - } - long firstSeen; - long lastSeen; - int lastSeenOffsetMinutes; - try { - firstSeen = Long.parseLong(parts[1]); - lastSeen = Long.parseLong(parts[2]); - lastSeenOffsetMinutes = Integer.parseInt(parts[3]); - } catch (NumberFormatException ignored) { - continue; - } - if (firstSeen <= 0L || lastSeen <= 0L) { - continue; - } - SeenApp existing = out.get(pkg); - if (existing == null) { - out.put(pkg, new SeenApp(pkg, firstSeen, lastSeen, lastSeenOffsetMinutes)); - } else { - long mergedFirstSeen = Math.min(existing.firstSeenMs, firstSeen); - long mergedLastSeen = existing.lastSeenMs; - int mergedOffset = existing.lastSeenTimezoneOffsetMinutes; - if (lastSeen >= mergedLastSeen) { - mergedLastSeen = lastSeen; - mergedOffset = lastSeenOffsetMinutes; - } - out.put(pkg, new SeenApp(pkg, mergedFirstSeen, mergedLastSeen, mergedOffset)); - } - } - return out; - } - - public static Set encodeSeenSession(Map map) { - Set out = new HashSet<>(); - if (map == null || map.isEmpty()) { - return out; - } - for (Map.Entry e : map.entrySet()) { - String pkg = e.getKey(); - SeenApp app = e.getValue(); - if (!isValidPackageName(pkg) || app == null) { - continue; - } - long firstSeen = app.firstSeenMs; - long lastSeen = app.lastSeenMs; - if (firstSeen <= 0L) { - continue; - } - if (lastSeen <= 0L) { - lastSeen = firstSeen; - } - out.add(pkg + "|" + firstSeen + "|" + lastSeen + "|" - + app.lastSeenTimezoneOffsetMinutes); - } - return out; - } - - public static final class SeenApp { - public final String packageName; - public final long firstSeenMs; - public final long lastSeenMs; - public final int lastSeenTimezoneOffsetMinutes; - - public SeenApp(String packageName, - long firstSeenMs, - long lastSeenMs, - int lastSeenTimezoneOffsetMinutes) { - this.packageName = packageName; - this.firstSeenMs = firstSeenMs; - this.lastSeenMs = lastSeenMs; - this.lastSeenTimezoneOffsetMinutes = lastSeenTimezoneOffsetMinutes; - } - } - - public static final class ExceptionRule { - public final String regex; - public final int modeMask; - - public ExceptionRule(String regex, int modeMask) { - this.regex = regex; - this.modeMask = sanitizeModeMask(modeMask); - } - - public boolean blocksMode(String mode) { - int modeBit = modeMask(mode); - if (modeBit == 0) { - return false; - } - return (modeMask & modeBit) != 0; - } - } - - private static final class IndexedExceptionRule { - final int index; - final ExceptionRule rule; - - IndexedExceptionRule(int index, ExceptionRule rule) { - this.index = index; - this.rule = rule; - } - } - - public static int currentTimezoneOffsetMinutes() { - long now = System.currentTimeMillis(); - return TimeZone.getDefault().getOffset(now) / 60000; - } - - public static List sortSeenOldestFirst(Map seen) { - List out = new ArrayList<>(); - if (seen == null || seen.isEmpty()) { - return out; - } - for (Map.Entry e : seen.entrySet()) { - String pkg = e.getKey(); - SeenApp app = e.getValue(); - if (!isValidPackageName(pkg) || app == null || app.firstSeenMs <= 0L) { - continue; - } - out.add(app); - } - out.sort((a, b) -> Long.compare(a.firstSeenMs, b.firstSeenMs)); - return out; - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtDefaults.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtDefaults.java index b6f8d72..adf054a 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtDefaults.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtDefaults.java @@ -3,54 +3,6 @@ package se.ajpanton.statusbartweak.shell.settings; public final class SbtDefaults { public static final int LOCKSCREEN_DOT_Y_OFFSET_DP = 3; - public static final boolean ICONS_AOD_CUTOUT_LIMIT_DEFAULT = true; - public static final boolean ICONS_LOCK_CUTOUT_LIMIT_DEFAULT = true; - - // Unlocked slider defaults and bounds. - public static final int UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT = 3; - public static final int UNLOCKED_MAX_ICONS_PER_ROW_MIN = 3; - public static final int UNLOCKED_MAX_ICONS_PER_ROW_MAX = 50; - - // Icons mode (AOD). - public static final int ICONS_AOD_MAX_ICONS_PER_ROW_DEFAULT = 8; - public static final int ICONS_AOD_MAX_ICONS_PER_ROW_MIN = 1; - public static final int ICONS_AOD_MAX_ICONS_PER_ROW_MAX = 50; - public static final int ICONS_AOD_MAX_ROWS_DEFAULT = 1; - public static final int ICONS_AOD_MAX_ROWS_MIN = 1; - public static final int ICONS_AOD_MAX_ROWS_MAX = 5; - public static final boolean ICONS_AOD_EVEN_DISTRIBUTION_DEFAULT = false; - - // Icons mode (Lockscreen). - public static final int ICONS_LOCK_MAX_ICONS_PER_ROW_DEFAULT = 8; - public static final int ICONS_LOCK_MAX_ICONS_PER_ROW_MIN = 1; - public static final int ICONS_LOCK_MAX_ICONS_PER_ROW_MAX = 50; - public static final int ICONS_LOCK_MAX_ROWS_DEFAULT = 1; - public static final int ICONS_LOCK_MAX_ROWS_MIN = 1; - public static final int ICONS_LOCK_MAX_ROWS_MAX = 5; - public static final boolean ICONS_LOCK_EVEN_DISTRIBUTION_DEFAULT = false; - - // Cards mode (AOD). - public static final int CARDS_AOD_MAX_ICONS_PER_ROW_DEFAULT = 5; - public static final int CARDS_AOD_MAX_ICONS_PER_ROW_MIN = 1; - public static final int CARDS_AOD_MAX_ICONS_PER_ROW_MAX = 15; - public static final int CARDS_AOD_MAX_ROWS_DEFAULT = 1; - public static final int CARDS_AOD_MAX_ROWS_MIN = 0; - public static final int CARDS_AOD_MAX_ROWS_MAX = 5; - public static final boolean CARDS_AOD_EVEN_DISTRIBUTION_DEFAULT = true; - public static final boolean CARDS_AOD_LIMIT_TO_WIDTH_DEFAULT = true; - - // Cards mode (Lockscreen). - public static final int CARDS_LOCK_MAX_ICONS_PER_ROW_DEFAULT = 5; - public static final int CARDS_LOCK_MAX_ICONS_PER_ROW_MIN = 1; - public static final int CARDS_LOCK_MAX_ICONS_PER_ROW_MAX = 15; - public static final int CARDS_LOCK_MAX_ROWS_DEFAULT = 1; - public static final int CARDS_LOCK_MAX_ROWS_MIN = 0; - public static final int CARDS_LOCK_MAX_ROWS_MAX = 5; - public static final boolean CARDS_LOCK_EVEN_DISTRIBUTION_DEFAULT = true; - public static final boolean CARDS_LOCK_LIMIT_TO_WIDTH_DEFAULT = true; - public static final boolean AOD_KEEP_VISIBLE_DURING_CALL_DEFAULT = false; - public static final boolean BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT_DEFAULT = true; - public static final boolean BATTERY_AOD_UNPLUGGED_PERCENT_DEFAULT = true; public static final boolean BATTERY_BAR_ENABLED_DEFAULT = true; public static final String BATTERY_BAR_POSITION_DEFAULT = "top"; public static final String BATTERY_BAR_ALIGNMENT_DEFAULT = "ltr"; @@ -136,8 +88,6 @@ public final class SbtDefaults { public static final int LAYOUT_NOTIF_ICON_HEIGHT_STEPS_DEFAULT = 46; public static final int LAYOUT_NOTIF_LOCK_ICON_HEIGHT_STEPS_DEFAULT = 46; public static final int LAYOUT_NOTIF_AOD_ICON_HEIGHT_STEPS_DEFAULT = 46; - public static final int LAYOUT_CARDS_NOTIF_LOCK_ICON_HEIGHT_STEPS_DEFAULT = 59; - public static final int LAYOUT_CARDS_NOTIF_AOD_ICON_HEIGHT_STEPS_DEFAULT = 65; public static final String LAYOUT_STATUS_POSITION_DEFAULT = "right"; public static final boolean LAYOUT_STATUS_ENABLED_AOD_DEFAULT = true; public static final boolean LAYOUT_STATUS_ENABLED_LOCKSCREEN_DEFAULT = true; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettings.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettings.java index 681b699..91be495 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettings.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettings.java @@ -150,35 +150,11 @@ public final class SbtSettings { "debug_visualize_aod_stock_containers"; public static final String KEY_DEBUG_EXPERIMENTAL_AOD_STATUSBAR_ROOT = "debug_experimental_aod_statusbar_root"; - public static final String KEY_LOCKED_NOTIFICATION_MODE = - "locked_notification_mode"; - public static final String KEY_UNLOCKED_MAX_ICONS_PER_ROW = "unlocked_max_icons_per_row"; - public static final String KEY_ICONS_AOD_MAX_ICONS_PER_ROW = "icons_aod_max_icons_per_row"; - public static final String KEY_ICONS_AOD_MAX_ROWS = "icons_aod_max_rows"; - public static final String KEY_ICONS_AOD_EVEN_DISTRIBUTION = "icons_aod_even_distribution"; - public static final String KEY_ICONS_AOD_CUTOUT_LIMIT = "icons_aod_cutout_limit"; - public static final String KEY_ICONS_LOCK_CUTOUT_LIMIT = "icons_lock_cutout_limit"; - public static final String KEY_ICONS_LOCK_MAX_ICONS_PER_ROW = "icons_lock_max_icons_per_row"; - public static final String KEY_ICONS_LOCK_MAX_ROWS = "icons_lock_max_rows"; - public static final String KEY_ICONS_LOCK_EVEN_DISTRIBUTION = "icons_lock_even_distribution"; - public static final String KEY_CARDS_AOD_MAX_ICONS_PER_ROW = "cards_aod_max_icons_per_row"; - public static final String KEY_CARDS_AOD_MAX_ROWS = "cards_aod_max_rows"; - public static final String KEY_CARDS_AOD_EVEN_DISTRIBUTION = "cards_aod_even_distribution"; - public static final String KEY_CARDS_AOD_LIMIT_TO_WIDTH = "cards_aod_limit_to_width"; - public static final String KEY_CARDS_AOD_ICON_HEIGHT_STEPS = "cards_aod_icon_height_steps"; - public static final String KEY_CARDS_LOCK_MAX_ICONS_PER_ROW = "cards_lock_max_icons_per_row"; - public static final String KEY_CARDS_LOCK_MAX_ROWS = "cards_lock_max_rows"; - public static final String KEY_CARDS_LOCK_EVEN_DISTRIBUTION = "cards_lock_even_distribution"; - public static final String KEY_CARDS_LOCK_LIMIT_TO_WIDTH = "cards_lock_limit_to_width"; - public static final String KEY_CARDS_LOCK_ICON_HEIGHT_STEPS = "cards_lock_icon_height_steps"; public static final String KEY_STATUS_CHIPS_HIDE_ALL = "status_chips_hide_all"; public static final String KEY_STATUS_CHIPS_HIDE_MEDIA_UNLOCKED = "status_chips_hide_media_unlocked"; public static final String KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED = "status_chips_hide_nav_unlocked"; public static final String KEY_STATUS_CHIPS_HIDE_CALL = "status_chips_hide_call"; public static final String KEY_STATUS_CHIPS_HIDE_BATTERY = "status_chips_hide_battery"; - public static final String KEY_AOD_KEEP_VISIBLE_DURING_CALL = "aod_keep_visible_during_call"; - public static final String KEY_BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT = "battery_lockscreen_unplugged_percent"; - public static final String KEY_BATTERY_AOD_UNPLUGGED_PERCENT = "battery_aod_unplugged_percent"; public static final String KEY_BATTERY_BAR_ENABLED = "battery_bar_enabled"; public static final String KEY_BATTERY_BAR_POSITION = "battery_bar_position"; public static final String KEY_BATTERY_BAR_ALIGNMENT = "battery_bar_alignment"; @@ -296,8 +272,6 @@ public final class SbtSettings { public static final String SYSTEM_ICON_DUAL_SIM_WEAKEST = "weakest"; public static final String SYSTEM_ICON_DUAL_SIM_DATA = "data"; public static final String SYSTEM_ICON_DUAL_SIM_PHONE = "phone"; - public static final String KEY_APP_ICON_BLOCKED_MODES = AppIconRules.PREF_KEY_BLOCKED_MODES; - public static final String KEY_APP_ICON_EXCEPTION_RULES = AppIconRules.PREF_KEY_EXCEPTION_RULES; public static String layoutNotifPositionKey(int index) { return suffixedKey(KEY_LAYOUT_NOTIF_POSITION, index); @@ -406,28 +380,6 @@ public final class SbtSettings { private static String suffixedKey(String base, int index) { return indexedKey(base, index); } - public final boolean enableAodCutoutLimit; - public final boolean enableLockCutoutLimit; - public final int unlockedMaxIconsPerRow; - public final int iconsAodMaxIconsPerRow; - public final int iconsAodMaxRows; - public final boolean iconsAodEvenDistribution; - public final int iconsLockMaxIconsPerRow; - public final int iconsLockMaxRows; - public final boolean iconsLockEvenDistribution; - public final int cardsAodMaxIconsPerRow; - public final int cardsAodMaxRows; - public final boolean cardsAodEvenDistribution; - public final boolean cardsAodLimitToWidth; - public final int cardsAodIconHeightSteps; - public final int cardsLockMaxIconsPerRow; - public final int cardsLockMaxRows; - public final boolean cardsLockEvenDistribution; - public final boolean cardsLockLimitToWidth; - public final int cardsLockIconHeightSteps; - public final boolean keepAodVisibleDuringCall; - public final boolean batteryLockscreenUnpluggedPercent; - public final boolean batteryAodUnpluggedPercent; public final boolean batteryBarEnabled; public final String batteryBarPosition; public final String batteryBarAlignment; @@ -533,9 +485,6 @@ public final class SbtSettings { public final boolean statusChipsHideNavUnlocked; public final boolean statusChipsHideCallUnlocked; public final boolean statusChipsHideBattery; - public final Map appIconBlockedModes; - public final Map> appIconExceptionRules; - public final String lockedNotificationMode; public final boolean debugVisualizeNotificationContainer; public final boolean debugVisualizeStatusContainer; public final boolean debugVisualizeClockContainer; @@ -544,29 +493,7 @@ public final class SbtSettings { public final boolean debugVisualizeAodStockContainers; public final boolean debugExperimentalAodStatusbarRoot; - private SbtSettings(boolean enableAodCutoutLimit, - boolean enableLockCutoutLimit, - int unlockedMaxIconsPerRow, - int iconsAodMaxIconsPerRow, - int iconsAodMaxRows, - boolean iconsAodEvenDistribution, - int iconsLockMaxIconsPerRow, - int iconsLockMaxRows, - boolean iconsLockEvenDistribution, - int cardsAodMaxIconsPerRow, - int cardsAodMaxRows, - boolean cardsAodEvenDistribution, - boolean cardsAodLimitToWidth, - int cardsAodIconHeightSteps, - int cardsLockMaxIconsPerRow, - int cardsLockMaxRows, - boolean cardsLockEvenDistribution, - boolean cardsLockLimitToWidth, - int cardsLockIconHeightSteps, - boolean keepAodVisibleDuringCall, - boolean batteryLockscreenUnpluggedPercent, - boolean batteryAodUnpluggedPercent, - boolean batteryBarEnabled, + private SbtSettings(boolean batteryBarEnabled, String batteryBarPosition, String batteryBarAlignment, int batteryBarThicknessDp, @@ -671,9 +598,6 @@ public final class SbtSettings { boolean statusChipsHideNavUnlocked, boolean statusChipsHideCallUnlocked, boolean statusChipsHideBattery, - Map appIconBlockedModes, - Map> appIconExceptionRules, - String lockedNotificationMode, boolean debugVisualizeNotificationContainer, boolean debugVisualizeStatusContainer, boolean debugVisualizeClockContainer, @@ -681,28 +605,6 @@ public final class SbtSettings { boolean debugVisualizeCameraCutout, boolean debugVisualizeAodStockContainers, boolean debugExperimentalAodStatusbarRoot) { - this.enableAodCutoutLimit = enableAodCutoutLimit; - this.enableLockCutoutLimit = enableLockCutoutLimit; - this.unlockedMaxIconsPerRow = unlockedMaxIconsPerRow; - this.iconsAodMaxIconsPerRow = iconsAodMaxIconsPerRow; - this.iconsAodMaxRows = iconsAodMaxRows; - this.iconsAodEvenDistribution = iconsAodEvenDistribution; - this.iconsLockMaxIconsPerRow = iconsLockMaxIconsPerRow; - this.iconsLockMaxRows = iconsLockMaxRows; - this.iconsLockEvenDistribution = iconsLockEvenDistribution; - this.cardsAodMaxIconsPerRow = cardsAodMaxIconsPerRow; - this.cardsAodMaxRows = cardsAodMaxRows; - this.cardsAodEvenDistribution = cardsAodEvenDistribution; - this.cardsAodLimitToWidth = cardsAodLimitToWidth; - this.cardsAodIconHeightSteps = clampIconHeightSteps(cardsAodIconHeightSteps); - this.cardsLockMaxIconsPerRow = cardsLockMaxIconsPerRow; - this.cardsLockMaxRows = cardsLockMaxRows; - this.cardsLockEvenDistribution = cardsLockEvenDistribution; - this.cardsLockLimitToWidth = cardsLockLimitToWidth; - this.cardsLockIconHeightSteps = clampIconHeightSteps(cardsLockIconHeightSteps); - this.keepAodVisibleDuringCall = keepAodVisibleDuringCall; - this.batteryLockscreenUnpluggedPercent = batteryLockscreenUnpluggedPercent; - this.batteryAodUnpluggedPercent = batteryAodUnpluggedPercent; this.batteryBarEnabled = batteryBarEnabled; this.batteryBarPosition = batteryBarPosition != null ? batteryBarPosition @@ -957,22 +859,6 @@ public final class SbtSettings { this.statusChipsHideNavUnlocked = statusChipsHideNavUnlocked; this.statusChipsHideCallUnlocked = statusChipsHideCallUnlocked; this.statusChipsHideBattery = statusChipsHideBattery; - this.appIconBlockedModes = appIconBlockedModes != null - ? Collections.unmodifiableMap(new HashMap<>(appIconBlockedModes)) - : Collections.emptyMap(); - if (appIconExceptionRules != null && !appIconExceptionRules.isEmpty()) { - HashMap> copy = new HashMap<>(); - for (Map.Entry> e : appIconExceptionRules.entrySet()) { - if (!AppIconRules.isValidPackageName(e.getKey())) { - continue; - } - copy.put(e.getKey(), AppIconRules.copyExceptionRules(e.getValue())); - } - this.appIconExceptionRules = Collections.unmodifiableMap(copy); - } else { - this.appIconExceptionRules = Collections.emptyMap(); - } - this.lockedNotificationMode = sanitizeLockedNotificationMode(lockedNotificationMode); this.debugVisualizeNotificationContainer = debugVisualizeNotificationContainer; this.debugVisualizeStatusContainer = debugVisualizeStatusContainer; this.debugVisualizeClockContainer = debugVisualizeClockContainer; @@ -986,13 +872,6 @@ public final class SbtSettings { return fromSource(EmptySettingsSource.INSTANCE); } - private static String sanitizeLockedNotificationMode(String mode) { - if ("cards".equals(mode) || "icons".equals(mode) || "dot".equals(mode)) { - return mode; - } - return "dot"; - } - public static boolean validSystemIconDualSimSignalMode(String mode) { return SYSTEM_ICON_DUAL_SIM_SEPARATE.equals(mode) || SYSTEM_ICON_DUAL_SIM_FIRST.equals(mode) @@ -1060,68 +939,6 @@ public final class SbtSettings { } } - public static void noteSeenIconApp(Context context, String packageName, long firstSeenMs) { - if (context == null || !AppIconRules.isValidPackageName(packageName)) { - return; - } - long seenMs = firstSeenMs > 0L ? firstSeenMs : System.currentTimeMillis(); - int offsetMinutes = AppIconRules.currentTimezoneOffsetMinutes(); - try { - if (!MODULE_PACKAGE.equals(context.getPackageName()) && hasSettingsProvider(context)) { - Bundle extras = new Bundle(); - extras.putString(AppIconRules.EXTRA_PACKAGE, packageName); - extras.putLong(AppIconRules.EXTRA_FIRST_SEEN_MS, seenMs); - extras.putLong(AppIconRules.EXTRA_LAST_SEEN_MS, seenMs); - extras.putInt(AppIconRules.EXTRA_LAST_SEEN_TIMEZONE_OFFSET_MINUTES, offsetMinutes); - context.getContentResolver() - .call(settingsProviderUri(), - SbtSettingsProvider.METHOD_NOTE_SEEN_ICON_APP, - null, - extras); - return; - } - SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); - Map seen = AppIconRules.loadSeenSession(prefs); - if (AppIconRules.noteSeen(seen, packageName, seenMs, offsetMinutes)) { - AppIconRules.saveSeenSession(prefs, seen); - } - } catch (Throwable ignored) { - // This list is advisory UI state; rendering should never fail because it cannot be updated. - } - } - - public static void setActiveIconApps(Context context, Set packageNames) { - if (context == null) { - return; - } - HashSet safePackages = new HashSet<>(); - if (packageNames != null) { - for (String packageName : packageNames) { - if (AppIconRules.isValidPackageName(packageName)) { - safePackages.add(packageName); - } - } - } - try { - if (!MODULE_PACKAGE.equals(context.getPackageName()) && hasSettingsProvider(context)) { - Bundle extras = new Bundle(); - extras.putStringArrayList( - SbtSettingsProvider.EXTRA_VALUE, - new ArrayList<>(safePackages)); - context.getContentResolver() - .call(settingsProviderUri(), - SbtSettingsProvider.METHOD_SET_ACTIVE_ICON_APPS, - null, - extras); - return; - } - SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); - AppIconRules.saveActiveSession(prefs, safePackages); - } catch (Throwable ignored) { - // This list is advisory UI state; rendering should never fail because it cannot be updated. - } - } - public static void setClockCameraDebugState(Context context, String cameraId, String autoType, @@ -1159,41 +976,6 @@ public final class SbtSettings { } Map systemIconBlockedModes = readSystemIconBlockedModes(prefs); return new SbtSettings( - prefs.getBoolean(KEY_ICONS_AOD_CUTOUT_LIMIT, SbtDefaults.ICONS_AOD_CUTOUT_LIMIT_DEFAULT), - prefs.getBoolean(KEY_ICONS_LOCK_CUTOUT_LIMIT, SbtDefaults.ICONS_LOCK_CUTOUT_LIMIT_DEFAULT), - clampAtLeast(prefs.getInt(KEY_UNLOCKED_MAX_ICONS_PER_ROW, SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT), - SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_MIN), - clampAtLeast(prefs.getInt(KEY_ICONS_AOD_MAX_ICONS_PER_ROW, SbtDefaults.ICONS_AOD_MAX_ICONS_PER_ROW_DEFAULT), - SbtDefaults.ICONS_AOD_MAX_ICONS_PER_ROW_MIN), - clampAtLeast(prefs.getInt(KEY_ICONS_AOD_MAX_ROWS, SbtDefaults.ICONS_AOD_MAX_ROWS_DEFAULT), - SbtDefaults.ICONS_AOD_MAX_ROWS_MIN), - prefs.getBoolean(KEY_ICONS_AOD_EVEN_DISTRIBUTION, SbtDefaults.ICONS_AOD_EVEN_DISTRIBUTION_DEFAULT), - clampAtLeast(prefs.getInt(KEY_ICONS_LOCK_MAX_ICONS_PER_ROW, SbtDefaults.ICONS_LOCK_MAX_ICONS_PER_ROW_DEFAULT), - SbtDefaults.ICONS_LOCK_MAX_ICONS_PER_ROW_MIN), - clampAtLeast(prefs.getInt(KEY_ICONS_LOCK_MAX_ROWS, SbtDefaults.ICONS_LOCK_MAX_ROWS_DEFAULT), - SbtDefaults.ICONS_LOCK_MAX_ROWS_MIN), - prefs.getBoolean(KEY_ICONS_LOCK_EVEN_DISTRIBUTION, SbtDefaults.ICONS_LOCK_EVEN_DISTRIBUTION_DEFAULT), - clampAtLeast(prefs.getInt(KEY_CARDS_AOD_MAX_ICONS_PER_ROW, SbtDefaults.CARDS_AOD_MAX_ICONS_PER_ROW_DEFAULT), - SbtDefaults.CARDS_AOD_MAX_ICONS_PER_ROW_MIN), - clampAtLeast(prefs.getInt(KEY_CARDS_AOD_MAX_ROWS, SbtDefaults.CARDS_AOD_MAX_ROWS_DEFAULT), - SbtDefaults.CARDS_AOD_MAX_ROWS_MIN), - prefs.getBoolean(KEY_CARDS_AOD_EVEN_DISTRIBUTION, SbtDefaults.CARDS_AOD_EVEN_DISTRIBUTION_DEFAULT), - prefs.getBoolean(KEY_CARDS_AOD_LIMIT_TO_WIDTH, SbtDefaults.CARDS_AOD_LIMIT_TO_WIDTH_DEFAULT), - clampAtLeast(prefs.getInt(KEY_CARDS_AOD_ICON_HEIGHT_STEPS, - SbtDefaults.LAYOUT_CARDS_NOTIF_AOD_ICON_HEIGHT_STEPS_DEFAULT), - SbtDefaults.LAYOUT_ICON_HEIGHT_STEPS_MIN), - clampAtLeast(prefs.getInt(KEY_CARDS_LOCK_MAX_ICONS_PER_ROW, SbtDefaults.CARDS_LOCK_MAX_ICONS_PER_ROW_DEFAULT), - SbtDefaults.CARDS_LOCK_MAX_ICONS_PER_ROW_MIN), - clampAtLeast(prefs.getInt(KEY_CARDS_LOCK_MAX_ROWS, SbtDefaults.CARDS_LOCK_MAX_ROWS_DEFAULT), - SbtDefaults.CARDS_LOCK_MAX_ROWS_MIN), - prefs.getBoolean(KEY_CARDS_LOCK_EVEN_DISTRIBUTION, SbtDefaults.CARDS_LOCK_EVEN_DISTRIBUTION_DEFAULT), - prefs.getBoolean(KEY_CARDS_LOCK_LIMIT_TO_WIDTH, SbtDefaults.CARDS_LOCK_LIMIT_TO_WIDTH_DEFAULT), - clampAtLeast(prefs.getInt(KEY_CARDS_LOCK_ICON_HEIGHT_STEPS, - SbtDefaults.LAYOUT_CARDS_NOTIF_LOCK_ICON_HEIGHT_STEPS_DEFAULT), - SbtDefaults.LAYOUT_ICON_HEIGHT_STEPS_MIN), - prefs.getBoolean(KEY_AOD_KEEP_VISIBLE_DURING_CALL, SbtDefaults.AOD_KEEP_VISIBLE_DURING_CALL_DEFAULT), - prefs.getBoolean(KEY_BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT, SbtDefaults.BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT_DEFAULT), - prefs.getBoolean(KEY_BATTERY_AOD_UNPLUGGED_PERCENT, SbtDefaults.BATTERY_AOD_UNPLUGGED_PERCENT_DEFAULT), prefs.getBoolean(KEY_BATTERY_BAR_ENABLED, SbtDefaults.BATTERY_BAR_ENABLED_DEFAULT), prefs.getString(KEY_BATTERY_BAR_POSITION, SbtDefaults.BATTERY_BAR_POSITION_DEFAULT), prefs.getString(KEY_BATTERY_BAR_ALIGNMENT, SbtDefaults.BATTERY_BAR_ALIGNMENT_DEFAULT), @@ -1410,13 +1192,6 @@ public final class SbtSettings { prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED, false), prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_CALL, false), prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_BATTERY, false), - AppIconRules.parseBlockedModes(readStringSet( - prefs, - KEY_APP_ICON_BLOCKED_MODES)), - AppIconRules.parseExceptionRules(readStringSet( - prefs, - KEY_APP_ICON_EXCEPTION_RULES)), - prefs.getString(KEY_LOCKED_NOTIFICATION_MODE, "dot"), prefs.getBoolean( KEY_DEBUG_VISUALIZE_NOTIFICATION_CONTAINER, SbtDefaults.DEBUG_VISUALIZE_NOTIFICATION_CONTAINER_DEFAULT), diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsProvider.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsProvider.java index 8c55209..b149f6c 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsProvider.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsProvider.java @@ -15,13 +15,8 @@ import java.util.Map; public class SbtSettingsProvider extends ContentProvider { public static final String AUTHORITY = "se.ajpanton.statusbartweak.settings"; - public static final String METHOD_GET_UNLOCKED = "get_unlocked"; public static final String METHOD_GET_ALL = "get_all"; public static final String METHOD_SET_CLOCK_CAMERA_DEBUG_STATE = "set_clock_camera_debug_state"; - public static final String METHOD_NOTE_SEEN_ICON_APP = "note_seen_icon_app"; - public static final String METHOD_SET_ACTIVE_ICON_APPS = "set_active_icon_apps"; - public static final String EXTRA_VALUE = "value"; - private static final Object LOCK = new Object(); @Override public boolean onCreate() { @@ -35,61 +30,8 @@ public class SbtSettingsProvider extends ContentProvider { return null; } SharedPreferences prefs = ctx.getSharedPreferences(SbtSettings.PREFS_NAME, Context.MODE_PRIVATE); - if (METHOD_GET_UNLOCKED.equals(method)) { - int value = prefs.getInt(SbtSettings.KEY_UNLOCKED_MAX_ICONS_PER_ROW, - SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT); - Bundle out = new Bundle(); - out.putInt(EXTRA_VALUE, value); - return out; - } if (METHOD_GET_ALL.equals(method)) { Bundle out = new Bundle(); - out.putBoolean(SbtSettings.KEY_ICONS_AOD_CUTOUT_LIMIT, - prefs.getBoolean(SbtSettings.KEY_ICONS_AOD_CUTOUT_LIMIT, SbtDefaults.ICONS_AOD_CUTOUT_LIMIT_DEFAULT)); - out.putBoolean(SbtSettings.KEY_ICONS_LOCK_CUTOUT_LIMIT, - prefs.getBoolean(SbtSettings.KEY_ICONS_LOCK_CUTOUT_LIMIT, SbtDefaults.ICONS_LOCK_CUTOUT_LIMIT_DEFAULT)); - out.putInt(SbtSettings.KEY_UNLOCKED_MAX_ICONS_PER_ROW, - prefs.getInt(SbtSettings.KEY_UNLOCKED_MAX_ICONS_PER_ROW, SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT)); - out.putInt(SbtSettings.KEY_ICONS_AOD_MAX_ICONS_PER_ROW, - prefs.getInt(SbtSettings.KEY_ICONS_AOD_MAX_ICONS_PER_ROW, SbtDefaults.ICONS_AOD_MAX_ICONS_PER_ROW_DEFAULT)); - out.putInt(SbtSettings.KEY_ICONS_AOD_MAX_ROWS, - prefs.getInt(SbtSettings.KEY_ICONS_AOD_MAX_ROWS, SbtDefaults.ICONS_AOD_MAX_ROWS_DEFAULT)); - out.putBoolean(SbtSettings.KEY_ICONS_AOD_EVEN_DISTRIBUTION, - prefs.getBoolean(SbtSettings.KEY_ICONS_AOD_EVEN_DISTRIBUTION, SbtDefaults.ICONS_AOD_EVEN_DISTRIBUTION_DEFAULT)); - out.putInt(SbtSettings.KEY_ICONS_LOCK_MAX_ICONS_PER_ROW, - prefs.getInt(SbtSettings.KEY_ICONS_LOCK_MAX_ICONS_PER_ROW, SbtDefaults.ICONS_LOCK_MAX_ICONS_PER_ROW_DEFAULT)); - out.putInt(SbtSettings.KEY_ICONS_LOCK_MAX_ROWS, - prefs.getInt(SbtSettings.KEY_ICONS_LOCK_MAX_ROWS, SbtDefaults.ICONS_LOCK_MAX_ROWS_DEFAULT)); - out.putBoolean(SbtSettings.KEY_ICONS_LOCK_EVEN_DISTRIBUTION, - prefs.getBoolean(SbtSettings.KEY_ICONS_LOCK_EVEN_DISTRIBUTION, SbtDefaults.ICONS_LOCK_EVEN_DISTRIBUTION_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_AOD_MAX_ICONS_PER_ROW, - prefs.getInt(SbtSettings.KEY_CARDS_AOD_MAX_ICONS_PER_ROW, SbtDefaults.CARDS_AOD_MAX_ICONS_PER_ROW_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_AOD_MAX_ROWS, - prefs.getInt(SbtSettings.KEY_CARDS_AOD_MAX_ROWS, SbtDefaults.CARDS_AOD_MAX_ROWS_DEFAULT)); - out.putBoolean(SbtSettings.KEY_CARDS_AOD_EVEN_DISTRIBUTION, - prefs.getBoolean(SbtSettings.KEY_CARDS_AOD_EVEN_DISTRIBUTION, SbtDefaults.CARDS_AOD_EVEN_DISTRIBUTION_DEFAULT)); - out.putBoolean(SbtSettings.KEY_CARDS_AOD_LIMIT_TO_WIDTH, - prefs.getBoolean(SbtSettings.KEY_CARDS_AOD_LIMIT_TO_WIDTH, SbtDefaults.CARDS_AOD_LIMIT_TO_WIDTH_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_AOD_ICON_HEIGHT_STEPS, - prefs.getInt(SbtSettings.KEY_CARDS_AOD_ICON_HEIGHT_STEPS, - SbtDefaults.LAYOUT_CARDS_NOTIF_AOD_ICON_HEIGHT_STEPS_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_LOCK_MAX_ICONS_PER_ROW, - prefs.getInt(SbtSettings.KEY_CARDS_LOCK_MAX_ICONS_PER_ROW, SbtDefaults.CARDS_LOCK_MAX_ICONS_PER_ROW_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_LOCK_MAX_ROWS, - prefs.getInt(SbtSettings.KEY_CARDS_LOCK_MAX_ROWS, SbtDefaults.CARDS_LOCK_MAX_ROWS_DEFAULT)); - out.putBoolean(SbtSettings.KEY_CARDS_LOCK_EVEN_DISTRIBUTION, - prefs.getBoolean(SbtSettings.KEY_CARDS_LOCK_EVEN_DISTRIBUTION, SbtDefaults.CARDS_LOCK_EVEN_DISTRIBUTION_DEFAULT)); - out.putBoolean(SbtSettings.KEY_CARDS_LOCK_LIMIT_TO_WIDTH, - prefs.getBoolean(SbtSettings.KEY_CARDS_LOCK_LIMIT_TO_WIDTH, SbtDefaults.CARDS_LOCK_LIMIT_TO_WIDTH_DEFAULT)); - out.putInt(SbtSettings.KEY_CARDS_LOCK_ICON_HEIGHT_STEPS, - prefs.getInt(SbtSettings.KEY_CARDS_LOCK_ICON_HEIGHT_STEPS, - SbtDefaults.LAYOUT_CARDS_NOTIF_LOCK_ICON_HEIGHT_STEPS_DEFAULT)); - out.putBoolean(SbtSettings.KEY_AOD_KEEP_VISIBLE_DURING_CALL, - prefs.getBoolean(SbtSettings.KEY_AOD_KEEP_VISIBLE_DURING_CALL, SbtDefaults.AOD_KEEP_VISIBLE_DURING_CALL_DEFAULT)); - out.putBoolean(SbtSettings.KEY_BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT, - prefs.getBoolean(SbtSettings.KEY_BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT, SbtDefaults.BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT_DEFAULT)); - out.putBoolean(SbtSettings.KEY_BATTERY_AOD_UNPLUGGED_PERCENT, - prefs.getBoolean(SbtSettings.KEY_BATTERY_AOD_UNPLUGGED_PERCENT, SbtDefaults.BATTERY_AOD_UNPLUGGED_PERCENT_DEFAULT)); out.putBoolean(SbtSettings.KEY_BATTERY_BAR_ENABLED, prefs.getBoolean(SbtSettings.KEY_BATTERY_BAR_ENABLED, SbtDefaults.BATTERY_BAR_ENABLED_DEFAULT)); out.putString(SbtSettings.KEY_BATTERY_BAR_POSITION, @@ -231,8 +173,6 @@ public class SbtSettingsProvider extends ContentProvider { out.putString(SbtSettings.KEY_LAYOUT_ITEM_ORDER, prefs.getString(SbtSettings.KEY_LAYOUT_ITEM_ORDER, SbtDefaults.LAYOUT_ITEM_ORDER_DEFAULT)); - out.putString(SbtSettings.KEY_LOCKED_NOTIFICATION_MODE, - prefs.getString(SbtSettings.KEY_LOCKED_NOTIFICATION_MODE, "dot")); out.putString(SbtSettings.KEY_LAYOUT_CARRIER_POSITION, prefs.getString(SbtSettings.KEY_LAYOUT_CARRIER_POSITION, SbtDefaults.LAYOUT_CARRIER_POSITION_DEFAULT)); @@ -405,51 +345,8 @@ public class SbtSettingsProvider extends ContentProvider { prefs.getBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_CALL, false)); out.putBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_BATTERY, prefs.getBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_BATTERY, false)); - putStringCollectionArrayList( - out, - SbtSettings.KEY_APP_ICON_BLOCKED_MODES, - AppIconRules.encodeBlockedModes(AppIconRules.loadBlockedModes(prefs))); - putStringCollectionArrayList( - out, - SbtSettings.KEY_APP_ICON_EXCEPTION_RULES, - AppIconRules.encodeExceptionRules(AppIconRules.loadExceptionRules(prefs))); return out; } - if (METHOD_NOTE_SEEN_ICON_APP.equals(method)) { - String pkg = extras != null ? extras.getString(AppIconRules.EXTRA_PACKAGE) : null; - long seenMs = extras != null - ? extras.getLong(AppIconRules.EXTRA_FIRST_SEEN_MS, System.currentTimeMillis()) - : System.currentTimeMillis(); - if (extras != null && extras.containsKey(AppIconRules.EXTRA_LAST_SEEN_MS)) { - seenMs = extras.getLong(AppIconRules.EXTRA_LAST_SEEN_MS, seenMs); - } - int offsetMinutes = extras != null - ? extras.getInt( - AppIconRules.EXTRA_LAST_SEEN_TIMEZONE_OFFSET_MINUTES, - AppIconRules.currentTimezoneOffsetMinutes()) - : AppIconRules.currentTimezoneOffsetMinutes(); - if (!AppIconRules.isValidPackageName(pkg)) { - return Bundle.EMPTY; - } - synchronized (LOCK) { - Map seen = AppIconRules.loadSeenSession(prefs); - if (AppIconRules.noteSeen(seen, pkg, seenMs, offsetMinutes)) { - AppIconRules.saveSeenSession(prefs, seen); - } - } - return Bundle.EMPTY; - } - if (METHOD_SET_ACTIVE_ICON_APPS.equals(method)) { - ArrayList packages = extras != null - ? extras.getStringArrayList(EXTRA_VALUE) - : null; - synchronized (LOCK) { - AppIconRules.saveActiveSession( - prefs, - packages != null ? new java.util.HashSet<>(packages) : Collections.emptySet()); - } - return Bundle.EMPTY; - } if (METHOD_SET_CLOCK_CAMERA_DEBUG_STATE.equals(method)) { String cameraId = extras != null ? extras.getString(SbtSettings.KEY_DEBUG_CURRENT_CAMERA_ID, "") : ""; String autoType = extras != null ? extras.getString(SbtSettings.KEY_DEBUG_CURRENT_CAMERA_AUTO_TYPE, "") : ""; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BlockAppNotificationIconsFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BlockAppNotificationIconsFragment.java deleted file mode 100644 index 512148e..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BlockAppNotificationIconsFragment.java +++ /dev/null @@ -1,156 +0,0 @@ -package se.ajpanton.statusbartweak.shell.ui; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ListView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import se.ajpanton.statusbartweak.R; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; -import se.ajpanton.statusbartweak.shell.settings.SbtDefaults; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; -import se.ajpanton.statusbartweak.shell.ui.HiddenAppsUiSupport.HiddenAppsAdapter; -import se.ajpanton.statusbartweak.shell.ui.HiddenAppsUiSupport.RowItem; - -public class BlockAppNotificationIconsFragment extends Fragment { - private final ArrayList rows = new ArrayList<>(); - private final Handler uiHandler = new Handler(Looper.getMainLooper()); - private HiddenAppsAdapter adapter; - private SharedPreferences prefs; - private PackageManager packageManager; - private Drawable fallbackIcon; - private TextView emptyView; - private ListView listView; - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, - @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View root = inflater.inflate(R.layout.fragment_block_app_notification_icons, container, false); - Context context = requireContext(); - prefs = context.getSharedPreferences(SbtSettings.PREFS_NAME, Context.MODE_PRIVATE); - packageManager = context.getPackageManager(); - fallbackIcon = packageManager.getDefaultActivityIcon(); - emptyView = root.findViewById(R.id.hidden_apps_empty); - listView = root.findViewById(R.id.hidden_apps_list); - SwipeRefreshLayout swipeRefresh = root.findViewById(R.id.hidden_apps_swipe); - View clearSessionButton = root.findViewById(R.id.hidden_apps_clear_session); - - adapter = new HiddenAppsAdapter(context, rows, (row, modeMask) -> { - if (!HiddenAppsUiSupport.toggleRowMode(row, modeMask)) { - return; - } - HiddenAppsUiSupport.persistRowState(requireContext(), prefs, row); - if (adapter != null) { - adapter.notifyDataSetChanged(); - } - }); - listView.setAdapter(adapter); - listView.setOnItemClickListener((parent, view, position, id) -> { - if (position < 0 || position >= rows.size()) { - return; - } - listView.clearChoices(); - adapter.notifyDataSetChanged(); - HiddenAppsUiSupport.flashRowTapFeedback(view); - HiddenAppsUiSupport.showModePopup(this, rows.get(position), changedRow -> { - HiddenAppsUiSupport.persistRowState(requireContext(), prefs, changedRow); - if (adapter != null) { - adapter.notifyDataSetChanged(); - } - }); - }); - swipeRefresh.setOnRefreshListener(() -> { - reloadRowsSnapshot(); - swipeRefresh.setRefreshing(false); - }); - clearSessionButton.setOnClickListener(v -> { - resetSeenSessionNow(); - reloadRowsSnapshot(); - scheduleAutoRefreshAfterClear(); - }); - reloadRowsSnapshot(); - applyLayoutAvailability(root); - return root; - } - - @Override - public void onDestroyView() { - uiHandler.removeCallbacksAndMessages(null); - super.onDestroyView(); - } - - private void resetSeenSessionNow() { - if (prefs == null) { - return; - } - Map seen = AppIconRules.loadSeenSession(prefs); - Set keep = new HashSet<>(AppIconRules.loadBlockedModes(prefs).keySet()); - keep.addAll(AppIconRules.loadActiveSession(prefs)); - seen.keySet().removeIf(pkg -> !keep.contains(pkg)); - AppIconRules.saveSeenSession(prefs, seen); - SbtSettings.ensureReadable(requireContext()); - } - - private void scheduleAutoRefreshAfterClear() { - uiHandler.removeCallbacksAndMessages(null); - uiHandler.postDelayed(this::reloadRowsSnapshot, 150); - uiHandler.postDelayed(this::reloadRowsSnapshot, 600); - uiHandler.postDelayed(this::reloadRowsSnapshot, 1400); - } - - private void reloadRowsSnapshot() { - HiddenAppsUiSupport.reloadRowsSnapshot(requireContext(), prefs, packageManager, fallbackIcon, rows); - - if (adapter != null) { - adapter.notifyDataSetChanged(); - } - updateEmptyState(); - } - - private void updateEmptyState() { - if (emptyView == null) { - return; - } - emptyView.setVisibility(rows.isEmpty() ? View.VISIBLE : View.GONE); - } - - private void applyLayoutAvailability(View root) { - if (root == null || prefs == null) { - return; - } - boolean enabled = prefs.getBoolean( - SbtSettings.KEY_CLOCK_ENABLED, - SbtDefaults.CLOCK_ENABLED_DEFAULT); - View content = root.findViewById(R.id.hidden_apps_content); - TextView disabledHint = root.findViewById(R.id.hidden_apps_disabled_hint); - if (content != null) { - ViewTreeSupport.setEnabledRecursive(content, enabled); - content.setAlpha(enabled ? 1f : 0.45f); - } - if (disabledHint != null) { - disabledHint.setVisibility(enabled ? View.GONE : View.VISIBLE); - disabledHint.setAlpha(1f); - } - } - -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/HiddenAppsUiSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/HiddenAppsUiSupport.java deleted file mode 100644 index 21a5d2e..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/HiddenAppsUiSupport.java +++ /dev/null @@ -1,910 +0,0 @@ -package se.ajpanton.statusbartweak.shell.ui; - -import se.ajpanton.statusbartweak.R; -import se.ajpanton.statusbartweak.shell.settings.AppIconRules; -import se.ajpanton.statusbartweak.shell.settings.SbtSettings; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.WindowManager; -import android.view.ViewParent; -import android.view.inputmethod.InputMethodManager; -import android.widget.Button; -import android.widget.BaseAdapter; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.core.content.ContextCompat; -import androidx.fragment.app.Fragment; -import androidx.recyclerview.widget.ItemTouchHelper; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.google.android.material.dialog.MaterialAlertDialogBuilder; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; - -@SuppressWarnings("deprecation") -final class HiddenAppsUiSupport { - interface RowChangedListener { - void onChanged(RowItem row); - } - - private static final int MODE_INDEX_AOD = 0; - private static final int MODE_INDEX_LOCK = 1; - private static final int MODE_INDEX_UNLOCK = 2; - - private static void bindModeIcon(ImageView icon, TextView cross, Drawable drawable, boolean blocked) { - if (icon == null || cross == null) { - return; - } - if (drawable != null && drawable.getConstantState() != null) { - icon.setImageDrawable(drawable.getConstantState().newDrawable().mutate()); - } else { - icon.setImageDrawable(drawable); - } - icon.setAlpha(blocked ? 0.25f : 1f); - cross.setVisibility(blocked ? View.VISIBLE : View.GONE); - } - - private HiddenAppsUiSupport() { - } - - static void reloadRowsSnapshot(Context context, - SharedPreferences prefs, - PackageManager packageManager, - Drawable fallbackIcon, - ArrayList rows) { - if (rows == null) { - return; - } - rows.clear(); - if (context == null || prefs == null || packageManager == null) { - return; - } - - Map blocked = AppIconRules.loadBlockedModes(prefs); - Map> exceptionRules = - AppIconRules.loadExceptionRules(prefs); - Map seen = AppIconRules.loadSeenSession(prefs); - - ArrayList blockedItems = new ArrayList<>(); - for (Map.Entry entry : blocked.entrySet()) { - String pkg = entry.getKey(); - Integer maskObj = entry.getValue(); - if (!AppIconRules.isValidPackageName(pkg) || maskObj == null) { - continue; - } - int mask = maskObj; - RowItem item = buildRowItem(context, packageManager, fallbackIcon, pkg); - item.blockAod = (mask & AppIconRules.MODE_AOD) != 0; - item.blockLock = (mask & AppIconRules.MODE_LOCK) != 0; - item.blockUnlock = (mask & AppIconRules.MODE_UNLOCK) != 0; - item.exceptionRules = toEditableExceptionRules(exceptionRules.get(pkg)); - applySeenInfo(item, seen.get(pkg)); - blockedItems.add(item); - } - blockedItems.sort((a, b) -> { - int byLabel = a.label.toLowerCase(Locale.ROOT).compareTo(b.label.toLowerCase(Locale.ROOT)); - if (byLabel != 0) { - return byLabel; - } - return a.packageName.compareTo(b.packageName); - }); - - rows.addAll(blockedItems); - Set alreadyAdded = new HashSet<>(); - for (RowItem item : blockedItems) { - alreadyAdded.add(item.packageName); - } - - List seenOldestFirst = AppIconRules.sortSeenOldestFirst(seen); - for (AppIconRules.SeenApp seenApp : seenOldestFirst) { - if (seenApp == null || !AppIconRules.isValidPackageName(seenApp.packageName)) { - continue; - } - if (alreadyAdded.contains(seenApp.packageName)) { - continue; - } - RowItem item = buildRowItem(context, packageManager, fallbackIcon, seenApp.packageName); - item.exceptionRules = toEditableExceptionRules(exceptionRules.get(seenApp.packageName)); - applySeenInfo(item, seenApp); - rows.add(item); - alreadyAdded.add(seenApp.packageName); - } - } - - private static void applySeenInfo(RowItem item, AppIconRules.SeenApp seenApp) { - if (item == null || seenApp == null) { - return; - } - item.lastSeenMs = seenApp.lastSeenMs; - item.lastSeenTimezoneOffsetMinutes = seenApp.lastSeenTimezoneOffsetMinutes; - } - - private static RowItem buildRowItem(Context context, - PackageManager packageManager, - Drawable fallbackIcon, - String packageName) { - String label = packageName; - Drawable icon = fallbackIcon; - try { - ApplicationInfo appInfo = packageManager.getApplicationInfo( - packageName, - PackageManager.ApplicationInfoFlags.of(0)); - CharSequence cs = packageManager.getApplicationLabel(appInfo); - if (cs != null && cs.length() > 0) { - label = cs.toString(); - } - icon = packageManager.getApplicationIcon(packageName); - } catch (PackageManager.NameNotFoundException ignored) { - // Keep fallback label/icon. - } - if (label == null || label.trim().isEmpty()) { - label = context.getString(R.string.hidden_apps_package_unknown); - } - return new RowItem(packageName, label, icon); - } - - static void showModePopup(Fragment host, RowItem row, RowChangedListener rowChangedListener) { - if (host == null || row == null) { - return; - } - Context context = host.requireContext(); - View content = LayoutInflater.from(context).inflate(R.layout.dialog_hidden_app_config, null, false); - TextView popupTitle = content.findViewById(R.id.hidden_app_config_title); - popupTitle.setText(row.label); - - View defaultAodCell = content.findViewById(R.id.hidden_app_default_aod_cell); - View defaultLockCell = content.findViewById(R.id.hidden_app_default_lock_cell); - View defaultUnlockCell = content.findViewById(R.id.hidden_app_default_unlock_cell); - ImageView defaultAodIcon = content.findViewById(R.id.hidden_app_default_aod_icon); - ImageView defaultLockIcon = content.findViewById(R.id.hidden_app_default_lock_icon); - ImageView defaultUnlockIcon = content.findViewById(R.id.hidden_app_default_unlock_icon); - TextView defaultAodCross = content.findViewById(R.id.hidden_app_default_aod_cross); - TextView defaultLockCross = content.findViewById(R.id.hidden_app_default_lock_cross); - TextView defaultUnlockCross = content.findViewById(R.id.hidden_app_default_unlock_cross); - RecyclerView exceptionsList = content.findViewById(R.id.hidden_app_exceptions_list); - View addException = content.findViewById(R.id.hidden_app_add_exception); - - final boolean[] defaultModes = new boolean[] { row.blockAod, row.blockLock, row.blockUnlock }; - bindModeIconTriple( - defaultAodIcon, defaultAodCross, - defaultLockIcon, defaultLockCross, - defaultUnlockIcon, defaultUnlockCross, - row.icon, - defaultModes[MODE_INDEX_AOD], - defaultModes[MODE_INDEX_LOCK], - defaultModes[MODE_INDEX_UNLOCK]); - final boolean[] originalModes = defaultModes.clone(); - bindPopupDefaultModeToggle(defaultAodCell, defaultAodIcon, defaultAodCross, - row.icon, defaultModes, MODE_INDEX_AOD, row, rowChangedListener); - bindPopupDefaultModeToggle(defaultLockCell, defaultLockIcon, defaultLockCross, - row.icon, defaultModes, MODE_INDEX_LOCK, row, rowChangedListener); - bindPopupDefaultModeToggle(defaultUnlockCell, defaultUnlockIcon, defaultUnlockCross, - row.icon, defaultModes, MODE_INDEX_UNLOCK, row, rowChangedListener); - - ArrayList workingRules = copyEditableExceptionRules(row.exceptionRules); - ExceptionRulesAdapter exceptionsAdapter = new ExceptionRulesAdapter( - context, - row.icon, - workingRules, - () -> requestExceptionsRelayout(exceptionsList)); - exceptionsList.setLayoutManager(new LinearLayoutManager(context)); - exceptionsList.setAdapter(exceptionsAdapter); - exceptionsList.setItemAnimator(null); - exceptionsList.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); - exceptionsList.setNestedScrollingEnabled(false); - - ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback( - ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) { - @Override - public boolean onMove(RecyclerView recyclerView, - RecyclerView.ViewHolder viewHolder, - RecyclerView.ViewHolder target) { - int from = viewHolder.getAdapterPosition(); - int to = target.getAdapterPosition(); - if (from < 0 || to < 0 || from >= workingRules.size() || to >= workingRules.size()) { - return false; - } - if (from == to) { - return true; - } - Collections.swap(workingRules, from, to); - exceptionsAdapter.notifyDataSetChanged(); - requestExceptionsRelayout(exceptionsList); - return true; - } - - @Override - public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { - // Not used. - } - - @Override - public boolean isLongPressDragEnabled() { - return true; - } - }); - itemTouchHelper.attachToRecyclerView(exceptionsList); - exceptionsAdapter.setItemTouchHelper(itemTouchHelper); - - addException.setOnClickListener(v -> { - workingRules.add(new EditableExceptionRule()); - int pos = workingRules.size() - 1; - exceptionsAdapter.notifyDataSetChanged(); - requestExceptionsRelayout(exceptionsList); - exceptionsList.post(() -> exceptionsList.scrollToPosition(pos)); - }); - - Runnable revertDefaults = () -> { - if (row.blockAod != originalModes[MODE_INDEX_AOD] - || row.blockLock != originalModes[MODE_INDEX_LOCK] - || row.blockUnlock != originalModes[MODE_INDEX_UNLOCK]) { - row.blockAod = originalModes[MODE_INDEX_AOD]; - row.blockLock = originalModes[MODE_INDEX_LOCK]; - row.blockUnlock = originalModes[MODE_INDEX_UNLOCK]; - notifyRowChanged(rowChangedListener, row); - } - }; - androidx.appcompat.app.AlertDialog dialog = new MaterialAlertDialogBuilder(context) - .setView(content) - .setNegativeButton(android.R.string.cancel, (d, w) -> revertDefaults.run()) - .setPositiveButton(android.R.string.ok, (dlg, which) -> { - row.blockAod = defaultModes[MODE_INDEX_AOD]; - row.blockLock = defaultModes[MODE_INDEX_LOCK]; - row.blockUnlock = defaultModes[MODE_INDEX_UNLOCK]; - row.exceptionRules = copyEditableExceptionRules(workingRules); - notifyRowChanged(rowChangedListener, row); - }) - .show(); - dialog.setCanceledOnTouchOutside(true); - dialog.setOnCancelListener(d -> revertDefaults.run()); - if (dialog.getWindow() != null) { - dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); - dialog.getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE - | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); - dialog.getWindow().setLayout( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - } - compactDialogButtons(dialog, context); - requestExceptionsRelayout(exceptionsList); - } - - static void persistRowState(Context context, SharedPreferences prefs, RowItem row) { - if (context == null || prefs == null || row == null) { - return; - } - Map blocked = AppIconRules.loadBlockedModes(prefs); - Map> exceptionRules = AppIconRules.loadExceptionRules(prefs); - AppIconRules.setModeBlocked(blocked, row.packageName, row.blockAod, row.blockLock, row.blockUnlock); - AppIconRules.setExceptionRules(exceptionRules, row.packageName, toPersistedExceptionRules(row.exceptionRules)); - AppIconRules.saveBlockedModes(prefs, blocked); - AppIconRules.saveExceptionRules(prefs, exceptionRules); - SbtSettings.ensureReadable(context); - } - - static boolean toggleRowMode(RowItem row, int modeMask) { - if (row == null) { - return false; - } - if (modeMask == AppIconRules.MODE_AOD) { - row.blockAod = !row.blockAod; - return true; - } - if (modeMask == AppIconRules.MODE_LOCK) { - row.blockLock = !row.blockLock; - return true; - } - if (modeMask == AppIconRules.MODE_UNLOCK) { - row.blockUnlock = !row.blockUnlock; - return true; - } - return false; - } - - static void flashRowTapFeedback(View rowView) { - if (rowView == null) { - return; - } - rowView.setPressed(true); - rowView.postDelayed(() -> { - rowView.setPressed(false); - rowView.jumpDrawablesToCurrentState(); - }, 120L); - } - - private static void notifyRowChanged(RowChangedListener listener, RowItem row) { - if (listener != null && row != null) { - listener.onChanged(row); - } - } - - private static void bindPopupDefaultModeToggle(View target, - ImageView icon, - TextView cross, - Drawable drawable, - boolean[] defaultModes, - int modeIndex, - RowItem row, - RowChangedListener listener) { - if (defaultModes == null || modeIndex < 0 || modeIndex >= defaultModes.length) { - return; - } - if (target == null) { - return; - } - target.setOnClickListener(v -> { - defaultModes[modeIndex] = !defaultModes[modeIndex]; - bindModeIcon(icon, cross, drawable, defaultModes[modeIndex]); - applyModeIndexToRow(row, modeIndex, defaultModes[modeIndex]); - notifyRowChanged(listener, row); - }); - } - - private static void applyModeIndexToRow(RowItem row, int modeIndex, boolean blocked) { - if (row == null) { - return; - } - if (modeIndex == MODE_INDEX_AOD) { - row.blockAod = blocked; - } else if (modeIndex == MODE_INDEX_LOCK) { - row.blockLock = blocked; - } else if (modeIndex == MODE_INDEX_UNLOCK) { - row.blockUnlock = blocked; - } - } - - private static void bindModeIconTriple(ImageView aodIcon, - TextView aodCross, - ImageView lockIcon, - TextView lockCross, - ImageView unlockIcon, - TextView unlockCross, - Drawable drawable, - boolean blockAod, - boolean blockLock, - boolean blockUnlock) { - bindModeIcon(aodIcon, aodCross, drawable, blockAod); - bindModeIcon(lockIcon, lockCross, drawable, blockLock); - bindModeIcon(unlockIcon, unlockCross, drawable, blockUnlock); - } - - private static void requestExceptionsRelayout(RecyclerView list) { - if (list == null) { - return; - } - list.post(() -> { - list.requestLayout(); - ViewParent parent = list.getParent(); - if (parent instanceof View) { - ((View) parent).requestLayout(); - ViewParent gp = parent.getParent(); - if (gp instanceof View) { - ((View) gp).requestLayout(); - } - } - }); - } - - private static ArrayList toEditableExceptionRules(List rules) { - ArrayList out = new ArrayList<>(); - if (rules == null) { - return out; - } - for (AppIconRules.ExceptionRule rule : rules) { - if (rule == null) { - continue; - } - EditableExceptionRule editable = new EditableExceptionRule(); - editable.regex = normalizeRegex(rule.regex); - editable.blockAod = (rule.modeMask & AppIconRules.MODE_AOD) != 0; - editable.blockLock = (rule.modeMask & AppIconRules.MODE_LOCK) != 0; - editable.blockUnlock = (rule.modeMask & AppIconRules.MODE_UNLOCK) != 0; - if (editable.regex != null) { - out.add(editable); - } - } - return out; - } - - private static ArrayList copyEditableExceptionRules(List source) { - ArrayList out = new ArrayList<>(); - if (source == null) { - return out; - } - for (EditableExceptionRule rule : source) { - if (rule == null) { - continue; - } - EditableExceptionRule copy = new EditableExceptionRule(); - copy.regex = normalizeRegex(rule.regex); - copy.blockAod = rule.blockAod; - copy.blockLock = rule.blockLock; - copy.blockUnlock = rule.blockUnlock; - out.add(copy); - } - return out; - } - - private static ArrayList toPersistedExceptionRules(List source) { - ArrayList out = new ArrayList<>(); - if (source == null) { - return out; - } - for (EditableExceptionRule rule : source) { - if (rule == null) { - continue; - } - String regex = normalizeRegex(rule.regex); - if (regex == null) { - continue; - } - int mask = 0; - if (rule.blockAod) { - mask |= AppIconRules.MODE_AOD; - } - if (rule.blockLock) { - mask |= AppIconRules.MODE_LOCK; - } - if (rule.blockUnlock) { - mask |= AppIconRules.MODE_UNLOCK; - } - out.add(new AppIconRules.ExceptionRule(regex, mask)); - } - return out; - } - - private static String normalizeRegex(String raw) { - if (raw == null) { - return null; - } - String normalized = raw.trim(); - return normalized.isEmpty() ? null : normalized; - } - - private static String formatLastSeen(Context context, RowItem row) { - if (context == null || row == null || row.lastSeenMs <= 0L) { - return null; - } - int offsetMinutes = row.lastSeenTimezoneOffsetMinutes; - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT); - format.setTimeZone(timeZoneForOffset(offsetMinutes)); - String timestamp = format.format(new Date(row.lastSeenMs)); - int currentOffsetMinutes = AppIconRules.currentTimezoneOffsetMinutes(); - if (offsetMinutes != currentOffsetMinutes) { - timestamp += formatOffsetSuffix(offsetMinutes); - } - return context.getString(R.string.hidden_apps_last_seen, timestamp); - } - - private static TimeZone timeZoneForOffset(int offsetMinutes) { - int absMinutes = Math.abs(offsetMinutes); - int hours = absMinutes / 60; - int minutes = absMinutes % 60; - String id = String.format(Locale.ROOT, "GMT%s%02d:%02d", - offsetMinutes < 0 ? "-" : "+", hours, minutes); - return TimeZone.getTimeZone(id); - } - - private static String formatOffsetSuffix(int offsetMinutes) { - int absMinutes = Math.abs(offsetMinutes); - int hours = absMinutes / 60; - int minutes = absMinutes % 60; - if (minutes == 0) { - return String.format(Locale.ROOT, "%s%02d", offsetMinutes < 0 ? "-" : "+", hours); - } - return String.format(Locale.ROOT, "%s%02d:%02d", - offsetMinutes < 0 ? "-" : "+", hours, minutes); - } - - static final class RowItem { - final String packageName; - final String label; - final Drawable icon; - boolean blockAod; - boolean blockLock; - boolean blockUnlock; - long lastSeenMs; - int lastSeenTimezoneOffsetMinutes; - ArrayList exceptionRules = new ArrayList<>(); - - RowItem(String packageName, String label, Drawable icon) { - this.packageName = packageName; - this.label = label; - this.icon = icon; - } - - boolean hasAnyBlocked() { - return blockAod || blockLock || blockUnlock; - } - - int exceptionCount() { - int count = 0; - for (EditableExceptionRule rule : exceptionRules) { - if (rule != null && normalizeRegex(rule.regex) != null) { - count++; - } - } - return count; - } - } - - static final class EditableExceptionRule { - String regex; - boolean blockAod; - boolean blockLock; - boolean blockUnlock; - } - - interface RowModeToggleListener { - void onToggle(RowItem row, int modeMask); - } - - private static final class RowHolder { - View root; - View iconAodCell; - View iconLockCell; - View iconUnlockCell; - ImageView iconAod; - ImageView iconLock; - ImageView iconUnlock; - TextView crossAod; - TextView crossLock; - TextView crossUnlock; - TextView label; - TextView pkg; - TextView lastSeen; - } - - static final class HiddenAppsAdapter extends BaseAdapter { - private final Context context; - private final ArrayList rows; - private final RowModeToggleListener rowModeToggleListener; - - HiddenAppsAdapter(Context context, - ArrayList rows, - RowModeToggleListener rowModeToggleListener) { - this.context = context; - this.rows = rows; - this.rowModeToggleListener = rowModeToggleListener; - } - - @Override - public int getCount() { - return rows != null ? rows.size() : 0; - } - - @Override - public Object getItem(int position) { - if (rows == null || position < 0 || position >= rows.size()) { - return null; - } - return rows.get(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - RowHolder holder; - if (convertView == null) { - convertView = LayoutInflater.from(context).inflate(R.layout.item_hidden_app, parent, false); - holder = new RowHolder(); - holder.root = convertView.findViewById(R.id.hidden_item_root); - holder.iconAodCell = convertView.findViewById(R.id.icon_mode_aod_cell); - holder.iconLockCell = convertView.findViewById(R.id.icon_mode_lock_cell); - holder.iconUnlockCell = convertView.findViewById(R.id.icon_mode_unlock_cell); - holder.iconAod = convertView.findViewById(R.id.icon_mode_aod); - holder.iconLock = convertView.findViewById(R.id.icon_mode_lock); - holder.iconUnlock = convertView.findViewById(R.id.icon_mode_unlock); - holder.crossAod = convertView.findViewById(R.id.icon_mode_aod_cross); - holder.crossLock = convertView.findViewById(R.id.icon_mode_lock_cross); - holder.crossUnlock = convertView.findViewById(R.id.icon_mode_unlock_cross); - holder.label = convertView.findViewById(R.id.hidden_item_label); - holder.pkg = convertView.findViewById(R.id.hidden_item_package); - holder.lastSeen = convertView.findViewById(R.id.hidden_item_last_seen); - convertView.setTag(holder); - } else { - holder = (RowHolder) convertView.getTag(); - } - - RowItem row = rows.get(position); - holder.label.setText(row.label); - int exceptionCount = row.exceptionCount(); - if (exceptionCount > 0) { - holder.pkg.setText(context.getResources().getQuantityString( - R.plurals.hidden_apps_package_with_exceptions, - exceptionCount, - row.packageName, - exceptionCount)); - } else { - holder.pkg.setText(row.packageName); - } - String lastSeenText = formatLastSeen(context, row); - if (lastSeenText == null) { - holder.lastSeen.setVisibility(View.GONE); - holder.lastSeen.setText(""); - } else { - holder.lastSeen.setVisibility(View.VISIBLE); - holder.lastSeen.setText(lastSeenText); - } - bindModeIconTriple( - holder.iconAod, holder.crossAod, - holder.iconLock, holder.crossLock, - holder.iconUnlock, holder.crossUnlock, - row.icon, - row.blockAod, row.blockLock, row.blockUnlock); - - int bg = row.hasAnyBlocked() - ? ContextCompat.getColor(context, R.color.sbt_hidden_item_active_bg) - : Color.TRANSPARENT; - holder.root.setBackgroundColor(bg); - holder.root.setPressed(false); - - bindModeToggle(holder.iconAodCell, row, AppIconRules.MODE_AOD); - bindModeToggle(holder.iconLockCell, row, AppIconRules.MODE_LOCK); - bindModeToggle(holder.iconUnlockCell, row, AppIconRules.MODE_UNLOCK); - - return convertView; - } - - private void bindModeToggle(View target, RowItem row, int modeMask) { - if (target == null) { - return; - } - target.setOnClickListener(v -> { - if (rowModeToggleListener != null) { - rowModeToggleListener.onToggle(row, modeMask); - } - }); - } - - } - - private static final class ExceptionRuleHolder extends RecyclerView.ViewHolder { - final View dragRoot; - final TextView title; - final TextView deleteButton; - final EditText regexField; - final View aodCell; - final View lockCell; - final View unlockCell; - final ImageView aodIcon; - final ImageView lockIcon; - final ImageView unlockIcon; - final TextView aodCross; - final TextView lockCross; - final TextView unlockCross; - TextWatcher watcher; - - ExceptionRuleHolder(View itemView) { - super(itemView); - dragRoot = itemView.findViewById(R.id.exception_rule_drag_root); - title = itemView.findViewById(R.id.exception_rule_title); - deleteButton = itemView.findViewById(R.id.exception_rule_delete); - regexField = itemView.findViewById(R.id.exception_rule_regex); - aodCell = itemView.findViewById(R.id.exception_rule_aod_cell); - lockCell = itemView.findViewById(R.id.exception_rule_lock_cell); - unlockCell = itemView.findViewById(R.id.exception_rule_unlock_cell); - aodIcon = itemView.findViewById(R.id.exception_rule_aod_icon); - lockIcon = itemView.findViewById(R.id.exception_rule_lock_icon); - unlockIcon = itemView.findViewById(R.id.exception_rule_unlock_icon); - aodCross = itemView.findViewById(R.id.exception_rule_aod_cross); - lockCross = itemView.findViewById(R.id.exception_rule_lock_cross); - unlockCross = itemView.findViewById(R.id.exception_rule_unlock_cross); - } - } - - private static final class ExceptionRulesAdapter - extends RecyclerView.Adapter { - private final Context context; - private final Drawable appIcon; - private final ArrayList rules; - private ItemTouchHelper itemTouchHelper; - private final Runnable onRulesCountChanged; - - ExceptionRulesAdapter(Context context, - Drawable appIcon, - ArrayList rules, - Runnable onRulesCountChanged) { - this.context = context; - this.appIcon = appIcon; - this.rules = rules; - this.onRulesCountChanged = onRulesCountChanged; - } - - void setItemTouchHelper(ItemTouchHelper itemTouchHelper) { - this.itemTouchHelper = itemTouchHelper; - } - - @Override - public ExceptionRuleHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(context) - .inflate(R.layout.item_hidden_app_exception_rule, parent, false); - RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - view.setLayoutParams(lp); - return new ExceptionRuleHolder(view); - } - - @Override - public void onBindViewHolder(ExceptionRuleHolder holder, int position) { - EditableExceptionRule rule = rules.get(position); - holder.title.setText(context.getString(R.string.hidden_apps_exception_label, position + 1)); - if (holder.watcher != null) { - holder.regexField.removeTextChangedListener(holder.watcher); - } - holder.regexField.setText(rule.regex != null ? rule.regex : ""); - holder.watcher = new SimpleTextWatcher() { - @Override - public void afterTextChanged(Editable s) { - int pos = holder.getAdapterPosition(); - if (pos == RecyclerView.NO_POSITION || pos >= rules.size()) { - return; - } - rules.get(pos).regex = s != null ? s.toString() : null; - } - }; - holder.regexField.addTextChangedListener(holder.watcher); - holder.regexField.setOnFocusChangeListener((v, hasFocus) -> { - if (hasFocus) { - showKeyboard(holder.regexField); - } - }); - holder.regexField.setOnClickListener(v -> showKeyboard(holder.regexField)); - holder.regexField.setOnTouchListener((v, event) -> { - v.getParent().requestDisallowInterceptTouchEvent(true); - return false; - }); - - bindModeIconTriple( - holder.aodIcon, holder.aodCross, - holder.lockIcon, holder.lockCross, - holder.unlockIcon, holder.unlockCross, - appIcon, - rule.blockAod, rule.blockLock, rule.blockUnlock); - bindExceptionModeToggle(holder, holder.aodCell, AppIconRules.MODE_AOD); - bindExceptionModeToggle(holder, holder.lockCell, AppIconRules.MODE_LOCK); - bindExceptionModeToggle(holder, holder.unlockCell, AppIconRules.MODE_UNLOCK); - - holder.deleteButton.setOnClickListener(v -> { - int pos = holder.getAdapterPosition(); - if (pos == RecyclerView.NO_POSITION || pos >= rules.size()) { - return; - } - rules.remove(pos); - notifyDataSetChanged(); - if (onRulesCountChanged != null) { - onRulesCountChanged.run(); - } - }); - - holder.dragRoot.setOnLongClickListener(v -> { - if (itemTouchHelper != null) { - itemTouchHelper.startDrag(holder); - return true; - } - return false; - }); - } - - @Override - public int getItemCount() { - return rules != null ? rules.size() : 0; - } - - private void bindExceptionModeToggle(ExceptionRuleHolder holder, View target, int modeMask) { - if (target == null) { - return; - } - target.setOnClickListener(v -> { - int pos = holder.getAdapterPosition(); - if (pos == RecyclerView.NO_POSITION || pos >= rules.size()) { - return; - } - EditableExceptionRule r = rules.get(pos); - if (modeMask == AppIconRules.MODE_AOD) { - r.blockAod = !r.blockAod; - } else if (modeMask == AppIconRules.MODE_LOCK) { - r.blockLock = !r.blockLock; - } else if (modeMask == AppIconRules.MODE_UNLOCK) { - r.blockUnlock = !r.blockUnlock; - } - bindModeIconTriple( - holder.aodIcon, holder.aodCross, - holder.lockIcon, holder.lockCross, - holder.unlockIcon, holder.unlockCross, - appIcon, - r.blockAod, r.blockLock, r.blockUnlock); - }); - } - } - - private abstract static class SimpleTextWatcher implements TextWatcher { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - } - - private static void showKeyboard(EditText field) { - if (field == null) { - return; - } - field.post(() -> { - field.requestFocus(); - InputMethodManager imm = (InputMethodManager) field.getContext() - .getSystemService(Context.INPUT_METHOD_SERVICE); - if (imm != null) { - field.requestFocusFromTouch(); - boolean shown = imm.showSoftInput(field, InputMethodManager.SHOW_IMPLICIT); - if (!shown) { - imm.showSoftInput(field, InputMethodManager.SHOW_FORCED); - } - } - }); - } - - private static void compactDialogButtons(androidx.appcompat.app.AlertDialog dialog, Context context) { - if (dialog == null || context == null) { - return; - } - int small = Math.round(2f * context.getResources().getDisplayMetrics().density); - Button pos = dialog.getButton(androidx.appcompat.app.AlertDialog.BUTTON_POSITIVE); - Button neg = dialog.getButton(androidx.appcompat.app.AlertDialog.BUTTON_NEGATIVE); - int actionColor = ContextCompat.getColor(context, R.color.sbt_accent_dark); - if (pos != null) { - pos.setMinHeight(0); - pos.setMinimumHeight(0); - pos.setPadding(pos.getPaddingLeft(), small, pos.getPaddingRight(), small); - pos.setTextColor(actionColor); - } - if (neg != null) { - neg.setMinHeight(0); - neg.setMinimumHeight(0); - neg.setPadding(neg.getPaddingLeft(), small, neg.getPaddingRight(), small); - neg.setTextColor(actionColor); - } - if (pos != null) { - ViewParent p = pos.getParent(); - if (p instanceof ViewGroup) { - ViewGroup panel = (ViewGroup) p; - panel.setPadding(panel.getPaddingLeft(), small, panel.getPaddingRight(), small); - ViewParent gp = panel.getParent(); - if (gp instanceof ViewGroup) { - ViewGroup gpGroup = (ViewGroup) gp; - gpGroup.setPadding(gpGroup.getPaddingLeft(), small, gpGroup.getPaddingRight(), small); - } - } - } - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/IconsDebugFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/IconsDebugFragment.java index 9ea49ca..0194760 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/IconsDebugFragment.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/IconsDebugFragment.java @@ -1,9 +1,7 @@ package se.ajpanton.statusbartweak.shell.ui; -import android.Manifest; import android.content.Context; import android.content.SharedPreferences; -import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; @@ -15,7 +13,6 @@ import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.google.android.material.button.MaterialButton; @@ -28,29 +25,17 @@ import java.util.Map; import se.ajpanton.statusbartweak.R; import se.ajpanton.statusbartweak.platform.SystemUiCapabilities; -import se.ajpanton.statusbartweak.shell.debug.DebugNotifications; import se.ajpanton.statusbartweak.shell.settings.ClockCameraTypeSupport; import se.ajpanton.statusbartweak.shell.settings.SbtDefaults; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; public class IconsDebugFragment extends Fragment { - private static final int REQUEST_POST_NOTIFICATIONS = 1001; - - private TextView countView; - private int currentCount; - @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_icons_debug, container, false); - countView = root.findViewById(R.id.debug_count_value); - MaterialButton minus10 = root.findViewById(R.id.btn_minus_10); - MaterialButton minus1 = root.findViewById(R.id.btn_minus_1); - MaterialButton plus1 = root.findViewById(R.id.btn_plus_1); - MaterialButton plus10 = root.findViewById(R.id.btn_plus_10); - MaterialButton reset = root.findViewById(R.id.btn_reset); SwitchMaterial writeLogsSwitch = root.findViewById(R.id.debug_write_logs_switch); SwitchMaterial visualizeNotificationContainerSwitch = root.findViewById(R.id.debug_visualize_notification_container_switch); @@ -67,7 +52,6 @@ public class IconsDebugFragment extends Fragment { MaterialButton restartSystemUiButton = root.findViewById(R.id.debug_restart_systemui_button); SwitchMaterial experimentalAodStatusbarRootSwitch = root.findViewById(R.id.debug_experimental_aod_statusbar_root_switch); - SwitchMaterial cycleIconsSwitch = root.findViewById(R.id.debug_cycle_icons_switch); TextView currentCameraIdentified = root.findViewById(R.id.debug_camera_current_identified); LinearLayout currentCameraOverrideRow = root.findViewById(R.id.debug_camera_current_override_row); TextView currentCameraOverride = root.findViewById(R.id.debug_camera_current_override); @@ -75,20 +59,6 @@ public class IconsDebugFragment extends Fragment { View otherCameraSection = root.findViewById(R.id.debug_camera_other_section); LinearLayout otherCameraList = root.findViewById(R.id.debug_camera_other_list); - currentCount = DebugNotifications.getDesiredCount(requireContext()); - updateCountLabel(); - bindCycleSwitch(cycleIconsSwitch); - styleCompactCounterButton(minus10); - styleCompactCounterButton(minus1); - styleCompactCounterButton(plus1); - styleCompactCounterButton(plus10); - - minus10.setOnClickListener(v -> adjustCount(-10)); - minus1.setOnClickListener(v -> adjustCount(-1)); - plus1.setOnClickListener(v -> adjustCount(1)); - plus10.setOnClickListener(v -> adjustCount(10)); - reset.setOnClickListener(v -> setCount(0)); - SharedPreferences prefs = requireContext() .getSharedPreferences(SbtSettings.PREFS_NAME, Context.MODE_PRIVATE); ViewTreeSupport.bindBooleanPreference( @@ -202,10 +172,6 @@ public class IconsDebugFragment extends Fragment { return root; } - private void styleCompactCounterButton(MaterialButton button) { - ViewTreeSupport.styleCompactButtonText(button, 13f); - } - private void bindRestartSystemUiButton(MaterialButton restartButton) { if (restartButton == null) { return; @@ -263,70 +229,6 @@ public class IconsDebugFragment extends Fragment { }, "StatusBarTweak:SystemUIRestart").start(); } - private void bindCycleSwitch(SwitchMaterial cycleSwitch) { - if (cycleSwitch == null) { - return; - } - Context context = requireContext(); - cycleSwitch.setChecked(DebugNotifications.isCycleEnabled(context)); - cycleSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { - if (isChecked) { - ensureNotificationPermission(); - } - DebugNotifications.setCycleEnabled(context, isChecked); - }); - } - - private void adjustCount(int delta) { - setCount(currentCount + delta); - } - - private void setCount(int value) { - int clamped = DebugNotifications.clampCount(value); - if (clamped == currentCount) { - return; - } - currentCount = clamped; - updateCountLabel(); - if (currentCount > 0) { - ensureNotificationPermission(); - } - DebugNotifications.setDesiredCount(requireContext(), currentCount); - } - - private void updateCountLabel() { - if (countView != null) { - countView.setText(String.valueOf(currentCount)); - } - } - - @SuppressWarnings("deprecation") - private void ensureNotificationPermission() { - Context context = requireContext(); - if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) - == PackageManager.PERMISSION_GRANTED) { - return; - } - requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_POST_NOTIFICATIONS); - Toast.makeText( - context, - R.string.debug_notification_permission_required, - Toast.LENGTH_SHORT).show(); - } - - @SuppressWarnings("deprecation") - @Override - public void onRequestPermissionsResult(int requestCode, - @NonNull String[] permissions, - @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if (requestCode == REQUEST_POST_NOTIFICATIONS - && grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - DebugNotifications.applyPending(requireContext()); - } - } - private void updateCameraUi(SharedPreferences prefs, TextView identifiedView, LinearLayout overrideRow, diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutFragment.java index 20a0640..af8fc0e 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutFragment.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutFragment.java @@ -131,7 +131,6 @@ public final class LayoutFragment extends Fragment { root.findViewById(R.id.clock_position_mode_unlocked), LayoutSectionCopySupport.Mode.UNLOCKED, LayoutSectionCopySupport.Section.CLOCK, - false, this::refreshSelf); bindCheckBoxPref(prefs, root.findViewById(R.id.notif_position_mode_unlocked), SbtSettings.KEY_LAYOUT_NOTIF_ENABLED_UNLOCKED, @@ -221,15 +220,12 @@ public final class LayoutFragment extends Fragment { countDefault); LayoutXmlCardSupport.setIndexedCardTitle(requireContext(), sourceCard, sectionTitleId, 0, count); setCompatPadding(sourceCard, count <= 1); - boolean cardsMode = LockedNotificationModeUi.MODE_CARDS.equals( - LockedNotificationModeUi.currentMode(requireContext())); LayoutSectionCopySupport.addDropdownRow( requireContext(), prefs, countContainer, LayoutSectionCopySupport.Mode.UNLOCKED, copySection, - cardsMode, 0, this::refreshSelf); countContainer.addView(ViewTreeSupport.iconContainerCountControl( diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutHomeFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutHomeFragment.java index 3cca87b..ad0416c 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutHomeFragment.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutHomeFragment.java @@ -7,7 +7,6 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; -import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.TextView; @@ -24,9 +23,6 @@ import se.ajpanton.statusbartweak.shell.settings.SbtSettings; public final class LayoutHomeFragment extends Fragment { private LinearLayout layoutOnContainer; private LinearLayout miscLayoutOnContainer; - private LinearLayout miscUnlockedOffOnlyContainer; - private RadioGroup lockedModeGroup; - private TextView lockedModeHint; @Nullable @Override @@ -52,14 +48,6 @@ public final class LayoutHomeFragment extends Fragment { master.setChecked(prefs.getBoolean(SbtSettings.KEY_CLOCK_ENABLED, SbtDefaults.CLOCK_ENABLED_DEFAULT)); root.addView(outlinedCard(context, R.string.layout_master_toggle_title, master)); - lockedModeGroup = new RadioGroup(context); - lockedModeGroup.setOrientation(RadioGroup.VERTICAL); - lockedModeHint = ViewTreeSupport.bodyText(context, R.string.layout_locked_notifications_hint, 0); - LinearLayout lockedContent = ViewTreeSupport.verticalLayout(context); - lockedContent.addView(lockedModeHint); - lockedContent.addView(lockedModeGroup); - root.addView(outlinedCard(context, R.string.layout_locked_notifications_title, lockedContent)); - layoutOnContainer = ViewTreeSupport.verticalLayout(context); layoutOnContainer.addView(paddingCard(context, prefs)); layoutOnContainer.addView(LayoutOrderingUi.createCard(context, prefs)); @@ -67,7 +55,7 @@ public final class LayoutHomeFragment extends Fragment { root.addView(miscCard(context, prefs)); - Runnable refreshAvailability = () -> refreshAvailability(context, prefs, master.isChecked()); + Runnable refreshAvailability = () -> refreshAvailability(master.isChecked()); master.setOnCheckedChangeListener((buttonView, isChecked) -> { prefs.edit().putBoolean(SbtSettings.KEY_CLOCK_ENABLED, isChecked).apply(); SbtSettings.ensureReadable(context); @@ -77,18 +65,11 @@ public final class LayoutHomeFragment extends Fragment { return scroll; } - private void refreshAvailability(Context context, SharedPreferences prefs, boolean layoutEnabled) { + private void refreshAvailability(boolean layoutEnabled) { ViewTreeSupport.setEnabledRecursive(layoutOnContainer, layoutEnabled); layoutOnContainer.setAlpha(layoutEnabled ? 1f : 0.45f); ViewTreeSupport.setEnabledRecursive(miscLayoutOnContainer, layoutEnabled); miscLayoutOnContainer.setAlpha(layoutEnabled ? 1f : 0.45f); - ViewTreeSupport.setEnabledRecursive(miscUnlockedOffOnlyContainer, !layoutEnabled); - miscUnlockedOffOnlyContainer.setAlpha(layoutEnabled ? 0.45f : 1f); - LockedNotificationModeUi.bind( - context, - prefs, - lockedModeGroup, - lockedModeHint); } private View paddingCard(Context context, SharedPreferences prefs) { @@ -153,16 +134,6 @@ public final class LayoutHomeFragment extends Fragment { SbtDefaults.LAYOUT_IGNORE_UNDER_DISPLAY_CAMERAS_DEFAULT, false)); content.addView(miscLayoutOnContainer); - miscUnlockedOffOnlyContainer = ViewTreeSupport.verticalLayout(context); - miscUnlockedOffOnlyContainer.addView(stepper( - context, - prefs, - R.string.label_max_unlocked_icons_per_row, - SbtSettings.KEY_UNLOCKED_MAX_ICONS_PER_ROW, - SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_DEFAULT, - SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_MIN, - SbtDefaults.UNLOCKED_MAX_ICONS_PER_ROW_MAX)); - content.addView(miscUnlockedOffOnlyContainer); return outlinedCard(context, R.string.layout_misc_title, content); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutSectionCopySupport.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutSectionCopySupport.java index f8e6893..fd6c5ab 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutSectionCopySupport.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/LayoutSectionCopySupport.java @@ -31,8 +31,7 @@ final class LayoutSectionCopySupport { enum Section { CLOCK, STATUS, - NOTIFICATIONS_ICONS, - NOTIFICATIONS_CARDS + NOTIFICATIONS_ICONS } private static final int MAX_COPIES = SbtDefaults.LAYOUT_ICON_CONTAINER_COUNT_MAX; @@ -46,13 +45,12 @@ final class LayoutSectionCopySupport { CheckBox enabled, Mode destinationMode, Section section, - boolean cardsMode, @Nullable Runnable refresh ) { if (context == null || prefs == null || enabled == null) { return; } - ArrayList