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.

44.5 KB
Raw Blame
package opensuite.ui;

import opensuite.ui.theme.*;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import java.awt.*;
import java.awt.event.InputEvent;

/**
 * The suite's visual theme: a flat interface, light or dark, with one orange accent.
 *
 * <p>Everything here is plain Swing. The cross-platform look and feel is the
 * base, so the interface is identical on every desktop, and the parts of it
 * that look dated (bevelled buttons, boxed tabs, chunky scrollbars) are
 * replaced with flat delegates from {@code opensuite.ui.theme}. Colours and
 * fonts live in this one class so the whole interface changes together.
 */
public final class Theme {
    private Theme() {}

    // ---- palette ----
    // Not final: the dark variant is chosen at install() time (before any UI is
    // built, so the Ui constants that copy these capture the right values). A
    // theme change relaunches the app, exactly as a scale change does.
    /** Page background: a shade off white, so tables, editors and fields stand out on it. */
    public static Color BG         = new Color(0xFB, 0xFB, 0xFB);
    /** Content surfaces that sit on the page: tables, trees, lists, editors, combo boxes. */
    public static Color CONTENT    = new Color(0xFF, 0xFF, 0xFF);
    /** Label and text colour of a disabled control: dimmed, but still easy to read. */
    public static Color DISABLED_TEXT = new Color(0x4B, 0x4B, 0x4B);
    /** Raised surfaces: toolbars, table headers, cards, the status bar. */
    public static Color SURFACE    = new Color(0xEE, 0xEE, 0xEE);
    /** Hover and pressed state of surfaces and secondary buttons. */
    public static Color SURFACE_2  = new Color(0xE4, 0xE4, 0xE4);
    public static Color SURFACE_3  = new Color(0xD8, 0xD8, 0xD8);
    /** Hairlines and outlines. */
    public static Color BORDER     = new Color(0xDF, 0xDF, 0xDF);
    public static Color TEXT       = new Color(0x2B, 0x2B, 0x2B);
    public static Color MUTED      = new Color(0x6B, 0x6B, 0x6B);
    /** The accent: orange, used on primary buttons and the active tab. */
    public static Color ACCENT       = new Color(0xDB, 0x61, 0x2F);
    public static Color ACCENT_DARK  = new Color(0xC0, 0x4E, 0x20);
    /** Row selection: a light blue selection that stays legible against the orange accent. */
    public static Color ACCENT_LIGHT = new Color(0xCA, 0xDA, 0xF0);
    /**
     * The colour of switched-on controls: check marks, radio dots, toggles,
     * filter chips, selection bars. Sampled from the reference frames, where it
     * is by far the most common saturated blue.
     */
    public static Color CONTROL      = new Color(0x26, 0x63, 0x9C);
    /** The tint behind a selected card or list row, sampled from the same frames. */
    public static Color CONTROL_TINT = new Color(0xEA, 0xEF, 0xF5);
    /** The fill of an unselected segment in a segmented control. */
    public static Color SEGMENT_OFF  = new Color(0xDF, 0xDF, 0xDF);
    /**
     * Tab titles. The reference keeps an unselected tab near-black rather than
     * greying it out: the selected tab is marked by its underline, not by the
     * others fading. Both values are sampled from the reference frames.
     */
    public static Color TAB_TEXT     = new Color(0x2B, 0x2B, 0x2B);
    public static Color TAB_TEXT_ON  = new Color(0x00, 0x00, 0x00);
    public static Color ACCENT_FAINT = new Color(0xFA, 0xFA, 0xFA);

    // ---- the rest of the palette: everything a tool used to hard-code ----
    /** Cards and other raised panels that sit on the page. */
    public static Color CARD        = new Color(0xFF, 0xFF, 0xFF);
    /** Table headers. */
    public static Color HEADER      = new Color(0xEE, 0xEE, 0xEE);
    /** Strokes of small drawn icons (play, pause, dots, section glyphs). */
    public static Color ICON        = new Color(0x55, 0x55, 0x55);
    /** The track of a switched-off toggle. */
    public static Color TOGGLE_OFF  = new Color(0xB8, 0xBC, 0xC2);
    public static Color SCROLL_THUMB       = new Color(0xDF, 0xDF, 0xDF);
    public static Color SCROLL_THUMB_HOVER = new Color(0xC9, 0xC9, 0xC9);
    /** Success: a finished task, a running service. */
    public static Color OK          = new Color(0x3A, 0x9A, 0x4B);
    /** The search-match highlight in message views. */
    public static Color HIGHLIGHT   = new Color(0xFF, 0xF1, 0x76);
    /** Message syntax colouring: header names and markup tags, the start line, JSON keys, strings, numbers. */
    public static Color CODE_NAME   = new Color(0x00, 0x00, 0x75);
    /** Message text that carries no syntax colour. */
    public static Color CODE_TEXT    = new Color(0x14, 0x14, 0x14);
    /** Parameter, cookie and attribute names. */
    public static Color CODE_PARAM   = new Color(0x00, 0x00, 0xC0);
    /** Parameter, cookie and attribute values. */
    public static Color CODE_VALUE   = new Color(0xA0, 0x10, 0x10);
    /** Markup tag names. */
    public static Color CODE_TAG     = new Color(0xB0, 0x00, 0xC0);
    /** Declarations and comments in markup. */
    public static Color CODE_COMMENT = new Color(0x00, 0x5A, 0x00);
    /** The band behind the line the caret is on. */
    public static Color CURRENT_LINE = new Color(0xF0, 0xF0, 0xF0);
    public static Color CODE_START  = new Color(0x8A, 0x1F, 0x1F);
    public static Color CODE_KEY    = new Color(0x9A, 0x4A, 0x0A);
    public static Color CODE_STRING = new Color(0x00, 0x5A, 0x00);
    public static Color CODE_NUMBER = new Color(0x0B, 0x72, 0x85);
    /** Hex view: the offset column and the text column. */
    public static Color HEX_OFFSET  = new Color(0x88, 0x88, 0x88);
    public static Color HEX_ASCII   = new Color(0x33, 0x55, 0x88);
    /** Comparer: backgrounds of deleted, added and modified runs. */
    public static Color DIFF_DELETED  = new Color(0xF7, 0xC9, 0xC9);
    public static Color DIFF_ADDED    = new Color(0xCB, 0xE8, 0xCB);
    public static Color DIFF_MODIFIED = new Color(0xC7, 0xDC, 0xF5);

    /** Fill of text inputs and combo boxes: a shade off the page, as in the reference. */
    public static Color FIELD        = new Color(0xFB, 0xFB, 0xFB);
    /** Outline of text inputs and combo boxes. */
    public static Color FIELD_BORDER = new Color(0xC9, 0xC9, 0xC9);
    /** The fill of an input that can be typed in or chosen from: a shade off the content white. */
    public static Color FIELD_BG = new Color(0xFB, 0xFB, 0xFB);
    /** Outline of an ordinary (grey) button. */
    public static Color BUTTON_BORDER = new Color(0xDF, 0xDF, 0xDF);
    /** Window chrome: the menu bar, the status bar and secondary panels. */
    public static Color CHROME       = new Color(0xFB, 0xFB, 0xFB);

    /** Whether the dark palette is active (set by {@link #configure}). */
    public static boolean dark = false;

    /** Read the saved theme preference (system property wins, then prefs). */
    public static boolean darkPreferred() {
        String flag = System.getProperty("opensuite.theme");
        if (flag != null) return flag.equalsIgnoreCase("dark");
        try { return "dark".equalsIgnoreCase(
                java.util.prefs.Preferences.userRoot().node("opensuite.v1").get("ui.theme", "light")); }
        catch (Exception e) { return false; }
    }

    /** Point the palette at the light or dark colours. Call before install(). */
    public static void configure(boolean darkMode) {
        dark = darkMode;
        if (darkMode) {
            // The reference's dark theme, each colour as measured from it: a
            // blue-grey page, darker tables and editors, lighter headers and
            // buttons, a steel-blue selection, and the same orange accent.
            BG                 = new Color(0x32, 0x33, 0x34);
            CONTENT            = new Color(0x2B, 0x2B, 0x2B);
            DISABLED_TEXT      = new Color(0x7D, 0x7F, 0x81);
            SURFACE            = new Color(0x42, 0x42, 0x44);
            SURFACE_2          = new Color(0x4A, 0x4A, 0x4D);
            SURFACE_3          = new Color(0x52, 0x52, 0x55);
            BORDER             = new Color(0x52, 0x52, 0x55);
            TEXT               = new Color(0xC5, 0xC7, 0xC8);
            MUTED              = new Color(0x9E, 0xA0, 0xA1);
            ACCENT             = new Color(0xDB, 0x61, 0x2F);
            ACCENT_DARK        = new Color(0xC0, 0x4E, 0x20);
            ACCENT_LIGHT       = new Color(0x2C, 0x51, 0x75);
            ACCENT_FAINT       = new Color(0x33, 0x33, 0x33);
            CARD               = new Color(0x32, 0x33, 0x34);
            HEADER             = new Color(0x42, 0x42, 0x44);
            ICON               = new Color(0xC5, 0xC7, 0xC8);
            TOGGLE_OFF         = new Color(0x52, 0x52, 0x55);
            SCROLL_THUMB       = new Color(0x52, 0x52, 0x55);
            SCROLL_THUMB_HOVER = new Color(0x6A, 0x6A, 0x6C);
            OK                 = new Color(0x5C, 0xC4, 0x6E);
            HIGHLIGHT          = new Color(0x7A, 0x60, 0x00);
            CODE_NAME          = new Color(0xD1, 0xE8, 0xF9);
            CODE_START         = new Color(0xD1, 0xE8, 0xF9);
            CODE_KEY           = new Color(0xBB, 0xCD, 0xFF);
            CODE_STRING        = new Color(0xE9, 0xC0, 0x63);
            CODE_NUMBER        = new Color(0xA5, 0xC3, 0x5B);
            HEX_OFFSET         = new Color(0xA0, 0xA0, 0xA0);
            HEX_ASCII          = new Color(0xBB, 0xCD, 0xFF);
            DIFF_DELETED       = new Color(0x6B, 0x2B, 0x2B);
            DIFF_ADDED         = new Color(0x2B, 0x5B, 0x2B);
            DIFF_MODIFIED      = new Color(0x2B, 0x45, 0x66);
            CONTROL            = new Color(0x26, 0x64, 0x9D);
            CONTROL_TINT       = new Color(0x32, 0x39, 0x45);
            SEGMENT_OFF        = new Color(0x52, 0x52, 0x55);
            TAB_TEXT           = new Color(0xC5, 0xC7, 0xC8);
            TAB_TEXT_ON        = new Color(0xFF, 0xFF, 0xFF);
        } else {
            BG           = new Color(0xFB, 0xFB, 0xFB);
            CONTENT      = new Color(0xFF, 0xFF, 0xFF);
            DISABLED_TEXT = new Color(0x4B, 0x4B, 0x4B);
            SURFACE      = new Color(0xEE, 0xEE, 0xEE);
            SURFACE_2    = new Color(0xE4, 0xE4, 0xE4);
            SURFACE_3    = new Color(0xD8, 0xD8, 0xD8);
            BORDER       = new Color(0xDF, 0xDF, 0xDF);
            TEXT         = new Color(0x2B, 0x2B, 0x2B);
            MUTED        = new Color(0x6B, 0x6B, 0x6B);
            ACCENT       = new Color(0xDB, 0x61, 0x2F);
            ACCENT_DARK  = new Color(0xC0, 0x4E, 0x20);
            ACCENT_LIGHT = new Color(0xCA, 0xDA, 0xF0);
            ACCENT_FAINT = new Color(0xFA, 0xFA, 0xFA);
            CARD         = new Color(0xFF, 0xFF, 0xFF);
            HEADER       = new Color(0xEE, 0xEE, 0xEE);
            ICON         = new Color(0x55, 0x55, 0x55);
            TOGGLE_OFF   = new Color(0xB8, 0xBC, 0xC2);
            SCROLL_THUMB       = new Color(0xDF, 0xDF, 0xDF);
            SCROLL_THUMB_HOVER = new Color(0xC9, 0xC9, 0xC9);
            OK           = new Color(0x3A, 0x9A, 0x4B);
            HIGHLIGHT    = new Color(0xFF, 0xF1, 0x76);
            CODE_NAME    = new Color(0x00, 0x00, 0x75);
            CODE_START   = new Color(0x8A, 0x1F, 0x1F);
            CODE_KEY     = new Color(0x9A, 0x4A, 0x0A);
            CODE_STRING  = new Color(0x00, 0x5A, 0x00);
            CODE_NUMBER  = new Color(0x0B, 0x72, 0x85);
            HEX_OFFSET   = new Color(0x88, 0x88, 0x88);
            HEX_ASCII    = new Color(0x33, 0x55, 0x88);
            DIFF_DELETED  = new Color(0xF7, 0xC9, 0xC9);
            DIFF_ADDED    = new Color(0xCB, 0xE8, 0xCB);
            DIFF_MODIFIED = new Color(0xC7, 0xDC, 0xF5);
            CONTROL       = new Color(0x26, 0x63, 0x9C);
            CONTROL_TINT  = new Color(0xEA, 0xEF, 0xF5);
            SEGMENT_OFF   = new Color(0xDF, 0xDF, 0xDF);
            TAB_TEXT      = new Color(0x2B, 0x2B, 0x2B);
            TAB_TEXT_ON   = new Color(0x00, 0x00, 0x00);
        }
        CODE_TEXT     = darkMode ? new Color(0xBA, 0xBA, 0xBA) : new Color(0x14, 0x14, 0x14);
        CODE_PARAM    = darkMode ? new Color(0xBB, 0xCD, 0xFF) : new Color(0x00, 0x00, 0xC0);
        CODE_VALUE    = darkMode ? new Color(0xA5, 0xC3, 0x5B) : new Color(0xA0, 0x10, 0x10);
        CODE_TAG      = darkMode ? new Color(0xBB, 0xCD, 0xFF) : new Color(0xB0, 0x00, 0xC0);
        CODE_COMMENT  = darkMode ? new Color(0x9E, 0xA0, 0xA1) : new Color(0x00, 0x5A, 0x00);
        CURRENT_LINE  = darkMode ? new Color(0x35, 0x38, 0x3A) : new Color(0xF0, 0xF0, 0xF0);
        FIELD         = darkMode ? new Color(0x32, 0x33, 0x34) : new Color(0xFB, 0xFB, 0xFB);
        FIELD_BORDER  = darkMode ? new Color(0x6A, 0x6A, 0x6C) : new Color(0xC9, 0xC9, 0xC9);
        FIELD_BG      = darkMode ? new Color(0x32, 0x33, 0x34) : new Color(0xFB, 0xFB, 0xFB);
        BUTTON_BORDER = darkMode ? new Color(0x42, 0x42, 0x44) : new Color(0xDF, 0xDF, 0xDF);
        CHROME        = darkMode ? new Color(0x32, 0x33, 0x34) : new Color(0xFB, 0xFB, 0xFB);
    }

    /** The reference's default interface font size. */
    public static final int DEFAULT_FONT_SIZE = 11;

    /**
     * The interface font size: Settings > User interface > Display > Font size,
     * read once at startup (a change takes effect on the next launch, as a
     * scale or theme change does).
     */
    public static int baseFontSize() {
        int size = chosenFontSize();
        // macOS takes no fractional interface scale from Java, so there the scale enlarges the text.
        return opensuite.core.Os.MAC ? Math.max(9, Math.min(32, (int) Math.round(size * UiScale.desired()))) : size;
    }

    private static int chosenFontSize() {
        String flag = System.getProperty("opensuite.fontSize");
        try {
            String v = flag != null ? flag
                    : java.util.prefs.Preferences.userRoot().node("opensuite.v1").get("ui.fontSize", null);
            if (v != null) return Math.max(9, Math.min(24, Integer.parseInt(v.trim())));
        } catch (Exception ignored) {}
        int desktop = desktopFontSize();
        return desktop > 0 ? desktop : DEFAULT_FONT_SIZE;
    }

    /**
     * The desktop's own interface font size in pixels, or 0 when the desktop
     * does not say. The reference follows it (a 10 point font at 96 dpi is 13
     * pixels), so on a real desktop both draw at the same size; only a bare
     * display with no desktop settings falls back to the smaller default.
     */
    static int desktopFontSize() {
        try {
            Toolkit tk = Toolkit.getDefaultToolkit();
            Object dpiValue = tk.getDesktopProperty("gnome.Xft/DPI");
            double dpi = dpiValue instanceof Integer i && i > 0 ? i / 1024.0 : 96.0;
            return pixelSize(String.valueOf(tk.getDesktopProperty("gnome.Gtk/FontName")), dpi);
        } catch (RuntimeException | Error e) {
            return 0;
        }
    }

    /** "Noto Sans 10" at 96 dpi is 13 pixels; 0 when the name carries no size. */
    static int pixelSize(String fontName, double dpi) {
        if (fontName == null) return 0;
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*$").matcher(fontName.trim());
        if (!m.find()) return 0;
        double px = Double.parseDouble(m.group(1)) * dpi / 72.0;
        return px < 9 || px > 24 ? 0 : (int) Math.floor(px + 0.4);
    }

    public static final int FONT_SIZE = baseFontSize();
    public static final Font FONT      = new Font("Dialog", Font.PLAIN, FONT_SIZE);
    public static final Font FONT_BOLD = new Font("Dialog", Font.BOLD, FONT_SIZE);

    /** Corner radius shared by buttons, fields and cards. */
    public static final int RADIUS = 4;

    /** Client property that marks a button as the primary action of its panel. */
    public static final String PRIMARY = "opensuite.primary";

    /** Install the theme. Call once, before any component is created. */
    /** How text is smoothed: what the desktop asks for (subpixel on an LCD), or plain smoothing when it does not say. */
    private static Object textAa = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
    private static Object lcdContrast;

    /**
     * Read the desktop's text smoothing, as the reference does. Forcing plain
     * greyscale instead made every label look lighter and thinner than the
     * reference on a desktop that uses subpixel rendering.
     * {@code -Dopensuite.textSmoothing=grey|lcd} overrides it.
     */
    static void readTextSmoothing() {
        Object aa = null;
        String flag = System.getProperty("opensuite.textSmoothing", "");
        if (flag.equalsIgnoreCase("lcd")) aa = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
        else if (flag.equalsIgnoreCase("grey") || flag.equalsIgnoreCase("gray")) aa = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
        else {
            try {
                if (Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints") instanceof java.util.Map<?, ?> hints) {
                    aa = hints.get(RenderingHints.KEY_TEXT_ANTIALIASING);
                    lcdContrast = hints.get(RenderingHints.KEY_TEXT_LCD_CONTRAST);
                }
            } catch (RuntimeException ignored) {}
        }
        if (aa == null || aa == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF || aa == RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT)
            aa = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
        textAa = aa;
    }

    /** Smooth text drawn by hand the way every label and field is smoothed. */
    public static void textSmoothing(Graphics g) {
        if (!(g instanceof Graphics2D g2)) return;
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAa);
        if (lcdContrast != null) g2.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, lcdContrast);
    }

    /**
     * On a Mac, Command does whatever Control does in every field, list, table
     * and tree: the look and feel binds copy, paste, select all and the rest to
     * Control only. Control keeps its bindings.
     */
    static void commandKeys(UIDefaults d) {
        for (Object k : new java.util.ArrayList<>(d.keySet())) {
            if (!(k instanceof String key) || !key.endsWith("InputMap") || !(d.get(key) instanceof InputMap m) || m.keys() == null) continue;
            for (KeyStroke ks : m.keys()) {
                int mod = ks.getModifiers();
                if (ks.getKeyCode() == java.awt.event.KeyEvent.VK_UNDEFINED || (mod & InputEvent.CTRL_DOWN_MASK) == 0
                        || (mod & InputEvent.META_DOWN_MASK) != 0) continue;
                // 0x2 is the old-style Control bit, which a keystroke reports alongside the new one.
                KeyStroke cmd = KeyStroke.getKeyStroke(ks.getKeyCode(), (mod & ~(InputEvent.CTRL_DOWN_MASK | 0x2)) | InputEvent.META_DOWN_MASK, ks.isOnKeyRelease());
                if (m.get(cmd) == null) m.put(cmd, m.get(ks));
            }
        }
    }

    public static void install() {
        configure(darkPreferred());
        MetalLookAndFeel.setCurrentTheme(new Palette());
        try { UIManager.setLookAndFeel(new MetalLookAndFeel()); } catch (Exception ignored) {}
        if (opensuite.core.Os.MAC) commandKeys(UIManager.getLookAndFeelDefaults());
        readTextSmoothing();
        UIManager.put(RenderingHints.KEY_TEXT_ANTIALIASING, textAa);
        if (lcdContrast != null) UIManager.put(RenderingHints.KEY_TEXT_LCD_CONTRAST, lcdContrast);

        UIDefaults d = UIManager.getDefaults();
        ColorUIResource bg = new ColorUIResource(BG), surface = new ColorUIResource(SURFACE),
                border = new ColorUIResource(BORDER), text = new ColorUIResource(TEXT),
                muted = new ColorUIResource(MUTED), sel = new ColorUIResource(ACCENT_LIGHT),
                content = new ColorUIResource(CONTENT), disabledText = new ColorUIResource(DISABLED_TEXT);
        FontUIResource font = new FontUIResource(FONT);

        for (String k : new String[]{"Button.font", "ToggleButton.font", "Label.font", "CheckBox.font",
                "RadioButton.font", "ComboBox.font", "TextField.font", "TextArea.font", "TabbedPane.font",
                "Table.font", "TableHeader.font", "Tree.font", "List.font", "Menu.font", "MenuItem.font",
                "MenuBar.font", "ToolTip.font", "ProgressBar.font", "TitledBorder.font", "OptionPane.font",
                "CheckBoxMenuItem.font", "RadioButtonMenuItem.font", "PopupMenu.font", "Spinner.font",
                "PasswordField.font", "EditorPane.font", "TextPane.font", "FormattedTextField.font"}) {
            d.put(k, font);
        }

        // Surfaces
        d.put("Panel.background", bg);
        d.put("Viewport.background", content);
        d.put("ScrollPane.background", bg);
        d.put("SplitPane.background", bg);
        d.put("TabbedPane.background", bg);
        d.put("TabbedPane.contentAreaColor", bg);
        d.put("OptionPane.background", bg);
        d.put("Label.foreground", text);
        d.put("control", bg);

        // Tabs: text with an accent underline, no boxes.
        d.put("TabbedPaneUI", FlatTabbedPaneUI.class.getName());
        d.put("TabbedPane.foreground", muted);
        d.put("TabbedPane.selectedForeground", text);
        d.put("TabbedPane.tabInsets", new Insets(8, 15, 7, 15));
        d.put("TabbedPane.tabAreaInsets", new Insets(0, 0, 0, 0));
        d.put("TabbedPane.contentBorderInsets", new Insets(1, 0, 0, 0));
        d.put("TabbedPane.selectedTabPadInsets", new Insets(0, 0, 0, 0));
        d.put("TabbedPane.tabRunOverlay", 0);

        // Buttons: flat, rounded, with a filled accent variant.
        d.put("ButtonUI", FlatButtonUI.class.getName());
        d.put("ToggleButtonUI", FlatButtonUI.class.getName());
        d.put("Button.foreground", text);
        d.put("ToggleButton.foreground", text);
        d.put("Button.disabledText", disabledText);
        d.put("ToggleButton.disabledText", disabledText);
        // The padding lives in the border so the flat shape keeps its size.
        d.put("Button.border", new javax.swing.plaf.BorderUIResource.EmptyBorderUIResource(3, 21, 3, 21));
        d.put("ToggleButton.border", new javax.swing.plaf.BorderUIResource.EmptyBorderUIResource(3, 21, 3, 21));
        d.put("Button.font", new FontUIResource(FONT_BOLD));
        d.put("ToggleButton.font", new FontUIResource(FONT_BOLD));
        d.put("Button.margin", new Insets(0, 0, 0, 0));
        d.put("ToggleButton.margin", new Insets(0, 0, 0, 0));

        // Inputs
        Border fieldBorder = new RoundedBorder(FIELD_BORDER, CONTROL, RADIUS * 2, new Insets(3, 6, 3, 6));
        d.put("TextField.border", fieldBorder);
        d.put("PasswordField.border", fieldBorder);
        d.put("FormattedTextField.border", fieldBorder);
        // An input you can use is a shade off white with a firm outline; one
        // you cannot is white with the page's hairline.
        d.put("TextArea.background", content);
        d.put("TextField.selectionBackground", sel);
        d.put("TextArea.selectionBackground", sel);
        d.put("TextField.selectionForeground", text);
        d.put("TextArea.selectionForeground", text);
        d.put("TextField.caretForeground", text);
        // Every text component, including the styled panes the message views
        // and advisories use, takes the page colours; otherwise they keep the
        // look and feel's white, which the dark theme cannot carry.
        for (String k : new String[]{"TextPane", "EditorPane", "TextArea", "TextField",
                "PasswordField", "FormattedTextField"}) {
            d.put(k + ".background", content);
            d.put(k + ".foreground", text);
            d.put(k + ".caretForeground", text);
            d.put(k + ".selectionBackground", sel);
            d.put(k + ".selectionForeground", text);
            // A read-only viewer keeps the page colour: the request and
            // response editors are not editable, and the reference draws them
            // on white like any other page. Only a genuinely disabled field is
            // greyed, which is what disabledBackground covers.
            d.put(k + ".inactiveBackground", content);
            d.put(k + ".inactiveForeground", text);
            d.put(k + ".disabledBackground", surface);
        }
        for (String k : new String[]{"TextField", "PasswordField", "FormattedTextField"}) {
            d.put(k + ".background", new ColorUIResource(FIELD_BG));
            d.put(k + ".inactiveBackground", new ColorUIResource(FIELD));
            d.put(k + ".disabledBackground", content);
        }
        d.put("List.background", content);
        d.put("List.foreground", text);
        d.put("Tree.foreground", text);
        d.put("Tree.textForeground", text);
        d.put("Tree.textBackground", content);
        d.put("Table.focusCellForeground", text);
        d.put("Spinner.background", content);
        d.put("Spinner.foreground", text);
        // A menu item that cannot be chosen is a mid grey that still reads (78, 80, 83 as measured), not washed out.
        ColorUIResource menuOff = dark ? disabledText : new ColorUIResource(new Color(0x4E, 0x50, 0x53));
        for (String k : new String[]{ "MenuItem", "Menu", "CheckBoxMenuItem", "RadioButtonMenuItem" }) d.put(k + ".disabledForeground", menuOff);
        d.put("Label.disabledForeground", disabledText);
        d.put("ComboBox.disabledForeground", disabledText);
        d.put("CheckBox.disabledText", disabledText);
        d.put("RadioButton.disabledText", disabledText);
        d.put("ComboBoxUI", FlatComboBoxUI.class.getName());
        d.put("ComboBox.background", new ColorUIResource(FIELD_BG));
        d.put("ComboBox.disabledBackground", content);
        d.put("ComboBox.foreground", text);
        d.put("ComboBox.selectionBackground", sel);
        d.put("ComboBox.selectionForeground", text);
        d.put("ComboBox.border", new RoundedBorder(FIELD_BORDER, CONTROL, RADIUS * 2, new Insets(2, 6, 2, 2)));
        d.put("ComboBox.squareButton", Boolean.FALSE);
        d.put("ComboBox.padding", new Insets(0, 0, 0, 0));
        d.put("CheckBox.icon", new CheckIcon(false));
        d.put("RadioButton.icon", new CheckIcon(true));
        // A radio or tick box starts at its own left edge and is 22px tall, the
        // height of a field, so a row of either lines up with the controls beside it.
        d.put("RadioButton.margin", new javax.swing.plaf.InsetsUIResource(0, 0, 0, 0));
        d.put("CheckBox.margin", new javax.swing.plaf.InsetsUIResource(0, 0, 0, 0));
        d.put("RadioButton.border", new javax.swing.plaf.BorderUIResource.EmptyBorderUIResource(3, 0, 3, 0));
        d.put("CheckBox.border", new javax.swing.plaf.BorderUIResource.EmptyBorderUIResource(3, 0, 3, 0));
        d.put("CheckBox.foreground", text);
        d.put("RadioButton.foreground", text);

        // Scrollbars: thin, no arrow buttons.
        d.put("ScrollBarUI", FlatScrollBarUI.class.getName());
        d.put("ScrollBar.width", 10);
        d.put("ScrollBar.background", bg);
        d.put("ScrollBar.track", bg);

        // Tables and trees
        d.put("TableUI", opensuite.ui.theme.FlatTableUI.class.getName());
        d.put("Table.background", content);
        d.put("Table.foreground", text);
        d.put("Table.gridColor", border);
        d.put("Table.selectionBackground", sel);
        d.put("Table.selectionForeground", text);
        // Zebra striping (Settings > Display > Table appearance), on by default as
        // in the reference: every standard cell renderer honours this colour.
        boolean zebra = true;
        try { zebra = !"off".equals(java.util.prefs.Preferences.userRoot().node("opensuite.v1").get("ui.zebra", "on")); }
        catch (Exception ignored) {}
        if (zebra) d.put("Table.alternateRowColor", new ColorUIResource(ACCENT_FAINT));
        // Cells share the header's left padding, so a column's title and values line up.
        d.put("Table.focusCellHighlightBorder", BorderFactory.createEmptyBorder(1, 4, 1, 4));
        d.put("Table.cellNoFocusBorder", BorderFactory.createEmptyBorder(1, 4, 1, 4));
        d.put("Table.focusSelectedCellHighlightBorder", BorderFactory.createEmptyBorder(1, 4, 1, 4));
        // The sort mark is a thin chevron beside the title, not a filled triangle.
        boolean usual = FONT_SIZE > DEFAULT_FONT_SIZE;
        d.put("Table.ascendingSortIcon", usual ? Glyphs.sortMark(TEXT, true) : Glyphs.chevron(12, TEXT, 2, 1.2f));
        d.put("Table.descendingSortIcon", usual ? Glyphs.sortMark(TEXT, false) : Glyphs.chevron(12, TEXT, 1, 1.2f));
        d.put("TableHeader.background", new ColorUIResource(HEADER));
        d.put("TableHeader.foreground", text);
        d.put("TableHeader.cellBorder", BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 1, BORDER),
                // At the usual 13px a title stands 1px lower in its 25px than at the fallback size.
                FONT_SIZE > DEFAULT_FONT_SIZE ? BorderFactory.createEmptyBorder(5, 3, 3, 2) : BorderFactory.createEmptyBorder(4, 3, 4, 2)));
        d.put("TableHeader.font", font);
        d.put("Tree.background", content);
        d.put("Tree.selectionBackground", sel);
        d.put("Tree.selectionForeground", text);
        d.put("Tree.selectionBorderColor", sel);
        d.put("Tree.rowHeight", 20);
        d.put("Tree.expandedIcon", Glyphs.chevron(12, MUTED, 1));
        d.put("Tree.collapsedIcon", Glyphs.chevron(12, MUTED, 0));
        d.put("Tree.leftChildIndent", 10);
        d.put("Tree.rightChildIndent", 12);
        d.put("Tree.paintLines", Boolean.FALSE);
        d.put("Tree.lineTypeDashed", Boolean.FALSE);
        d.put("List.selectionBackground", sel);
        d.put("List.selectionForeground", text);

        // Split panes: a plain hairline divider.
        d.put("SplitPaneUI", FlatSplitPaneUI.class.getName());
        d.put("SplitPane.dividerSize", 1);
        d.put("SplitPaneDivider.border", BorderFactory.createEmptyBorder());
        d.put("SplitPane.border", BorderFactory.createEmptyBorder());
        d.put("SplitPane.background", bg);

        // Menus
        d.put("MenuBar.gradient", null);
        d.put("MenuBar.background", new ColorUIResource(CHROME));
        d.put("MenuBar.border", BorderFactory.createMatteBorder(0, 0, 1, 0, BORDER));
        d.put("Menu.background", new ColorUIResource(CHROME));
        d.put("Menu.foreground", text);
        d.put("Menu.selectionBackground", sel);
        d.put("Menu.selectionForeground", text);
        d.put("Menu.border", new MenuBorder());
        // Menu rows: 22px tall with a 28px gutter, shortcuts in the text colour
        // joined by a plus, and a thin chevron on rows that open a submenu.
        for (String k : new String[]{"MenuItem", "CheckBoxMenuItem", "RadioButtonMenuItem", "Menu"}) {
            d.put(k + ".acceleratorForeground", text);
            d.put(k + ".acceleratorSelectionForeground", text);
            d.put(k + ".acceleratorDelimiter", "+");
            d.put(k + ".acceleratorFont", font);
            // Swing rounds a row's height up to an odd number unless told not to; the reference's rows are 22px.
            d.put(k + ".evenHeight", Boolean.TRUE);
        }
        d.put("Menu.arrowIcon", new MenuChevron());
        d.put("MenuItem.background", bg);
        d.put("MenuItem.selectionBackground", sel);
        d.put("MenuItem.selectionForeground", text);
        d.put("MenuItem.border", BorderFactory.createEmptyBorder(3, 24, 3, 0));
        // A ticked row shows a bare tick in the gutter and its text on the same edge as every other row.
        d.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(3, 24, 3, 0));
        d.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(3, 24, 3, 0));
        d.put("PopupMenuSeparatorUI", MenuRule.class.getName());
        d.put("CheckBoxMenuItem.checkIcon", new MenuTick());
        d.put("RadioButtonMenuItem.checkIcon", new MenuTick());
        d.put("CheckBoxMenuItem.background", bg);
        d.put("RadioButtonMenuItem.background", bg);
        d.put("CheckBoxMenuItem.selectionBackground", sel);
        d.put("RadioButtonMenuItem.selectionBackground", sel);
        d.put("CheckBoxMenuItem.selectionForeground", text);
        d.put("RadioButtonMenuItem.selectionForeground", text);
        d.put("PopupMenu.background", bg);
        d.put("PopupMenu.border", BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(BORDER), BorderFactory.createEmptyBorder(3, 0, 3, 0)));
        d.put("Separator.foreground", border);
        d.put("Separator.background", bg);

        // Progress, tooltips, dialogs
        d.put("ProgressBarUI", "javax.swing.plaf.basic.BasicProgressBarUI");
        d.put("ProgressBar.foreground", new ColorUIResource(ACCENT));
        d.put("ProgressBar.background", new ColorUIResource(SURFACE_2));
        d.put("ProgressBar.selectionForeground", bg);
        d.put("ProgressBar.selectionBackground", text);
        d.put("ProgressBar.border", BorderFactory.createEmptyBorder());
        d.put("ToolTip.background", new ColorUIResource(TEXT));
        d.put("ToolTip.foreground", bg);
        d.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 8, 5, 8));
        d.put("OptionPane.messageForeground", text);
        // Every message and question window alike: its content clear of the frame,
        // its buttons one size, together at the right with the answer that goes ahead last.
        d.put("OptionPane.border", BorderFactory.createEmptyBorder(Ui.em(14), Ui.em(16), Ui.em(12), Ui.em(16)));
        d.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(Ui.em(14), 0, 0, 0));
        d.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
        d.put("OptionPane.sameSizeButtons", Boolean.TRUE);
        d.put("OptionPane.buttonMinimumWidth", Ui.em(84));
        d.put("OptionPane.isYesLast", Boolean.TRUE);
        fitOptionWindows();
        d.put("OptionPane.informationIcon", new DialogIcon(DialogIcon.Kind.INFO));
        d.put("OptionPane.questionIcon", new DialogIcon(DialogIcon.Kind.QUESTION));
        d.put("OptionPane.warningIcon", new DialogIcon(DialogIcon.Kind.WARNING));
        d.put("OptionPane.errorIcon", new DialogIcon(DialogIcon.Kind.ERROR));
        d.put("TitledBorder.titleColor", text);
        d.put("TabbedPane.focus", new Color(0, 0, 0, 0));
    }

    /**
     * An HTML editor kit whose page colours follow the theme. A plain
     * {@code JEditorPane} renders HTML in black on white whatever the look and
     * feel says, which the dark theme cannot carry; every HTML pane (the
     * response render, advisories, issue definitions) takes this kit. A page
     * that brings its own styles still overrides these, as a render should.
     */
    public static javax.swing.text.html.HTMLEditorKit htmlKit() {
        javax.swing.text.html.HTMLEditorKit kit = new javax.swing.text.html.HTMLEditorKit();
        javax.swing.text.html.StyleSheet ss = new javax.swing.text.html.StyleSheet();
        ss.addStyleSheet(kit.getStyleSheet());
        ss.addRule(String.format("body { color: #%06X; background-color: #%06X; font-family: sans-serif; }",
                TEXT.getRGB() & 0xFFFFFF, BG.getRGB() & 0xFFFFFF));
        ss.addRule(String.format("a { color: #%06X; }", ACCENT.getRGB() & 0xFFFFFF));
        ss.addRule(String.format("pre, code { color: #%06X; }", TEXT.getRGB() & 0xFFFFFF));
        kit.setStyleSheet(ss);
        return kit;
    }

    /** A rounded hairline border for cards and grouped content. */
    public static Border cardBorder() {
        return new RoundedBorder(BORDER, null, RADIUS + 2, new Insets(10, 12, 10, 12));
    }

    /** Mark a button as the panel's primary action: filled with the accent. */
    public static <B extends AbstractButton> B primary(B b) {
        b.putClientProperty(PRIMARY, Boolean.TRUE);
        return b;
    }

    /**
     * Padding of a menu title. On the menu bar it is a compact label; inside a
     * popup (a row that opens a submenu) it takes the same gutter and height as
     * an ordinary item, so every row of a menu starts on one edge.
     */
    /** The rule between groups of menu rows: one pixel, with no space of its own, as the reference draws it. */
    public static final class MenuRule extends javax.swing.plaf.basic.BasicPopupMenuSeparatorUI {
        public static javax.swing.plaf.ComponentUI createUI(JComponent c) { return new MenuRule(); }
        @Override public Dimension getPreferredSize(JComponent c) { return new Dimension(0, 1); }
        @Override public void paint(Graphics g, JComponent c) {
            g.setColor(BORDER);
            g.fillRect(0, 0, c.getWidth(), 1);
        }
    }

    /** The chevron on a row that opens a submenu: 6 by 10, standing 7px in from the menu's right edge. */
    private static final class MenuChevron implements Icon, javax.swing.plaf.UIResource {
        @Override public int getIconWidth() { return 11; }
        @Override public int getIconHeight() { return 10; }
        @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.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2.setColor(c.isEnabled() ? TEXT : MUTED);
            g2.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
            java.awt.geom.Path2D.Float p = new java.awt.geom.Path2D.Float();
            p.moveTo(x + 4.8f, y + 0.6f);
            p.lineTo(x + 9.4f, y + 5f);
            p.lineTo(x + 4.8f, y + 9.4f);
            g2.draw(p);
            g2.dispose();
        }
    }

    /** The mark on a ticked menu row: no box, drawn in the gutter to the left of where the icon would sit. */
    private static final class MenuTick implements Icon, javax.swing.plaf.UIResource {
        @Override public int getIconWidth() { return 0; }
        @Override public int getIconHeight() { return 9; }
        @Override public void paintIcon(Component c, Graphics g, int x, int y) {
            if (!(c instanceof AbstractButton b) || !b.isSelected()) return;
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2.setColor(c.isEnabled() ? TEXT : MUTED);
            g2.setStroke(new BasicStroke(1.9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
            int left = x - 18, top = y;
            java.awt.geom.Path2D.Float tick = new java.awt.geom.Path2D.Float();
            tick.moveTo(left + 0.8f, top + 4.6f);
            tick.lineTo(left + 3.6f, top + 7.6f);
            tick.lineTo(left + 9.2f, top + 0.8f);
            g2.draw(tick);
            g2.dispose();
        }
    }

    private static final class MenuBorder extends javax.swing.border.AbstractBorder implements javax.swing.plaf.UIResource {
        @Override public Insets getBorderInsets(Component c, Insets in) {
            boolean top = !(c instanceof JMenu m) || m.isTopLevelMenu();
            // In the title bar a menu's name is lit over the bar's whole height, as the reference's is.
            boolean inTitle = top && SwingUtilities.getAncestorOfClass(TitleBar.class, c) != null;
            if (inTitle) in.set(9, 8, 9, 8); else if (top) in.set(4, 8, 4, 8); else in.set(3, 24, 3, 0);
            return in;
        }
        @Override public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0, 0, 0, 0)); }
    }

    /** The base colours the look and feel falls back to for anything not styled here. */
    private static final class Palette extends DefaultMetalTheme {
        private final ColorUIResource p1 = new ColorUIResource(ACCENT_DARK);
        private final ColorUIResource p2 = new ColorUIResource(ACCENT);
        private final ColorUIResource p3 = new ColorUIResource(ACCENT_LIGHT);
        private final ColorUIResource s1 = new ColorUIResource(BORDER);
        private final ColorUIResource s2 = new ColorUIResource(SURFACE_2);
        private final ColorUIResource s3 = new ColorUIResource(BG);
        private final ColorUIResource black = new ColorUIResource(TEXT);
        private final FontUIResource font = new FontUIResource(FONT);
        @Override public String getName() { return "Open Suite"; }
        @Override protected ColorUIResource getPrimary1() { return p1; }
        @Override protected ColorUIResource getPrimary2() { return p2; }
        @Override protected ColorUIResource getPrimary3() { return p3; }
        @Override protected ColorUIResource getSecondary1() { return s1; }
        @Override protected ColorUIResource getSecondary2() { return s2; }
        @Override protected ColorUIResource getSecondary3() { return s3; }
        @Override protected ColorUIResource getBlack() { return black; }
        @Override public FontUIResource getControlTextFont() { return font; }
        @Override public FontUIResource getSystemTextFont() { return font; }
        @Override public FontUIResource getUserTextFont() { return font; }
        @Override public FontUIResource getMenuTextFont() { return font; }
        @Override public FontUIResource getWindowTitleFont() { return font; }
        @Override public FontUIResource getSubTextFont() { return font; }
    }

    private static boolean fittingOptionWindows;

    private static void raise(Dialog d) {
        if (!d.isShowing()) return;
        d.toFront();
        d.requestFocus();
    }

    /** Bring forward the waiting question that holds {@code w} up, if there is one. */
    private static void raiseQuestionsOver(Window w) {
        for (Window o : Window.getWindows()) {
            if (!(o instanceof Dialog d) || !d.isModal() || !d.isShowing()) continue;
            // The question belongs to this window, or to one this window belongs to.
            for (Window up = d.getOwner(); up != null; up = up.getOwner()) {
                if (up == w) { raise(d); return; }
            }
        }
    }

    /**
     * Give every message and question window the room its content asks for.
     * A window is sized before the desktop adds its title bar, and on many Linux
     * desktops the bar then comes out of the content, leaving it a bar's height
     * short. A form laid out on a grid answers any shortfall by dropping every
     * input to its smallest size, a few pixels wide. Once the window is open
     * its real room is known, so it is grown by whatever is missing.
     */
    private static synchronized void fitOptionWindows() {
        if (fittingOptionWindows || GraphicsEnvironment.isHeadless()) return;
        fittingOptionWindows = true;
        // A question that waits for an answer must be seen. Some desktops open it
        // under the window it belongs to, or let that window be raised over it,
        // and the window then takes no clicks and looks frozen. So a question is
        // brought to the front when it opens, and again whenever a window it is
        // holding up is clicked or comes forward.
        Toolkit.getDefaultToolkit().addAWTEventListener(ev -> {
            int id = ev.getID();
            if (id == java.awt.event.WindowEvent.WINDOW_OPENED && ev.getSource() instanceof Dialog d && d.isModal()) {
                SwingUtilities.invokeLater(() -> raise(d));
            } else if ((id == java.awt.event.WindowEvent.WINDOW_ACTIVATED || id == java.awt.event.WindowEvent.WINDOW_GAINED_FOCUS)
                    && ev.getSource() instanceof Window w && !(w instanceof Dialog dd && dd.isModal())) {
                SwingUtilities.invokeLater(() -> raiseQuestionsOver(w));
            }
        }, AWTEvent.WINDOW_EVENT_MASK | AWTEvent.WINDOW_FOCUS_EVENT_MASK);
        Toolkit.getDefaultToolkit().addAWTEventListener(ev -> {
            if (ev.getID() != java.awt.event.WindowEvent.WINDOW_OPENED || !(ev.getSource() instanceof JDialog dlg)) return;
            Container content = dlg.getContentPane();
            if (content.getComponentCount() == 0 || !(content.getComponent(0) instanceof JOptionPane)) return;
            SwingUtilities.invokeLater(() -> {
                if (!dlg.isShowing()) return;
                Dimension want = content.getPreferredSize(), has = content.getSize();
                int dw = Math.max(0, want.width - has.width), dh = Math.max(0, want.height - has.height);
                if (dw == 0 && dh == 0) return;
                dlg.setSize(dlg.getWidth() + dw, dlg.getHeight() + dh);
                dlg.validate();
            });
        }, AWTEvent.WINDOW_EVENT_MASK);
        // Every window of the application carries its icon. One opened without
        // any would show the desktop's own placeholder in its title bar.
        Toolkit.getDefaultToolkit().addAWTEventListener(ev -> {
            if (ev.getID() != java.awt.event.WindowEvent.WINDOW_OPENED) return;
            if (!(ev.getSource() instanceof Window w) || !(w instanceof Frame || w instanceof Dialog)) return;
            if (w.getIconImages().isEmpty()) w.setIconImages(AppIcon.images());
        }, AWTEvent.WINDOW_EVENT_MASK);
    }
}