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.

40.2 KB
Raw Blame
package opensuite.ui;

import opensuite.core.SuiteContext;
import opensuite.ui.settings.InterfacePages;
import opensuite.ui.settings.NetworkPages;
import opensuite.ui.settings.ProjectPages;
import opensuite.ui.settings.SettingsPage;
import opensuite.ui.settings.SuitePages;
import opensuite.ui.settings.ToolPages;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * The suite Settings window: a tree of sections and pages on the left with
 * All / User / Project filter pills and a search box, the chosen page on the
 * right under a breadcrumb and a "Manage global settings" menu, and the
 * Configuration library beneath the tree.
 *
 * <p>Tools own their settings panes and register them by category name; the
 * dialog places each registered pane at its spot in the tree (a tool's
 * category is a page under Tools, and so on). Pages nobody registers are
 * built here from the shared settings pages.
 */
public final class SettingsDialog {

    /** The tree pane: 342 wide at the smallest font, 353 at the usual 13px. */
    private static final int LEFT_WIDTH = 342 + Math.round(5.5f * Ui.fontGrowth());

    private SettingsDialog() {}

    /** One page in the tree. */
    private record Page(String section, String name, Supplier<JComponent> pane) {
        String path() { return section == null ? name : section + " > " + name; }
    }

    /** Registered panes by legacy category name (a tool's name, "Sessions", ...). */
    private static final Map<String, Supplier<JComponent>> PANES = new LinkedHashMap<>();

    /** The categories, for callers that open the dialog at one. */
    public static final String[] CATEGORIES = {
        "General", "Proxy", "Intruder", "Repeater", "Sequencer", "Comparer", "Browser",
        "Project", "Sessions", "Suite", "Extensions", "Configuration library",
    };

    /** Claim a category. The supplier is called each time the dialog opens. */
    public static void register(String category, Supplier<JComponent> pane) {
        PANES.put(category, pane);
    }

    /** The tree: section -> pages, in the reference order. */
    /**
     * Every settings page, built. Used by the test that opens all of them: a
     * page that throws on construction takes the whole dialog down, and that
     * is only noticed by someone clicking that one entry in the tree.
     */
    public static java.util.List<String> buildEveryPage(SuiteContext ctx) {
        java.util.List<String> failures = new ArrayList<>();
        for (Page p : pages(ctx)) {
            try {
                JComponent c = p.pane().get();
                if (c == null) failures.add(p.path() + ": built nothing");
            } catch (Throwable t) {
                failures.add(p.path() + ": " + t);
            }
        }
        return failures;
    }

    private static List<Page> pages(SuiteContext ctx) {
        List<Page> out = new ArrayList<>();
        // Tools
        out.add(new Page("Tools", "Proxy", registered("Proxy")));
        out.add(new Page("Tools", "Intruder", registered("Intruder")));
        out.add(new Page("Tools", "Repeater", registered("Repeater")));
        out.add(new Page("Tools", "Sequencer", registered("Sequencer")));
        out.add(new Page("Tools", "Comparer", () -> ToolPages.comparer(ctx)));
        out.add(new Page("Tools", "Browser", () -> ToolPages.browser(ctx, PANES.containsKey("Browser") ? PANES.get("Browser").get() : null)));
        // Project
        out.add(new Page("Project", "Scope", () -> ProjectPages.scope(ctx)));
        out.add(new Page("Project", "Collaborator", () -> ProjectPages.collaborator(ctx)));
        out.add(new Page("Project", "Tasks", () -> ProjectPages.tasks(ctx)));
        out.add(new Page("Project", "Automatic backup", () -> ProjectPages.backup(ctx)));
        out.add(new Page("Project", "Logging", () -> ProjectPages.logging(ctx)));
        // Sessions
        out.add(new Page(null, "Sessions", registered("Sessions")));
        // Network
        out.add(new Page("Network", "Connections", () -> NetworkPages.connections(ctx)));
        out.add(new Page("Network", "DNS", () -> NetworkPages.dns(ctx)));
        out.add(new Page("Network", "TLS", () -> NetworkPages.tls(ctx)));
        out.add(new Page("Network", "HTTP", () -> NetworkPages.http(ctx)));
        // User interface
        out.add(new Page("User interface", "Side panel", () -> InterfacePages.sidePanel(ctx)));
        out.add(new Page("User interface", "Message editor", () -> InterfacePages.messageEditor(ctx)));
        out.add(new Page("User interface", "Hotkeys", () -> InterfacePages.hotkeys(ctx)));
        out.add(new Page("User interface", "Display", () -> InterfacePages.display(ctx, null)));
        // Suite
        out.add(new Page("Suite", "REST API", () -> SuitePages.restApi(ctx)));
        out.add(new Page("Suite", "Updates", () -> SuitePages.updates(ctx)));
        out.add(new Page("Suite", "Performance", () -> SuitePages.performance(ctx)));
        out.add(new Page("Suite", "Temporary files location", () -> SuitePages.tempFiles(ctx)));
        out.add(new Page("Suite", "Startup behavior", () -> SuitePages.startup(ctx)));
        out.add(new Page("Suite", "Shutdown behavior", () -> SuitePages.shutdown(ctx)));
        // Extensions
        out.add(new Page("Extensions", "Core extension settings", registered("Extensions")));
        return out;
    }

    private static Supplier<JComponent> registered(String category) {
        return () -> {
            Supplier<JComponent> s = PANES.get(category);
            if (s != null) return s.get();
            JPanel p = new JPanel(new BorderLayout());
            p.add(Ui.note("No settings registered for " + category + "."), BorderLayout.NORTH);
            return p;
        };
    }

    /** Where a legacy category name lands in the tree. */
    private static String pathFor(String category) {
        if (category == null) return "Tools > Proxy";
        return switch (category) {
            case "General" -> "User interface > Display";
            case "Proxy", "Intruder", "Repeater", "Sequencer", "Comparer", "Browser" -> "Tools > " + category;
            case "Project" -> "Project > Logging";
            case "Scope" -> "Project > Scope";
            case "Collaborator" -> "Project > Collaborator";
            case "Tasks" -> "Project > Tasks";
            case "Sessions" -> "Sessions";
            case "Suite" -> "Suite > Performance";
            case "Extensions" -> "Extensions > Core extension settings";
            case "Configuration library" -> "Configuration library";
            default -> category.contains(" > ") ? category : "Tools > Proxy";
        };
    }

    public static void open(Window owner, SuiteContext ctx) { open(owner, ctx, null); }

    /** The one Settings window; opening it again brings it forward at the page asked for. */
    private static JFrame openWindow;
    private static java.util.function.Consumer<String> openGoto;

    /** Open the window, showing {@code category} (a tool name or a "Section > Page" path) if given. */
    public static void open(Window owner, SuiteContext ctx, String category) {
        if (openWindow != null && openWindow.isDisplayable()) {
            if (category != null && openGoto != null) openGoto.accept(category);
            openWindow.setExtendedState(openWindow.getExtendedState() & ~Frame.ICONIFIED);
            openWindow.toFront();
            return;
        }
        // A window of its own, as the reference's is: titled, resizable, and
        // not modal, so the tools stay usable while it is open.
        final JFrame d = new JFrame("Settings");
        d.setIconImages(AppIcon.images());
        boolean ownBar = ctx.settings().getBool("ui.mergeTitleBar", !opensuite.core.Os.MAC);
        if (ownBar) TitleBar.install(d);
        List<Page> pages = pages(ctx);

        // ---- right: breadcrumb + manage menu, then the page cards ----
        CardLayout cards = new CardLayout();
        final JPanel right = new JPanel(cards);
        right.setBackground(Theme.BG);
        Map<String, JComponent> built = new LinkedHashMap<>();
        lastBuilt = built;
        Map<String, Page> byPath = new LinkedHashMap<>();
        for (Page p : pages) byPath.put(p.path(), p);
        // What the window added to hosted pages, undone when it closes.
        List<Runnable> undo = new ArrayList<>();

        final JPanel crumb = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        crumb.setOpaque(false);
        JLabel manageLabel = new JLabel("Manage global settings");
        manageLabel.setFont(Ui.PLAIN);
        manageLabel.setForeground(Theme.TEXT);
        JButton kebab = Glyphs.menuButton("Manage global settings", () -> manageMenu(d, ctx, built));
        kebab.setIcon(kebabIcon());
        kebab.setBorder(null);
        Ui.sized(kebab, 11);
        JPanel manage = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        manage.setOpaque(false);
        manage.add(manageLabel);
        manage.add(Box.createHorizontalStrut(13));
        manage.add(kebab);
        JPanel head = new JPanel(new BorderLayout());
        head.setBackground(Theme.CONTENT);
        head.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(10, 20, 10, 18)));
        head.setPreferredSize(new Dimension(10, Ui.tall(43)));
        head.add(crumb, BorderLayout.WEST);
        head.add(manage, BorderLayout.EAST);
        JPanel rightWrap = new JPanel(new BorderLayout());
        rightWrap.setBackground(Theme.BG);
        rightWrap.add(head, BorderLayout.NORTH);
        rightWrap.add(right, BorderLayout.CENTER);

        // The Configuration library is a page too, reached from the menu.
        Supplier<JComponent> library = registered("Configuration library");

        java.util.function.Consumer<String> show = path -> {
            JComponent pane = built.get(path);
            if (pane == null) {
                Page p = byPath.get(path);
                pane = "Configuration library".equals(path) ? library.get() : (p == null ? new JPanel() : p.pane().get());
                List<OptionsPage> inside = new ArrayList<>();
                collectPages(pane, inside);
                for (OptionsPage op : inside) {
                    // 10px in from the top and the sides,
                    // and every section with its scope badge and its settings mark.
                    op.setPageInsets(10, 10, 10);
                    undo.add(() -> op.setPageInsets(0, 0, 0));
                    boolean userPage = path.startsWith("User interface") || path.startsWith("Suite") || path.startsWith("Extensions");
                    for (JPanel sec : op.sections()) {
                        if (!Sections.hasTrailing(sec)) {
                            Sections.setTrailing(sec, Sections.badges(userPage ? "User setting" : "Project setting"));
                            undo.add(() -> Sections.setTrailing(sec, null));
                        }
                        if (!Sections.hasSecond(sec)) {
                            Sections.setSecond(sec, sectionGear(d, ctx, built, path));
                            undo.add(() -> Sections.setSecond(sec, null));
                        }
                    }
                }
                if (inside.isEmpty()) {
                    JPanel wrap = new JPanel(new BorderLayout());
                    wrap.setBackground(Theme.BG);
                    wrap.setBorder(Ui.pad(18, 20, 8, 10));
                    wrap.add(pane, BorderLayout.CENTER);
                    pane = wrap;
                }
                built.put(path, pane);
                right.add(pane, path);
            }
            // Tools > Proxy, in ordinary weight with a chevron between.
            crumb.removeAll();
            String[] parts = path.split(" > ");
            for (int k = 0; k < parts.length; k++) {
                if (k > 0) {
                    JLabel sep = new JLabel(crumbChevron());
                    sep.setBorder(Ui.pad(1, 14, 0, 14));
                    crumb.add(sep);
                }
                JLabel part = new JLabel(parts[k]);
                part.setFont(Ui.PLAIN);
                part.setForeground(Theme.TEXT);
                part.setPreferredSize(new Dimension(part.getPreferredSize().width, Ui.tall(22)));
                crumb.add(part);
            }
            crumb.revalidate();
            crumb.repaint();
            cards.show(right, path);
        };

        // ---- left: search, pills, tree ----
        JTextField search = Ui.searchField(12);
        search.setColumns(0);
        search.setPreferredSize(new Dimension(LEFT_WIDTH - 40, Ui.tall(22)));
        JToggleButton all = pill("All", true, 72), user = pill("User", false, 72), project = pill("Project", false, 82);
        ButtonGroup pills = new ButtonGroup();
        pills.add(all); pills.add(user); pills.add(project);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("settings");
        RowTree tree = new RowTree(new DefaultTreeModel(root));
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        tree.setRowHeight(Ui.tall(26));
        tree.setOpaque(false);
        tree.setBackground(Theme.CONTENT);
        tree.setBorder(Ui.pad(11, TREE_LEFT, 11, 0));
        tree.setIndents(TREE_INDENT_L, TREE_INDENT_R);
        tree.setBand(11, 10);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        Runnable rebuild = () -> {
            root.removeAllChildren();
            String q = search.getText().strip().toLowerCase();
            SettingsPage.Kind want = user.isSelected() ? SettingsPage.Kind.USER : project.isSelected() ? SettingsPage.Kind.PROJECT : null;
            Map<String, DefaultMutableTreeNode> sections = new LinkedHashMap<>();
            for (Page p : pages) {
                if (!q.isEmpty() && !p.name().toLowerCase().contains(q) && !(p.section() != null && p.section().toLowerCase().contains(q))) continue;
                if (want != null && !matchesKind(p, want, built)) continue;
                DefaultMutableTreeNode leaf = new DefaultMutableTreeNode(p);
                if (p.section() == null) root.add(leaf);
                else sections.computeIfAbsent(p.section(), k -> { DefaultMutableTreeNode n = new DefaultMutableTreeNode(k); root.add(n); return n; }).add(leaf);
            }
            ((DefaultTreeModel) tree.getModel()).reload();
            for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i);
        };
        // Plain names, no icons; the tree paints the band behind the chosen row.
        javax.swing.tree.DefaultTreeCellRenderer cell = new javax.swing.tree.DefaultTreeCellRenderer() {
            @Override public Component getTreeCellRendererComponent(JTree t, Object v, boolean sel, boolean exp, boolean leaf, int row, boolean focus) {
                super.getTreeCellRendererComponent(t, v, sel, exp, leaf, row, false);
                Object o = ((DefaultMutableTreeNode) v).getUserObject();
                setText(o instanceof Page p ? p.name() : String.valueOf(o));
                setIcon(null);
                setFont(Ui.PLAIN);
                setForeground(Theme.TEXT);
                setOpaque(false);
                return this;
            }
        };
        tree.setCellRenderer(cell);
        tree.addTreeSelectionListener(e -> {
            Object o = tree.getLastSelectedPathComponent();
            if (o instanceof DefaultMutableTreeNode n && n.getUserObject() instanceof Page p) show.accept(p.path());
        });
        for (AbstractButton b : new AbstractButton[]{all, user, project}) b.addActionListener(e -> rebuild.run());
        search.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void insertUpdate(javax.swing.event.DocumentEvent e) { rebuild.run(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e) { rebuild.run(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { rebuild.run(); }
        });

        JPanel searchRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        searchRow.setOpaque(false);
        searchRow.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(10, 20, 10, 0)));
        searchRow.setPreferredSize(new Dimension(10, Ui.tall(43)));
        searchRow.add(search);

        JButton expand = Glyphs.button(foldIcon(true), "Expand all", () -> { for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); });
        JButton collapse = Glyphs.button(foldIcon(false), "Collapse all", () -> { for (int i = tree.getRowCount() - 1; i >= 0; i--) tree.collapseRow(i); });
        expand.setBorder(null);
        collapse.setBorder(null);
        // Pills at 20, 98 and 176; the two marks at 280 and 307.
        JPanel pillRow = new JPanel(null);
        pillRow.setOpaque(false);
        pillRow.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER));
        pillRow.setPreferredSize(new Dimension(10, Ui.tall(43)));
        all.setBounds(20, 10, 72, Ui.tall(22));
        user.setBounds(98, 10, 72, Ui.tall(22));
        project.setBounds(176, 10, 82, Ui.tall(22));
        expand.setBounds(280, 14, 13, 15);
        collapse.setBounds(307, 14, 13, 15);
        for (JComponent c : new JComponent[] { all, user, project, expand, collapse }) pillRow.add(c);
        rebuild.run();

        JPanel left = new JPanel(new BorderLayout());
        left.setBackground(Theme.CONTENT);
        JPanel leftTop = new JPanel(new BorderLayout());
        leftTop.setOpaque(false);
        leftTop.add(searchRow, BorderLayout.NORTH);
        leftTop.add(pillRow, BorderLayout.SOUTH);
        left.add(leftTop, BorderLayout.NORTH);
        // Beneath the tree, under a rule, the Configuration library has a row of its own.
        boolean[] libraryOn = { false };
        JComponent libraryRow = new JComponent() {
            @Override protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                Theme.textSmoothing(g2);
                int top = 12, h = Ui.tall(26);
                g2.setColor(Theme.BORDER);
                g2.fillRect(21, 0, getWidth() - 41, 1);
                if (libraryOn[0]) {
                    g2.setColor(UIManager.getColor("Tree.selectionBackground"));
                    g2.fillRoundRect(11, top, getWidth() - 21, h, 8, 8);
                }
                Icon book = Glyphs.book(14, Theme.TEXT);
                book.paintIcon(this, g2, 18, top + (h - book.getIconHeight()) / 2);
                g2.setFont(Ui.PLAIN);
                FontMetrics fm = g2.getFontMetrics();
                g2.setColor(Theme.TEXT);
                g2.drawString("Configuration library", 37, top + (h - fm.getHeight()) / 2 + fm.getAscent());
                g2.dispose();
            }
        };
        libraryRow.setPreferredSize(new Dimension(10, 12 + Ui.tall(26) + 12));
        libraryRow.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) {
                if (e.getY() < 12) return;
                tree.clearSelection();
                libraryOn[0] = true;
                libraryRow.repaint();
                show.accept("Configuration library");
            }
        });
        tree.addTreeSelectionListener(e -> {
            if (tree.getSelectionCount() > 0 && libraryOn[0]) { libraryOn[0] = false; libraryRow.repaint(); }
        });
        JPanel treeColumn = new JPanel(new BorderLayout());
        treeColumn.setBackground(Theme.CONTENT);
        treeColumn.add(tree, BorderLayout.NORTH);
        JPanel foot = new JPanel(new BorderLayout());
        foot.setOpaque(false);
        foot.add(libraryRow, BorderLayout.NORTH);
        treeColumn.add(foot, BorderLayout.CENTER);
        JScrollPane ts = new JScrollPane(treeColumn);
        ts.setBorder(null);
        ts.setOpaque(false);
        ts.getViewport().setBackground(Theme.CONTENT);
        ts.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        ts.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        ts.getVerticalScrollBar().setUnitIncrement(16);
        left.add(ts, BorderLayout.CENTER);
        left.setMinimumSize(new Dimension(LEFT_WIDTH, 100));

        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, rightWrap);
        split.setDividerSize(1);
        split.setBorder(null);
        split.setDividerLocation(LEFT_WIDTH);

        // Open at the requested page, now and whenever the window is asked for again.
        java.util.function.Consumer<String> go = cat -> {
            String path = "Configuration library".equals(cat) ? "Configuration library" : pathFor(cat);
            if ("Configuration library".equals(path)) { tree.clearSelection(); libraryOn[0] = true; libraryRow.repaint(); show.accept(path); }
            else if (byPath.containsKey(path)) { selectPath(tree, path); show.accept(path); }
        };
        go.accept(category);
        openGoto = go;

        // Release the hosted panes when the window goes, so a tool's pane can be
        // hosted again next time (and shown by the tool meanwhile if it wants).
        d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        d.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override public void windowClosed(java.awt.event.WindowEvent e) {
                for (Runnable r : undo) r.run();
                undo.clear();
                right.removeAll();
                if (openWindow == d) { openWindow = null; openGoto = null; }
            }
        });
        d.getRootPane().registerKeyboardAction(e -> d.dispose(),
                KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        d.getContentPane().add(split, BorderLayout.CENTER);
        // 1231 by 800 at the smallest font, 1425 by 900 at the usual 13px, never larger than the screen.
        Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        d.setSize(Math.min(screen.width, 1231 + 97 * Ui.fontGrowth()), Math.min(screen.height, 800 + 50 * Ui.fontGrowth()));
        d.setMinimumSize(new Dimension(900, 600));
        // As the reference opens: only the group of the page in front is unfolded.
        javax.swing.tree.TreePath chosen = tree.getSelectionPath();
        for (int i = tree.getRowCount() - 1; i >= 0; i--) {
            javax.swing.tree.TreePath row = tree.getPathForRow(i);
            if (row != null && row.getPathCount() == 2 && (chosen == null || !row.isDescendant(chosen))) tree.collapseRow(i);
        }
        if (chosen != null) tree.setSelectionPath(chosen);
        d.setLocationRelativeTo(owner);
        openWindow = d;
        d.setVisible(true);
    }

    /** Every options page in {@code c}: the pane itself, or pages it nests (but not pages inside pages). */
    private static void collectPages(Component c, List<OptionsPage> out) {
        if (c instanceof OptionsPage op) { out.add(op); return; }
        if (c instanceof Container k) for (Component child : k.getComponents()) collectPages(child, out);
    }

    private static final int TREE_LEFT = 25 - Math.round(1.5f * Ui.fontGrowth()), TREE_INDENT_L = 1, TREE_INDENT_R = 11 + Math.round(1.5f * Ui.fontGrowth());

    /** The mark under a section's help mark: a gear whose menu restores, loads or saves settings. */
    private static JButton sectionGear(Window d, SuiteContext ctx, Map<String, JComponent> built, String path) {
        JButton b = Glyphs.button(Glyphs.gear(21, Theme.TEXT), "Settings for this section", null);
        b.setBorder(null);
        b.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            m.add(item("Restore defaults", () -> restoreDefaults(ctx, built, path)));
            m.add(item("Load settings", () -> load(d, ctx)));
            m.add(item("Save settings", () -> save(d, ctx, "project")));
            m.show(b, 0, b.getHeight());
        });
        return b;
    }

    /** The three dots beside "Manage global settings": 3px, 5px apart. */
    private static Icon kebabIcon() {
        return new Icon() {
            @Override public int getIconWidth() { return 3; }
            @Override public int getIconHeight() { return 13; }
            @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(Theme.TEXT);
                for (int k = 0; k < 3; k++) g2.fill(new java.awt.geom.Ellipse2D.Double(x, y + k * 5, 3, 3));
                g2.dispose();
            }
        };
    }

    /** The chevron between the parts of the breadcrumb. */
    private static Icon crumbChevron() {
        return new Icon() {
            @Override public int getIconWidth() { return 6; }
            @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(Theme.TEXT);
                g2.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
                p.moveTo(x + 0.8, y + 0.8); p.lineTo(x + 5.2, y + 5); p.lineTo(x + 0.8, y + 9.2);
                g2.draw(p);
                g2.dispose();
            }
        };
    }

    /**
     * Expand all: two bars with arrowheads pushing them apart. Collapse all:
     * one bar with arrowheads closing on it. 13 by 15.
     */
    private static Icon foldIcon(boolean expand) {
        return new Icon() {
            @Override public int getIconWidth() { return 13; }
            @Override public int getIconHeight() { return 15; }
            private void head(Graphics2D g2, double cx, double tip, double base) {
                java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
                p.moveTo(cx, tip); p.lineTo(cx - 3, base); p.lineTo(cx + 3, base); p.closePath();
                g2.fill(p);
            }
            @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(Theme.TEXT);
                double cx = x + 6.5;
                if (expand) {
                    g2.fill(new java.awt.geom.Rectangle2D.Double(x, y, 13, 1.5));
                    g2.fill(new java.awt.geom.Rectangle2D.Double(x, y + 13.5, 13, 1.5));
                    head(g2, cx, y + 3, y + 6.5);
                    head(g2, cx, y + 12, y + 8.5);
                } else {
                    g2.fill(new java.awt.geom.Rectangle2D.Double(x, y + 6.75, 13, 1.5));
                    head(g2, cx, y + 4, y + 0.5);
                    head(g2, cx, y + 11, y + 14.5);
                }
                g2.dispose();
            }
        };
    }

    private static boolean matchesKind(Page p, SettingsPage.Kind want, Map<String, JComponent> built) {
        JComponent c = built.get(p.path());
        if (c instanceof SettingsPage sp) {
            if (sp.kinds().isEmpty()) return true;
            return sp.kinds().contains(want) || sp.kinds().contains(SettingsPage.Kind.BOTH);
        }
        // Not built yet: classify by section, as the reference does.
        String sec = p.section() == null ? p.name() : p.section();
        return switch (sec) {
            case "User interface", "Suite", "Extensions" -> want == SettingsPage.Kind.USER;
            case "Sessions" -> want == SettingsPage.Kind.PROJECT;
            case "Project" -> want == SettingsPage.Kind.PROJECT || "Automatic backup".equals(p.name()) || "Collaborator".equals(p.name());
            default -> true;   // Tools and Network mix both kinds
        };
    }

    private static void selectPath(JTree tree, String path) {
        for (int i = 0; i < tree.getRowCount(); i++) {
            Object o = tree.getPathForRow(i).getLastPathComponent();
            if (o instanceof DefaultMutableTreeNode n && n.getUserObject() instanceof Page p && p.path().equals(path)) {
                tree.setSelectionRow(i);
                final int row = i;
                // Keep the top of the tree in view when the row is near it, so
                // the row's group heading is not scrolled away.
                SwingUtilities.invokeLater(() -> {
                    Rectangle r = tree.getRowBounds(row);
                    if (r == null) return;
                    int room = tree.getParent() == null ? 0 : tree.getParent().getHeight();
                    if (r.y + r.height <= room) tree.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
                    else tree.scrollRowToVisible(row);
                });
                return;
            }
        }
    }

    /**
     * One of the All / User / Project filter pills: fully rounded, 22px tall,
     * bold. The chosen pill is filled with the control colour.
     */
    private static JToggleButton pill(String text, boolean on, int width) {
        JToggleButton b = new JToggleButton(text, on) {
            @Override protected void paintComponent(java.awt.Graphics g) {
                java.awt.Graphics2D g2 = (java.awt.Graphics2D) g.create();
                g2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
                opensuite.ui.Theme.textSmoothing(g2);
                int w = getWidth(), h = getHeight();
                g2.setColor(isSelected() ? Theme.CONTROL : Theme.BORDER);
                g2.fillRoundRect(0, 0, w, h, h, h);
                if (!isSelected()) {
                    g2.setColor(Theme.SURFACE);
                    g2.fillRoundRect(1, 1, w - 2, h - 2, h - 2, h - 2);
                }
                g2.setColor(isSelected() ? java.awt.Color.WHITE : Theme.TEXT);
                g2.setFont(getFont());
                java.awt.FontMetrics fm = g2.getFontMetrics();
                g2.drawString(getText(), (w - fm.stringWidth(getText())) / 2f, (h + fm.getAscent() - fm.getDescent()) / 2f);
                g2.dispose();
            }
        };
        b.setFont(Ui.BOLD);
        b.setFocusable(false);
        b.setContentAreaFilled(false);
        b.setBorder(null);
        b.setPreferredSize(new Dimension(width, Ui.tall(22)));
        b.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
        return b;
    }

    /** What one level of nesting costs a tree row, matching the tree's own indent. */
    private static final int INDENT_PER_LEVEL = 20;

    /** The mark beside a settings section, so the sections read apart at a glance. */
    private static Icon sectionIcon(String section) {
        return switch (section) {
            case "Tools"                 -> Glyphs.gear(14, Theme.ICON);
            case "Project"               -> Glyphs.book(14, Theme.ICON);
            case "Sessions"              -> Glyphs.clock(14, Theme.ICON);
            case "Network"               -> Glyphs.bolt(14, Theme.ICON);
            case "User interface"        -> Glyphs.hamburger(14, Theme.ICON);
            case "Suite"                 -> Glyphs.star(14, Theme.ICON, false);
            case "Extensions"            -> Glyphs.plusRing(14, Theme.ICON);
            case "Configuration library" -> Glyphs.book(14, Theme.ICON);
            default -> null;
        };
    }

    /** User settings > Restore defaults / Load / Save; Project settings > Restore defaults > ... / Load / Save. */
    private static JPopupMenu manageMenu(Window d, SuiteContext ctx, Map<String, JComponent> built) {
        JPopupMenu m = new JPopupMenu();
        m.add(userSettingsMenu(d, ctx, built));
        m.add(projectSettingsMenu(d, ctx, built));
        return m;
    }

    /** The pages of the settings window that is open, or was open last; empty before the first. */
    private static Map<String, JComponent> lastBuilt = new LinkedHashMap<>();

    /** "User settings" as the application menu shows it: Restore defaults, Load, Save. */
    public static JMenu userSettingsMenu(Window d, SuiteContext ctx) { return userSettingsMenu(d, ctx, null); }

    /** "Project settings" as the Project menu shows it. */
    public static JMenu projectSettingsMenu(Window d, SuiteContext ctx) { return projectSettingsMenu(d, ctx, null); }

    private static JMenu userSettingsMenu(Window d, SuiteContext ctx, Map<String, JComponent> built) {
        JMenu userMenu = new JMenu("User settings");
        userMenu.setFont(Ui.PLAIN);
        userMenu.add(item("Restore defaults", () -> restoreDefaults(ctx, built == null ? lastBuilt : built, "User interface", "Suite", "Extensions", "Tools")));
        userMenu.add(item("Load user settings", () -> load(d, ctx)));
        userMenu.add(item("Save user settings", () -> save(d, ctx, "user")));
        return userMenu;
    }

    private static JMenu projectSettingsMenu(Window d, SuiteContext ctx, Map<String, JComponent> given) {
        JMenu projectMenu = new JMenu("Project settings");
        projectMenu.setFont(Ui.PLAIN);
        JMenu restore = new JMenu("Restore defaults");
        restore.setFont(Ui.PLAIN);
        java.util.function.Supplier<Map<String, JComponent>> built = () -> given == null ? lastBuilt : given;
        restore.add(item("All", () -> restoreDefaults(ctx, built.get(), "Project", "Network", "Sessions", "Tools")));
        restore.add(item("Target", () -> restoreDefaults(ctx, built.get(), "Project > Scope")));
        restore.add(item("Proxy", () -> restoreDefaults(ctx, built.get(), "Tools > Proxy")));
        restore.add(item("Repeater", () -> restoreDefaults(ctx, built.get(), "Tools > Repeater")));
        restore.add(item("Sequencer", () -> restoreDefaults(ctx, built.get(), "Tools > Sequencer")));
        restore.add(item("Logger", () -> restoreDefaults(ctx, built.get(), "Project > Logging")));
        restore.add(item("Other project settings", () -> restoreDefaults(ctx, built.get(), "Project", "Network")));
        projectMenu.add(restore);
        projectMenu.add(item("Load project settings", () -> load(d, ctx)));
        projectMenu.add(item("Save project settings", () -> save(d, ctx, "project")));
        return projectMenu;
    }

    private static JMenuItem item(String text, Runnable r) {
        JMenuItem mi = new JMenuItem(text);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> r.run());
        return mi;
    }

    /** Restore every built page whose path starts with one of the prefixes. */
    private static void restoreDefaults(SuiteContext ctx, Map<String, JComponent> built, String... prefixes) {
        int n = 0;
        for (Map.Entry<String, JComponent> e : built.entrySet()) {
            for (String p : prefixes) {
                if (e.getKey().startsWith(p) && e.getValue() instanceof SettingsPage sp) { sp.restoreAll(); n++; break; }
            }
        }
        JOptionPane.showMessageDialog(ctx.frame(), n == 0
                ? "Open a page first. Only pages viewed in this window can be restored here."
                : "Restored defaults for " + n + " page(s).", "Restore defaults", JOptionPane.INFORMATION_MESSAGE);
    }

    private static void save(Window d, SuiteContext ctx, String kind) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setSelectedFile(new java.io.File("opensuite-" + kind + "-settings.properties"));
        if (fc.showSaveDialog(d) != JFileChooser.APPROVE_OPTION) return;
        java.util.Properties p = new java.util.Properties();
        p.putAll(ctx.settings().snapshot());
        try (var w = java.nio.file.Files.newBufferedWriter(fc.getSelectedFile().toPath())) { p.store(w, "Open Suite " + kind + " settings"); }
        catch (java.io.IOException e) { JOptionPane.showMessageDialog(d, "Could not save: " + e.getMessage(), "Save settings", JOptionPane.ERROR_MESSAGE); }
    }

    private static void load(Window d, SuiteContext ctx) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        if (fc.showOpenDialog(d) != JFileChooser.APPROVE_OPTION) return;
        java.util.Properties p = new java.util.Properties();
        try (var r = java.nio.file.Files.newBufferedReader(fc.getSelectedFile().toPath())) { p.load(r); }
        catch (java.io.IOException e) { JOptionPane.showMessageDialog(d, "Could not load: " + e.getMessage(), "Load settings", JOptionPane.ERROR_MESSAGE); return; }
        for (String k : p.stringPropertyNames()) ctx.settings().set(k, p.getProperty(k));
        JOptionPane.showMessageDialog(d, "Loaded " + p.size() + " setting(s). Reopen Settings to see them.", "Load settings", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * A small page for a tool's own settings tab: it says where the settings
     * live and opens the dialog there, so each setting has exactly one home.
     */
    /**
     * A sub-tab that is really a button: choosing it opens the Settings window
     * at {@code category} rather than showing a page with a button on it, which
     * is what the reference does. The component itself is never seen; the tab
     * strip snaps back to where it was.
     *
     * <p>The heading and note are kept for the brief moment the pane is shown
     * if a tabbed pane is not wired, and as the accessible description.
     */
    public static JComponent launcher(SuiteContext ctx, String category, String heading, String note) {
        JPanel page = new JPanel(new BorderLayout());
        page.setBorder(Ui.pad(16, 16, 16, 16));
        page.putClientProperty(LAUNCH_CATEGORY, category);
        page.putClientProperty(LAUNCH_CONTEXT, ctx);
        page.getAccessibleContext().setAccessibleDescription(heading + ". " + note);
        return page;
    }

    private static final String LAUNCH_CATEGORY = "opensuite.settingsLauncher.category";
    private static final String LAUNCH_CONTEXT  = "opensuite.settingsLauncher.context";

    /**
     * Make any launcher tabs in {@code tabs} behave as buttons: choosing one
     * opens Settings at its page and leaves the strip on the tab that was
     * showing before.
     */
    public static void wireLaunchers(JTabbedPane tabs) {
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (categoryOf(tabs.getComponentAt(i)) != null) {
                tabs.setIconAt(i, new LauncherIcon());
            }
        }
        final int[] previous = { tabs.getSelectedIndex() };
        tabs.addChangeListener(e -> {
            int i = tabs.getSelectedIndex();
            if (i < 0) return;
            Component c = tabs.getComponentAt(i);
            String category = categoryOf(c);
            if (category == null) { previous[0] = i; return; }
            int back = previous[0] >= 0 && previous[0] != i && previous[0] < tabs.getTabCount()
                    ? previous[0] : 0;
            SuiteContext ctx = (SuiteContext) ((JComponent) c).getClientProperty(LAUNCH_CONTEXT);
            // Put the strip back first, so the tab never reads as selected
            // while the window is open, then open it.
            SwingUtilities.invokeLater(() -> {
                tabs.setSelectedIndex(back);
                Window w = ctx != null && ctx.frame() instanceof Window win ? win : null;
                open(w, ctx, category);
            });
        });
    }

    private static String categoryOf(Component c) {
        return c instanceof JComponent jc ? (String) jc.getClientProperty(LAUNCH_CATEGORY) : null;
    }

    /**
     * The mark on a "... settings" sub-tab: a vertical divider that parts it
     * from the real sub-tabs, then the cog. The divider is drawn just outside
     * the icon's own box so it stands in the gap between the two tabs.
     */
    private static final class LauncherIcon implements Icon, opensuite.ui.theme.FlatTabbedPaneUI.Divided {
        private final Icon cog = Glyphs.gear(18, Theme.TEXT);
        @Override public int getIconWidth() { return 9 + 18 + 4; }
        @Override public int getIconHeight() { return 18; }
        @Override public void paintIcon(Component c, Graphics g, int x, int y) {
            cog.paintIcon(c, g, x + 9, y);
        }
    }
}