feat(YouTube - Debugging): Add setting to block experimental client flags (#6196)

This commit is contained in:
MarcaD
2025-11-08 10:01:46 +02:00
committed by GitHub
parent 81f83690d6
commit 2e9d6959c9
36 changed files with 1174 additions and 281 deletions

View File

@@ -16,6 +16,7 @@ import java.util.Arrays;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
import com.amazon.video.sdk.player.Player;
@@ -64,9 +65,8 @@ public class PlaybackSpeedPatch {
SpeedIconDrawable speedIcon = new SpeedIconDrawable();
speedButton.setImageDrawable(speedIcon);
int buttonSize = Utils.dipToPixels(48);
speedButton.setMinimumWidth(buttonSize);
speedButton.setMinimumHeight(buttonSize);
speedButton.setMinimumWidth(Dim.dp48);
speedButton.setMinimumHeight(Dim.dp48);
return speedButton;
}
@@ -197,11 +197,11 @@ class SpeedIconDrawable extends Drawable {
@Override
public int getIntrinsicWidth() {
return Utils.dipToPixels(32);
return Dim.dp32;
}
@Override
public int getIntrinsicHeight() {
return Utils.dipToPixels(32);
return Dim.dp32;
}
}

View File

@@ -23,9 +23,7 @@ import android.os.Looper;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
@@ -63,6 +61,7 @@ import app.revanced.extension.shared.settings.AppLanguage;
import app.revanced.extension.shared.settings.BaseSettings;
import app.revanced.extension.shared.settings.BooleanSetting;
import app.revanced.extension.shared.settings.preference.ReVancedAboutPreference;
import app.revanced.extension.shared.ui.Dim;
@SuppressWarnings("NewApi")
public class Utils {
@@ -801,13 +800,10 @@ public class Utils {
public static void setDialogWindowParameters(Window window, int gravity, int yOffsetDip, int widthPercentage, boolean dimAmount) {
WindowManager.LayoutParams params = window.getAttributes();
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
int portraitWidth = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
params.width = (int) (portraitWidth * (widthPercentage / 100.0f)); // Set width based on parameters.
params.width = Dim.pctPortraitWidth(widthPercentage);
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = gravity;
params.y = yOffsetDip > 0 ? dipToPixels(yOffsetDip) : 0;
params.y = yOffsetDip > 0 ? Dim.dp(yOffsetDip) : 0;
if (dimAmount) {
params.dimAmount = 0f;
}
@@ -816,18 +812,6 @@ public class Utils {
window.setBackgroundDrawable(null); // Remove default dialog background
}
/**
* Creates an array of corner radii for a rounded rectangle shape.
*
* @param dp Radius in density-independent pixels (dip) to apply to all corners.
* @return An array of eight float values representing the corner radii
* (top-left, top-right, bottom-right, bottom-left).
*/
public static float[] createCornerRadii(float dp) {
final float radius = dipToPixels(dp);
return new float[]{radius, radius, radius, radius, radius, radius, radius, radius};
}
/**
* Sets the theme light color used by the app.
*/
@@ -1132,42 +1116,6 @@ public class Utils {
return getResourceColor(colorString);
}
/**
* Converts dip value to actual device pixels.
*
* @param dip The density-independent pixels value.
* @return The device pixel value.
*/
public static int dipToPixels(float dip) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip,
Resources.getSystem().getDisplayMetrics()
);
}
/**
* Converts a percentage of the screen height to actual device pixels.
*
* @param percentage The percentage of the screen height (e.g., 30 for 30%).
* @return The device pixel value corresponding to the percentage of screen height.
*/
public static int percentageHeightToPixels(int percentage) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return (int) (metrics.heightPixels * (percentage / 100.0f));
}
/**
* Converts a percentage of the screen width to actual device pixels.
*
* @param percentage The percentage of the screen width (e.g., 30 for 30%).
* @return The device pixel value corresponding to the percentage of screen width.
*/
public static int percentageWidthToPixels(int percentage) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return (int) (metrics.widthPixels * (percentage / 100.0f));
}
/**
* Uses {@link #adjustColorBrightness(int, float)} depending if light or dark mode is active.
*/

View File

@@ -1,5 +1,9 @@
package app.revanced.extension.shared.patches;
import static java.lang.Boolean.TRUE;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -21,12 +25,28 @@ public final class EnableDebuggingPatch {
? new ConcurrentHashMap<>(800, 0.5f, 1)
: null;
private static final Set<Long> DISABLED_FEATURE_FLAGS = parseFlags(BaseSettings.DISABLED_FEATURE_FLAGS.get());
// Log all disabled flags on app startup.
static {
if (LOG_FEATURE_FLAGS && !DISABLED_FEATURE_FLAGS.isEmpty()) {
StringBuilder sb = new StringBuilder("Disabled feature flags:\n");
for (Long flag : DISABLED_FEATURE_FLAGS) {
sb.append(" ").append(flag).append('\n');
}
Logger.printDebug(sb::toString);
}
}
/**
* Injection point.
*/
public static boolean isBooleanFeatureFlagEnabled(boolean value, Long flag) {
if (LOG_FEATURE_FLAGS && value) {
if (featureFlags.putIfAbsent(flag, true) == null) {
if (DISABLED_FEATURE_FLAGS.contains(flag)) {
return false;
}
if (featureFlags.putIfAbsent(flag, TRUE) == null) {
Logger.printDebug(() -> "boolean feature is enabled: " + flag);
}
}
@@ -70,10 +90,44 @@ public final class EnableDebuggingPatch {
if (LOG_FEATURE_FLAGS && !defaultValue.equals(value)) {
if (featureFlags.putIfAbsent(flag, true) == null) {
Logger.printDebug(() -> " string feature is enabled: " + flag
+ " value: " + value + (defaultValue.isEmpty() ? "" : " default: " + defaultValue));
+ " value: " + value + (defaultValue.isEmpty() ? "" : " default: " + defaultValue));
}
}
return value;
}
/**
* Get all logged feature flags.
* @return Set of all known flags
*/
public static Set<Long> getAllLoggedFlags() {
if (featureFlags != null) {
return new HashSet<>(featureFlags.keySet());
}
return new HashSet<>();
}
/**
* Public method for parsing flags.
* @param flags String containing newline-separated flag IDs
* @return Set of parsed flag IDs
*/
public static Set<Long> parseFlags(String flags) {
Set<Long> parsedFlags = new HashSet<>();
if (!flags.isBlank()) {
for (String flag : flags.split("\n")) {
String trimmedFlag = flag.trim();
if (trimmedFlag.isEmpty()) continue; // Skip empty lines.
try {
parsedFlags.add(Long.parseLong(trimmedFlag));
} catch (NumberFormatException e) {
Logger.printException(() -> "Invalid flag ID: " + flag);
}
}
}
return parsedFlags;
}
}

View File

@@ -7,7 +7,6 @@ import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceFragment;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@@ -16,6 +15,7 @@ import android.widget.Toolbar;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.settings.preference.ToolbarPreferenceFragment;
import app.revanced.extension.shared.ui.Dim;
/**
* Base class for hooking activities to inject a custom PreferenceFragment with a toolbar.
@@ -109,13 +109,12 @@ public abstract class BaseActivityHook extends Activity {
toolbar.setNavigationOnClickListener(getNavigationClickListener(activity));
toolbar.setTitle(STRING_REVANCED_SETTINGS_TITLE);
final int margin = Utils.dipToPixels(16);
toolbar.setTitleMarginStart(margin);
toolbar.setTitleMarginEnd(margin);
toolbar.setTitleMarginStart(Dim.dp16);
toolbar.setTitleMarginEnd(Dim.dp16);
TextView toolbarTextView = Utils.getChildView(toolbar, false, view -> view instanceof TextView);
if (toolbarTextView != null) {
toolbarTextView.setTextColor(Utils.getAppForegroundColor());
toolbarTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
toolbarTextView.setTextSize(20);
}
setToolbarLayoutParams(toolbar);

View File

@@ -42,4 +42,6 @@ public class BaseSettings {
public static final EnumSetting<BrandingTheme> CUSTOM_BRANDING_ICON = new EnumSetting<>("revanced_custom_branding_icon", BrandingTheme.ORIGINAL, true);
public static final IntegerSetting CUSTOM_BRANDING_NAME = new IntegerSetting("revanced_custom_branding_name", 1, true);
public static final StringSetting DISABLED_FEATURE_FLAGS = new StringSetting("revanced_disabled_feature_flags", "", true, parent(DEBUG));
}

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.shared.settings.preference;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.shared.Utils.getResourceIdentifierOrThrow;
import android.app.Dialog;
@@ -37,6 +36,7 @@ import app.revanced.extension.shared.settings.Setting;
import app.revanced.extension.shared.settings.StringSetting;
import app.revanced.extension.shared.ui.ColorDot;
import app.revanced.extension.shared.ui.CustomDialog;
import app.revanced.extension.shared.ui.Dim;
/**
* A custom preference for selecting a color via a hexadecimal code or a color picker dialog.
@@ -310,11 +310,8 @@ public class ColorPickerPreference extends EditTextPreference {
inputLayout.setGravity(Gravity.CENTER_VERTICAL);
dialogColorDot = new View(context);
LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(
dipToPixels(20),
dipToPixels(20)
);
previewParams.setMargins(dipToPixels(16), 0, dipToPixels(10), 0);
LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(Dim.dp20,Dim.dp20);
previewParams.setMargins(Dim.dp16, 0, Dim.dp10, 0);
dialogColorDot.setLayoutParams(previewParams);
inputLayout.addView(dialogColorDot);
updateDialogColorDot();

View File

@@ -1,6 +1,5 @@
package app.revanced.extension.shared.settings.preference;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.shared.settings.preference.ColorPickerPreference.getColorString;
import android.annotation.SuppressLint;
@@ -21,6 +20,7 @@ import androidx.annotation.ColorInt;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
/**
* A custom color picker view that allows the user to select a color using a hue slider, a saturation-value selector
@@ -54,28 +54,28 @@ public class ColorPickerView extends View {
}
/** Expanded touch area for the hue and opacity bars to increase the touch-sensitive area. */
public static final float TOUCH_EXPANSION = dipToPixels(20f);
public static final float TOUCH_EXPANSION = Dim.dp20;
/** Margin between different areas of the view (saturation-value selector, hue bar, and opacity slider). */
private static final float MARGIN_BETWEEN_AREAS = dipToPixels(24);
private static final float MARGIN_BETWEEN_AREAS = Dim.dp24;
/** Padding around the view. */
private static final float VIEW_PADDING = dipToPixels(16);
private static final float VIEW_PADDING = Dim.dp16;
/** Height of the hue bar. */
private static final float HUE_BAR_HEIGHT = dipToPixels(12);
private static final float HUE_BAR_HEIGHT = Dim.dp12;
/** Height of the opacity slider. */
private static final float OPACITY_BAR_HEIGHT = dipToPixels(12);
private static final float OPACITY_BAR_HEIGHT = Dim.dp12;
/** Corner radius for the hue bar. */
private static final float HUE_CORNER_RADIUS = dipToPixels(6);
private static final float HUE_CORNER_RADIUS = Dim.dp6;
/** Corner radius for the opacity slider. */
private static final float OPACITY_CORNER_RADIUS = dipToPixels(6);
private static final float OPACITY_CORNER_RADIUS = Dim.dp6;
/** Radius of the selector handles. */
private static final float SELECTOR_RADIUS = dipToPixels(12);
private static final float SELECTOR_RADIUS = Dim.dp12;
/** Stroke width for the selector handle outlines. */
private static final float SELECTOR_STROKE_WIDTH = 8;
@@ -202,7 +202,7 @@ public class ColorPickerView extends View {
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final float DESIRED_ASPECT_RATIO = 0.8f; // height = width * 0.8
final int minWidth = dipToPixels(250);
final int minWidth = Dim.dp(250);
final int minHeight = (int) (minWidth * DESIRED_ASPECT_RATIO) + (int) (HUE_BAR_HEIGHT + MARGIN_BETWEEN_AREAS)
+ (opacitySliderEnabled ? (int) (OPACITY_BAR_HEIGHT + MARGIN_BETWEEN_AREAS) : 0);

View File

@@ -0,0 +1,621 @@
package app.revanced.extension.shared.settings.preference;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.getResourceIdentifierOrThrow;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.preference.Preference;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Space;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.patches.EnableDebuggingPatch;
import app.revanced.extension.shared.settings.BaseSettings;
import app.revanced.extension.shared.ui.CustomDialog;
import app.revanced.extension.shared.ui.Dim;
/**
* A custom preference that opens a dialog for managing feature flags.
* Allows moving boolean flags between active and blocked states with advanced selection.
*/
@SuppressWarnings({"deprecation", "unused"})
public class FeatureFlagsManagerPreference extends Preference {
private static final int DRAWABLE_REVANCED_SETTINGS_SELECT_ALL =
getResourceIdentifierOrThrow("revanced_settings_select_all", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_DESELECT_ALL =
getResourceIdentifierOrThrow("revanced_settings_deselect_all", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_COPY_ALL =
getResourceIdentifierOrThrow("revanced_settings_copy_all", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_ARROW_RIGHT_ONE =
getResourceIdentifierOrThrow("revanced_settings_arrow_right_one", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_ARROW_RIGHT_DOUBLE =
getResourceIdentifierOrThrow("revanced_settings_arrow_right_double", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_ARROW_LEFT_ONE =
getResourceIdentifierOrThrow("revanced_settings_arrow_left_one", "drawable");
private static final int DRAWABLE_REVANCED_SETTINGS_ARROW_LEFT_DOUBLE =
getResourceIdentifierOrThrow("revanced_settings_arrow_left_double", "drawable");
/**
* Flags to hide from the UI.
*/
private static final Set<Long> FLAGS_TO_IGNORE = Set.of(
45386834L // 'You' tab settings icon.
);
/**
* Tracks state for range selection in ListView.
*/
private static class ListViewSelectionState {
int lastClickedPosition = -1; // Position of the last clicked item.
boolean isRangeSelecting = false; // True while a range is being selected.
}
/**
* Helper class to pass ListView and Adapter together.
*/
private record ColumnViews(ListView listView, FlagAdapter adapter) {}
{
setOnPreferenceClickListener(pref -> {
showFlagsManagerDialog();
return true;
});
}
public FeatureFlagsManagerPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public FeatureFlagsManagerPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public FeatureFlagsManagerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FeatureFlagsManagerPreference(Context context) {
super(context);
}
/**
* Shows the main dialog for managing feature flags.
*/
private void showFlagsManagerDialog() {
if (!BaseSettings.DEBUG.get()) {
Utils.showToastShort(str("revanced_debug_logs_disabled"));
return;
}
Context context = getContext();
// Load all known and disabled flags.
TreeSet<Long> allKnownFlags = new TreeSet<>(EnableDebuggingPatch.getAllLoggedFlags());
allKnownFlags.removeAll(FLAGS_TO_IGNORE);
TreeSet<Long> disabledFlags = new TreeSet<>(EnableDebuggingPatch.parseFlags(
BaseSettings.DISABLED_FEATURE_FLAGS.get()));
disabledFlags.removeAll(FLAGS_TO_IGNORE);
if (allKnownFlags.isEmpty() && disabledFlags.isEmpty()) {
// String does not need to be localized because it's basically impossible
// to reach the settings menu without encountering at least 1 flag.
Utils.showToastShort("No feature flags logged yet");
return;
}
TreeSet<Long> availableFlags = new TreeSet<>(allKnownFlags);
availableFlags.removeAll(disabledFlags);
TreeSet<Long> blockedFlags = new TreeSet<>(disabledFlags);
Pair<Dialog, LinearLayout> dialogPair = CustomDialog.create(
context,
getTitle() != null ? getTitle().toString() : "",
null,
null,
str("revanced_settings_save"),
() -> saveFlags(blockedFlags),
() -> {},
str("revanced_settings_reset"),
this::resetFlags,
true
);
LinearLayout mainLayout = dialogPair.second;
LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1.0f);
// Insert content before the dialog button row.
View contentView = createContentView(context, availableFlags, blockedFlags);
mainLayout.addView(contentView, mainLayout.getChildCount() - 1, contentParams);
Dialog dialog = dialogPair.first;
dialog.show();
Window window = dialog.getWindow();
if (window != null) {
Utils.setDialogWindowParameters(window, Gravity.CENTER, 0, 100, false);
}
}
/**
* Creates the main content view with two columns.
*/
private View createContentView(Context context, TreeSet<Long> availableFlags, TreeSet<Long> blockedFlags) {
LinearLayout contentLayout = new LinearLayout(context);
contentLayout.setOrientation(LinearLayout.VERTICAL);
// Headers.
TextView availableHeader = createHeader(context, "revanced_debug_feature_flags_manager_active_header");
TextView blockedHeader = createHeader(context, "revanced_debug_feature_flags_manager_blocked_header");
LinearLayout headersLayout = new LinearLayout(context);
headersLayout.setOrientation(LinearLayout.HORIZONTAL);
headersLayout.addView(availableHeader, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
headersLayout.addView(blockedHeader, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
// Columns.
View leftColumn = createColumn(context, availableFlags, availableHeader);
View rightColumn = createColumn(context, blockedFlags, blockedHeader);
ColumnViews leftViews = (ColumnViews) leftColumn.getTag();
ColumnViews rightViews = (ColumnViews) rightColumn.getTag();
updateHeaderCount(availableHeader, leftViews.adapter);
updateHeaderCount(blockedHeader, rightViews.adapter);
// Main columns layout.
LinearLayout columnsLayout = new LinearLayout(context);
columnsLayout.setOrientation(LinearLayout.HORIZONTAL);
columnsLayout.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
columnsLayout.addView(leftColumn, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
Space spaceBetweenColumns = new Space(context);
spaceBetweenColumns.setLayoutParams(new LinearLayout.LayoutParams(Dim.dp8, ViewGroup.LayoutParams.MATCH_PARENT));
columnsLayout.addView(spaceBetweenColumns);
columnsLayout.addView(rightColumn, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
// Move buttons below columns.
Pair<LinearLayout, LinearLayout> moveButtons = createMoveButtons(context,
leftViews.listView, rightViews.listView,
availableFlags, blockedFlags, availableHeader, blockedHeader);
// Layout for buttons row.
LinearLayout buttonsRow = new LinearLayout(context);
buttonsRow.setOrientation(LinearLayout.HORIZONTAL);
buttonsRow.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
buttonsRow.addView(moveButtons.first, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
Space spaceBetweenButtons = new Space(context);
spaceBetweenButtons.setLayoutParams(new LinearLayout.LayoutParams(Dim.dp8, ViewGroup.LayoutParams.WRAP_CONTENT));
buttonsRow.addView(spaceBetweenButtons);
buttonsRow.addView(moveButtons.second, new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
contentLayout.addView(headersLayout);
contentLayout.addView(columnsLayout);
contentLayout.addView(buttonsRow);
return contentLayout;
}
/**
* Creates a header TextView.
*/
private TextView createHeader(Context context, String tag) {
TextView textview = new TextView(context);
textview.setTag(tag);
textview.setTextSize(16);
textview.setTextColor(Utils.getAppForegroundColor());
textview.setGravity(Gravity.CENTER);
return textview;
}
/**
* Creates a single column (search + buttons + list).
*/
private View createColumn(Context context, TreeSet<Long> flags, TextView countText) {
LinearLayout wrapper = new LinearLayout(context);
wrapper.setOrientation(LinearLayout.VERTICAL);
Pair<ListView, FlagAdapter> pair = createListView(context, flags, countText);
ListView listView = pair.first;
FlagAdapter adapter = pair.second;
EditText search = createSearchBox(context, adapter, listView, countText);
LinearLayout buttons = createActionButtons(context, listView, adapter);
listView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Dim.roundedCorners(10), null, null));
background.getPaint().setColor(Utils.getEditTextBackground());
listView.setPadding(0, Dim.dp4, 0, Dim.dp4);
listView.setBackground(background);
listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
wrapper.addView(search);
wrapper.addView(buttons);
wrapper.addView(listView);
// Save references for move buttons.
wrapper.setTag(new ColumnViews(listView, adapter));
return wrapper;
}
/**
* Updates the header text with the current count.
*/
private void updateHeaderCount(TextView header, FlagAdapter adapter) {
header.setText(str((String) header.getTag(), adapter.getCount()));
}
/**
* Creates a search box that filters the list.
*/
@SuppressLint("ClickableViewAccessibility")
private EditText createSearchBox(Context context, FlagAdapter adapter, ListView listView, TextView countText) {
EditText search = new EditText(context);
search.setInputType(InputType.TYPE_CLASS_NUMBER);
search.setTextSize(16);
search.setHint(str("revanced_debug_feature_flags_manager_search_hint"));
search.setHapticFeedbackEnabled(false);
search.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
search.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) {
adapter.setSearchQuery(s.toString());
listView.clearChoices();
updateHeaderCount(countText, adapter);
Drawable clearIcon = context.getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel);
clearIcon.setBounds(0, 0, Dim.dp20, Dim.dp20);
search.setCompoundDrawables(null, null, TextUtils.isEmpty(s) ? null : clearIcon, null);
}
@Override public void afterTextChanged(Editable s) {}
});
search.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
Drawable[] compoundDrawables = search.getCompoundDrawables();
if (compoundDrawables[2] != null &&
event.getRawX() >= (search.getRight() - compoundDrawables[2].getBounds().width())) {
search.setText("");
return true;
}
}
return false;
});
return search;
}
/**
* Creates action buttons.
*/
private LinearLayout createActionButtons(Context context, ListView listView, FlagAdapter adapter) {
LinearLayout row = new LinearLayout(context);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setGravity(Gravity.CENTER);
row.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ImageButton selectAll = createButton(context, DRAWABLE_REVANCED_SETTINGS_SELECT_ALL,
() -> {
for (int i = 0, count = adapter.getCount(); i < count; i++) {
listView.setItemChecked(i, true);
}
});
ImageButton clearAll = createButton(context, DRAWABLE_REVANCED_SETTINGS_DESELECT_ALL,
() -> {
listView.clearChoices();
adapter.notifyDataSetChanged();
});
ImageButton copy = createButton(context, DRAWABLE_REVANCED_SETTINGS_COPY_ALL,
() -> {
List<String> items = new ArrayList<>();
SparseBooleanArray checked = listView.getCheckedItemPositions();
if (checked.size() > 0) {
for (int i = 0, count = adapter.getCount(); i < count; i++) {
if (checked.get(i)) {
items.add(adapter.getItem(i));
}
}
} else {
for (Long flag : adapter.getFullFlags()) {
items.add(String.valueOf(flag));
}
}
Utils.setClipboard(TextUtils.join("\n", items));
Utils.showToastShort(str("revanced_debug_feature_flags_manager_toast_copied"));
});
row.addView(selectAll);
row.addView(clearAll);
row.addView(copy);
return row;
}
/**
* Creates the move buttons (left and right groups).
*/
private Pair<LinearLayout, LinearLayout> createMoveButtons(Context context,
ListView availableListView, ListView blockedListView,
TreeSet<Long> availableFlags, TreeSet<Long> blockedFlags,
TextView availableCountText, TextView blockedCountText) {
// Left group: >> >
LinearLayout leftButtons = new LinearLayout(context);
leftButtons.setOrientation(LinearLayout.HORIZONTAL);
leftButtons.setGravity(Gravity.CENTER);
ImageButton moveAllRight = createButton(context, DRAWABLE_REVANCED_SETTINGS_ARROW_RIGHT_DOUBLE,
() -> moveFlags(availableListView, blockedListView, availableFlags, blockedFlags,
availableCountText, blockedCountText, true));
ImageButton moveOneRight = createButton(context, DRAWABLE_REVANCED_SETTINGS_ARROW_RIGHT_ONE,
() -> moveFlags(availableListView, blockedListView, availableFlags, blockedFlags,
availableCountText, blockedCountText, false));
leftButtons.addView(moveAllRight);
leftButtons.addView(moveOneRight);
// Right group: < <<
LinearLayout rightButtons = new LinearLayout(context);
rightButtons.setOrientation(LinearLayout.HORIZONTAL);
rightButtons.setGravity(Gravity.CENTER);
ImageButton moveOneLeft = createButton(context, DRAWABLE_REVANCED_SETTINGS_ARROW_LEFT_ONE,
() -> moveFlags(blockedListView, availableListView, blockedFlags, availableFlags,
blockedCountText, availableCountText, false));
ImageButton moveAllLeft = createButton(context, DRAWABLE_REVANCED_SETTINGS_ARROW_LEFT_DOUBLE,
() -> moveFlags(blockedListView, availableListView, blockedFlags, availableFlags,
blockedCountText, availableCountText, true));
rightButtons.addView(moveOneLeft);
rightButtons.addView(moveAllLeft);
return new Pair<>(leftButtons, rightButtons);
}
/**
* Creates a styled ImageButton.
*/
@SuppressLint("ResourceType")
private ImageButton createButton(Context context, int drawableResId, Runnable action) {
ImageButton button = new ImageButton(context);
button.setImageResource(drawableResId);
button.setScaleType(ImageView.ScaleType.CENTER);
int[] attrs = {android.R.attr.selectableItemBackgroundBorderless};
try (TypedArray ripple = context.obtainStyledAttributes(attrs)) {
button.setBackgroundDrawable(ripple.getDrawable(0));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Dim.dp32, Dim.dp32);
params.setMargins(Dim.dp8, Dim.dp8, Dim.dp8, Dim.dp8);
button.setLayoutParams(params);
button.setOnClickListener(v -> action.run());
return button;
}
/**
* Custom adapter with search filtering.
*/
private static class FlagAdapter extends ArrayAdapter<String> {
private final TreeSet<Long> fullFlags;
private String searchQuery = "";
public FlagAdapter(Context context, TreeSet<Long> fullFlags) {
super(context, android.R.layout.simple_list_item_multiple_choice, new ArrayList<>());
this.fullFlags = fullFlags;
updateFiltered();
}
public void setSearchQuery(String query) {
searchQuery = query == null ? "" : query.trim();
updateFiltered();
}
private void updateFiltered() {
clear();
for (Long flag : fullFlags) {
String flagString = String.valueOf(flag);
if (searchQuery.isEmpty() || flagString.contains(searchQuery)) {
add(flagString);
}
}
notifyDataSetChanged();
}
public void refresh() {
updateFiltered();
}
public List<Long> getFullFlags() {
return new ArrayList<>(fullFlags);
}
}
/**
* Creates a ListView with filtering, multi-select, and range selection.
*/
@SuppressLint("ClickableViewAccessibility")
private Pair<ListView, FlagAdapter> createListView(Context context,
TreeSet<Long> flags, TextView countText) {
ListView listView = new ListView(context);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setDividerHeight(0);
FlagAdapter adapter = new FlagAdapter(context, flags);
listView.setAdapter(adapter);
final ListViewSelectionState state = new ListViewSelectionState();
listView.setOnItemClickListener((parent, view, position, id) -> {
if (!state.isRangeSelecting) {
state.lastClickedPosition = position;
} else {
state.isRangeSelecting = false;
}
});
listView.setOnItemLongClickListener((parent, view, position, id) -> {
if (state.lastClickedPosition == -1) {
listView.setItemChecked(position, true);
state.lastClickedPosition = position;
} else {
int start = Math.min(state.lastClickedPosition, position);
int end = Math.max(state.lastClickedPosition, position);
for (int i = start; i <= end; i++) {
listView.setItemChecked(i, true);
}
state.isRangeSelecting = true;
}
return true;
});
listView.setOnTouchListener((view, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP && state.isRangeSelecting) {
state.isRangeSelecting = false;
}
return false;
});
return new Pair<>(listView, adapter);
}
/**
* Moves selected or all flags from one list to another.
*
* @param fromListView Source ListView.
* @param toListView Destination ListView.
* @param fromFlags Source flag set.
* @param toFlags Destination flag set.
* @param fromCountText Header showing count of source items.
* @param toCountText Header showing count of destination items.
* @param moveAll If true, move all items; if false, move only selected.
*/
private void moveFlags(ListView fromListView, ListView toListView,
TreeSet<Long> fromFlags, TreeSet<Long> toFlags,
TextView fromCountText, TextView toCountText,
boolean moveAll) {
if (fromListView == null || toListView == null) return;
List<Long> flagsToMove = new ArrayList<>();
FlagAdapter fromAdapter = (FlagAdapter) fromListView.getAdapter();
if (moveAll) {
flagsToMove.addAll(fromFlags);
} else {
SparseBooleanArray checked = fromListView.getCheckedItemPositions();
for (int i = 0, count = fromAdapter.getCount(); i < count; i++) {
if (checked.get(i)) {
String item = fromAdapter.getItem(i);
if (item != null) {
flagsToMove.add(Long.parseLong(item));
}
}
}
}
if (flagsToMove.isEmpty()) return;
for (Long flag : flagsToMove) {
fromFlags.remove(flag);
toFlags.add(flag);
}
// Clear selections before refreshing.
fromListView.clearChoices();
toListView.clearChoices();
// Refresh both adapters.
fromAdapter.refresh();
((FlagAdapter) toListView.getAdapter()).refresh();
// Update headers.
updateHeaderCount(fromCountText, fromAdapter);
updateHeaderCount(toCountText, (FlagAdapter) toListView.getAdapter());
}
/**
* Saves blocked flags to settings.
*/
private void saveFlags(TreeSet<Long> blockedFlags) {
StringBuilder flagsString = new StringBuilder();
for (Long flag : blockedFlags) {
if (flagsString.length() > 0) {
flagsString.append("\n");
}
flagsString.append(flag);
}
BaseSettings.DISABLED_FEATURE_FLAGS.save(flagsString.toString());
Utils.showToastShort(str("revanced_debug_feature_flags_manager_toast_saved"));
Logger.printDebug(() -> "Feature flags saved. Blocked: " + blockedFlags.size());
AbstractPreferenceFragment.showRestartDialog(getContext());
}
/**
* Resets all blocked flags.
*/
private void resetFlags() {
BaseSettings.DISABLED_FEATURE_FLAGS.save("");
Utils.showToastShort(str("revanced_debug_feature_flags_manager_toast_reset"));
AbstractPreferenceFragment.showRestartDialog(getContext());
}
}

View File

@@ -11,7 +11,6 @@ import android.preference.Preference;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
@@ -20,6 +19,7 @@ import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.settings.Setting;
import app.revanced.extension.shared.ui.CustomDialog;
import app.revanced.extension.shared.ui.Dim;
@SuppressWarnings({"unused", "deprecation"})
public class ImportExportPreference extends EditTextPreference implements Preference.OnPreferenceClickListener {
@@ -35,7 +35,7 @@ public class ImportExportPreference extends EditTextPreference implements Prefer
editText.setAutofillHints((String) null);
}
editText.setInputType(editText.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setTextSize(TypedValue.COMPLEX_UNIT_PT, 7); // Use a smaller font to reduce text wrap.
editText.setTextSize(14);
setOnPreferenceClickListener(this);
}

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.shared.settings.preference;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.shared.requests.Route.Method.GET;
import android.annotation.SuppressLint;
@@ -41,6 +40,7 @@ import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.requests.Requester;
import app.revanced.extension.shared.requests.Route;
import app.revanced.extension.shared.ui.Dim;
/**
* Opens a dialog showing official links.
@@ -222,11 +222,10 @@ class WebViewDialog extends Dialog {
LinearLayout mainLayout = new LinearLayout(getContext());
mainLayout.setOrientation(LinearLayout.VERTICAL);
final int padding = dipToPixels(10);
mainLayout.setPadding(padding, padding, padding, padding);
mainLayout.setPadding(Dim.dp10, Dim.dp10, Dim.dp10, Dim.dp10);
// Set rounded rectangle background.
ShapeDrawable mainBackground = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(28), null, null));
Dim.roundedCorners(28), null, null));
mainBackground.getPaint().setColor(Utils.getDialogBackgroundColor());
mainLayout.setBackground(mainBackground);

View File

@@ -8,7 +8,6 @@ import android.os.Build;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
@@ -20,6 +19,7 @@ import androidx.annotation.Nullable;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.settings.BaseActivityHook;
import app.revanced.extension.shared.ui.Dim;
@SuppressWarnings({"deprecation", "NewApi"})
public class ToolbarPreferenceFragment extends AbstractPreferenceFragment {
@@ -88,14 +88,13 @@ public class ToolbarPreferenceFragment extends AbstractPreferenceFragment {
toolbar.setNavigationIcon(getBackButtonDrawable());
toolbar.setNavigationOnClickListener(view -> preferenceScreenDialog.dismiss());
final int margin = Utils.dipToPixels(16);
toolbar.setTitleMargin(margin, 0, margin, 0);
toolbar.setTitleMargin(Dim.dp16, 0, Dim.dp16, 0);
TextView toolbarTextView = Utils.getChildView(toolbar,
true, TextView.class::isInstance);
if (toolbarTextView != null) {
toolbarTextView.setTextColor(Utils.getAppForegroundColor());
toolbarTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
toolbarTextView.setTextSize(20);
}
// Allow package-specific toolbar customization.

View File

@@ -484,7 +484,7 @@ public abstract class BaseSearchResultsAdapter extends ArrayAdapter<BaseSearchRe
return -1;
}
for (int i = 0; i < adapter.getCount(); i++) {
for (int i = 0, count = adapter.getCount(); i < count; i++) {
Object item = adapter.getItem(i);
if (item == targetPreference) {
return i;
@@ -522,8 +522,8 @@ public abstract class BaseSearchResultsAdapter extends ArrayAdapter<BaseSearchRe
if (currentAnimator != null && currentAnimator.isRunning()) {
currentAnimator.cancel();
}
int startColor = Utils.getAppBackgroundColor();
int highlightColor = Utils.adjustColorBrightness(
final int startColor = Utils.getAppBackgroundColor();
final int highlightColor = Utils.adjustColorBrightness(
startColor,
Utils.isDarkModeEnabled() ? 1.25f : 0.8f
);
@@ -566,7 +566,7 @@ public abstract class BaseSearchResultsAdapter extends ArrayAdapter<BaseSearchRe
}
// First search on current level.
for (int i = 0; i < group.getPreferenceCount(); i++) {
for (int i = 0, count = group.getPreferenceCount(); i < count; i++) {
Preference pref = group.getPreference(i);
if (key.equals(pref.getKey())) {
return pref;

View File

@@ -13,7 +13,6 @@ import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
@@ -45,6 +44,7 @@ import app.revanced.extension.shared.settings.Setting;
import app.revanced.extension.shared.settings.preference.ColorPickerPreference;
import app.revanced.extension.shared.settings.preference.CustomDialogListPreference;
import app.revanced.extension.shared.settings.preference.NoTitlePreferenceCategory;
import app.revanced.extension.shared.ui.Dim;
/**
* Abstract controller for managing the overlay search view in ReVanced settings.
@@ -123,7 +123,7 @@ public abstract class BaseSearchViewController {
searchView.setQueryHint(str("revanced_settings_search_hint"));
// Set text size.
searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
searchEditText.setTextSize(16);
// Set cursor color.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
@@ -149,7 +149,7 @@ public abstract class BaseSearchViewController {
// Create cursor drawable.
GradientDrawable cursorDrawable = new GradientDrawable();
cursorDrawable.setShape(GradientDrawable.RECTANGLE);
cursorDrawable.setSize(Utils.dipToPixels(2), -1); // Width: 2dp, Height: match text height.
cursorDrawable.setSize(Dim.dp2, -1); // Width: 2dp, Height: match text height.
cursorDrawable.setColor(cursorColor);
// Set cursor drawable.
@@ -164,7 +164,7 @@ public abstract class BaseSearchViewController {
overlayContainer = new FrameLayout(activity);
overlayContainer.setVisibility(View.GONE);
overlayContainer.setBackgroundColor(Utils.getAppBackgroundColor());
overlayContainer.setElevation(Utils.dipToPixels(8));
overlayContainer.setElevation(Dim.dp8);
// Container for search results.
FrameLayout searchResultsContainer = new FrameLayout(activity);
@@ -669,7 +669,7 @@ public abstract class BaseSearchViewController {
protected static GradientDrawable createBackgroundDrawable() {
GradientDrawable background = new GradientDrawable();
background.setShape(GradientDrawable.RECTANGLE);
background.setCornerRadius(Utils.dipToPixels(28));
background.setCornerRadius(Dim.dp28);
background.setColor(getSearchViewBackground());
return background;
}

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.shared.ui;
import static app.revanced.extension.shared.Utils.adjustColorBrightness;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.shared.Utils.getAppBackgroundColor;
import static app.revanced.extension.shared.Utils.isDarkModeEnabled;
import static app.revanced.extension.shared.settings.preference.ColorPickerPreference.DISABLED_ALPHA;
@@ -13,7 +12,7 @@ import android.view.View;
import androidx.annotation.ColorInt;
public class ColorDot {
private static final int STROKE_WIDTH = dipToPixels(1.5f); // Stroke width in dp.
private static final int STROKE_WIDTH = Dim.dp(1.5f);
/**
* Creates a circular drawable with a main fill and a stroke.
@@ -55,7 +54,7 @@ public class ColorDot {
targetView.setAlpha(enabled ? 1.0f : DISABLED_ALPHA);
if (!isDarkModeEnabled()) {
targetView.setClipToOutline(true);
targetView.setElevation(dipToPixels(2));
targetView.setElevation(Dim.dp2);
}
}
}

View File

@@ -1,7 +1,5 @@
package app.revanced.extension.shared.ui;
import static app.revanced.extension.shared.Utils.dipToPixels;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
@@ -37,7 +35,6 @@ public class CustomDialog {
private final Context context;
private final Dialog dialog;
private final LinearLayout mainLayout;
private final int dip4, dip8, dip16, dip24, dip36;
/**
* Creates a custom dialog with a styled layout, including a title, message, buttons, and an optional EditText.
@@ -93,13 +90,6 @@ public class CustomDialog {
this.dialog = new Dialog(context);
this.dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Remove default title bar.
// Preset size constants.
dip4 = dipToPixels(4);
dip8 = dipToPixels(8);
dip16 = dipToPixels(16);
dip24 = dipToPixels(24);
dip36 = dipToPixels(36);
// Create main layout.
mainLayout = createMainLayout();
addTitle(title);
@@ -122,11 +112,11 @@ public class CustomDialog {
private LinearLayout createMainLayout() {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(dip24, dip16, dip24, dip24);
layout.setPadding(Dim.dp24, Dim.dp16, Dim.dp24, Dim.dp24);
// Set rounded rectangle background.
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(28), null, null));
Dim.roundedCorners(28), null, null));
// Dialog background.
background.getPaint().setColor(Utils.getDialogBackgroundColor());
layout.setBackground(background);
@@ -152,7 +142,7 @@ public class CustomDialog {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 0, dip16);
params.setMargins(0, 0, 0, Dim.dp16);
titleView.setLayoutParams(params);
mainLayout.addView(titleView);
@@ -180,9 +170,9 @@ public class CustomDialog {
// EditText (if provided).
if (editText != null) {
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(10), null, null));
Dim.roundedCorners(10), null, null));
background.getPaint().setColor(Utils.getEditTextBackground());
scrollView.setPadding(dip8, dip8, dip8, dip8);
scrollView.setPadding(Dim.dp8, Dim.dp8, Dim.dp8, Dim.dp8);
scrollView.setBackground(background);
scrollView.setClipToOutline(true);
@@ -241,7 +231,7 @@ public class CustomDialog {
LinearLayout.LayoutParams buttonContainerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
buttonContainerParams.setMargins(0, dip16, 0, 0);
buttonContainerParams.setMargins(0, Dim.dp16, 0, 0);
buttonContainer.setLayoutParams(buttonContainerParams);
List<Button> buttons = new ArrayList<>();
@@ -289,12 +279,12 @@ public class CustomDialog {
button.setEllipsize(TextUtils.TruncateAt.END);
button.setGravity(Gravity.CENTER);
// Set internal padding.
button.setPadding(dip16, 0, dip16, 0);
button.setPadding(Dim.dp16, 0, Dim.dp16, 0);
// Background color for OK button (inversion).
// Background color for Cancel or Neutral buttons.
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(20), null, null));
Dim.roundedCorners(20), null, null));
background.getPaint().setColor(isOkButton
? Utils.getOkButtonBackgroundColor()
: Utils.getCancelOrNeutralButtonBackgroundColor());
@@ -331,20 +321,19 @@ public class CustomDialog {
if (buttons.isEmpty()) return;
// Check if buttons fit in one row.
int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
int totalWidth = 0;
for (Integer width : buttonWidths) {
totalWidth += width;
}
if (buttonWidths.size() > 1) {
// Add margins for gaps.
totalWidth += (buttonWidths.size() - 1) * dip8;
totalWidth += (buttonWidths.size() - 1) * Dim.dp8;
}
// Single button: stretch to full width.
if (buttons.size() == 1) {
layoutSingleButton(buttonContainer, buttons.get(0));
} else if (totalWidth <= screenWidth * 0.8) {
} else if (totalWidth <= Dim.pctWidth(80)) {
// Single row: Neutral, Cancel, OK.
layoutButtonsInRow(buttonContainer, buttons, buttonWidths);
} else {
@@ -369,7 +358,7 @@ public class CustomDialog {
button.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dip36));
Dim.dp36));
singleContainer.addView(button);
buttonContainer.addView(singleContainer);
}
@@ -405,17 +394,17 @@ public class CustomDialog {
if (parent != null) parent.removeView(button);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
0, dip36, buttonWidths.get(i));
0, Dim.dp36, buttonWidths.get(i));
// Set margins based on button type and combination.
if (buttons.size() == 2) {
// Neutral + OK or Cancel + OK.
params.setMargins(i == 0 ? 0 : dip4, 0, i == 0 ? dip4 : 0, 0);
params.setMargins(i == 0 ? 0 : Dim.dp4, 0, i == 0 ? Dim.dp4 : 0, 0);
} else if (buttons.size() == 3) {
// Neutral.
// Cancel.
// OK.
params.setMargins(i == 0 ? 0 : dip4, 0, i == 2 ? 0 : dip4, 0);
params.setMargins(i == 0 ? 0 : Dim.dp4, 0, i == 2 ? 0 : Dim.dp4, 0);
}
button.setLayoutParams(params);
@@ -447,14 +436,14 @@ public class CustomDialog {
singleContainer.setGravity(Gravity.CENTER);
singleContainer.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dip36));
Dim.dp36));
ViewGroup parent = (ViewGroup) button.getParent();
if (parent != null) parent.removeView(button);
button.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dip36));
Dim.dp36));
singleContainer.addView(button);
buttonContainer.addView(singleContainer);
@@ -463,7 +452,7 @@ public class CustomDialog {
View spacer = new View(context);
LinearLayout.LayoutParams spacerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dip8);
Dim.dp8);
spacer.setLayoutParams(spacerParams);
buttonContainer.addView(spacer);
}

View File

@@ -0,0 +1,89 @@
package app.revanced.extension.shared.ui;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.TypedValue;
/**
* Utility class for converting design units (dp) and screen percentages to pixels.
*/
public final class Dim {
private Dim() {} // Prevent instantiation.
private static final DisplayMetrics METRICS = Resources.getSystem().getDisplayMetrics();
public static final int SCREEN_WIDTH = METRICS.widthPixels;
public static final int SCREEN_HEIGHT = METRICS.heightPixels;
// DP constants (density-independent pixels).
public static final int dp1 = dp(1);
public static final int dp2 = dp(2);
public static final int dp4 = dp(4);
public static final int dp6 = dp(6);
public static final int dp7 = dp(7);
public static final int dp8 = dp(8);
public static final int dp10 = dp(10);
public static final int dp12 = dp(12);
public static final int dp16 = dp(16);
public static final int dp20 = dp(20);
public static final int dp24 = dp(24);
public static final int dp28 = dp(28);
public static final int dp32 = dp(32);
public static final int dp36 = dp(36);
public static final int dp40 = dp(40);
public static final int dp48 = dp(48);
/**
* Converts dp (density-independent pixels) to actual device pixels.
* Uses Android's official TypedValue.applyDimension() for accurate rounding.
*
* @param dp The dp value to convert (supports float, e.g. 1.2f).
* @return The equivalent pixel value as int.
*/
public static int dp(float dp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, METRICS);
}
/**
* Converts a percentage of the screen height to pixels.
*
* @param percent The percentage (0100).
* @return The pixel value corresponding to the percentage of screen height.
*/
public static int pctHeight(int percent) {
return (SCREEN_HEIGHT * percent) / 100;
}
/**
* Converts a percentage of the screen width to pixels.
*
* @param percent The percentage (0100).
* @return The pixel value corresponding to the percentage of screen width.
*/
public static int pctWidth(int percent) {
return (SCREEN_WIDTH * percent) / 100;
}
/**
* Converts a percentage of the screen's portrait width (min side) to pixels.
*
* @param percent The percentage (0100).
* @return The pixel value.
*/
public static int pctPortraitWidth(int percent) {
final int portraitWidth = Math.min(SCREEN_WIDTH, SCREEN_HEIGHT);
return (int) (portraitWidth * (percent / 100.0f));
}
/**
* Creates an array of corner radii for a rounded rectangle.
* All corners use the same radius.
*
* @param dp radius in density-independent pixels
* @return array of 8 floats: [top-left-x, top-left-y, top-right-x, top-right-y, ...]
*/
public static float[] roundedCorners(float dp) {
final float r = dp(dp);
return new float[]{r, r, r, r, r, r, r, r};
}
}

View File

@@ -1,7 +1,5 @@
package app.revanced.extension.shared.ui;
import static app.revanced.extension.shared.Utils.dipToPixels;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
@@ -63,9 +61,8 @@ public class SheetBottomDialog {
// Add top spacer.
View spacer = new View(context);
final int dip40 = dipToPixels(40);
LinearLayout.LayoutParams spacerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, dip40);
LinearLayout.LayoutParams.MATCH_PARENT, Dim.dp40);
spacer.setLayoutParams(spacerParams);
spacer.setClickable(true);
dragContainer.addView(spacer);
@@ -105,20 +102,15 @@ public class SheetBottomDialog {
* @return A configured {@link DraggableLinearLayout} with a handle bar and styled background.
*/
public static DraggableLinearLayout createMainLayout(@NonNull Context context, @Nullable Integer backgroundColor) {
// Preset size constants.
final int dip4 = dipToPixels(4); // Handle bar height.
final int dip8 = dipToPixels(8); // Dialog padding.
final int dip40 = dipToPixels(40); // Handle bar width.
DraggableLinearLayout mainLayout = new DraggableLinearLayout(context);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(dip8, 0, dip8, dip8);
layoutParams.setMargins(Dim.dp8, 0, Dim.dp8, Dim.dp8);
mainLayout.setLayoutParams(layoutParams);
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(12), null, null));
Dim.roundedCorners(12), null, null));
int color = (backgroundColor != null) ? backgroundColor : Utils.getDialogBackgroundColor();
background.getPaint().setColor(color);
mainLayout.setBackground(background);
@@ -127,14 +119,14 @@ public class SheetBottomDialog {
LinearLayout handleContainer = new LinearLayout(context);
LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
containerParams.setMargins(0, dip8, 0, 0);
containerParams.setMargins(0, Dim.dp8, 0, 0);
handleContainer.setLayoutParams(containerParams);
handleContainer.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
View handleBar = new View(context);
ShapeDrawable handleBackground = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(4), null, null));
Dim.roundedCorners(4), null, null));
handleBackground.getPaint().setColor(Utils.adjustColorBrightness(color, 0.9f, 1.25f));
LinearLayout.LayoutParams handleParams = new LinearLayout.LayoutParams(dip40, dip4);
LinearLayout.LayoutParams handleParams = new LinearLayout.LayoutParams(Dim.dp40, Dim.dp4);
handleBar.setLayoutParams(handleParams);
handleBar.setBackground(handleBackground);

View File

@@ -4,6 +4,7 @@ import android.view.View;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.settings.Settings;
@SuppressWarnings("unused")
@@ -31,7 +32,7 @@ public final class WideSearchbarPatch {
final int paddingRight = searchBarView.getPaddingRight();
final int paddingTop = searchBarView.getPaddingTop();
final int paddingBottom = searchBarView.getPaddingBottom();
final int paddingStart = Utils.dipToPixels(8);
final int paddingStart = Dim.dp8;
if (Utils.isRightToLeftLocale()) {
searchBarView.setPadding(paddingLeft, paddingTop, paddingStart, paddingBottom);

View File

@@ -2,7 +2,6 @@ package app.revanced.extension.youtube.patches.announcements;
import static android.text.Html.FROM_HTML_MODE_COMPACT;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.youtube.patches.announcements.requests.AnnouncementsRoutes.GET_LATEST_ANNOUNCEMENTS;
import static app.revanced.extension.youtube.patches.announcements.requests.AnnouncementsRoutes.GET_LATEST_ANNOUNCEMENT_IDS;
@@ -24,6 +23,7 @@ import java.time.LocalDateTime;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.requests.Requester;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.patches.announcements.requests.AnnouncementsRoutes;
import app.revanced.extension.youtube.settings.Settings;
@@ -148,7 +148,7 @@ public final class AnnouncementsPatch {
if (child instanceof TextView childTextView && finalTitle.equals(childTextView.getText().toString())) {
childTextView.setCompoundDrawablesWithIntrinsicBounds(
finalLevel.icon, 0, 0, 0);
childTextView.setCompoundDrawablePadding(dipToPixels(8));
childTextView.setCompoundDrawablePadding(Dim.dp8);
}
}

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.youtube.patches.playback.speed;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.youtube.videoplayer.PlayerControlButton.fadeInDuration;
import static app.revanced.extension.youtube.videoplayer.PlayerControlButton.getDialogBackgroundColor;
@@ -30,6 +29,7 @@ import java.util.function.Function;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.shared.ui.SheetBottomDialog;
import app.revanced.extension.youtube.patches.VideoInformation;
import app.revanced.extension.youtube.patches.components.PlaybackSpeedMenuFilter;
@@ -264,14 +264,6 @@ public class CustomPlaybackSpeedPatch {
SheetBottomDialog.DraggableLinearLayout mainLayout =
SheetBottomDialog.createMainLayout(context, getDialogBackgroundColor());
// Preset size constants.
final int dip4 = dipToPixels(4);
final int dip8 = dipToPixels(8);
final int dip12 = dipToPixels(12);
final int dip20 = dipToPixels(20);
final int dip32 = dipToPixels(32);
final int dip60 = dipToPixels(60);
// Display current playback speed.
TextView currentSpeedText = new TextView(context);
float currentSpeed = VideoInformation.getPlaybackSpeed();
@@ -283,7 +275,7 @@ public class CustomPlaybackSpeedPatch {
currentSpeedText.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.setMargins(0, dip20, 0, 0);
textParams.setMargins(0, Dim.dp20, 0, 0);
currentSpeedText.setLayoutParams(textParams);
// Add current speed text view to main layout.
mainLayout.addView(currentSpeedText);
@@ -294,8 +286,8 @@ public class CustomPlaybackSpeedPatch {
sliderLayout.setGravity(Gravity.CENTER_VERTICAL);
// Create +/- buttons.
Button minusButton = createStyledButton(context, false, dip8, dip8);
Button plusButton = createStyledButton(context, true, dip8, dip8);
Button minusButton = createStyledButton(context, false);
Button plusButton = createStyledButton(context, true);
// Create slider for speed adjustment.
SeekBar speedSlider = new SeekBar(context);
@@ -363,7 +355,7 @@ public class CustomPlaybackSpeedPatch {
gridLayout.setRowCount((int) Math.ceil(customPlaybackSpeeds.length / 5.0));
LinearLayout.LayoutParams gridParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
gridParams.setMargins(dip4, dip12, dip4, dip12); // Speed buttons container.
gridParams.setMargins(Dim.dp4, Dim.dp12, Dim.dp4, Dim.dp12); // Speed buttons container.
gridLayout.setLayoutParams(gridParams);
// For button use 1 digit minimum.
@@ -378,8 +370,8 @@ public class CustomPlaybackSpeedPatch {
GridLayout.LayoutParams containerParams = new GridLayout.LayoutParams();
containerParams.width = 0; // Equal width for columns.
containerParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f);
containerParams.setMargins(dip4, 0, dip4, 0); // Button margins.
containerParams.height = dip60; // Fixed height for button and label.
containerParams.setMargins(Dim.dp4, 0, Dim.dp4, 0); // Button margins.
containerParams.height = Dim.dp(60); // Fixed height for button and label.
buttonContainer.setLayoutParams(containerParams);
// Create speed button.
@@ -391,14 +383,14 @@ public class CustomPlaybackSpeedPatch {
speedButton.setGravity(Gravity.CENTER);
ShapeDrawable buttonBackground = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(20), null, null));
Dim.roundedCorners(20), null, null));
buttonBackground.getPaint().setColor(getAdjustedBackgroundColor(false));
speedButton.setBackground(buttonBackground);
speedButton.setPadding(dip4, dip4, dip4, dip4);
speedButton.setPadding(Dim.dp4, Dim.dp4, Dim.dp4, Dim.dp4);
// Center button vertically and stretch horizontally in container.
FrameLayout.LayoutParams buttonParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, dip32, Gravity.CENTER);
FrameLayout.LayoutParams.MATCH_PARENT, Dim.dp32, Gravity.CENTER);
speedButton.setLayoutParams(buttonParams);
// Add speed buttons view to buttons container layout.
@@ -475,21 +467,18 @@ public class CustomPlaybackSpeedPatch {
*
* @param context The Android context used to create the button.
* @param isPlus True to display a plus symbol, false to display a minus symbol.
* @param marginStart The start margin in pixels (left for LTR, right for RTL).
* @param marginEnd The end margin in pixels (right for LTR, left for RTL).
* @return A configured {@link Button} with the specified styling and layout parameters.
*/
private static Button createStyledButton(Context context, boolean isPlus, int marginStart, int marginEnd) {
private static Button createStyledButton(Context context, boolean isPlus) {
Button button = new Button(context, null, 0); // Disable default theme style.
button.setText(""); // No text on button.
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(20), null, null));
Dim.roundedCorners(20), null, null));
background.getPaint().setColor(getAdjustedBackgroundColor(false));
button.setBackground(background);
button.setForeground(new OutlineSymbolDrawable(isPlus)); // Plus or minus symbol.
final int dip36 = dipToPixels(36);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dip36, dip36);
params.setMargins(marginStart, 0, marginEnd, 0); // Set margins.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Dim.dp36, Dim.dp36);
params.setMargins(Dim.dp8, 0, Dim.dp8, 0); // Set margins.
button.setLayoutParams(params);
return button;
}
@@ -554,7 +543,7 @@ class OutlineSymbolDrawable extends Drawable {
paint = new Paint(Paint.ANTI_ALIAS_FLAG); // Enable anti-aliasing for smooth rendering.
paint.setColor(Utils.getAppForegroundColor());
paint.setStyle(Paint.Style.STROKE); // Use stroke style for outline.
paint.setStrokeWidth(dipToPixels(1)); // 1dp stroke width.
paint.setStrokeWidth(Dim.dp1); // 1dp stroke width.
}
@Override

View File

@@ -40,6 +40,7 @@ import java.util.concurrent.TimeoutException;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.returnyoutubedislike.requests.RYDVoteData;
import app.revanced.extension.youtube.returnyoutubedislike.requests.ReturnYouTubeDislikeApi;
import app.revanced.extension.youtube.settings.Settings;
@@ -124,12 +125,12 @@ public class ReturnYouTubeDislike {
static {
leftSeparatorBounds = new Rect(0, 0,
Utils.dipToPixels(1.2f),
Utils.dipToPixels(14f));
final int middleSeparatorSize = Utils.dipToPixels(3.7f);
Dim.dp(1.2f),
Dim.dp(14f));
final int middleSeparatorSize = Dim.dp(3.7f);
middleSeparatorBounds = new Rect(0, 0, middleSeparatorSize, middleSeparatorSize);
leftSeparatorShapePaddingPixels = Utils.dipToPixels(8.4f);
leftSeparatorShapePaddingPixels = Dim.dp(8.4f);
leftSeparatorShape = new ShapeDrawable(new RectShape());
leftSeparatorShape.setBounds(leftSeparatorBounds);

View File

@@ -2,7 +2,6 @@ package app.revanced.extension.youtube.settings.preference;
import static app.revanced.extension.shared.StringRef.sf;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import android.app.Dialog;
import android.content.Context;
@@ -15,13 +14,9 @@ import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import androidx.annotation.Nullable;
@@ -37,6 +32,7 @@ import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.settings.preference.CustomDialogListPreference;
import app.revanced.extension.shared.ui.CustomDialog;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.settings.Settings;
/**
@@ -264,42 +260,12 @@ public class ExternalDownloaderPreference extends CustomDialogListPreference {
// Add ListView to content layout with initial height.
LinearLayout.LayoutParams listViewParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0 // Initial height, will be updated.
);
listViewParams.bottomMargin = dipToPixels(16);
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1.0f);
listViewParams.bottomMargin = Dim.dp16;
contentLayout.addView(listView, listViewParams);
// Add EditText for custom package name.
editText = new EditText(context);
editText.setText(packageName);
editText.setSelection(packageName.length());
editText.setHint(str("revanced_external_downloader_other_item_hint"));
editText.setSingleLine(true); // Restrict EditText to a single line.
editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
// Set initial EditText state based on selected downloader.
editText.setEnabled(usingCustomDownloader);
editText.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 edit) {
String updatedPackageName = edit.toString().trim();
updateListViewSelection.apply(updatedPackageName);
}
});
ShapeDrawable editTextBackground = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(10), null, null));
editTextBackground.getPaint().setColor(Utils.getEditTextBackground());
final int dip8 = dipToPixels(8);
editText.setPadding(dip8, dip8, dip8, dip8);
editText.setBackground(editTextBackground);
editText.setClipToOutline(true);
editText = createEditText(context, packageName, usingCustomDownloader, updateListViewSelection);
contentLayout.addView(editText);
// Create the custom dialog.
@@ -350,50 +316,59 @@ public class ExternalDownloaderPreference extends CustomDialogListPreference {
);
// Add the content layout directly to the dialog's main layout.
LinearLayout dialogMainLayout = dialogPair.second;
dialogMainLayout.addView(contentLayout, dialogMainLayout.getChildCount() - 1);
LinearLayout mainLayout = dialogPair.second;
LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1.0f);
// Update ListView height dynamically based on orientation.
//noinspection ExtractMethodRecommender
Runnable updateListViewHeight = () -> {
int totalHeight = 0;
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final int listAdapterCount = listAdapter.getCount();
for (int i = 0; i < listAdapterCount; i++) {
View item = listAdapter.getView(i, null, listView);
item.measure(
View.MeasureSpec.makeMeasureSpec(metrics.widthPixels, View.MeasureSpec.AT_MOST),
View.MeasureSpec.UNSPECIFIED
);
totalHeight += item.getMeasuredHeight();
}
totalHeight += listView.getDividerHeight() * (listAdapterCount - 1);
// Insert content before the dialog button row.
mainLayout.addView(contentLayout, mainLayout.getChildCount() - 1, contentParams);
Dialog dialog = dialogPair.first;
dialog.show();
}
/**
* Creates and configures the EditText for the custom package name.
*
* @param context Context for creating views.
* @param initialPackageName The package name to pre-fill.
* @param isCustom Whether the "Other" option is selected.
* @param textChangeCallback Callback to run when text changes.
* @return A configured EditText.
*/
private EditText createEditText(Context context,
String initialPackageName, boolean isCustom,
Function<String, Void> textChangeCallback) {
EditText editText = new EditText(context);
editText.setText(initialPackageName);
editText.setSelection(initialPackageName.length());
editText.setHint(str("revanced_external_downloader_other_item_hint"));
editText.setSingleLine(true);
editText.setTextSize(16);
editText.setEnabled(isCustom);
editText.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 edit) {
String updatedPackageName = edit.toString().trim();
textChangeCallback.apply(updatedPackageName);
}
});
final int orientation = context.getResources().getConfiguration().orientation;
if (orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT) {
// In portrait orientation, use WRAP_CONTENT for ListView height.
listViewParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else {
// In landscape orientation, limit ListView height to 30% of screen height.
final int maxHeight = Utils.percentageHeightToPixels(30);
listViewParams.height = Math.min(totalHeight, maxHeight);
}
listView.setLayoutParams(listViewParams);
};
ShapeDrawable editTextBackground = new ShapeDrawable(new RoundRectShape(
Dim.roundedCorners(10), null, null));
editTextBackground.getPaint().setColor(Utils.getEditTextBackground());
editText.setPadding(Dim.dp8, Dim.dp8, Dim.dp8, Dim.dp8);
editText.setBackground(editTextBackground);
editText.setClipToOutline(true);
// Initial height calculation.
updateListViewHeight.run();
// Listen for configuration changes (e.g., orientation).
View dialogView = dialogPair.second;
// Recalculate height when layout changes (e.g., orientation change).
dialogView.getViewTreeObserver().addOnGlobalLayoutListener(updateListViewHeight::run);
// Show the dialog.
dialogPair.first.show();
return editText;
}
/**

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.youtube.sponsorblock;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.youtube.sponsorblock.objects.CategoryBehaviour.SKIP_AUTOMATICALLY;
import android.annotation.SuppressLint;
@@ -34,6 +33,7 @@ import java.util.Objects;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.patches.VideoInformation;
import app.revanced.extension.youtube.settings.Settings;
import app.revanced.extension.youtube.shared.PlayerType;
@@ -82,7 +82,7 @@ public class SegmentPlaybackController {
* Highlight segments have zero length as they are a point in time.
* Draw them on screen using a fixed width bar.
*/
private static final int HIGHLIGHT_SEGMENT_DRAW_BAR_WIDTH = dipToPixels(7);
private static final int HIGHLIGHT_SEGMENT_DRAW_BAR_WIDTH = Dim.dp7;
@Nullable
private static String currentVideoId;
@@ -808,14 +808,12 @@ public class SegmentPlaybackController {
LinearLayout mainLayout = new LinearLayout(currentContext);
mainLayout.setOrientation(LinearLayout.VERTICAL);
final int dip8 = dipToPixels(8);
final int dip16 = dipToPixels(16);
mainLayout.setPadding(dip16, dip8, dip16, dip8);
mainLayout.setPadding(Dim.dp16, Dim.dp8, Dim.dp16, Dim.dp8);
mainLayout.setGravity(Gravity.CENTER);
mainLayout.setMinimumHeight(dipToPixels(48));
mainLayout.setMinimumHeight(Dim.dp48);
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(
Utils.createCornerRadii(20), null, null));
Dim.roundedCorners(20), null, null));
background.getPaint().setColor(Utils.getDialogBackgroundColor());
mainLayout.setBackground(background);

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.youtube.sponsorblock.objects;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.youtube.sponsorblock.SponsorBlockSettings.migrateOldColorString;
import android.content.Context;
@@ -17,6 +16,7 @@ import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.Utils;
import app.revanced.extension.shared.settings.preference.ColorPickerPreference;
import app.revanced.extension.shared.ui.ColorDot;
import app.revanced.extension.shared.ui.Dim;
@SuppressWarnings("deprecation")
public class SegmentCategoryPreference extends ColorPickerPreference {
@@ -110,7 +110,7 @@ public class SegmentCategoryPreference extends ColorPickerPreference {
}
radioGroup.setOnCheckedChangeListener((group, checkedId) -> selectedDialogEntryIndex = checkedId);
radioGroup.setPadding(dipToPixels(10), 0, dipToPixels(10), dipToPixels(10));
radioGroup.setPadding(Dim.dp10, 0, Dim.dp10, Dim.dp10);
return radioGroup;
}

View File

@@ -15,6 +15,7 @@ import android.widget.FrameLayout;
import android.widget.ImageButton;
import app.revanced.extension.shared.Logger;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.patches.VideoInformation;
import app.revanced.extension.youtube.settings.Settings;
import app.revanced.extension.youtube.sponsorblock.SponsorBlockUtils;
@@ -132,9 +133,7 @@ public final class NewSegmentLayout extends FrameLayout {
GradientDrawable backgroundDrawable = new GradientDrawable();
backgroundDrawable.setColor(getResourceColor("skip_ad_button_background_color"));
final float cornerRadius = squareLayout
? 0
: 16 * getResources().getDisplayMetrics().density;
final float cornerRadius = squareLayout ? 0f : Dim.dp16;
backgroundDrawable.setCornerRadius(cornerRadius);
setBackground(backgroundDrawable);
}

View File

@@ -18,7 +18,6 @@ import android.preference.SwitchPreference;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
@@ -34,6 +33,7 @@ import app.revanced.extension.shared.settings.Setting;
import app.revanced.extension.shared.settings.preference.CustomDialogListPreference;
import app.revanced.extension.shared.settings.preference.ResettableEditTextPreference;
import app.revanced.extension.shared.ui.CustomDialog;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.youtube.settings.Settings;
import app.revanced.extension.youtube.sponsorblock.SegmentPlaybackController;
import app.revanced.extension.youtube.sponsorblock.SponsorBlockSettings;
@@ -507,7 +507,7 @@ public class SponsorBlockPreferenceGroup extends PreferenceGroup {
EditText editText = getEditText();
editText.setInputType(editText.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setTextSize(TypedValue.COMPLEX_UNIT_PT, 7); // Use a smaller font to reduce text wrap.
editText.setTextSize(14);
// Create a custom dialog.
Pair<Dialog, LinearLayout> dialogPair = CustomDialog.create(
@@ -550,7 +550,7 @@ public class SponsorBlockPreferenceGroup extends PreferenceGroup {
| InputType.TYPE_TEXT_FLAG_MULTI_LINE
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setAutofillHints((String) null);
editText.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);
editText.setTextSize(14);
// Set preference listeners.
importExport.setOnPreferenceClickListener(preference1 -> {

View File

@@ -1,7 +1,6 @@
package app.revanced.extension.youtube.videoplayer;
import static app.revanced.extension.shared.StringRef.str;
import static app.revanced.extension.shared.Utils.dipToPixels;
import static app.revanced.extension.shared.settings.preference.CustomDialogListPreference.*;
import static app.revanced.extension.youtube.patches.VideoInformation.AUTOMATIC_VIDEO_QUALITY_VALUE;
import static app.revanced.extension.youtube.patches.VideoInformation.VIDEO_QUALITY_PREMIUM_NAME;
@@ -21,6 +20,7 @@ import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import app.revanced.extension.shared.ui.Dim;
import app.revanced.extension.shared.ui.SheetBottomDialog;
import app.revanced.extension.youtube.shared.PlayerType;
import com.google.android.libraries.youtube.innertube.model.media.VideoQuality;
@@ -214,11 +214,6 @@ public class VideoQualityDialogButton {
}
}
// Preset size constants.
final int dip8 = dipToPixels(8);
final int dip12 = dipToPixels(12);
final int dip16 = dipToPixels(16);
// Create main layout.
SheetBottomDialog.DraggableLinearLayout mainLayout =
SheetBottomDialog.createMainLayout(context, getDialogBackgroundColor());
@@ -269,7 +264,7 @@ public class VideoQualityDialogButton {
LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
titleParams.setMargins(dip12, dip16, 0, dip16);
titleParams.setMargins(Dim.dp12, Dim.dp16, 0, Dim.dp16);
titleView.setLayoutParams(titleParams);
mainLayout.addView(titleView);