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.

123 KB
Raw Blame
package opensuite.ui;

import opensuite.core.*;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The shared request/response viewer and editor: a
 * Pretty (syntax-highlighted) / Raw / Hex (+ Render) tab set, an Inspector panel
 * docked on the right with collapsible parameter and header sections, and a
 * search bar along the bottom.
 *
 * <p>Views are gated by a bitmask: 1 for requests, 2 for responses. Pretty is a
 * coloured, byte-exact view of the same bytes as Raw (no reformatting), so edits
 * in either map one-to-one onto the message.
 */
public class MessageEditor extends JPanel {

    public static final int REQUEST  = 1;
    public static final int RESPONSE = 2;

    public interface ActionProvider { void contribute(JPopupMenu menu); }

    // Above this many characters, the message is shown without syntax
    // colouring or HTML rendering: both walk the whole body on the event
    // thread, so a multi-megabyte response (common with mobile traffic) would
    // freeze the interface. The plain, byte-exact text is still shown.
    private static final int MAX_DECORATE_CHARS = 512 * 1024;

    /**
     * A read-only Pretty view breaks lines longer than this into display lines.
     * One minified line of hundreds of kilobytes would otherwise make Swing
     * measure the paragraph quadratically and freeze the window.
     */
    private static final int MAX_DISPLAY_LINE_CHARS = 8 * 1024;

    /** A response editor at least this wide opens with its Inspector docked, as in the reference. */
    private static final int INSPECTOR_AUTO_OPEN_WIDTH = 820;

    // Syntax colours for request and response highlighting.
    // Syntax colours, measured from the reference: header names navy, parameter
    // and attribute names blue with their values dark red, tag names magenta,
    // declarations, comments and JSON strings green. The start line is plain.
    private static final Color C_HEADER_NAME = Theme.CODE_NAME;
    private static final Color C_STRING      = Theme.CODE_STRING;
    private static final Color C_NUMBER      = Theme.CODE_NUMBER;
    private static final Color C_TAG         = Theme.CODE_TAG;
    private static final Color C_PARAM       = Theme.CODE_PARAM;
    private static final Color C_VALUE       = Theme.CODE_VALUE;
    private static final Color C_COMMENT     = Theme.CODE_COMMENT;

    private final JLabel titleLabel = new JLabel();
    private final JPanel titleBar = new JPanel(new BorderLayout());

    /** Hide the Request/Response heading, for a host that draws its own. */
    public void setTitleVisible(boolean visible) { titleBar.setVisible(visible); }

    /** Put a control (a layout switch, say) at the right end of the heading row. */
    public void setTitleTrailing(JComponent c) { titleBar.add(c, BorderLayout.EAST); titleBar.revalidate(); }

    private final int flags;
    private final boolean editable;
    private SuiteContext ctx;   // not final: a viewer built before its tool's init() is given the context after

    /** Supply the context to a viewer that was built before one was available, so its menu works. */
    public void setContext(SuiteContext ctx) { this.ctx = ctx; }

    private HttpMessage message = new HttpMessage(new byte[0]);
    private HttpService service;
    private HttpMessage relatedRequest;

    /**
     * Width held clear at the right of the tab row for the toolbar marks that
     * share that line. The tab row is narrowed by an empty border and the
     * content area is widened back by the same amount, so the pages still fill
     * the editor while the tabs stop short of the marks.
     */
    private int tabRowReserve;

    /**
     * Narrows the tab row by {@code reserve} and widens the content area back
     * by the same amount, so the pages still fill the editor while the tabs
     * stop short of the marks that share their line. The reserve is adjusted in
     * place rather than by reinstalling the UI: replacing a pane's UI during
     * layout churns listeners and is what the resize handler used to do.
     */
    private static final class ReserveTabUI extends opensuite.ui.theme.FlatTabbedPaneUI {
        private int reserve;

        @Override protected void installDefaults() {
            super.installDefaults();
            // The editor is a white surface; its view tabs sit on it directly.
            tabPane.setBackground(Theme.CONTENT);
            tabInsets = new java.awt.Insets(8, 14, 7, 13);
            apply();
        }

        @Override protected boolean fillsSelectedTab() { return false; }
        @Override protected int labelInset() { return 15; }

        void setReserve(int r) {
            if (r == reserve) return;
            reserve = r;
            apply();
            if (tabPane != null) { tabPane.revalidate(); tabPane.repaint(); }
        }

        private void apply() {
            if (contentBorderInsets == null) return;
            contentBorderInsets = new java.awt.Insets(contentBorderInsets.top, contentBorderInsets.left,
                    contentBorderInsets.bottom, -reserve);
        }
    }

    private final JTabbedPane views = new JTabbedPane() {
        @Override public void updateUI() { setUI(new ReserveTabUI()); }
    };
    /** Whether the views wrap long lines; driven by the toolbar's wrap toggle. */
    private boolean wrapLines = true;

    /**
     * The pretty pane wraps only when the toggle says so.
     *
     * <p>This used to decide for itself by asking the UI for its preferred
     * width, but Swing calls getScrollableTracksViewportWidth during layout, so
     * that query ran inside the very layout it was trying to measure. The
     * answer flipped mid-pass and the pane drew a long line's rows on top of
     * one another. A plain flag cannot do that.
     */
    private final JTextPane prettyPane = new JTextPane() {
        @Override public boolean getScrollableTracksViewportWidth() { return wrapLines; }
    };

    /**
     * An editor kit whose text may be broken anywhere, not only between words.
     *
     * <p>A response body is frequently one enormous unbreakable run: a base64
     * blob, a JWT, a minified JSON line. A plain styled pane can only break at
     * a space, so such a line cannot be folded at all; it overflows the pane
     * and is clipped, and because the pane still reports that it fits the
     * viewport no scroll bar appears to reach the rest. Reporting a minimum
     * width of zero lets the line fold mid-token instead, which is what the
     * reference does.
     */
    private static final class CharWrapKit extends javax.swing.text.StyledEditorKit {
        private final javax.swing.text.ViewFactory factory = elem -> {
            String kind = elem.getName();
            if (kind != null) {
                switch (kind) {
                    case javax.swing.text.AbstractDocument.ContentElementName:
                        return new javax.swing.text.LabelView(elem) {
                            @Override public float getMinimumSpan(int axis) {
                                return axis == javax.swing.text.View.X_AXIS ? 0 : super.getMinimumSpan(axis);
                            }
                        };
                    case javax.swing.text.AbstractDocument.ParagraphElementName:
                        return new javax.swing.text.ParagraphView(elem);
                    case javax.swing.text.AbstractDocument.SectionElementName:
                        return new javax.swing.text.BoxView(elem, javax.swing.text.View.Y_AXIS);
                    case javax.swing.text.StyleConstants.ComponentElementName:
                        return new javax.swing.text.ComponentView(elem);
                    case javax.swing.text.StyleConstants.IconElementName:
                        return new javax.swing.text.IconView(elem);
                    default:
                        break;
                }
            }
            return new javax.swing.text.LabelView(elem);
        };
        @Override public javax.swing.text.ViewFactory getViewFactory() { return factory; }
    }
    private final JTextArea rawArea = new JTextArea();
    private final HexView hexView;
    private final JEditorPane renderPane = new JEditorPane();

    private final JTextField searchField = Ui.field("");
    private final JLabel matchLabel = Ui.label("0 highlights");
    private final JLabel selectionLabel = Ui.label("");

    private final Inspector inspector;
    private final JPanel flyout = new JPanel(new BorderLayout());
    private final JTextArea notesArea = new JTextArea();
    private VerticalTab inspectorBtn, notesBtn, actionsBtn;
    private final CustomActionsPanel customActions = new CustomActionsPanel(this);

    private final List<ActionProvider> providers = new ArrayList<>();
    private boolean updating;
    private Runnable changeListener;
    // A line above the views for something the bytes alone would not say, such
    // as a response whose body was not kept in the project.
    private final JLabel noteLabel = new JLabel();

    public MessageEditor(SuiteContext ctx, int flags, boolean editable) {
        super(new BorderLayout());
        this.ctx = ctx;
        this.flags = flags;
        this.editable = editable;
        this.hexView = new HexView(editable);
        this.inspector = new Inspector();

        // Installed before any text is set: swapping the kit resets the document.
        prettyPane.setEditorKit(new CharWrapKit());
        prettyPane.setFont(Ui.MONO);
        prettyPane.setEditable(editable);
        prettyPane.setBackground(Theme.CONTENT);   // white, like the reference request/response editors
        prettyPane.setMargin(new Insets(2, 5, 2, 4));
        rawArea.setMargin(new Insets(2, 5, 2, 4));

        rawArea.setFont(Ui.MONO);
        rawArea.setEditable(editable);
        rawArea.setLineWrap(true);
        rawArea.setWrapStyleWord(false);
        rawArea.setTabSize(4);
        rawArea.setBackground(Theme.CONTENT);

        renderPane.setEditable(false);
        renderPane.setBackground(Theme.CONTENT);
        renderPane.setEditorKit(Theme.htmlKit());   // page colours from the theme, not black on white

        views.setFont(Ui.PLAIN);
        // Never wrap onto a second row: the toolbar marks share the tab line, so
        // a narrow editor scrolls its tabs rather than stacking them.
        views.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        // No box around the text: the editor's own hairlines frame it.
        JScrollPane prettyScroll = Ui.scroll(prettyPane);
        prettyScroll.setBorder(null);
        prettyGutter = new LineGutter(prettyPane);
        prettyScroll.setRowHeaderView(prettyGutter);
        JScrollPane rawScroll = Ui.scroll(rawArea);
        rawScroll.setBorder(null);
        rawScroll.setRowHeaderView(new LineGutter(rawArea));
        prettyView = prettyScroll;
        rawView = rawScroll;
        renderView = Ui.scroll(renderPane);
        applyViewSettings();
        // Hotkeys reach the context menu's items from wherever in the editor the focus is.
        java.util.function.Supplier<JPopupMenu> menuForHotkeys = this::buildMenu;
        putClientProperty(Hotkeys.MENU, menuForHotkeys);
        views.addChangeListener(e -> { if (!rebuildingViews) onViewChanged(); });
        watchSettings(this);

        noteLabel.setFont(Ui.PLAIN);
        noteLabel.setForeground(Theme.MUTED);
        noteLabel.setBorder(Ui.pad(3, 8, 3, 8));
        noteLabel.setVisible(false);
        // The icons sit on the tab row's right end, like the reference, so the
        // tabs and the icons share one line.
        final JComponent icons = buildToolbar();
        final JLayeredPane layer = new JLayeredPane();
        layer.setLayout(null);
        layer.add(views, JLayeredPane.DEFAULT_LAYER);
        layer.add(icons, JLayeredPane.PALETTE_LAYER);
        layer.addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override public void componentResized(java.awt.event.ComponentEvent e) {
                int w = layer.getWidth(), h = layer.getHeight();
                views.setBounds(0, 0, w, h);
                views.doLayout();
                Dimension d = icons.getPreferredSize();
                int reserve = d.width + 8;
                if (reserve != tabRowReserve) {
                    tabRowReserve = reserve;
                    views.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, reserve));
                    if (views.getUI() instanceof ReserveTabUI u) u.setReserve(reserve);
                    views.setBounds(0, 0, w, h);
                    views.doLayout();
                }
                int rowH = views.getTabCount() > 0 ? views.getUI().getTabBounds(views, 0).height : d.height;
                icons.setBounds(w - d.width - 4, Math.max(0, (rowH - 3 - d.height) / 2 + 1), d.width, d.height);
            }
        });
        // The pane's heading, as the reference has above every message view.
        titleLabel.setText((flags & RESPONSE) != 0 && (flags & REQUEST) == 0 ? "Response" : "Request");
        titleLabel.setFont(Ui.HEADING);
        titleBar.setOpaque(true);
        titleBar.setBackground(Theme.CONTENT);
        titleBar.setBorder(Ui.pad(0, 15, 2, 10));
        // At the usual 13px the names on the tabs under the heading stand 1px higher in their row.
        if (Ui.fontGrowth() > 0) views.putClientProperty(opensuite.ui.theme.FlatTabbedPaneUI.LABEL_SHIFT, -1);
        titleBar.add(titleLabel, BorderLayout.WEST);
        // One fixed height, so a request and a response heading line up even
        // when one of them carries a control.
        titleBar.setPreferredSize(new Dimension(10, Ui.roomy(40)));
        JPanel top = new JPanel(new BorderLayout());
        top.setBackground(Theme.CONTENT);
        top.add(titleBar, BorderLayout.NORTH);
        top.add(noteLabel, BorderLayout.SOUTH);
        JComponent editorSide = new JPanel(new BorderLayout());
        editorSide.add(top, BorderLayout.NORTH);
        editorSide.add(layer, BorderLayout.CENTER);
        CurrentLine.install(prettyPane);
        CurrentLine.install(rawArea);

        // The search bar belongs to the message column; the side dock, where
        // there is one, runs the full height beside both.
        JPanel column = new JPanel(new BorderLayout());
        column.add(editorSide, BorderLayout.CENTER);
        footer = buildFooter();
        viewLayer = layer;
        column.setBackground(Theme.CONTENT);
        editorSide.setBackground(Theme.CONTENT);
        column.add(footer, BorderLayout.SOUTH);
        add(column, BorderLayout.CENTER);
        // One Inspector per request/response pair, on the far-right (response)
        // editor. Request-only editors (the left pane) show no strip.
        if ((flags & RESPONSE) != 0) { dock = buildRightDock(); add(dock, BorderLayout.EAST); placeDock(); }

        DocumentListener edit = new DocumentListener() {
            public void insertUpdate(DocumentEvent e)  { onEdit(); }
            public void removeUpdate(DocumentEvent e)  { onEdit(); }
            // changedUpdate fires for attribute (colour) changes; ignore it so
            // re-highlighting does not recurse or mutate during a notification.
            public void changedUpdate(DocumentEvent e) {}
        };
        prettyPane.getDocument().addDocumentListener(edit);
        rawArea.getDocument().addDocumentListener(edit);
        rawArea.addCaretListener(e -> updateSelectionLabel());
        prettyPane.addCaretListener(e -> updateSelectionLabel());

        installPopup(prettyPane);
        installPopup(rawArea);
        installEncodeAsYouType(prettyPane);
        installEncodeAsYouType(rawArea);

        // Editor shortcuts the reference provides: undo/redo and delete-line.
        EditorKeys.install(rawArea);
        EditorKeys.install(prettyPane);
    }

    /** An icon centred in a box of a fixed size, so the rows under it sit where the layout expects. */
    private static Icon boxed(Icon icon, int w, int h) {
        return new Icon() {
            @Override public int getIconWidth() { return w; }
            @Override public int getIconHeight() { return h; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                icon.paintIcon(c, g, x + (w - icon.getIconWidth()) / 2, y + (h - icon.getIconHeight()) / 2);
            }
        };
    }

    private JComponent dock;
    private JComponent footer, viewLayer;
    private boolean hideWhenEmpty;
    private MessageEditor paired;
    private final List<Runnable> messageListeners = new ArrayList<>();

    /**
     * Show only the heading while there is no message: no view tabs and no
     * search bar. Repeater's response pane is like this until a response arrives.
     */
    public void setHideWhenEmpty(boolean on) { hideWhenEmpty = on; applyHideWhenEmpty(); }

    private void applyHideWhenEmpty() {
        boolean show = !hideWhenEmpty || message.raw().length > 0;
        if (viewLayer != null && viewLayer.isVisible() != show) {
            viewLayer.setVisible(show);
            footer.setVisible(show);
            revalidate();
            repaint();
        }
    }

    /**
     * Name the request editor shown beside this response editor, so the one
     * Inspector describes the request as it is being edited, before any
     * response exists.
     */
    public void pairWith(MessageEditor request) {
        paired = request;
        request.messageListeners.add(inspector::rebuild);
        inspector.rebuild();
    }

    /**
     * Hand the side dock (Inspector, Notes) to a host that shows this editor
     * beside its request, so the dock stands at the right of the pair rather
     * than inside the response's half. Null when this editor has no dock.
     */
    public JComponent detachDock() {
        if (dock == null) return null;
        remove(dock);
        dockDetached = true;
        revalidate();
        return dock;
    }
    private boolean dockDetached;

    /**
     * Offer the Inspector alone beside this editor, with no Notes. With one
     * panel there is nothing to switch between, so the strip of tabs stands
     * only while the panel is closed, to open it again.
     */
    public void setInspectorOnly() {
        inspectorOnly = true;
        if (notesBtn != null) notesBtn.setVisible(false);
        if (stripWrap != null && flyout != null) stripWrap.setVisible(!flyout.isVisible());
    }
    private boolean inspectorOnly;

    /** Custom actions are offered only where a message can be sent (Repeater). */
    public void setCustomActionsVisible(boolean visible) {
        if (actionsBtn != null) actionsBtn.setVisible(visible);
    }

    private JToggleButton wrapToggle;
    private boolean showNewlines;

    /**
     * The view marks at the right end of the tab row: hide non-printing
     * characters, word wrap (a filled blue square while on), show line endings
     * and the actions menu. Each sits in its own fixed cell so the four keep
     * the reference's spacing whatever their glyphs measure.
     */
    private JComponent buildToolbar() {
        JPanel bar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        bar.setOpaque(false);
        JButton hide = cell(boxed(eyeOffIcon()), 28, "Hide headers", () -> {
            java.awt.Window w = SwingUtilities.getWindowAncestor(this);
            SettingsDialog.open(w, ctx, "User interface > Message editor");
        });
        wrapToggle = new JToggleButton((Icon) null, true) {
            @Override protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                int box = 18 + Ui.fontGrowth();
                int x = (getWidth() - box) / 2, y = (getHeight() - box) / 2;
                if (isSelected()) {
                    g2.setColor(Theme.CONTROL);
                    g2.fillRoundRect(x, y, box, box, 7, 7);
                }
                Icon mark = Glyphs.scaled(Glyphs.wrap(14, isSelected() ? Color.WHITE : Theme.TEXT));
                mark.paintIcon(this, g2, x + (box - mark.getIconWidth()) / 2, y + (box - mark.getIconHeight()) / 2);
                g2.dispose();
            }
        };
        wrapToggle.setPreferredSize(new Dimension(28 + Ui.fontGrowth(), Ui.tall(22)));
        wrapToggle.setToolTipText("Word wrap");
        wrapToggle.setFocusable(false);
        wrapToggle.setBorder(BorderFactory.createEmptyBorder());
        wrapToggle.setContentAreaFilled(false);
        wrapToggle.setOpaque(false);
        wrapToggle.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        wrapToggle.addActionListener(e -> {
            boolean on = wrapToggle.isSelected();
            wrapLines = on;
            rawArea.setLineWrap(on);
            prettyPane.revalidate();
            prettyPane.repaint();
        });
        rawArea.setLineWrap(true);
        rawArea.setWrapStyleWord(false);
        JButton nl = cell(boxed(textGlyph("\\n", false, false)), 28, "Show line endings", () -> { showNewlines = !showNewlines; refreshViews(); });
        JButton menu = cell(Glyphs.hamburger(14, Theme.TEXT), 26, "Actions", null);
        menu.addActionListener(e -> buildMenu().show(menu, 0, menu.getHeight()));
        bar.add(hide);
        bar.add(wrapToggle);
        bar.add(nl);
        bar.add(menu);
        return bar;
    }

    /** A borderless icon button of a fixed width, so a row of them keeps an even pitch. */
    private static JButton cell(Icon icon, int width, String tip, Runnable action) {
        JButton b = Glyphs.button(icon, tip, action);
        b.setBorder(BorderFactory.createEmptyBorder());
        b.setPreferredSize(new Dimension(width + Ui.fontGrowth(), Ui.tall(22)));
        return b;
    }

    /**
     * The reference stands these two marks in a box of the editor's own colour
     * with rounded corners: all that shows of it is the page colour at its
     * four corners. Drawn the same, 17 by 18 about the mark's centre.
     */
    private static Icon boxed(Icon icon) {
        return new Icon() {
            @Override public int getIconWidth() { return icon.getIconWidth(); }
            @Override public int getIconHeight() { return icon.getIconHeight(); }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                int left = x + icon.getIconWidth() / 2 - 8, top = y + icon.getIconHeight() / 2 - 9;
                g.setColor(Theme.BG);
                for (int dx : new int[]{ 0, 16 }) for (int dy : new int[]{ 0, 17 }) g.fillRect(left + dx, top + dy, 1, 1);
                icon.paintIcon(c, g, x, y);
            }
        };
    }

    /** A thin eye with a stroke through it. */
    private static Icon eyeOffIcon() {
        java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(16, 16, java.awt.image.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);
        g.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        java.awt.geom.Path2D eye = new java.awt.geom.Path2D.Double();
        eye.moveTo(1.5, 8); eye.quadTo(8, 1, 14.5, 8); eye.quadTo(8, 15, 1.5, 8); eye.closePath();
        g.draw(eye);
        g.draw(new java.awt.geom.Ellipse2D.Double(6, 6, 4, 4));
        g.draw(new java.awt.geom.Line2D.Double(2.5, 2.5, 13.5, 13.5));
        g.dispose();
        return new ImageIcon(img);
    }

    /** The right edge: a vertical Inspector / Notes strip whose buttons flyout a panel. */
    private boolean inspectorDecided;

    /** Dock the Inspector open once, the first time this editor is shown at a real width. */
    private void autoOpenInspector() {
        // Early layout passes report a tiny width; wait for a real one.
        if (inspectorDecided || !isShowing() || getWidth() < 300) return;
        inspectorDecided = true;
        // Settings > Side panel can keep it collapsed until it is asked for.
        if (settings() != null && "collapsed".equals(settings().get("sidepanel.mode", "auto"))) return;
        // Beside a pair the dock has the whole pair's width to draw on.
        int room = dockDetached && dock != null && dock.getParent() != null ? dock.getParent().getWidth() : getWidth();
        if (room >= (dockDetached ? 900 : INSPECTOR_AUTO_OPEN_WIDTH) && !inspectorBtn.isSelected()
                && !notesBtn.isSelected() && !actionsBtn.isSelected()) {
            inspectorBtn.setSelected(true);
            show("Inspector", inspector);
        }
    }

    private JComponent buildRightDock() {
        flyout.setVisible(false);
        flyout.setPreferredSize(new Dimension(314 + 15 * Ui.fontGrowth(), 10));   // 344 at 13px, as measured
        notesArea.setFont(Ui.MONO);

        inspectorBtn = new VerticalTab("Inspector", VerticalTab.inspectorMark());
        notesBtn = new VerticalTab("Notes", VerticalTab.notesMark());
        actionsBtn = new VerticalTab("Custom actions", VerticalTab.actionsMark());
        actionsBtn.setVisible(false);
        inspectorBtn.addActionListener(e -> {
            if (inspectorBtn.isSelected()) { notesBtn.setSelected(false); actionsBtn.setSelected(false); show("Inspector", inspector); }
            else hideFlyout();
        });
        notesBtn.addActionListener(e -> {
            if (notesBtn.isSelected()) { inspectorBtn.setSelected(false); actionsBtn.setSelected(false); show("Notes", notesPanel()); }
            else hideFlyout();
        });
        actionsBtn.addActionListener(e -> {
            if (actionsBtn.isSelected()) { inspectorBtn.setSelected(false); notesBtn.setSelected(false); show("Custom actions", customActions); }
            else hideFlyout();
        });

        JPanel strip = new JPanel();
        strip.setLayout(new BoxLayout(strip, BoxLayout.Y_AXIS));
        strip.setBackground(Theme.BG);
        strip.add(inspectorBtn);
        strip.add(notesBtn);
        strip.add(actionsBtn);
        stripWrap = new JPanel(new BorderLayout());
        stripWrap.setBackground(Theme.BG);
        stripWrap.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Theme.BORDER));
        stripWrap.add(strip, BorderLayout.NORTH);
        JButton stripGear = Glyphs.button(Glyphs.gear(18, Theme.TEXT), "Side panel settings", () -> {
            java.awt.Window w = SwingUtilities.getWindowAncestor(this);
            SettingsDialog.open(w, ctx, "User interface > Side panel");
        });
        stripGear.setBorder(BorderFactory.createEmptyBorder());
        JPanel gearWrap = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        gearWrap.setOpaque(false);
        gearWrap.setBorder(Ui.pad(0, 0, 14, 0));
        gearWrap.add(stripGear);
        stripWrap.add(gearWrap, BorderLayout.SOUTH);

        JPanel dock = new JPanel(new BorderLayout());
        dock.add(flyout, BorderLayout.CENTER);
        dock.add(stripWrap, BorderLayout.EAST);

        // The reference opens the Inspector docked beside the response. Do the
        // same the first time this editor is laid out, but only where there is
        // room for it: in a narrow pane it would leave no space for the message.
        addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override public void componentResized(java.awt.event.ComponentEvent e) { autoOpenInspector(); }
        });
        addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0 && isShowing()) {
                SwingUtilities.invokeLater(this::autoOpenInspector);
            }
        });
        return dock;
    }

    private void show(String title, JComponent content) {
        flyout.removeAll();
        flyout.setBackground(Theme.BG);
        boolean onLeft = BorderLayout.WEST.equals(dockSide());
        flyout.setBorder(BorderFactory.createMatteBorder(0, onLeft ? 0 : 1, 0, onLeft ? 1 : 0, Theme.BORDER));
        JPanel head = new JPanel(new BorderLayout());
        head.setBackground(Theme.BG);
        head.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(0, 10, 0, 4)));
        head.setPreferredSize(new Dimension(10, Ui.roomy(39)));
        JLabel titleLabel = Ui.heading(title);
        head.add(titleLabel, BorderLayout.WEST);
        JButton close = headMark(Glyphs.cross(16, Theme.TEXT), "Close this panel", null);
        close.addActionListener(e -> { inspectorBtn.setSelected(false); notesBtn.setSelected(false); actionsBtn.setSelected(false); hideFlyout(); });
        JPanel headRight = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        headRight.setOpaque(false);
        // The pair of marks moves the panel to the left or the right of the message.
        JComponent width = LayoutIcons.createDockSide(onLeft ? 0 : 1, i -> {
            sideChosen = i == 0 ? BorderLayout.WEST : BorderLayout.EAST;
            placeDock();
        });
        headRight.add(width);
        headRight.add(Box.createHorizontalStrut(6));
        if (content == inspector) {
            headRight.add(headMark(spreadIcon(true), "Expand all sections", () -> inspector.expandAll(true)));
            headRight.add(headMark(spreadIcon(false), "Collapse all sections", () -> inspector.expandAll(false)));
        }
        headRight.add(close);
        JPanel rightWrap = new JPanel(new GridBagLayout());
        rightWrap.setOpaque(false);
        rightWrap.add(headRight);
        head.add(rightWrap, BorderLayout.EAST);
        flyout.add(head, BorderLayout.NORTH);
        flyout.add(content, BorderLayout.CENTER);
        flyout.setVisible(true);
        if (inspectorOnly && stripWrap != null) stripWrap.setVisible(false);
        if (content == inspector) inspector.rebuild();
        revalidate();
        if (dock != null) dock.revalidate();
        repaint();
    }

    /** A 27px-wide mark on a side panel's heading line. */
    private static JButton headMark(Icon icon, String tip, Runnable action) {
        JButton b = Glyphs.button(icon, tip, action);
        b.setBorder(BorderFactory.createEmptyBorder());
        b.setPreferredSize(new Dimension(27 + Ui.fontGrowth(), Ui.tall(22)));
        return b;
    }

    /** Two arrows either side of a rule: pointing apart to expand all, together to collapse all. */
    private static Icon spreadIcon(boolean apart) {
        java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(16, 16, java.awt.image.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);
        g.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        if (apart) {
            g.draw(new java.awt.geom.Line2D.Double(2, 1.5, 14, 1.5));
            g.draw(new java.awt.geom.Line2D.Double(2, 14.5, 14, 14.5));
            java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
            p.moveTo(5.5, 6.5); p.lineTo(8, 4); p.lineTo(10.5, 6.5);
            p.moveTo(5.5, 9.5); p.lineTo(8, 12); p.lineTo(10.5, 9.5);
            g.draw(p);
        } else {
            g.draw(new java.awt.geom.Line2D.Double(2, 8, 14, 8));
            java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
            p.moveTo(5.5, 1.5); p.lineTo(8, 4.5); p.lineTo(10.5, 1.5);
            p.moveTo(5.5, 14.5); p.lineTo(8, 11.5); p.lineTo(10.5, 14.5);
            g.draw(p);
        }
        g.dispose();
        return new ImageIcon(img);
    }

    /** The Notes flyout: a plain place to write, with nothing above it, as in the reference. */
    private JComponent notesPanel() {
        JPanel p = new JPanel(new BorderLayout());
        p.setOpaque(false);
        p.add(Ui.scroll(notesArea), BorderLayout.CENTER);
        return p;
    }

    private static Icon textGlyph(String text, boolean bold, boolean italic) {
        java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(18, 18, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        opensuite.ui.Theme.textSmoothing(g);
        g.setFont(new Font("Dialog", (bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0), 12));
        g.setColor(Theme.TEXT);
        FontMetrics fm = g.getFontMetrics();
        g.drawString(text, (18 - fm.stringWidth(text)) / 2f, 9 + (fm.getAscent() - fm.getDescent()) / 2f);
        if ("S".equals(text)) g.drawLine(3, 9, 15, 9);
        g.dispose();
        return new ImageIcon(img);
    }

    /**
     * The bar under an editor: help, settings, two bordered step buttons, a
     * search field with its magnifier, then one or more counts parted by
     * vertical rules. 45px under a hairline, and 47px at the usual 13px, where
     * the marks stand a little wider and the step buttons are 25px. Shared so that every editor in the
     * suite, Intruder's included, carries the same one.
     */
    public static JPanel searchBar(JTextField field, Runnable onHelp, java.util.function.Consumer<JButton> onSettings,
                                   Runnable onPrev, Runnable onNext, JComponent... counts) {
        JPanel p = new JPanel(new BorderLayout(10, 0));
        p.setBackground(Theme.CONTENT);
        final boolean usual = Ui.fontGrowth() > 0;
        p.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Theme.BORDER), Ui.pad(0, usual ? 3 : 2, 0, 0)));
        p.setPreferredSize(new Dimension(10, usual ? 48 : 46));
        JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        left.setOpaque(false);
        JButton help = footMark(Glyphs.help(usual ? 21 : 20, Theme.TEXT), "Help", onHelp);
        JButton gear = footMark(Glyphs.gear(20, Theme.TEXT), "Settings", null);
        if (usual) {
            help.setPreferredSize(new Dimension(29, 23));
            gear.setPreferredSize(new Dimension(28, 23));
        }
        gear.addActionListener(e -> onSettings.accept(gear));
        left.add(help);
        left.add(gear);
        left.add(Box.createHorizontalStrut(3));
        left.add(stepButton(3, "Previous match", onPrev));
        left.add(Box.createHorizontalStrut(5));
        left.add(stepButton(0, "Next match", onNext));
        p.add(vcentre(left), BorderLayout.WEST);
        field.setColumns(0);
        field.putClientProperty("JTextField.placeholderText", "Search");
        field.setBorder(new opensuite.ui.theme.RoundedBorder(new Color(0xC9, 0xC9, 0xC9), Theme.CONTROL, Theme.RADIUS * 2, new Insets(3, 8, 3, 26)) {
            @Override public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
                super.paintBorder(c, g, x, y, w, h);
                Glyphs.searchLeft(14, Theme.TEXT).paintIcon(c, g, x + w - 21, y + (h - 14) / 2);
            }
        });
        field.setBackground(Theme.BG);
        p.add(vcentre(field), BorderLayout.CENTER);
        JPanel right = new JPanel();
        right.setLayout(new BoxLayout(right, BoxLayout.X_AXIS));
        right.setOpaque(false);
        right.add(Box.createHorizontalStrut(12));
        for (int i = 0; i < counts.length; i++) {
            if (i > 0) {
                right.add(Box.createHorizontalStrut(i == 1 ? 7 : 10));
                JComponent rule = new JComponent() {
                    @Override protected void paintComponent(Graphics g) { g.setColor(Theme.BORDER); g.fillRect(0, 0, 1, getHeight()); }
                };
                rule.setPreferredSize(new Dimension(1, 10));
                rule.setMaximumSize(new Dimension(1, Short.MAX_VALUE));
                right.add(rule);
                right.add(Box.createHorizontalStrut(10));
            }
            counts[i].setForeground(Theme.TEXT);
            for (Component k : counts[i].getComponents()) if (k instanceof JLabel l && l.getForeground() != Theme.MUTED) l.setForeground(Theme.TEXT);
            right.add(counts[i] instanceof JLabel ? counts[i] : vcentre(counts[i]));
        }
        right.add(Box.createHorizontalStrut(counts.length > 1 ? 10 : 12));
        p.add(right, BorderLayout.EAST);
        return p;
    }

    /** A 26px-wide borderless mark on the search bar. */
    private static JButton footMark(Icon icon, String tip, Runnable action) {
        JButton b = Glyphs.button(icon, tip, action);
        b.setBorder(BorderFactory.createEmptyBorder());
        b.setPreferredSize(new Dimension(Ui.fontGrowth() > 0 ? 27 : 26, 23));
        return b;
    }

    /** A 23px bordered button carrying a thin arrow: the search bar's previous and next. */
    private static JButton stepButton(int dir, String tip, Runnable action) {
        boolean usual = Ui.fontGrowth() > 0;
        JButton b = new JButton(Glyphs.arrow(usual ? 18 : 15, Theme.TEXT, dir));
        b.setToolTipText(Ui.tip(tip));
        b.setFocusable(false);
        b.setBorder(BorderFactory.createEmptyBorder());
        b.setPreferredSize(new Dimension(usual ? 25 : 23, usual ? 25 : 23));
        b.addActionListener(e -> action.run());
        return b;
    }

    /** Hold a component at its own height, centred in a taller row; it keeps the row's width. */
    private static JComponent vcentre(JComponent c) {
        JPanel p = new JPanel(new GridBagLayout());
        p.setOpaque(false);
        GridBagConstraints gc = new GridBagConstraints();
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.weightx = 1;
        p.add(c, gc);
        return p;
    }

    private void hideFlyout() {
        flyout.setVisible(false);
        if (stripWrap != null) stripWrap.setVisible(true);
        revalidate();
        repaint();
    }

    /** A vertical (rotated) tab button for the Inspector/Notes strip. */
    private JPanel buildFooter() {
        matchLabel.setText("0 highlights");
        selectionLabel.setForeground(Theme.MUTED);
        JPanel counts = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        counts.setOpaque(false);
        counts.add(selectionLabel);
        counts.add(matchLabel);
        JPanel p = searchBar(searchField,
                () -> JOptionPane.showMessageDialog(this,
                        "Pretty, Raw and Hex are views of the same message; edits can be made in any of them.\nSearch applies to the current view. Use the arrows to step through matches.",
                        "Message editor", JOptionPane.INFORMATION_MESSAGE),
                this::showSearchOptions,
                () -> highlightMatches(-1), () -> highlightMatches(1), counts);
        searchField.setToolTipText("search this message");
        installHoverDecode(prettyPane);
        installHoverDecode(rawArea);

        searchField.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e)  { highlightMatches(0); }
            public void removeUpdate(DocumentEvent e)  { highlightMatches(0); }
            public void changedUpdate(DocumentEvent e) { highlightMatches(0); }
        });
        return p;
    }

    /**
     * The search options, opened by the cog beside the search box: three tick
     * boxes in a small panel above it, as in the reference. They are the same
     * settings Settings > User interface > Message editor holds, so a change
     * here is kept and reaches every editor.
     */
    private void showSearchOptions(JButton from) {
        JPopupMenu menu = new JPopupMenu();
        JPanel box = new JPanel();
        box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
        box.setBackground(Theme.CONTENT);
        box.setBorder(Ui.pad(4, 6, 4, 10));
        String[][] options = {
                {"editor.search.caseSensitive", "Case sensitive"},
                {"editor.search.regex", "Regex"},
                {"editor.search.autoScroll", "Auto-scroll to match when text changes"}};
        for (String[] o : options) {
            JCheckBox tick = Ui.check(o[1], ctx != null && ctx.settings().getBool(o[0], false));
            tick.setOpaque(false);
            tick.setEnabled(ctx != null);
            tick.addActionListener(e -> {
                ctx.settings().setBool(o[0], tick.isSelected());
                highlightMatches(0);
            });
            box.add(tick);
        }
        menu.add(box);
        menu.show(from, 0, -menu.getPreferredSize().height);
    }

    // ---------------- content ----------------

    public void setMessage(HttpService svc, HttpMessage m) { setMessage(svc, m, null); }

    public void setMessage(HttpService svc, HttpMessage m, HttpMessage related) {
        this.service = svc;
        this.message = m == null ? new HttpMessage(new byte[0]) : m;
        this.relatedRequest = related;
        this.marks = List.of();   // marks belong to the message they were set on
        loadActiveFromMessage();
        refreshViews();
        SwingUtilities.invokeLater(this::scrollToFirstMatch);
    }

    /** Show a history entry's request: a copy of it, so edits never touch the record. */
    public void showRequest(LogEntry e) {
        setNote(null);
        setMessage(e.service(), e.request() == null ? new HttpMessage(new byte[0]) : e.request().copy());
    }

    /**
     * Show a history entry's response: a copy, with the entry's request as the
     * related message, and a note when the project holds less than the whole body.
     */
    public void showResponse(LogEntry e) {
        setMessage(e.service(), e.response() == null ? new HttpMessage(new byte[0]) : e.response().copy(), e.request());
        setNote(e.bodyNote());
    }

    /** A line shown above the views, or hidden when null. */
    public void setNote(String text) {
        noteLabel.setText(text == null ? "" : text);
        noteLabel.setVisible(text != null && !text.isEmpty());
        noteLabel.getParent().revalidate();
    }

    public HttpMessage message()  { return message; }
    public HttpService service()  { return service; }
    public byte[] bytes()         { return message.raw(); }

    /** The context this editor was given; null for a viewer not yet given one. */
    SuiteContext context() { return ctx; }

    /** The editor holding the request a custom action works on: the paired request editor, or this one. */
    MessageEditor requestSource() { return paired != null ? paired : this; }

    /**
     * Show {@code m} as one change that a single undo takes back. A text view
     * has its text replaced and the message takes {@code m}'s exact bytes;
     * any other view simply shows {@code m}.
     */
    void replaceMessageUndoably(HttpMessage m) {
        Component shown = views.getSelectedComponent();
        if (!editable || !(shown == prettyView || shown == rawView || shown == null)) { setMessage(service, m); return; }
        JTextComponent t = activeText();
        updating = true;
        try {
            EditorKeys.asOneEdit(t, () -> {
                t.setText(textOf(m));
                // Colouring is recorded by the undo history too; done here, it is part of the same step.
                if (t == prettyPane) applySyntax();
            });
        } finally {
            updating = false;
        }
        t.setCaretPosition(0);
        message = m.copy();
        messageChanged();
    }

    /**
     * The charset the message's text is shown in.
     *
     * <p>Bytes are held exactly as they arrived, so the default is ISO-8859-1,
     * where every byte is one character and anything round-trips untouched.
     * When a message declares a charset and its bytes really are valid in it,
     * that one is used instead: otherwise a UTF-8 body reads as mojibake, with
     * "sönmez" shown as "sönmez". A declared charset the bytes do not satisfy
     * is ignored rather than trusted, because decoding it would replace the bad
     * sequences and an edit would then write those replacements back.
     */
    private java.nio.charset.Charset charsetOf(HttpMessage m) {
        if (m == null) return java.nio.charset.StandardCharsets.ISO_8859_1;
        String declared = m.charsetName();
        if (declared == null || declared.isEmpty()) return java.nio.charset.StandardCharsets.ISO_8859_1;
        try {
            java.nio.charset.Charset cs = java.nio.charset.Charset.forName(declared);
            if (cs.equals(java.nio.charset.StandardCharsets.ISO_8859_1)) return cs;
            cs.newDecoder()
              .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
              .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
              .decode(java.nio.ByteBuffer.wrap(m.raw()));
            return cs;
        } catch (Exception notValidInThatCharset) {
            return java.nio.charset.StandardCharsets.ISO_8859_1;
        }
    }

    /** The message as text, in whatever charset it declares. */
    private String textOf(HttpMessage m) {
        return m == null ? "" : new String(m.raw(), charsetOf(m));
    }

    /**
     * The text the Pretty view shows. A read-only message has its body
     * pretty-printed when Settings > Message editor > Pretty print by default
     * is on; an editable one is always shown as it is, because its Pretty view
     * is edited and sent. A read-only view breaks extremely long lines for
     * display: the message bytes are untouched and Raw still shows them as they
     * are, while Swing no longer has to measure one enormous paragraph.
     */
    private String prettyTextOf(HttpMessage m) {
        String text = textOf(m);
        if (editable || m == null) return text;
        String shown = text;
        if (ctx == null || ctx.settings().getBool("editor.display.prettyByDefault", true)) {
            try { shown = PrettyPrint.message(text, m.contentType()); }
            catch (RuntimeException | StackOverflowError e) { shown = text; }   // formatting is decoration only
        }
        return PrettyPrint.wrapLongLines(shown, MAX_DISPLAY_LINE_CHARS);
    }

    /** The parts of the message a finding points at: marked in their own colour, apart from the search box. */
    private List<String> marks = List.of();
    private static final Color MARK = new Color(0xEC, 0x67, 0x3A, 120);

    /**
     * Mark the given pieces of text wherever they occur (a finding's evidence,
     * the payload that was sent) and bring the first into view. The search box
     * is left alone and its own matches are still shown in the search colour.
     */
    public void mark(String... terms) {
        List<String> keep = new ArrayList<>();
        if (terms != null) for (String t : terms) if (t != null && !t.isBlank() && !keep.contains(t)) keep.add(t);
        marks = keep;
        searchField.setText("");
        highlightMatches(0);
        JTextComponent a = activeText();
        List<int[]> found = markSpans(a);
        if (!found.isEmpty()) {
            final int pos = found.get(0)[0];
            SwingUtilities.invokeLater(() -> {
                try {
                    java.awt.geom.Rectangle2D r = a.modelToView2D(pos);
                    if (r != null) {
                        Rectangle view = r.getBounds();
                        view.y = Math.max(0, view.y - a.getVisibleRect().height / 3);
                        view.height = a.getVisibleRect().height;
                        a.scrollRectToVisible(view);
                    }
                } catch (BadLocationException | RuntimeException ignored) { }
            });
        }
    }

    /**
     * A pattern that finds a piece of text as it stands and also as the Pretty
     * view lays it out: white space may differ, and may appear between tags.
     */
    static java.util.regex.Pattern loose(String mark) {
        StringBuilder p = new StringBuilder();
        boolean gap = false;
        for (int i = 0; i < mark.length(); i++) {
            char c = mark.charAt(i);
            if (Character.isWhitespace(c)) { if (!gap) { p.append("\\s*"); gap = true; } continue; }
            if (c == '<' && !gap && i > 0) p.append("\\s*");
            p.append(java.util.regex.Pattern.quote(String.valueOf(c)));
            gap = false;
            if (c == '>' && i < mark.length() - 1) { p.append("\\s*"); gap = true; }
        }
        return java.util.regex.Pattern.compile(p.toString());
    }

    /** Where the marks fall in a view's text, in order. */
    private List<int[]> markSpans(JTextComponent a) {
        List<int[]> out = new ArrayList<>();
        if (marks.isEmpty()) return out;
        String text;
        try { text = a.getDocument().getText(0, a.getDocument().getLength()); }
        catch (BadLocationException e) { return out; }
        for (String t : marks) {
            if (t.length() > 4000) continue;
            try {
                java.util.regex.Matcher m = loose(t).matcher(text);
                int n = 0;
                while (m.find() && n++ < 200) if (m.end() > m.start()) out.add(new int[]{m.start(), m.end()});
            } catch (RuntimeException | StackOverflowError ignored) { }
        }
        out.sort(java.util.Comparator.comparingInt(x -> x[0]));
        return out;
    }

    private void paintMarks(JTextComponent a, Highlighter h) {
        for (int[] span : markSpans(a)) {
            try { h.addHighlight(span[0], span[1], new DefaultHighlighter.DefaultHighlightPainter(MARK)); }
            catch (BadLocationException ignored) { }
        }
    }

    public void highlight(String term) {
        searchField.setText(term == null ? "" : term);
        if (term == null || term.isEmpty()) return;
        int pos = activeText().getText().toLowerCase(Locale.ROOT).indexOf(term.toLowerCase(Locale.ROOT));
        if (pos >= 0) try { activeText().setCaretPosition(pos); } catch (RuntimeException ignored) {}
    }

    public void setChangeListener(Runnable r) { this.changeListener = r; }
    public void addActionProvider(ActionProvider p) { providers.add(p); }

    /** The currently active text editor (Pretty or Raw); defaults to Pretty. */
    private JTextComponent activeText() {
        return views.getSelectedComponent() == prettyScroll() ? prettyPane : rawArea;
    }

    private Component prettyScroll() { return prettyView; }

    private JScrollPane prettyView, rawView, renderView;
    private boolean rebuildingViews;
    private String viewSignature;
    private final java.util.Map<String, PartsView> partsViews = new java.util.HashMap<>();

    private Settings settings() { return ctx == null ? null : ctx.settings(); }

    /** The settings prefix of this editor's views: a response editor's or a request editor's. */
    private String viewPrefix() { return (flags & RESPONSE) != 0 ? "editor.response." : "editor.request."; }

    /**
     * Offer the views Settings > User interface > Message editor has ticked,
     * in its order. Raw is always among them.
     */
    private void applyViewSettings() {
        Settings st = settings();
        boolean response = (flags & RESPONSE) != 0;
        String[] all = response ? opensuite.ui.settings.InterfacePages.RESPONSE_VIEWS : opensuite.ui.settings.InterfacePages.REQUEST_VIEWS;
        List<String> order = st == null ? List.of(all) : opensuite.ui.settings.InterfacePages.ordered(st, viewPrefix() + "order", all);
        List<String> shown = new ArrayList<>();
        StringBuilder sig = new StringBuilder();
        for (String v : order) {
            boolean def = opensuite.ui.settings.InterfacePages.viewShownByDefault(v);
            boolean on = "Raw".equals(v) || (st == null ? def : st.getBool(opensuite.ui.settings.InterfacePages.viewKey(viewPrefix(), v, "show"), def));
            boolean wrap = st != null && st.getBool(opensuite.ui.settings.InterfacePages.viewKey(viewPrefix(), v, "wrap"), false);
            if (on) { shown.add(v); sig.append(v).append(wrap ? "+|" : "|"); }
        }
        if (sig.toString().equals(viewSignature)) return;
        viewSignature = sig.toString();
        String was = views.getSelectedIndex() >= 0 ? views.getTitleAt(views.getSelectedIndex()) : null;
        rebuildingViews = true;
        try {
            views.removeAll();
            for (String v : shown) {
                switch (v) {
                    case "Pretty" -> views.addTab(v, prettyView);
                    case "Raw" -> views.addTab(v, rawView);
                    case "Hex" -> views.addTab(v, hexView);
                    case "Render" -> views.addTab(v, renderView);
                    default -> {
                        PartsView pv = partsViews.computeIfAbsent(v, PartsView::new);
                        pv.setWrap(st != null && st.getBool(opensuite.ui.settings.InterfacePages.viewKey(viewPrefix(), v, "wrap"), false));
                        views.addTab(v, pv);
                    }
                }
            }
            int keep = was == null ? -1 : views.indexOfTab(was);
            if (views.getTabCount() > 0) views.setSelectedIndex(keep >= 0 ? keep : 0);
        } finally { rebuildingViews = false; }
        if (was != null) onViewChanged();
    }

    /** A message's headers, parameters, cookies or attributes as a table of names and values. */
    private final class PartsView extends JPanel {
        private final String kind;
        private final javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel(new Object[] { "Name", "Value" }, 0) {
            @Override public boolean isCellEditable(int r, int c) { return false; }
        };
        private final JTable table = new JTable(model);
        private boolean wrap;

        PartsView(String kind) {
            super(new BorderLayout());
            this.kind = kind;
            Ui.styleTable(table);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
            table.getColumnModel().getColumn(0).setPreferredWidth(220);
            table.getColumnModel().getColumn(1).setPreferredWidth(600);
            JScrollPane sp = Ui.scroll(table);
            sp.setBorder(null);
            add(sp, BorderLayout.CENTER);
            table.addComponentListener(new java.awt.event.ComponentAdapter() {
                @Override public void componentResized(java.awt.event.ComponentEvent e) { fitRows(); }
            });
        }

        void setWrap(boolean on) {
            wrap = on;
            table.getColumnModel().getColumn(1).setCellRenderer(on ? new WrapCell() : null);
            fitRows();
        }

        void fill(HttpMessage m) {
            model.setRowCount(0);
            if (m == null || m.raw().length == 0) return;
            List<String[]> rows = switch (kind) {
                case "Headers" -> inspector.headerRows(m);
                case "Query params" -> m.isRequest() ? inspector.rows(m, Param.Type.URL) : List.<String[]>of();
                case "Body params" -> m.isRequest() ? inspector.rows(m, Param.Type.BODY, Param.Type.JSON, Param.Type.XML, Param.Type.MULTIPART) : List.<String[]>of();
                case "Cookies" -> m.isRequest() ? inspector.rows(m, Param.Type.COOKIE) : List.<String[]>of();
                default -> inspector.attributeRows(m, m.isRequest());
            };
            for (String[] r : rows) model.addRow(new Object[] { r[0], r[1] });
            fitRows();
        }

        /** With wrapping on, each row is as tall as its value needs at the column's width. */
        private void fitRows() {
            int plain = Theme.FONT_SIZE + 7;
            if (!wrap) { if (table.getRowHeight() != plain) table.setRowHeight(plain); return; }
            int w = table.getColumnModel().getColumn(1).getWidth();
            if (w <= 0) return;
            JTextArea probe = new WrapCell();
            for (int r = 0; r < table.getRowCount(); r++) {
                probe.setText(String.valueOf(model.getValueAt(r, 1)));
                probe.setSize(w, Short.MAX_VALUE);
                int h = Math.max(plain, probe.getPreferredSize().height);
                if (table.getRowHeight(r) != h) table.setRowHeight(r, h);
            }
        }
    }

    /** A table cell whose text wraps onto as many lines as it needs. */
    private static final class WrapCell extends JTextArea implements javax.swing.table.TableCellRenderer {
        WrapCell() {
            setLineWrap(true);
            setWrapStyleWord(false);
            setFont(Ui.PLAIN);
            setBorder(Ui.pad(1, 4, 1, 4));
        }
        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean focus, int row, int col) {
            setText(v == null ? "" : String.valueOf(v));
            setBackground(sel ? t.getSelectionBackground() : t.getBackground());
            setForeground(sel ? t.getSelectionForeground() : t.getForeground());
            return this;
        }
    }

    // ---- settings that reach every editor ----

    private static final java.util.Set<MessageEditor> LIVE =
            java.util.Collections.synchronizedSet(java.util.Collections.newSetFromMap(new java.util.WeakHashMap<>()));
    private static final java.util.Set<Settings> WATCHED =
            java.util.Collections.synchronizedSet(java.util.Collections.newSetFromMap(new java.util.WeakHashMap<>()));

    /**
     * One listener per settings store tells every editor still in use when a
     * setting of the editor or its side panel changes. Editors are held
     * weakly, so the store does not keep closed ones alive.
     */
    private static void watchSettings(MessageEditor e) {
        Settings st = e.settings();
        if (st == null) return;
        LIVE.add(e);
        if (!WATCHED.add(st)) return;
        st.addListener(key -> {
            if (key == null || !(key.startsWith("editor.request.") || key.startsWith("editor.response.")
                    || key.startsWith("inspector.") || key.startsWith("sidepanel."))) return;
            SwingUtilities.invokeLater(() -> {
                List<MessageEditor> all;
                synchronized (LIVE) { all = new ArrayList<>(LIVE); }
                for (MessageEditor ed : all) {
                    if (ed.settings() != st) continue;
                    if (key.startsWith("editor.")) ed.applyViewSettings();
                    else if (key.startsWith("inspector.")) ed.inspector.rebuild();
                    else ed.placeDock();
                }
            });
        });
    }

    /** Which edge the side panel stands at: BorderLayout.EAST unless Settings > Side panel says left. */
    public String dockSide() {
        if (sideChosen != null) return sideChosen;
        Settings st = settings();
        return st != null && "left".equals(st.get("sidepanel.position", "right")) ? BorderLayout.WEST : BorderLayout.EAST;
    }

    /** Stand the side panel at the edge the setting names, wherever it is hosted. */
    private void placeDock() {
        if (dock == null || stripWrap == null) return;
        boolean left = BorderLayout.WEST.equals(dockSide());
        dock.remove(stripWrap);
        dock.add(stripWrap, left ? BorderLayout.WEST : BorderLayout.EAST);
        stripWrap.setBorder(BorderFactory.createMatteBorder(0, left ? 0 : 1, 0, left ? 1 : 0, Theme.BORDER));
        flyout.setBorder(BorderFactory.createMatteBorder(0, left ? 0 : 1, 0, left ? 1 : 0, Theme.BORDER));
        Container host = dock.getParent();
        if (host != null && host.getLayout() instanceof BorderLayout) {
            host.remove(dock);
            host.add(dock, dockSide());
            host.revalidate();
            host.repaint();
        }
    }
    private JPanel stripWrap;
    /** The edge chosen on the panel's own heading, which outranks the setting for this editor. */
    private String sideChosen;
    private LineGutter prettyGutter;

    private void loadActiveFromMessage() {
        updating = true;
        String text = textOf(message);
        String pretty = prettyTextOf(message);
        // Fill only the view on screen. The other is filled when it is chosen,
        // in onViewChanged: laying out a long body is expensive, and a hidden
        // view is measured by the window validation all the same.
        // Under any view but Pretty (Raw, Hex, Render, an extension's own) the
        // Raw text is what copy, search and the selection actions read, so it
        // is the one kept current there.
        Component shown = views.getSelectedComponent();
        if (shown == prettyView || shown == null) {
            prettyPane.setText(pretty);
            // Lines the formatting added carry no number; the message's own lines keep theirs.
            if (prettyGutter != null) prettyGutter.setNumbers(PrettyPrint.sourceLines(text, pretty));
            applySyntax();
        } else {
            rawArea.setText(text);
        }
        prettyPane.setCaretPosition(0);
        rawArea.setCaretPosition(0);
        updating = false;
    }

    /** The text with CRLF and lone CR turned into LF, as the editor stores it. */
    private static String lf(String text) {
        return text.replace("\r\n", "\n").replace('\r', '\n');
    }

    private void onEdit() {
        if (updating) return;
        message.setRaw(activeText().getText().getBytes(charsetOf(message)));
        // Re-colour after the current document notification completes, to avoid
        // "mutate in notification" from changing attributes mid-edit.
        if (activeText() == prettyPane) SwingUtilities.invokeLater(this::reSyntax);
        messageChanged();
    }

    /** Tell everything that follows the message that it has changed. */
    private void messageChanged() {
        inspector.rebuild();
        for (Runnable r : messageListeners) r.run();
        updateSelectionLabel();
        if (changeListener != null) changeListener.run();
    }

    private void reSyntax() {
        updating = true;
        try { applySyntax(); } finally { updating = false; }
    }

    private void onViewChanged() {
        updating = true;
        Component selected = views.getSelectedComponent();
        if (selected == prettyView) {
            String text = prettyTextOf(message);
            if (!prettyPane.getText().equals(lf(text))) {
                prettyPane.setText(text);
                prettyPane.setCaretPosition(0);
            }
            // Lines the formatting added carry no number; the message's own lines keep theirs.
            if (prettyGutter != null) prettyGutter.setNumbers(PrettyPrint.sourceLines(textOf(message), text));
            applySyntax();
        } else if (selected == rawView) {
            String text = textOf(message);
            if (!rawArea.getText().equals(text)) {
                rawArea.setText(text);
                rawArea.setCaretPosition(0);
            }
        }
        updating = false;
        refreshViews();
        if (!marks.isEmpty()) highlightMatches(0);   // the marks follow the message into whichever view is shown
    }

    private void refreshViews() {
        hexView.setData(message.raw());
        if (views.getSelectedComponent() instanceof PartsView pv) pv.fill(message);
        inspector.rebuild();
        for (Runnable r : messageListeners) r.run();
        applyHideWhenEmpty();
        if ((flags & RESPONSE) != 0 && views.getSelectedIndex() == views.indexOfTab("Render")) renderHtml();
        updateSelectionLabel();
    }

    private void renderHtml() {
        try {
            String body = message.bodyText();
            if (body == null) body = "";
            // A huge body would make the sanitising regexes below run for a long
            // time on the event thread; do not attempt to render it inline.
            if (body.length() > MAX_DECORATE_CHARS) {
                renderPane.setText("<html><body><i>Response too large to render inline "
                        + "(" + (body.length() / 1024) + " KB). Use the Raw view.</i></body></html>");
                renderPane.setCaretPosition(0);
                return;
            }
            body = body.replaceAll("(?is)<script.*?</script>", "")
                       .replaceAll("(?i)<link[^>]*>", "")
                       .replaceAll("(?i)src\\s*=\\s*\"https?://[^\"]*\"", "");
            // Reset the document before each render. Reusing the previous
            // HTMLDocument makes JEditorPane keep showing the earlier page (or
            // nothing at all) on the next setText, which is why most responses
            // came up blank. A fresh document forces a clean re-parse every time.
            renderPane.setDocument(renderPane.getEditorKit().createDefaultDocument());
            if (body.isBlank()) {
                renderPane.setText("<html><body><i>No HTML body to render.</i></body></html>");
            } else {
                renderPane.setText(body);
            }
            renderPane.setCaretPosition(0);
        } catch (Exception e) {
            renderPane.setText("<html><body><i>Could not render this response.</i></body></html>");
        }
    }

    private void updateSelectionLabel() {
        JTextComponent a = activeText();
        int n = Math.abs(a.getSelectionEnd() - a.getSelectionStart());
        selectionLabel.setText(n > 0 ? "Selection: " + n + " (0x" + Integer.toHexString(n) + ")" : "");
    }

    // ---------------- syntax highlighting ----------------

    /** Colour the Pretty view's headers and body without changing any bytes. */
    private void applySyntax() {
        StyledDocument doc = prettyPane.getStyledDocument();
        // Use the document's own text, not getText(): getText() returns the
        // original CRLF string while the document stores LF-normalised content,
        // so their offsets differ and highlighting would drift down the page.
        String text;
        try { text = doc.getText(0, doc.getLength()); }
        catch (javax.swing.text.BadLocationException e) { return; }
        // A very large body is shown plain: colouring it walks every character
        // on the event thread and would freeze the interface.
        if (text.length() > MAX_DECORATE_CHARS) return;
        SimpleAttributeSet plain = new SimpleAttributeSet();
        StyleConstants.setForeground(plain, Theme.CODE_TEXT);
        doc.setCharacterAttributes(0, text.length(), plain, true);

        // Settings > Message editor > HTTP message display: colouring can be switched off for either kind of message.
        if (ctx != null && !ctx.settings().getBool((flags & REQUEST) != 0 ? "editor.display.highlightRequest" : "editor.display.highlightResponse", true)) return;

        int bodyStart = text.indexOf("\r\n\r\n");
        int sep = 4;
        if (bodyStart < 0) { bodyStart = text.indexOf("\n\n"); sep = 2; }
        int headerEnd = bodyStart < 0 ? text.length() : bodyStart;

        // Header lines.
        int pos = 0;
        boolean first = true;
        while (pos < headerEnd) {
            int eol = text.indexOf('\n', pos);
            if (eol < 0 || eol > headerEnd) eol = headerEnd;
            int lineEnd = eol;
            if (first) {
                // The start line is plain; a request's query string has its
                // parameter names and values coloured.
                int q = text.indexOf('?', pos);
                if (message.isRequest() && q > pos && q < lineEnd) {
                    int sp = text.indexOf(' ', q);
                    colourPairs(doc, text, q + 1, sp > q && sp < lineEnd ? sp : lineEnd, '&');
                }
                first = false;
            } else {
                int colon = text.indexOf(':', pos);
                if (colon > pos && colon < lineEnd) {
                    style(doc, pos, colon - pos, C_HEADER_NAME, false);
                    if (text.regionMatches(true, pos, "Cookie", 0, colon - pos) && colon - pos == 6)
                        colourPairs(doc, text, colon + 1, lineEnd, ';');
                }
            }
            pos = eol + 1;
        }

        // Body. Colouring is best-effort decoration; colourBody contains any
        // failure so the event thread always survives it.
        if (bodyStart >= 0) {
            int bodyFrom = bodyStart + sep;
            String body = text.substring(Math.min(bodyFrom, text.length()));
            if (message.contentType().contains("x-www-form-urlencoded")) colourPairs(doc, text, bodyFrom, text.length(), '&');
            else colourBody(doc, bodyFrom, body, message.contentType());
        }
    }

    /** A JSON syntax colourer, substitutable in tests. */
    interface JsonColourer { void colour(StyledDocument doc, int base, String body); }

    /**
     * Colour a body best-effort. Colouring is decoration, so nothing it does
     * may take the app down: a StackOverflowError unwinds to this frame,
     * where catching it is safe, and the body simply shows uncoloured. The
     * trace is omitted on purpose - it is a thousand Pattern frames with the
     * caller cut off, as the field logs of the original crash showed.
     */
    static void colourBody(StyledDocument doc, int base, String body, String ct) {
        colourBody(doc, base, body, ct, MessageEditor::colourJson);
    }

    static void colourBody(StyledDocument doc, int base, String body, String ct, JsonColourer json) {
        try {
            if (ct.contains("json") || looksJson(body)) json.colour(doc, base, body);
            else if (ct.contains("xml") || ct.contains("html") || body.trim().startsWith("<")) colourMarkup(doc, base, body);
        } catch (StackOverflowError e) {
            Debug.error("syntax colouring aborted; body shown uncoloured: " + e, null);
        }
    }

    private static boolean looksJson(String s) { String t = s.trim(); return t.startsWith("{") || t.startsWith("["); }

    static void colourJson(StyledDocument doc, int base, String body) {
        // Quoted strings are found by a linear walk, not a regex. Java's
        // Pattern nests one stack frame per character for a group loop such
        // as "(\\.|[^"\\])*", so one large string value (RUM payloads carry
        // 100 KB+ values) overflowed the AWT event queue's stack and killed
        // the app the moment such a message was rendered. The walk cannot
        // recurse, and pairs spans off exactly as the old regex did: an
        // opening quote closes at the next quote a backslash has not escaped.
        List<Span> strings = jsonStringSpans(body);
        for (Span span : strings) {
            int after = span.end();
            while (after < body.length() && Character.isWhitespace(body.charAt(after))) after++;
            boolean key = after < body.length() && body.charAt(after) == ':';
            style(doc, base + span.start(), span.end() - span.start(), key ? C_HEADER_NAME : C_STRING, false);
        }
        Matcher num = Pattern.compile("(?<![\\w\"])-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?").matcher(body);
        int si = 0;
        while (num.find()) {
            // Skip digits that sit inside a quoted string: they are text, not a number.
            while (si < strings.size() && strings.get(si).end() <= num.start()) si++;
            if (si < strings.size() && strings.get(si).start() <= num.start()) continue;
            style(doc, base + num.start(), num.end() - num.start(), C_NUMBER, false);
        }
    }

    /**
     * A quoted string in a JSON body: {@link #start} inclusive, {@link #end}
     * exclusive (one past the closing quote) - the same convention a Matcher
     * reports for a match that includes both quotes.
     */
    record Span(int start, int end) {}

    /**
     * The quoted-string spans of a JSON body. An unterminated final string
     * yields nothing and nothing beyond it can pair off, matching the
     * previous regex's behaviour.
     */
    static List<Span> jsonStringSpans(String body) {
        ArrayList<Span> out = new ArrayList<>();
        int n = body.length();
        int i = 0;
        while (i < n) {
            if (body.charAt(i) != '"') { i++; continue; }
            int start = i;
            i++;
            boolean closed = false;
            while (i < n) {
                char c = body.charAt(i);
                if (c == '\\') { i += 2; continue; }
                i++;
                if (c == '"') { closed = true; break; }
            }
            if (!closed) break;
            out.add(new Span(start, i));
        }
        return out;
    }

    /**
     * Colour {@code name=value} pairs between {@code from} and {@code to}:
     * a query string or form body (separated by {@code &}) or a Cookie header
     * (separated by {@code ;}). Names take the parameter colour, values the
     * value colour; the separators and the equals sign stay plain.
     */
    static void colourPairs(StyledDocument doc, String text, int from, int to, char separator) {
        int i = from;
        to = Math.min(to, text.length());
        while (i < to) {
            int end = text.indexOf(separator, i);
            if (end < 0 || end > to) end = to;
            int start = i;
            while (start < end && Character.isWhitespace(text.charAt(start))) start++;
            int stop = end;
            while (stop > start && Character.isWhitespace(text.charAt(stop - 1))) stop--;
            int eq = text.indexOf('=', start);
            if (eq < 0 || eq >= stop) {
                style(doc, start, stop - start, C_PARAM, false);
            } else {
                style(doc, start, eq - start, C_PARAM, false);
                style(doc, eq + 1, stop - eq - 1, C_VALUE, false);
            }
            i = end + 1;
        }
    }

    /**
     * Colour markup with a linear walk (no regex, so a huge attribute cannot
     * overflow the stack): tag names, attribute names and values, and
     * declarations and comments.
     */
    static void colourMarkup(StyledDocument doc, int base, String body) {
        int n = body.length();
        int i = 0;
        while (i < n) {
            int lt = body.indexOf('<', i);
            if (lt < 0) break;
            if (body.startsWith("<!--", lt)) {
                int end = body.indexOf("-->", lt);
                end = end < 0 ? n : end + 3;
                style(doc, base + lt, end - lt, C_COMMENT, false);
                i = end;
                continue;
            }
            if (lt + 1 < n && (body.charAt(lt + 1) == '!' || body.charAt(lt + 1) == '?')) {
                int end = body.indexOf('>', lt);
                end = end < 0 ? n : end + 1;
                style(doc, base + lt, end - lt, C_COMMENT, false);
                i = end;
                continue;
            }
            int j = lt + 1;
            if (j < n && body.charAt(j) == '/') j++;
            int nameStart = j;
            while (j < n && (Character.isLetterOrDigit(body.charAt(j)) || body.charAt(j) == '-' || body.charAt(j) == ':' || body.charAt(j) == '_')) j++;
            if (j == nameStart) { i = lt + 1; continue; }   // a bare '<' in text
            style(doc, base + nameStart, j - nameStart, C_TAG, false);
            // Attributes, up to the closing '>'.
            while (j < n && body.charAt(j) != '>') {
                char c = body.charAt(j);
                if (Character.isWhitespace(c) || c == '/') { j++; continue; }
                int an = j;
                while (j < n && !Character.isWhitespace(body.charAt(j)) && body.charAt(j) != '=' && body.charAt(j) != '>' && body.charAt(j) != '/') j++;
                if (j > an) style(doc, base + an, j - an, C_PARAM, false);
                else { j++; continue; }
                if (j < n && body.charAt(j) == '=') {
                    j++;
                    int vs = j;
                    if (j < n && (body.charAt(j) == '"' || body.charAt(j) == '\'')) {
                        char quote = body.charAt(j);
                        int close = body.indexOf(quote, j + 1);
                        j = close < 0 ? n : close + 1;
                        // The quotes stay plain; the value between them is coloured.
                        style(doc, base + vs + 1, Math.max(0, j - vs - 2), C_VALUE, false);
                    } else {
                        while (j < n && !Character.isWhitespace(body.charAt(j)) && body.charAt(j) != '>') j++;
                        style(doc, base + vs, j - vs, C_VALUE, false);
                    }
                }
            }
            i = j + 1;
        }
    }

    private static void style(StyledDocument doc, int off, int len, Color c, boolean bold) {
        if (off < 0 || len <= 0 || off + len > doc.getLength()) return;
        SimpleAttributeSet a = new SimpleAttributeSet();
        StyleConstants.setForeground(a, c);
        StyleConstants.setBold(a, bold);
        doc.setCharacterAttributes(off, len, a, false);
    }

    // ---------------- search ----------------

    private int lastMatchPos = -1;

    private void highlightMatches(int direction) {
        JTextComponent a = activeText();
        Highlighter h = a.getHighlighter();
        h.removeAllHighlights();
        CurrentLine.install(a, false);   // the caret line band is a highlight too; put it back
        paintMarks(a, h);
        String term = searchField.getText();
        if (term.isEmpty()) { matchLabel.setText("0 highlights"); return; }

        // Settings > Message editor > Search: how the term is read.
        boolean caseSensitive = ctx != null && ctx.settings().getBool("editor.search.caseSensitive", false);
        boolean regex = ctx != null && ctx.settings().getBool("editor.search.regex", false);
        String text;
        try { text = a.getDocument().getText(0, a.getDocument().getLength()); }
        catch (BadLocationException e) { text = a.getText(); }
        List<int[]> found = findAll(text, term, caseSensitive, regex);
        List<Integer> positions = new ArrayList<>();
        java.util.Map<Integer, Integer> ends = new java.util.HashMap<>();
        for (int[] m : found) {
            positions.add(m[0]);
            ends.put(m[0], m[1]);
            try { h.addHighlight(m[0], m[1], new DefaultHighlighter.DefaultHighlightPainter(Theme.HIGHLIGHT)); }
            catch (BadLocationException ignored) {}
        }
        int count = found.size();
        matchLabel.setText(count + (count == 1 ? " highlight" : " highlights"));

        if (!positions.isEmpty() && direction != 0) {
            int idx = positions.indexOf(lastMatchPos);
            idx = (idx + direction + positions.size()) % positions.size();
            lastMatchPos = positions.get(idx);
            a.setCaretPosition(lastMatchPos);
            a.select(lastMatchPos, ends.get(lastMatchPos));
            a.requestFocusInWindow();
        } else if (!positions.isEmpty()) {
            lastMatchPos = positions.get(0);
        }
    }

    /** "Auto-scroll to match when text changes": bring the first match into view without taking the caret or the focus. */
    private void scrollToFirstMatch() {
        if (ctx == null || !ctx.settings().getBool("editor.search.autoScroll", false) || searchField.getText().isEmpty()) return;
        highlightMatches(0);
        if (lastMatchPos < 0) return;
        JTextComponent a = activeText();
        try {
            java.awt.geom.Rectangle2D r = a.modelToView2D(Math.min(lastMatchPos, a.getDocument().getLength()));
            if (r != null) a.scrollRectToVisible(r.getBounds());
        } catch (BadLocationException ignored) {}
    }

    /** Every place the term is found, as start and end offsets. A pattern that will not compile, or matches nothing at all, finds nothing. */
    static List<int[]> findAll(String text, String term, boolean caseSensitive, boolean regex) {
        List<int[]> out = new ArrayList<>();
        if (text == null || term == null || term.isEmpty()) return out;
        if (regex) {
            try {
                java.util.regex.Matcher m = java.util.regex.Pattern.compile(term, caseSensitive ? 0 : java.util.regex.Pattern.CASE_INSENSITIVE).matcher(text);
                while (m.find()) {
                    if (m.end() > m.start()) out.add(new int[]{ m.start(), m.end() });
                    else if (m.end() >= text.length()) break;
                    else m.region(m.end() + 1, text.length());
                }
            } catch (java.util.regex.PatternSyntaxException e) {
                return out;
            }
            return out;
        }
        String hay = caseSensitive ? text : text.toLowerCase(Locale.ROOT);
        String want = caseSensitive ? term : term.toLowerCase(Locale.ROOT);
        for (int i = hay.indexOf(want); i >= 0; i = hay.indexOf(want, i + 1)) out.add(new int[]{ i, i + want.length() });
        return out;
    }

    /**
     * What a selection decodes to, for the tip shown when the pointer rests on
     * it: URL encoding first, then HTML entities, then Base64 that comes out as
     * readable text. Null when the selection is already plain.
     */
    static String hoverDecode(String selection) {
        if (selection == null) return null;
        String sel = selection.strip();
        if (sel.length() < 3 || sel.length() > 4096) return null;
        try {
            if (sel.matches("(?s).*%[0-9A-Fa-f]{2}.*")) {
                String d = Convert.urlDecode(sel);
                if (!d.equals(sel)) return d;
            }
            if (sel.matches("(?s).*&(#\\d+|#[xX][0-9A-Fa-f]+|[A-Za-z]+);.*")) {
                String d = Convert.htmlDecode(sel);
                if (!d.equals(sel)) return d;
            }
            if (sel.length() >= 8 && sel.length() % 4 != 1 && sel.matches("[A-Za-z0-9+/_-]+={0,2}")) {
                String d = sel.indexOf('-') >= 0 || sel.indexOf('_') >= 0 ? Convert.base64UrlDecode(sel) : Convert.base64Decode(sel);
                if (!d.isEmpty() && d.chars().allMatch(c -> c == '\n' || c == '\r' || c == '\t' || (c >= 0x20 && c < 0x7F))) return d;
            }
        } catch (RuntimeException e) {
            return null;
        }
        return null;
    }

    /** Show what the selection decodes to while the pointer is over it, unless Settings says to hide it. */
    private void installHoverDecode(JTextComponent area) {
        area.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            @Override public void mouseMoved(java.awt.event.MouseEvent e) {
                String tip = null;
                boolean hidden = ctx != null && ctx.settings().getBool("editor.display.hideDecodedOnHover", false);
                int from = area.getSelectionStart(), to = area.getSelectionEnd();
                if (!hidden && to > from) {
                    int at = area.viewToModel2D(e.getPoint());
                    if (at >= from && at <= to) {
                        String decoded = hoverDecode(area.getSelectedText());
                        if (decoded != null) tip = "<html><b>Decoded:</b> " + Advisory.esc(Ui.truncate(decoded, 300)) + "</html>";
                    }
                }
                if (!java.util.Objects.equals(tip, area.getToolTipText())) area.setToolTipText(tip);
            }
        });
    }

    // ---------------- inspector ----------------

    /** The right-hand Inspector: collapsible parameter and header sections. */
    private final class Inspector extends JPanel {
        private final JPanel stack = new JPanel();

        Inspector() {
            super(new BorderLayout());
            setBackground(Theme.BG);
            stack.setLayout(new BoxLayout(stack, BoxLayout.Y_AXIS));
            stack.setBackground(Theme.BG);
            JScrollPane sp = new JScrollPane(stack);
            sp.setBorder(null);
            sp.getViewport().setBackground(Theme.BG);
            sp.getVerticalScrollBar().setUnitIncrement(16);
            holder.setOpaque(false);
            holder.add(sp, "stack");
            JPanel none = EmptyState.of(boxed(EmptyState.art(0.7), 97, 100), 32, "Inspector",
                    "The Inspector lists the components of the current message, such as parameters, cookies and "
                  + "headers, and lets you view and edit them without modifying the raw text.",
                    250, Theme.BG, EmptyState.learnMore());
            // Centred a little above the middle of the pane, as the reference places it.
            none.setBorder(Ui.pad(0, 0, 12, 0));
            holder.add(none, "empty");
            add(holder, BorderLayout.CENTER);
        }

        private final CardLayout cards = new CardLayout();
        private final JPanel holder = new JPanel(cards);

        private final List<Runnable> toggles = new ArrayList<>();
        private final List<JComponent> bodies = new ArrayList<>();

        /** Open or close every section. */
        void expandAll(boolean open) {
            for (int i = 0; i < bodies.size(); i++) {
                if (bodies.get(i).isVisible() != open) toggles.get(i).run();
            }
        }

        void rebuild() {
            stack.removeAll();
            toggles.clear();
            bodies.clear();
            // One inspector for the pair: request sections (from the shown request
            // or its related request) then response sections.
            HttpMessage req = message.isRequest() ? message : relatedRequest;
            // Beside a request editor, the request being edited is the one described.
            if (paired != null && (req == null || req.raw().length == 0 || message.raw().length == 0)) req = paired.message;
            HttpMessage resp = message.isRequest() ? null : message;
            // As the reference: beside a request that can be edited every request
            // section is listed, an empty one with a count of 0, since rows can be
            // added to it; elsewhere a section appears only when it has rows.
            listEmpty = paired != null && paired.editable;
            // Settings > Side panel > Inspector widgets: which are shown, and in what order.
            Settings st = settings();
            String[] all = opensuite.ui.settings.InterfacePages.INSPECTOR_WIDGETS;
            boolean haveReq = req != null && req.raw().length > 0, haveResp = resp != null && resp.raw().length > 0;
            for (String widget : st == null ? List.of(all) : opensuite.ui.settings.InterfacePages.ordered(st, "inspector.order", all)) {
                if (st != null && !st.getBool(opensuite.ui.settings.InterfacePages.inspectorKey(widget, "show"), true)) continue;
                switch (widget) {
                    case "Request attributes" -> { if (haveReq) addSection(widget, attributeRows(req, true)); }
                    case "Request query parameters" -> { if (haveReq) addIfAny(widget, rows(req, Param.Type.URL)); }
                    case "Request body parameters" -> { if (haveReq) addIfAny(widget, rows(req, Param.Type.BODY, Param.Type.JSON, Param.Type.XML, Param.Type.MULTIPART)); }
                    case "Request cookies" -> { if (haveReq) addIfAny(widget, rows(req, Param.Type.COOKIE)); }
                    case "Request headers" -> { if (haveReq) addIfAny(widget, headerRows(req)); }
                    case "Response headers" -> { if (haveResp) addIfAny(widget, headerRows(resp)); }
                    default -> { }
                }
            }
            cards.show(holder, stack.getComponentCount() == 0 ? "empty" : "stack");
            stack.revalidate();
            stack.repaint();
        }

        private List<String[]> attributeRows(HttpMessage m, boolean req) {
            List<String[]> out = new ArrayList<>();
            if (req) {
                out.add(new String[]{"Method", m.method()});
                out.add(new String[]{"Path", m.path()});
            } else {
                out.add(new String[]{"Status code", String.valueOf(m.statusCode())});
                out.add(new String[]{"Status", m.statusText()});
            }
            return out;
        }

        private boolean listEmpty;
        /** Sections the user has opened or closed by hand, which stay so while the message changes. */
        private final java.util.Map<String, Boolean> opened = new java.util.HashMap<>();
        /** Whether the section being built wraps its values. */
        private boolean wrapValues;

        private void addIfAny(String titleText, List<String[]> data) {
            if (!data.isEmpty() || (listEmpty && titleText.startsWith("Request"))) addSection(titleText, data);
        }

        private void addSection(String titleText, List<String[]> data) {
            Settings st = settings();
            wrapValues = st != null && st.getBool(opensuite.ui.settings.InterfacePages.inspectorKey(titleText, "wrap"), false);
            final JComponent body = buildTable(data, "Request attributes".equals(titleText));
            // Open as it was left; a section not yet touched follows "Open by default".
            Boolean left = opened.get(titleText);
            boolean open = left != null ? left : st != null && st.getBool(opensuite.ui.settings.InterfacePages.inspectorKey(titleText, "open"), false);
            body.setVisible(open);

            JLabel chevron = new JLabel(Glyphs.chevron(22, Theme.TEXT, open ? 2 : 1, 1.3f));
            JLabel title = new JLabel(titleText);
            title.setFont(Ui.PLAIN);
            title.setForeground(Theme.TEXT);

            JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            right.setOpaque(false);
            right.add(countPill(data.size()));
            right.add(Box.createHorizontalStrut(19));
            right.add(chevron);

            JPanel header = new JPanel(new BorderLayout());
            header.setBackground(Theme.BG);
            header.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(0, 10, 0, 7)));
            header.setPreferredSize(new Dimension(10, Ui.tall(38)));
            header.add(title, BorderLayout.WEST);
            JPanel rightWrap = new JPanel(new GridBagLayout());
            rightWrap.setOpaque(false);
            rightWrap.add(right);
            header.add(rightWrap, BorderLayout.EAST);
            header.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            Runnable toggle = () -> {
                boolean show = !body.isVisible();
                body.setVisible(show);
                opened.put(titleText, show);
                chevron.setIcon(Glyphs.chevron(22, Theme.TEXT, show ? 2 : 1, 1.3f));
                stack.revalidate();
            };
            toggles.add(toggle);
            bodies.add(body);
            header.addMouseListener(new MouseAdapter() {
                @Override public void mouseClicked(MouseEvent e) { toggle.run(); }
            });

            header.setAlignmentX(LEFT_ALIGNMENT);
            body.setAlignmentX(LEFT_ALIGNMENT);
            header.setMaximumSize(new Dimension(Integer.MAX_VALUE, header.getPreferredSize().height));
            stack.add(header);
            stack.add(body);
        }

        /** A small rounded grey count badge. */
        private JComponent countPill(int n) {
            JLabel l = new JLabel(String.valueOf(n)) {
                @Override protected void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g.create();
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.setColor(Theme.SURFACE);
                    g2.fillRoundRect(0, 0, getWidth(), getHeight(), getHeight(), getHeight());
                    g2.dispose();
                    super.paintComponent(g);
                }
            };
            l.setFont(Ui.PLAIN);
            l.setForeground(Theme.TEXT);
            l.setHorizontalAlignment(SwingConstants.CENTER);
            // 17px tall, as the reference's: the text keeps its place and the pill loses its last row.
            l.setBorder(BorderFactory.createEmptyBorder(1, 9, 0, 9));
            l.setVerticalAlignment(SwingConstants.TOP);
            l.setOpaque(false);
            return l;
        }

        /**
         * A section body: for request attributes a protocol toggle first; then
         * the Name / Value table with a drill-in chevron per row and the column
         * menu in its header, a footer of delete / down / up / add marks, or
         * "It's empty in here" with Add when there is nothing to show.
         */
        private JComponent buildTable(List<String[]> data, boolean attributes) {
            JPanel col = new JPanel();
            col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
            col.setBackground(Theme.BG);
            col.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Ui.GRID));
            if (attributes) {
                JPanel proto = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 4));
                proto.setOpaque(false);
                proto.add(Ui.label("Protocol"));
                JToggleButton h1 = new JToggleButton("HTTP/1"), h2 = new JToggleButton("HTTP/2");
                h1.setFont(Ui.PLAIN); h2.setFont(Ui.PLAIN);
                h1.setFocusable(false); h2.setFocusable(false);
                ButtonGroup g = new ButtonGroup(); g.add(h1); g.add(h2);
                boolean http2 = message != null && message.startLine().contains("HTTP/2");
                (http2 ? h2 : h1).setSelected(true);
                proto.add(h1); proto.add(h2);
                proto.setAlignmentX(LEFT_ALIGNMENT);
                proto.setMaximumSize(new Dimension(Integer.MAX_VALUE, proto.getPreferredSize().height));
                col.add(proto);
            }
            if (data.isEmpty()) {
                JPanel empty = new JPanel();
                empty.setLayout(new BoxLayout(empty, BoxLayout.Y_AXIS));
                empty.setOpaque(false);
                empty.setBorder(Ui.pad(14, 0, 14, 0));
                JLabel l = Ui.label("It's empty in here");
                l.setForeground(Theme.MUTED);
                l.setAlignmentX(CENTER_ALIGNMENT);
                JButton add = Ui.button("Add");
                add.setEnabled(editable);
                add.setAlignmentX(CENTER_ALIGNMENT);
                add.addActionListener(e -> addRow());
                empty.add(l); empty.add(Box.createVerticalStrut(8)); empty.add(add);
                empty.setAlignmentX(LEFT_ALIGNMENT);
                empty.setMaximumSize(new Dimension(Integer.MAX_VALUE, empty.getPreferredSize().height));
                col.add(empty);
                return col;
            }
            AbstractTableModel m = new AbstractTableModel() {
                public int getRowCount() { return data.size(); }
                public int getColumnCount() { return 3; }
                public String getColumnName(int c) { return c == 0 ? "Name" : c == 1 ? "Value" : ""; }
                public Object getValueAt(int r, int c) { return c < 2 ? data.get(r)[c] : ">"; }
            };
            JTable t = new JTable(m);
            Ui.styleTable(t);
            t.setRowHeight(20);
            t.getColumnModel().getColumn(2).setMaxWidth(22);
            t.getColumnModel().getColumn(2).setCellRenderer(new javax.swing.table.DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable tb, Object v, boolean sel, boolean f, int r, int c) {
                    super.getTableCellRendererComponent(tb, "", sel, f, r, c);
                    setIcon(Glyphs.chevron(12, Theme.MUTED, 0));
                    setHorizontalAlignment(CENTER);
                    return this;
                }
            });
            t.getColumnModel().getColumn(2).setHeaderRenderer(new javax.swing.table.DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable tb, Object v, boolean sel, boolean f, int r, int c) {
                    super.getTableCellRendererComponent(tb, "", sel, f, r, c);
                    setIcon(Glyphs.kebab(12, Theme.MUTED));
                    setHorizontalAlignment(CENTER);
                    return this;
                }
            });
            t.addMouseListener(new MouseAdapter() {
                @Override public void mouseClicked(MouseEvent e) {
                    int r = t.rowAtPoint(e.getPoint());
                    if (r >= 0 && (e.getClickCount() == 2 || t.columnAtPoint(e.getPoint()) == 2)) drill(data.get(r));
                }
            });
            int h = data.size() * 20 + t.getTableHeader().getPreferredSize().height + 2;
            JScrollPane sp = new JScrollPane(t);
            sp.setBorder(null);
            sp.setPreferredSize(new Dimension(240, h));
            sp.setMaximumSize(new Dimension(Integer.MAX_VALUE, h));
            if (wrapValues) {
                // Each row grows to show its whole value, and the section with it.
                t.getColumnModel().getColumn(1).setCellRenderer(new WrapCell());
                int head = t.getTableHeader().getPreferredSize().height + 2;
                t.addComponentListener(new java.awt.event.ComponentAdapter() {
                    @Override public void componentResized(java.awt.event.ComponentEvent e) {
                        int w = t.getColumnModel().getColumn(1).getWidth();
                        if (w <= 0) return;
                        JTextArea probe = new WrapCell();
                        int total = head;
                        for (int r = 0; r < t.getRowCount(); r++) {
                            probe.setText(data.get(r)[1]);
                            probe.setSize(w, Short.MAX_VALUE);
                            int rh = Math.max(20, probe.getPreferredSize().height);
                            if (t.getRowHeight(r) != rh) t.setRowHeight(r, rh);
                            total += rh;
                        }
                        if (sp.getPreferredSize().height != total) {
                            sp.setPreferredSize(new Dimension(240, total));
                            sp.setMaximumSize(new Dimension(Integer.MAX_VALUE, total));
                            stack.revalidate();
                        }
                    }
                });
            }
            sp.setAlignmentX(LEFT_ALIGNMENT);
            col.add(sp);
            JPanel foot = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 2));
            foot.setOpaque(false);
            foot.add(Glyphs.button(Glyphs.trash(14, Theme.MUTED), "Delete the selected row", () -> { if (editable) { int r = t.getSelectedRow(); if (r >= 0) { data.remove(r); m.fireTableDataChanged(); } } }));
            foot.add(Glyphs.button(Glyphs.chevron(14, Theme.MUTED, 1), "Move down", () -> moveRow(t, m, data, 1)));
            foot.add(Glyphs.button(Glyphs.chevron(14, Theme.MUTED, 2), "Move up", () -> moveRow(t, m, data, -1)));
            foot.add(Glyphs.button(Glyphs.plus(14, Theme.MUTED), "Add a row", this::addRow));
            foot.setAlignmentX(LEFT_ALIGNMENT);
            foot.setMaximumSize(new Dimension(Integer.MAX_VALUE, foot.getPreferredSize().height));
            col.add(foot);
            return col;
        }

        private void moveRow(JTable t, AbstractTableModel m, List<String[]> data, int d) {
            int r = t.getSelectedRow(), to = r + d;
            if (r < 0 || to < 0 || to >= data.size()) return;
            data.add(to, data.remove(r));
            m.fireTableDataChanged();
            t.setRowSelectionInterval(to, to);
        }

        private void addRow() {
            if (!editable) { JOptionPane.showMessageDialog(this, "This message is read-only. Send it to Repeater to edit it.", "Inspector", JOptionPane.INFORMATION_MESSAGE); return; }
            JTextField name = Ui.field(""), value = Ui.field("");
            JPanel f = Ui.form("Name:", name, "Value:", value);
            if (JOptionPane.showConfirmDialog(this, f, "Add", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION && !name.getText().isBlank()) {
                String line = name.getText().strip() + ": " + value.getText();
                // Show Raw first: it is filled from the message when it becomes
                // the shown view, and the insert below must land in that text.
                views.setSelectedComponent(rawView);
                rawArea.insert(line + "\n", Math.max(0, rawArea.getText().indexOf("\n") + 1));
            }
        }

        /** Drill into one row: its decoded value, with the common decodings beneath. */
        private void drill(String[] row) {
            JPanel p = new JPanel(new BorderLayout(0, 6));
            p.setBorder(Ui.pad(8, 8, 8, 8));
            JTextArea v = new JTextArea(row[1], 6, 50);
            v.setFont(Ui.MONO);
            v.setLineWrap(true);
            String decoded;
            try { decoded = java.net.URLDecoder.decode(row[1], java.nio.charset.StandardCharsets.UTF_8); } catch (Exception e) { decoded = row[1]; }
            JTextArea d = new JTextArea(decoded, 6, 50);
            d.setFont(Ui.MONO);
            d.setLineWrap(true);
            d.setEditable(false);
            p.add(Ui.vbox(Ui.bold(row[0]), Ui.scroll(v), Ui.label("URL-decoded:"), Ui.scroll(d)), BorderLayout.CENTER);
            JOptionPane.showMessageDialog(this, p, row[0], JOptionPane.PLAIN_MESSAGE);
        }

        private List<String[]> rows(HttpMessage m, Param.Type... types) {
            List<String[]> out = new ArrayList<>();
            java.util.Set<Param.Type> want = new java.util.HashSet<>(java.util.Arrays.asList(types));
            for (Param p : m.parameters()) if (want.contains(p.type())) out.add(new String[]{p.name(), p.value()});
            return out;
        }

        private List<String[]> headerRows(HttpMessage m) {
            List<String[]> out = new ArrayList<>();
            for (String line : m.headerLines()) {
                int c = line.indexOf(':');
                if (c < 0) out.add(new String[]{line, ""});
                else out.add(new String[]{line.substring(0, c).trim(), line.substring(c + 1).trim()});
            }
            return out;
        }
    }

    // ---------------- context menu ----------------

    private void installPopup(JComponent c) {
        c.addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(MouseEvent e)  { maybe(e); }
            @Override public void mouseReleased(MouseEvent e) { maybe(e); }
            private void maybe(MouseEvent e) {
                if (e.isPopupTrigger()) buildMenu().show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }

    private boolean showsRequest(HttpMessage shown) {
        if ((flags & REQUEST) == 0) return false;
        if ((flags & RESPONSE) == 0) return true;
        return shown.isRequest();
    }

    /**
     * Build the right-click menu. The items and their order are the
     * reference's message editor menu; the tools only Open Suite sends to
     * follow the reference's own, and what a view cannot do is left out.
     */
    public JPopupMenu buildMenu() {
        JPopupMenu menu = new JPopupMenu();
        boolean haveRequest = (flags & REQUEST) != 0 || relatedRequest != null;
        boolean haveMessage = message != null && message.raw().length > 0;
        boolean isRequest = haveMessage && message.isRequest();
        HttpMessage req = !haveMessage ? relatedRequest : isRequest ? message : relatedRequest;
        // A request pane offers what is done with the response too, once its pair holds one.
        HttpMessage paired = relatedResponse == null ? null : relatedResponse.get();
        HttpMessage resp = haveMessage && !isRequest ? message
                : paired != null && paired.raw().length > 0 && !paired.isRequest() ? paired : null;
        int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();

        // Scan.
        if (ctx != null && service != null && req != null && ctx.hasSink("scanner")) {
            addItem(menu, "Scan", null, e -> scan(req, resp, true));
            addItem(menu, "Passive scan selected message", null, e -> scan(req, resp, false));
            addItem(menu, "Active scan selected message", null, e -> scan(req, resp, true));
            menu.addSeparator();
        }

        // Send to each tool, the reference's in its order, then the collaborator payload.
        boolean anySend = false;
        if (ctx != null) {
            List<String> sinks = ctx.sinkNames(), ordered = new ArrayList<>();
            for (String t : List.of("intruder", "repeater", "sequencer", "comparer", "decoder", "organizer")) if (sinks.contains(t)) ordered.add(t);
            for (String t : sinks) if (!ordered.contains(t) && !Engagement.isEngagement(t) && !t.equals("scanner")) ordered.add(t);
            for (String t : ordered) {
                JMenuItem mi = sendItem(t);
                if (mi == null) continue;
                mi.setText("Send to " + capitalise(t));
                KeyStroke ks = Hotkeys.keyStroke(Hotkeys.bindingOf(settings(), "Send to " + capitalise(t)));
                if (ks != null) mi.setAccelerator(ks);
                menu.add(mi);
                anySend = true;
            }
        }
        if (editable && ctx != null) {
            addItem(menu, "Insert Collaborator payload", null, e -> insertCollaboratorPayload());
            anySend = true;
        }
        if (anySend) menu.addSeparator();

        if (ctx != null && service != null && haveMessage) {
            JMenu record = sub("Record an issue");
            addItem(record, "Create a new issue", null, e -> ManualIssue.record(this, ctx, service, req, resp));
            menu.add(record);
            menu.addSeparator();
        }

        boolean browser = false;
        if (resp != null && service != null) {
            addItem(menu, "Open response in browser", null, e -> openResponseInBrowser());
            browser = true;
        }
        if (req != null && service != null) {
            JMenu inBrowser = sub("Request in browser");
            addItem(inBrowser, "In original session", null, e -> MessageActions.openRequestInBrowser(this, service, req));
            addItem(inBrowser, "In current browser session", null, e -> MessageActions.openRequestInBrowser(this, service, req));
            menu.add(inBrowser);
            browser = true;
        }
        if (browser) menu.addSeparator();

        // Engagement tools submenu (CSRF PoC, content discovery, ...).
        List<String> eng = new ArrayList<>();
        if (ctx != null) for (String tool : ctx.sinkNames()) if (Engagement.isEngagement(tool)) eng.add(tool);
        if (!eng.isEmpty() && service != null && haveRequest) {
            JMenu sub = sub("Engagement tools");
            for (String t : eng) { JMenuItem mi = sendItem(t); if (mi != null) { mi.setText(Engagement.label(t)); sub.add(mi); } }
            menu.add(sub);
            menu.addSeparator();
        }

        // Editing.
        boolean editsRequest = (flags & REQUEST) != 0 && editable;
        if (editsRequest) addItem(menu, "Change request method", null, e -> toggleMethod());
        if (editable) addItem(menu, "Cut", KeyStroke.getKeyStroke(KeyEvent.VK_X, mask), e -> activeText().cut());
        if (editsRequest) addItem(menu, "Paste host / URL as request", null, e -> pasteUrlAsRequest());
        addItem(menu, "Copy", KeyStroke.getKeyStroke(KeyEvent.VK_C, mask), e -> {
            String sel = activeText().getSelectedText();
            clip(sel == null || sel.isEmpty() ? activeText().getText() : sel);
        });
        if (haveMessage) addItem(menu, "Copy prettified", Hotkeys.keyStroke(Hotkeys.bindingOf(settings(), "Copy prettified")), e -> clip(prettified()));
        addItem(menu, "Save selected text to file", null, e -> copyToFile());
        if (editable) {
            addItem(menu, "Paste", KeyStroke.getKeyStroke(KeyEvent.VK_V, mask), e -> activeText().paste());
            addItem(menu, "Paste text from file", null, e -> pasteFromFile());
            JCheckBoxMenuItem asYouType = new JCheckBoxMenuItem("URL-encode as you type", urlEncodeAsYouType);
            asYouType.setFont(Ui.PLAIN);
            asYouType.addActionListener(e -> urlEncodeAsYouType = asYouType.isSelected());
            menu.add(asYouType);

            String sel = activeText().getSelectedText();
            JMenu convert = new JMenu("Convert selection");
            convert.setFont(Ui.PLAIN);
            convert.setEnabled(sel != null && !sel.isEmpty());   // only with a selection, as the reference

            JMenu url = sub("URL");
            conv(url, "URL-decode", Convert::urlDecode);
            conv(url, "URL-encode key characters", Convert::urlEncodeKey);
            conv(url, "URL-encode key characters (Unicode)", Convert::urlEncodeKeyU);
            conv(url, "URL-encode all characters", Convert::urlEncodeAll);
            conv(url, "URL-encode all characters (Unicode)", Convert::urlEncodeAllU);
            convert.add(url);

            JMenu html = sub("HTML");
            conv(html, "HTML-decode", Convert::htmlDecode);
            conv(html, "HTML-encode key characters", Convert::htmlEncodeKey);
            conv(html, "HTML-encode all characters (numeric entities)", Convert::htmlEncodeAll);
            conv(html, "HTML-encode all characters (hex entities)", Convert::htmlEncodeHex);
            convert.add(html);

            JMenu b64 = sub("Base64");
            conv(b64, "Base64-decode", Convert::base64Decode);
            conv(b64, "Base64-encode", Convert::base64Encode);
            convert.add(b64);

            JMenu b64u = sub("Base64 URL");
            conv(b64u, "Base64 URL-decode", Convert::base64UrlDecode);
            conv(b64u, "Base64 URL-encode", Convert::base64UrlEncode);
            convert.add(b64u);

            JMenu str = sub("Construct string");
            conv(str, "Create string in JavaScript", Convert::constructJs);
            conv(str, "Create string in Microsoft SQL Server", Convert::constructMssql);
            conv(str, "Create string in Oracle", Convert::constructOracle);
            conv(str, "Create string in MySQL", Convert::constructMysql);
            convert.add(str);

            menu.add(convert);
        }
        if (editsRequest) {
            JMenu encoding = sub("Change body encoding");
            addItem(encoding, "Form URL-encoded", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.FORM));
            addItem(encoding, "Multipart", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.MULTIPART));
            addItem(encoding, "JSON", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.JSON));
            menu.add(encoding);
        }
        menu.addSeparator();

        // Saving and copying the item.
        if (historySaver != null) addItem(menu, "Save entire history", null, e -> historySaver.run());
        if (service != null && haveMessage) {
            addItem(menu, "Copy URL", null, e -> clip(service.url() + (req != null ? req.requestTarget() : "")));
            if (req != null) addItem(menu, "Copy as curl command (bash)", null, e -> clip(MessageActions.curl(service, req)));
        }
        if (resp != null && service != null) {
            String base = service.url() + (req != null ? req.requestTarget() : "/");
            addItem(menu, "Copy links in response", null, e -> clip(MessageActions.linksIn(resp, base)));
        }
        if (haveMessage) addItem(menu, "Save item", null, e -> saveItem(req, resp));
        if (ctx != null && service != null && req != null) {
            menu.addSeparator();
            addItem(menu, "Add to site map", null, e -> MessageActions.addToSiteMap(ctx, service, req, resp));
        }

        menu.addSeparator();
        addItem(menu, "Message editor documentation", null, e -> AboutDialog.open(Unbuilt.PROJECT_URL + "#readme"));
        if (toolDocs != null) addItem(menu, toolDocs + " documentation", null, e -> AboutDialog.open(Unbuilt.PROJECT_URL + "#readme"));

        if (!providers.isEmpty()) {
            menu.addSeparator();
            for (ActionProvider p : providers) p.contribute(menu);
        }
        for (Component c : menu.getComponents()) {
            if (c instanceof JMenuItem mi && !(c instanceof JMenu) && MENU_ICONS.containsKey(mi.getText())) {
                mi.setIcon(MENU_ICONS.get(mi.getText()).apply(15, Theme.ICON));
            }
        }
        return menu;
    }

    // What the tool that owns this editor adds to the menu.
    private Runnable historySaver;
    private java.util.function.Consumer<HttpService> targetSetter;
    private String toolDocs;
    private boolean urlEncodeAsYouType;

    /** "Save entire history" appears in the menu and runs this; for a tool that keeps a history of what it sent. */
    public void setHistorySaver(Runnable saver) { this.historySaver = saver; }

    /** Told the target of a URL pasted as a request, by a tool that has a target of its own to set. */
    public void setTargetSetter(java.util.function.Consumer<HttpService> setter) { this.targetSetter = setter; }

    /** The tool's own documentation item, "Repeater documentation" for "Repeater". */
    public void setToolDocs(String toolName) { this.toolDocs = toolName; }

    private void scan(HttpMessage req, HttpMessage resp, boolean active) {
        ctx.sendTo("scanner", service, req.copy(), resp == null ? null : resp.copy(), active ? "active" : "passive");
    }

    /** Put a fresh collaborator address at the caret, in place of any selection. */
    private void insertCollaboratorPayload() {
        String host = ctx.collaborator().payloadHost();
        if (host == null) {
            JOptionPane.showMessageDialog(this, "The collaborator is not running. Start it in the Collaborator tab first.",
                    "Insert Collaborator payload", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        activeText().replaceSelection(host);
    }

    /** The message as the Pretty view would lay it out. */
    private String prettified() {
        String text = textOf(message);
        try { return PrettyPrint.message(text, message.contentType()); }
        catch (RuntimeException | StackOverflowError e) { return text; }
    }

    /** Replace the request with a GET for the address on the clipboard, and set the target to its host. */
    private void pasteUrlAsRequest() {
        String text;
        try { text = String.valueOf(Toolkit.getDefaultToolkit().getSystemClipboard().getData(java.awt.datatransfer.DataFlavor.stringFlavor)).strip(); }
        catch (Exception e) { return; }
        HttpMessage made = requestFor(text);
        if (made == null) {
            JOptionPane.showMessageDialog(this, "The clipboard does not hold a host or a URL.", "Paste host / URL as request", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        HttpService svc = HttpService.parse(text.contains("://") ? text : "http://" + text);
        setMessage(svc, made);
        if (targetSetter != null) targetSetter.accept(svc);
        if (changeListener != null) changeListener.run();
    }

    /** A plain GET for a host or a URL, or null when the text is neither. */
    static HttpMessage requestFor(String text) {
        if (text == null || text.isBlank() || text.matches("(?s).*\\s.*")) return null;
        String url = text.contains("://") ? text : "http://" + text;
        java.net.URI u;
        try { u = java.net.URI.create(url); } catch (IllegalArgumentException e) { return null; }
        if (u.getHost() == null || u.getScheme() == null || !u.getScheme().matches("(?i)https?")) return null;
        String path = u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath();
        if (u.getRawQuery() != null) path += "?" + u.getRawQuery();
        boolean tls = u.getScheme().equalsIgnoreCase("https");
        String host = u.getHost() + (u.getPort() < 0 || u.getPort() == (tls ? 443 : 80) ? "" : ":" + u.getPort());
        return new HttpMessage(Bytes.bytes("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n"));
    }

    /** Save the request and, when there is one, the response to a file. */
    private void saveItem(HttpMessage req, HttpMessage resp) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Save item");
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        try (java.io.OutputStream out = java.nio.file.Files.newOutputStream(fc.getSelectedFile().toPath())) {
            if (req != null) out.write(req.raw());
            if (req != null && resp != null) out.write(Bytes.bytes("\n\n"));
            if (resp != null) out.write(resp.raw());
        } catch (java.io.IOException ex) {
            JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(), "Save item", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** While "URL-encode as you type" is on, a typed character that has a special meaning in a URL goes in encoded. */
    private void installEncodeAsYouType(JTextComponent c) {
        c.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                if (!urlEncodeAsYouType || !c.isEditable() || ch < 0x20 || ch == 0x7f || ch == KeyEvent.CHAR_UNDEFINED
                        || e.isControlDown() || e.isAltDown() || e.isMetaDown()) return;
                String encoded = Convert.urlEncodeKey(String.valueOf(ch));
                if (encoded.equals(String.valueOf(ch))) return;
                e.consume();
                c.replaceSelection(encoded);
            }
        });
    }

    private JMenuItem sendItem(String t) {
        boolean haveRequest = (flags & REQUEST) != 0 || relatedRequest != null;
        boolean haveMessage = message != null && message.raw().length > 0;
        if (ctx.sinkTakesSingleItem(t)) {
            if (!haveMessage) return null;
            JMenuItem mi = new JMenuItem("Send to " + t);
            mi.setFont(Ui.PLAIN);
            mi.addActionListener(e -> {
                HttpMessage own = message.copy();
                boolean asRequest = showsRequest(own);
                ctx.sendTo(t, service, asRequest ? own : null, asRequest ? null : own, null);
            });
            return mi;
        }
        if (service == null || !haveRequest) return null;
        JMenuItem mi = new JMenuItem("Send to " + t);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> {
            HttpMessage own = message.copy();
            boolean asRequest = showsRequest(own);
            HttpMessage req = asRequest ? own : (relatedRequest == null ? null : relatedRequest.copy());
            HttpMessage resp = asRequest ? null : own;
            ctx.sendTo(t, service, req, resp, null);
        });
        return mi;
    }

    private void openResponseInBrowser() {
        MessageActions.openResponseInBrowser(this, ctx, service,
                relatedRequest != null ? relatedRequest : (message.isRequest() ? message : null),
                message.isRequest() ? (relatedResponse == null ? null : relatedResponse.get()) : message);
    }

    /** The items the reference's menu marks with an icon, and the icon each carries. */
    private static final java.util.Map<String, java.util.function.BiFunction<Integer, Color, Icon>> MENU_ICONS = java.util.Map.ofEntries(
            java.util.Map.entry("Insert Collaborator payload", Glyphs::ringPlus),
            java.util.Map.entry("Change request method", Glyphs::swap),
            java.util.Map.entry("Cut", Glyphs::scissors),
            java.util.Map.entry("Paste host / URL as request", Glyphs::clipboard),
            java.util.Map.entry("Copy", Glyphs::copy),
            java.util.Map.entry("Copy prettified", Glyphs::copy),
            java.util.Map.entry("Save selected text to file", Glyphs::save),
            java.util.Map.entry("Paste", Glyphs::clipboard),
            java.util.Map.entry("Paste text from file", Glyphs::clipboard),
            java.util.Map.entry("Save entire history", Glyphs::save),
            java.util.Map.entry("Copy URL", Glyphs::copy),
            java.util.Map.entry("Copy as curl command (bash)", Glyphs::copy),
            java.util.Map.entry("Copy links in response", Glyphs::copy),
            java.util.Map.entry("Save item", Glyphs::save));

    private java.util.function.Supplier<HttpMessage> relatedResponse;

    /** The response this request pane is shown beside, so its menu can offer what is done with a response. */
    public void setRelatedResponse(java.util.function.Supplier<HttpMessage> response) { relatedResponse = response; }

    private String asCurl() {
        StringBuilder b = new StringBuilder("curl -i -s -k ");
        b.append("-X ").append(message.method()).append(' ');
        for (String line : message.headerLines()) {
            int c = line.indexOf(':');
            if (c < 0) continue;
            String n = line.substring(0, c).trim();
            if (n.equalsIgnoreCase("content-length")) continue;
            b.append("-H '").append(line.replace("'", "'\\''")).append("' ");
        }
        byte[] body = message.body();
        if (body.length > 0) b.append("--data-raw '").append(message.bodyText().replace("'", "'\\''")).append("' ");
        b.append('\'').append(service == null ? "" : service.url()).append(message.requestTarget()).append('\'');
        return b.toString();
    }

    private static void clip(String s) {
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(s), null);
    }

    private void addItem(JComponent menu, String label, KeyStroke ks, java.awt.event.ActionListener l) {
        JMenuItem mi = new JMenuItem(label);
        mi.setFont(Ui.PLAIN);
        if (ks != null) mi.setAccelerator(ks);
        mi.addActionListener(l);
        menu.add(mi);
    }

    private JMenu sub(String label) {
        JMenu m = new JMenu(label);
        m.setFont(Ui.PLAIN);
        return m;
    }

    /** A "Convert selection" item: transform the current selection in place. */
    private void conv(JMenu parent, String label, java.util.function.Function<String, String> fn) {
        JMenuItem mi = new JMenuItem(label);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> {
            JTextComponent t = activeText();
            String s = t.getSelectedText();
            if (s == null || s.isEmpty()) return;
            try { t.replaceSelection(fn.apply(s)); } catch (Exception ex) { /* a bad decode leaves the text as it was */ }
        });
        parent.add(mi);
    }

    /** Switch between GET and POST, moving parameters between URL and body. */
    private void toggleMethod() {
        String method = message.method();
        if ("GET".equalsIgnoreCase(method)) {
            String q = message.query();
            message.setMethod("POST");
            message.setRequestTarget(message.path());
            message.setBody(Bytes.bytes(q));
            message.setHeader("Content-Type", "application/x-www-form-urlencoded");
            message.updateContentLength();
        } else {
            String body = message.bodyText();
            message.setMethod("GET");
            String target = message.path();
            if (!body.isBlank()) target += "?" + body;
            message.setRequestTarget(target);
            message.setBody(new byte[0]);
            message.removeHeader("Content-Type");
            message.removeHeader("Content-Length");
        }
        loadActiveFromMessage();
        refreshViews();
        if (changeListener != null) changeListener.run();
    }

    /** Convert the body to another encoding. */
    private void changeBodyEncoding(opensuite.core.BodyEncoding.Kind to) {
        if (!opensuite.core.BodyEncoding.convert(message, to, opensuite.core.BodyEncoding.newBoundary())) return;
        loadActiveFromMessage();
        refreshViews();
        if (changeListener != null) changeListener.run();
    }

    /** Save the selection, or the whole message when nothing is selected, to a file. */
    private void copyToFile() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Save selected text to file");
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        String sel = activeText().getSelectedText();
        byte[] data = sel == null || sel.isEmpty() ? bytes() : sel.getBytes(charsetOf(message));
        try { java.nio.file.Files.write(fc.getSelectedFile().toPath(), data); }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(),
                    "Save selected text to file", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** Replace the selection (or insert at the caret) with a file's contents. */
    private void pasteFromFile() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Paste text from file");
        if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
        try {
            byte[] data = java.nio.file.Files.readAllBytes(fc.getSelectedFile().toPath());
            activeText().replaceSelection(new String(data, charsetOf(message)));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not read the file: " + ex.getMessage(),
                    "Paste text from file", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void selectView(String name) {
        int i = views.indexOfTab(name);
        if (i < 0) i = views.indexOfTab(capitalise(name));
        if (i >= 0) views.setSelectedIndex(i);
    }

    private static String capitalise(String s) {
        return s == null || s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }
}