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.

64.4 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.image.BufferedImage;

/** Shared look-and-feel constants and small widget factories. */
public final class Ui {
    private Ui() {}

    // Base sizes; actual fonts derive from these through UiScale so the whole
    // interface scales from one factor.
    public static final Font PLAIN   = new Font("Dialog", Font.PLAIN, Theme.FONT_SIZE);
    public static final Font BOLD    = new Font("Dialog", Font.BOLD, Theme.FONT_SIZE);
    public static final Font MONO    = new Font(Font.MONOSPACED, Font.PLAIN, Theme.FONT_SIZE);
    public static final Font HEADING = new Font("Dialog", Font.BOLD, Theme.FONT_SIZE + 2);

    public static final Color ACCENT      = Theme.ACCENT;
    public static final Color PANEL_BG    = Theme.SURFACE;
    public static final Color GRID        = Theme.BORDER;
    /** Red for a warning in text: a lighter one on the dark theme, where the usual red cannot be read. */
    public static final Color ERROR_RED   = Theme.dark ? new Color(0xFF, 0x6B, 0x68) : new Color(0xCC, 0x00, 0x00);
    public static final Color ZEBRA       = Theme.ACCENT_FAINT;
    public static final Color SELECTION   = Theme.ACCENT_LIGHT;

    // Severity palette, shared by the dashboard badges and the issue tree so a
    // finding's colour means the same thing everywhere.
    public static final Color SEV_HIGH   = new Color(0xD5, 0x1F, 0x3D);
    public static final Color SEV_MEDIUM = new Color(0xFF, 0x66, 0x33);
    public static final Color SEV_LOW    = new Color(0x26, 0x64, 0x9D);
    public static final Color SEV_INFO   = new Color(0xB0, 0xAF, 0xAF);

    public static Color severityColor(opensuite.core.Issue.Severity s) {
        if (s == null) return SEV_INFO;
        return switch (s) {
            case HIGH -> SEV_HIGH;
            case MEDIUM -> SEV_MEDIUM;
            case LOW -> SEV_LOW;
            default -> SEV_INFO;
        };
    }

    /** Colour the given table column by its severity label (High/Medium/Low/Information). */
    /**
     * The severity cell reads as ordinary text. The reference carries severity
     * on the coloured dot in the issue-type column, not by tinting the word, so
     * colouring it here as well said the same thing twice and made the column
     * shout.
     */
    public static void severityColumn(JTable table, int col) {
        javax.swing.table.DefaultTableCellRenderer r = new javax.swing.table.DefaultTableCellRenderer() {
            @Override public Component getTableCellRendererComponent(JTable t, Object v,
                    boolean sel, boolean focus, int row, int column) {
                super.getTableCellRendererComponent(t, v, sel, focus, row, column);
                setHorizontalAlignment(SwingConstants.LEADING);
                setFont(PLAIN);
                setForeground(sel ? t.getSelectionForeground() : Theme.TEXT);
                return this;
            }
        };
        table.getColumnModel().getColumn(col).setCellRenderer(r);
    }

    /**
     * The issue badge: a filled disc coloured by severity carrying a white
     * glyph, "?" for a tentative finding, "i" for an informational one and "!"
     * otherwise. Every issue list uses this, so a finding looks the same
     * wherever it is listed.
     */
    /**
     * The character a badge carries: "?" for a finding that is only suspected,
     * "i" for one that is informational, "!" for the rest.
     */
    public static String issueGlyph(opensuite.core.Issue.Severity sev, opensuite.core.Issue.Confidence conf) {
        if (conf == opensuite.core.Issue.Confidence.TENTATIVE) return "?";
        return sev == opensuite.core.Issue.Severity.INFORMATION ? "i" : "!";
    }

    public static Icon issueBadge(opensuite.core.Issue.Severity sev, opensuite.core.Issue.Confidence conf) {
        final Color col = severityColor(sev);
        final String glyph = issueGlyph(sev, conf);
        return new Icon() {
            @Override public int getIconWidth()  { return 15; }
            @Override public int getIconHeight() { return 15; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(col);
                g2.fillOval(x + 1, y + 1, 13, 13);
                g2.setColor(Color.WHITE);
                g2.setFont(new Font("Dialog", Font.BOLD, 11));
                FontMetrics fm = g2.getFontMetrics();
                g2.drawString(glyph, x + 1 + (13 - fm.stringWidth(glyph)) / 2f,
                        y + 1 + (13 + fm.getAscent() - fm.getDescent()) / 2f);
                g2.dispose();
            }
        };
    }

    /** The badge from the words a table model holds, rather than the enums. */
    public static Icon issueBadge(String severity, String confidence) {
        opensuite.core.Issue.Severity sev = switch (severity == null ? "" : severity) {
            case "High" -> opensuite.core.Issue.Severity.HIGH;
            case "Medium" -> opensuite.core.Issue.Severity.MEDIUM;
            case "Low" -> opensuite.core.Issue.Severity.LOW;
            default -> opensuite.core.Issue.Severity.INFORMATION;
        };
        return issueBadge(sev, "Tentative".equalsIgnoreCase(confidence)
                ? opensuite.core.Issue.Confidence.TENTATIVE : opensuite.core.Issue.Confidence.CERTAIN);
    }

    /** A small filled circle coloured by severity, for the issue-type column. */
    public static javax.swing.Icon severityDot(String severity) {
        Color c = switch (severity == null ? "" : severity) {
            case "High" -> SEV_HIGH;
            case "Medium" -> SEV_MEDIUM;
            case "Low" -> SEV_LOW;
            default -> SEV_INFO;
        };
        int d = 10;
        java.awt.image.BufferedImage img =
                new java.awt.image.BufferedImage(d + 2, d + 2, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(c);
        g.fillOval(1, 1, d, d);
        g.dispose();
        return new javax.swing.ImageIcon(img);
    }

    /**
     * Show a small severity dot in front of the text of {@code textCol}, coloured
     * by the value in {@code sevCol} on the same row (reads via the model so it
     * survives sorting).
     */
    public static void severityIconColumn(JTable table, int textCol, int sevCol) {
        severityIconColumn(table, textCol, sevCol, -1);
    }

    /**
     * As above, also reading the confidence from {@code confCol} so a tentative
     * finding gets the "?" badge. Pass -1 when the model has no confidence.
     */
    public static void severityIconColumn(JTable table, int textCol, int sevCol, int confCol) {
        table.getColumnModel().getColumn(textCol).setCellRenderer(
            new javax.swing.table.DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable t, Object v,
                        boolean sel, boolean focus, int row, int column) {
                    super.getTableCellRendererComponent(t, v, sel, focus, row, column);
                    int mr = t.convertRowIndexToModel(row);
                    Object sev = t.getModel().getValueAt(mr, sevCol);
                    Object conf = confCol >= 0 ? t.getModel().getValueAt(mr, confCol) : null;
                    setIcon(issueBadge(String.valueOf(sev), conf == null ? null : String.valueOf(conf)));
                    setIconTextGap(7);
                    return this;
                }
            });
    }

    /** A small filled dot in a severity's colour, for the issue tree. */
    public static Icon severityDot(opensuite.core.Issue.Severity s) {
        final Color c = severityColor(s);
        return new Icon() {
            @Override public int getIconWidth()  { return 12; }
            @Override public int getIconHeight() { return 12; }
            @Override public void paintIcon(Component comp, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(c);
                g2.fillOval(x + 1, y + 1, 9, 9);
                g2.setColor(c.darker());
                g2.drawOval(x + 1, y + 1, 9, 9);
                g2.dispose();
            }
        };
    }

    /**
     * User-facing text starts with a capital, as in the reference, so a label
     * written in lower case in code still reads as a proper heading or button.
     * Leading spaces and symbols are kept; only the first letter is raised.
     */
    public static String sentence(String text) {
        if (text == null || text.isEmpty()) return text;
        int i = 0;
        while (i < text.length() && !Character.isLetter(text.charAt(i))) i++;
        if (i >= text.length() || Character.isUpperCase(text.charAt(i))) return text;
        // A letter that follows a digit belongs to a figure ("2xx", "3rd") and is left as written.
        if (i > 0 && Character.isDigit(text.charAt(i - 1))) return text;
        return text.substring(0, i) + Character.toUpperCase(text.charAt(i)) + text.substring(i + 1);
    }

    /**
     * A tooltip as it is shown: starting with a capital, like every other
     * piece of text. One written as HTML is left as it is.
     */
    public static String tip(String text) {
        return text == null || text.startsWith("<") ? text : sentence(text);
    }

    public static JLabel heading(String text) {
        JLabel l = new JLabel(sentence(text));
        l.setFont(HEADING);
        l.setForeground(Theme.TAB_TEXT_ON);   // headings are full black, a step stronger than body text
        return l;
    }

    public static JLabel label(String text) {
        JLabel l = new JLabel(sentence(text));
        l.setFont(PLAIN);
        return l;
    }

    public static JLabel bold(String text) {
        JLabel l = new JLabel(sentence(text));
        l.setFont(BOLD);
        // Headings are white on the dark theme, a step brighter than the text under them.
        if (Theme.dark) l.setForeground(Theme.TAB_TEXT_ON);
        return l;
    }

    public static JCheckBox check(String text, boolean selected) {
        JCheckBox c = new JCheckBox(sentence(text), selected);
        c.setFont(PLAIN);
        c.setFocusable(false);
        c.setOpaque(false);
        return c;
    }

    /**
     * A tick box drawn as a sliding switch, which is how the reference shows an
     * on/off state that takes effect at once (Filter on, Capturing).
     */
    public static JCheckBox switchBox(String text, boolean selected) {
        JCheckBox c = check(text, selected);
        Icon icon = new Icon() {
            // 28 by 16 at the usual 13px, as measured: switched on, a white knob of
            // 10px on the accent; switched off, a dark knob of 8px on grey.
            private final boolean big = fontGrowth() > 0;
            private final int w = big ? 28 : 24, h = big ? 16 : 13;
            @Override public int getIconWidth() { return w; }
            @Override public int getIconHeight() { return h; }
            @Override public void paintIcon(Component comp, Graphics g, int x, int y) {
                boolean on = ((AbstractButton) comp).isSelected();
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(on ? Theme.CONTROL : big && !Theme.dark ? new Color(0xB0, 0xAF, 0xAF) : Theme.TOGGLE_OFF);
                g2.fillRoundRect(x, y, w, h, h, h);
                if (!big) {
                    g2.setColor(Color.WHITE);
                    g2.fillOval(on ? x + 14 : x + 3, y + 3, 7, 7);
                } else if (on) {
                    g2.setColor(Color.WHITE);
                    g2.fillOval(x + 15, y + 3, 10, 10);
                } else {
                    g2.setColor(Theme.dark ? Color.WHITE : Color.BLACK);
                    g2.fillOval(x + 3, y + 4, 8, 8);
                }
                g2.dispose();
            }
        };
        c.setIcon(icon);
        c.setSelectedIcon(icon);
        c.setIconTextGap(10);
        return c;
    }

    public static JRadioButton radio(String text, boolean selected) {
        JRadioButton r = new JRadioButton(sentence(text), selected);
        r.setFont(PLAIN);
        r.setFocusable(false);
        r.setOpaque(false);
        return r;
    }

    public static JButton button(String text) {
        JButton b = new JButton(sentence(text));
        b.setFont(BOLD);   // the reference sets every button label in bold
        return b;
    }

    /** Give a row of buttons one size, the largest of theirs and no narrower than a short word needs. */
    public static void sameSize(JButton... buttons) {
        int w = em(84), h = 0;
        for (JButton b : buttons) { Dimension d = b.getPreferredSize(); w = Math.max(w, d.width); h = Math.max(h, d.height); }
        for (JButton b : buttons) { Dimension d = new Dimension(w, h); b.setPreferredSize(d); b.setMinimumSize(d); }
    }

    public static JButton button(String text, String tooltip) {
        JButton b = button(text);
        b.setToolTipText(tip(tooltip));
        return b;
    }

    /** The one button on a panel that starts its main action, filled with the accent. */
    public static JButton primaryButton(String text, String tooltip) {
        JButton b = button(text, tooltip);
        return Theme.primary(b);
    }

    /**
     * The width a text input takes when nothing stretches it. Inside a form a
     * field fills the row instead, so this only decides how wide one looks on
     * a loose row.
     */
    public static final int FIELD_COLUMNS = 24;

    /** The width of an input that holds a number: a port, a count, a timeout. */
    public static final int SHORT_COLUMNS = 6;

    /**
     * A text input of the standard width. In a form it stretches to the row,
     * so every field in that form starts and ends at the same place.
     *
     * <p>The application used to pick a column count per call site, twenty
     * different ones across a hundred-odd fields, which is why no two forms
     * lined up. Prefer this and {@link #shortField}; reach for the explicit
     * width only when a field genuinely has to be a particular size.
     */
    public static JTextField field(String text) { return field(text, FIELD_COLUMNS); }

    /**
     * A narrow input for a number. Marked so a form leaves it at its own
     * width rather than stretching it across the row.
     */
    public static JTextField shortField(String text) {
        JTextField f = natural(field(text, SHORT_COLUMNS));
        // 64px by 22, the reference's width for a count, a port or a timeout.
        f.setColumns(0);
        Ui.sized(f, 64);
        return f;
    }

    public static JTextField field(String text, int columns) {
        JTextField f = new PlaceholderField(text, columns);
        f.setFont(PLAIN);
        return f;
    }

    /** A password input of the standard width, matching {@link #field}. */
    public static JPasswordField passwordField(String text) {
        JPasswordField f = new JPasswordField(text == null ? "" : text, FIELD_COLUMNS);
        f.setFont(PLAIN);
        return f;
    }

    /** A section's fold mark: the broad one at the larger font sizes, the small chevron at the fallback size. */
    private static Icon foldMark(boolean open) {
        return fontGrowth() > 0 ? Glyphs.fold(Theme.TEXT, open) : Glyphs.chevron(16, Theme.TEXT, open ? 2 : 1, 1.5f);
    }

    /** Client property: Boolean.TRUE sets a field's placeholder in italics, as the reference does for "Enter a new item". */
    public static final String ITALIC_PLACEHOLDER = "opensuite.placeholder.italic";

    /**
     * A text field that paints the "JTextField.placeholderText" client property
     * in muted text while it is empty, as every search box in the suite does.
     */
    public static class PlaceholderField extends JTextField {
        public PlaceholderField(String text, int columns) { super(text, columns); }
        @Override protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Object ph = getClientProperty("JTextField.placeholderText");
            if (ph == null || !getText().isEmpty()) return;
            Graphics2D g2 = (Graphics2D) g.create();
            opensuite.ui.Theme.textSmoothing(g2);
            g2.setColor(Theme.MUTED);
            g2.setFont(Boolean.TRUE.equals(getClientProperty(ITALIC_PLACEHOLDER)) ? getFont().deriveFont(Font.ITALIC) : getFont());
            Insets in = getInsets();
            FontMetrics fm = g2.getFontMetrics();
            g2.drawString(String.valueOf(ph), in.left, (getHeight() - fm.getHeight()) / 2 + fm.getAscent());
            g2.dispose();
        }
    }

    /** A search box: placeholder "Search" and a magnifier at its right edge. */
    public static JTextField searchField(int columns) {
        JTextField f = new PlaceholderField("", columns) {
            @Override protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // At the usual 13px the glass is larger and as dark as the text.
                boolean big = fontGrowth() > 0;
                Icon ic = big ? Glyphs.search(16, Theme.TAB_TEXT_ON) : Glyphs.search(14, Theme.MUTED);
                ic.paintIcon(this, g, getWidth() - ic.getIconWidth() - (big ? 7 : 8), (getHeight() - ic.getIconHeight()) / 2);
            }
        };
        f.setFont(PLAIN);
        f.putClientProperty("JTextField.placeholderText", "Search");
        f.setBorder(BorderFactory.createCompoundBorder(f.getBorder(),
                BorderFactory.createEmptyBorder(0, fontGrowth() > 0 ? 2 : 0, 0, 18)));
        return f;
    }

    public static <T> JComboBox<T> combo(T[] items) {
        JComboBox<T> c = new JComboBox<>(items);
        c.setFont(PLAIN);
        c.setMaximumRowCount(14);
        // Items read as labels, with a leading capital, without touching the
        // values themselves: the model still holds whatever was handed in, so
        // code that compares against an item string keeps working.
        c.setRenderer(new DefaultListCellRenderer() {
            @Override public Component getListCellRendererComponent(JList<?> l, Object v, int i,
                    boolean sel, boolean focus) {
                super.getListCellRendererComponent(l, v, i, sel, focus);
                setText(v == null ? "" : sentence(String.valueOf(v)));
                setFont(PLAIN);
                return this;
            }
        });
        return c;
    }

    /**
     * A wrapping, read-only paragraph. A plain wrapping text area has no idea
     * how wide it will be laid out, so it reports a one-line (or a one-column)
     * preferred size and gets squashed or clipped. This one reports an honest
     * size for its text: up to {@link #NOTE_COLUMNS} wide and as many rows as
     * that needs. Laid out wider it just uses fewer lines.
     */
    public static JTextArea note(String text) {
        JTextArea a = new JTextArea() {
            @Override public Dimension getPreferredSize() {
                Insets in = getInsets();
                int w = getColumns() * getColumnWidth() + in.left + in.right;
                int h = getRows() * getRowHeight() + in.top + in.bottom;
                return new Dimension(w, h);
            }
            @Override public void setText(String t) {
                super.setText(t);
                sizeNote(this);
            }
        };
        a.setFont(PLAIN);
        a.setEditable(false);
        a.setOpaque(false);
        a.setLineWrap(true);
        a.setWrapStyleWord(true);
        a.setBorder(null);
        a.setFocusable(false);
        a.setText(text);
        return a;
    }

    /** The widest a note lays itself out before wrapping, in characters. */
    public static final int NOTE_COLUMNS = 90;

    /**
     * Size a note to exactly the height its text needs at {@code width}, so a
     * page that knows how wide its notes will be gets no estimate at all.
     */
    public static void sizeNote(JTextArea a, int width) {
        a.setSize(width, Short.MAX_VALUE);
        int real = a.getUI().getPreferredSize(a).height;   // the true wrapped height
        FontMetrics fm = a.getFontMetrics(a.getFont());     // the same units JTextArea sizes columns and rows in
        a.setColumns(Math.max(1, width / Math.max(1, fm.charWidth('m'))));
        a.setRows(Math.max(1, (int) Math.ceil(real / (double) Math.max(1, fm.getHeight()))));
        a.setMaximumSize(new Dimension(width, a.getPreferredSize().height));
    }

    /** Size a note's rows and columns to its text, and stop layouts stretching it. */
    public static void sizeNote(JTextArea a) {
        String t = a.getText();
        int len = t == null ? 0 : t.length();
        int cols = Math.max(24, Math.min(NOTE_COLUMNS, len));
        a.setColumns(cols);
        // Word wrap lands a little short of the column count, so allow for it.
        a.setRows(Math.max(1, (int) Math.ceil(len / (cols * 0.9))));
        a.setMaximumSize(new Dimension(Integer.MAX_VALUE, a.getPreferredSize().height));
    }

    public static Border pad(int t, int l, int b, int r) {
        return BorderFactory.createEmptyBorder(t, l, b, r);
    }

    /**
     * A field with something on its right, as a "File: [___] [Select file ...]"
     * row needs. The field stretches and the trailing component keeps its own
     * width, so the row still ends where every other row in the form ends.
     */
    public static JPanel fieldWith(JComponent field, JComponent trailing) {
        JPanel p = new JPanel(new BorderLayout(6, 0));
        p.setOpaque(false);
        p.add(field, BorderLayout.CENTER);
        p.add(trailing, BorderLayout.EAST);
        return p;
    }

    public static JPanel row(Component... parts) {
        // 5px between parts and none around them: a row starts exactly where
        // it is placed, so it shares a left edge with whatever is above it.
        JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        p.setOpaque(false);
        p.setBorder(BorderFactory.createEmptyBorder(0, -5, 0, -5));
        for (Component c : parts) p.add(c);
        return p;
    }

    public static JPanel vbox(Component... parts) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.setOpaque(false);
        for (Component c : parts) {
            if (c instanceof JComponent jc) jc.setAlignmentX(Component.LEFT_ALIGNMENT);
            p.add(c);
        }
        return p;
    }

    /**
     * A neat column of equal-width, equal-height buttons, hugging
     * the top. Use this for any vertical group of buttons so they line up instead
     * of each being sized to its own text.
     */
    public static JPanel buttonColumn(AbstractButton... buttons) {
        JPanel grid = new JPanel(new GridLayout(buttons.length, 1, 0, 5));
        grid.setOpaque(false);
        for (AbstractButton b : buttons) grid.add(b);
        JPanel wrap = new JPanel(new BorderLayout());
        wrap.setOpaque(false);
        wrap.add(grid, BorderLayout.NORTH); // keep buttons their natural height, aligned to the top
        return wrap;
    }

    /** A neat row of equal-width buttons. */
    public static JPanel buttonRow(AbstractButton... buttons) {
        JPanel grid = new JPanel(new GridLayout(1, buttons.length, 5, 0));
        grid.setOpaque(false);
        for (AbstractButton b : buttons) grid.add(b);
        JPanel wrap = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        wrap.setOpaque(false);
        wrap.add(grid);
        return wrap;
    }

    /**
     * A vertical scroller for a column of sections: the content keeps its
     * natural height and scrolls when the pane is shorter, and always takes the
     * pane's width so nothing scrolls sideways. Without this a tall column
     * squeezed into a short pane collapses its lower sections to nothing.
     */
    public static JScrollPane scrollColumn(JComponent content) {
        JPanel holder = new ColumnHolder();
        holder.add(content, BorderLayout.NORTH);
        JScrollPane sp = new JScrollPane(holder,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        sp.setBorder(BorderFactory.createEmptyBorder());
        sp.setOpaque(false);
        sp.getViewport().setOpaque(false);
        sp.getVerticalScrollBar().setUnitIncrement(16);
        // One notch of the wheel moves a page of settings 25px at the usual 13px, as measured.
        sp.setWheelScrollingEnabled(false);
        sp.addMouseWheelListener(e -> {
            JScrollBar bar = sp.getVerticalScrollBar();
            if (!bar.isVisible()) return;
            bar.setValue(bar.getValue() + (int) Math.round(e.getPreciseWheelRotation() * 25 * Theme.FONT_SIZE / 13.0));
        });
        // A column opens at its top: text set inside it while it was hidden must not leave it part way down.
        sp.addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0 && sp.isShowing())
                SwingUtilities.invokeLater(() -> sp.getViewport().setViewPosition(new Point(0, 0)));
        });
        return sp;
    }

    private static final class ColumnHolder extends JPanel implements Scrollable {
        ColumnHolder() { super(new BorderLayout()); setOpaque(false); }
        @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); }
        @Override public int getScrollableUnitIncrement(Rectangle r, int o, int d) { return 16; }
        @Override public int getScrollableBlockIncrement(Rectangle r, int o, int d) { return Math.max(16, r.height - 32); }
        @Override public boolean getScrollableTracksViewportWidth() {
            return !(getParent() instanceof JViewport v) || v.getWidth() >= least();
        }
        @Override public boolean getScrollableTracksViewportHeight() { return false; }
        int minWidth;
        /** When set, the column is never narrower than its widest fixed-width row (a table and its buttons). */
        boolean fitFixedRows;
        private int fixedWidth;
        private int least() { return Math.max(minWidth, fitFixedRows ? fixedWidth : 0); }
        @Override public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            return least() > 0 ? new Dimension(least(), d.height) : d;
        }
        @Override public void doLayout() {
            super.doLayout();
            if (!fitFixedRows) return;
            // The rows take their places during this pass; measure them once it is over.
            SwingUtilities.invokeLater(() -> {
                int w = widest(this);
                if (w != fixedWidth) { fixedWidth = w; revalidate(); }
            });
        }
        private int widest(Container c) {
            int w = 0;
            for (Component k : c.getComponents()) {
                if (!k.isVisible()) continue;
                if (k instanceof JComponent j && Boolean.TRUE.equals(j.getClientProperty(FIXED_ROW))) {
                    Point at = SwingUtilities.convertPoint(j.getParent(), j.getX(), 0, this);
                    w = Math.max(w, at.x + j.getPreferredSize().width + 15);
                } else if (k instanceof Container inner) {
                    w = Math.max(w, widest(inner));
                }
            }
            return w;
        }
    }

    /** Marks a row of fixed width (a table with its side arrow) for {@link #columnFitsFixedRows}. */
    public static final String FIXED_ROW = "opensuite.fixedRow";

    /**
     * Let a pane made by {@link #scrollColumn} scroll sideways rather than
     * squeeze a fixed-width table: the reference's settings pages do this when
     * the window is narrower than their widest table.
     */
    public static void columnFitsFixedRows(JScrollPane sp) {
        if (!(sp.getViewport().getView() instanceof ColumnHolder h)) return;
        h.fitFixedRows = true;
        sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    }

    /**
     * Give a pane made by {@link #scrollColumn} a least width: narrower than
     * that, the column stops shrinking and scrolls sideways instead.
     */
    public static void columnMinWidth(JScrollPane sp, int width) {
        if (!(sp.getViewport().getView() instanceof ColumnHolder h)) return;
        h.minWidth = width;
        sp.setHorizontalScrollBarPolicy(width > 0 ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        h.revalidate();
    }

    /** A table heading row of the reference's fixed height at the larger font sizes. */
    private static final class FixedHeader extends javax.swing.table.JTableHeader {
        FixedHeader(javax.swing.table.TableColumnModel m) { super(m); }
        @Override public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            if (fontGrowth() > 0) d.height = 26;   // 25 and its rule, as measured at 13px
            return d;
        }
    }

    /** Configure a table with the conventions used throughout the suite. */
    public static void styleTable(JTable t) {
        t.setFont(PLAIN);
        t.setRowHeight(Theme.FONT_SIZE + 7);   // 18px rows at the default size, as the reference
        // The heading row is 25px at every font size (a sort arrow must not make it taller).
        if (!(t.getTableHeader() instanceof FixedHeader) && t.getTableHeader() != null
                && t.getTableHeader().getClass() == javax.swing.table.JTableHeader.class
                && t.getTableHeader().getMouseListeners().length <= new javax.swing.table.JTableHeader().getMouseListeners().length) {
            t.setTableHeader(new FixedHeader(t.getColumnModel()));
        }
        t.getTableHeader().setFont(PLAIN);
        t.setDefaultRenderer(Boolean.class, new TickRenderer());
        // Column titles read with a leading capital, as in the reference.
        for (int i = 0; i < t.getColumnModel().getColumnCount(); i++) {
            javax.swing.table.TableColumn c = t.getColumnModel().getColumn(i);
            Object v = c.getHeaderValue();
            if (v instanceof String s) c.setHeaderValue(sentence(s));
        }
        t.getTableHeader().setReorderingAllowed(false);
        t.getTableHeader().setToolTipText("Click a column to sort ascending (Shift-click for descending)");
        t.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        t.setGridColor(GRID);
        t.setShowVerticalLines(false);
        t.setShowHorizontalLines(false);   // rows are told apart by striping, not rules
        t.setIntercellSpacing(new Dimension(0, 0));
        t.setSelectionBackground(SELECTION);
        t.setSelectionForeground(Theme.TEXT);
        leftAlign(t);
    }

    /**
     * Left-align the header labels and every cell, the convention used by other
     * proxy-first suites. The Metal look and feel centres headers and
     * right-aligns numbers by default, which looks untidy, so override both.
     */
    public static void leftAlign(JTable t) {
        // Text sits 4px inside its column, and 8px inside the table's first one,
        // as the reference spaces both its header and its rows.
        javax.swing.table.DefaultTableCellRenderer left = new javax.swing.table.DefaultTableCellRenderer() {
            @Override public Component getTableCellRendererComponent(JTable tb, Object v, boolean sel, boolean focus, int row, int column) {
                super.getTableCellRendererComponent(tb, v, sel, focus, row, column);
                if (column == 0) setBorder(FIRST_CELL);
                else if (fontGrowth() > 0) {
                    // At the usual 13px a cell's text stands 1px nearer its column's edge than the title does.
                    Insets in = getInsets();
                    setBorder(BorderFactory.createEmptyBorder(in.top, Math.max(0, in.left - 1), in.bottom, in.right));
                }
                return this;
            }
        };
        left.setHorizontalAlignment(SwingConstants.LEADING);
        final javax.swing.table.TableCellRenderer stock = t.getTableHeader().getDefaultRenderer();
        if (!(stock instanceof FirstColumnHeader)) t.getTableHeader().setDefaultRenderer(new FirstColumnHeader(stock));
        t.setDefaultRenderer(Object.class, left);
        t.setDefaultRenderer(Number.class, left);
        t.setDefaultRenderer(Integer.class, left);
        t.setDefaultRenderer(Long.class, left);
        t.setDefaultRenderer(String.class, left);
        if (stock instanceof javax.swing.table.DefaultTableCellRenderer h) {
            h.setHorizontalAlignment(SwingConstants.LEADING);
            h.setHorizontalTextPosition(SwingConstants.LEADING);
        }
    }

    private static final javax.swing.border.Border FIRST_CELL = BorderFactory.createEmptyBorder(1, 8, 1, 4);

    /** The stock header renderer, with the first column's title set 8px in and the sort mark beside the title. */
    private static final class FirstColumnHeader implements javax.swing.table.TableCellRenderer {
        private final javax.swing.table.TableCellRenderer inner;
        FirstColumnHeader(javax.swing.table.TableCellRenderer inner) { this.inner = inner; }
        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean focus, int row, int column) {
            Component c = inner.getTableCellRendererComponent(t, v, sel, focus, row, column);
            if (c instanceof JLabel l) {
                l.setHorizontalAlignment(SwingConstants.LEADING);
                l.setHorizontalTextPosition(SwingConstants.LEADING);
                l.setIconTextGap(1);
                if (column == 0) l.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createMatteBorder(0, 0, 1, 1, Theme.BORDER),
                        fontGrowth() > 0 ? BorderFactory.createEmptyBorder(5, 8, 3, 0) : BorderFactory.createEmptyBorder(4, 8, 4, 0)));
            }
            return c;
        }
    }

    /** Center the text in every non-boolean cell of a table, for a tidy grid. */
    /**
     * Size columns proportionally to the given weights and let them fill the
     * viewport width, adapting to the window. Long columns (host, URL) get more
     * space; a horizontal scrollbar appears only when the window is too narrow
     * for the minimum widths. Call after the model is set.
     */
    /** As {@link #distributeWidths}, but a title may truncate: the widths are kept in exactly these proportions. */
    public static void exactWidths(JTable t, int... weights) {
        distributeWidths(t, weights);
        for (int i = 0; i < weights.length && i < t.getColumnModel().getColumnCount(); i++) {
            javax.swing.table.TableColumn c = t.getColumnModel().getColumn(i);
            c.setMinWidth(24);
            c.setPreferredWidth(wide(weights[i]));   // column widths grow as the tables themselves do
        }
    }

    /**
     * Columns that keep these proportions at any table width. Swing shares
     * spare width equally but takes a shortfall in proportion, so the
     * preferred widths are set far too large and the table shrinks them.
     */
    public static void proportionalWidths(JTable t, int... weights) {
        distributeWidths(t, weights);
        for (int i = 0; i < weights.length && i < t.getColumnModel().getColumnCount(); i++) {
            javax.swing.table.TableColumn c = t.getColumnModel().getColumn(i);
            c.setMinWidth(0);
            c.setPreferredWidth(weights[i] * 100);
        }
    }

    public static void distributeWidths(JTable t, int... weights) {
        t.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        t.getTableHeader().setResizingAllowed(true);
        t.getTableHeader().setReorderingAllowed(false);
        // Never let a column squeeze narrower than its own header text, so the
        // header labels never truncate to "met...", "st...", "MIM..." etc.
        java.awt.FontMetrics fm = t.getTableHeader().getFontMetrics(t.getTableHeader().getFont());
        int cols = t.getColumnModel().getColumnCount();
        for (int i = 0; i < weights.length && i < cols; i++) {
            javax.swing.table.TableColumn c = t.getColumnModel().getColumn(i);
            String name = String.valueOf(c.getHeaderValue());
            int headerMin = fm.stringWidth(name) + 10;
            c.setPreferredWidth(Math.max(weights[i], headerMin));
            c.setMinWidth(Math.max(Math.max(24, weights[i] / 3), headerMin));
        }
    }

    /** Retained for call sites; tables are left-aligned throughout now. */
    /**
     * Sort a history table newest first by its number column, so the latest
     * entry is always at the top as more arrive. A sorter is created when the
     * table has none; an existing one keeps its filter. The user can still
     * click a header to sort another way.
     */
    public static void newestFirst(JTable t, int numberColumn) {
        javax.swing.RowSorter<? extends javax.swing.table.TableModel> rs = t.getRowSorter();
        if (rs == null) {
            rs = new opensuite.ui.NumberSorter<>(t.getModel());
            t.setRowSorter(rs);
        }
        rs.setSortKeys(java.util.List.of(
                new javax.swing.RowSorter.SortKey(numberColumn, javax.swing.SortOrder.DESCENDING)));
    }

    public static void centerCells(JTable t) {
        leftAlign(t);
    }

    /**
     * Make the whole of a card select its option, not only the small dot of
     * the radio button or check box inside it. The option is taken on the
     * press: a click is lost when the pointer moves at all between press and
     * release, which on a large card it usually does.
     */
    public static void wholeCardSelects(JComponent card, AbstractButton option) {
        card.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        java.awt.event.MouseAdapter pick = new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) {
                if (!SwingUtilities.isLeftMouseButton(e) || !option.isEnabled()) return;
                option.requestFocusInWindow();
                // A radio button is chosen; a check box is switched. Both tell their listeners, as a press on the dot does.
                if (option instanceof JRadioButton) { if (!option.isSelected()) option.doClick(0); }
                else option.doClick(0);
            }
        };
        listenAcross(card, option, pick);
    }

    private static void listenAcross(Component c, AbstractButton option, java.awt.event.MouseListener l) {
        if (c == option) return;   // the button answers for itself
        c.addMouseListener(l);
        if (c instanceof Container cont) for (Component child : cont.getComponents()) listenAcross(child, option, l);
    }

    /**
     * Set initial column widths and let the columns stretch in proportion to
     * fill the table's pane, so no table sits in a strip of empty space. A
     * table that needs a different mode sets it after calling this.
     */
    public static void setWidths(JTable t, int... widths) {
        t.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        java.awt.FontMetrics fm = t.getTableHeader().getFontMetrics(t.getTableHeader().getFont());
        for (int i = 0; i < widths.length && i < t.getColumnCount(); i++) {
            javax.swing.table.TableColumn c = t.getColumnModel().getColumn(i);
            int headerMin = fm.stringWidth(String.valueOf(c.getHeaderValue())) + 18;
            c.setPreferredWidth(Math.max(widths[i], headerMin));
            c.setMinWidth(Math.max(Math.max(24, widths[i] / 3), headerMin));
        }
    }

    /**
     * Give a split pane a sensible initial division and keep it proportional as
     * the window resizes, instead of a fixed divider that leaves one pane tiny.
     * weight is the fraction given to the first (top/left) component.
     */
    public static void balance(javax.swing.JSplitPane sp, double weight) {
        sp.setResizeWeight(weight);
        sp.setContinuousLayout(true);
        // Hold the proportion through every resize until the user drags the
        // divider; from then on the split is theirs. Setting it only once went
        // wrong when the first layout pass ran at a size the window never kept.
        final boolean[] userMoved = {false};
        if (sp.getUI() instanceof javax.swing.plaf.basic.BasicSplitPaneUI ui && ui.getDivider() != null) {
            ui.getDivider().addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) { userMoved[0] = true; }
            });
        }
        sp.addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override public void componentResized(java.awt.event.ComponentEvent e) {
                int dim = sp.getOrientation() == javax.swing.JSplitPane.VERTICAL_SPLIT
                        ? sp.getHeight() : sp.getWidth();
                if (!userMoved[0] && dim > 0) sp.setDividerLocation(weight);
            }
        });
    }

    /**
     * Let a table fill the width it is given, and scroll only when it genuinely
     * cannot fit.
     *
     * <p>Every table was left on AUTO_RESIZE_OFF, which keeps columns at the
     * widths the calling code asked for and never uses the rest of the pane.
     * A narrow table therefore sat against a wide band of empty grey while its
     * own headers were clipped to "Open by ...". Tables that really are wider
     * than the pane still scroll, because stretching those would squash every
     * column instead.
     *
     * <p>The decision is made against the width the columns were asked for,
     * recorded once, rather than against their current width: comparing with
     * the live width would flip back and forth as each mode changed it.
     */
    /** Client property: the table keeps the column widths it was given and does not stretch them over the pane. */
    public static final String KEEP_WIDTHS = "opensuite.table.keepWidths";

    private static void fitColumnsToViewport(JTable t, JScrollPane s) {
        final String naturalKey = "opensuite.table.naturalWidth";
        Runnable fit = () -> {
            Integer natural = (Integer) t.getClientProperty(naturalKey);
            if (natural == null) {
                int sum = 0;
                for (int i = 0; i < t.getColumnModel().getColumnCount(); i++) {
                    sum += t.getColumnModel().getColumn(i).getPreferredWidth();
                }
                if (sum <= 0) return;
                natural = sum;
                t.putClientProperty(naturalKey, natural);
            }
            // A table that asked to keep its columns as set leaves the spare width empty.
            if (Boolean.TRUE.equals(t.getClientProperty(KEEP_WIDTHS))) {
                if (t.getAutoResizeMode() != JTable.AUTO_RESIZE_OFF) t.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                return;
            }
            int available = s.getViewport().getWidth();
            if (available <= 0) return;
            // Columns always share the pane's width, as the reference's do: a
            // table never scrolls sideways, however many columns it carries.
            int wanted = JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS;
            if (t.getAutoResizeMode() != wanted) t.setAutoResizeMode(wanted);
        };
        s.getViewport().addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override public void componentResized(java.awt.event.ComponentEvent e) { fit.run(); }
        });
        // A table whose columns arrive after it is wrapped still gets fitted.
        t.getColumnModel().addColumnModelListener(new javax.swing.event.TableColumnModelListener() {
            public void columnAdded(javax.swing.event.TableColumnModelEvent e) {
                t.putClientProperty(naturalKey, null);
                SwingUtilities.invokeLater(fit);
            }
            public void columnRemoved(javax.swing.event.TableColumnModelEvent e) {
                t.putClientProperty(naturalKey, null);
                SwingUtilities.invokeLater(fit);
            }
            public void columnMoved(javax.swing.event.TableColumnModelEvent e) {}
            public void columnMarginChanged(javax.swing.event.ChangeEvent e) {}
            public void columnSelectionChanged(javax.swing.event.ListSelectionEvent e) {}
        });
        SwingUtilities.invokeLater(fit);
    }

    /**
     * A scroll pane with no box around it, for a table or list that fills one
     * side of a split pane: the divider's hairline is its only edge.
     */
    public static JScrollPane scrollPlain(Component c) {
        JScrollPane s = scroll(c);
        s.setBorder(BorderFactory.createEmptyBorder());
        return s;
    }

    public static JScrollPane scroll(Component c) {
        JScrollPane s = new JScrollPane(c);
        s.getVerticalScrollBar().setUnitIncrement(16);
        s.setBorder(BorderFactory.createLineBorder(GRID));
        if (c instanceof JTable t) {
            s.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            // The space under the last row reads as part of the table, not a
            // grey hole: same background, and the table paints to the bottom.
            t.setFillsViewportHeight(true);
            s.getViewport().setBackground(t.getBackground());
            fitColumnsToViewport(t, s);
        }
        return s;
    }

    /** Truncate long labels the way the original context menus did. */
    /**
     * A clickable filter bar, styled so it is obviously pressable: a funnel
     * icon, a button border and a trailing hint. Used by the proxy history and
     * the site map so the filter popup is clearly a click away. Set the text and
     * action on the returned button.
     */
    public static JButton filterButton() {
        JButton b = new JButton();
        b.setFont(PLAIN);
        b.setHorizontalAlignment(SwingConstants.LEFT);
        b.setFocusable(false);
        b.setIcon(funnelIcon());
        b.setIconTextGap(fontGrowth() > 0 ? 6 : 4);
        b.setBackground(Theme.SURFACE);
        b.setOpaque(true);
        b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        b.setBorder(new opensuite.ui.theme.RoundedBorder(GRID, null, Theme.RADIUS, new Insets(5, 9, 5, 8)));
        b.setToolTipText("click to open the filter and full-text search");
        return b;
    }

    /**
     * A tidy label-and-field form. Labels are right-aligned in a fixed first
     * column and fields share a left edge in the second, so every field lines up
     * no matter how long its label is.
     *
     * <p>Use this wherever a panel has more than one labelled input, so the whole
     * app stays aligned rather than each label pushing its field to a different
     * place. Pass label, component, label, component, ...
     */
    /**
     * A label-and-field form laid out as the reference draws its side panels:
     * labels left-aligned in a shared first column and fields stretched across
     * the rest of the width, rather than right-aligned labels beside fields at
     * their natural size.
     *
     * <p>Pass a field wrapped in {@link #natural} to keep it at its own width
     * on a row that would otherwise stretch it.
     */

    private static final String NATURAL_WIDTH = "opensuite.naturalWidth";

    /** Marks a field so {@link #leftForm} leaves it at its own width. */
    public static <T extends JComponent> T natural(T field) {
        field.putClientProperty(NATURAL_WIDTH, Boolean.TRUE);
        return field;
    }

    /**
     * A collapsible block as the reference's side panels are built: a title row
     * with a chevron that folds the body away, a hairline above it, and an
     * explanatory paragraph before the controls.
     */
    public static JPanel section(String title, String description, JComponent body) {
        // Measured from the reference's side panels: a rule across the whole
        // panel, the title's centre 20px under it, the paragraph 12px under
        // the title row, the controls 14px under that, and 10px beneath.
        JPanel p = new JPanel(new BorderLayout());
        p.setOpaque(false);
        p.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, GRID), pad(7, 10, 10, 10)));

        java.util.List<Component> parts = new java.util.ArrayList<>();
        parts.add(Sections.gap(18));
        if (description != null && !description.isBlank()) {
            JTextArea d = Sections.text(description);
            d.setBorder(pad(0, 0, 0, 14));
            parts.add(d);
            parts.add(Sections.gap(15));
        }
        parts.add(Sections.fill(body));
        JPanel inner = Sections.column(0, parts.toArray(new Component[0]));

        JLabel heading = new JLabel(title);
        heading.setFont(PLAIN);
        heading.setForeground(Theme.TEXT);
        JButton fold = Glyphs.button(foldMark(true), "Collapse this section", null);
        fold.setBorder(pad(0, 4, 0, 1));
        fold.addActionListener(e -> {
            boolean show = !inner.isVisible();
            inner.setVisible(show);
            fold.setIcon(foldMark(show));
            fold.setToolTipText(show ? "Collapse this section" : "Expand this section");
            p.revalidate();
        });
        JPanel head = new JPanel(new BorderLayout());
        head.setOpaque(false);
        Ui.sized(head, 10);
        head.add(heading, BorderLayout.WEST);
        head.add(fold, BorderLayout.EAST);

        p.add(head, BorderLayout.NORTH);
        p.add(inner, BorderLayout.CENTER);
        return p;
    }

    /**
     * One row of a side panel: a label in a fixed first column and a control
     * (or a plain value) filling the rest, {@code height} tall.
     */
    /**
     * A height measured at the reference's smallest font (11px), as it is at
     * the font in use. The reference keeps its padding and lets a row grow by
     * exactly what its text grows: a 22px field at 11px is 24px at 13px.
     */
    public static int tall(int at11) { return at11 + Theme.FONT_SIZE - Theme.DEFAULT_FONT_SIZE; }

    /**
     * Give a control the size it has at 11px, carried to the font in use: it is
     * taller by the font's growth; a button or label is wider by what its own
     * text has grown, a field in proportion, and a chooser keeps its width.
     */
    public static void sized(JComponent c, int widthAt11) {
        c.setPreferredSize(new Dimension(widthAt11 + widthGrowth(c, widthAt11), tall(22)));
    }

    /** The same for several buttons that share one width: all as wide as the one that grew most. */
    public static void sizedAlike(int widthAt11, JComponent... cs) {
        int grow = 0;
        for (JComponent c : cs) grow = Math.max(grow, widthGrowth(c, widthAt11));
        for (JComponent c : cs) c.setPreferredSize(new Dimension(widthAt11 + grow, tall(22)));
    }

    private static int widthGrowth(JComponent c, int widthAt11) {
        if (fontGrowth() == 0) return 0;
        String text = c instanceof AbstractButton b ? b.getText() : c instanceof JLabel l ? l.getText() : null;
        if (c instanceof AbstractButton || c instanceof JLabel) {
            return text == null || text.isEmpty() ? 0 : column(0, c.getFont(), text);
        }
        if (c instanceof JComboBox) return 0;   // a chooser keeps its width, as measured
        return Math.round((widthAt11 + 2) * Theme.FONT_SIZE / (float) Theme.DEFAULT_FONT_SIZE) - widthAt11;
    }

    /**
     * The size of a column of {@code n} standard buttons, 5px apart: 87 by 22
     * each at the smallest font, 95 by 24 at the usual 13px.
     */
    public static Dimension buttonBlock(int n) {
        return new Dimension(87 + 4 * fontGrowth(), n * tall(22) + (n - 1) * 5);
    }

    /** How many pixels larger the font is than the reference's smallest (11px). */
    public static int fontGrowth() { return Theme.FONT_SIZE - Theme.DEFAULT_FONT_SIZE; }

    /** A height or inset that grows half as fast again as the font: a 25px heading row is 28px at 13px. */
    public static int roomy(int at11) { return at11 + Math.round(fontGrowth() * 1.5f); }

    /** The width to ask for where {@link #wide} is applied but the reference keeps {@code px} at every font size. */
    public static int unwide(int px) { return Math.round(px * (float) px / wide(px)); }

    /**
     * A fixed width the reference sets in its own scaled units: a 420px table
     * at 11px is 560px at 13px (a third wider for those two pixels of font).
     */
    public static int wide(int at11) { return Math.round(at11 * (1 + fontGrowth() / 6f)); }

    /** A size in proportion to the font: a 314px field at 11px is 371px at 13px. */
    public static int em(int at11) { return Math.round(at11 * Theme.FONT_SIZE / (float) Theme.DEFAULT_FONT_SIZE); }

    /**
     * A column width measured at 11px for the given widest text, as it is at
     * the font in use: wider by exactly what that text has grown.
     */
    public static int column(int at11, Font font, String widest) {
        if (Theme.FONT_SIZE == Theme.DEFAULT_FONT_SIZE) return at11;
        java.awt.font.FontRenderContext frc = new java.awt.font.FontRenderContext(null, true, false);
        double small = font.deriveFont((float) Theme.DEFAULT_FONT_SIZE).getStringBounds(widest, frc).getWidth();
        double now = font.deriveFont((float) Theme.FONT_SIZE).getStringBounds(widest, frc).getWidth();
        return at11 + (int) Math.round(now - small);
    }

    public static JPanel labelled(String label, int labelWidth, JComponent control, int rowHeight) {
        int height = tall(rowHeight);
        JLabel l = label(label);
        l.setPreferredSize(new Dimension(labelWidth, height));
        JPanel row = new JPanel(new BorderLayout());
        row.setOpaque(false);
        row.add(l, BorderLayout.WEST);
        row.add(control, BorderLayout.CENTER);
        row.setPreferredSize(new Dimension(labelWidth + 40, height));
        return Sections.fill(row);
    }

    /**
     * The one label-and-field form in the suite: labels left-aligned in a
     * shared first column, fields stretched across the rest of the row. Every
     * field in a form therefore starts at the same place and ends at the same
     * place.
     *
     * <p>Wrap a field in {@link #natural} to keep it at its own width, which
     * is what a number input or a combo box usually wants. There used to be
     * two helpers here, one right-aligned and one left, and screens that mixed
     * them had fields starting at different places on the same page.
     */
    public static JPanel form(Object... labelThenComponent) {
        JPanel p = new JPanel(new GridBagLayout());
        p.setOpaque(false);
        GridBagConstraints c = new GridBagConstraints();
        for (int i = 0, row = 0; i + 1 < labelThenComponent.length; i += 2, row++) {
            c.gridy = row;
            c.gridx = 0; c.weightx = 0;
            c.anchor = GridBagConstraints.LINE_START;
            c.fill = GridBagConstraints.NONE;
            c.insets = new Insets(0, 0, 5, 5);
            Object l = labelThenComponent[i];
            Component labelComponent = l instanceof Component lc ? lc : label(String.valueOf(l));

            // A null value means the row owns the whole width: a radio button
            // or a check box that the rows beneath it belong to. Its fields
            // still share the one column, so nothing drifts out of line.
            if (labelThenComponent[i + 1] == null) {
                c.gridwidth = 2; c.weightx = 1;
                c.fill = GridBagConstraints.HORIZONTAL;
                p.add(labelComponent, c);
                c.gridwidth = 1;
                continue;
            }
            p.add(labelComponent, c);

            Component fieldComponent = (Component) labelThenComponent[i + 1];
            boolean stretch = !(fieldComponent instanceof JComponent jc
                    && Boolean.TRUE.equals(jc.getClientProperty(NATURAL_WIDTH)));
            c.gridx = 1; c.weightx = 1;
            c.fill = stretch ? GridBagConstraints.HORIZONTAL : GridBagConstraints.NONE;
            c.insets = new Insets(0, 0, 5, 0);
            p.add(fieldComponent, c);
        }
        return p;
    }

    /**
     * Assemble a filter bar: the clickable filter button stretched across, then
     * the quick-search label and field on the right, all at one uniform height.
     * Used by the proxy history and the site map so both bars look identical.
     */
    public static JPanel filterBar(JButton filterButton, JComponent... right) {
        JPanel bar = new JPanel(new GridBagLayout());
        bar.setOpaque(false);
        bar.setBorder(pad(5, 10, 5, 3));

        // The field's natural height is the common height; shrink the button to it
        // so the two are the same size rather than the button standing taller.
        int h = 0;
        for (JComponent p : right) h = Math.max(h, p.getPreferredSize().height);
        if (h > 0) {
            Dimension d = filterButton.getPreferredSize();
            filterButton.setPreferredSize(new Dimension(d.width, h));
        }

        GridBagConstraints c = new GridBagConstraints();
        c.gridy = 0;
        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 0; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL;
        bar.add(filterButton, c);

        c.weightx = 0; c.fill = GridBagConstraints.NONE;
        for (JComponent p : right) {
            c.gridx++;
            boolean field = p instanceof JTextField;
            if (p instanceof JTextField f) { f.setColumns(0); f.setPreferredSize(new Dimension(233 + 25 * fontGrowth(), f.getPreferredSize().height)); }
            boolean last = p == right[right.length - 1];
            c.insets = new Insets(0, field || p instanceof JCheckBox ? 10 : p instanceof JButton ? (last ? -1 : 5) : 8, 0, 2);
            bar.add(p, c);
        }
        return bar;
    }

    /**
     * A joined run of mutually exclusive views, as the site map's "URL view" /
     * "Crawl paths view" switch. The segments abut with square inner edges and
     * the outer corners rounded, the chosen one filled with the control colour
     * and the rest with the segment grey; {@code onChoose} is handed the chosen
     * index. Geometry and both fills are taken from the reference frames.
     */
    public static JPanel segmented(java.util.function.IntConsumer onChoose, String... labels) {
        JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        p.setOpaque(false);
        ButtonGroup g = new ButtonGroup();
        final java.util.List<JToggleButton> all = new java.util.ArrayList<>();
        for (int i = 0; i < labels.length; i++) {
            final int idx = i;
            final boolean first = i == 0, last = i == labels.length - 1;
            JToggleButton b = new JToggleButton(labels[i], i == 0) {
                @Override protected void paintComponent(Graphics gr) {
                    Graphics2D g2 = (Graphics2D) gr.create();
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    int w = getWidth(), h = getHeight(), arc = Theme.RADIUS;
                    g2.setColor(isSelected() ? Theme.CONTROL : Theme.SEGMENT_OFF);
                    // Round only the outer corners: fill the rounded shape, then
                    // square off whichever inner edge touches a neighbour.
                    g2.fillRoundRect(0, 0, w, h, arc, arc);
                    if (!first) g2.fillRect(0, 0, arc, h);
                    if (!last)  g2.fillRect(w - arc, 0, arc, h);
                    g2.setColor(isSelected() ? Color.WHITE : Theme.TEXT);
                    g2.setFont(getFont());
                    FontMetrics fm = g2.getFontMetrics();
                    g2.drawString(getText(), (w - fm.stringWidth(getText())) / 2f,
                            (h + fm.getAscent() - fm.getDescent()) / 2f);
                    g2.dispose();
                }
            };
            b.setFont(PLAIN);
            b.setFocusable(false);
            b.setContentAreaFilled(false);
            b.setBorder(BorderFactory.createEmptyBorder(5, 12, 5, 12));
            b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            all.add(b);
            g.add(b);
            p.add(b);
            b.addActionListener(e -> { for (JToggleButton t : all) t.repaint(); onChoose.accept(idx); });
        }
        return p;
    }

    /**
     * A filter chip: a fully rounded pill that toggles on and off, as the
     * Collaborator's HTTP / DNS / SMTP filters are drawn. Off it is the page
     * colour inside a grey outline with bold dark text, measured from the
     * reference frames; on it takes the control colour, like every other
     * switched-on control. The accent is not used here, because it belongs to
     * the one button that starts an action and this toolbar already has one.
     */
    public static JToggleButton chip(String text) {
        JToggleButton t = new JToggleButton(text, false) {
            @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(), arc = h;      // a full pill
                if (isSelected()) {
                    g2.setColor(Theme.CONTROL);
                    g2.fillRoundRect(0, 0, w - 1, h - 1, arc, arc);
                } else {
                    g2.setColor(Theme.BG);
                    g2.fillRoundRect(0, 0, w - 1, h - 1, arc, arc);
                    g2.setColor(Theme.BORDER);
                    g2.drawRoundRect(0, 0, w - 1, h - 1, arc, arc);
                }
                g2.setColor(isSelected() ? Color.WHITE : Theme.TAB_TEXT);
                g2.setFont(getFont());
                FontMetrics fm = g2.getFontMetrics();
                g2.drawString(getText(), (w - fm.stringWidth(getText())) / 2f,
                        (h + fm.getAscent() - fm.getDescent()) / 2f);
                g2.dispose();
            }
        };
        t.setFont(BOLD);
        t.setFocusable(false);
        t.setContentAreaFilled(false);
        t.setBorder(BorderFactory.createEmptyBorder(4, 14, 4, 14));
        t.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        return t;
    }

    /** A round "?" that explains the panel it sits on. */
    public static JButton helpButton(String title, String body) {
        JButton b = Glyphs.button(Glyphs.help(18, Theme.ICON), title, null);
        b.addActionListener(e -> JOptionPane.showMessageDialog(b, body, title, JOptionPane.INFORMATION_MESSAGE));
        return b;
    }

    /**
     * Boolean cells: a tick when true and nothing when false, as the reference
     * draws Params / Edited / TLS; an editable cell keeps its check box.
     */
    public static final class TickRenderer extends javax.swing.table.DefaultTableCellRenderer {
        private final javax.swing.table.TableCellRenderer box = new JTable().getDefaultRenderer(Boolean.class);
        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean f, int r, int c) {
            if (t.isCellEditable(r, c)) {
                Component cb = box.getTableCellRendererComponent(t, v, sel, f, r, c);
                if (cb instanceof JComponent jc) jc.setOpaque(true);
                return cb;
            }
            super.getTableCellRendererComponent(t, "", sel, f, r, c);
            setIcon(Boolean.TRUE.equals(v) ? Glyphs.tick(14 + fontGrowth(), Theme.TEXT) : null);
            setHorizontalAlignment(CENTER);
            return this;
        }
    }

    /** A small funnel glyph for the filter bar, drawn so it needs no resource. */
    private static Icon funnelIcon() {
        BufferedImage img = new BufferedImage(14, 14, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setColor(Theme.TEXT);
        boolean big = fontGrowth() > 0;   // it fills its 14px at the usual font size, and 11 by 10.5 at the fallback
        g.setStroke(new BasicStroke(big ? 1.4f : 1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        java.awt.geom.Path2D f = new java.awt.geom.Path2D.Double();
        f.moveTo(1.5, 2); f.lineTo(12.5, 2); f.lineTo(8.3, 7.2); f.lineTo(8.3, 12.5); f.lineTo(5.7, 11); f.lineTo(5.7, 7.2); f.closePath();
        if (big) {
            java.awt.geom.AffineTransform grow = new java.awt.geom.AffineTransform();
            grow.translate(0.8, 0.8);
            grow.scale(12.4 / 11, 12.4 / 10.5);
            grow.translate(-1.5, -2);
            f.transform(grow);
        }
        g.draw(f);
        g.dispose();
        return new ImageIcon(img);
    }

    public static String truncate(String s, int max) {
        if (s == null) return "";
        if (s.length() <= max) return s;
        return s.substring(0, 25) + "..." + s.substring(s.length() - 30);
    }
}