package org.saturnclient.ui.elements; import java.util.function.BooleanSupplier; import org.saturnclient.config.Theme; import org.saturnclient.ui.Element; import org.saturnclient.ui.ElementContext; import org.saturnclient.ui.RenderScope; import org.saturnclient.ui.components.inputs.Toggle; import org.saturnclient.ui.resources.Fonts; /** * A labelled on/off switch ("Enabled" / "Disabled") that tints itself with the * accent color while on. */ public class SwitchButton extends Element { private static final int HEIGHT = 34; private static final int PADDING_LEFT = 14; private static final int PADDING_RIGHT = 5; private static final int GAP = 10; private static final float TEXT_SCALE = 0.66f; private final String onText; private final String offText; private final BooleanSupplier value; private final Runnable onToggle; public SwitchButton(String onText, String offText, BooleanSupplier value, Runnable onToggle) { this.onText = onText; this.offText = offText; this.value = value; this.onToggle = onToggle; this.height = HEIGHT; // Sized for the longer label, so the button doesn't change width when toggled int textWidth = Math.max(Fonts.getWidth(onText, Theme.FONT.value), Fonts.getWidth(offText, Theme.FONT.value)); this.width = PADDING_LEFT + (int) (textWidth * TEXT_SCALE) + GAP + Toggle.SWITCH_WIDTH + PADDING_RIGHT; } @Override public void render(RenderScope renderScope, ElementContext ctx) { boolean on = value.getAsBoolean(); float tint = ctx.isHovering() ? 0.1f : 0.06f; renderScope.drawRoundedRectangle(0, 0, width, height, Theme.WIDGET_RADIUS.value, on ? Theme.withAlpha(tint * 2.5f, Theme.ACCENT.value) : Theme.withAlpha(tint, Theme.FOREGROUND.value)); renderScope.drawText(TEXT_SCALE, on ? onText : offText, PADDING_LEFT, Field.textY(height, TEXT_SCALE), Theme.FONT.value, on ? Theme.ACCENT.value : Theme.PRIMARY_FG.value); Toggle.drawSwitch(renderScope, width - PADDING_RIGHT - Toggle.SWITCH_WIDTH, (height - Toggle.SWITCH_HEIGHT) / 2, on); } @Override public void click(int mouseX, int mouseY) { onToggle.run(); } }