Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

2.4 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;

/**
 * The small switch of a settings row: a 24 by 14 lozenge, grey with a dark dot
 * at the left when off, the control colour with a white dot at the right when on.
 */
public final class SmallSwitch extends JComponent {
    private boolean on;
    private Runnable onToggle;

    public SmallSwitch(boolean on) {
        this.on = on;
        // 24 by 14 at the fallback font size; 28 by 16 at the usual 13px, as measured.
        Dimension d = new Dimension(WIDTH, HEIGHT);
        setPreferredSize(d);
        setMinimumSize(d);
        setMaximumSize(d);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        setFocusable(true);
        addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(MouseEvent e) { if (isEnabled()) flip(); }
        });
        getInputMap().put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE, 0), "flip");
        getActionMap().put("flip", new AbstractAction() {
            @Override public void actionPerformed(java.awt.event.ActionEvent e) { flip(); }
        });
    }

    private void flip() {
        on = !on;
        repaint();
        if (onToggle != null) onToggle.run();
    }

    public static final int WIDTH = 24 + 2 * Ui.fontGrowth(), HEIGHT = 14 + Ui.fontGrowth();

    public boolean isOn() { return on; }
    public void setOn(boolean v) { if (on != v) { on = v; repaint(); } }
    public void setOnToggle(Runnable r) { onToggle = r; }

    @Override protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth(), h = getHeight();
        g2.setColor(on ? Theme.CONTROL : (Theme.dark ? Theme.TOGGLE_OFF : new Color(0xB0, 0xAF, 0xAF)));
        g2.fillRoundRect(0, 0, w, h, h, h);
        g2.setColor(on ? Color.WHITE : (Theme.dark ? Color.WHITE : Color.BLACK));
        // At the larger sizes the knob grows with the switch, and more so when on.
        int grow = Ui.fontGrowth();
        double r = 2.6 + (on ? 1.5 : 0.45) * grow, cx = on ? w - 6.5 - 0.5 * grow : 6.5 + 0.25 * grow, cy = h / 2.0;
        g2.fill(new Ellipse2D.Double(cx - r, cy - r, 2 * r, 2 * r));
        g2.dispose();
    }
}