From 23dfc1dc5296b55dfad0d6bd3f2c37d8553f7e8f Mon Sep 17 00:00:00 2001 From: ajp_anton Date: Sat, 17 Oct 2026 02:10:36 +0000 Subject: [PATCH] Reduce runtime overhead and improve clock responsiveness Remove duplicate clock refreshes and hidden or sleeping tickers. Request frames before formatting styled clock text to reduce update latency. Reuse bounded parsing and styled-fragment results, cached reflection lookups, and broadcast-fed battery state. Reduce snapshot scanning overhead and avoid outline span mutation during drawing. Remove unused hooks and forwarding, consolidate text styling, and fix settings layout churn and font-preview lifecycle handling. Add unit and instrumentation regression coverage. Validated with 35 JVM tests, lint, disposable AOSP API 34/36 instrumentation runs, and Samsung device checks including paired clock/widget timing measurements. --- .../clock/ClockLayoutTextFactoryTest.java | 71 ++++++ .../features/clock/ClockRowsOverlayTest.java | 156 ++++++++++++ .../features/clock/ClockTextRendererTest.java | 56 +++++ .../render/ClockOutlineTextViewTest.java | 111 ++++++++ .../render/ClockProxyRendererTest.java | 41 +++ .../runtime/render/SnapshotRendererTest.java | 72 ++++++ .../runtime/settings/BatteryStateTest.java | 73 ++++++ .../shell/ui/ClockFontPickerTest.java | 65 +++++ .../shell/ui/MainActivityTest.java | 67 +++++ .../module/ModuleCoordinator.java | 52 ---- .../module/StatusBarTweakModule.java | 39 +-- .../platform/SystemUiCapabilities.java | 19 -- .../runtime/NotificationKeyReflection.java | 42 ---- .../runtime/RuntimeMutationGuard.java | 10 +- .../runtime/features/RuntimeContext.java | 2 +- .../runtime/features/RuntimeFeature.java | 31 +-- .../runtime/features/RuntimeLogGate.java | 2 +- .../features/StandaloneFeatureRegistry.java | 24 +- .../battery/BatteryBarController.java | 47 +--- .../features/battery/BatteryBarFeature.java | 11 +- .../features/chips/StatusChipsFeature.java | 11 +- .../runtime/features/clock/ClockFeature.java | 11 +- .../clock/ClockLayoutTextFactory.java | 15 +- .../features/clock/ClockPatternParser.java | 16 +- .../features/clock/ClockTextRenderer.java | 20 +- .../clock/DrawerClockTextController.java | 114 ++++++--- .../features/clock/StockClockController.java | 238 +++++++++--------- .../runtime/hooks/ReflectionSupport.java | 28 +++ .../runtime/hooks/XposedHookSupport.java | 25 +- .../layout/StockLayoutCanvasController.java | 122 +++------ .../layout/StockLayoutCanvasFeature.java | 8 +- .../mode/SystemUiStatusBarStateFeature.java | 2 +- .../AodNotificationIconSourceStore.java | 29 --- .../runtime/render/ClockLayout.java | 6 +- .../runtime/render/ClockOutlineTextView.java | 77 +++--- .../runtime/render/ClockProxyRenderer.java | 78 +----- .../runtime/render/OwnedIconHostManager.java | 13 +- .../runtime/render/SnapshotRenderer.java | 51 ++-- .../runtime/render/TextViewStyleSupport.java | 76 ++++++ .../UnlockedChipPlacementController.java | 40 --- .../UnlockedIconSnapshotRenderController.java | 151 +---------- .../render/UnlockedStockSourceCollector.java | 22 +- .../runtime/settings/BatteryState.java | 66 +++++ .../settings/BroadcastReceiverSupport.java | 5 - .../settings/RuntimeSettingsCache.java | 2 +- .../shell/settings/BatteryBarStyle.java | 78 +----- .../settings/ClockCameraTypeSupport.java | 14 -- .../shell/ui/BatteryBarFragment.java | 12 - .../shell/ui/ClockFragment.java | 20 +- .../statusbartweak/shell/ui/MainActivity.java | 19 +- .../main/resources/META-INF/xposed/scope.list | 3 - .../runtime/RuntimeMutationGuardTest.java | 26 ++ .../clock/ClockPatternParserTest.java | 24 ++ .../runtime/hooks/ReflectionSupportTest.java | 49 ++++ .../shell/settings/SbtSettingsTest.java | 15 ++ 55 files changed, 1418 insertions(+), 1059 deletions(-) create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactoryTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockRowsOverlayTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRendererTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextViewTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRendererTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRendererTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/settings/BatteryStateTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/ClockFontPickerTest.java create mode 100644 app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/MainActivityTest.java delete mode 100644 app/src/main/java/se/ajpanton/statusbartweak/module/ModuleCoordinator.java create mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/render/TextViewStyleSupport.java create mode 100644 app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BatteryState.java create mode 100644 app/src/test/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuardTest.java create mode 100644 app/src/test/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupportTest.java diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactoryTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactoryTest.java new file mode 100644 index 0000000..1270adf --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactoryTest.java @@ -0,0 +1,71 @@ +package se.ajpanton.statusbartweak.runtime.features.clock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.content.ContextWrapper; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.text.style.RelativeSizeSpan; +import android.widget.TextView; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import java.util.TimeZone; + +import se.ajpanton.statusbartweak.shell.settings.SbtSettings; + +public final class ClockLayoutTextFactoryTest { + @Test + public void cachedModelsPreserveRowsStylingTintAndTimezoneInvalidation() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + Context target = InstrumentationRegistry.getInstrumentation().getTargetContext(); + SharedPreferences prefs = target.getSharedPreferences("clock-model-test", Context.MODE_PRIVATE); + prefs.edit().clear() + .putBoolean(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT_ENABLED, true) + .putString(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT, + "{@sans-serif}HH{\\n30 big color(#f00;#00f)}mm") + .commit(); + Context context = new ContextWrapper(target) { + @Override + public SharedPreferences getSharedPreferences(String name, int mode) { return prefs; } + }; + SbtSettings settings = SbtSettings.from(context); + TimeZone originalZone = TimeZone.getDefault(); + try { + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); + ClockLayoutTextFactory.invalidate(); + TextView source = new TextView(context); + var bright = ClockLayoutTextFactory.build(source, settings, Color.WHITE); + assertSame(bright, ClockLayoutTextFactory.build(source, settings, Color.WHITE)); + assertFalse(bright.containsSeconds); + assertEquals(2, bright.rows.size()); + assertEquals(30, bright.rows.get(1).gapBeforePx); + Spanned row = (Spanned) bright.rows.get(1).text; + assertEquals(Color.RED, row.getSpans(0, row.length(), ForegroundColorSpan.class)[0] + .getForegroundColor()); + assertTrue(row.getSpans(0, row.length(), RelativeSizeSpan.class)[0].getSizeChange() > 1f); + var dark = ClockLayoutTextFactory.build(source, settings, Color.BLACK); + Spanned darkRow = (Spanned) dark.rows.get(1).text; + assertEquals(Color.BLUE, darkRow.getSpans(0, darkRow.length(), ForegroundColorSpan.class)[0] + .getForegroundColor()); + TimeZone.setDefault(TimeZone.getTimeZone("GMT+09:00")); + ClockLayoutTextFactory.invalidate(); + var moved = ClockLayoutTextFactory.build(source, settings, Color.BLACK); + assertNotEquals(dark.rows.get(0).text.toString(), moved.rows.get(0).text.toString()); + } finally { + TimeZone.setDefault(originalZone); + ClockLayoutTextFactory.invalidate(); + prefs.edit().clear().commit(); + } + }); + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockRowsOverlayTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockRowsOverlayTest.java new file mode 100644 index 0000000..73d592a --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockRowsOverlayTest.java @@ -0,0 +1,156 @@ +package se.ajpanton.statusbartweak.runtime.features.clock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.os.SystemClock; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.TextView; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import se.ajpanton.statusbartweak.shell.ui.MainActivity; + +public final class ClockRowsOverlayTest { + @Test + public void unmeasuredTextDoesNotStartAPostingLoop() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + FrameLayout host = new FrameLayout(context); + CountingSource source = new CountingSource(context); + host.addView(source); + var overlay = new StockClockController.ClockRowsOverlay(host); + overlay.update(source, rows()); + assertEquals("Layout/pre-draw events should retry unmeasured rows", 0, source.posts); + overlay.remove(); + }); + } + + @Test + public void staticRowsStayIdleAndFollowSourceVisualChanges() { + var instrumentation = InstrumentationRegistry.getInstrumentation(); + Activity activity = instrumentation.startActivitySync(new Intent( + instrumentation.getTargetContext(), MainActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + AtomicInteger frames = new AtomicInteger(); + AtomicReference fixture = new AtomicReference<>(); + try { + instrumentation.runOnMainSync(() -> { + FrameLayout host = new FrameLayout(activity); + TextView source = new TextView(activity); + source.setTextSize(40); + source.setText("56"); + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + params.topMargin = 400; + host.addView(source, params); + activity.setContentView(host); + var overlay = new StockClockController.ClockRowsOverlay(host); + fixture.set(new Fixture(host, source, overlay)); + overlay.update(source, rows()); + host.getViewTreeObserver().addOnPreDrawListener(() -> { + overlay.syncFromSource(source); + return true; + }); + host.getViewTreeObserver().addOnDrawListener(frames::incrementAndGet); + }); + SystemClock.sleep(700); + int settled = frames.get(); + SystemClock.sleep(1200); + int idleFrames = frames.get() - settled; + assertTrue("Static clock rows requested " + idleFrames + " idle frames", idleFrames <= 3); + instrumentation.runOnMainSync(() -> { + Fixture f = fixture.get(); + Ink original = upperRowInk(f); + assertNotNull("The upper row must be rendered", original.bounds); + f.source.setTranslationX(40); + f.overlay.syncFromSource(f.source); + Ink moved = upperRowInk(f); + assertEquals(original.bounds.left + 40, moved.bounds.left); + assertEquals(original.bounds.top, moved.bounds.top); + f.source.setAlpha(0.5f); + f.overlay.syncFromSource(f.source); + assertEquals(original.maxAlpha * 0.5f, upperRowInk(f).maxAlpha, 1f); + f.source.setTextSize(60); + f.host.measure(ViewGroup.MeasureSpec.makeMeasureSpec(f.host.getWidth(), ViewGroup.MeasureSpec.EXACTLY), + ViewGroup.MeasureSpec.makeMeasureSpec(f.host.getHeight(), ViewGroup.MeasureSpec.EXACTLY)); + f.host.layout(f.host.getLeft(), f.host.getTop(), f.host.getRight(), f.host.getBottom()); + f.overlay.syncFromSource(f.source); + assertTrue("A font change must invalidate row measurements", + upperRowInk(f).bounds.height() > original.bounds.height()); + f.source.setVisibility(ViewGroup.INVISIBLE); + f.overlay.syncFromSource(f.source); + assertNull("Hidden source text must hide its rows", upperRowInk(f).bounds); + f.overlay.remove(); + }); + } finally { + instrumentation.runOnMainSync(activity::finish); + } + } + + private static Ink upperRowInk(Fixture fixture) { + int width = fixture.host.getWidth(); + int height = fixture.source.getTop(); + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + try { + fixture.host.draw(new Canvas(bitmap)); + int[] pixels = new int[width * height]; + bitmap.getPixels(pixels, 0, width, 0, 0, width, height); + int left = width, top = height, right = -1, bottom = -1, maxAlpha = 0; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int alpha = pixels[y * width + x] >>> 24; + if (alpha == 0) { + continue; + } + left = Math.min(left, x); + right = Math.max(right, x); + top = Math.min(top, y); + bottom = Math.max(bottom, y); + maxAlpha = Math.max(maxAlpha, alpha); + } + } + return new Ink(right >= left ? new Rect(left, top, right + 1, bottom + 1) : null, maxAlpha); + } finally { + bitmap.recycle(); + } + } + + private record Fixture(FrameLayout host, TextView source, StockClockController.ClockRowsOverlay overlay) { } + + private record Ink(Rect bounds, int maxAlpha) { } + + private static ArrayList rows() { + ArrayList rows = new ArrayList<>(); + rows.add(new ClockTextRenderer.LayoutRowResult("12:34", "", "", "12:34", 0, 0)); + rows.add(new ClockTextRenderer.LayoutRowResult("56", "", "", "56", 0, 30)); + return rows; + } + + private static final class CountingSource extends TextView { + int posts; + + CountingSource(Context context) { super(context); } + + @Override + public boolean post(Runnable action) { + posts++; + return true; + } + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRendererTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRendererTest.java new file mode 100644 index 0000000..ba1e86e --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRendererTest.java @@ -0,0 +1,56 @@ +package se.ajpanton.statusbartweak.runtime.features.clock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import android.content.Context; +import android.graphics.Color; +import android.text.Spannable; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +public final class ClockTextRendererTest { + @Test + public void unchangedMarkupIsReusedButTimeAndTintStayLive() { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + ClockTextRenderer renderer = new ClockTextRenderer(); + TimeZone previous = TimeZone.getDefault(); + String pattern = "H:mm"; + Date now = new Date(1_700_000_000_000L); + try { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + CharSequence first = renderer.formatMarkup(context, Locale.US, now, pattern, Color.WHITE); + assertFalse(first instanceof Spannable); + assertSame(first, renderer.formatMarkup(context, Locale.US, + new Date(now.getTime() + 1000), pattern, Color.WHITE)); + CharSequence nextMinute = renderer.formatMarkup(context, Locale.US, + new Date(now.getTime() + 60_000), pattern, Color.WHITE); + assertNotSame(first, nextMinute); + assertEquals("22:14", nextMinute.toString()); + CharSequence dark = renderer.formatMarkup(context, Locale.US, now, pattern, Color.BLACK); + assertNotSame(first, dark); + assertEquals(Color.BLACK, foreground(dark)); + assertEquals(Color.WHITE, foreground(first)); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata")); + assertEquals("3:43", renderer.formatMarkup(context, Locale.US, + now, pattern, Color.WHITE).toString()); + } finally { + TimeZone.setDefault(previous); + } + } + + private static int foreground(CharSequence text) { + Spanned spanned = (Spanned) text; + return spanned.getSpans(0, spanned.length(), ForegroundColorSpan.class)[0].getForegroundColor(); + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextViewTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextViewTest.java new file mode 100644 index 0000000..c58c575 --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextViewTest.java @@ -0,0 +1,111 @@ +package se.ajpanton.statusbartweak.runtime.render; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.app.Activity; +import android.content.Intent; +import android.os.SystemClock; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.SpanWatcher; +import android.text.style.ForegroundColorSpan; +import android.widget.TextView; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import se.ajpanton.statusbartweak.shell.ui.MainActivity; + +public final class ClockOutlineTextViewTest { + @Test + public void staticOutlineDoesNotKeepRequestingFrames() { + var instrumentation = InstrumentationRegistry.getInstrumentation(); + Activity activity = instrumentation.startActivitySync(new Intent( + instrumentation.getTargetContext(), MainActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + AtomicInteger frames = new AtomicInteger(); + try { + instrumentation.runOnMainSync(() -> { + FrameLayout host = new FrameLayout(activity); + ClockOutlineTextView clock = new ClockOutlineTextView(activity); + clock.setTextSize(40); + clock.setText("12:34:56"); + clock.setOutline(new ClockOutlineSpec(Color.BLACK, 3f)); + host.addView(clock); + activity.setContentView(host); + host.getViewTreeObserver().addOnDrawListener(frames::incrementAndGet); + }); + SystemClock.sleep(700); + int settled = frames.get(); + SystemClock.sleep(1200); + int idleFrames = frames.get() - settled; + assertTrue("Static outlined text requested " + idleFrames + " idle frames", idleFrames <= 3); + } finally { + instrumentation.runOnMainSync(activity::finish); + } + } + + @Test + public void drawingOutlineDoesNotMutateLiveTextSpans() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + ClockOutlineTextView view = new ClockOutlineTextView( + InstrumentationRegistry.getInstrumentation().getTargetContext()); + view.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + view.setTextSize(40); + view.setTextColor(Color.WHITE); + SpannableString text = new SpannableString("12:34:56"); + text.setSpan(new ForegroundColorSpan(Color.GREEN), 6, 8, 0); + view.setText(text, TextView.BufferType.SPANNABLE); + view.setOutline(new ClockOutlineSpec(Color.BLACK, 3f)); + view.measure(0, 0); + view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); + int[] changes = {0}; + SpanWatcher watcher = new SpanWatcher() { + public void onSpanAdded(Spannable s, Object what, int start, int end) { changes[0]++; } + public void onSpanRemoved(Spannable s, Object what, int start, int end) { changes[0]++; } + public void onSpanChanged(Spannable s, Object what, int os, int oe, int ns, int ne) { + changes[0]++; + } + }; + Spannable liveText = (Spannable) view.getText(); + liveText.setSpan(watcher, 0, liveText.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); + changes[0] = 0; + Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); + try { + Canvas canvas = new Canvas(bitmap); + view.draw(canvas); + view.draw(canvas); + assertEquals("Drawing must not notify TextView's span watchers", 0, changes[0]); + assertTrue("Plain digits retain their fill colour", pixelsOfColor(bitmap, Color.WHITE) > 0); + assertTrue("Coloured digits retain their fill colour", pixelsOfColor(bitmap, Color.GREEN) > 0); + assertTrue("The outline has its own colour", pixelsOfColor(bitmap, Color.BLACK) > 0); + assertEquals(Color.GREEN, liveText.getSpans(0, liveText.length(), + ForegroundColorSpan.class)[0].getForegroundColor()); + } finally { + bitmap.recycle(); + } + }); + } + + private static int pixelsOfColor(Bitmap bitmap, int color) { + int count = 0; + for (int y = 0; y < bitmap.getHeight(); y++) { + for (int x = 0; x < bitmap.getWidth(); x++) { + if (bitmap.getPixel(x, y) == color) { + count++; + } + } + } + return count; + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRendererTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRendererTest.java new file mode 100644 index 0000000..d310f2e --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRendererTest.java @@ -0,0 +1,41 @@ +package se.ajpanton.statusbartweak.runtime.render; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import android.content.Context; +import android.graphics.Color; +import android.widget.TextView; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +public final class ClockProxyRendererTest { + @Test + public void stableTintOverrideDoesNotRewriteSourceAndOverrideColors() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + TextView source = new TextView(context); + source.setTextColor(Color.WHITE); + CountingTextView target = new CountingTextView(context); + TextViewStyleSupport.copyIfChanged(source, target, 30f, Color.BLACK); + target.colorWrites = 0; + assertFalse(TextViewStyleSupport.copyIfChanged(source, target, 30f, Color.BLACK)); + assertEquals(Color.BLACK, target.getCurrentTextColor()); + assertEquals(0, target.colorWrites); + }); + } + + private static final class CountingTextView extends TextView { + int colorWrites; + + CountingTextView(Context context) { super(context); } + + @Override + public void setTextColor(int color) { + colorWrites++; + super.setTextColor(color); + } + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRendererTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRendererTest.java new file mode 100644 index 0000000..ac66528 --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRendererTest.java @@ -0,0 +1,72 @@ +package se.ajpanton.statusbartweak.runtime.render; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.view.View; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import se.ajpanton.statusbartweak.runtime.RuntimeMutationGuard; +import se.ajpanton.statusbartweak.runtime.layoutsolver.StatusBarLayoutSolver.Bounds; + +public final class SnapshotRendererTest { + @Test + public void contentBoundsKeepTheirPixelExactEdges() { + Bitmap bitmap = Bitmap.createBitmap(300, 80, Bitmap.Config.ARGB_8888); + try { + Paint paint = new Paint(); + paint.setColor(Color.WHITE); + new Canvas(bitmap).drawRect(10, 5, 290, 75, paint); + assertEquals(new Bounds(10, 5, 280, 70), SnapshotRenderer.bitmapContentBounds(bitmap)); + bitmap.eraseColor(Color.TRANSPARENT); + assertNull(SnapshotRenderer.bitmapContentBounds(bitmap)); + bitmap.setPixel(0, 0, 0x01000000); + bitmap.setPixel(299, 79, Color.BLACK); + assertEquals(new Bounds(0, 0, 300, 80), SnapshotRenderer.bitmapContentBounds(bitmap)); + } finally { + bitmap.recycle(); + } + } + + @Test + public void failedSnapshotRestoresVisibilityAlphaAndMutationGuard() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + IllegalStateException failure = new IllegalStateException("Drawing failed"); + View source = new View(context) { + @Override + public void draw(Canvas canvas) { + assertTrue(RuntimeMutationGuard.isSnapshotRenderMutation()); + assertEquals(View.VISIBLE, getVisibility()); + assertEquals(1f, getAlpha(), 0f); + throw failure; + } + }; + source.setVisibility(View.INVISIBLE); + source.setAlpha(0.25f); + SnapshotRenderer renderer = new SnapshotRenderer(false, false, false); + try { + renderer.snapshotContentBounds(new SnapshotSource(source, SnapshotMode.VIEW), + new Bounds(0, 0, 40, 40)); + fail("Drawing failure must propagate"); + } catch (IllegalStateException actual) { + assertSame(failure, actual); + } + assertEquals(View.INVISIBLE, source.getVisibility()); + assertEquals(0.25f, source.getAlpha(), 0f); + assertFalse(RuntimeMutationGuard.isSnapshotRenderMutation()); + }); + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/settings/BatteryStateTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/settings/BatteryStateTest.java new file mode 100644 index 0000000..f4e961f --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/runtime/settings/BatteryStateTest.java @@ -0,0 +1,73 @@ +package se.ajpanton.statusbartweak.runtime.settings; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.ContextWrapper; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.BatteryManager; + +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +public final class BatteryStateTest { + @Test + public void readsAreCachedAndListenersSeeTheUpdatedSnapshot() { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + BatteryContext context = new BatteryContext(); + BatteryState first = BatteryState.get(context); + assertEquals(80, first.level()); + assertFalse(first.charging()); + for (int i = 0; i < 1000; i++) { + assertSame(first, BatteryState.get(context)); + } + assertEquals(1, context.registrations); + int[] changes = {0}; + BatteryState.addListener(context, () -> { + changes[0]++; + assertEquals(50, BatteryState.get(context).level()); + assertTrue(BatteryState.get(context).charging()); + }); + context.receiver.onReceive(context, battery(80, 100, false)); + assertEquals(0, changes[0]); + context.receiver.onReceive(context, battery(100, 200, true)); + assertEquals(1, changes[0]); + assertEquals(1, context.registrations); + }); + } + + private static Intent battery(int level, int scale, boolean plugged) { + return new Intent(Intent.ACTION_BATTERY_CHANGED) + .putExtra(BatteryManager.EXTRA_LEVEL, level) + .putExtra(BatteryManager.EXTRA_SCALE, scale) + .putExtra(BatteryManager.EXTRA_PLUGGED, plugged ? 1 : 0) + .putExtra(BatteryManager.EXTRA_STATUS, plugged + ? BatteryManager.BATTERY_STATUS_CHARGING + : BatteryManager.BATTERY_STATUS_DISCHARGING); + } + + private static final class BatteryContext extends ContextWrapper { + int registrations; + BroadcastReceiver receiver; + + BatteryContext() { + super(InstrumentationRegistry.getInstrumentation().getTargetContext()); + } + + @Override + public Context getApplicationContext() { return this; } + + @Override + public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) { + registrations++; + this.receiver = receiver; + return battery(80, 100, false); + } + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/ClockFontPickerTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/ClockFontPickerTest.java new file mode 100644 index 0000000..062af6c --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/ClockFontPickerTest.java @@ -0,0 +1,65 @@ +package se.ajpanton.statusbartweak.shell.ui; + +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.action.ViewActions.scrollTo; +import static androidx.test.espresso.matcher.RootMatchers.isDialog; +import static androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom; +import static androidx.test.espresso.matcher.ViewMatchers.withId; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.app.Activity; +import android.content.Intent; +import android.database.DataSetObserver; +import android.os.SystemClock; +import android.view.View; +import android.widget.ListView; + +import androidx.test.espresso.UiController; +import androidx.test.espresso.ViewAction; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.hamcrest.Matcher; +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import se.ajpanton.statusbartweak.R; + +public final class ClockFontPickerTest { + @Test + public void samplesPauseInBackgroundAndResumeWithTheDialog() throws Exception { + var instrumentation = InstrumentationRegistry.getInstrumentation(); + var context = instrumentation.getTargetContext(); + Activity activity = instrumentation.startActivitySync(new Intent(context, MainActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("open_nav_item", R.id.nav_clock)); + AtomicInteger refreshes = new AtomicInteger(); + try { + onView(withId(R.id.clock_font_picker_button)).perform(scrollTo(), click()); + onView(isAssignableFrom(ListView.class)).inRoot(isDialog()).perform(new ViewAction() { + public Matcher getConstraints() { return isAssignableFrom(ListView.class); } + public String getDescription() { return "Observe font sample refreshes"; } + public void perform(UiController controller, View view) { + ((ListView) view).getAdapter().registerDataSetObserver(new DataSetObserver() { + @Override + public void onChanged() { refreshes.incrementAndGet(); } + }); + } + }); + SystemClock.sleep(1200); + assertTrue(refreshes.get() > 0); + instrumentation.getUiAutomation().executeShellCommand("input keyevent HOME").close(); + SystemClock.sleep(500); + int paused = refreshes.get(); + SystemClock.sleep(1500); + assertEquals("Background dialog must stop refreshing", paused, refreshes.get()); + context.startActivity(new Intent(context, MainActivity.class).addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP)); + SystemClock.sleep(1200); + assertTrue("Visible dialog must resume refreshing", refreshes.get() > paused); + } finally { + instrumentation.runOnMainSync(activity::finish); + } + } +} diff --git a/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/MainActivityTest.java b/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/MainActivityTest.java new file mode 100644 index 0000000..3eeebd4 --- /dev/null +++ b/app/src/androidTest/java/se/ajpanton/statusbartweak/shell/ui/MainActivityTest.java @@ -0,0 +1,67 @@ +package se.ajpanton.statusbartweak.shell.ui; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.app.Activity; +import android.content.Intent; +import android.os.SystemClock; +import android.view.View; + +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import se.ajpanton.statusbartweak.R; + +public final class MainActivityTest { + @Test + public void settingsSettleAndDrawerSurvivesNarrowWideNarrowLayout() { + var instrumentation = InstrumentationRegistry.getInstrumentation(); + Activity activity = instrumentation.startActivitySync(new Intent( + instrumentation.getTargetContext(), MainActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + AtomicInteger frames = new AtomicInteger(); + try { + instrumentation.runOnMainSync(() -> { + SafeInsetDrawerLayout drawer = activity.findViewById(R.id.drawer_layout); + int narrowWidth = drawer.getWidth(); + int height = drawer.getHeight(); + layout(drawer, narrowWidth * 2, height); + assertEquals(View.VISIBLE, activity.findViewById(R.id.nav_view_permanent).getVisibility()); + assertEquals(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, drawer.getDrawerLockMode(GravityCompat.START)); + layout(drawer, narrowWidth, height); + assertEquals(View.GONE, activity.findViewById(R.id.nav_view_permanent).getVisibility()); + assertEquals(View.VISIBLE, activity.findViewById(R.id.nav_view_drawer).getVisibility()); + assertEquals(DrawerLayout.LOCK_MODE_UNLOCKED, drawer.getDrawerLockMode(GravityCompat.START)); + assertFalse(drawer.isDrawerOpen(GravityCompat.START)); + drawer.openDrawer(GravityCompat.START, false); + assertTrue(drawer.isDrawerOpen(GravityCompat.START)); + drawer.closeDrawer(GravityCompat.START, false); + // A focused number field legitimately redraws its blinking caret. + drawer.setFocusableInTouchMode(true); + drawer.requestFocus(); + drawer.getViewTreeObserver().addOnDrawListener(frames::incrementAndGet); + }); + // Allow the navigation/ScrollView scrollbar fade to finish too. + SystemClock.sleep(2500); + int settled = frames.get(); + SystemClock.sleep(1200); + int idleFrames = frames.get() - settled; + assertTrue("Settings requested " + idleFrames + " idle frames", idleFrames <= 3); + } finally { + instrumentation.runOnMainSync(activity::finish); + } + } + + private static void layout(View view, int width, int height) { + view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); + view.layout(0, 0, width, height); + } +} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/module/ModuleCoordinator.java b/app/src/main/java/se/ajpanton/statusbartweak/module/ModuleCoordinator.java deleted file mode 100644 index d048586..0000000 --- a/app/src/main/java/se/ajpanton/statusbartweak/module/ModuleCoordinator.java +++ /dev/null @@ -1,52 +0,0 @@ -package se.ajpanton.statusbartweak.module; - -import io.github.libxposed.api.XposedInterface; -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.StandaloneFeatureRegistry; -import se.ajpanton.statusbartweak.runtime.mode.ModeStateRepository; - -/** - * Fresh rebuild entrypoint. - * - * Intentionally does not install layout/icon hooks yet. During the reset - * phase, the settings app remains available while runtime behaviour is rebuilt - * slice by slice under the runtime package tree. - */ -public final class ModuleCoordinator { - - private final RuntimeContext runtimeContext; - private final StandaloneFeatureRegistry standaloneFeatureRegistry; - - public ModuleCoordinator(XposedInterface framework) { - ModeStateRepository modeStateRepository = new ModeStateRepository(); - runtimeContext = new RuntimeContext( - framework, - modeStateRepository); - standaloneFeatureRegistry = new StandaloneFeatureRegistry(runtimeContext); - } - - public void onModuleLoaded(XposedModuleInterface.ModuleLoadedParam param) { - String processName = param.getProcessName(); - if (!SystemUiCapabilities.isHandledProcessName(processName)) { - return; - } - standaloneFeatureRegistry.onModuleLoaded(param); - } - - public void onPackageReady(XposedModuleInterface.PackageReadyParam param) { - if (!shouldHandlePackage(param.getPackageName())) { - return; - } - standaloneFeatureRegistry.onPackageReady(param); - } - - public void onSystemServerStarting(XposedModuleInterface.SystemServerStartingParam param) { - standaloneFeatureRegistry.onSystemServerStarting(param); - } - - private static boolean shouldHandlePackage(String packageName) { - return SystemUiCapabilities.isHandledPackageName(packageName); - } -} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/module/StatusBarTweakModule.java b/app/src/main/java/se/ajpanton/statusbartweak/module/StatusBarTweakModule.java index 43fa8f8..b461c37 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/module/StatusBarTweakModule.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/module/StatusBarTweakModule.java @@ -6,6 +6,11 @@ import io.github.libxposed.api.XposedInterface; import io.github.libxposed.api.XposedModule; 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.StandaloneFeatureRegistry; +import se.ajpanton.statusbartweak.runtime.mode.ModeStateRepository; + /** * Modern module entrypoint. */ @@ -13,8 +18,8 @@ public final class StatusBarTweakModule extends XposedModule { private static final String FAILSAFE_PATH = "/data/local/tmp/disable_statusbar_fix"; - private final ModuleCoordinator moduleCoordinator = new ModuleCoordinator(this); - private boolean moduleLoadedHandled; + private final StandaloneFeatureRegistry features = new StandaloneFeatureRegistry( + new RuntimeContext(this, new ModeStateRepository())); public StatusBarTweakModule() { } @@ -29,23 +34,6 @@ public final class StatusBarTweakModule extends XposedModule { XposedModuleInterface.ModuleLoadedParam param ) { attachFrameworkIfAvailable(framework); - handleModuleLoaded(param); - } - - @Override - public void onModuleLoaded(ModuleLoadedParam param) { - handleModuleLoaded(param); - } - - private void handleModuleLoaded(ModuleLoadedParam param) { - if (moduleLoadedHandled) { - return; - } - moduleLoadedHandled = true; - if (new File(FAILSAFE_PATH).exists()) { - return; - } - moduleCoordinator.onModuleLoaded(param); } private void attachFrameworkIfAvailable(XposedInterface framework) { @@ -64,17 +52,10 @@ public final class StatusBarTweakModule extends XposedModule { @Override public void onPackageReady(PackageReadyParam param) { - if (new File(FAILSAFE_PATH).exists()) { + if (!SystemUiCapabilities.isSystemUiPackageName(param.getPackageName()) + || new File(FAILSAFE_PATH).exists()) { return; } - moduleCoordinator.onPackageReady(param); - } - - @Override - public void onSystemServerStarting(XposedModuleInterface.SystemServerStartingParam param) { - if (new File(FAILSAFE_PATH).exists()) { - return; - } - moduleCoordinator.onSystemServerStarting(param); + features.onPackageReady(param); } } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/platform/SystemUiCapabilities.java b/app/src/main/java/se/ajpanton/statusbartweak/platform/SystemUiCapabilities.java index a994e5c..4b50994 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/platform/SystemUiCapabilities.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/platform/SystemUiCapabilities.java @@ -5,10 +5,7 @@ import android.os.Build; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; public final class SystemUiCapabilities { - public static final String PACKAGE_ANDROID = "android"; - public static final String PACKAGE_SYSTEM = "system"; public static final String PACKAGE_SYSTEMUI = "com.android.systemui"; - public static final String PACKAGE_SAMSUNG_AOD_SERVICE = "com.samsung.android.app.aodservice"; private static final boolean SAMSUNG_ONE_UI = "samsung".equalsIgnoreCase(Build.MANUFACTURER); private SystemUiCapabilities() { @@ -22,10 +19,6 @@ public final class SystemUiCapabilities { return !isSamsungOneUi(); } - public static boolean supportsSamsungAodServiceProcess() { - return isSamsungOneUi(); - } - public static boolean supportsSamsungStatusChipHooks() { return isSamsungOneUi(); } @@ -38,18 +31,6 @@ public final class SystemUiCapabilities { return PACKAGE_SYSTEMUI.equals(packageName); } - public static boolean isHandledPackageName(String packageName) { - return PACKAGE_SYSTEMUI.equals(packageName) - || PACKAGE_ANDROID.equals(packageName) - || PACKAGE_SYSTEM.equals(packageName) - || (supportsSamsungAodServiceProcess() - && PACKAGE_SAMSUNG_AOD_SERVICE.equals(packageName)); - } - - public static boolean isHandledProcessName(String processName) { - return isHandledPackageName(processName); - } - public static boolean supportsExperimentalGenericAodStatusbarRoot(SbtSettings settings) { return !isSamsungOneUi() && settings != null diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/NotificationKeyReflection.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/NotificationKeyReflection.java index 199a31a..3af43c4 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/NotificationKeyReflection.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/NotificationKeyReflection.java @@ -4,12 +4,6 @@ import android.view.View; import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; public final class NotificationKeyReflection { - private static final String[] ENTRY_KEY_FIELD_NAMES = { - "mKey", - "key", - "notificationKey", - "mNotificationKey" - }; private static final String[] ICON_VIEW_KEY_FIELD_NAMES = { "mNotificationKey", "notificationKey", @@ -22,29 +16,6 @@ public final class NotificationKeyReflection { private NotificationKeyReflection() { } - public static String rowFilterKey(Object target) { - String key = nonEmptyStringFromMethod(target, "getKey"); - if (key != null) { - return key; - } - key = nonEmptyStringFromMethod(target, "getNotificationKey"); - if (key != null) { - return key; - } - return nonEmptyStringFromFields(target, "mKey", "key"); - } - - public static String keyForEntry(Object entry) { - if (entry == null) { - return null; - } - String key = nonEmptyStringFromMethod(entry, "getKey"); - if (key != null) { - return key; - } - return nonEmptyStringFromFields(entry, ENTRY_KEY_FIELD_NAMES); - } - public static String keyForIconView(View view) { if (view == null) { return null; @@ -60,19 +31,6 @@ public final class NotificationKeyReflection { return nonEmptyStringFromFields(view, ICON_VIEW_KEY_FIELD_NAMES); } - public static Object entryForRow(View row) { - Object value = primaryEntryForRow(row); - return value != null ? value : ReflectionSupport.getFieldValue(row, "entry"); - } - - public static Object primaryEntryForRow(View row) { - Object value = ReflectionSupport.invokeMethod(row, "getEntry"); - if (value != null) { - return value; - } - return ReflectionSupport.getFieldValue(row, "mEntry"); - } - public static String packageFromNotificationKey(String key) { if (key == null) { return null; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuard.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuard.java index b42d7c8..1978755 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuard.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuard.java @@ -12,16 +12,10 @@ public final class RuntimeMutationGuard { } public static void exitSnapshotRenderMutation() { - int depth = SNAPSHOT_RENDER_DEPTH.get() - 1; - if (depth <= 0) { - SNAPSHOT_RENDER_DEPTH.remove(); - } else { - SNAPSHOT_RENDER_DEPTH.set(depth); - } + SNAPSHOT_RENDER_DEPTH.set(SNAPSHOT_RENDER_DEPTH.get() - 1); } public static boolean isSnapshotRenderMutation() { - Integer depth = SNAPSHOT_RENDER_DEPTH.get(); - return depth != null && depth > 0; + return SNAPSHOT_RENDER_DEPTH.get() > 0; } } 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 830495a..673f6bd 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 @@ -42,7 +42,7 @@ public final class RuntimeContext { } public void logError(String message, Throwable throwable) { - logSplit(Log.ERROR, message, throwable); + framework.log(Log.ERROR, LOG_TAG, message, throwable); } private void logSplit(int priority, String message, Throwable throwable) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeFeature.java index 3a1a467..42eae95 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeFeature.java @@ -1,39 +1,14 @@ package se.ajpanton.statusbartweak.runtime.features; import io.github.libxposed.api.XposedModuleInterface; -import se.ajpanton.statusbartweak.platform.SystemUiCapabilities; -/** - * Small independent runtime slice. - * - * The rebuild is intentionally moving away from one giant Xposed init class. - * Each feature gets its own lifecycle and can stay outside the icon-layout - * engine until it truly needs to integrate with it. - */ +/** A SystemUI feature installed at package-ready. */ public interface RuntimeFeature { String getName(); - static boolean isSystemUiPackage(XposedModuleInterface.PackageReadyParam param) { - return param != null - && SystemUiCapabilities.isSystemUiPackageName(param.getPackageName()); - } - - default void onModuleLoaded( - RuntimeContext context, - XposedModuleInterface.ModuleLoadedParam param - ) throws Throwable { - } - - default void onPackageReady( + void onPackageReady( RuntimeContext context, XposedModuleInterface.PackageReadyParam param - ) throws Throwable { - } - - default void onSystemServerStarting( - RuntimeContext context, - XposedModuleInterface.SystemServerStartingParam param - ) throws Throwable { - } + ) throws Throwable; } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeLogGate.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeLogGate.java index dd7ff1d..b77c463 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeLogGate.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/RuntimeLogGate.java @@ -11,7 +11,7 @@ final class RuntimeLogGate { private static final Object LOCK = new Object(); - private static Boolean cachedEnabled; + private static volatile Boolean cachedEnabled; private static boolean receiverRegistered; private RuntimeLogGate() { 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 8178c8b..e5c5baa 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 @@ -9,10 +9,7 @@ import se.ajpanton.statusbartweak.runtime.features.clock.ClockFeature; import se.ajpanton.statusbartweak.runtime.layout.StockLayoutCanvasFeature; import se.ajpanton.statusbartweak.runtime.mode.SystemUiStatusBarStateFeature; -/** - * Tracks independently rebuilt features that do not need the custom icon - * layout engine yet. - */ +/** Installs runtime features independently so one unsupported feature cannot block the rest. */ public final class StandaloneFeatureRegistry { private final RuntimeContext runtimeContext; @@ -29,22 +26,10 @@ public final class StandaloneFeatureRegistry { ); } - public void onModuleLoaded(XposedModuleInterface.ModuleLoadedParam param) { - forEachFeature(feature -> feature.onModuleLoaded(runtimeContext, param)); - } - public void onPackageReady(XposedModuleInterface.PackageReadyParam param) { - forEachFeature(feature -> feature.onPackageReady(runtimeContext, param)); - } - - public void onSystemServerStarting(XposedModuleInterface.SystemServerStartingParam param) { - forEachFeature(feature -> feature.onSystemServerStarting(runtimeContext, param)); - } - - private void forEachFeature(FeatureAction action) { for (RuntimeFeature feature : features) { try { - action.run(feature); + feature.onPackageReady(runtimeContext, param); } catch (Throwable throwable) { runtimeContext.logError( "Feature bootstrap failed: " + feature.getName() @@ -55,9 +40,4 @@ public final class StandaloneFeatureRegistry { } } } - - @FunctionalInterface - private interface FeatureAction { - void run(RuntimeFeature feature) throws Throwable; - } } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarController.java index 1e7123f..db41ca5 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarController.java @@ -1,9 +1,7 @@ package se.ajpanton.statusbartweak.runtime.features.battery; import android.app.KeyguardManager; -import android.content.BroadcastReceiver; import android.content.Context; -import android.content.Intent; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Color; @@ -13,7 +11,6 @@ import android.graphics.PathMeasure; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; -import android.os.BatteryManager; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.RoundedCorner; @@ -39,6 +36,7 @@ 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.BatteryState; import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; import se.ajpanton.statusbartweak.shell.settings.BatteryBarGeometry; import se.ajpanton.statusbartweak.shell.settings.BatteryBarStyle; @@ -288,41 +286,22 @@ final class BatteryBarController { if (context == null || receiverRegistered) { return; } - BroadcastReceiver receiver = new BroadcastReceiver() { - @Override - public void onReceive(Context ctx, Intent intent) { - String action = intent.getAction(); - if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { - updateBatteryState(intent); - } - if (Intent.ACTION_BATTERY_CHANGED.equals(action) - || SbtSettings.ACTION_SETTINGS_CHANGED.equals(action)) { - refreshAllRoots(); - } - } - }; - Intent sticky = BroadcastReceiverSupport.registerExportedOnApplicationContext( + BroadcastReceiverSupport.registerInvalidatingReceiver( context, - receiver, - BroadcastReceiverSupport.filter( - Intent.ACTION_BATTERY_CHANGED, - SbtSettings.ACTION_SETTINGS_CHANGED)); + this::refreshAllRoots, + BroadcastReceiverSupport.filter(SbtSettings.ACTION_SETTINGS_CHANGED)); receiverRegistered = true; - if (sticky != null) { - updateBatteryState(sticky); - } + updateBatteryState(context); + BatteryState.addListener(context, () -> { + updateBatteryState(context); + refreshAllRoots(); + }); } - private void updateBatteryState(Intent intent) { - int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); - int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); - if (level >= 0 && scale > 0) { - batteryLevel = Math.round((level * 100f) / scale); - } - int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); - plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 - || status == BatteryManager.BATTERY_STATUS_CHARGING - || status == BatteryManager.BATTERY_STATUS_FULL; + private void updateBatteryState(Context context) { + BatteryState state = BatteryState.get(context); + batteryLevel = state.level(); + plugged = state.charging(); } private void refreshAllRoots() { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarFeature.java index 3dc9674..0a9f4f6 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/battery/BatteryBarFeature.java @@ -4,13 +4,7 @@ import io.github.libxposed.api.XposedModuleInterface; import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; -/** - * Reserved home for the rebuilt Battery Bar runtime. - * - * This feature is intentionally separate from the future icon layout engine. - * The old implementation mostly owned its own overlays and can be ported as a - * standalone slice first. - */ +/** Embedded and fullscreen battery bars, independent of the icon layout toggle. */ public final class BatteryBarFeature implements RuntimeFeature { private BatteryBarController controller; @@ -25,9 +19,6 @@ public final class BatteryBarFeature implements RuntimeFeature { RuntimeContext context, XposedModuleInterface.PackageReadyParam param ) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } installController(context, param.getClassLoader()); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/chips/StatusChipsFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/chips/StatusChipsFeature.java index 2c891eb..d5f1a40 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/chips/StatusChipsFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/chips/StatusChipsFeature.java @@ -5,13 +5,7 @@ import se.ajpanton.statusbartweak.platform.SystemUiCapabilities; import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; -/** - * Reserved home for stock status-chip suppression. - * - * Status chips appear to be largely independent of the custom icon-layout - * rebuild because they mostly suppress Samsung-owned chip views rather than - * participating in our future icon solver. - */ +/** Stock Samsung status-chip suppression. */ public final class StatusChipsFeature implements RuntimeFeature { private StatusChipHider statusChipHider; @@ -26,9 +20,6 @@ public final class StatusChipsFeature implements RuntimeFeature { RuntimeContext context, XposedModuleInterface.PackageReadyParam param ) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } installController(context, param.getClassLoader()); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockFeature.java index d08fcb7..f331a3e 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockFeature.java @@ -4,13 +4,7 @@ import io.github.libxposed.api.XposedModuleInterface; import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; -/** - * First clock slice for the rebuild. - * - * For now this only targets the stock SystemUI clock while the custom Layout - * engine is off. Later, when the rewritten layout owns the clock container, - * this feature can hand off to that path instead of owning the stock view. - */ +/** Custom text for native statusbar clocks (layout off) and drawer clocks. */ public final class ClockFeature implements RuntimeFeature { private StockClockController stockClockController; @@ -26,9 +20,6 @@ public final class ClockFeature implements RuntimeFeature { RuntimeContext context, XposedModuleInterface.PackageReadyParam param ) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } installController(context, param.getClassLoader()); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactory.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactory.java index 64d5e78..ff93170 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactory.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockLayoutTextFactory.java @@ -21,6 +21,10 @@ public final class ClockLayoutTextFactory { private ClockLayoutTextFactory() { } + static void invalidate() { + MODEL_CACHE.clear(); + } + public static Model build(TextView source, SbtSettings settings) { return build(source, settings, source != null ? source.getCurrentTextColor() : 0); } @@ -91,9 +95,7 @@ public final class ClockLayoutTextFactory { String pattern = settings.clockCustomFormat != null ? settings.clockCustomFormat : ""; boolean customPattern = settings.clockCustomFormatEnabled && !pattern.isEmpty(); boolean generatedText = hasCustomClockTextEnabled(settings); - boolean seconds = settings.clockShowSeconds - || (customPattern && ClockMarkupSupport.containsSecondsPattern(pattern)); - long divisor = seconds ? 1_000L : 60_000L; + long divisor = usesSeconds(settings) ? 1_000L : 60_000L; CharSequence sourceText = source.getText(); CharSequence sourceDescription = source.getContentDescription(); return new CacheKey( @@ -118,6 +120,13 @@ public final class ClockLayoutTextFactory { || (settings.clockCustomFormatEnabled && !pattern.isEmpty()); } + public static boolean usesSeconds(SbtSettings settings) { + String pattern = settings.clockCustomFormat; + return settings.clockCustomFormatEnabled && pattern != null && !pattern.isEmpty() + ? ClockMarkupSupport.containsSecondsPattern(pattern) + : settings.clockShowSeconds; + } + private static CharSequence renderFallbackClockText(Context context, SbtSettings settings) { Locale locale = localeFor(context); Date now = new Date(); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParser.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParser.java index 45f144b..7be2bb5 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParser.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParser.java @@ -1,14 +1,21 @@ package se.ajpanton.statusbartweak.runtime.features.clock; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; final class ClockPatternParser { static final int ROW_GAP_AUTO = Integer.MIN_VALUE; + private final LinkedHashMap parsedPatterns = + new LinkedHashMap<>(16, 0.75f, true); - ClockParsedPattern parse(String rawPattern) { + synchronized ClockParsedPattern parse(String rawPattern) { + ClockParsedPattern cached = parsedPatterns.get(rawPattern); + if (cached != null) { + return cached; + } String pattern = rawPattern; ArrayList rows = new ArrayList<>(); boolean containsSeconds = ClockMarkupSupport.containsSecondsPattern(pattern); @@ -96,7 +103,12 @@ final class ClockPatternParser { index++; } rows.add(finalizeRow(rowMarkup, rowState, gapBeforePx, rowSyntaxError)); - return new ClockParsedPattern(rows, containsSeconds); + ClockParsedPattern parsed = new ClockParsedPattern(rows, containsSeconds); + if (parsedPatterns.size() == 16) { + parsedPatterns.remove(parsedPatterns.keySet().iterator().next()); + } + parsedPatterns.put(rawPattern, parsed); + return parsed; } private ClockParsedPattern.ClockParsedRow finalizeRow( diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRenderer.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRenderer.java index de3eb9c..3c8c791 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRenderer.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockTextRenderer.java @@ -5,6 +5,7 @@ import android.graphics.Color; import android.text.Editable; import android.text.SpannableStringBuilder; import android.text.Spanned; +import android.text.SpannedString; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.style.ForegroundColorSpan; @@ -16,6 +17,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; +import java.util.LinkedHashMap; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,6 +37,8 @@ final class ClockTextRenderer { Pattern.compile("(?i)(<\\s*font\\b[^>]*\\bcolor\\s*=\\s*['\"])([^'\"]+)(['\"])"); private final ClockColorResolver colorResolver = new ClockColorResolver(); + private final LinkedHashMap renderedMarkup = + new LinkedHashMap<>(16, 0.75f, true); ArrayList renderRows( Context context, @@ -260,7 +264,7 @@ final class ClockTextRenderer { } } - private CharSequence formatMarkup( + synchronized CharSequence formatMarkup( Context context, Locale locale, Date now, @@ -274,12 +278,21 @@ final class ClockTextRenderer { return new SimpleDateFormat(markup, locale).format(now); } String renderedHtml = formatPatternHtml(context, locale, now, markup, referenceColor); + RenderedMarkup cached = renderedMarkup.get(markup); + if (cached != null && cached.html.equals(renderedHtml)) { + return cached.text; + } CharSequence parsed = HtmlCompat.fromHtml( renderedHtml, HtmlCompat.FROM_HTML_MODE_LEGACY, null, this::handleCustomHtmlTag); - return applyAlphaAwareClockColours(parsed, renderedHtml); + SpannedString text = new SpannedString(applyAlphaAwareClockColours(parsed, renderedHtml)); + if (renderedMarkup.size() == 16 && cached == null) { + renderedMarkup.remove(renderedMarkup.keySet().iterator().next()); + } + renderedMarkup.put(markup, new RenderedMarkup(renderedHtml, text)); + return text; } private String formatPatternHtml( @@ -331,6 +344,9 @@ final class ClockTextRenderer { return out.toString(); } + private record RenderedMarkup(String html, SpannedString text) { + } + private String normalizeHtmlTag( Context context, String rawTag, diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/DrawerClockTextController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/DrawerClockTextController.java index 9f4710c..f195e60 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/DrawerClockTextController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/DrawerClockTextController.java @@ -3,6 +3,7 @@ package se.ajpanton.statusbartweak.runtime.features.clock; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.os.PowerManager; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.view.View; @@ -27,6 +28,7 @@ import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; import se.ajpanton.statusbartweak.runtime.mode.SceneKey; import se.ajpanton.statusbartweak.runtime.mode.SurfaceMode; import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport; +import se.ajpanton.statusbartweak.runtime.settings.BatteryState; import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; import se.ajpanton.statusbartweak.R; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; @@ -46,6 +48,7 @@ final class DrawerClockTextController { private final Set ownedTexts = Collections.newSetFromMap(new WeakHashMap<>()); private boolean hooksInstalled; private boolean receiverRegistered; + private boolean screenInteractive; private int ownTextWriteDepth; DrawerClockTextController(RuntimeContext runtimeContext) { @@ -59,6 +62,10 @@ final class DrawerClockTextController { XposedInterface framework = runtimeContext.getFramework(); Class viewRootClass = ReflectionSupport.requireClass("android.view.ViewRootImpl", classLoader); XposedHookSupport.hookAllMethods(framework, viewRootClass, "performTraversals", chain -> { + Object before = ReflectionSupport.requireFieldValue(chain.getThisObject(), "mView"); + if (before instanceof View root && isNotificationShadeRoot(root)) { + syncTickerVisibility(root); + } Object result = chain.proceed(); Object rootObj = ReflectionSupport.requireFieldValue(chain.getThisObject(), "mView"); if (rootObj instanceof View root && isNotificationShadeRoot(root)) { @@ -144,16 +151,13 @@ final class DrawerClockTextController { } } - private int restoreTrackedDescendants(View root) { - int restored = 0; + private void restoreTrackedDescendants(View root) { for (TextView textView : new ArrayList<>(trackedRoles.keySet())) { - if (textView == null || root == null || isDescendantOf(textView, root)) { + if (isDescendantOf(textView, root)) { restore(textView); untrack(textView); - restored++; } } - return restored; } private void untrackDisabledRoles(boolean clockEnabled, boolean dateEnabled) { @@ -242,9 +246,7 @@ final class DrawerClockTextController { stockSnapshots.remove(textView); renderCache.remove(textView); ownedTexts.remove(textView); - if (textView != null) { - textView.setTag(R.id.sbt_debug_drawer_clock_container, null); - } + textView.setTag(R.id.sbt_debug_drawer_clock_container, null); stopTicker(textView); } @@ -369,7 +371,7 @@ final class DrawerClockTextController { } private void writeText(TextView textView, CharSequence text, boolean force) { - if (!force && sameText(textView.getText(), text)) { + if (!force && TextUtils.equals(textView.getText(), text)) { return; } ownTextWriteDepth++; @@ -384,9 +386,20 @@ final class DrawerClockTextController { if (context == null || receiverRegistered) { return; } + screenInteractive = context.getSystemService(PowerManager.class).isInteractive(); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context ctx, Intent intent) { + if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { + screenInteractive = false; + for (TextView textView : new ArrayList<>(tickers.keySet())) { + stopTicker(textView); + } + return; + } + if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) { + screenInteractive = true; + } renderCache.clear(); refreshTrackedTexts(); } @@ -397,38 +410,83 @@ final class DrawerClockTextController { BroadcastReceiverSupport.filter( SbtSettings.ACTION_SETTINGS_CHANGED, Intent.ACTION_USER_UNLOCKED, - Intent.ACTION_BATTERY_CHANGED, + Intent.ACTION_SCREEN_ON, + Intent.ACTION_SCREEN_OFF, Intent.ACTION_TIME_TICK, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED, Intent.ACTION_LOCALE_CHANGED, Intent.ACTION_CONFIGURATION_CHANGED)); receiverRegistered = true; + BatteryState.addListener(context, () -> { + renderCache.clear(); + refreshTrackedTexts(); + }); } private void refreshTrackedTexts() { + if (!screenInteractive) { + return; + } for (TextView textView : new ArrayList<>(trackedRoles.keySet())) { reapplyTrackedText(textView, false, false); } } - private void startTicker(TextView textView) { - Runnable ticker = tickers.get(textView); - if (ticker == null) { - ticker = new Runnable() { - @Override - public void run() { - if (textView.getHandler() == null || !textView.isAttachedToWindow()) { - stopTicker(textView); - return; - } - reapplyTrackedText(textView, false, false); - scheduleNextTick(textView, this); - } - }; - tickers.put(textView, ticker); + private void syncTickerVisibility(View root) { + if (trackedRoles.isEmpty() || runtimeContext.getModeStateRepository().getActiveScene().isAod()) { + return; } - textView.removeCallbacks(ticker); + SbtSettings settings = RuntimeSettingsCache.get(root.getContext()); + for (Map.Entry entry : trackedRoles.entrySet()) { + TextView text = entry.getKey(); + if (!isDescendantOf(text, root)) { + continue; + } + if (!isClockVisible(text)) { + stopTicker(text); + } else if (!tickers.containsKey(text) && isEnabled(settings, entry.getValue()) + && ClockMarkupSupport.containsSecondsPattern(pattern(settings, entry.getValue()))) { + reapplyTrackedText(text, false, false); + } + } + } + + private boolean isClockVisible(TextView text) { + if (text.getWindowVisibility() != View.VISIBLE || !text.isShown()) { + return false; + } + View current = text; + while (current != null) { + if (current.getAlpha() <= 0f) { + return false; + } + current = current.getParent() instanceof View parent ? parent : null; + } + return true; + } + + private void startTicker(TextView textView) { + if (tickers.containsKey(textView) + || !isClockVisible(textView) + || !screenInteractive) { + return; + } + Runnable ticker = new Runnable() { + @Override + public void run() { + if (!textView.isAttachedToWindow() + || !isClockVisible(textView) + || !screenInteractive) { + stopTicker(textView); + return; + } + // Reapplying may disable or untrack this clock. + scheduleNextTick(textView, this); + reapplyTrackedText(textView, false, false); + } + }; + tickers.put(textView, ticker); scheduleNextTick(textView, ticker); } @@ -458,10 +516,6 @@ final class DrawerClockTextController { return locale != null ? locale.toLanguageTag() : Locale.getDefault().toLanguageTag(); } - private boolean sameText(CharSequence left, CharSequence right) { - return TextUtils.equals(left != null ? left.toString() : "", right != null ? right.toString() : ""); - } - private boolean isEnabled(SbtSettings settings, Role role) { String pattern = pattern(settings, role); if (TextUtils.isEmpty(pattern)) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/StockClockController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/StockClockController.java index 8440473..66f97f9 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/StockClockController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/features/clock/StockClockController.java @@ -4,6 +4,7 @@ import android.app.KeyguardManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.os.PowerManager; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; @@ -32,7 +33,9 @@ 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.render.TextViewStyleSupport; import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport; +import se.ajpanton.statusbartweak.runtime.settings.BatteryState; import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; @@ -46,6 +49,8 @@ final class StockClockController { private final RuntimeContext runtimeContext; private final Set trackedClocks = Collections.newSetFromMap(new WeakHashMap<>()); + private final Set lifecycleClocks = + Collections.newSetFromMap(new WeakHashMap<>()); private final Set ownedClocks = Collections.newSetFromMap(new WeakHashMap<>()); private final Map tickers = new WeakHashMap<>(); @@ -55,6 +60,7 @@ final class StockClockController { private final Map stockSnapshots = new WeakHashMap<>(); private boolean hooksInstalled; private boolean receiverRegistered; + private boolean screenInteractive; private boolean layoutModeListenerRegistered; StockClockController(RuntimeContext runtimeContext) { @@ -85,22 +91,6 @@ final class StockClockController { } private void hookClockClass(XposedInterface framework, Class clockClass) { - XposedHookSupport.hookAllMethodsIfExists(framework, clockClass, "onAttachedToWindow", chain -> { - Object result = chain.proceed(); - Object target = chain.getThisObject(); - if (target instanceof TextView clockView) { - trackAndApply(clockView, null); - } - return result; - }); - XposedHookSupport.hookAllMethodsIfExists(framework, clockClass, "onDetachedFromWindow", chain -> { - Object result = chain.proceed(); - Object target = chain.getThisObject(); - if (target instanceof TextView clockView) { - untrackClock(clockView); - } - return result; - }); XposedHookSupport.hookAllMethodsIfExists(framework, clockClass, "setVisibility", chain -> { Object result = chain.proceed(); Object target = chain.getThisObject(); @@ -108,6 +98,8 @@ final class StockClockController { TextView clockView = (TextView) target; if (clockView.getVisibility() == View.VISIBLE) { trackAndApply(clockView, null); + } else { + stopTicker(clockView); } if (rowOverlays.containsKey(clockView)) { syncRowOverlayVisuals(clockView); @@ -191,6 +183,25 @@ final class StockClockController { if (isNotificationShadeDescendant(clockView)) { return; } + if (lifecycleClocks.add(clockView)) { + // Inherited OEM callbacks need no hooks when the view owns its lifecycle listener. + clockView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { + @Override + public void onViewAttachedToWindow(View view) { + if (!trackedClocks.contains(view)) { + trackAndApply((TextView) view, null); + } + } + + @Override + public void onViewDetachedFromWindow(View view) { + untrackClock((TextView) view); + } + }); + } + if (!clockView.isAttachedToWindow()) { + return; + } trackedClocks.add(clockView); registerReceiverIfNeeded(clockView.getContext()); if (bellSound != null) { @@ -205,7 +216,6 @@ final class StockClockController { trackedClocks.remove(clockView); ownedClocks.remove(clockView); removeRowOverlay(clockView); - stopRowOverlayVisualSync(clockView); stockSnapshots.remove(clockView); stopTicker(clockView); } @@ -214,9 +224,19 @@ final class StockClockController { if (context == null || receiverRegistered) { return; } + screenInteractive = context.getSystemService(PowerManager.class).isInteractive(); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context ctx, Intent intent) { + if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { + screenInteractive = false; + suspendOwnedClockTickers(); + return; + } + if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) { + screenInteractive = true; + } + ClockLayoutTextFactory.invalidate(); refreshAllClocks(); } }; @@ -226,13 +246,18 @@ final class StockClockController { BroadcastReceiverSupport.filter( SbtSettings.ACTION_SETTINGS_CHANGED, Intent.ACTION_USER_UNLOCKED, - Intent.ACTION_BATTERY_CHANGED, + Intent.ACTION_SCREEN_ON, + Intent.ACTION_SCREEN_OFF, Intent.ACTION_TIME_TICK, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED, Intent.ACTION_LOCALE_CHANGED, Intent.ACTION_CONFIGURATION_CHANGED)); receiverRegistered = true; + BatteryState.addListener(context, () -> { + ClockLayoutTextFactory.invalidate(); + refreshAllClocks(); + }); } private void refreshAllClocks() { @@ -264,6 +289,10 @@ final class StockClockController { restoreOwnedClock(clockView); return; } + if (!clockView.isAttachedToWindow() || !screenInteractive || clockView.getVisibility() != View.VISIBLE) { + stopTicker(clockView); + return; + } captureCurrentStockSnapshot(clockView); ClockLayoutTextFactory.Model model = ClockLayoutTextFactory.build(clockView, settings); @@ -390,16 +419,15 @@ final class StockClockController { || runtimeContext.getModeStateRepository().isLayoutEnabled() || !isUnlockedForOverlay(clockView.getContext())) { removeRowOverlay(clockView); - stopRowOverlayVisualSync(clockView); return; } - ViewGroup host = findOverlayHost(clockView); - if (host == null) { + if (!(clockView.getRootView() instanceof ViewGroup host)) { removeRowOverlay(clockView); - stopRowOverlayVisualSync(clockView); return; } - disableAncestorClipping(host); + host.setClipChildren(false); + host.setClipToPadding(false); + host.setClipToOutline(false); ClockRowsOverlay overlay = rowOverlays.get(clockView); if (overlay == null || overlay.host != host) { removeRowOverlay(clockView); @@ -430,32 +458,6 @@ final class StockClockController { } } - private void disableAncestorClipping(View view) { - Object parent = view; - int depth = 0; - while (parent instanceof ViewGroup && depth < 12) { - ViewGroup group = (ViewGroup) parent; - group.setClipChildren(false); - group.setClipToPadding(false); - group.setClipToOutline(false); - parent = group.getParent(); - depth++; - } - } - - private ViewGroup findOverlayHost(TextView clockView) { - android.view.ViewParent parent = clockView.getParent(); - ViewGroup best = null; - int depth = 0; - while (parent instanceof ViewGroup && depth < 12) { - ViewGroup group = (ViewGroup) parent; - best = group; - parent = group.getParent(); - depth++; - } - return best; - } - private void removeRowOverlay(TextView clockView) { ClockRowsOverlay overlay = rowOverlays.remove(clockView); if (overlay != null) { @@ -465,11 +467,11 @@ final class StockClockController { } private void ensureRowOverlayVisualSync(TextView clockView) { - if (clockView == null || rowOverlaySyncListeners.containsKey(clockView)) { + if (rowOverlaySyncListeners.containsKey(clockView)) { return; } ViewTreeObserver observer = clockView.getViewTreeObserver(); - if (observer == null || !observer.isAlive()) { + if (!observer.isAlive()) { return; } ViewTreeObserver.OnPreDrawListener listener = () -> { @@ -486,7 +488,7 @@ final class StockClockController { return; } ViewTreeObserver observer = clockView.getViewTreeObserver(); - if (observer != null && observer.isAlive()) { + if (observer.isAlive()) { observer.removeOnPreDrawListener(listener); } } @@ -501,22 +503,22 @@ final class StockClockController { } private void startTicker(TextView clockView) { - Runnable ticker = tickers.get(clockView); - if (ticker == null) { - ticker = new Runnable() { - @Override - public void run() { - if (clockView.getHandler() == null || !clockView.isAttachedToWindow()) { - stopTicker(clockView); - return; - } - applyClockText(clockView); - scheduleNextTick(clockView, this); - } - }; - tickers.put(clockView, ticker); + if (tickers.containsKey(clockView)) { + return; } - clockView.removeCallbacks(ticker); + Runnable ticker = new Runnable() { + @Override + public void run() { + if (!clockView.isAttachedToWindow() || !screenInteractive) { + stopTicker(clockView); + return; + } + // Schedule first so applyClockText can cancel the next tick. + scheduleNextTick(clockView, this); + applyClockText(clockView); + } + }; + tickers.put(clockView, ticker); scheduleNextTick(clockView, ticker); } @@ -604,11 +606,14 @@ final class StockClockController { } } - private final class ClockRowsOverlay { + static final class ClockRowsOverlay { final ViewGroup host; private final ViewGroupOverlay overlay; private final ArrayList rowViews = new ArrayList<>(); + private final int[] sourceLocation = new int[2]; + private final int[] hostLocation = new int[2]; private ArrayList lastRows; + private ArrayList rowMetrics; private boolean removed; ClockRowsOverlay(ViewGroup host) { @@ -622,38 +627,52 @@ final class StockClockController { remove(); return; } - lastRows = new ArrayList<>(rows); + lastRows = rows; + rowMetrics = null; if (!source.isAttachedToWindow() || source.getBaseline() < 0 || source.getWidth() <= 0) { - source.post(() -> { - if (!removed) { - update(source, rows); - } - }); return; } int visibleRows = rows.size() - 1; ensureViewCount(source, visibleRows); + for (int rowIndex = 0; rowIndex < visibleRows; rowIndex++) { + TextView rowView = rowViews.get(rowIndex); + rowView.setText(rows.get(rowIndex).text); + TextViewStyleSupport.copyIfChanged(source, rowView); + } + rowMetrics = measureRows(source, rows); + syncFromSource(source); + } - int[] sourceLocation = new int[2]; - int[] hostLocation = new int[2]; + void syncFromSource(TextView source) { + if (removed || lastRows == null) { + return; + } + if (rowMetrics == null) { + update(source, lastRows); + return; + } + boolean styleChanged = false; + VisualState visualState = resolveVisualState(source); + for (TextView rowView : rowViews) { + styleChanged |= TextViewStyleSupport.copyIfChanged(source, rowView); + rowView.setVisibility(visualState.visible ? View.VISIBLE : View.INVISIBLE); + rowView.setAlpha(visualState.alpha); + } + if (styleChanged) { + rowMetrics = measureRows(source, lastRows); + } source.getLocationOnScreen(sourceLocation); host.getLocationOnScreen(hostLocation); int sourceBaselineY = sourceLocation[1] - hostLocation[1] + source.getBaseline(); - ArrayList rowMetrics = measureRows(source, rows); - int anchorOffset = alignmentOffset(rowMetrics.get(rows.size() - 1), rowMetrics); - RowMetrics bottomMetrics = rowMetrics.get(rows.size() - 1); + int anchorOffset = alignmentOffset(rowMetrics.get(lastRows.size() - 1), rowMetrics); + RowMetrics bottomMetrics = rowMetrics.get(lastRows.size() - 1); int rowBottomY = sourceBaselineY - bottomMetrics.baseline + bottomMetrics.height; - for (int rowIndex = rows.size() - 2; rowIndex >= 0; rowIndex--) { - ClockTextRenderer.LayoutRowResult nextRow = rows.get(rowIndex + 1); - rowBottomY -= resolveGap(nextRow != null ? nextRow.gapBeforePx : 0, source); + for (int rowIndex = lastRows.size() - 2; rowIndex >= 0; rowIndex--) { + rowBottomY -= resolveGap(lastRows.get(rowIndex + 1).gapBeforePx, source); TextView rowView = rowViews.get(rowIndex); - ClockTextRenderer.LayoutRowResult row = rows.get(rowIndex); RowMetrics metrics = rowMetrics.get(rowIndex); - rowView.setText(row != null ? row.text : ""); - copyTextViewStyle(source, rowView); positionRowView( - source, rowView, sourceLocation[0] - hostLocation[0] + alignmentOffset(rowMetrics.get(rowIndex), rowMetrics) @@ -662,14 +681,6 @@ final class StockClockController { } } - void syncFromSource(TextView source) { - if (lastRows == null || lastRows.size() <= 1) { - remove(); - return; - } - update(source, lastRows); - } - private ArrayList measureRows( TextView source, ArrayList rows @@ -679,7 +690,7 @@ final class StockClockController { probe.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - copyTextViewStyle(source, probe); + TextViewStyleSupport.copyIfChanged(source, probe); for (ClockTextRenderer.LayoutRowResult row : rows) { metrics.add(measureRowMetrics(probe, row)); } @@ -690,8 +701,8 @@ final class StockClockController { TextView probe, ClockTextRenderer.LayoutRowResult row ) { - TextMetrics text = measureText(probe, row != null ? row.text : ""); - if (row == null || row.pipeCount <= 0) { + TextMetrics text = measureText(probe, row.text); + if (row.pipeCount <= 0) { return new RowMetrics(text.width, text.height, text.baseline, 0, 0); } int leftPipe = measureText(probe, row.leftText).width; @@ -703,7 +714,7 @@ final class StockClockController { } private TextMetrics measureText(TextView probe, CharSequence text) { - probe.setText(text != null ? text : ""); + probe.setText(text); int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); probe.measure(widthSpec, heightSpec); @@ -714,12 +725,12 @@ final class StockClockController { } private int alignmentOffset(RowMetrics row, ArrayList rows) { - if (row == null || row.pipeCount <= 0) { + if (row.pipeCount <= 0) { return 0; } int maxPipePosition = 0; for (RowMetrics candidate : rows) { - if (candidate != null && candidate.pipeCount > 0) { + if (candidate.pipeCount > 0) { maxPipePosition = Math.max(maxPipePosition, candidate.pipePosition); } } @@ -753,28 +764,6 @@ final class StockClockController { } } - private void copyTextViewStyle(TextView source, TextView target) { - target.setTextColor(source.getCurrentTextColor()); - target.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, source.getTextSize()); - target.setTypeface(source.getTypeface()); - target.setGravity(source.getGravity()); - target.setIncludeFontPadding(source.getIncludeFontPadding()); - target.setPadding( - source.getPaddingLeft(), - source.getPaddingTop(), - source.getPaddingRight(), - source.getPaddingBottom()); - target.setLetterSpacing(source.getLetterSpacing()); - target.setFontFeatureSettings(source.getFontFeatureSettings()); - VisualState visualState = resolveVisualState(source); - target.setVisibility(visualState.visible ? View.VISIBLE : View.INVISIBLE); - target.setAlpha(visualState.alpha); - } - - int rowCount() { - return rowViews.size(); - } - private VisualState resolveVisualState(TextView source) { float alpha = 1f; boolean visible = source.isShown(); @@ -791,7 +780,6 @@ final class StockClockController { } private void positionRowView( - TextView source, TextView rowView, int left, int baselineY @@ -812,11 +800,11 @@ final class StockClockController { } private int statusbarHeight(TextView source) { - if (source == null || source.getHeight() <= 0) { + if (source.getHeight() <= 0) { return 1; } View root = source.getRootView(); - if (root == null || root.getHeight() <= 0) { + if (root.getHeight() <= 0) { return Math.max(1, source.getTop() + source.getHeight()); } int[] sourceLocation = new int[2]; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupport.java index bdff494..f948c08 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupport.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupport.java @@ -2,12 +2,27 @@ package se.ajpanton.statusbartweak.runtime.hooks; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; /** * Small reflection helpers used by rebuilt runtime slices. */ public final class ReflectionSupport { private static final Class[] NO_ARGS = new Class[0]; + private static final ClassValue>> FIELDS = new ClassValue<>() { + @Override + protected Map> computeValue(Class type) { + return new ConcurrentHashMap<>(); + } + }; + private static final ClassValue>> NO_ARG_METHODS = new ClassValue<>() { + @Override + protected Map> computeValue(Class type) { + return new ConcurrentHashMap<>(); + } + }; private ReflectionSupport() { } @@ -162,6 +177,11 @@ public final class ReflectionSupport { } private static Field findField(Class type, String fieldName) { + return FIELDS.get(type).computeIfAbsent(fieldName, + name -> Optional.ofNullable(lookupField(type, name))).orElse(null); + } + + private static Field lookupField(Class type, String fieldName) { Class current = type; while (current != null) { try { @@ -176,6 +196,14 @@ public final class ReflectionSupport { } private static Method findMethod(Class type, String methodName, Class[] parameterTypes) { + if (parameterTypes == null || parameterTypes.length == 0) { + return NO_ARG_METHODS.get(type).computeIfAbsent(methodName, + name -> Optional.ofNullable(lookupMethod(type, name, NO_ARGS))).orElse(null); + } + return lookupMethod(type, methodName, parameterTypes); + } + + private static Method lookupMethod(Class type, String methodName, Class[] parameterTypes) { Class current = type; while (current != null) { try { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/XposedHookSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/XposedHookSupport.java index daee6c4..e2fa5c7 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/XposedHookSupport.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/hooks/XposedHookSupport.java @@ -26,21 +26,7 @@ public final class XposedHookSupport { String methodName, XposedInterface.Hooker hooker ) { - Objects.requireNonNull(framework, "framework"); - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(methodName, "methodName"); - Objects.requireNonNull(hooker, "hooker"); - List handles = new ArrayList<>(); - for (Method method : type.getDeclaredMethods()) { - if (!methodName.equals(method.getName())) { - continue; - } - if (Modifier.isAbstract(method.getModifiers())) { - continue; - } - method.setAccessible(true); - handles.add(framework.hook(method).intercept(hooker)); - } + List handles = hookAllMethodsIfExists(framework, type, methodName, hooker); if (handles.isEmpty()) { throw new IllegalStateException( "No methods matched hook target: " + type.getName() + "#" + methodName); @@ -77,14 +63,7 @@ public final class XposedHookSupport { Class type, XposedInterface.Hooker hooker ) { - Objects.requireNonNull(framework, "framework"); - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(hooker, "hooker"); - List handles = new ArrayList<>(); - for (Constructor constructor : type.getDeclaredConstructors()) { - constructor.setAccessible(true); - handles.add(framework.hook(constructor).intercept(hooker)); - } + List handles = hookAllConstructorsIfExists(framework, type, hooker); if (handles.isEmpty()) { throw new IllegalStateException("No constructors matched hook target: " + type.getName()); } 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 002e1e5..c8e04cf 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 @@ -40,6 +40,7 @@ import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection; import se.ajpanton.statusbartweak.runtime.RuntimeMutationGuard; import se.ajpanton.statusbartweak.runtime.ViewIdNames; import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; +import se.ajpanton.statusbartweak.runtime.features.clock.ClockLayoutTextFactory; import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport; import se.ajpanton.statusbartweak.runtime.hooks.XposedHookSupport; import se.ajpanton.statusbartweak.runtime.layoutsolver.StatusBarLayoutSolver.Bounds; @@ -56,6 +57,7 @@ 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.runtime.settings.BatteryState; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; final class StockLayoutCanvasController { @@ -187,6 +189,7 @@ final class StockLayoutCanvasController { private WeakReference lockedCarrierTextSource = new WeakReference<>(null); private boolean hooksInstalled; + private boolean batteryListenerRegistered; private int ownHiddenViewAlphaWriteDepth; private boolean notificationDrawerWasOpen; private int notificationDrawerCloseGeneration; @@ -359,7 +362,8 @@ final class StockLayoutCanvasController { } for (Method method : type.getDeclaredMethods()) { String lowerName = method.getName().toLowerCase(Locale.ROOT); - if (!isNotificationCollectionMutationMethod(lowerName)) { + if (java.lang.reflect.Modifier.isStatic(method.getModifiers()) + || !isNotificationCollectionMutationMethod(lowerName)) { continue; } method.setAccessible(true); @@ -653,13 +657,6 @@ final class StockLayoutCanvasController { if (darkIconDispatcherClass != null) { darkIconDispatcherGuard.install(darkIconDispatcherClass); } - Class lightBarTransitionsControllerClass = ReflectionSupport.findClassIfExists( - "com.android.systemui.statusbar.phone.LightBarTransitionsController", - classLoader); - if (lightBarTransitionsControllerClass != null) { - hookLightBarTintTarget(lightBarTransitionsControllerClass); - } - Class statusBarIconViewClass = ReflectionSupport.findClassIfExists( "com.android.systemui.statusbar.StatusBarIconView", classLoader); @@ -741,7 +738,6 @@ final class StockLayoutCanvasController { hookStatusChipLifecycle(touchInterceptClass, "onDetachedFromWindow"); hookStatusChipLifecycle(touchInterceptClass, "onLayout"); hookStatusChipLifecycle(touchInterceptClass, "setVisibility"); - hookStatusChipLifecycle(touchInterceptClass, "setAlpha"); } Class batteryClass = ReflectionSupport.findClassIfExists( @@ -764,27 +760,6 @@ final class StockLayoutCanvasController { hookStatusChipContentInvalidation(ImageView.class, "setImageLevel"); } - private void hookLightBarTintTarget(Class type) { - for (Method method : type.getDeclaredMethods()) { - if (!isSetIconsDarkMethod(method)) { - continue; - } - method.setAccessible(true); - runtimeContext.getFramework().hook(method).intercept( - chain -> { - List args = chain.getArgs(); - Object result = chain.proceed(); - return result; - }); - } - } - - private boolean isSetIconsDarkMethod(Method method) { - return "setIconsDark".equals(method.getName()) - && method.getParameterCount() >= 1 - && method.getParameterTypes()[0] == boolean.class; - } - private void hookViewAppearanceInvalidation(Class type, String methodName) { XposedHookSupport.hookAllMethodsIfExists( runtimeContext.getFramework(), @@ -852,10 +827,7 @@ final class StockLayoutCanvasController { View view = chain.getThisObject() instanceof View candidate ? candidate : null; View rootBefore = view != null ? unlockedStatusBarRootFor(view) : null; Object result = chain.proceed(); - if (view != null && ("onLayout".equals(methodName) - || "setVisibility".equals(methodName) - || "onAttachedToWindow".equals(methodName) - || "onDetachedFromWindow".equals(methodName))) { + if (view != null) { markStatusChipLifecycleDirtyIfNeeded(view, rootBefore); } return result; @@ -1880,10 +1852,7 @@ final class StockLayoutCanvasController { && !settings.clockCustomFormatEnabled)) { return 0L; } - String pattern = settings.clockCustomFormat != null ? settings.clockCustomFormat : ""; - boolean seconds = settings.clockShowSeconds - || (settings.clockCustomFormatEnabled && pattern.contains("s")); - long divisor = seconds ? 1_000L : 60_000L; + long divisor = ClockLayoutTextFactory.usesSeconds(settings) ? 1_000L : 60_000L; return System.currentTimeMillis() / divisor; } @@ -1893,18 +1862,20 @@ final class StockLayoutCanvasController { return; } Runnable existing = unlockedClockTickersByRoot.get(root); - if (existing != null) { + if (existing != null || !isInteractive(root.getContext())) { return; } Runnable ticker = new Runnable() { @Override public void run() { - if (!clockNeedsSecondTicker(root, RuntimeSettingsCache.get(root.getContext()), + if (!isInteractive(root.getContext()) + || !clockNeedsSecondTicker(root, RuntimeSettingsCache.get(root.getContext()), runtimeContext.getModeStateRepository().getActiveScene())) { stopUnlockedClockTicker(root); return; } - scheduleUnlockedClockTextRefreshForRoot(root); + clockTimeBucketByRoot.put(root, clockTimeBucket(RuntimeSettingsCache.get(root.getContext()))); + refreshUnlockedClockTextNow(root); scheduleNextUnlockedClockTick(root, this); } }; @@ -1921,16 +1892,8 @@ final class StockLayoutCanvasController { || !clockTextRefreshEnabledForScene(settings, scene)) { return false; } - return clockUsesSeconds(settings); - } - - private boolean clockUsesSeconds(SbtSettings settings) { - if (settings == null) { - return false; - } - String pattern = settings.clockCustomFormat != null ? settings.clockCustomFormat : ""; - return settings.clockShowSeconds - || (settings.clockCustomFormatEnabled && pattern.contains("s")); + return ClockLayoutTextFactory.usesSeconds(settings) + && isClockHostVisible(unlockedHostsByRoot.get(root)); } private void scheduleNextUnlockedClockTick(View root, Runnable ticker) { @@ -2024,8 +1987,13 @@ final class StockLayoutCanvasController { root.getHandler().post(refresh); } if (lockscreenEntry) { - root.postDelayed(() -> refreshSceneRoot(root), 80L); - root.postDelayed(() -> refreshSceneRoot(root), 180L); + Runnable followup = () -> { + if (current.equals(runtimeContext.getModeStateRepository().getActiveScene())) { + refreshSceneRoot(root); + } + }; + root.postDelayed(followup, 80L); + root.postDelayed(followup, 180L); } } } @@ -2181,7 +2149,7 @@ final class StockLayoutCanvasController { return; } UnlockedHosts unlockedHosts = unlockedHostsByRoot.get(root); - if (unlockedHosts == null || !areUnlockedHostsAttached(root, unlockedHosts)) { + if (!isClockHostVisible(unlockedHosts) || !areUnlockedHostsAttached(root, unlockedHosts)) { return; } if (unlockedIconRenderController.refreshUnlockedClockText( @@ -2193,6 +2161,13 @@ final class StockLayoutCanvasController { } } + private boolean isClockHostVisible(UnlockedHosts hosts) { + return hosts != null + && hosts.clockHost.getWindowVisibility() == View.VISIBLE + && hosts.clockHost.isShown() + && hosts.clockHost.getAlpha() > 0f; + } + private void bringUnlockedHostsAndDebugOverlayToFront(View root) { ownedIconHostManager.bringUnlockedHostsToFront(root); debugBoundsOverlayController.bringToFront(root); @@ -2297,6 +2272,10 @@ final class StockLayoutCanvasController { applyLayoutOffRoot(root, settings, statusBarRoot, activeScene); return; } + if (statusBarRoot && !batteryListenerRegistered) { + BatteryState.addListener(context, this::requestUnlockedLayoutRefreshForAllRoots); + batteryListenerRegistered = true; + } installPendingPluginClassLoaderHooks(); layoutOffCleanedRoots.remove(root); if (statusIconModelTracker.updateActiveSlots( @@ -2354,7 +2333,7 @@ final class StockLayoutCanvasController { } else if (activeScene != null && activeScene.isLockscreen() && canContainLockedStatusBarIconSurfaces(root)) { - removeUnlockedLayoutHosts(root); + removeSharedLayoutHosts(root); hideOrDiscoverLockedStatusBarIconSurfaces(root); } else { removeSharedLayoutHosts(root); @@ -2362,17 +2341,12 @@ final class StockLayoutCanvasController { removeDebugOverlay(root); return; } - if (activeScene != null - && (activeScene.isUnlocked() || activeScene.isLockscreen() || activeScene.isAod()) - && resetUnlockedHostsForRootGeometryChange(root)) { + if (activeScene != null && resetUnlockedHostsForRootGeometryChange(root)) { return; } UnlockedHosts unlockedHosts = updateUnlockedOwnedHosts(root, activeScene); RenderResult renderResult = new RenderResult(false, false, false); - if (unlockedHosts != null - && (unlockedScene - || activeScene != null && activeScene.isLockscreen() - || aodScene)) { + if (unlockedHosts != null && activeScene != null) { boolean shouldRender = !unlockedIconRenderController.hasLayoutPlan(root) || rootDirty; if (shouldRender && shouldDeferUnlockedRenderForDrawer(root)) { @@ -2394,7 +2368,7 @@ final class StockLayoutCanvasController { lockedCarrierTextSource()); boolean shouldShowUnlockedHosts = unlockedScene || aodScene - || (!unlockedScene && renderResult.shouldOwnLockscreen()); + || renderResult.shouldOwnLockscreen(); ownedIconHostManager.setUnlockedHostsVisible(root, shouldShowUnlockedHosts); if (shouldShowUnlockedHosts) { bringUnlockedHostsAndDebugOverlayToFront(root); @@ -3280,13 +3254,9 @@ final class StockLayoutCanvasController { private boolean stackContainsConflictingShadeHeaderAnimator() { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stack) { - if (element == null) { - continue; - } String className = element.getClassName(); String methodName = element.getMethodName(); - if (className != null - && className.contains("LegacyQsExpandAnimator") + if (className.contains("LegacyQsExpandAnimator") && ("setQsExpansionPosition".equals(methodName) || "clearAnimationState".equals(methodName))) { return true; @@ -4588,19 +4558,6 @@ final class StockLayoutCanvasController { clearUnlockedClockRefreshState(root); } - private void removeUnlockedLayoutHosts(View root) { - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_UNLOCKED_STATUS_HOST); - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_UNLOCKED_NOTIFICATION_HOST); - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_UNLOCKED_CLOCK_HOST); - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_UNLOCKED_CARRIER_HOST); - ownedIconHostManager.removeHost(root, OwnedIconHostManager.TAG_UNLOCKED_CHIP_HOST); - unlockedHostsByRoot.remove(root); - pendingUnlockedAppearanceRefreshRoots.remove(root); - dirtyUnlockedLayoutRoots.remove(root); - settingsIdentityByRoot.remove(root); - clearUnlockedClockRefreshState(root); - } - private boolean isDescendantOfNotificationShadeWindow(View view) { View current = view; while (current != null) { @@ -4670,8 +4627,7 @@ final class StockLayoutCanvasController { && isAodLayoutRoot(root, activeScene))) { return null; } - if (activeScene != null - && (activeScene.isUnlocked() || activeScene.isLockscreen() || activeScene.isAod())) { + if (activeScene != null) { UnlockedHosts cached = unlockedHostsByRoot.get(root); if (areUnlockedHostsAttached(root, cached)) { return cached; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasFeature.java index 10c3067..f9a33c1 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/layout/StockLayoutCanvasFeature.java @@ -4,10 +4,7 @@ import io.github.libxposed.api.XposedModuleInterface; import se.ajpanton.statusbartweak.runtime.features.RuntimeContext; import se.ajpanton.statusbartweak.runtime.features.RuntimeFeature; -/** - * First layout-engine behavioral slice: clear stock icon surfaces so the new - * layout runtime starts from an empty canvas when Layout is enabled. - */ +/** Owns stock-source suppression and custom statusbar layout/rendering. */ public final class StockLayoutCanvasFeature implements RuntimeFeature { private StockLayoutCanvasController systemUiController; @@ -19,9 +16,6 @@ public final class StockLayoutCanvasFeature implements RuntimeFeature { @Override public void onPackageReady(RuntimeContext context, XposedModuleInterface.PackageReadyParam param) { - if (!RuntimeFeature.isSystemUiPackage(param)) { - return; - } if (systemUiController == null) { systemUiController = new StockLayoutCanvasController(context); } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/mode/SystemUiStatusBarStateFeature.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/mode/SystemUiStatusBarStateFeature.java index 494b56d..863ce10 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/mode/SystemUiStatusBarStateFeature.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/mode/SystemUiStatusBarStateFeature.java @@ -35,7 +35,7 @@ public final class SystemUiStatusBarStateFeature implements RuntimeFeature { @Override public void onPackageReady(RuntimeContext context, XposedModuleInterface.PackageReadyParam param) { - if (installed || !RuntimeFeature.isSystemUiPackage(param)) { + if (installed) { return; } Class controllerClass = ReflectionSupport.findClassIfExists( diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java index 398f359..e3526c0 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/AodNotificationIconSourceStore.java @@ -241,35 +241,6 @@ public final class AodNotificationIconSourceStore { return result; } - public static int snapshotSourceSignatureForRoot(View root) { - ArrayList sources = snapshotSourcesForRoot(root); - int result = 17; - for (SnapshotSource source : sources) { - result = 31 * result + snapshotSourceSignature(root, source); - } - return result; - } - - private static int snapshotSourceSignature(View root, SnapshotSource source) { - if (source == null) { - return 0; - } - int result = 17; - View view = source.view(); - result = 31 * result + System.identityHashCode(view); - result = 31 * result + (source.keyHint() != null ? source.keyHint().hashCode() : 0); - result = 31 * result + (source.mode() != null ? source.mode().hashCode() : 0); - Bounds override = source.boundsOverride(); - result = 31 * result + (override != null ? override.signature() : 0); - Bounds bounds = ViewGeometry.boundsRelativeTo(root, view); - result = 31 * result + (bounds != null ? bounds.signature() : 0); - if (view != null) { - result = 31 * result + view.getVisibility(); - result = 31 * result + Float.floatToIntBits(view.getAlpha()); - } - return result; - } - static ArrayList snapshotSourcesForAodIconsRoot(View root) { ArrayList result = new ArrayList<>(); ViewGroup container = sourceContainerForAodIconsRoot(root); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockLayout.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockLayout.java index 05c7116..35f0439 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockLayout.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockLayout.java @@ -74,7 +74,7 @@ final class ClockLayout { probe.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - ClockProxyRenderer.copyTextStyleIfChanged(source, probe); + TextViewStyleSupport.copyIfChanged(source, probe); float resolvedTextSizePx = textSizeForTargetPlainRowHeight(probe, model, textSizePx); applyTextSizeOverride(probe, resolvedTextSizePx); ArrayList measuredRows = new ArrayList<>(); @@ -169,7 +169,7 @@ final class ClockLayout { probe.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - ClockProxyRenderer.copyTextStyleIfChanged(source, probe); + TextViewStyleSupport.copyIfChanged(source, probe); MeasuredText measured = measureText(probe, source.getText()); if (measured.width <= 0 || measured.height <= 0) { return null; @@ -208,7 +208,7 @@ final class ClockLayout { probe.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - ClockProxyRenderer.copyTextStyleIfChanged(source, probe); + TextViewStyleSupport.copyIfChanged(source, probe); MeasuredText measured = measureText(probe, source.getText()); int availableHeight = containerHeight > 0 ? containerHeight : measured.height; int extraHeight = Math.max(0, availableHeight - measured.height); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextView.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextView.java index 43b25b5..709cf40 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextView.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockOutlineTextView.java @@ -3,14 +3,15 @@ package se.ajpanton.statusbartweak.runtime.render; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; -import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextPaint; +import android.text.style.CharacterStyle; import android.text.style.ForegroundColorSpan; -import java.util.ArrayList; - import androidx.appcompat.widget.AppCompatTextView; -/** Draws the outline with one colour, then restores the original span colours for the text fill. */ +/** Uses draw-state spans so outlining never mutates the TextView's live text. */ final class ClockOutlineTextView extends AppCompatTextView { private int sourcePaddingLeft; private int sourcePaddingTop; @@ -18,12 +19,38 @@ final class ClockOutlineTextView extends AppCompatTextView { private int sourcePaddingBottom; private int outlineColor; private float outlineThicknessPx; - private ForegroundColorSpan outlineSpan; ClockOutlineTextView(Context context) { super(context); } + @Override + public void setText(CharSequence text, BufferType type) { + if (text == null || text.length() == 0) { + super.setText(text, type); + return; + } + SpannableStringBuilder styled = new SpannableStringBuilder(text); + for (StrokeColorSpan span : styled.getSpans(0, styled.length(), StrokeColorSpan.class)) { + styled.removeSpan(span); + } + for (ForegroundColorSpan span : styled.getSpans(0, styled.length(), ForegroundColorSpan.class)) { + int start = styled.getSpanStart(span); + int end = styled.getSpanEnd(span); + int flags = styled.getSpanFlags(span); + styled.removeSpan(span); + styled.setSpan(new ForegroundColorSpan(span.getForegroundColor()) { + @Override + public void updateDrawState(TextPaint paint) { + super.updateDrawState(paint); + applyStrokeColor(paint); + } + }, start, end, flags); + } + styled.setSpan(new StrokeColorSpan(), 0, styled.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); + super.setText(styled, BufferType.SPANNABLE); + } + boolean setSourcePadding(int left, int top, int right, int bottom) { if (sourcePaddingLeft == left && sourcePaddingTop == top @@ -47,7 +74,6 @@ final class ClockOutlineTextView extends AppCompatTextView { } outlineColor = color; outlineThicknessPx = thickness; - outlineSpan = new ForegroundColorSpan(color); applyPaddedInsets(); return true; } @@ -66,14 +92,12 @@ final class ClockOutlineTextView extends AppCompatTextView { Paint.Style style = paint.getStyle(); float strokeWidth = paint.getStrokeWidth(); int color = paint.getColor(); - ArrayList foregrounds = replaceForegroundColors(); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(outlineThicknessPx * 2f); paint.setColor(outlineColor); try { super.onDraw(canvas); } finally { - restoreForegroundColors(foregrounds); paint.setStyle(style); paint.setStrokeWidth(strokeWidth); paint.setColor(color); @@ -81,34 +105,9 @@ final class ClockOutlineTextView extends AppCompatTextView { super.onDraw(canvas); } - private ArrayList replaceForegroundColors() { - if (!(getText() instanceof Spannable text) || text.length() == 0) { - return null; - } - ForegroundColorSpan[] spans = text.getSpans(0, text.length(), ForegroundColorSpan.class); - ArrayList states = new ArrayList<>(spans.length); - for (ForegroundColorSpan span : spans) { - states.add(new SpanState( - span, - text.getSpanStart(span), - text.getSpanEnd(span), - text.getSpanFlags(span))); - text.removeSpan(span); - } - text.setSpan(outlineSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - return states; - } - - private void restoreForegroundColors(ArrayList states) { - if (!(getText() instanceof Spannable text) || outlineSpan == null) { - return; - } - text.removeSpan(outlineSpan); - if (states == null) { - return; - } - for (SpanState state : states) { - text.setSpan(state.span, state.start, state.end, state.flags); + private void applyStrokeColor(TextPaint paint) { + if (paint.getStyle() == Paint.Style.STROKE) { + paint.setColor(outlineColor); } } @@ -125,6 +124,10 @@ final class ClockOutlineTextView extends AppCompatTextView { sourcePaddingBottom + inset); } - private record SpanState(ForegroundColorSpan span, int start, int end, int flags) { + private final class StrokeColorSpan extends CharacterStyle { + @Override + public void updateDrawState(TextPaint paint) { + applyStrokeColor(paint); + } } } diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRenderer.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRenderer.java index 01f0fc6..58f25a9 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRenderer.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/ClockProxyRenderer.java @@ -50,15 +50,13 @@ final class ClockProxyRenderer { for (int i = 0; i < placement.rows.size(); i++) { ClockRow row = placement.rows.get(i); ClockOutlineTextView view = (ClockOutlineTextView) views.get(i); - if (copyTextStyleIfChanged(placement.source, view, placement.textSizePx)) { + if (TextViewStyleSupport.copyIfChanged(placement.source, view, + placement.textSizePx, placement.textColorOverride)) { hostChanged = true; } if (view.setOutline(outline)) { hostChanged = true; } - if (applyTextColorOverrideIfNeeded(view, placement.textColorOverride)) { - hostChanged = true; - } if (applyCarrierMarqueeIfNeeded(placement.source, view)) { hostChanged = true; } @@ -180,78 +178,6 @@ final class ClockProxyRenderer { } } - static boolean copyTextStyleIfChanged(TextView source, TextView target) { - return copyTextStyleIfChanged(source, target, 0f); - } - - static boolean copyTextStyleIfChanged(TextView source, TextView target, float textSizePx) { - boolean changed = false; - if (target.getCurrentTextColor() != source.getCurrentTextColor()) { - target.setTextColor(source.getCurrentTextColor()); - changed = true; - } - float desiredTextSize = textSizePx > 0f ? textSizePx : source.getTextSize(); - if (target.getTextSize() != desiredTextSize) { - target.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, desiredTextSize); - changed = true; - } - if (!Objects.equals(target.getTypeface(), source.getTypeface())) { - target.setTypeface(source.getTypeface()); - changed = true; - } - if (target.getGravity() != source.getGravity()) { - target.setGravity(source.getGravity()); - changed = true; - } - if (target.getIncludeFontPadding() != source.getIncludeFontPadding()) { - target.setIncludeFontPadding(source.getIncludeFontPadding()); - changed = true; - } - if (target.getMaxLines() != 1) { - target.setSingleLine(true); - target.setMaxLines(1); - changed = true; - } - if (!target.isHorizontallyScrollable()) { - target.setHorizontallyScrolling(true); - changed = true; - } - if (target instanceof ClockOutlineTextView outlineTarget) { - changed |= outlineTarget.setSourcePadding( - source.getPaddingLeft(), - source.getPaddingTop(), - source.getPaddingRight(), - source.getPaddingBottom()); - } else if (target.getPaddingLeft() != source.getPaddingLeft() - || target.getPaddingTop() != source.getPaddingTop() - || target.getPaddingRight() != source.getPaddingRight() - || target.getPaddingBottom() != source.getPaddingBottom()) { - target.setPadding( - source.getPaddingLeft(), - source.getPaddingTop(), - source.getPaddingRight(), - source.getPaddingBottom()); - changed = true; - } - if (target.getLetterSpacing() != source.getLetterSpacing()) { - target.setLetterSpacing(source.getLetterSpacing()); - changed = true; - } - if (!Objects.equals(target.getFontFeatureSettings(), source.getFontFeatureSettings())) { - target.setFontFeatureSettings(source.getFontFeatureSettings()); - changed = true; - } - return changed; - } - - private static boolean applyTextColorOverrideIfNeeded(TextView view, int color) { - if (view == null || (color >>> 24) == 0 || view.getCurrentTextColor() == color) { - return false; - } - view.setTextColor(color); - return true; - } - private static boolean applyTextLayoutParams( ViewGroup host, TextView view, 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 21c52de..b4956a0 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 @@ -33,13 +33,6 @@ public final class OwnedIconHostManager { TAG_UNLOCKED_CARRIER_HOST, TAG_UNLOCKED_CHIP_HOST }; - private static final String[] UNLOCKED_HOST_ORDER = { - TAG_UNLOCKED_STATUS_HOST, - TAG_UNLOCKED_NOTIFICATION_HOST, - TAG_UNLOCKED_CLOCK_HOST, - TAG_UNLOCKED_CARRIER_HOST, - TAG_UNLOCKED_CHIP_HOST - }; public FrameLayout ensureUnlockedStatusHost(View root) { return ensureHost(root, TAG_UNLOCKED_STATUS_HOST); @@ -100,7 +93,7 @@ public final class OwnedIconHostManager { } public void setUnlockedHostsVisible(View root, boolean visible) { - for (String tag : UNLOCKED_HOST_ORDER) { + for (String tag : OWNED_HOST_TAGS) { setHostVisible(root, tag, visible); } } @@ -111,7 +104,7 @@ public final class OwnedIconHostManager { float translationX, float translationY ) { - for (String tag : UNLOCKED_HOST_ORDER) { + for (String tag : OWNED_HOST_TAGS) { setHostTransform(root, tag, alpha, translationX, translationY); } } @@ -193,7 +186,7 @@ public final class OwnedIconHostManager { private ArrayList unlockedHosts(ViewGroup parent) { ArrayList hosts = new ArrayList<>(); - for (String tag : UNLOCKED_HOST_ORDER) { + for (String tag : OWNED_HOST_TAGS) { View host = findDirectHost(parent, tag); if (host != null) { hosts.add(host); diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRenderer.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRenderer.java index 402abf8..6625afb 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRenderer.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/SnapshotRenderer.java @@ -1,7 +1,6 @@ package se.ajpanton.statusbartweak.runtime.render; import android.content.Context; -import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; @@ -14,7 +13,6 @@ import android.graphics.RectF; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; -import android.os.BatteryManager; import android.text.TextUtils; import android.os.SystemClock; import android.view.View; @@ -40,7 +38,7 @@ import se.ajpanton.statusbartweak.runtime.RuntimeMutationGuard; 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.runtime.settings.BroadcastReceiverSupport; +import se.ajpanton.statusbartweak.runtime.settings.BatteryState; final class SnapshotRenderer { private static final long TRANSITION_SIGNAL_HOLD_MS = 700L; @@ -409,19 +407,21 @@ final class SnapshotRenderer { && (source.mode() == SnapshotMode.VIEW || source.mode() == SnapshotMode.STATUS_CHIP); } - private Bounds bitmapContentBounds(Bitmap bitmap) { + static Bounds bitmapContentBounds(Bitmap bitmap) { if (bitmap == null || bitmap.isRecycled()) { return null; } int width = bitmap.getWidth(); int height = bitmap.getHeight(); + int[] pixels = new int[width * height]; + bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int left = width; int top = height; int right = -1; int bottom = -1; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { - if (Color.alpha(bitmap.getPixel(x, y)) == 0) { + if (Color.alpha(pixels[y * width + x]) == 0) { continue; } left = Math.min(left, x); @@ -793,6 +793,7 @@ final class SnapshotRenderer { } int oldVisibility = sourceView.getVisibility(); float oldAlpha = sourceView.getAlpha(); + RuntimeMutationGuard.enterSnapshotRenderMutation(); try { // StatusBarIconView may be mid-transition while its drawable is valid. if (source.mode() == SnapshotMode.VIEW @@ -812,20 +813,14 @@ final class SnapshotRenderer { bitmap.getHeight())) { return; } - RuntimeMutationGuard.enterSnapshotRenderMutation(); - try { - sourceView.setVisibility(View.VISIBLE); - sourceView.setAlpha(1f); - if (source.mode() == SnapshotMode.STATUS_CHIP) { - drawTemporarilySizedView(sourceView, canvas, bitmap.getWidth(), bitmap.getHeight()); - } else { - sourceView.draw(canvas); - } - } finally { - RuntimeMutationGuard.exitSnapshotRenderMutation(); + sourceView.setVisibility(View.VISIBLE); + sourceView.setAlpha(1f); + if (source.mode() == SnapshotMode.STATUS_CHIP) { + drawTemporarilySizedView(sourceView, canvas, bitmap.getWidth(), bitmap.getHeight()); + } else { + sourceView.draw(canvas); } } finally { - RuntimeMutationGuard.enterSnapshotRenderMutation(); try { sourceView.setAlpha(oldAlpha); sourceView.setVisibility(oldVisibility); @@ -991,26 +986,8 @@ final class SnapshotRenderer { if (parsed >= 0) { return parsed; } - Integer stickyLevel = stickyBatteryLevel(source != null ? source.getContext() : null); - return stickyLevel != null ? stickyLevel : 100; - } - - private Integer stickyBatteryLevel(Context context) { - if (context == null) { - return null; - } - Intent intent = BroadcastReceiverSupport.readExportedSticky( - context, - BroadcastReceiverSupport.filter(Intent.ACTION_BATTERY_CHANGED)); - if (intent == null) { - return null; - } - int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); - int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); - if (level < 0 || scale <= 0) { - return null; - } - return Math.max(0, Math.min(100, Math.round(level * 100f / scale))); + int level = source != null ? BatteryState.get(source.getContext()).level() : -1; + return level >= 0 ? Math.min(100, level) : 100; } private CharSequence findChargingBatteryText(View source) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/TextViewStyleSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/TextViewStyleSupport.java new file mode 100644 index 0000000..af9c1fd --- /dev/null +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/TextViewStyleSupport.java @@ -0,0 +1,76 @@ +package se.ajpanton.statusbartweak.runtime.render; + +import android.widget.TextView; + +import java.util.Objects; + +/** Shared single-row text styling for layout proxies and native clock overlays. */ +public final class TextViewStyleSupport { + private TextViewStyleSupport() { + } + + public static boolean copyIfChanged(TextView source, TextView target) { + return copyIfChanged(source, target, 0f, 0); + } + + public static boolean copyIfChanged(TextView source, TextView target, float textSizePx, int colorOverride) { + boolean changed = false; + int desiredColor = (colorOverride >>> 24) != 0 ? colorOverride : source.getCurrentTextColor(); + if (target.getCurrentTextColor() != desiredColor) { + target.setTextColor(desiredColor); + changed = true; + } + float desiredTextSize = textSizePx > 0f ? textSizePx : source.getTextSize(); + if (target.getTextSize() != desiredTextSize) { + target.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, desiredTextSize); + changed = true; + } + if (!Objects.equals(target.getTypeface(), source.getTypeface())) { + target.setTypeface(source.getTypeface()); + changed = true; + } + if (target.getGravity() != source.getGravity()) { + target.setGravity(source.getGravity()); + changed = true; + } + if (target.getIncludeFontPadding() != source.getIncludeFontPadding()) { + target.setIncludeFontPadding(source.getIncludeFontPadding()); + changed = true; + } + if (target.getMaxLines() != 1) { + target.setSingleLine(true); + target.setMaxLines(1); + changed = true; + } + if (!target.isHorizontallyScrollable()) { + target.setHorizontallyScrolling(true); + changed = true; + } + if (target instanceof ClockOutlineTextView outlineTarget) { + changed |= outlineTarget.setSourcePadding( + source.getPaddingLeft(), + source.getPaddingTop(), + source.getPaddingRight(), + source.getPaddingBottom()); + } else if (target.getPaddingLeft() != source.getPaddingLeft() + || target.getPaddingTop() != source.getPaddingTop() + || target.getPaddingRight() != source.getPaddingRight() + || target.getPaddingBottom() != source.getPaddingBottom()) { + target.setPadding( + source.getPaddingLeft(), + source.getPaddingTop(), + source.getPaddingRight(), + source.getPaddingBottom()); + changed = true; + } + if (target.getLetterSpacing() != source.getLetterSpacing()) { + target.setLetterSpacing(source.getLetterSpacing()); + changed = true; + } + if (!Objects.equals(target.getFontFeatureSettings(), source.getFontFeatureSettings())) { + target.setFontFeatureSettings(source.getFontFeatureSettings()); + changed = true; + } + return changed; + } +} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedChipPlacementController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedChipPlacementController.java index 0f91e27..f2f0ef1 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedChipPlacementController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedChipPlacementController.java @@ -40,7 +40,6 @@ final class UnlockedChipPlacementController { ArrayList rawPlacements = renderer.rawPlacements( root, withNaturalChipBounds(root, visibleSources)); - rawPlacements = withVisualChipCollision(rawPlacements); if (!rawPlacements.isEmpty()) { rememberMetrics(root, rawPlacements); heldPlacements = new ChipHoldState( @@ -61,45 +60,6 @@ final class UnlockedChipPlacementController { return placements; } - private ArrayList withVisualChipCollision(ArrayList placements) { - if (placements == null || placements.isEmpty()) { - return placements; - } - ArrayList result = null; - for (int i = 0; i < placements.size(); i++) { - SnapshotPlacement placement = placements.get(i); - if (placement == null - || placement.source == null - || placement.source.mode() != SnapshotMode.STATUS_CHIP - || placement.contentBounds == null - || placement.bounds == null) { - continue; - } - Bounds visualCollision = new Bounds( - placement.contentBounds.left, - placement.contentBounds.top, - placement.contentBounds.width, - placement.contentBounds.height); - if (visualCollision.equals(placement.contentBounds)) { - continue; - } - if (result == null) { - result = new ArrayList<>(placements); - } - result.set(i, new SnapshotPlacement( - placement.source, - placement.bounds, - placement.key, - placement.signal, - placement.overflowDot, - placement.overflowDotColor, - placement.heldSignal, - visualCollision, - placement.sourceOffsetX)); - } - return result != null ? result : placements; - } - private ArrayList withNaturalChipBounds( View root, ArrayList sources diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedIconSnapshotRenderController.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedIconSnapshotRenderController.java index c820b9f..6ec5676 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedIconSnapshotRenderController.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/render/UnlockedIconSnapshotRenderController.java @@ -71,9 +71,7 @@ public final class UnlockedIconSnapshotRenderController { boolean forceStockRefresh, TextView externalCarrierView ) { - if (scene == null - || (!scene.isUnlocked() && !scene.isLockscreen() && !scene.isAod()) - || !root.isAttachedToWindow()) { + if (scene == null || !root.isAttachedToWindow()) { clearAll(); return new RenderResult(true, true, true); } @@ -119,19 +117,11 @@ public final class UnlockedIconSnapshotRenderController { boolean chipSourcesChanged = previousSignature == null || signature.chipSources != previousSignature.chipSources; if (signature.equals(previousSignature) && !forceChipRefresh) { - LayoutPlan cachedPlan = lastLayoutPlanByRoot.get(root); return new RenderResult( false, false, false, - !scene.isLockscreen() || lastLayoutPlanByRoot.get(root) != null, - lockscreenIconDebugSummary( - root, - notificationHost, - scene, - cachedPlan, - lastCollectedIconsByRoot.get(root), - "cacheHit")); + !scene.isLockscreen() || lastLayoutPlanByRoot.get(root) != null); } lastLayoutSignatureByRoot.put(root, signature); Integer currentClockSourceGeometry = clockSourceGeometrySignature( @@ -213,14 +203,7 @@ public final class UnlockedIconSnapshotRenderController { false, stockSourcesChanged, chipSourcesChanged, - false, - lockscreenIconDebugSummary( - root, - notificationHost, - scene, - null, - collectedIcons, - "missingClock")); + false); } LayoutPlan layoutPlan = layoutPlanner.solve( root, @@ -271,14 +254,7 @@ public final class UnlockedIconSnapshotRenderController { true, stockSourcesChanged, chipSourcesChanged, - true, - lockscreenIconDebugSummary( - root, - notificationHost, - scene, - layoutPlan, - collectedIcons, - "solved")); + true); } public void refreshUnlockedAppearance( @@ -370,6 +346,8 @@ public final class UnlockedIconSnapshotRenderController { if (!clockEnabledForScene(settings, scene)) { return false; } + // Request the frame before formatting so styled text does not delay its vsync request. + clockHost.invalidate(); CollectedIcons collectedIcons = lastCollectedIconsByRoot.get(root); int referenceColor = clockReferenceColor(layoutPlan.clockPlacement, collectedIcons); ClockPlacement updatedClock = clockPlacementWithTextFromModel( @@ -1162,127 +1140,14 @@ public final class UnlockedIconSnapshotRenderController { return result; } - private String lockscreenIconDebugSummary( - View root, - ViewGroup notificationHost, - SceneKey scene, - LayoutPlan plan, - CollectedIcons icons, - String phase - ) { - if (scene == null - || !scene.isLockscreen() - || scene.notificationDisplayStyle() != NotificationDisplayStyle.ICONS) { - return null; - } - ArrayList notificationPlacements = - plan != null ? plan.notificationPlacements : null; - return "phase=" + phase - + " root=" + viewBounds(root) - + " hostChildren=" + (notificationHost != null ? notificationHost.getChildCount() : -1) - + " sourceNotifs=" + sizeOf(icons != null ? icons.notificationIcons : null) - + " placementCount=" + sizeOf(notificationPlacements) - + " renderableCount=" + renderablePlacementCount(notificationPlacements) - + " clock=" + boundsText(plan != null && plan.clockPlacement != null - ? plan.clockPlacement.bounds - : null) - + " carrier=" + boundsText(plan != null && plan.carrierPlacement != null - ? plan.carrierPlacement.bounds - : null) - + " notifs=" + placementSummary(notificationPlacements); - } - - private int sizeOf(ArrayList values) { - return values != null ? values.size() : 0; - } - - private int renderablePlacementCount(ArrayList placements) { - if (placements == null) { - return 0; - } - int count = 0; - for (SnapshotPlacement placement : placements) { - if (isRenderablePlacement(placement)) { - count++; - } - } - return count; - } - - private boolean isRenderablePlacement(SnapshotPlacement placement) { - return placement != null - && (placement.source != null - || placement.overflowDot - || placement.heldSignal != null); - } - - private String placementSummary(ArrayList placements) { - if (placements == null || placements.isEmpty()) { - return "[]"; - } - StringBuilder out = new StringBuilder("["); - int limit = Math.min(placements.size(), 8); - for (int i = 0; i < limit; i++) { - if (i > 0) { - out.append(';'); - } - SnapshotPlacement placement = placements.get(i); - out.append(i).append('{'); - if (placement == null) { - out.append("null"); - } else { - out.append("key=").append(placement.key) - .append(",b=").append(boundsText(placement.bounds)) - .append(",source=").append(placement.source != null) - .append(",dot=").append(placement.overflowDot) - .append(",held=").append(placement.heldSignal != null) - .append(",renderable=").append(isRenderablePlacement(placement)); - } - out.append('}'); - } - if (placements.size() > limit) { - out.append(";..."); - } - out.append(']'); - return out.toString(); - } - - private String viewBounds(View view) { - if (view == null) { - return "null"; - } - return view.getWidth() + "x" + view.getHeight() - + "+" + view.getLeft() - + "," + view.getTop(); - } - - private String boundsText(Bounds bounds) { - if (bounds == null) { - return "null"; - } - return bounds.width + "x" + bounds.height - + "+" + bounds.left - + "," + bounds.top; - } - public record RenderResult( boolean layoutChanged, boolean stockSourcesChanged, boolean chipSourcesChanged, - boolean shouldOwnLockscreen, - String debugSummary + boolean shouldOwnLockscreen ) { public RenderResult(boolean layoutChanged, boolean stockSourcesChanged, boolean chipSourcesChanged) { - this(layoutChanged, stockSourcesChanged, chipSourcesChanged, true, null); - } - - public RenderResult( - boolean layoutChanged, - boolean stockSourcesChanged, - boolean chipSourcesChanged, - boolean shouldOwnLockscreen - ) { - this(layoutChanged, stockSourcesChanged, chipSourcesChanged, shouldOwnLockscreen, null); + this(layoutChanged, stockSourcesChanged, chipSourcesChanged, true); } } 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 2cbf3fe..512ddff 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 @@ -1,10 +1,8 @@ package se.ajpanton.statusbartweak.runtime.render; import android.content.Context; -import android.content.Intent; import android.graphics.Rect; import android.graphics.drawable.Drawable; -import android.os.BatteryManager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; @@ -27,7 +25,7 @@ import se.ajpanton.statusbartweak.runtime.mode.NotificationDisplayStyle; import se.ajpanton.statusbartweak.runtime.mode.SceneKey; import se.ajpanton.statusbartweak.runtime.notifications.NotificationActiveKeyStore; import se.ajpanton.statusbartweak.runtime.notifications.NotificationUnreadTracker; -import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport; +import se.ajpanton.statusbartweak.runtime.settings.BatteryState; import se.ajpanton.statusbartweak.shell.settings.SbtDefaults; import se.ajpanton.statusbartweak.shell.settings.SbtSettings; @@ -1014,23 +1012,7 @@ final class UnlockedStockSourceCollector { } private boolean isDevicePlugged(Context context) { - Intent intent = batteryIntent(context); - if (intent == null) { - return false; - } - int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); - return intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 - || status == BatteryManager.BATTERY_STATUS_CHARGING - || status == BatteryManager.BATTERY_STATUS_FULL; - } - - private Intent batteryIntent(Context context) { - if (context == null) { - return null; - } - return BroadcastReceiverSupport.readExportedSticky( - context, - BroadcastReceiverSupport.filter(Intent.ACTION_BATTERY_CHANGED)); + return context != null && BatteryState.get(context).charging(); } private void append(StringBuilder sb, String value) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BatteryState.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BatteryState.java new file mode 100644 index 0000000..c74f963 --- /dev/null +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BatteryState.java @@ -0,0 +1,66 @@ +package se.ajpanton.statusbartweak.runtime.settings; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.BatteryManager; + +import java.util.concurrent.CopyOnWriteArrayList; + +/** Process-local battery snapshot, updated by broadcasts rather than rendering-time IPC. */ +public record BatteryState(int level, boolean charging) { + private static volatile BatteryState current; + private static final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); + + public static BatteryState get(Context context) { + if (current == null) { + initialize(context); + } + return current; + } + + public static void addListener(Context context, Runnable listener) { + get(context); + listeners.add(listener); + } + + private static synchronized void initialize(Context context) { + if (current != null) { + return; + } + Intent sticky = BroadcastReceiverSupport.registerExportedOnApplicationContext( + context, + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + BatteryState updated = fromIntent(intent); + BatteryState previous = current; + current = updated; + if (!updated.equals(previous)) { + for (Runnable listener : listeners) { + listener.run(); + } + } + } + }, + BroadcastReceiverSupport.filter(Intent.ACTION_BATTERY_CHANGED)); + if (sticky != null) { + current = fromIntent(sticky); + } else { + BatteryManager manager = context.getSystemService(BatteryManager.class); + current = new BatteryState(manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY), + manager.isCharging()); + } + } + + private static BatteryState fromIntent(Intent intent) { + int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); + int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); + int percent = level >= 0 && scale > 0 ? Math.round(level * 100f / scale) : -1; + int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); + return new BatteryState(percent, + intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 + || status == BatteryManager.BATTERY_STATUS_CHARGING + || status == BatteryManager.BATTERY_STATUS_FULL); + } +} diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BroadcastReceiverSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BroadcastReceiverSupport.java index 1644802..fe47561 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BroadcastReceiverSupport.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/BroadcastReceiverSupport.java @@ -46,11 +46,6 @@ public final class BroadcastReceiverSupport { return registerExportedOnApplicationContext(context, receiver, filter); } - public static Intent readExportedSticky(Context context, IntentFilter filter) { - return applicationContext(context) - .registerReceiver(null, filter, Context.RECEIVER_EXPORTED); - } - private static Context applicationContext(Context context) { Context appContext = context.getApplicationContext(); return appContext != null ? appContext : context; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/RuntimeSettingsCache.java b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/RuntimeSettingsCache.java index 1596ede..c011a50 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/RuntimeSettingsCache.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/runtime/settings/RuntimeSettingsCache.java @@ -16,7 +16,7 @@ public final class RuntimeSettingsCache { private static final Object LOCK = new Object(); - private static SbtSettings cachedSettings; + private static volatile SbtSettings cachedSettings; private static boolean receiverRegistered; private RuntimeSettingsCache() { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/BatteryBarStyle.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/BatteryBarStyle.java index 2f4d0f3..024949f 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/BatteryBarStyle.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/BatteryBarStyle.java @@ -1,19 +1,17 @@ package se.ajpanton.statusbartweak.shell.settings; import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; import android.content.SharedPreferences; -import android.graphics.Color; import android.net.Uri; -import android.os.BatteryManager; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; -import java.util.Locale; + +import se.ajpanton.statusbartweak.runtime.settings.BatteryState; +import se.ajpanton.statusbartweak.runtime.settings.RuntimeSettingsCache; public final class BatteryBarStyle { public static final String THRESHOLD_CHARGE_USE_DEFAULT = "@default_charge"; @@ -36,10 +34,6 @@ public final class BatteryBarStyle { return ColourExpressionSupport.normaliseExpression(raw, true); } - public static int parseColorOrDefault(String raw, int fallback) { - return ColourExpressionSupport.resolveColor(raw, fallback, fallback, true); - } - public static String normalizeThresholdChargeColor(String raw) { if (raw == null) { return ""; @@ -58,21 +52,6 @@ public final class BatteryBarStyle { return THRESHOLD_CHARGE_USE_DEFAULT.equals(raw); } - public static String resolveCurrentColorHex(Context context, String fallbackRaw) { - int fallback = parseColorOrDefault(fallbackRaw, Color.WHITE); - return resolveCurrentColorHex(context, fallback, fallbackRaw); - } - - public static String resolveCurrentColorHex(Context context, int referenceColor, String fallbackRaw) { - int fallback = parseColorOrDefault(fallbackRaw, Color.WHITE); - int resolved = resolveCurrentColor(context, referenceColor, fallback); - int alpha = Color.alpha(resolved); - if (alpha >= 255) { - return String.format(Locale.ROOT, "#%06X", resolved & 0xFFFFFF); - } - return String.format(Locale.ROOT, "#%08X", resolved); - } - public static ArrayList decodeThresholds(Collection encoded) { ArrayList result = new ArrayList<>(); if (encoded == null) { @@ -179,19 +158,17 @@ public final class BatteryBarStyle { return fallback; } - public static int resolveCurrentColor(Context context, int fallback) { - return resolveCurrentColor(context, fallback, fallback); - } - public static int resolveCurrentColor(Context context, int referenceColor, int fallback) { if (context == null) { return fallback; } - SbtSettings settings = SbtSettings.from(context); - BatterySnapshot snapshot = resolveBatterySnapshot(context); + SbtSettings settings = SbtSettings.MODULE_PACKAGE.equals(context.getPackageName()) + ? SbtSettings.from(context) + : RuntimeSettingsCache.get(context); + BatteryState snapshot = BatteryState.get(context); return resolveColor( - snapshot.level, - snapshot.charging, + snapshot.level(), + snapshot.charging(), settings.batteryBarDefaultDischargeColor, settings.batteryBarDefaultChargeColor, settings.batteryBarThresholds, @@ -199,43 +176,6 @@ public final class BatteryBarStyle { fallback); } - private static BatterySnapshot resolveBatterySnapshot(Context context) { - IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); - Intent sticky = null; - try { - sticky = context.registerReceiver(null, filter, Context.RECEIVER_EXPORTED); - } catch (Throwable ignored) { - } - if (sticky != null) { - int level = sticky.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); - int scale = sticky.getIntExtra(BatteryManager.EXTRA_SCALE, 100); - int percent = (level >= 0 && scale > 0) - ? Math.round((level * 100f) / scale) - : -1; - int status = sticky.getIntExtra(BatteryManager.EXTRA_STATUS, -1); - boolean charging = sticky.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 - || status == BatteryManager.BATTERY_STATUS_CHARGING - || status == BatteryManager.BATTERY_STATUS_FULL; - return new BatterySnapshot(percent, charging); - } - BatteryManager batteryManager = context.getSystemService(BatteryManager.class); - int level = batteryManager != null - ? batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) - : -1; - boolean charging = batteryManager != null && batteryManager.isCharging(); - return new BatterySnapshot(level, charging); - } - - private static final class BatterySnapshot { - final int level; - final boolean charging; - - BatterySnapshot(int level, boolean charging) { - this.level = level; - this.charging = charging; - } - } - public static int clampPercent(int percent) { if (percent < 1) { return 1; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/ClockCameraTypeSupport.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/ClockCameraTypeSupport.java index 4e0201b..a3014d0 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/ClockCameraTypeSupport.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/settings/ClockCameraTypeSupport.java @@ -194,20 +194,6 @@ public final class ClockCameraTypeSupport { prefs.edit().putStringSet(key, encodeOverrides(overrides)).apply(); } - public static String findReportValue(String report, String key) { - if (TextUtils.isEmpty(report) || TextUtils.isEmpty(key)) { - return ""; - } - String prefix = key + "="; - String[] lines = report.split("\\r?\\n"); - for (String line : lines) { - if (line != null && line.startsWith(prefix)) { - return line.substring(prefix.length()).trim(); - } - } - return ""; - } - private static void finalizeCameraInfo(CameraInfo info, SbtSettings settings) { if (info == null) { return; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BatteryBarFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BatteryBarFragment.java index e373eaf..59a58df 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BatteryBarFragment.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/BatteryBarFragment.java @@ -1604,18 +1604,6 @@ public final class BatteryBarFragment extends Fragment { return "top"; } - private String batteryBarPositionLabel(BatteryBarGeometry geometry) { - if (geometry != null && "bottom".equals(geometry.position)) { - return getString(R.string.battery_bar_position_bottom); - } - if (geometry != null - && SbtSettings.BATTERY_BAR_CURVED_GEOMETRY_LENGTH.equals( - geometry.curvedGeometryMode)) { - return getString(R.string.battery_bar_curved_geometry_length); - } - return getString(R.string.battery_bar_position_top); - } - private String curvedGeometryValue(int checkedId) { if (checkedId == R.id.battery_bar_curved_geometry_length) { return SbtSettings.BATTERY_BAR_CURVED_GEOMETRY_LENGTH; diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/ClockFragment.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/ClockFragment.java index 5908a7f..83a7353 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/ClockFragment.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/ClockFragment.java @@ -36,6 +36,8 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; +import androidx.lifecycle.Lifecycle; +import androidx.lifecycle.LifecycleEventObserver; import com.google.android.material.button.MaterialButton; import com.google.android.material.card.MaterialCardView; @@ -944,7 +946,7 @@ public final class ClockFragment extends Fragment { @Override public void run() { adapter.notifyDataSetChanged(); - listView.postDelayed(this, 1000L); + listView.postDelayed(this, nextSecondDelayMillis()); } }; @@ -953,8 +955,20 @@ public final class ClockFragment extends Fragment { .setView(container) .setNegativeButton(android.R.string.cancel, null) .show(); - listView.post(refreshSamples); - dialog.setOnDismissListener(d -> listView.removeCallbacks(refreshSamples)); + Lifecycle lifecycle = getViewLifecycleOwner().getLifecycle(); + LifecycleEventObserver observer = (owner, event) -> { + listView.removeCallbacks(refreshSamples); + if (event == Lifecycle.Event.ON_RESUME) { + listView.post(refreshSamples); + } else if (event == Lifecycle.Event.ON_DESTROY) { + dialog.dismiss(); + } + }; + dialog.setOnDismissListener(d -> { + listView.removeCallbacks(refreshSamples); + lifecycle.removeObserver(observer); + }); + lifecycle.addObserver(observer); } private void applyFontFilter(FontFamilyAdapter adapter, List allFamilies, String query) { diff --git a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/MainActivity.java b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/MainActivity.java index 580742c..35db2f4 100644 --- a/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/MainActivity.java +++ b/app/src/main/java/se/ajpanton/statusbartweak/shell/ui/MainActivity.java @@ -1,6 +1,5 @@ package se.ajpanton.statusbartweak.shell.ui; -import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; @@ -40,13 +39,6 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On private boolean permanentSidebar; private int currentItemId = R.id.nav_layout; - public static Intent newOpenDebugIntent(Context context) { - Intent intent = new Intent(context, MainActivity.class); - intent.putExtra(EXTRA_OPEN_NAV_ITEM, R.id.nav_icons_debug); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); - return intent; - } - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -316,14 +308,11 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On } drawerToggle.syncState(); } - if (permanentSidebar) { - drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.START); - drawerNavigationView.setVisibility(View.GONE); - } else { - drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.START); - drawerNavigationView.setVisibility(View.VISIBLE); - drawerNavigationView.requestLayout(); + int lockMode = permanentSidebar ? DrawerLayout.LOCK_MODE_LOCKED_CLOSED : DrawerLayout.LOCK_MODE_UNLOCKED; + if (drawerLayout.getDrawerLockMode(GravityCompat.START) != lockMode) { + drawerLayout.setDrawerLockMode(lockMode, GravityCompat.START); } + drawerNavigationView.setVisibility(permanentSidebar ? View.GONE : View.VISIBLE); updateNavigationHeaderHeight(drawerNavigationView); updateNavigationHeaderHeight(permanentNavigationView); applyPageTitleVisibility(); diff --git a/app/src/main/resources/META-INF/xposed/scope.list b/app/src/main/resources/META-INF/xposed/scope.list index bae17ab..fb7c8c8 100644 --- a/app/src/main/resources/META-INF/xposed/scope.list +++ b/app/src/main/resources/META-INF/xposed/scope.list @@ -1,4 +1 @@ -android -system com.android.systemui -com.samsung.android.app.aodservice diff --git a/app/src/test/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuardTest.java b/app/src/test/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuardTest.java new file mode 100644 index 0000000..ba4746a --- /dev/null +++ b/app/src/test/java/se/ajpanton/statusbartweak/runtime/RuntimeMutationGuardTest.java @@ -0,0 +1,26 @@ +package se.ajpanton.statusbartweak.runtime; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public final class RuntimeMutationGuardTest { + @Test + public void nestedSnapshotsKeepTheGuardUntilTheOuterSnapshotEnds() { + assertFalse(RuntimeMutationGuard.isSnapshotRenderMutation()); + RuntimeMutationGuard.enterSnapshotRenderMutation(); + try { + RuntimeMutationGuard.enterSnapshotRenderMutation(); + try { + assertTrue(RuntimeMutationGuard.isSnapshotRenderMutation()); + } finally { + RuntimeMutationGuard.exitSnapshotRenderMutation(); + } + assertTrue(RuntimeMutationGuard.isSnapshotRenderMutation()); + } finally { + RuntimeMutationGuard.exitSnapshotRenderMutation(); + } + assertFalse(RuntimeMutationGuard.isSnapshotRenderMutation()); + } +} diff --git a/app/src/test/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParserTest.java b/app/src/test/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParserTest.java index fd2d328..b8c7221 100644 --- a/app/src/test/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParserTest.java +++ b/app/src/test/java/se/ajpanton/statusbartweak/runtime/features/clock/ClockPatternParserTest.java @@ -1,12 +1,24 @@ package se.ajpanton.statusbartweak.runtime.features.clock; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import org.junit.Test; public final class ClockPatternParserTest { private final ClockPatternParser parser = new ClockPatternParser(); + @Test + public void secondsDetectionIgnoresMarkupAndQuotedLiterals() { + assertFalse(ClockMarkupSupport.containsSecondsPattern("{@sans-serif-condensed-light}H:mm 'seconds'")); + assertFalse(parser.parse("H:mm").containsSeconds); + assertTrue(ClockMarkupSupport.containsSecondsPattern("{@sans-serif-condensed-light}H:mm:ss")); + assertTrue(parser.parse("H:mm 'it''s' ss").containsSeconds); + } + @Test public void lineBreakBlockAcceptsFollowingShorthandTags() { ClockParsedPattern combined = parser.parse("HH{\\n30 big}mm"); @@ -18,4 +30,16 @@ public final class ClockPatternParserTest { assertEquals(30, combined.rows.get(1).gapBeforePx); assertEquals(split.rows.get(1).markup, combined.rows.get(1).markup); } + + @Test + public void immutablePatternsAreReusedAndOldEntriesAreEvicted() { + ClockParsedPattern first = parser.parse("H:mm:ss"); + assertSame(first, parser.parse("H:mm:ss")); + for (int i = 0; i < 16; i++) { + parser.parse("H:mm '" + i + "'"); + } + assertNotSame(first, parser.parse("H:mm:ss")); + assertEquals(1, first.rows.size()); + assertTrue(first.containsSeconds); + } } diff --git a/app/src/test/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupportTest.java b/app/src/test/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupportTest.java new file mode 100644 index 0000000..f25e1e0 --- /dev/null +++ b/app/src/test/java/se/ajpanton/statusbartweak/runtime/hooks/ReflectionSupportTest.java @@ -0,0 +1,49 @@ +package se.ajpanton.statusbartweak.runtime.hooks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; + +import org.junit.Test; + +public final class ReflectionSupportTest { + @Test + public void inheritedFieldsCacheMembersNotValues() { + Child first = new Child(); + Child second = new Child(); + assertEquals(1, ReflectionSupport.getFieldValue(first, "value")); + ReflectionSupport.setFieldValue(first, "value", 7); + assertEquals(7, ReflectionSupport.requireFieldValue(first, "value")); + assertEquals(1, ReflectionSupport.getFieldValue(second, "value")); + assertEquals(2, ReflectionSupport.getFieldValue(new Other(), "value")); + } + + @Test + public void methodsRemainLiveAndOverloadsRemainDistinct() { + Child child = new Child(); + assertEquals(1, ReflectionSupport.invokeMethod(child, "read")); + ReflectionSupport.setFieldValue(child, "value", 9); + assertEquals(9, ReflectionSupport.invokeMethod(child, "read")); + assertEquals(12, ReflectionSupport.invokeMethod(child, "read", new Class[]{int.class}, 3)); + } + + @Test + public void optionalMissesDoNotChangeRequiredLookupErrors() { + Child child = new Child(); + for (int i = 0; i < 2; i++) { + assertNull(ReflectionSupport.getFieldValue(child, "absent")); + assertNull(ReflectionSupport.invokeMethod(child, "absent")); + assertThrows(IllegalStateException.class, + () -> ReflectionSupport.requireFieldValue(child, "absent")); + } + } + + private static class Parent { + private int value = 1; + private int read() { return value; } + private int read(int add) { return value + add; } + } + + private static final class Child extends Parent {} + private static final class Other { private int value = 2; } +} diff --git a/app/src/test/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsTest.java b/app/src/test/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsTest.java index 8dab261..0f7b2f4 100644 --- a/app/src/test/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsTest.java +++ b/app/src/test/java/se/ajpanton/statusbartweak/shell/settings/SbtSettingsTest.java @@ -2,6 +2,7 @@ package se.ajpanton.statusbartweak.shell.settings; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -11,7 +12,21 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +import se.ajpanton.statusbartweak.runtime.features.clock.ClockLayoutTextFactory; + public final class SbtSettingsTest { + @Test + public void customClockPatternControlsWhetherSecondsAreNeeded() { + MapSource source = new MapSource(); + source.put(SbtSettings.KEY_CLOCK_SHOW_SECONDS, true); + assertTrue(ClockLayoutTextFactory.usesSeconds(SbtSettings.fromSource(source))); + source.put(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT_ENABLED, true); + source.put(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT, "{@sans-serif}H:mm 'seconds'"); + assertFalse(ClockLayoutTextFactory.usesSeconds(SbtSettings.fromSource(source))); + source.put(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT, "H:mm:ss"); + assertTrue(ClockLayoutTextFactory.usesSeconds(SbtSettings.fromSource(source))); + } + @Test public void emptySourceMatchesRepresentativeDefaults() { SbtSettings defaults = SbtSettings.defaults();