10 Commits
43 changed files with 2340 additions and 496 deletions
@@ -1,5 +1,6 @@
package se.ajpanton.statusbartweak.runtime.features.battery;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -154,8 +155,17 @@ final class BatteryBarController {
return result;
});
XposedHookSupport.hookAllMethodsIfExists(framework, View.class, "setAlpha", chain -> {
Object result = chain.proceed();
Object target = chain.getThisObject();
Object alphaArg = chain.getArgs() != null && !chain.getArgs().isEmpty()
? chain.getArgs().get(0)
: null;
if (target instanceof View root
&& alphaArg instanceof Float alpha
&& roots.contains(root)
&& shouldBlockChargingChipRootAlpha(root, alpha)) {
return null;
}
Object result = chain.proceed();
if (target instanceof View root && roots.contains(root)) {
applyBatteryBarAfterRootTransform(root);
}
@@ -271,6 +281,7 @@ final class BatteryBarController {
}
int result = 17;
result = 31 * result + root.getVisibility();
result = 31 * result + Float.floatToIntBits(root.getAlpha());
result = 31 * result + Float.floatToIntBits(root.getY());
result = 31 * result + Float.floatToIntBits(root.getTranslationY());
result = 31 * result + root.getWidth();
@@ -378,12 +389,13 @@ final class BatteryBarController {
return;
}
int color = resolveBarColor(root, settings);
BatteryBarGeometry.Scenario scenario = scenarioForRoot(root);
if (!shouldRenderOnRoot(root)) {
removeBatteryBarView(root);
return;
}
BatteryBarGeometry.Scenario scenario = scenarioForRoot(root);
boolean transientStatusBarReveal = isFullscreenScenario(scenario)
&& !isLockedPhoneStatusBarRoot(root)
&& shouldRenderVisibleFullscreenBar(root);
if (transientStatusBarReveal) {
scenario = visibleStatusBarScenarioForRoot(root);
@@ -547,7 +559,7 @@ final class BatteryBarController {
return BatteryBarGeometry.Scenario.LOCKSCREEN;
}
boolean fullscreen = isPhoneRoot(root)
&& isUnlockedScene()
&& (isUnlockedScene() || isLockedPhoneFullscreenRoot(root))
&& (isStatusBarSurfaceHidden(root) || isFullscreenSystemBarState());
boolean landscape = isLandscapeForRoot(root, fullscreen);
if (fullscreen) {
@@ -588,11 +600,22 @@ final class BatteryBarController {
return scene == null || !scene.isUnlocked();
}
if (isPhoneRoot(root)) {
return scene == null || scene.isUnlocked();
if (isLockedPhoneStatusBarRoot(root)) {
return isLockedPhoneFullscreenRoot(root);
}
return scene == null || scene.isUnlocked() || isLockedPhoneFullscreenRoot(root);
}
return true;
}
private boolean shouldBlockChargingChipRootAlpha(View root, float alpha) {
return alpha < 0.99f
&& isPhoneRoot(root)
&& isUnlockedScene()
&& !isFullscreenSystemBarState()
&& hasSamsungBatteryStatusChip(root);
}
private boolean isUnlockedScene() {
SceneKey scene = runtimeContext.getModeStateRepository().getActiveScene();
return scene == null || scene.isUnlocked();
@@ -606,6 +629,23 @@ final class BatteryBarController {
return root != null && root.getClass().getName().contains("KeyguardStatusBarView");
}
private boolean isLockedPhoneStatusBarRoot(View root) {
return isPhoneRoot(root) && isKeyguardLocked(root.getContext());
}
private boolean isLockedPhoneFullscreenRoot(View root) {
return isLockedPhoneStatusBarRoot(root)
&& (isStatusBarSurfaceHidden(root) || isFullscreenSystemBarState());
}
private boolean isKeyguardLocked(Context context) {
if (context == null) {
return false;
}
KeyguardManager keyguardManager = context.getSystemService(KeyguardManager.class);
return keyguardManager != null && keyguardManager.isKeyguardLocked();
}
private boolean isHiddenKeyguardRoot(View root) {
return isKeyguardRoot(root) && !root.isShown();
}
@@ -758,6 +798,32 @@ final class BatteryBarController {
return bottom <= 0f || top >= screenHeight || right <= 0f || left >= screenWidth;
}
private boolean hasSamsungBatteryStatusChip(View root) {
if (!(root != null && root.getRootView() instanceof ViewGroup rootView)) {
return false;
}
return findSamsungBatteryStatusChip(rootView) != null;
}
private View findSamsungBatteryStatusChip(View view) {
if (view == null) {
return null;
}
if (view.getClass().getName().contains("SamsungBatteryStatusChip")) {
return view;
}
if (!(view instanceof ViewGroup group)) {
return null;
}
for (int i = 0; i < group.getChildCount(); i++) {
View found = findSamsungBatteryStatusChip(group.getChildAt(i));
if (found != null) {
return found;
}
}
return null;
}
private static Integer asInteger(Object value) {
return value instanceof Integer integer ? integer : null;
}
@@ -922,6 +988,7 @@ final class BatteryBarController {
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
@@ -7,40 +7,66 @@ import java.util.Locale;
import se.ajpanton.statusbartweak.shell.settings.BatteryBarStyle;
final class ClockColorResolver {
public final class ClockColorResolver {
private static final int CHANNEL_ALPHA = 0;
private static final int CHANNEL_RED = 1;
private static final int CHANNEL_GREEN = 2;
private static final int CHANNEL_BLUE = 3;
private static final int CHANNEL_COUNT = 4;
String resolveColorHex(
public String resolveColorHex(
Context context,
String expression,
int referenceColor,
int fallbackColor
) {
int resolved = resolveColor(context, expression, referenceColor, fallbackColor);
return colorHex(resolved);
}
public String resolveColorHex(
Context context,
String expression,
int referenceColor,
int fallbackColor,
Options options
) {
int resolved = resolveColor(context, expression, referenceColor, fallbackColor, options);
return colorHex(resolved);
}
private String colorHex(int resolved) {
if (alpha(resolved) >= 255) {
return String.format(Locale.ROOT, "#%06X", resolved & 0xFFFFFF);
}
return String.format(Locale.ROOT, "#%08X", resolved);
}
int resolveColor(
public int resolveColor(
Context context,
String expression,
int referenceColor,
int fallbackColor
) {
return resolveColor(context, expression, referenceColor, fallbackColor, Options.clock());
}
public int resolveColor(
Context context,
String expression,
int referenceColor,
int fallbackColor,
Options options
) {
if (isEmpty(expression)) {
return fallbackColor;
}
Options resolvedOptions = options != null ? options : Options.clock();
VariantExpressions variants = splitVariants(expression);
Value bright = evaluateExpression(context, variants.brightExpression, null, fallbackColor);
Value bright = evaluateExpression(context, variants.brightExpression, null, fallbackColor, resolvedOptions);
Value dark = variants.darkExpression.isEmpty()
? bright
: evaluateExpression(context, variants.darkExpression, bright, fallbackColor);
: evaluateExpression(context, variants.darkExpression, bright, fallbackColor, resolvedOptions);
return toColor(isDark(referenceColor) ? dark : bright);
}
@@ -48,7 +74,8 @@ final class ClockColorResolver {
Context context,
String expression,
Value inherited,
int fallbackColor
int fallbackColor,
Options options
) {
ArrayList<String> tokens = tokenize(expression);
ArrayList<Value> stack = new ArrayList<>();
@@ -56,7 +83,7 @@ final class ClockColorResolver {
stack.add(inherited.copy());
}
for (String token : tokens) {
applyToken(context, stack, token, fallbackColor);
applyToken(context, stack, token, fallbackColor, options);
}
if (stack.isEmpty()) {
throw new IllegalArgumentException("Empty colour expression");
@@ -64,7 +91,13 @@ final class ClockColorResolver {
return top(stack).copy();
}
private void applyToken(Context context, ArrayList<Value> stack, String token, int fallbackColor) {
private void applyToken(
Context context,
ArrayList<Value> stack,
String token,
int fallbackColor,
Options options
) {
if (isEmpty(token)) {
return;
}
@@ -73,7 +106,7 @@ final class ClockColorResolver {
applyOperation(stack, operation);
return;
}
stack.add(parseOperand(context, token, fallbackColor));
stack.add(parseOperand(context, token, fallbackColor, options));
}
private Operation parseOperation(String token) {
@@ -244,12 +277,15 @@ final class ClockColorResolver {
stack.add(Value.vector(result));
}
private Value parseOperand(Context context, String token, int fallbackColor) {
private Value parseOperand(Context context, String token, int fallbackColor, Options options) {
String value = token != null ? token.trim() : "";
if (value.isEmpty()) {
throw new IllegalArgumentException("Empty colour token");
}
if ("#batterybar".equalsIgnoreCase(value)) {
if (options == null || !options.allowBatteryBarOperand) {
throw new IllegalArgumentException("#batterybar is not supported here");
}
return Value.vector(vectorForColor(BatteryBarStyle.resolveCurrentColor(context, fallbackColor, fallbackColor)));
}
if (value.charAt(0) == '#') {
@@ -258,6 +294,9 @@ final class ClockColorResolver {
if (value.charAt(0) == '[') {
return Value.vector(parseVector(value));
}
if (options != null && options.allowBareHexOperand && looksLikeBareHex(value)) {
return Value.vector(vectorForColor(parseHexColor("#" + value)));
}
try {
return Value.number(Double.parseDouble(value));
} catch (NumberFormatException e) {
@@ -265,6 +304,22 @@ final class ClockColorResolver {
}
}
private boolean looksLikeBareHex(String value) {
int length = value != null ? value.length() : 0;
if (length != 3 && length != 4 && length != 6 && length != 8) {
return false;
}
boolean hasHexLetter = false;
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
if (!isHexDigit(c)) {
return false;
}
hasHexLetter |= (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
return length != 3 || hasHexLetter;
}
private double[] parseVector(String token) {
String value = token != null ? token.trim() : "";
if (!value.startsWith("[") || !value.endsWith("]")) {
@@ -608,4 +663,22 @@ final class ClockColorResolver {
return Math.max(0d, Math.min(255d, value));
}
}
public static final class Options {
private final boolean allowBatteryBarOperand;
private final boolean allowBareHexOperand;
private Options(boolean allowBatteryBarOperand, boolean allowBareHexOperand) {
this.allowBatteryBarOperand = allowBatteryBarOperand;
this.allowBareHexOperand = allowBareHexOperand;
}
public static Options clock() {
return new Options(true, false);
}
public static Options batteryBar() {
return new Options(false, true);
}
}
}
@@ -1,7 +1,5 @@
package se.ajpanton.statusbartweak.runtime.features.clock;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -94,7 +92,7 @@ final class ClockMarkupSupport {
}
static void applyParsedTag(StringBuilder out, TagState state, ParsedTag parsedTag) {
if (TextUtils.isEmpty(parsedTag.name)) {
if (isEmpty(parsedTag.name)) {
return;
}
if (parsedTag.selfClosing) {
@@ -125,7 +123,7 @@ final class ClockMarkupSupport {
String literal,
TagCategory category
) {
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(literal)) {
if (isEmpty(name) || isEmpty(literal)) {
return;
}
if (category == TagCategory.FONT_COLOR) {
@@ -140,7 +138,7 @@ final class ClockMarkupSupport {
}
private static void closeTag(StringBuilder out, TagState state, String name) {
if (TextUtils.isEmpty(name)) {
if (isEmpty(name)) {
return;
}
String normalized = name.toLowerCase(Locale.ROOT);
@@ -187,7 +185,7 @@ final class ClockMarkupSupport {
}
static ParsedTag parseTagLiteral(String literal) {
if (TextUtils.isEmpty(literal)) {
if (isEmpty(literal)) {
return null;
}
String trimmed = literal.trim();
@@ -232,7 +230,7 @@ final class ClockMarkupSupport {
}
static List<Integer> findPipePositions(String markup) {
if (TextUtils.isEmpty(markup)) {
if (isEmpty(markup)) {
return Collections.emptyList();
}
ArrayList<Integer> positions = new ArrayList<>();
@@ -262,7 +260,7 @@ final class ClockMarkupSupport {
}
static boolean containsSecondsPattern(String pattern) {
if (TextUtils.isEmpty(pattern)) {
if (isEmpty(pattern)) {
return false;
}
boolean insideTag = false;
@@ -300,4 +298,8 @@ final class ClockMarkupSupport {
}
return false;
}
private static boolean isEmpty(CharSequence value) {
return value == null || value.length() == 0;
}
}
@@ -1,7 +1,5 @@
package se.ajpanton.statusbartweak.runtime.features.clock;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@@ -42,6 +40,13 @@ final class ClockPatternParser {
rowMarkup = new StringBuilder();
ClockMarkupSupport.appendOpenTags(rowMarkup, carriedState);
rowSyntaxError = false;
if (!isEmpty(lineBreak.trailingShorthand)) {
try {
appendShorthandBlock(rowMarkup, rowState, lineBreak.trailingShorthand);
} catch (IllegalArgumentException e) {
rowSyntaxError = true;
}
}
gapBeforePx = lineBreak.gapBeforePx;
index = lineBreak.endIndex;
continue;
@@ -111,7 +116,7 @@ final class ClockPatternParser {
}
private ClockParsedPattern.ClockParsedRow buildParsedRow(String markup, int gapBeforePx) {
if (TextUtils.isEmpty(markup)) {
if (isEmpty(markup)) {
return ClockParsedPattern.ClockParsedRow.plain("", gapBeforePx);
}
List<Integer> pipePositions = ClockMarkupSupport.findPipePositions(markup);
@@ -153,7 +158,7 @@ final class ClockPatternParser {
}
ArrayList<String> tokens = tokenizeShorthand(trimmed);
for (String token : tokens) {
if (TextUtils.isEmpty(token)) {
if (isEmpty(token)) {
continue;
}
if ("/font".equalsIgnoreCase(token)) {
@@ -260,6 +265,10 @@ final class ClockPatternParser {
&& value.endsWith(")");
}
private boolean isEmpty(CharSequence value) {
return value == null || value.length() == 0;
}
private void openClockColorTag(
StringBuilder out,
ClockMarkupSupport.TagState tagState,
@@ -281,7 +290,7 @@ final class ClockPatternParser {
private LineBreakToken tryParseLineBreak(String pattern, int index) {
if (pattern.startsWith("\\n", index)) {
return new LineBreakToken(index + 2, false, ROW_GAP_AUTO);
return new LineBreakToken(index + 2, false, ROW_GAP_AUTO, "");
}
if (pattern.charAt(index) != '{') {
return null;
@@ -296,10 +305,11 @@ final class ClockPatternParser {
resetPropagation = true;
body = body.substring(1).trim();
}
if (!body.startsWith("\\n")) {
ArrayList<String> tokens = tokenizeShorthand(body);
if (tokens.isEmpty() || !tokens.get(0).startsWith("\\n")) {
return null;
}
String gapText = body.substring(2).trim();
String gapText = tokens.get(0).substring(2).trim();
int gapBeforePx = ROW_GAP_AUTO;
if (!gapText.isEmpty()) {
try {
@@ -308,18 +318,27 @@ final class ClockPatternParser {
throw new IllegalArgumentException("Invalid row gap", e);
}
}
return new LineBreakToken(end + 1, resetPropagation, gapBeforePx);
StringBuilder trailingShorthand = new StringBuilder();
for (int i = 1; i < tokens.size(); i++) {
if (trailingShorthand.length() > 0) {
trailingShorthand.append(' ');
}
trailingShorthand.append(tokens.get(i));
}
return new LineBreakToken(end + 1, resetPropagation, gapBeforePx, trailingShorthand.toString());
}
private static final class LineBreakToken {
final int endIndex;
final boolean resetPropagation;
final int gapBeforePx;
final String trailingShorthand;
LineBreakToken(int endIndex, boolean resetPropagation, int gapBeforePx) {
LineBreakToken(int endIndex, boolean resetPropagation, int gapBeforePx, String trailingShorthand) {
this.endIndex = endIndex;
this.resetPropagation = resetPropagation;
this.gapBeforePx = gapBeforePx;
this.trailingShorthand = trailingShorthand != null ? trailingShorthand : "";
}
}
}
@@ -0,0 +1,45 @@
package se.ajpanton.statusbartweak.runtime.features.clock;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import java.util.ArrayList;
public final class ClockPatternPreviewRenderer {
public static final int ROW_GAP_AUTO = ClockPatternParser.ROW_GAP_AUTO;
private static final ClockPatternParser PATTERN_PARSER = new ClockPatternParser();
private static final ClockTextRenderer TEXT_RENDERER = new ClockTextRenderer();
private ClockPatternPreviewRenderer() {
}
public static Result render(Context context, String pattern, int referenceColor) {
if (context == null || TextUtils.isEmpty(pattern)) {
return new Result(new ArrayList<>(), "", false);
}
ClockParsedPattern parsedPattern = PATTERN_PARSER.parse(pattern);
ArrayList<ClockTextRenderer.LayoutRowResult> renderedRows =
TEXT_RENDERER.renderLayoutRows(context, parsedPattern, referenceColor);
ArrayList<Row> rows = new ArrayList<>();
StringBuilder description = new StringBuilder();
for (int i = 0; i < renderedRows.size(); i++) {
ClockTextRenderer.LayoutRowResult row = renderedRows.get(i);
if (i > 0) {
description.append('\n');
}
description.append(row.contentDescription);
rows.add(new Row(row.text, row.leftText, row.rightText, row.pipeCount, row.gapBeforePx));
}
if (rows.isEmpty()) {
return new Result(new ArrayList<>(), "", parsedPattern.containsSeconds);
}
return new Result(rows, description.toString(), parsedPattern.containsSeconds);
}
public record Result(ArrayList<Row> rows, String contentDescription, boolean containsSeconds) {
}
public record Row(CharSequence text, CharSequence leftText, CharSequence rightText, int pipeCount, int gapBeforePx) {
}
}
@@ -28,6 +28,7 @@ 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.RuntimeSettingsCache;
import se.ajpanton.statusbartweak.R;
import se.ajpanton.statusbartweak.shell.settings.SbtSettings;
final class DrawerClockTextController {
@@ -204,6 +205,7 @@ final class DrawerClockTextController {
return;
}
Role previous = trackedRoles.put(textView, role);
textView.setTag(R.id.sbt_debug_drawer_clock_container, role.name());
if (previous == null || previous != role || !stockSnapshots.containsKey(textView)) {
captureSnapshot(textView);
}
@@ -214,6 +216,9 @@ 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);
}
stopTicker(textView);
}
@@ -414,6 +414,9 @@ final class StockLayoutCanvasController {
if (shouldSuppressTrackedStatusChipAlpha(view, alpha)) {
return null;
}
if (shouldSuppressSamsungBatteryStatusChipAlpha(view, alpha)) {
return null;
}
if (shouldCaptureAodVisualAlpha(view)) {
rememberAodPluginVisualAlpha(view, alpha);
}
@@ -424,6 +427,9 @@ final class StockLayoutCanvasController {
Object target = chain.getThisObject();
Object visibilityArg = firstArg(chain.getArgs());
if (target instanceof View view && visibilityArg instanceof Integer visibility) {
if (shouldSuppressSamsungBatteryStatusChipVisibility(view, visibility)) {
return null;
}
if (shouldSuppressTrackedStatusChipVisibility(view, visibility)) {
return null;
}
@@ -3286,6 +3292,9 @@ final class StockLayoutCanvasController {
if (confirmedAodPluginViews.contains(view)) {
return true;
}
if (isSamsungBatteryStatusChipSurface(view)) {
return true;
}
String idName = ViewIdNames.idName(view);
if (TARGET_ID_NAMES.contains(idName)) {
return true;
@@ -3300,6 +3309,41 @@ final class StockLayoutCanvasController {
return containsAny(className, TARGET_CLASS_SUBSTRINGS);
}
private boolean isSamsungBatteryStatusChipSurface(View view) {
return view != null && view.getClass().getName().contains("SamsungBatteryStatusChip");
}
private boolean shouldSuppressSamsungBatteryStatusChipAlpha(View view, float alpha) {
if (alpha <= 0f || ownHiddenViewAlphaWriteDepth > 0 || !isSamsungBatteryStatusChipSurface(view)) {
return false;
}
if (!shouldSuppressSamsungBatteryStatusChip(view)) {
return false;
}
hideView(view, true);
return true;
}
private boolean shouldSuppressSamsungBatteryStatusChipVisibility(View view, int visibility) {
if (visibility != View.VISIBLE
|| ownHiddenViewAlphaWriteDepth > 0
|| !isSamsungBatteryStatusChipSurface(view)) {
return false;
}
if (!shouldSuppressSamsungBatteryStatusChip(view)) {
return false;
}
hideView(view, true);
return true;
}
private boolean shouldSuppressSamsungBatteryStatusChip(View view) {
if (view == null || !view.isAttachedToWindow() || !isLayoutEnabled(view.getContext())) {
return false;
}
return true;
}
private boolean isStatusChipSource(View view) {
if (view == null || view.getVisibility() != View.VISIBLE) {
return false;
@@ -94,6 +94,12 @@ public final class DebugBoundsOverlayController {
OwnedIconHostManager.TAG_UNLOCKED_CLOCK_HOST,
COLOR_CLOCK,
specs);
addTaggedDescendantSpecs(
root,
parent,
R.id.sbt_debug_drawer_clock_container,
COLOR_CLOCK,
specs);
}
if (layoutEnabled && settings.debugVisualizeChipContainer) {
addHostContainerSpecs(
@@ -148,6 +154,9 @@ public final class DebugBoundsOverlayController {
result = 31 * result + hostSignature(root, OwnedIconHostManager.TAG_UNLOCKED_NOTIFICATION_HOST);
result = 31 * result + hostSignature(root, OwnedIconHostManager.TAG_UNLOCKED_STATUS_HOST);
result = 31 * result + hostSignature(root, OwnedIconHostManager.TAG_UNLOCKED_CLOCK_HOST);
if (settings.debugVisualizeClockContainer) {
result = 31 * result + taggedDescendantSignature(root, root, R.id.sbt_debug_drawer_clock_container);
}
result = 31 * result + hostSignature(root, OwnedIconHostManager.TAG_UNLOCKED_CHIP_HOST);
return result;
}
@@ -403,6 +412,30 @@ public final class DebugBoundsOverlayController {
}
}
private void addTaggedDescendantSpecs(
View root,
View view,
int tagKey,
int color,
ArrayList<OverlaySpec> specs
) {
if (root == null || view == null || specs == null) {
return;
}
if (view.getTag(tagKey) != null && view.getVisibility() != View.GONE) {
Bounds bounds = boundsRelativeTo(root, view);
if (bounds != null && bounds.width > 0 && bounds.height > 0) {
specs.add(new OverlaySpec(bounds, color));
}
}
if (!(view instanceof ViewGroup group)) {
return;
}
for (int i = 0; i < group.getChildCount(); i++) {
addTaggedDescendantSpecs(root, group.getChildAt(i), tagKey, color, specs);
}
}
private OverlayView ensureOverlay(ViewGroup parent) {
View existing = findDirectTaggedChild(parent, TAG_OVERLAY_HOST);
if (existing instanceof OverlayView overlayView) {
@@ -493,6 +526,24 @@ public final class DebugBoundsOverlayController {
return result;
}
private int taggedDescendantSignature(View root, View view, int tagKey) {
if (root == null || view == null) {
return 0;
}
int result = 17;
Object tag = view.getTag(tagKey);
if (tag != null && view.getVisibility() != View.GONE) {
result = 31 * result + signature(boundsRelativeTo(root, view));
result = 31 * result + tag.hashCode();
}
if (view instanceof ViewGroup group) {
for (int i = 0; i < group.getChildCount(); i++) {
result = 31 * result + taggedDescendantSignature(root, group.getChildAt(i), tagKey);
}
}
return result;
}
private Bounds boundsRelativeTo(View root, View view) {
if (root == null || view == null) {
return null;
@@ -0,0 +1,85 @@
package se.ajpanton.statusbartweak.runtime.render;
import android.graphics.Rect;
import android.view.DisplayCutout;
import android.view.View;
import android.view.WindowInsets;
import java.util.Objects;
import java.util.WeakHashMap;
import se.ajpanton.statusbartweak.shell.settings.ClockCameraTypeSupport;
import se.ajpanton.statusbartweak.shell.settings.SbtSettings;
final class EffectiveCutoutSupport {
private static final WeakHashMap<View, CameraTypeCache> CAMERA_TYPE_BY_ROOT = new WeakHashMap<>();
private EffectiveCutoutSupport() {
}
static Rect middleCutout(View root, SbtSettings settings, boolean ignoreUnderDisplayCamera) {
Rect cutout = ViewGeometry.middleCutout(root);
if (cutout == null || !ignoreUnderDisplayCamera) {
return cutout;
}
String effectiveType = effectiveCameraType(root, cutout, settings);
return ClockCameraTypeSupport.TYPE_UDC.equals(effectiveType) ? null : cutout;
}
static Rect layoutMiddleCutout(View root, SbtSettings settings) {
return middleCutout(
root,
settings,
settings != null && settings.layoutIgnoreUnderDisplayCameras);
}
static Rect clockMiddleCutout(View root, SbtSettings settings) {
return middleCutout(
root,
settings,
settings != null && settings.clockIgnoreUnderDisplayCameras);
}
private static String effectiveCameraType(View root, Rect cutout, SbtSettings settings) {
int signature = cameraTypeSignature(root, cutout, settings);
CameraTypeCache cached = CAMERA_TYPE_BY_ROOT.get(root);
if (cached != null && cached.signature == signature) {
return cached.effectiveType;
}
WindowInsets insets = root != null ? root.getRootWindowInsets() : null;
DisplayCutout displayCutout = insets != null ? insets.getDisplayCutout() : null;
ClockCameraTypeSupport.CameraInfo cameraInfo =
ClockCameraTypeSupport.resolveCameraInfo(root, displayCutout, settings);
String effectiveType = cameraInfo.effectiveType;
if (root != null) {
SbtSettings.setClockCameraDebugState(
root.getContext(),
cameraInfo.cameraId,
cameraInfo.automaticType,
cameraInfo.effectiveType);
}
CAMERA_TYPE_BY_ROOT.put(root, new CameraTypeCache(signature, effectiveType));
return effectiveType;
}
private static int cameraTypeSignature(View root, Rect cutout, SbtSettings settings) {
return Objects.hash(
root != null ? root.getWidth() : 0,
root != null ? root.getHeight() : 0,
cutout != null ? cutout.left : 0,
cutout != null ? cutout.top : 0,
cutout != null ? cutout.right : 0,
cutout != null ? cutout.bottom : 0,
settings != null ? settings.clockCameraTypeOverrides : null);
}
private static final class CameraTypeCache {
final int signature;
final String effectiveType;
CameraTypeCache(int signature, String effectiveType) {
this.signature = signature;
this.effectiveType = effectiveType;
}
}
}
@@ -34,6 +34,10 @@ final class SnapshotIconFilter {
}
ArrayList<SnapshotPlacement> filtered = new ArrayList<>(placements.size());
for (SnapshotPlacement placement : placements) {
if (isChargingBatteryChipPlacement(placement)) {
filtered.add(placement);
continue;
}
if (!isStatusBlocked(placement, settings.systemIconBlockedModes, mode)) {
filtered.add(placement);
}
@@ -109,6 +113,11 @@ final class SnapshotIconFilter {
return false;
}
private static boolean isChargingBatteryChipPlacement(SnapshotPlacement placement) {
return placement != null
&& SnapshotKeys.CHARGING_BATTERY_CHIP.equals(placement.key);
}
private static AppIconRules.ExceptionRule matchingExceptionRule(
SnapshotPlacement placement,
ArrayList<AppIconRules.ExceptionRule> rules
@@ -36,6 +36,7 @@ final class SnapshotKeys {
static final String OVERFLOW_DOT = "statusbartweak:overflow_dot";
static final String EMPTY_CHIP = "statusbartweak:empty_chip";
static final String EMPTY_ICON_CONTAINER = "statusbartweak:empty_icon_container";
static final String CHARGING_BATTERY_CHIP = "statusbartweak:charging_battery_chip";
private SnapshotKeys() {
}
@@ -1,15 +1,19 @@
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;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
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;
@@ -34,6 +38,7 @@ import se.ajpanton.statusbartweak.runtime.NotificationKeyReflection;
import se.ajpanton.statusbartweak.runtime.ViewIdNames;
import se.ajpanton.statusbartweak.runtime.hooks.ReflectionSupport;
import se.ajpanton.statusbartweak.runtime.layoutsolver.StatusBarLayoutSolver.Bounds;
import se.ajpanton.statusbartweak.runtime.settings.BroadcastReceiverSupport;
final class SnapshotRenderer {
private static final long TRANSITION_SIGNAL_HOLD_MS = 700L;
@@ -336,6 +341,7 @@ final class SnapshotRenderer {
private boolean shouldTrimContent(SnapshotSource source) {
return trimViewContentForCollision
&& source != null
&& !SnapshotKeys.CHARGING_BATTERY_CHIP.equals(source.keyHint())
&& (source.mode() == SnapshotMode.VIEW || source.mode() == SnapshotMode.STATUS_CHIP);
}
@@ -713,6 +719,10 @@ final class SnapshotRenderer {
if (offsetX != 0) {
canvas.translate(-offsetX, 0);
}
if (isChargingBatteryChipSource(source)) {
drawChargingBatteryChip(source, bitmap);
return;
}
View sourceView = source.view();
if (sourceView == null) {
return;
@@ -823,6 +833,152 @@ final class SnapshotRenderer {
&& source.mode() != SnapshotMode.STATUS_CHIP;
}
private boolean isChargingBatteryChipSource(SnapshotSource source) {
return source != null && SnapshotKeys.CHARGING_BATTERY_CHIP.equals(source.keyHint());
}
private void drawChargingBatteryChip(SnapshotSource source, Bitmap bitmap) {
if (source == null
|| bitmap == null
|| bitmap.isRecycled()
|| bitmap.getWidth() <= 0
|| bitmap.getHeight() <= 0) {
return;
}
bitmap.eraseColor(Color.TRANSPARENT);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float inset = Math.max(1f, height * 0.05f);
RectF pill = new RectF(inset, inset, width - inset, height - inset);
float radius = pill.height() / 2f;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
paint.setColor(Color.argb(235, 42, 45, 49));
Canvas canvas = new Canvas(bitmap);
canvas.drawRoundRect(pill, radius, radius, paint);
int level = chargingBatteryLevel(source.view());
float gaugeWidth = Math.min(pill.width(), Math.max(height * 1.35f, pill.width() * 0.42f));
float fillRight = pill.left + gaugeWidth * Math.max(0f, Math.min(100f, level)) / 100f;
if (fillRight > pill.left) {
Path clip = new Path();
clip.addRoundRect(pill, radius, radius, Path.Direction.CW);
int save = canvas.save();
canvas.clipPath(clip);
paint.setColor(Color.rgb(42, 220, 103));
canvas.drawRect(pill.left, pill.top, fillRight, pill.bottom, paint);
canvas.restoreToCount(save);
}
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(Math.max(1f, height * 0.035f));
paint.setColor(Color.argb(120, 255, 255, 255));
canvas.drawRoundRect(pill, radius, radius, paint);
paint.setStyle(Paint.Style.FILL);
drawChargingBolt(canvas, paint, pill.left + height * 0.48f, height / 2f, height * 0.55f);
String text = chargingBatteryText(source.view(), level);
paint.setTextAlign(Paint.Align.RIGHT);
paint.setFakeBoldText(true);
paint.setColor(Color.WHITE);
paint.setTextSize(Math.max(1f, height * 0.42f));
Paint.FontMetrics metrics = paint.getFontMetrics();
float baseline = height / 2f - (metrics.ascent + metrics.descent) / 2f;
canvas.drawText(text, pill.right - Math.max(2f, height * 0.18f), baseline, paint);
paint.setFakeBoldText(false);
}
private void drawChargingBolt(Canvas canvas, Paint paint, float centerX, float centerY, float size) {
float half = size / 2f;
Path bolt = new Path();
bolt.moveTo(centerX + half * 0.10f, centerY - half);
bolt.lineTo(centerX - half * 0.42f, centerY + half * 0.08f);
bolt.lineTo(centerX - half * 0.04f, centerY + half * 0.08f);
bolt.lineTo(centerX - half * 0.18f, centerY + half);
bolt.lineTo(centerX + half * 0.44f, centerY - half * 0.18f);
bolt.lineTo(centerX + half * 0.04f, centerY - half * 0.18f);
bolt.close();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(bolt, paint);
}
private String chargingBatteryText(View source, int fallbackLevel) {
CharSequence text = findChargingBatteryText(source);
if (text != null && text.length() > 0) {
return text.toString();
}
return Math.max(0, Math.min(100, fallbackLevel)) + "%";
}
private int chargingBatteryLevel(View source) {
CharSequence text = findChargingBatteryText(source);
int parsed = parsePercent(text);
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)));
}
private CharSequence findChargingBatteryText(View source) {
if (source == null) {
return null;
}
if (source instanceof TextView textView) {
CharSequence text = textView.getText();
if (parsePercent(text) >= 0) {
return text;
}
}
if (!(source instanceof ViewGroup group)) {
return null;
}
for (int i = 0; i < group.getChildCount(); i++) {
CharSequence text = findChargingBatteryText(group.getChildAt(i));
if (text != null && text.length() > 0) {
return text;
}
}
return null;
}
private int parsePercent(CharSequence text) {
if (text == null) {
return -1;
}
int value = 0;
boolean found = false;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c >= '0' && c <= '9') {
value = value * 10 + c - '0';
found = true;
} else if (found) {
break;
}
}
return found ? Math.max(0, Math.min(100, value)) : -1;
}
private boolean isTintableMonochrome(Bitmap bitmap) {
int coloredPixels = 0;
int monochromePixels = 0;
@@ -1,5 +1,7 @@
package se.ajpanton.statusbartweak.runtime.render;
import android.app.KeyguardManager;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@@ -71,6 +73,11 @@ public final class UnlockedIconSnapshotRenderController {
clearAll();
return new RenderResult(true, true, true);
}
if (scene.isUnlocked() && isKeyguardLocked(root.getContext())) {
clearLockscreenHosts(clockHost, carrierHost, chipHost, statusHost, notificationHost);
clearRoot(root);
return new RenderResult(true, true, true);
}
SbtSettings settings = RuntimeSettingsCache.get(root.getContext());
setStatusBarTintTargetEnabled(scene.isUnlocked());
layoutHostToRoot(root, clockHost);
@@ -96,7 +103,7 @@ public final class UnlockedIconSnapshotRenderController {
root,
settings,
scene,
ViewGeometry.middleCutout(root),
EffectiveCutoutSupport.layoutMiddleCutout(root, settings),
anchors,
previousIcons);
LayoutInputSignature previousSignature = lastLayoutSignatureByRoot.get(root);
@@ -154,12 +161,12 @@ public final class UnlockedIconSnapshotRenderController {
root,
currentClockLayout,
settings,
UnlockedLayoutPlanner.cutoutBounds(ViewGeometry.middleCutout(root), settings.clockMiddleCutoutGapPx));
clockCutoutBounds(root, settings));
ClockPlacement textPlacement = clockTextPlacementForPrevious(
root,
currentClockLayout,
settings,
UnlockedLayoutPlanner.cutoutBounds(ViewGeometry.middleCutout(root), settings.clockMiddleCutoutGapPx),
clockCutoutBounds(root, settings),
previousPlan != null ? previousPlan.clockPlacement : null);
ClockPlacement updatedClock = clockPlacementWithUpdatedText(
previousPlan != null ? previousPlan.clockPlacement : null,
@@ -193,7 +200,7 @@ public final class UnlockedIconSnapshotRenderController {
root,
currentClockLayout,
settings,
UnlockedLayoutPlanner.cutoutBounds(ViewGeometry.middleCutout(root), settings.clockMiddleCutoutGapPx));
clockCutoutBounds(root, settings));
}
if (scene.isLockscreen() && clockEnabledForScene(settings, scene) && currentClockLayout == null) {
clearLockscreenHosts(clockHost, carrierHost, chipHost, statusHost, notificationHost);
@@ -392,6 +399,14 @@ public final class UnlockedIconSnapshotRenderController {
notificationRenderer.clear(notificationHost);
}
private boolean isKeyguardLocked(Context context) {
if (context == null) {
return false;
}
KeyguardManager keyguardManager = context.getSystemService(KeyguardManager.class);
return keyguardManager != null && keyguardManager.isKeyguardLocked();
}
private void layoutHostToRoot(View root, ViewGroup host) {
if (root == null || host == null || root.getWidth() <= 0 || root.getHeight() <= 0) {
return;
@@ -724,7 +739,13 @@ public final class UnlockedIconSnapshotRenderController {
anchors,
settings,
scene,
UnlockedLayoutPlanner.cutoutBounds(ViewGeometry.middleCutout(root), settings != null ? settings.clockMiddleCutoutGapPx : 0));
clockCutoutBounds(root, settings));
}
private Bounds clockCutoutBounds(View root, SbtSettings settings) {
return UnlockedLayoutPlanner.cutoutBounds(
EffectiveCutoutSupport.clockMiddleCutout(root, settings),
settings != null ? settings.clockMiddleCutoutGapPx : 0);
}
private ClockLayout buildClockLayout(
@@ -68,13 +68,14 @@ final class UnlockedLayoutPlanner {
aodInitialStatusbarHeightByRoot.remove(root);
}
ArrayList<UnlockedLayoutBand> bands = new ArrayList<>();
Rect cutout = ViewGeometry.middleCutout(root);
Rect layoutCutout = EffectiveCutoutSupport.layoutMiddleCutout(root, settings);
Rect clockCutout = EffectiveCutoutSupport.clockMiddleCutout(root, settings);
Bounds layoutCutoutBounds = scene != null && scene.isAod()
? aodCutoutBounds(root, cutout, settings.layoutPaddingCutoutPx)
: cutoutBounds(cutout, settings.layoutPaddingCutoutPx);
? aodCutoutBounds(root, layoutCutout, settings.layoutPaddingCutoutPx)
: cutoutBounds(layoutCutout, settings.layoutPaddingCutoutPx);
Bounds clockCutoutBounds = scene != null && scene.isAod()
? aodCutoutBounds(root, cutout, settings.clockMiddleCutoutGapPx)
: cutoutBounds(cutout, settings.clockMiddleCutoutGapPx);
? aodCutoutBounds(root, clockCutout, settings.clockMiddleCutoutGapPx)
: cutoutBounds(clockCutout, settings.clockMiddleCutoutGapPx);
Bounds aodStatusAnchorBounds = scene != null && scene.isAod()
? aodStatusAnchorBounds(root, anchors, scene)
: null;
@@ -1112,7 +1113,9 @@ final class UnlockedLayoutPlanner {
if (bounds == null || bounds.height <= 0) {
continue;
}
int width = Math.max(1, Math.round((float) bounds.width * targetHeight / bounds.height));
int width = isChargingBatteryChipPlacement(placement)
? chargingBatteryChipWidth(targetHeight)
: Math.max(1, Math.round((float) bounds.width * targetHeight / bounds.height));
int bottom = bounds.top + bounds.height;
Bounds resized = new Bounds(bounds.left, bottom - targetHeight, width, targetHeight);
result.add(new SnapshotPlacement(
@@ -1130,6 +1133,15 @@ final class UnlockedLayoutPlanner {
return result;
}
private boolean isChargingBatteryChipPlacement(SnapshotPlacement placement) {
return placement != null
&& SnapshotKeys.CHARGING_BATTERY_CHIP.equals(placement.key);
}
private int chargingBatteryChipWidth(int height) {
return Math.max(1, Math.round(Math.max(1, height) * 2.7f));
}
private Bounds sourceRenderBoundsForResize(SnapshotPlacement placement) {
if (placement == null || placement.source == null || placement.bounds == null) {
return placement != null ? placement.sourceRenderBounds : null;
@@ -1,7 +1,10 @@
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;
@@ -23,6 +26,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.shell.settings.SbtDefaults;
import se.ajpanton.statusbartweak.shell.settings.SbtSettings;
@@ -74,6 +78,7 @@ final class UnlockedStockSourceCollector {
if (anchors.battery != null && !ViewGeometry.isDescendantOf(anchors.battery, anchors.statusRoot)) {
collectStatusSnapshotViews(anchors.battery, statusIcons);
}
addSamsungBatteryStatusChipSource(root, statusIcons, settings);
selectDualSimStatusSignals(statusIcons, settings);
normalizeStatusIconSourceBounds(root, statusIcons);
if (scene != null && scene.isAod()) {
@@ -185,6 +190,7 @@ final class UnlockedStockSourceCollector {
: 0;
int statusSourceSignature = sourceLayoutListSignature(
previousIcons != null ? previousIcons.statusIcons : null);
statusSourceSignature = 31 * statusSourceSignature + batteryChargingSignature(root);
if (scene != null && scene.isAod()) {
statusSourceSignature = 31 * statusSourceSignature
+ aodLayoutAnchorSignature(root, anchors, scene);
@@ -283,7 +289,7 @@ final class UnlockedStockSourceCollector {
return;
}
if (isStatusChipMetricCandidate(root, source.view(), true)
&& hasVisibleStatusChipContent(source.view())) {
&& hasRenderableStatusChipContent(source.view())) {
metricOut.add(source);
return;
}
@@ -880,6 +886,132 @@ final class UnlockedStockSourceCollector {
}
}
private void addSamsungBatteryStatusChipSource(
View root,
ArrayList<SnapshotSource> sources,
SbtSettings settings
) {
if (root == null
|| sources == null
|| settings == null
|| settings.statusChipsHideAll
|| settings.statusChipsHideBattery
|| !isDevicePlugged(root.getContext())) {
return;
}
View chip = samsungBatteryStatusChip(root);
if (chip == null) {
return;
}
removeBatteryStatusSources(sources);
Bounds bounds = ViewGeometry.boundsRelativeTo(root, chip);
sources.add(new SnapshotSource(
chip,
SnapshotMode.STATUS_CHIP,
SnapshotKeys.CHARGING_BATTERY_CHIP,
validBounds(bounds) ? bounds : null));
}
private View samsungBatteryStatusChip(View root) {
if (root == null) {
return null;
}
ArrayDeque<View> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
View view = queue.removeFirst();
if (isSamsungBatteryStatusChip(view) && hasUsableSamsungBatteryStatusChipBounds(root, view)) {
return view;
}
if (view instanceof ViewGroup group) {
for (int i = 0; i < group.getChildCount(); i++) {
View child = group.getChildAt(i);
if (child != null) {
queue.addLast(child);
}
}
}
}
return null;
}
private boolean hasUsableSamsungBatteryStatusChipBounds(View root, View view) {
if (root == null
|| view == null
|| view == root
|| !view.isAttachedToWindow()
|| view.getVisibility() != View.VISIBLE
|| (view.getAlpha() <= 0f && !hasVisibleStatusChipContent(view))) {
return false;
}
Bounds bounds = ViewGeometry.boundsRelativeTo(root, view);
return validBounds(bounds)
&& bounds.top >= 0
&& bounds.top <= root.getHeight()
&& bounds.width < root.getWidth() / 2;
}
private boolean validBounds(Bounds bounds) {
return bounds != null && bounds.width > 0 && bounds.height > 0;
}
private void removeBatteryStatusSources(ArrayList<SnapshotSource> sources) {
if (sources == null || sources.isEmpty()) {
return;
}
for (int i = sources.size() - 1; i >= 0; i--) {
SnapshotSource source = sources.get(i);
if (isBatteryStatusSource(source)) {
sources.remove(i);
}
}
}
private boolean isBatteryStatusSource(SnapshotSource source) {
View view = source != null ? source.view() : null;
StringBuilder sb = new StringBuilder();
append(sb, source != null ? source.keyHint() : null);
append(sb, reflectString(view, "getSlot", "mSlot", "slot"));
append(sb, view != null ? ViewIdNames.idName(view) : null);
append(sb, view != null ? view.getClass().getName() : null);
return sb.toString().toLowerCase(Locale.ROOT).contains("battery");
}
private boolean isSamsungBatteryStatusChip(View view) {
return view != null && view.getClass().getName().contains("SamsungBatteryStatusChip");
}
private int batteryChargingSignature(View root) {
return root != null && isDevicePlugged(root.getContext()) ? 1 : 0;
}
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));
}
private void append(StringBuilder sb, String value) {
if (sb == null || value == null || value.isEmpty()) {
return;
}
sb.append(';').append(value);
}
private int normalizedStatusIconWidth(int drawableWidth, int iconHeight) {
return Math.max(1, drawableWidth + statusIconHorizontalPadding(iconHeight));
}
@@ -1060,7 +1192,7 @@ final class UnlockedStockSourceCollector {
|| !ViewGeometry.isDescendantOf(view, root)
|| ReflectionSupport.getBooleanField(view, "sbtStatusChipForcedHidden", false)
|| !isStatusChipCandidate(view)
|| !hasVisibleStatusChipContent(view)) {
|| !hasRenderableStatusChipContent(view)) {
return false;
}
Bounds bounds = source.boundsOverride() != null
@@ -1078,7 +1210,7 @@ final class UnlockedStockSourceCollector {
if (view == null || view == root || view.getVisibility() != View.VISIBLE) {
return false;
}
if (!allowHidden && view.getAlpha() <= 0f && !hasVisibleStatusChipContent(view)) {
if (!allowHidden && view.getAlpha() <= 0f && !hasRenderableStatusChipContent(view)) {
return false;
}
if (ReflectionSupport.getBooleanField(view, "sbtStatusChipForcedHidden", false)) {
@@ -1093,7 +1225,7 @@ final class UnlockedStockSourceCollector {
if (bounds == null || bounds.top < 0 || bounds.top > root.getHeight()) {
return false;
}
if (!isStatusChipCandidate(view)) {
if (!isStatusChipCandidate(view) || !hasRenderableStatusChipContent(view)) {
return false;
}
Object parent = view.getParent();
@@ -1106,6 +1238,39 @@ final class UnlockedStockSourceCollector {
return true;
}
private boolean hasRenderableStatusChipContent(View source) {
if (!(source instanceof ViewGroup group)) {
return false;
}
ArrayDeque<View> queue = new ArrayDeque<>();
for (int i = 0; i < group.getChildCount(); i++) {
queue.addLast(group.getChildAt(i));
}
while (!queue.isEmpty()) {
View view = queue.removeFirst();
if (view == null) {
continue;
}
if (view instanceof TextView textView
&& view.getVisibility() == View.VISIBLE
&& view.getAlpha() > 0f
&& textView.getText() != null
&& textView.getText().length() > 0) {
int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth();
int height = view.getHeight() > 0 ? view.getHeight() : view.getMeasuredHeight();
if (width > 0 && height > 0) {
return true;
}
}
if (view instanceof ViewGroup childGroup) {
for (int i = 0; i < childGroup.getChildCount(); i++) {
queue.addLast(childGroup.getChildAt(i));
}
}
}
return false;
}
private boolean hasVisibleStatusChipContent(View source) {
if (!(source instanceof ViewGroup group)) {
return false;
@@ -1139,7 +1304,7 @@ final class UnlockedStockSourceCollector {
if (view == null || view == root || root == null) {
return false;
}
if (!allowHidden && view.getAlpha() <= 0f && !hasVisibleStatusChipContent(view)) {
if (!allowHidden && view.getAlpha() <= 0f && !hasRenderableStatusChipContent(view)) {
return false;
}
int width = view.getWidth() > 0 ? view.getWidth() : view.getMeasuredWidth();
@@ -1151,7 +1316,7 @@ final class UnlockedStockSourceCollector {
if (bounds == null || bounds.top < 0 || bounds.top > root.getHeight()) {
return false;
}
if (!isStatusChipCandidate(view)) {
if (!isStatusChipCandidate(view) || !hasRenderableStatusChipContent(view)) {
return false;
}
Object parent = view.getParent();
@@ -1350,7 +1515,7 @@ final class UnlockedStockSourceCollector {
queue.add(root);
while (!queue.isEmpty()) {
View view = queue.removeFirst();
if (view != root && isStatusChipCandidate(view) && hasVisibleStatusChipContent(view)) {
if (view != root && isStatusChipCandidate(view) && hasRenderableStatusChipContent(view)) {
result = 31 * result + chipViewLayoutSignature(view);
}
if (view instanceof ViewGroup group) {
@@ -1370,7 +1535,7 @@ final class UnlockedStockSourceCollector {
result = 31 * result + sources.size();
for (SnapshotSource source : sources) {
result = 31 * result + source.mode().ordinal();
result = 31 * result + (hasVisibleStatusChipContent(source.view()) ? 1 : 0);
result = 31 * result + (hasRenderableStatusChipContent(source.view()) ? 1 : 0);
result = 31 * result + chipViewLayoutSignature(source.view());
}
return result;
@@ -1494,6 +1659,7 @@ final class UnlockedStockSourceCollector {
settings.clockCustomFormatEnabled,
settings.clockCustomFormat,
settings.clockIgnoreUnderDisplayCameras,
settings.clockCameraTypeOverrides,
settings.layoutPaddingCutoutPx,
settings.layoutPaddingLeftPx,
settings.layoutPaddingRightPx,
@@ -1556,7 +1722,8 @@ final class UnlockedStockSourceCollector {
settings.statusChipsHideAll,
settings.statusChipsHideMediaUnlocked,
settings.statusChipsHideNavUnlocked,
settings.statusChipsHideCallUnlocked);
settings.statusChipsHideCallUnlocked,
settings.statusChipsHideBattery);
}
}
@@ -29,6 +29,9 @@ public final class ClockCameraTypeSupport {
public static final class CameraInfo {
public int semDisplayDeviceType = Integer.MIN_VALUE;
public int fillUdcDisplayCutout = Integer.MIN_VALUE;
public int rootWidth = Integer.MIN_VALUE;
public int rootHeight = Integer.MIN_VALUE;
public int rotation = Integer.MIN_VALUE;
public boolean isUdcMainDisplay;
public String cutoutType;
public String cutoutString;
@@ -59,8 +62,15 @@ public final class ClockCameraTypeSupport {
: "blocking cutout";
}
public static String buildCameraId(int semDisplayDeviceType, String cutoutType, String cutoutString) {
private static String buildCameraId(int semDisplayDeviceType,
int rootWidth,
int rootHeight,
int rotation,
String cutoutType,
String cutoutString) {
String descriptor = semDisplayDeviceType + "|"
+ rootWidth + "x" + rootHeight + "|"
+ rotation + "|"
+ safe(cutoutType) + "|"
+ safe(cutoutString);
return "cam_" + shortSha1(descriptor);
@@ -78,6 +88,20 @@ public final class ClockCameraTypeSupport {
finalizeCameraInfo(info, settings);
return info;
}
Display display = root.getDisplay();
if (display != null) {
info.rotation = display.getRotation();
}
int width = root.getWidth();
if (width <= 0 && root.getRootView() != null) {
width = root.getRootView().getWidth();
}
info.rootWidth = width;
int height = root.getHeight();
if (height <= 0 && root.getRootView() != null) {
height = root.getRootView().getHeight();
}
info.rootHeight = height;
info.semDisplayDeviceType = readSemDisplayDeviceType(context);
info.fillUdcDisplayCutout = readGlobalInt(context, "fill_udc_display_cutout");
Object displayLifecycle = resolveDisplayLifecycle(context);
@@ -93,15 +117,9 @@ public final class ClockCameraTypeSupport {
finalizeCameraInfo(info, settings);
return info;
}
Object input = newInstance(inputClass, context);
Display display = root.getDisplay();
if (display != null) {
setIntField(input, "rotation", display.getRotation());
}
int width = root.getWidth();
if (width <= 0 && root.getRootView() != null) {
width = root.getRootView().getWidth();
setIntField(input, "rotation", info.rotation);
}
if (width > 0) {
setIntField(input, "statusBarWidth", width);
@@ -196,6 +214,9 @@ public final class ClockCameraTypeSupport {
}
info.cameraId = buildCameraId(
info.semDisplayDeviceType,
info.rootWidth,
info.rootHeight,
info.rotation,
info.cutoutType,
info.cutoutString);
boolean explicitUdc = info.isUdcMainDisplay || "UDC".equals(info.cutoutType);
@@ -1,394 +1,105 @@
package se.ajpanton.statusbartweak.shell.settings;
import android.graphics.Color;
import android.text.TextUtils;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import se.ajpanton.statusbartweak.runtime.features.clock.ClockColorResolver;
public final class ColourExpressionSupport {
private static final Pattern OPERATION_PATTERN =
Pattern.compile("([+\\-*/])\\s*(" + hexOperandPattern() + "|\\d+(?:\\.\\d+)?|\\.\\d+)");
private static final Pattern LEADING_HEX_PATTERN =
Pattern.compile("(?i)^#?(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})");
private static final ClockColorResolver RESOLVER = new ClockColorResolver();
private static final ClockColorResolver.Options OPTIONS = ClockColorResolver.Options.batteryBar();
private ColourExpressionSupport() {
}
public static String normaliseExpression(String raw, boolean assumeHashPrefix) {
if (raw == null) {
return "";
}
String value = raw.trim();
String value = normaliseSeparators(raw);
if (value.isEmpty()) {
return "";
}
int variantSplit = findVariantSplit(value);
String left = value;
String right = null;
if (variantSplit >= 0) {
left = value.substring(0, variantSplit).trim();
right = value.substring(variantSplit + 1).trim();
}
if (!isValidSegment(left, assumeHashPrefix, false, Color.WHITE)) {
try {
RESOLVER.resolveColor(null, value, Color.WHITE, Color.WHITE, OPTIONS);
RESOLVER.resolveColor(null, value, Color.BLACK, Color.WHITE, OPTIONS);
return value;
} catch (IllegalArgumentException ignored) {
return "";
}
if (right != null && !isValidSegment(right, assumeHashPrefix, true, Color.WHITE)) {
return "";
}
if (right == null) {
return left;
}
return left + "|" + right;
}
public static int resolveColor(String raw,
public static int resolveColor(
String raw,
int referenceColor,
int fallbackColor,
boolean assumeHashPrefix) {
String value = normaliseExpression(raw, assumeHashPrefix);
boolean assumeHashPrefix
) {
String value = normaliseSeparators(raw);
if (value.isEmpty()) {
return fallbackColor;
}
int variantSplit = findVariantSplit(value);
if (variantSplit < 0) {
return resolveSegment(value, fallbackColor, assumeHashPrefix, false);
try {
return RESOLVER.resolveColor(null, value, referenceColor, fallbackColor, OPTIONS);
} catch (IllegalArgumentException ignored) {
return fallbackColor;
}
String left = value.substring(0, variantSplit).trim();
String right = value.substring(variantSplit + 1).trim();
int brightVariant = resolveSegment(left, fallbackColor, assumeHashPrefix, false);
if (!isDark(referenceColor)) {
return brightVariant;
}
return resolveSegment(right, brightVariant, assumeHashPrefix, true);
}
public static String resolveColorHex(String raw,
public static String resolveColorHex(
String raw,
int referenceColor,
int fallbackColor,
boolean assumeHashPrefix) {
int resolved = resolveColor(raw, referenceColor, fallbackColor, assumeHashPrefix);
int alpha = Color.alpha(resolved);
if (alpha >= 255) {
return String.format(Locale.ROOT, "#%06X", resolved & 0xFFFFFF);
}
return String.format(Locale.ROOT, "#%08X", resolved);
}
private static boolean isValidSegment(String segment,
boolean assumeHashPrefix,
boolean allowInheritedBase,
int baseColor) {
if (TextUtils.isEmpty(segment)) {
return false;
boolean assumeHashPrefix
) {
String value = normaliseSeparators(raw);
if (value.isEmpty()) {
return hexFor(fallbackColor);
}
try {
resolveSegment(segment, baseColor, assumeHashPrefix, allowInheritedBase);
return true;
return RESOLVER.resolveColorHex(null, value, referenceColor, fallbackColor, OPTIONS);
} catch (IllegalArgumentException ignored) {
return false;
return hexFor(fallbackColor);
}
}
private static int resolveSegment(String segment,
int baseColor,
boolean assumeHashPrefix,
boolean allowInheritedBase) {
String value = segment != null ? segment.trim() : "";
if (value.isEmpty()) {
throw new IllegalArgumentException("Empty colour segment");
}
int index = 0;
boolean invert = false;
if (value.regionMatches(true, 0, "inv", 0, 3)) {
invert = true;
index = 3;
}
double[] channels;
double alpha;
String remainder;
if (startsWithOperator(value, index)) {
if (!allowInheritedBase) {
throw new IllegalArgumentException("Missing starting colour");
}
channels = channelsFor(baseColor);
alpha = Color.alpha(baseColor);
remainder = value.substring(index).trim();
} else {
LeadingColour leading = parseLeadingColour(value, index, assumeHashPrefix);
channels = channelsFor(leading.color);
alpha = Color.alpha(leading.color);
remainder = value.substring(leading.endIndex).trim();
}
if (invert) {
invertChannels(channels);
}
alpha = applyOperations(channels, alpha, remainder);
return colorFromChannels(channels, alpha);
}
private static LeadingColour parseLeadingColour(String value,
int start,
boolean assumeHashPrefix) {
String remainder = value.substring(start).trim();
Matcher matcher = LEADING_HEX_PATTERN.matcher(remainder);
if (!matcher.find()) {
throw new IllegalArgumentException("Missing starting colour");
}
String token = matcher.group();
if (assumeHashPrefix && token.charAt(0) != '#') {
token = "#" + token;
}
int color = parseHexColor(token, assumeHashPrefix);
return new LeadingColour(color, start + matcher.end());
}
private static double applyOperations(double[] channels, double alpha, String remainder) {
int index = 0;
while (index < remainder.length()) {
while (index < remainder.length() && Character.isWhitespace(remainder.charAt(index))) {
index++;
}
if (index >= remainder.length()) {
break;
}
Matcher matcher = OPERATION_PATTERN.matcher(remainder);
matcher.region(index, remainder.length());
if (!matcher.lookingAt()) {
throw new IllegalArgumentException("Invalid colour operation");
}
char operator = matcher.group(1).charAt(0);
String operandText = matcher.group(2);
alpha = applyOperation(channels, alpha, operator, operandText);
index = matcher.end();
}
return alpha;
}
private static double applyOperation(double[] channels, double alpha, char operator, String operandText) {
Operand operand = parseOperand(operandText);
for (int i = 0; i < 3; i++) {
double value = channels[i];
double rhs = operand.rgb[i];
if (operand.isHex && (operator == '*' || operator == '/')) {
rhs = rhs / 255d;
}
switch (operator) {
case '+':
channels[i] = value + rhs;
break;
case '-':
channels[i] = value - rhs;
break;
case '*':
channels[i] = value * rhs;
break;
case '/':
channels[i] = rhs == 0d ? value : value / rhs;
break;
default:
throw new IllegalArgumentException("Unknown operator");
}
}
if (operand.hasAlpha) {
double rhs = operand.alpha;
if (operand.isHex && (operator == '*' || operator == '/')) {
rhs = rhs / 255d;
}
switch (operator) {
case '+':
alpha = alpha + rhs;
break;
case '-':
alpha = alpha - rhs;
break;
case '*':
alpha = alpha * rhs;
break;
case '/':
alpha = rhs == 0d ? alpha : alpha / rhs;
break;
default:
throw new IllegalArgumentException("Unknown operator");
}
}
return alpha;
}
private static Operand parseOperand(String operandText) {
String value = operandText != null ? operandText.trim() : "";
if (value.isEmpty()) {
throw new IllegalArgumentException("Missing operand");
}
if (value.charAt(0) == '#') {
return parseHexOperand(value);
}
double scalar;
try {
scalar = Double.parseDouble(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid operand", e);
}
return new Operand(new double[] { scalar, scalar, scalar }, 0d, false, false);
}
private static int parseHexColor(String raw, boolean assumeHashPrefix) {
private static String normaliseSeparators(String raw) {
String value = raw != null ? raw.trim() : "";
if (value.isEmpty()) {
throw new IllegalArgumentException("Empty colour");
return "";
}
if (assumeHashPrefix && value.charAt(0) != '#') {
value = "#" + value;
}
if (value.charAt(0) != '#') {
throw new IllegalArgumentException("Expected colour literal");
}
String hex = value.substring(1);
if (hex.length() == 3) {
hex = expandShortHex(hex);
} else if (hex.length() == 4) {
hex = expandShortHex(hex);
} else if (hex.length() != 6 && hex.length() != 8) {
throw new IllegalArgumentException("Unsupported colour length");
}
try {
return Color.parseColor("#" + hex);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid colour", e);
int split = findTopLevelPipe(value);
if (split < 0) {
return value;
}
return value.substring(0, split).trim() + " ; " + value.substring(split + 1).trim();
}
private static String expandShortHex(String hex) {
StringBuilder out = new StringBuilder(hex.length() * 2);
for (int i = 0; i < hex.length(); i++) {
char c = hex.charAt(i);
out.append(c).append(c);
}
return out.toString();
}
private static double[] channelsFor(int color) {
return new double[] {
Color.red(color),
Color.green(color),
Color.blue(color)
};
}
private static void invertChannels(double[] channels) {
for (int i = 0; i < 3; i++) {
channels[i] = 255d - channels[i];
}
}
private static int colorFromChannels(double[] channels, double alpha) {
int red = clampChannel(channels[0]);
int green = clampChannel(channels[1]);
int blue = clampChannel(channels[2]);
return Color.argb(clampChannel(alpha), red, green, blue);
}
private static Operand parseHexOperand(String raw) {
String value = raw != null ? raw.trim() : "";
if (value.isEmpty() || value.charAt(0) != '#') {
throw new IllegalArgumentException("Expected colour literal");
}
String hex = value.substring(1);
if (hex.length() == 3 || hex.length() == 4) {
hex = expandShortHex(hex);
} else if (hex.length() != 6 && hex.length() != 8) {
throw new IllegalArgumentException("Unsupported colour length");
}
boolean hasAlpha = hex.length() == 8;
int offset = hasAlpha ? 2 : 0;
double alpha = 0d;
if (hasAlpha) {
alpha = parseHexByte(hex.substring(0, 2));
}
double[] rgb = new double[] {
parseHexByte(hex.substring(offset, offset + 2)),
parseHexByte(hex.substring(offset + 2, offset + 4)),
parseHexByte(hex.substring(offset + 4, offset + 6))
};
return new Operand(rgb, alpha, hasAlpha, true);
}
private static double parseHexByte(String value) {
return Integer.parseInt(value, 16);
}
private static int clampChannel(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
return 0;
}
if (value <= 0d) {
return 0;
}
if (value >= 255d) {
return 255;
}
return (int) Math.round(value);
}
private static boolean startsWithOperator(String value, int start) {
if (start < 0 || start >= value.length()) {
return false;
}
char c = value.charAt(start);
return c == '+' || c == '-' || c == '*' || c == '/';
}
private static int findVariantSplit(String value) {
if (TextUtils.isEmpty(value)) {
return -1;
}
boolean quoted = false;
private static int findTopLevelPipe(String value) {
boolean inVector = false;
int split = -1;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\'') {
quoted = !quoted;
if (inVector) {
if (c == ']') {
inVector = false;
}
continue;
}
if (!quoted && c == '|') {
return i;
}
if (c == '[') {
inVector = true;
continue;
}
if (c == '|') {
if (split >= 0) {
return -1;
}
private static boolean isDark(int color) {
double brightness = (Color.red(color) * 299d
+ Color.green(color) * 587d
+ Color.blue(color) * 114d) / 1000d;
return brightness < 128d;
}
private static String hexOperandPattern() {
return "#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})";
}
private static final class LeadingColour {
final int color;
final int endIndex;
LeadingColour(int color, int endIndex) {
this.color = color;
this.endIndex = endIndex;
split = i;
}
}
private static final class Operand {
final double[] rgb;
final double alpha;
final boolean hasAlpha;
final boolean isHex;
Operand(double[] rgb, double alpha, boolean hasAlpha, boolean isHex) {
this.rgb = rgb;
this.alpha = alpha;
this.hasAlpha = hasAlpha;
this.isHex = isHex;
return split;
}
private static String hexFor(int color) {
if (Color.alpha(color) >= 255) {
return String.format(java.util.Locale.ROOT, "#%06X", color & 0xFFFFFF);
}
return String.format(java.util.Locale.ROOT, "#%08X", color);
}
}
@@ -64,6 +64,7 @@ public final class SbtSettings {
public static final String KEY_STATUS_CHIPS_HIDE_MEDIA_UNLOCKED = "status_chips_hide_media_unlocked";
public static final String KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED = "status_chips_hide_nav_unlocked";
public static final String KEY_STATUS_CHIPS_HIDE_CALL = "status_chips_hide_call";
public static final String KEY_STATUS_CHIPS_HIDE_BATTERY = "status_chips_hide_battery";
public static final String KEY_AOD_KEEP_VISIBLE_DURING_CALL = "aod_keep_visible_during_call";
public static final String KEY_BATTERY_LOCKSCREEN_UNPLUGGED_PERCENT = "battery_lockscreen_unplugged_percent";
public static final String KEY_BATTERY_AOD_UNPLUGGED_PERCENT = "battery_aod_unplugged_percent";
@@ -106,6 +107,7 @@ public final class SbtSettings {
public static final String KEY_DRAWER_DATE_CUSTOM_FORMAT_ENABLED =
"drawer_date_custom_format_enabled";
public static final String KEY_DRAWER_DATE_CUSTOM_FORMAT = "drawer_date_custom_format";
public static final String KEY_CLOCK_STORED_PATTERNS = "clock_stored_patterns";
public static final String KEY_CLOCK_IGNORE_UNDER_DISPLAY_CAMERAS = "clock_ignore_under_display_cameras";
public static final String KEY_CLOCK_CAMERA_TYPE_OVERRIDES = "clock_camera_type_overrides";
public static final String KEY_LAYOUT_PADDING_CUTOUT_PX = "layout_padding_cutout_px";
@@ -408,6 +410,7 @@ public final class SbtSettings {
public final boolean statusChipsHideMediaUnlocked;
public final boolean statusChipsHideNavUnlocked;
public final boolean statusChipsHideCallUnlocked;
public final boolean statusChipsHideBattery;
public final Map<String, Integer> appIconBlockedModes;
public final Map<String, ArrayList<AppIconRules.ExceptionRule>> appIconExceptionRules;
public final String lockedNotificationMode;
@@ -540,6 +543,7 @@ public final class SbtSettings {
boolean statusChipsHideMediaUnlocked,
boolean statusChipsHideNavUnlocked,
boolean statusChipsHideCallUnlocked,
boolean statusChipsHideBattery,
Map<String, Integer> appIconBlockedModes,
Map<String, ArrayList<AppIconRules.ExceptionRule>> appIconExceptionRules,
String lockedNotificationMode,
@@ -827,6 +831,7 @@ public final class SbtSettings {
this.statusChipsHideMediaUnlocked = statusChipsHideMediaUnlocked;
this.statusChipsHideNavUnlocked = statusChipsHideNavUnlocked;
this.statusChipsHideCallUnlocked = statusChipsHideCallUnlocked;
this.statusChipsHideBattery = statusChipsHideBattery;
this.appIconBlockedModes = appIconBlockedModes != null
? Collections.unmodifiableMap(new HashMap<>(appIconBlockedModes))
: Collections.emptyMap();
@@ -975,6 +980,7 @@ public final class SbtSettings {
false,
false,
false,
false,
Collections.emptyMap(),
Collections.emptyMap(),
"dot",
@@ -1124,6 +1130,29 @@ public final class SbtSettings {
}
}
public static void setClockCameraDebugState(Context context,
String cameraId,
String autoType,
String effectiveType) {
if (context == null || MODULE_PACKAGE.equals(context.getPackageName()) || !hasSettingsProvider(context)) {
return;
}
try {
Bundle extras = new Bundle();
extras.putString(KEY_DEBUG_CURRENT_CAMERA_ID, cameraId != null ? cameraId : "");
extras.putString(KEY_DEBUG_CURRENT_CAMERA_AUTO_TYPE, autoType != null ? autoType : "");
extras.putString(KEY_DEBUG_CURRENT_CAMERA_EFFECTIVE_TYPE,
effectiveType != null ? effectiveType : "");
context.getContentResolver()
.call(settingsProviderUri(),
SbtSettingsProvider.METHOD_SET_CLOCK_CAMERA_DEBUG_STATE,
null,
extras);
} catch (Throwable ignored) {
// Debug camera metadata is advisory UI state only.
}
}
private static boolean hasSettingsProvider(Context context) {
if (context == null) {
return false;
@@ -1422,6 +1451,7 @@ public final class SbtSettings {
prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_MEDIA_UNLOCKED, false),
prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED, false),
prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_CALL, false),
prefs.getBoolean(KEY_STATUS_CHIPS_HIDE_BATTERY, false),
AppIconRules.parseBlockedModes(readStringSetFromPrefs(
prefs,
KEY_APP_ICON_BLOCKED_MODES)),
@@ -1740,6 +1770,7 @@ public final class SbtSettings {
bundle.getBoolean(KEY_STATUS_CHIPS_HIDE_MEDIA_UNLOCKED, false),
bundle.getBoolean(KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED, false),
bundle.getBoolean(KEY_STATUS_CHIPS_HIDE_CALL, false),
bundle.getBoolean(KEY_STATUS_CHIPS_HIDE_BATTERY, false),
AppIconRules.parseBlockedModes(readStringSetFromBundle(
bundle,
KEY_APP_ICON_BLOCKED_MODES)),
@@ -412,6 +412,8 @@ public class SbtSettingsProvider extends ContentProvider {
prefs.getBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_NAV_UNLOCKED, false));
out.putBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_CALL,
prefs.getBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_CALL, false));
out.putBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_BATTERY,
prefs.getBoolean(SbtSettings.KEY_STATUS_CHIPS_HIDE_BATTERY, false));
putStringCollectionArrayList(
out,
SbtSettings.KEY_APP_ICON_BLOCKED_MODES,
@@ -3,7 +3,11 @@ package se.ajpanton.statusbartweak.shell.ui;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
@@ -32,6 +36,7 @@ import com.google.android.material.switchmaterial.SwitchMaterial;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import se.ajpanton.statusbartweak.R;
import se.ajpanton.statusbartweak.shell.settings.BatteryBarGeometry;
@@ -80,6 +85,8 @@ public final class BatteryBarFragment extends Fragment {
TextView maxLevelLabel = root.findViewById(R.id.battery_bar_max_level_label);
MaterialButton defaultDischargeButton = root.findViewById(R.id.battery_bar_default_discharge_button);
MaterialButton defaultChargeButton = root.findViewById(R.id.battery_bar_default_charge_button);
TextView colourHelpToggle = root.findViewById(R.id.battery_bar_colour_help_toggle);
TextView colourHelp = root.findViewById(R.id.battery_bar_colour_help);
MaterialButton addThresholdButton = root.findViewById(R.id.battery_bar_add_threshold_button);
LinearLayout thresholdsContainer = root.findViewById(R.id.battery_bar_thresholds_container);
View geometrySection = root.findViewById(R.id.battery_bar_geometry_section);
@@ -145,6 +152,11 @@ public final class BatteryBarFragment extends Fragment {
SbtSettings.KEY_BATTERY_BAR_DEFAULT_CHARGE_COLOR,
SbtDefaults.BATTERY_BAR_DEFAULT_CHARGE_COLOR_DEFAULT),
R.string.battery_bar_colour_same_as_default);
bindExpandableHelp(
colourHelpToggle,
colourHelp,
R.string.battery_bar_colour_help_show,
R.string.battery_bar_colour_help_hide);
enabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
prefs.edit().putBoolean(SbtSettings.KEY_BATTERY_BAR_ENABLED, isChecked).apply();
@@ -270,15 +282,129 @@ public final class BatteryBarFragment extends Fragment {
return;
}
String normalised = BatteryBarStyle.normalizeColor(colour);
String value;
CharSequence value;
int backgroundColor = Color.TRANSPARENT;
boolean hasBackground = false;
if (BatteryBarStyle.isThresholdChargeDefault(colour)) {
value = getString(R.string.battery_bar_colour_same_as_default);
} else if (normalised.isEmpty()) {
value = getString(emptyLabelRes);
} else {
value = normalised;
value = displayColourValue(normalised);
backgroundColor = resolvePreviewColour(normalised);
hasBackground = true;
}
button.setText(getString(labelRes) + ": " + value);
SpannableStringBuilder label = new SpannableStringBuilder();
label.append(compactColourLabel(labelRes));
label.append(":\n");
label.append(value);
button.setText(label);
if (!hasBackground) {
button.setBackgroundTintList(null);
button.setTextColor(ContextCompat.getColor(requireContext(), R.color.sbt_on_surface));
} else {
button.setBackgroundTintList(ColorStateList.valueOf(backgroundColor));
button.setTextColor(contrastTextColor(backgroundColor));
}
}
private String compactColourLabel(int labelRes) {
String label = getString(labelRes).toLowerCase(Locale.ROOT);
if (label.contains("discharge")) {
return getString(R.string.battery_bar_button_label_discharge);
}
return getString(R.string.battery_bar_button_label_charge);
}
private CharSequence displayColourValue(String expression) {
String normalised = BatteryBarStyle.normalizeColor(expression);
if (normalised.isEmpty()) {
return "";
}
SpannableStringBuilder out = new SpannableStringBuilder();
appendDisplayHex(out, resolveExpressionHex(normalised, Color.WHITE));
if (hasTintVariant(normalised)) {
out.append(" ; ");
appendDisplayHex(out, resolveExpressionHex(normalised, Color.BLACK));
}
return out;
}
private void appendDisplayHex(SpannableStringBuilder out, String hex) {
int start = out.length();
out.append(hex);
if (hex != null && hex.length() == 9) {
out.setSpan(new UnderlineSpan(), start + 1, start + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
private String resolveExpressionHex(String expression, int referenceColor) {
int fallback = Color.WHITE;
int resolved = se.ajpanton.statusbartweak.shell.settings.ColourExpressionSupport.resolveColor(
expression,
referenceColor,
fallback,
true);
if (Color.alpha(resolved) >= 255) {
return String.format(Locale.ROOT, "#%06X", resolved & 0xFFFFFF);
}
return String.format(Locale.ROOT, "#%08X", resolved);
}
private boolean hasTintVariant(String expression) {
if (expression == null) {
return false;
}
boolean inVector = false;
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (inVector) {
if (c == ']') {
inVector = false;
}
continue;
}
if (c == '[') {
inVector = true;
continue;
}
if (c == ';' || c == '|') {
return true;
}
}
return false;
}
private int resolvePreviewColour(String expression) {
return se.ajpanton.statusbartweak.shell.settings.ColourExpressionSupport.resolveColor(
expression,
ContextCompat.getColor(requireContext(), R.color.sbt_on_surface),
Color.WHITE,
true);
}
private int contrastTextColor(int backgroundColor) {
int alpha = Color.alpha(backgroundColor);
int red = compositeChannel(Color.red(backgroundColor), alpha, 255);
int green = compositeChannel(Color.green(backgroundColor), alpha, 255);
int blue = compositeChannel(Color.blue(backgroundColor), alpha, 255);
double luminance = (0.299d * red + 0.587d * green + 0.114d * blue) / 255d;
return luminance > 0.55d ? Color.BLACK : Color.WHITE;
}
private int compositeChannel(int source, int alpha, int destination) {
return Math.round((source * alpha + destination * (255 - alpha)) / 255f);
}
private void bindExpandableHelp(TextView toggle, TextView content, int showRes, int hideRes) {
if (toggle == null || content == null) {
return;
}
toggle.setOnClickListener(v -> {
boolean show = content.getVisibility() != View.VISIBLE;
content.setVisibility(show ? View.VISIBLE : View.GONE);
toggle.setText(show ? hideRes : showRes);
});
}
private void trimMappingStepButton(MaterialButton button) {
@@ -1,6 +1,7 @@
package se.ajpanton.statusbartweak.shell.ui;
import se.ajpanton.statusbartweak.R;
import se.ajpanton.statusbartweak.runtime.features.clock.ClockPatternPreviewRenderer;
import se.ajpanton.statusbartweak.shell.settings.SbtDefaults;
import se.ajpanton.statusbartweak.shell.settings.SbtSettings;
@@ -8,6 +9,9 @@ import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
@@ -30,18 +34,49 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public final class ClockFragment extends Fragment {
private static final String PATTERN_ORIGIN_STATUSBAR = "statusbar";
private static final String PATTERN_ORIGIN_DRAWER_CLOCK = "drawer_clock";
private static final String PATTERN_ORIGIN_DRAWER_DATE = "drawer_date";
private static final int COLOR_STATUSBAR = 0xffe85050;
private static final int COLOR_DRAWER_CLOCK = 0xff4caf50;
private static final int COLOR_DRAWER_DATE = 0xff4f8cff;
private static final int CARD_STROKE_DP = 2;
private final ArrayList<PreviewBinding> previewBindings = new ArrayList<>();
private final ArrayList<StoredPatternBinding> storedPatternBindings = new ArrayList<>();
private final ArrayList<StoredPatternRowBinding> storedPatternRowBindings = new ArrayList<>();
private final Runnable previewTicker = new Runnable() {
@Override
public void run() {
boolean needsNextTick = false;
HashMap<String, ClockPatternPreviewRenderer.Result> renderCache = new HashMap<>();
for (PreviewBinding binding : previewBindings) {
needsNextTick |= updatePreview(binding);
}
for (StoredPatternRowBinding binding : storedPatternRowBindings) {
needsNextTick |= updateStoredPatternPreview(binding, renderCache);
}
if (needsNextTick && getView() != null) {
getView().postDelayed(this, nextSecondDelayMillis());
}
}
};
@Nullable
@Override
@@ -52,22 +87,35 @@ public final class ClockFragment extends Fragment {
SharedPreferences prefs = requireContext()
.getSharedPreferences(SbtSettings.PREFS_NAME, Context.MODE_PRIVATE);
MaterialCardView customFormatCard = root.findViewById(R.id.clock_custom_format_card);
CheckBox customFormatEnabled = root.findViewById(R.id.clock_custom_format_enabled);
View customFormatContainer = root.findViewById(R.id.clock_custom_format_container);
EditText customFormatInput = root.findViewById(R.id.clock_custom_format_input);
ClockPatternPreviewView customFormatPreview =
root.findViewById(R.id.clock_custom_format_preview);
MaterialCardView drawerClockCustomFormatCard =
root.findViewById(R.id.drawer_clock_custom_format_card);
CheckBox drawerClockCustomFormatEnabled =
root.findViewById(R.id.drawer_clock_custom_format_enabled);
View drawerClockCustomFormatContainer =
root.findViewById(R.id.drawer_clock_custom_format_container);
EditText drawerClockCustomFormatInput =
root.findViewById(R.id.drawer_clock_custom_format_input);
ClockPatternPreviewView drawerClockCustomFormatPreview =
root.findViewById(R.id.drawer_clock_custom_format_preview);
MaterialCardView drawerDateCustomFormatCard =
root.findViewById(R.id.drawer_date_custom_format_card);
CheckBox drawerDateCustomFormatEnabled =
root.findViewById(R.id.drawer_date_custom_format_enabled);
View drawerDateCustomFormatContainer =
root.findViewById(R.id.drawer_date_custom_format_container);
EditText drawerDateCustomFormatInput =
root.findViewById(R.id.drawer_date_custom_format_input);
ClockPatternPreviewView drawerDateCustomFormatPreview =
root.findViewById(R.id.drawer_date_custom_format_preview);
MaterialButton fontPickerButton = root.findViewById(R.id.clock_font_picker_button);
MaterialButton restoreStoredPatternsButton =
root.findViewById(R.id.clock_restore_stored_patterns_button);
TextView customFormatHelpToggle = root.findViewById(R.id.clock_custom_format_help_toggle);
View customFormatHelpContainer = root.findViewById(R.id.clock_custom_format_help_container);
TextView customFormatHelpCommon = root.findViewById(R.id.clock_custom_format_help);
@@ -94,27 +142,54 @@ public final class ClockFragment extends Fragment {
SbtSettings.KEY_DRAWER_DATE_CUSTOM_FORMAT,
SbtDefaults.DRAWER_DATE_CUSTOM_FORMAT_DEFAULT);
customFormatEnabled.setChecked(customFormatEnabledValue);
customFormatInput.setText(customFormatValue);
updateCustomFormatVisibility(customFormatContainer, customFormatEnabledValue);
previewBindings.clear();
storedPatternBindings.clear();
ensureDefaultStoredPatterns(prefs);
bindCustomFormat(
prefs,
customFormatCard,
customFormatEnabled,
customFormatContainer,
customFormatInput,
customFormatPreview,
PATTERN_ORIGIN_STATUSBAR,
COLOR_STATUSBAR,
SbtSettings.KEY_CLOCK_CUSTOM_FORMAT_ENABLED,
SbtSettings.KEY_CLOCK_CUSTOM_FORMAT,
customFormatEnabledValue,
customFormatValue,
18f,
true);
bindCustomFormat(
prefs,
drawerClockCustomFormatCard,
drawerClockCustomFormatEnabled,
drawerClockCustomFormatContainer,
drawerClockCustomFormatInput,
drawerClockCustomFormatPreview,
PATTERN_ORIGIN_DRAWER_CLOCK,
COLOR_DRAWER_CLOCK,
SbtSettings.KEY_DRAWER_CLOCK_CUSTOM_FORMAT_ENABLED,
SbtSettings.KEY_DRAWER_CLOCK_CUSTOM_FORMAT,
drawerClockCustomFormatEnabledValue,
drawerClockCustomFormatValue);
drawerClockCustomFormatValue,
24f,
false);
bindCustomFormat(
prefs,
drawerDateCustomFormatCard,
drawerDateCustomFormatEnabled,
drawerDateCustomFormatContainer,
drawerDateCustomFormatInput,
drawerDateCustomFormatPreview,
PATTERN_ORIGIN_DRAWER_DATE,
COLOR_DRAWER_DATE,
SbtSettings.KEY_DRAWER_DATE_CUSTOM_FORMAT_ENABLED,
SbtSettings.KEY_DRAWER_DATE_CUSTOM_FORMAT,
drawerDateCustomFormatEnabledValue,
drawerDateCustomFormatValue);
drawerDateCustomFormatValue,
16f,
false);
updateCustomFormatHelpVisibility(customFormatHelpContainer, customFormatHelpToggle, false);
applyBulletText(customFormatHelpCommon);
applyBulletText(customFormatHelpStyling);
@@ -123,12 +198,6 @@ public final class ClockFragment extends Fragment {
customFormatHelpLink.setMovementMethod(LinkMovementMethod.getInstance());
}
customFormatEnabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
updateCustomFormatVisibility(customFormatContainer, isChecked);
prefs.edit().putBoolean(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT_ENABLED, isChecked).apply();
SbtSettings.ensureReadable(requireContext());
});
if (customFormatHelpToggle != null) {
customFormatHelpToggle.setOnClickListener(v -> updateCustomFormatHelpVisibility(
customFormatHelpContainer,
@@ -136,27 +205,15 @@ public final class ClockFragment extends Fragment {
customFormatHelpContainer == null || customFormatHelpContainer.getVisibility() != View.VISIBLE));
}
customFormatInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
prefs.edit()
.putString(SbtSettings.KEY_CLOCK_CUSTOM_FORMAT, s != null ? s.toString() : "")
.apply();
SbtSettings.ensureReadable(requireContext());
}
});
if (fontPickerButton != null) {
fontPickerButton.setOnClickListener(v -> showFontPickerDialog());
}
if (restoreStoredPatternsButton != null) {
restoreStoredPatternsButton.setOnClickListener(v -> {
persistStoredPatterns(prefs, mergeDefaultPatterns(loadStoredPatterns(prefs)));
renderAllStoredPatternLists(prefs);
});
}
return root;
}
@@ -169,23 +226,53 @@ public final class ClockFragment extends Fragment {
}
private void bindCustomFormat(SharedPreferences prefs,
MaterialCardView card,
CheckBox enabledView,
View container,
EditText input,
ClockPatternPreviewView preview,
String origin,
int accentColor,
String enabledKey,
String formatKey,
boolean enabled,
String format) {
String format,
float previewTextSizeSp,
boolean multilinePreview) {
if (enabledView == null || input == null) {
return;
}
styleClockCard(card, accentColor);
styleBorderedView(input, accentColor, 6, 8, 6);
styleBorderedView(preview, accentColor, 8, 10, 8);
enabledView.setChecked(enabled);
input.setText(format != null ? format : "");
if (preview != null) {
preview.setPreviewTextAppearance(
requireContext().getColor(R.color.sbt_on_surface),
previewTextSizeSp);
}
updateCustomFormatVisibility(container, enabled);
PreviewBinding binding = new PreviewBinding(enabledView, input, preview, multilinePreview);
previewBindings.add(binding);
StoredPatternBinding storedBinding = createStoredPatternSection(
prefs,
container,
input,
origin,
accentColor,
multilinePreview);
if (storedBinding != null) {
storedPatternBindings.add(storedBinding);
renderStoredPatternList(prefs, storedBinding);
}
updatePreview(binding);
enabledView.setOnCheckedChangeListener((buttonView, isChecked) -> {
updateCustomFormatVisibility(container, isChecked);
prefs.edit().putBoolean(enabledKey, isChecked).apply();
SbtSettings.ensureReadable(requireContext());
updatePreview(binding);
schedulePreviewTickerIfNeeded();
});
input.addTextChangedListener(new TextWatcher() {
@Override
@@ -202,10 +289,501 @@ public final class ClockFragment extends Fragment {
.putString(formatKey, s != null ? s.toString() : "")
.apply();
SbtSettings.ensureReadable(requireContext());
updatePreview(binding);
schedulePreviewTickerIfNeeded();
}
});
}
private void styleClockCard(MaterialCardView card, int accentColor) {
if (card == null) {
return;
}
card.setStrokeWidth(ViewTreeSupport.dp(card.getContext(), CARD_STROKE_DP));
card.setStrokeColor(accentColor);
}
private void styleBorderedView(View view,
int accentColor,
int radiusDp,
int horizontalPaddingDp,
int verticalPaddingDp) {
if (view == null) {
return;
}
Context context = view.getContext();
GradientDrawable background = new GradientDrawable();
background.setColor(Color.TRANSPARENT);
background.setCornerRadius(ViewTreeSupport.dp(context, radiusDp));
background.setStroke(ViewTreeSupport.dp(context, CARD_STROKE_DP), accentColor);
view.setBackground(background);
view.setPadding(
ViewTreeSupport.dp(context, horizontalPaddingDp),
ViewTreeSupport.dp(context, verticalPaddingDp),
ViewTreeSupport.dp(context, horizontalPaddingDp),
ViewTreeSupport.dp(context, verticalPaddingDp));
}
private StoredPatternBinding createStoredPatternSection(
SharedPreferences prefs,
View container,
EditText input,
String origin,
int accentColor,
boolean multilinePreview
) {
if (!(container instanceof LinearLayout parent) || input == null) {
return null;
}
Context context = parent.getContext();
MaterialButton toggle = new MaterialButton(
context,
null,
com.google.android.material.R.attr.materialButtonOutlinedStyle);
toggle.setText(R.string.clock_stored_patterns_show);
LinearLayout.LayoutParams toggleParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
toggleParams.topMargin = ViewTreeSupport.dp(context, 12);
parent.addView(toggle, toggleParams);
LinearLayout section = new LinearLayout(context);
section.setOrientation(LinearLayout.VERTICAL);
section.setVisibility(View.GONE);
parent.addView(section, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
TextView hint = new TextView(context);
hint.setText(R.string.clock_stored_patterns_hint);
hint.setTextAppearance(android.R.style.TextAppearance_Material_Body2);
LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
hintParams.topMargin = ViewTreeSupport.dp(context, 8);
section.addView(hint, hintParams);
LinearLayout list = new LinearLayout(context);
list.setOrientation(LinearLayout.VERTICAL);
section.addView(list, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
MaterialButton storeButton = new MaterialButton(
context,
null,
com.google.android.material.R.attr.materialButtonOutlinedStyle);
storeButton.setText(R.string.clock_store_current_pattern);
LinearLayout.LayoutParams storeParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
storeParams.topMargin = ViewTreeSupport.dp(context, 8);
section.addView(storeButton, storeParams);
StoredPatternBinding binding = new StoredPatternBinding(
input,
origin,
accentColor,
multilinePreview,
toggle,
section,
list);
toggle.setOnClickListener(v -> {
boolean show = section.getVisibility() != View.VISIBLE;
section.setVisibility(show ? View.VISIBLE : View.GONE);
toggle.setText(show
? R.string.clock_stored_patterns_hide
: R.string.clock_stored_patterns_show);
if (show) {
renderStoredPatternList(prefs, binding);
} else {
removeStoredPatternRowsFor(binding);
list.removeAllViews();
schedulePreviewTickerIfNeeded();
}
});
storeButton.setOnClickListener(v -> {
String pattern = input.getText() != null ? input.getText().toString() : "";
storePattern(prefs, pattern, origin);
renderAllStoredPatternLists(prefs);
});
return binding;
}
private void renderAllStoredPatternLists(SharedPreferences prefs) {
for (StoredPatternBinding binding : storedPatternBindings) {
renderStoredPatternList(prefs, binding);
}
}
private void renderStoredPatternList(SharedPreferences prefs, StoredPatternBinding binding) {
if (binding == null || binding.listContainer == null) {
return;
}
Context context = binding.listContainer.getContext();
removeStoredPatternRowsFor(binding);
binding.listContainer.removeAllViews();
if (binding.section == null || binding.section.getVisibility() != View.VISIBLE) {
schedulePreviewTickerIfNeeded();
return;
}
ArrayList<StoredPattern> patterns = loadStoredPatterns(prefs);
for (StoredPattern pattern : patterns) {
binding.listContainer.addView(createStoredPatternRow(context, prefs, binding, pattern));
}
schedulePreviewTickerIfNeeded();
}
private View createStoredPatternRow(
Context context,
SharedPreferences prefs,
StoredPatternBinding binding,
StoredPattern pattern
) {
LinearLayout row = new LinearLayout(context);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setGravity(android.view.Gravity.CENTER_VERTICAL);
LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rowParams.topMargin = ViewTreeSupport.dp(context, 8);
row.setLayoutParams(rowParams);
ClockPatternPreviewView preview = new ClockPatternPreviewView(context);
preview.setPreviewTextAppearance(
requireContext().getColor(R.color.sbt_on_surface),
previewTextSizeForOrigin(pattern.origin));
styleBorderedView(preview, colorForOrigin(pattern.origin), 8, 10, 8);
StoredPatternRowBinding rowBinding = new StoredPatternRowBinding(
binding,
preview,
pattern.pattern,
normaliseOrigin(pattern.origin),
binding.multilinePreview);
storedPatternRowBindings.add(rowBinding);
updateStoredPatternPreview(rowBinding, new HashMap<>());
preview.setOnClickListener(v -> {
binding.input.setText(pattern.pattern);
binding.input.setSelection(binding.input.getText() != null
? binding.input.getText().length()
: 0);
});
row.addView(preview, new LinearLayout.LayoutParams(
0,
ViewGroup.LayoutParams.WRAP_CONTENT,
1f));
MaterialButton deleteButton = new MaterialButton(context);
deleteButton.setText("×");
deleteButton.setTextColor(Color.WHITE);
deleteButton.setBackgroundTintList(android.content.res.ColorStateList.valueOf(
ContextCompat.getColor(context, R.color.sbt_danger)));
deleteButton.setMinWidth(0);
deleteButton.setMinHeight(0);
deleteButton.setPadding(0, 0, 0, 0);
deleteButton.setOnClickListener(v -> {
deleteStoredPattern(prefs, pattern.pattern);
renderAllStoredPatternLists(prefs);
});
LinearLayout.LayoutParams deleteParams = new LinearLayout.LayoutParams(
ViewTreeSupport.dp(context, 44),
ViewTreeSupport.dp(context, 44));
deleteParams.leftMargin = ViewTreeSupport.dp(context, 8);
row.addView(deleteButton, deleteParams);
return row;
}
private void removeStoredPatternRowsFor(StoredPatternBinding binding) {
for (int i = storedPatternRowBindings.size() - 1; i >= 0; i--) {
if (storedPatternRowBindings.get(i).owner == binding) {
storedPatternRowBindings.remove(i);
}
}
}
private void ensureDefaultStoredPatterns(SharedPreferences prefs) {
if (prefs == null || prefs.contains(SbtSettings.KEY_CLOCK_STORED_PATTERNS)) {
return;
}
persistStoredPatterns(prefs, defaultStoredPatterns());
}
private ArrayList<StoredPattern> mergeDefaultPatterns(ArrayList<StoredPattern> current) {
ArrayList<StoredPattern> result = current != null ? current : new ArrayList<>();
for (StoredPattern pattern : defaultStoredPatterns()) {
upsertPattern(result, pattern.pattern, pattern.origin);
}
return result;
}
private ArrayList<StoredPattern> defaultStoredPatterns() {
ArrayList<StoredPattern> patterns = new ArrayList<>();
patterns.add(new StoredPattern("H:mm:ss", PATTERN_ORIGIN_STATUSBAR));
patterns.add(new StoredPattern("{big}H:mm:{/big color(#batterybar)}ss", PATTERN_ORIGIN_STATUSBAR));
patterns.add(new StoredPattern(
"{@sans-serif-condensed-light color(#fff;#000)}|d{\\n30 big}H:mm:|{/big color(#batterybar invRGB 0.5 *RGB invRGB;#batterybar 0.5 *RGB)}ss",
PATTERN_ORIGIN_STATUSBAR));
patterns.add(new StoredPattern("{@sans-serif-condensed-light}H:mm:{small}ss", PATTERN_ORIGIN_DRAWER_CLOCK));
patterns.add(new StoredPattern("EEE, d MMM", PATTERN_ORIGIN_DRAWER_DATE));
patterns.add(new StoredPattern("EEE, MMM d", PATTERN_ORIGIN_DRAWER_DATE));
patterns.add(new StoredPattern("{@sans-serif-condensed-light}EEEE, MMMM d", PATTERN_ORIGIN_DRAWER_DATE));
patterns.add(new StoredPattern("{@sans-serif-condensed-light}EEEE, d MMMM", PATTERN_ORIGIN_DRAWER_DATE));
return patterns;
}
private void storePattern(SharedPreferences prefs, String pattern, String origin) {
String value = pattern != null ? pattern.trim() : "";
if (value.isEmpty()) {
return;
}
ArrayList<StoredPattern> patterns = loadStoredPatterns(prefs);
upsertPattern(patterns, value, origin);
persistStoredPatterns(prefs, patterns);
}
private void upsertPattern(ArrayList<StoredPattern> patterns, String pattern, String origin) {
if (patterns == null || pattern == null || pattern.trim().isEmpty()) {
return;
}
String value = pattern.trim();
String resolvedOrigin = normaliseOrigin(origin);
for (int i = 0; i < patterns.size(); i++) {
StoredPattern existing = patterns.get(i);
if (existing != null && value.equals(existing.pattern)) {
patterns.set(i, new StoredPattern(value, resolvedOrigin));
return;
}
}
patterns.add(new StoredPattern(value, resolvedOrigin));
}
private void deleteStoredPattern(SharedPreferences prefs, String pattern) {
ArrayList<StoredPattern> patterns = loadStoredPatterns(prefs);
for (int i = patterns.size() - 1; i >= 0; i--) {
StoredPattern existing = patterns.get(i);
if (existing != null && existing.pattern.equals(pattern)) {
patterns.remove(i);
}
}
persistStoredPatterns(prefs, patterns);
}
private ArrayList<StoredPattern> loadStoredPatterns(SharedPreferences prefs) {
ArrayList<StoredPattern> patterns = new ArrayList<>();
if (prefs == null) {
return patterns;
}
String encoded = prefs.getString(SbtSettings.KEY_CLOCK_STORED_PATTERNS, "");
if (encoded == null || encoded.isEmpty()) {
return patterns;
}
String[] lines = encoded.split("\\n", -1);
for (String line : lines) {
StoredPattern pattern = decodeStoredPattern(line);
if (pattern == null) {
continue;
}
upsertPattern(patterns, pattern.pattern, pattern.origin);
}
return patterns;
}
private void persistStoredPatterns(SharedPreferences prefs, ArrayList<StoredPattern> patterns) {
if (prefs == null) {
return;
}
StringBuilder encoded = new StringBuilder();
if (patterns != null) {
for (StoredPattern pattern : patterns) {
if (pattern == null || pattern.pattern == null || pattern.pattern.trim().isEmpty()) {
continue;
}
if (encoded.length() > 0) {
encoded.append('\n');
}
encoded.append(normaliseOrigin(pattern.origin))
.append('|')
.append(Uri.encode(pattern.pattern));
}
}
prefs.edit().putString(SbtSettings.KEY_CLOCK_STORED_PATTERNS, encoded.toString()).apply();
}
private StoredPattern decodeStoredPattern(String line) {
if (line == null || line.isEmpty()) {
return null;
}
int split = line.indexOf('|');
if (split <= 0 || split >= line.length() - 1) {
return null;
}
String origin = normaliseOrigin(line.substring(0, split));
String pattern = Uri.decode(line.substring(split + 1));
if (pattern == null || pattern.trim().isEmpty()) {
return null;
}
return new StoredPattern(pattern.trim(), origin);
}
private String normaliseOrigin(String origin) {
if (PATTERN_ORIGIN_DRAWER_CLOCK.equals(origin)
|| PATTERN_ORIGIN_DRAWER_DATE.equals(origin)
|| PATTERN_ORIGIN_STATUSBAR.equals(origin)) {
return origin;
}
return PATTERN_ORIGIN_STATUSBAR;
}
private int colorForOrigin(String origin) {
switch (normaliseOrigin(origin)) {
case PATTERN_ORIGIN_DRAWER_CLOCK:
return COLOR_DRAWER_CLOCK;
case PATTERN_ORIGIN_DRAWER_DATE:
return COLOR_DRAWER_DATE;
case PATTERN_ORIGIN_STATUSBAR:
default:
return COLOR_STATUSBAR;
}
}
private float previewTextSizeForOrigin(String origin) {
switch (normaliseOrigin(origin)) {
case PATTERN_ORIGIN_DRAWER_CLOCK:
return 24f;
case PATTERN_ORIGIN_DRAWER_DATE:
return 16f;
case PATTERN_ORIGIN_STATUSBAR:
default:
return 18f;
}
}
private boolean updatePreview(PreviewBinding binding) {
if (binding == null || binding.preview == null) {
return false;
}
boolean enabled = binding.enabled != null && binding.enabled.isChecked();
String pattern = binding.input != null && binding.input.getText() != null
? binding.input.getText().toString()
: "";
if (!enabled || pattern.isEmpty()) {
binding.preview.setVisibility(View.GONE);
binding.preview.setPreview(null);
binding.preview.setContentDescription("");
return false;
}
ClockPatternPreviewRenderer.Result result = ClockPatternPreviewRenderer.render(
binding.preview.getContext(),
pattern,
binding.preview.getPreviewTextColor());
if (!binding.multilinePreview) {
result = flattenRows(result);
}
binding.preview.setPreview(result);
binding.preview.setVisibility(result.rows().isEmpty() ? View.GONE : View.VISIBLE);
binding.preview.setContentDescription(result.contentDescription());
return result.containsSeconds();
}
private boolean updateStoredPatternPreview(
StoredPatternRowBinding binding,
Map<String, ClockPatternPreviewRenderer.Result> cache
) {
if (binding == null
|| binding.preview == null
|| binding.owner == null
|| binding.owner.section == null
|| binding.owner.section.getVisibility() != View.VISIBLE) {
return false;
}
String key = binding.origin + "\u0000" + binding.multilinePreview + "\u0000" + binding.pattern;
ClockPatternPreviewRenderer.Result result = cache != null ? cache.get(key) : null;
if (result == null) {
result = ClockPatternPreviewRenderer.render(
binding.preview.getContext(),
binding.pattern,
binding.preview.getPreviewTextColor());
if (!binding.multilinePreview) {
result = flattenRows(result);
}
if (cache != null) {
cache.put(key, result);
}
}
binding.preview.setPreview(result);
binding.preview.setContentDescription(result.contentDescription());
return result.containsSeconds();
}
private ClockPatternPreviewRenderer.Result flattenRows(ClockPatternPreviewRenderer.Result result) {
if (result == null || result.rows() == null || result.rows().size() <= 1) {
return result;
}
SpannableStringBuilder text = new SpannableStringBuilder();
StringBuilder description = new StringBuilder();
for (int i = 0; i < result.rows().size(); i++) {
ClockPatternPreviewRenderer.Row row = result.rows().get(i);
if (i > 0) {
text.append(' ');
description.append(' ');
}
if (row != null && row.text() != null) {
text.append(row.text());
description.append(row.text());
}
}
ArrayList<ClockPatternPreviewRenderer.Row> rows = new ArrayList<>();
rows.add(new ClockPatternPreviewRenderer.Row(text, "", "", 0, 0));
return new ClockPatternPreviewRenderer.Result(rows, description.toString(), result.containsSeconds());
}
private void schedulePreviewTickerIfNeeded() {
View view = getView();
if (view == null) {
return;
}
view.removeCallbacks(previewTicker);
for (PreviewBinding binding : previewBindings) {
if (updatePreview(binding)) {
view.postDelayed(previewTicker, nextSecondDelayMillis());
return;
}
}
}
private long nextSecondDelayMillis() {
long now = System.currentTimeMillis();
long next = now - (now % 1000L) + 1000L;
return Math.max(1L, next - now);
}
@Override
public void onResume() {
super.onResume();
schedulePreviewTickerIfNeeded();
}
@Override
public void onPause() {
View view = getView();
if (view != null) {
view.removeCallbacks(previewTicker);
}
super.onPause();
}
@Override
public void onDestroyView() {
View view = getView();
if (view != null) {
view.removeCallbacks(previewTicker);
}
previewBindings.clear();
storedPatternBindings.clear();
storedPatternRowBindings.clear();
super.onDestroyView();
}
private void updateCustomFormatHelpVisibility(View helpContainer,
TextView helpToggle,
boolean visible) {
@@ -354,6 +932,32 @@ public final class ClockFragment extends Fragment {
view.setText(builder);
}
private record PreviewBinding(CheckBox enabled, EditText input, ClockPatternPreviewView preview, boolean multilinePreview) {
}
private record StoredPatternBinding(
EditText input,
String origin,
int accentColor,
boolean multilinePreview,
MaterialButton toggle,
View section,
LinearLayout listContainer
) {
}
private record StoredPatternRowBinding(
StoredPatternBinding owner,
ClockPatternPreviewView preview,
String pattern,
String origin,
boolean multilinePreview
) {
}
private record StoredPattern(String pattern, String origin) {
}
private static final class FontFamilyAdapter extends BaseAdapter {
private static final String SAMPLE_PATTERN = "EEEE HH:mm:ss";
@@ -0,0 +1,228 @@
package se.ajpanton.statusbartweak.shell.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import java.util.ArrayList;
import se.ajpanton.statusbartweak.runtime.features.clock.ClockPatternPreviewRenderer;
import se.ajpanton.statusbartweak.shell.settings.SbtDefaults;
public final class ClockPatternPreviewView extends View {
private final TextPaint textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
private final ArrayList<MeasuredRow> measuredRows = new ArrayList<>();
private ClockPatternPreviewRenderer.Result result;
private int textColor;
private float textSizePx;
private int contentWidth;
private int contentHeight;
public ClockPatternPreviewView(Context context) {
super(context);
}
public ClockPatternPreviewView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setPreviewTextAppearance(int color, float sizeSp) {
textColor = color;
textSizePx = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
sizeSp,
getResources().getDisplayMetrics());
textPaint.setColor(textColor);
textPaint.setTextSize(textSizePx);
rebuildMeasurements();
}
public int getPreviewTextColor() {
return textColor;
}
public void setPreview(ClockPatternPreviewRenderer.Result nextResult) {
result = nextResult;
rebuildMeasurements();
}
private void rebuildMeasurements() {
measuredRows.clear();
contentWidth = 0;
contentHeight = 0;
if (result == null || result.rows() == null || result.rows().isEmpty()) {
requestLayout();
invalidate();
return;
}
int leftColumnWidth = 0;
int rightColumnWidth = 0;
int baseRowHeight = measureText("0").height;
for (ClockPatternPreviewRenderer.Row row : result.rows()) {
MeasuredRow measured = measureRow(row);
measuredRows.add(measured);
if (measured.piped) {
leftColumnWidth = Math.max(leftColumnWidth, measured.left.width);
rightColumnWidth = Math.max(rightColumnWidth, measured.right.width);
} else {
contentWidth = Math.max(contentWidth, measured.full.width);
}
}
if (leftColumnWidth > 0 || rightColumnWidth > 0) {
contentWidth = Math.max(contentWidth, leftColumnWidth + rightColumnWidth);
for (MeasuredRow measured : measuredRows) {
measured.leftColumnWidth = leftColumnWidth;
}
}
positionRows(Math.max(1, baseRowHeight));
requestLayout();
invalidate();
}
private MeasuredRow measureRow(ClockPatternPreviewRenderer.Row row) {
if (row != null && row.pipeCount() > 0) {
MeasuredText left = measureText(row.leftText());
MeasuredText right = measureText(row.rightText());
return MeasuredRow.piped(left, right, row.gapBeforePx());
}
return MeasuredRow.full(measureText(row != null ? row.text() : ""), row != null ? row.gapBeforePx() : 0);
}
private MeasuredText measureText(CharSequence text) {
CharSequence safeText = text != null ? text : "";
if (TextUtils.isEmpty(safeText)) {
safeText = " ";
}
int width = Math.max(1, (int) Math.ceil(Layout.getDesiredWidth(safeText, textPaint)));
StaticLayout layout = StaticLayout.Builder
.obtain(safeText, 0, safeText.length(), textPaint, width)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setIncludePad(false)
.setLineSpacing(0f, 1f)
.build();
if (layout.getLineCount() <= 0) {
TextPaint.FontMetricsInt metrics = textPaint.getFontMetricsInt();
int ascent = -metrics.ascent;
int descent = metrics.descent;
return new MeasuredText(layout, width, Math.max(1, ascent + descent), ascent, descent);
}
int baseline = layout.getLineBaseline(0);
int ascent = Math.max(0, baseline - layout.getLineTop(0));
int descent = Math.max(0, layout.getLineBottom(0) - baseline);
return new MeasuredText(layout, width, Math.max(1, ascent + descent), ascent, descent);
}
private void positionRows(int baseRowHeight) {
if (measuredRows.isEmpty()) {
return;
}
int minTop = Integer.MAX_VALUE;
int maxBottom = Integer.MIN_VALUE;
int bottom = 0;
for (int i = 0; i < measuredRows.size(); i++) {
MeasuredRow row = measuredRows.get(i);
if (i == 0) {
bottom = row.height;
} else {
bottom += resolveGapPx(row.gapBeforePx, baseRowHeight);
}
int top = bottom - row.height;
row.drawTop = top;
minTop = Math.min(minTop, top);
maxBottom = Math.max(maxBottom, bottom);
}
for (MeasuredRow row : measuredRows) {
row.drawTop -= minTop;
}
contentHeight = Math.max(1, maxBottom - minTop);
}
private int resolveGapPx(int gapBefore, int baseRowHeight) {
if (gapBefore == ClockPatternPreviewRenderer.ROW_GAP_AUTO) {
return Math.max(1, baseRowHeight);
}
if (gapBefore == 0) {
return 0;
}
int defaultSteps = Math.max(1, SbtDefaults.CLOCK_TEXT_SIZE_STEPS_DEFAULT);
return Math.max(1, Math.round(gapBefore * Math.max(1, baseRowHeight) / (float) defaultSteps));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = getPaddingLeft() + contentWidth + getPaddingRight();
int desiredHeight = getPaddingTop() + contentHeight + getPaddingBottom();
setMeasuredDimension(
resolveSize(desiredWidth, widthMeasureSpec),
resolveSize(desiredHeight, heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (MeasuredRow row : measuredRows) {
int y = getPaddingTop() + row.drawTop;
if (row.piped) {
drawText(canvas, row.left, getPaddingLeft() + row.leftColumnWidth - row.left.width, y + row.ascent - row.left.ascent);
drawText(canvas, row.right, getPaddingLeft() + row.leftColumnWidth, y + row.ascent - row.right.ascent);
} else {
drawText(canvas, row.full, getPaddingLeft(), y);
}
}
}
private void drawText(Canvas canvas, MeasuredText text, int left, int top) {
if (text == null || text.layout == null) {
return;
}
int save = canvas.save();
canvas.translate(left, top);
text.layout.draw(canvas);
canvas.restoreToCount(save);
}
private static final class MeasuredRow {
final boolean piped;
final MeasuredText full;
final MeasuredText left;
final MeasuredText right;
final int height;
final int ascent;
final int descent;
final int gapBeforePx;
int leftColumnWidth;
int drawTop;
private MeasuredRow(boolean piped, MeasuredText full, MeasuredText left, MeasuredText right, int gapBeforePx) {
this.piped = piped;
this.full = full;
this.left = left;
this.right = right;
this.gapBeforePx = gapBeforePx;
this.ascent = piped
? Math.max(left != null ? left.ascent : 0, right != null ? right.ascent : 0)
: full != null ? full.ascent : 0;
this.descent = piped
? Math.max(left != null ? left.descent : 0, right != null ? right.descent : 0)
: full != null ? full.descent : 0;
this.height = Math.max(1, ascent + descent);
}
static MeasuredRow full(MeasuredText text, int gapBeforePx) {
return new MeasuredRow(false, text, null, null, gapBeforePx);
}
static MeasuredRow piped(MeasuredText left, MeasuredText right, int gapBeforePx) {
return new MeasuredRow(true, null, left, right, gapBeforePx);
}
}
private record MeasuredText(StaticLayout layout, int width, int height, int ascent, int descent) {
}
}
@@ -338,7 +338,8 @@ public class IconsDebugFragment extends Fragment {
if (TextUtils.isEmpty(cameraId)) {
identifiedView.setText(getString(R.string.debug_camera_identified_as,
getString(R.string.debug_camera_unknown)));
getString(R.string.debug_camera_unknown),
""));
if (overrideRow != null) {
overrideRow.setVisibility(View.GONE);
}
@@ -352,7 +353,8 @@ public class IconsDebugFragment extends Fragment {
: ClockCameraTypeSupport.normalizeType(effectiveTypeFromReport));
identifiedView.setText(getString(
R.string.debug_camera_identified_as,
readableType(currentAutoType)));
readableType(currentAutoType),
cameraId));
if (overrideRow != null && overrideView != null && actionButton != null) {
overrideRow.setVisibility(View.VISIBLE);
@@ -5,7 +5,11 @@ import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
@@ -22,10 +26,18 @@ import se.ajpanton.statusbartweak.R;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String EXTRA_OPEN_NAV_ITEM = "open_nav_item";
private static final String STATE_CURRENT_ITEM_ID = "current_item_id";
private static final float PERMANENT_SIDEBAR_FOLDED_WIDTH_MULTIPLIER = 1.1f;
private SafeInsetDrawerLayout drawerLayout;
private NavigationView navigationView;
private Integer navigationBasePaddingLeft;
private NavigationView drawerNavigationView;
private NavigationView permanentNavigationView;
private MaterialToolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private Integer drawerNavigationBasePaddingLeft;
private Integer permanentNavigationBasePaddingLeft;
private boolean permanentSidebar;
private int currentItemId = R.id.nav_layout;
public static Intent newOpenDebugIntent(Context context) {
Intent intent = new Intent(context, MainActivity.class);
@@ -39,34 +51,63 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MaterialToolbar toolbar = findViewById(R.id.toolbar);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().setGroupCheckable(0, true, true);
drawerNavigationView = findViewById(R.id.nav_view_drawer);
permanentNavigationView = findViewById(R.id.nav_view_permanent);
setupNavigationView(drawerNavigationView);
setupNavigationView(permanentNavigationView);
applyNavigationDrawerInsets();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.nav_open,
R.string.nav_close
);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
toolbar.setNavigationOnClickListener(v -> {
if (!permanentSidebar) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (!permanentSidebar && drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
setEnabled(false);
getOnBackPressedDispatcher().onBackPressed();
setEnabled(true);
}
});
if (savedInstanceState != null) {
currentItemId = savedInstanceState.getInt(STATE_CURRENT_ITEM_ID, currentItemId);
}
if (savedInstanceState == null) {
int initialItemId = resolveInitialItemId(getIntent());
navigateTo(initialItemId);
consumeOpenNavItemExtra(getIntent());
} else {
syncDrawerSelection(currentItemId);
setTitle(resolveTitle(currentItemId));
drawerLayout.post(this::applyPageTitleVisibility);
handleOpenNavIntent(getIntent());
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
outState.putInt(STATE_CURRENT_ITEM_ID, currentItemId);
super.onSaveInstanceState(outState);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
@@ -77,11 +118,14 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
@Override
public boolean onNavigationItemSelected(@NonNull android.view.MenuItem item) {
navigateTo(item.getItemId());
if (!permanentSidebar) {
drawerLayout.closeDrawer(GravityCompat.START);
}
return true;
}
private void navigateTo(int itemId) {
currentItemId = itemId;
syncDrawerSelection(itemId);
Fragment fragment;
if (itemId == R.id.nav_system_icons) {
@@ -110,6 +154,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.runOnCommit(this::applyPageTitleVisibility)
.commit();
setTitle(resolveTitle(itemId));
}
@@ -149,6 +194,11 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
}
private void syncDrawerSelection(int itemId) {
syncNavigationSelection(drawerNavigationView, itemId);
syncNavigationSelection(permanentNavigationView, itemId);
}
private void syncNavigationSelection(NavigationView navigationView, int itemId) {
if (navigationView == null) {
return;
}
@@ -167,6 +217,17 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
navigationView.invalidate();
}
private void setupNavigationView(NavigationView navigationView) {
if (navigationView == null) {
return;
}
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().setGroupCheckable(0, true, true);
navigationView.addOnLayoutChangeListener((view, left, top, right, bottom,
oldLeft, oldTop, oldRight, oldBottom) ->
updateNavigationHeaderHeight(navigationView));
}
private int resolveInitialItemId(Intent intent) {
int requested = resolveOpenItemId(intent);
return requested != -1 ? requested : R.id.nav_layout;
@@ -195,6 +256,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
private void applyNavigationDrawerMarginsFromRootInsets() {
WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(drawerLayout);
if (insets == null) {
applyNavigationDrawerSafeArea(0, 0);
return;
}
Insets safeInsets = insets.getInsetsIgnoringVisibility(
@@ -206,10 +268,25 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
int safeLeft = Math.max(Math.max(0, leftInset), Math.max(0, drawerLayout.getPaddingLeft()));
int safeRight = Math.max(Math.max(0, rightInset), Math.max(0, drawerLayout.getPaddingRight()));
drawerLayout.setDrawerSafeInsets(safeLeft, safeRight);
if (navigationBasePaddingLeft == null) {
navigationBasePaddingLeft = navigationView.getPaddingLeft();
drawerNavigationBasePaddingLeft = applyNavigationLeftPadding(
drawerNavigationView,
drawerNavigationBasePaddingLeft,
safeLeft);
permanentNavigationBasePaddingLeft = applyNavigationLeftPadding(
permanentNavigationView,
permanentNavigationBasePaddingLeft,
0);
updatePermanentSidebarMode();
}
int leftPadding = navigationBasePaddingLeft + safeLeft;
private Integer applyNavigationLeftPadding(NavigationView navigationView,
Integer basePaddingLeft,
int safeLeft) {
if (navigationView == null) {
return basePaddingLeft;
}
int base = basePaddingLeft != null ? basePaddingLeft : navigationView.getPaddingLeft();
int leftPadding = base + safeLeft;
if (navigationView.getPaddingLeft() != leftPadding
|| Math.round(navigationView.getTranslationX()) != 0) {
navigationView.setTranslationX(0f);
@@ -220,5 +297,96 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
navigationView.getPaddingBottom());
navigationView.requestLayout();
}
return base;
}
private void updatePermanentSidebarMode() {
int rootWidth = drawerLayout.getWidth();
if (rootWidth <= 0) {
return;
}
int drawerWidth = getResources().getDimensionPixelSize(R.dimen.sbt_navigation_drawer_width);
int foldedPortraitWidth = getResources().getDimensionPixelSize(R.dimen.sbt_folded_portrait_width);
boolean shouldUsePermanentSidebar = rootWidth >= drawerWidth
+ Math.round(foldedPortraitWidth * PERMANENT_SIDEBAR_FOLDED_WIDTH_MULTIPLIER);
if (permanentSidebar != shouldUsePermanentSidebar) {
permanentSidebar = shouldUsePermanentSidebar;
drawerToggle.setDrawerIndicatorEnabled(!permanentSidebar);
toolbar.setVisibility(permanentSidebar ? View.GONE : View.VISIBLE);
setTitle(resolveTitle(currentItemId));
if (permanentSidebar) {
permanentNavigationView.setVisibility(View.VISIBLE);
drawerLayout.closeDrawer(GravityCompat.START, false);
} else {
drawerNavigationView.setVisibility(View.VISIBLE);
drawerLayout.closeDrawer(GravityCompat.START, false);
permanentNavigationView.setVisibility(View.GONE);
drawerNavigationView.requestLayout();
}
drawerToggle.syncState();
}
updateNavigationHeaderHeight(drawerNavigationView);
updateNavigationHeaderHeight(permanentNavigationView);
applyPageTitleVisibility();
}
private void updateNavigationHeaderHeight(NavigationView navigationView) {
if (navigationView == null || navigationView.getHeaderCount() == 0) {
return;
}
int navigationHeight = navigationView.getHeight();
if (navigationHeight <= 0) {
return;
}
int menuRows = countVisibleMenuRows(navigationView.getMenu());
int menuHeight = menuRows * getResources().getDimensionPixelSize(R.dimen.sbt_navigation_menu_item_height);
int minHeaderHeight = getResources().getDimensionPixelSize(R.dimen.sbt_drawer_header_min_height);
int maxHeaderHeight = getResources().getDimensionPixelSize(R.dimen.sbt_drawer_header_max_height);
int desiredHeaderHeight = Math.max(
minHeaderHeight,
Math.min(maxHeaderHeight, navigationHeight - menuHeight));
View header = navigationView.getHeaderView(0);
if (header == null || header.getLayoutParams() == null
|| header.getLayoutParams().height == desiredHeaderHeight) {
return;
}
header.getLayoutParams().height = desiredHeaderHeight;
header.requestLayout();
}
private int countVisibleMenuRows(Menu menu) {
if (menu == null) {
return 0;
}
int count = 0;
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item != null && item.isVisible()) {
count++;
}
}
return count;
}
private void applyPageTitleVisibility() {
View content = findViewById(R.id.content_frame);
setTaggedPageTitlesVisible(content, permanentSidebar);
}
private void setTaggedPageTitlesVisible(View view, boolean visible) {
if (view == null) {
return;
}
Object tag = view.getTag();
if (tag instanceof String string && "statusbartweak.page.title".equals(string)
&& view instanceof TextView) {
view.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (!(view instanceof ViewGroup group)) {
return;
}
for (int i = 0; i < group.getChildCount(); i++) {
setTaggedPageTitlesVisible(group.getChildAt(i), visible);
}
}
}
@@ -45,6 +45,11 @@ public class StatusChipsFragment extends Fragment {
SbtSettings.KEY_STATUS_CHIPS_HIDE_CALL,
false,
true);
ViewTreeSupport.bindBooleanPreference(requireContext(), prefs, root,
R.id.status_chips_hide_battery_switch,
SbtSettings.KEY_STATUS_CHIPS_HIDE_BATTERY,
false,
true);
return root;
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<stroke
android:width="1dp"
android:color="@color/sbt_card_outline" />
<corners android:radius="6dp" />
<padding
android:left="8dp"
android:top="6dp"
android:right="8dp"
android:bottom="6dp" />
</shape>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<stroke
android:width="1dp"
android:color="@color/sbt_panel_outline" />
<corners android:radius="8dp" />
<padding
android:left="10dp"
android:top="8dp"
android:right="10dp"
android:bottom="8dp" />
</shape>
+24 -2
View File
@@ -9,8 +9,28 @@
android:fitsSystemWindows="true">
<LinearLayout
android:id="@+id/main_shell"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view_permanent"
android:layout_width="@dimen/sbt_navigation_drawer_width"
android:layout_height="match_parent"
android:background="@color/sbt_surface"
android:fitsSystemWindows="true"
android:visibility="gone"
app:headerLayout="@layout/drawer_header"
app:itemBackground="@drawable/drawer_item_background"
app:itemTextColor="@color/drawer_item_text_color"
app:menu="@menu/drawer_menu" />
<LinearLayout
android:id="@+id/main_content"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<com.google.android.material.appbar.MaterialToolbar
@@ -30,9 +50,11 @@
</LinearLayout>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:id="@+id/nav_view_drawer"
android:layout_width="@dimen/sbt_navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/sbt_surface"
+2 -2
View File
@@ -2,11 +2,11 @@
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="172dp"
android:layout_height="@dimen/sbt_drawer_header_height"
android:background="@drawable/sbt_drawer_header_background"
android:gravity="bottom"
android:orientation="vertical"
android:padding="20dp">
android:padding="@dimen/sbt_drawer_header_padding">
<TextView
android:layout_width="wrap_content"
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/battery_bar_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
@@ -569,6 +570,25 @@
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/battery_bar_default_charge_colour" />
<TextView
android:id="@+id/battery_bar_colour_help_toggle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="@string/battery_bar_colour_help_show"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="@color/sbt_accent_dark"
android:textStyle="bold" />
<TextView
android:id="@+id/battery_bar_colour_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:visibility="gone"
android:text="@string/battery_bar_colour_help_text"
android:textAppearance="?attr/textAppearanceBody2" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
@@ -9,6 +9,7 @@
android:id="@+id/hidden_apps_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/hidden_apps_page_title"
android:textAppearance="?attr/textAppearanceHeadline6"
android:textStyle="bold" />
+51 -18
View File
@@ -13,10 +13,12 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/clock_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/clock_custom_format_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
@@ -53,17 +55,24 @@
android:orientation="vertical"
android:visibility="gone">
<EditText
android:id="@+id/clock_custom_format_input"
android:layout_width="match_parent"
<se.ajpanton.statusbartweak.shell.ui.ClockPatternPreviewView
android:id="@+id/clock_custom_format_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_preview_background" />
<EditText
android:id="@+id/clock_custom_format_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_input_background"
android:gravity="top|start"
android:hint="@string/clock_custom_format_hint"
android:importantForAutofill="no"
android:inputType="textMultiLine|textNoSuggestions"
android:maxLines="4"
android:minLines="2"
android:minWidth="120dp"
android:minLines="1"
android:scrollHorizontally="false"
android:singleLine="false" />
</LinearLayout>
@@ -71,6 +80,7 @@
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="@+id/drawer_clock_custom_format_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
@@ -107,17 +117,24 @@
android:orientation="vertical"
android:visibility="gone">
<EditText
android:id="@+id/drawer_clock_custom_format_input"
android:layout_width="match_parent"
<se.ajpanton.statusbartweak.shell.ui.ClockPatternPreviewView
android:id="@+id/drawer_clock_custom_format_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_preview_background" />
<EditText
android:id="@+id/drawer_clock_custom_format_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_input_background"
android:gravity="top|start"
android:hint="@string/clock_custom_format_hint"
android:importantForAutofill="no"
android:inputType="textMultiLine|textNoSuggestions"
android:maxLines="4"
android:minLines="2"
android:minWidth="120dp"
android:minLines="1"
android:scrollHorizontally="false"
android:singleLine="false" />
</LinearLayout>
@@ -125,6 +142,7 @@
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="@+id/drawer_date_custom_format_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
@@ -161,17 +179,24 @@
android:orientation="vertical"
android:visibility="gone">
<EditText
android:id="@+id/drawer_date_custom_format_input"
android:layout_width="match_parent"
<se.ajpanton.statusbartweak.shell.ui.ClockPatternPreviewView
android:id="@+id/drawer_date_custom_format_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_preview_background" />
<EditText
android:id="@+id/drawer_date_custom_format_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/sbt_clock_input_background"
android:gravity="top|start"
android:hint="@string/clock_custom_format_hint"
android:importantForAutofill="no"
android:inputType="textMultiLine|textNoSuggestions"
android:maxLines="4"
android:minLines="2"
android:minWidth="120dp"
android:minLines="1"
android:scrollHorizontally="false"
android:singleLine="false" />
</LinearLayout>
@@ -209,6 +234,14 @@
android:layout_marginTop="8dp"
android:text="@string/clock_font_picker_button" />
<com.google.android.material.button.MaterialButton
android:id="@+id/clock_restore_stored_patterns_button"
style="?attr/materialButtonOutlinedStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/clock_restore_stored_patterns" />
<TextView
android:id="@+id/clock_custom_format_help_toggle"
android:layout_width="match_parent"
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/debug_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/layout_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/misc_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/status_chips_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
@@ -47,6 +48,12 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/status_chips_hide_call_unlocked_label" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/status_chips_hide_battery_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/status_chips_hide_battery_label" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
@@ -13,6 +13,7 @@
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="statusbartweak.page.title"
android:text="@string/system_icons_title"
android:textAppearance="?attr/textAppearanceHeadline5" />
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="sbt_navigation_drawer_width">216dp</dimen>
<dimen name="sbt_folded_portrait_width">360dp</dimen>
<dimen name="sbt_navigation_menu_item_height">48dp</dimen>
<dimen name="sbt_drawer_header_height">86dp</dimen>
<dimen name="sbt_drawer_header_min_height">86dp</dimen>
<dimen name="sbt_drawer_header_max_height">172dp</dimen>
<dimen name="sbt_drawer_header_padding">16dp</dimen>
</resources>
+1
View File
@@ -1,3 +1,4 @@
<resources>
<item name="sbt_debug_container_bounds" type="id" />
<item name="sbt_debug_drawer_clock_container" type="id" />
</resources>
+15 -5
View File
@@ -44,7 +44,7 @@
<string name="debug_notification_permission_required">Notification permission is required for debug icons.</string>
<string name="debug_camera_current_title">Current camera</string>
<string name="debug_camera_other_title">Other overridden cameras</string>
<string name="debug_camera_identified_as">Identified as %1$s</string>
<string name="debug_camera_identified_as">Identified as %1$s\n%2$s</string>
<string name="debug_camera_overridden_as">Overridden as %1$s</string>
<string name="debug_camera_action_wrong">This is wrong</string>
<string name="debug_camera_action_undo"></string>
@@ -131,6 +131,7 @@
<string name="status_chips_hide_media_unlocked_label">Hide media chip (unlocked)</string>
<string name="status_chips_hide_navigation_unlocked_label">Hide navigation chip (unlocked)</string>
<string name="status_chips_hide_call_unlocked_label">Hide call chip (unlocked)</string>
<string name="status_chips_hide_battery_label">Hide charging battery chip (unlocked)</string>
<string name="misc_title">Misc</string>
<string name="battery_bar_title">Battery bar</string>
<string name="battery_bar_master_toggle_title">Master toggle</string>
@@ -164,11 +165,13 @@
<string name="battery_bar_colours_title">Default colours</string>
<string name="battery_bar_default_discharge_colour">Discharge colour</string>
<string name="battery_bar_default_charge_colour">Charge colour</string>
<string name="battery_bar_button_label_discharge">Discharge</string>
<string name="battery_bar_button_label_charge">Charge</string>
<string name="battery_bar_thresholds_title">Threshold colours</string>
<string name="battery_bar_thresholds_hint">Below a threshold, the first matching colour overrides the default.</string>
<string name="battery_bar_add_threshold">Add threshold</string>
<string name="battery_bar_colour_dialog_title">Set colour</string>
<string name="battery_bar_colour_dialog_hint">Examples: FA0, 80FA, or FFAA00</string>
<string name="battery_bar_colour_dialog_hint">Examples: #FA0, FA0, or #FA0 ; invRGB 0.5 *RGB</string>
<string name="battery_bar_threshold_percent_title">Threshold percent</string>
<string name="battery_bar_threshold_percent_hint">Applies when battery is at or below this percent.</string>
<string name="battery_bar_threshold_change_percent">Change threshold %</string>
@@ -178,7 +181,10 @@
<string name="battery_bar_threshold_remove">Remove threshold</string>
<string name="battery_bar_colour_auto">Auto</string>
<string name="battery_bar_colour_same_as_discharge">Same as discharge</string>
<string name="battery_bar_colour_same_as_default">Same as default</string>
<string name="battery_bar_colour_same_as_default">Default</string>
<string name="battery_bar_colour_help_show">Show colour syntax</string>
<string name="battery_bar_colour_help_hide">Hide colour syntax</string>
<string name="battery_bar_colour_help_text">Colour values:\n#FA0, #FFAA00, #80FFAA00, FA0, or [255, 255, 170, 0]\n\nPostfix math:\n#FA0 1.2 *RGB clip\n#FA0 invRGB\n\nOperators:\n+ - * / ^ inv min max sqrt clip dup\n\nChannels:\nAdd A, R, G, or B to limit vector operations.\nExamples: invRGB, *A, +RB\n\nTint variants:\nUse ; for a dark-tint expression.\nThe dark expression starts with the result from the bright expression.</string>
<string name="battery_bar_threshold_duplicate">A threshold at that percentage already exists.</string>
<string name="battery_bar_threshold_reordered">That threshold moved to a new position in the list.</string>
<string name="battery_bar_threshold_charge_note">Leave the field empty and press OK for \"Same as discharge\", or use the button below for \"Same as default\".</string>
@@ -242,14 +248,18 @@
<string name="clock_custom_format_enabled">Enable custom date/time pattern</string>
<string name="drawer_clock_custom_format_enabled">Enable custom date/time pattern</string>
<string name="drawer_date_custom_format_enabled">Enable custom date/time pattern</string>
<string name="clock_custom_format_hint">Examples: HH:mm, EEE d MMM HH:mm:ss, {color(#batterybar 1.2 * ; invRGB 0.5 *RGB) big @sans-serif-condensed}HH:mm</string>
<string name="clock_custom_format_help_common">Date/time patterns:\n\u2022 Uses Java SimpleDateFormat-style pattern letters\n\u2022 Common symbols: yyyy yy MMMM MMM MM EEEE EEE dd d HH hh mm ss a\n\nTags:\n\u2022 Supported tags: &lt;i&gt;, &lt;u&gt;, &lt;small&gt;, &lt;big&gt;, &lt;font color=\'...\'&gt;, &lt;font face=\'...\'&gt;\n\u2022 &lt;b&gt; is not supported\n\u2022 Custom font tags: &lt;sans&gt;, &lt;serif&gt;, &lt;mono&gt;, &lt;condensed&gt;\n\u2022 {/font} closes any open &lt;font ...&gt; tag\n\u2022 Opening a new colour or font face automatically closes the previous one</string>
<string name="clock_custom_format_help_styling">Shorthand blocks:\n\u2022 {#FA0 big @sans-serif-condensed} is shorthand for opening multiple tags in order\n\u2022 {#FA0} is shorthand for {color(#FA0)}\n\u2022 In shorthand: / closes a tag, color(...) sets font colour, @ sets font face\n\u2022 Each whitespace-separated token inside {} becomes its own tag, except color(...) which may contain spaces\n\nLine breaks:\n\u2022 Use \\n, {\\n} or {\\n15}; the number is the line-height delta in statusbar units\n\u2022 Omit the number to use the default row spacing\n\u2022 { /\\n } style line breaks are written without spaces: {/\\n} or {/\\n15}\n\u2022 Normal line breaks propagate open tags onto the next row\n\u2022 A / line break ends all currently open tags before the next row starts\n\nPipes and grouping:\n\u2022 Maximum two pipes per row; more than two is a syntax error for that row only\n\u2022 Pipes inside single quotes or {} do not split the row\n\u2022 One pipe splits into left and right segments\n\u2022 Two pipes remove the middle section, then split using the outer pipes\n\u2022 Tags are logically continued across pipe splits, even if the middle section is ignored\n\u2022 Rows without pipes are independent; rows with pipes share one common pipe group\n\u2022 A syntax-error row becomes the text Syntax error, with no whole-clock fallback\n\nColours:\n\u2022 Supported operands: #RGB, #ARGB, #RRGGBB, #AARRGGBB, #batterybar, [R,G,B], [A,R,G,B], and numbers\n\u2022 Colour expressions use reverse Polish notation: operands first, operator last\n\u2022 Use ; to separate bright/dark variants; the dark side starts with the raw result from the bright side on the stack\n\u2022 Operators: + - * / ^ inv min max sqrt clip dup\n\u2022 Operators can be channel-filtered, for example +A, *RGB, invRGB, maxRGB, clipA\n\u2022 Final values are clipped to 0..255; a final number becomes opaque grayscale</string>
<string name="clock_custom_format_help_examples">Examples:\n\u2022 &lt;small&gt;EEE d MMM&lt;/small&gt; HH:mm\n\u2022 HH&lt;small&gt;:mm&lt;/small&gt;\n\u2022 &lt;font color=\'#FA0\'&gt;ss&lt;/font&gt;\n\u2022 {color(#FA0 ; invRGB 0.8 *RGB)}ss\n\u2022 {color(#batterybar 1.2 * ; invRGB 0.5 *RGB) big u @sans-serif-condensed}HH:mm\n\u2022 {color([255, 255, 170, 0] ; invRGB)}HH:mm\n\u2022 HH:mm{\\n12 small}EEE d MMM\n\u2022 HH|mm aligns the pipe position across every piped row\n\u2022 left||right removes the middle section before split alignment\n\u2022 {/font}{/\\n big}HH:mm starts a new row without carrying the previous font tags forward</string>
<string name="clock_font_picker_button">Browse font families</string>
<string name="clock_restore_stored_patterns">Restore stored patterns</string>
<string name="clock_stored_patterns_show">Show stored patterns</string>
<string name="clock_stored_patterns_hide">Hide stored patterns</string>
<string name="clock_stored_patterns_hint">Tap a preview to use it</string>
<string name="clock_store_current_pattern">Store current pattern</string>
<string name="clock_custom_format_help_show">▾ Show pattern instructions</string>
<string name="clock_custom_format_help_hide">▴ Hide pattern instructions</string>
<string name="clock_font_picker_title">Font families</string>
<string name="clock_font_picker_title">Font families (tap to copy)</string>
<string name="clock_font_picker_hint">Search font family</string>
<string name="clock_font_picker_copied">Copied: %1$s</string>
<string name="clock_custom_format_help_link">Date/time pattern reference only: https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html</string>
@@ -49,4 +49,38 @@ public final class ClockColorResolverTest {
public void rejectsMoreThanTwoColorVariants() {
resolver.resolveColor(null, "#123 ; #456 ; #789", WHITE_REFERENCE, 0xffffffff);
}
@Test
public void batteryBarOptionsAllowBareHexColours() {
assertEquals(
0xff808080,
resolver.resolveColor(
null,
"808080",
WHITE_REFERENCE,
0xffffffff,
ClockColorResolver.Options.batteryBar()));
}
@Test
public void batteryBarOptionsKeepThreeDigitNumbersAsNumbers() {
assertEquals(
0xffffffff,
resolver.resolveColor(
null,
"255",
WHITE_REFERENCE,
0xffffffff,
ClockColorResolver.Options.batteryBar()));
}
@Test(expected = IllegalArgumentException.class)
public void batteryBarOptionsRejectBatteryBarOperand() {
resolver.resolveColor(
null,
"#batterybar",
WHITE_REFERENCE,
0xffffffff,
ClockColorResolver.Options.batteryBar());
}
}
@@ -0,0 +1,21 @@
package se.ajpanton.statusbartweak.runtime.features.clock;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public final class ClockPatternParserTest {
private final ClockPatternParser parser = new ClockPatternParser();
@Test
public void lineBreakBlockAcceptsFollowingShorthandTags() {
ClockParsedPattern combined = parser.parse("HH{\\n30 big}mm");
ClockParsedPattern split = parser.parse("HH{\\n30}{big}mm");
assertEquals(split.rows.size(), combined.rows.size());
assertEquals(2, combined.rows.size());
assertEquals(split.rows.get(1).gapBeforePx, combined.rows.get(1).gapBeforePx);
assertEquals(30, combined.rows.get(1).gapBeforePx);
assertEquals(split.rows.get(1).markup, combined.rows.get(1).markup);
}
}
+1 -1
View File
@@ -1 +1 @@
version=0.1
version=0.2