Skip to content

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

44.7 KB
Raw Blame
package opensuite.ui;

import opensuite.core.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * The suite shell. It knows nothing about any individual tool: it asks each
 * registered module for a name, its tabs and its menus, and renders those.
 */
public class SuiteFrame extends JFrame implements ToolHost {

    private final SuiteContext ctx;
    /** Width reserved at the right of the tab row for the tool icons. */
    private static final int TAB_ROW_RESERVE = 124;

    /**
     * The main tab strip. The right end of its tab row is kept clear for the
     * top-right tool icons (browser, console, search, settings), as in the
     * reference. The reserve is an empty right border, which is what the
     * scrolling tab layout sizes its tab viewport and scroll buttons from; the
     * content area is widened back by the same amount so pages still fill the
     * window. Re-applied on updateUI so it survives a theme switch.
     */
    private final JTabbedPane tabs = new JTabbedPane() {
        @Override public void updateUI() {
            setUI(new opensuite.ui.theme.FlatTabbedPaneUI() {
                @Override protected void installDefaults() {
                    super.installDefaults();
                    // The top-level row is white; the selected tab takes the page
                    // colour. Set here because a layout-policy change reinstalls
                    // the defaults and would otherwise put the page colour back.
                    tabPane.setBackground(Theme.CONTENT);
                    contentBorderInsets = new Insets(contentBorderInsets.top, contentBorderInsets.left,
                            contentBorderInsets.bottom, -TAB_ROW_RESERVE);
                }
            });
            setBorder(BorderFactory.createEmptyBorder(0, 0, 0, TAB_ROW_RESERVE));
        }
    };
    private final JMenuBar menuBar = new JMenuBar();
    private final List<ToolModule> modules = new ArrayList<>();
    /** Set once {@link #buildUi()} has run, after which tools come and go through {@link #toolAdded} and {@link #toolRemoved}. */
    private boolean built;
    private final JLabel statusLabel = new JLabel(" ");
    private final JLabel memoryLabel = new JLabel();
    private final MemoryMeter memoryMeter = new MemoryMeter();
    private final JLabel memoryInfo = new JLabel(ToolIcons.info());
    private final JButton eventLogLabel = new JButton("Event log");
    private final JButton issuesLabel = new JButton("All issues");
    private AlertsPanel alertsPanel;
    private IssuesPanel issuesPanel;
    private final JSplitPane centreSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    private final JPanel bottomDock = new JPanel(new BorderLayout());
    private String bottomShowing;
    private opensuite.session.SessionPanel sessionPanel;   // Settings > Sessions, built on first use
    private ConfigLibraryPanel configLibrary;             // Settings > Configuration library

    /** The project's name for the title bar: its file name without the ending, or the temporary project. */
    static String projectLabel(java.io.File f) {
        if (f == null) return "Temporary Project";
        String n = f.getName();
        int dot = n.lastIndexOf('.');
        return dot > 0 ? n.substring(0, dot) : n;
    }

    public SuiteFrame(SuiteContext ctx, String title) {
        super(title + " - " + projectLabel(ctx.projectFile()));
        this.ctx = ctx;
        ctx.setFrame(this);
        // The title names the project in use, as the first screen named it.
        ctx.onProjectFile(() -> javax.swing.SwingUtilities.invokeLater(
                () -> setTitle(title + " - " + projectLabel(ctx.projectFile()))));
        // Suite-level settings panes. Tools register their own in init().
        SettingsDialog.register("Sessions", () -> {
            if (sessionPanel == null) sessionPanel = new opensuite.session.SessionPanel(ctx);
            sessionPanel.refreshAll();
            return sessionPanel;
        });
        SettingsDialog.register("Configuration library", () -> {
            if (configLibrary == null) configLibrary = new ConfigLibraryPanel();
            configLibrary.reload();
            return configLibrary;
        });
        // The audit traffic and WebSocket frame caps follow their settings,
        // including ones restored from a project.
        ctx.store().setAuditCapBytes(opensuite.core.ProjectOptions.auditMemoryBytes(ctx.settings()));
        ctx.wsStore().setCapBytes(opensuite.core.ProjectOptions.wsMemoryBytes(ctx.settings()));
        Advisory.bind(ctx.settings());
        // "Prompt for credentials on platform authentication failure": asked once per host, kept for the session.
        opensuite.core.PlatformAuth.setPrompter((host, schemes) -> {
            opensuite.core.PlatformAuth.Login[] typed = new opensuite.core.PlatformAuth.Login[1];
            Runnable ask = () -> {
                JTextField user = Ui.field("", 20), domain = Ui.field("", 20);
                JPasswordField password = Ui.passwordField("");
                password.setFont(Ui.PLAIN);
                JPanel form = Ui.vbox(Ui.label(host + " requires credentials (" + schemes + ")."), Box.createVerticalStrut(8),
                        Ui.form("Username:", user, "Password:", password, "Domain (NTLM only):", domain));
                form.setBorder(Ui.pad(10, 10, 10, 10));
                if (JOptionPane.showConfirmDialog(this, form, "Platform authentication", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION
                        && !user.getText().isBlank())
                    typed[0] = new opensuite.core.PlatformAuth.Login("", user.getText().strip(), new String(password.getPassword()), domain.getText().strip(), "");
            };
            try {
                if (SwingUtilities.isEventDispatchThread()) ask.run(); else SwingUtilities.invokeAndWait(ask);
            } catch (Exception e) { return null; }
            return typed[0];
        });

        // New connections take their timeouts from the Timeouts setting.
        Runnable timeouts = () -> opensuite.core.HttpClient.setDefaultTimeouts(
                ctx.settings().getInt("timeout.connect", 120), ctx.settings().getInt("timeout.read", 120));
        timeouts.run();
        ctx.settings().addListener(key -> {
            if (key.startsWith("timeout.")) timeouts.run();
            if (opensuite.core.ProjectOptions.AUDIT_MEMORY_MB.equals(key))
                ctx.store().setAuditCapBytes(opensuite.core.ProjectOptions.auditMemoryBytes(ctx.settings()));
            if (opensuite.core.ProjectOptions.WS_MEMORY_MB.equals(key))
                ctx.wsStore().setCapBytes(opensuite.core.ProjectOptions.wsMemoryBytes(ctx.settings()));
        });
        setIconImages(AppIcon.images());
        // The Dock shows no window icon, only the application's.
        if (Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
            Taskbar.getTaskbar().setIconImage(AppIcon.images().stream().max(java.util.Comparator.comparingInt(java.awt.image.BufferedImage::getWidth)).orElseThrow());
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        tabs.setFont(Ui.PLAIN);
        // One compact row, as in the reference: tabs keep their natural width and
        // never wrap onto a second row (which would stretch them to fill the
        // width). On a narrow window the row scrolls instead.
        tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        setLayout(new BorderLayout());
        centreSplit.setTopComponent(buildCenter());
        bottomDock.setOpaque(false);
        bottomDock.setVisible(false);
        centreSplit.setBottomComponent(bottomDock);
        centreSplit.setDividerSize(0);
        centreSplit.setBorder(null);
        centreSplit.setResizeWeight(1.0);
        add(centreSplit, BorderLayout.CENTER);
        add(buildStatusBar(), BorderLayout.SOUTH);
        // The menu merges into the window's own title bar unless Settings >
        // Display says otherwise; then the desktop draws the title bar and the
        // menu sits in a strip of its own.
        if (ctx.settings().getBool("ui.mergeTitleBar", !opensuite.core.Os.MAC)) TitleBar.install(this, menuBar);
        else setJMenuBar(menuBar);

        addWindowListener(new WindowAdapter() {
            @Override public void windowClosing(WindowEvent e) { confirmExit(); }
        });
        // The macOS application menu: Quit (Cmd+Q) would otherwise end the
        // process at once, without the save and the question a close gets.
        if (Desktop.isDesktopSupported()) {
            Desktop d = Desktop.getDesktop();
            if (d.isSupported(Desktop.Action.APP_QUIT_HANDLER)) d.setQuitHandler((e, r) -> { r.cancelQuit(); confirmExit(); });
            if (d.isSupported(Desktop.Action.APP_ABOUT)) d.setAboutHandler(e -> AboutDialog.show(this));
            if (d.isSupported(Desktop.Action.APP_PREFERENCES)) d.setPreferencesHandler(e -> SettingsDialog.open(this, ctx));
        }

        // A session bound to a project file is written back every 30 seconds
        // when something changed (in the background, atomically), so a crash
        // costs half a minute at most. Writing on every request is not an
        // option: each save rewrites the whole file.
        Timer autosave = new Timer(30_000, e -> StateIO.autosave(ctx, size -> setStatus(
                "Project saved at " + java.time.LocalTime.now().withNano(0) + ", "
                + ProjectSizeDialog.human(size) + " on disk")));
        autosave.setRepeats(true);
        autosave.start();

        Timer t = new Timer(2000, e -> updateMemory());
        t.start();
        updateMemory();
    }

    private JPanel buildStatusBar() {
        JPanel p = new JPanel(new BorderLayout());
        p.setBackground(Theme.CHROME);
        p.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, Theme.BORDER), Ui.pad(0, 13, 0, 14)));
        // 40px in all, as the reference: a hairline, the strip, and the
        // window's own 1px edge beneath it when the title bar is merged.
        p.setPreferredSize(new Dimension(10, ctx.settings().getBool("ui.mergeTitleBar", !opensuite.core.Os.MAC) ? Ui.tall(39) : Ui.tall(40)));
        statusLabel.setFont(Ui.PLAIN);
        memoryLabel.setFont(Ui.PLAIN);
        memoryLabel.setForeground(Theme.TEXT);

        linkify(eventLogLabel, () -> toggleBottom("Event log", alertsPanel));
        linkify(issuesLabel, () -> toggleBottom("All issues", issuesPanel));

        JPanel west = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        west.setOpaque(false);
        west.add(eventLogLabel);
        west.add(Box.createHorizontalStrut(26));
        west.add(issuesLabel);
        p.add(centred(west), BorderLayout.WEST);

        // The right-hand side carries the project/save detail and the memory
        // readout together: the project saved note and disk size, the numeric
        // memory in use, then the help glyph and the live meter.
        JPanel east = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        east.setOpaque(false);
        JLabel info = memoryInfo;
        east.add(statusLabel);
        east.add(Box.createHorizontalStrut(16));
        east.add(info);
        east.add(Box.createHorizontalStrut(9));
        east.add(memoryLabel);
        east.add(Box.createHorizontalStrut(15));
        east.add(memoryMeter);
        p.add(centred(east), BorderLayout.EAST);

        // Live counters for the status bar.
        ctx.addAlertListener(a -> SwingUtilities.invokeLater(() ->
                eventLogLabel.setToolTipText(ctx.alerts().size() + " events")));
        ctx.addIssueListener(i -> SwingUtilities.invokeLater(() ->
                issuesLabel.setToolTipText(ctx.issues().size() + " issues")));
        return p;
    }

    /** Open, switch or close the bottom panel the status bar links control. */
    private void toggleBottom(String name, JComponent panel) {
        if (name.equals(bottomShowing)) {
            bottomDock.setVisible(false);
            centreSplit.setDividerSize(0);
            bottomShowing = null;
        } else {
            bottomDock.removeAll();
            JPanel head = new JPanel(new BorderLayout());
            head.setOpaque(false);
            head.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Ui.GRID), Ui.pad(4, 10, 4, 6)));
            head.add(Ui.bold(name), BorderLayout.WEST);
            head.add(Glyphs.button(Glyphs.cross(14, Theme.ICON), "Close", () -> toggleBottom(name, panel)), BorderLayout.EAST);
            bottomDock.add(head, BorderLayout.NORTH);
            bottomDock.add(panel, BorderLayout.CENTER);
            bottomDock.setVisible(true);
            centreSplit.setDividerSize(1);
            centreSplit.setDividerLocation(Math.max(200, centreSplit.getHeight() - 320));
            bottomShowing = name;
        }
        bottomDock.revalidate();
        centreSplit.revalidate();
        repaint();
    }

    /** Make a button read as a flat clickable link in the status bar. */
    private void linkify(JButton b, Runnable action) {
        b.setFont(Ui.PLAIN);
        b.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2));
        b.setContentAreaFilled(false);
        b.setFocusable(false);
        b.setForeground(Theme.TEXT);
        b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        b.addActionListener(e -> action.run());
    }

    /**
     * The memory readout: everything Open Suite is using, out of the machine's
     * memory, with the parts on hover. Where the system cannot say what the
     * programs Open Suite started are using, it is the application's own
     * memory out of its limit, and the hover says so.
     */
    private void updateMemory() {
        opensuite.core.MemoryUse.Reading m = opensuite.core.MemoryUse.latest();
        String tip;
        if (m.whole() && m.machine() > 0) {
            memoryLabel.setText("Memory: " + memory(m.total()) + " of " + memory(m.machine()));
            memoryMeter.setFraction((double) m.total() / m.machine());
            tip = "<html>Memory in use by Open Suite and everything it runs: " + memory(m.total())
                    + "<br>Open Suite: " + memory(m.app())
                    + "<br>Scan engine: " + memory(m.engine())
                    + "<br>Browsers and other programs it started: " + memory(m.others())
                    + (m.data() > 0 ? "<br>Scan data held in memory: " + memory(m.data()) : "")
                    + "<br><br>This computer: " + memory(m.machine()) + ", " + memory(m.available()) + " available</html>";
        } else {
            long max = Runtime.getRuntime().maxMemory();
            memoryLabel.setText("Memory: " + memory(m.total()) + " of " + memory(max));
            memoryMeter.setFraction(max <= 0 ? 0 : (double) m.total() / max);
            tip = "Memory in use by Open Suite itself. The scan engine and browsers it starts are not counted on this system.";
        }
        memoryLabel.setToolTipText(tip);
        memoryMeter.setToolTipText(tip);
        memoryInfo.setToolTipText(tip);
    }

    /** A byte count as the reference writes it: "149.8MB" below a gigabyte, "15.61GB" above. */
    static String memory(long bytes) {
        double mb = bytes / (1024.0 * 1024.0);
        if (mb >= 1024) return String.format(java.util.Locale.ROOT, "%.2fGB", mb / 1024.0);
        return String.format(java.util.Locale.ROOT, "%.1fMB", mb);
    }

    /** Hold a row at its own height, centred in the bar. */
    private static JComponent centred(JComponent row) {
        JPanel p = new JPanel(new GridBagLayout());
        p.setOpaque(false);
        p.add(row);
        return p;
    }

    /** A small rounded usage meter shown beside the memory readout. */
    private static final class MemoryMeter extends JComponent {
        private double fraction;
        MemoryMeter() {
            Dimension d = new Dimension(45, 8);
            setPreferredSize(d); setMinimumSize(d); setMaximumSize(d);
        }
        void setFraction(double f) {
            this.fraction = Math.max(0, Math.min(1, f));
            repaint();
        }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth(), h = getHeight();
            g2.setColor(Theme.SURFACE);
            g2.fillRoundRect(0, 0, w, h, h, h);
            int fill = (int) Math.round(fraction * (w - 1));
            if (fill > 0) {
                g2.setColor(Theme.ACCENT);
                g2.fillRoundRect(0, 0, Math.max(h, fill), h - 1, h, h);
            }

            g2.dispose();
        }
    }

    public void setStatus(String s) {
        SwingUtilities.invokeLater(() -> statusLabel.setText(s == null ? " " : s));
    }

    /** Register a tool. Call before {@link #buildUi()}; after it, {@link #toolAdded}. */
    public void register(ToolModule m) {
        modules.add(m);
        ctx.registerTool(m);
    }

    /** Build the tab strip and menu bar from everything registered. */
    public void buildUi() {
        for (ToolModule m : modules) m.init(ctx);

        for (ToolModule m : modules) installTab(m);

        // The event log and the issue list slide open at the bottom of the window
        // from the status bar links, as in the reference; neither is a tab.
        alertsPanel = new AlertsPanel(ctx);
        issuesPanel = new IssuesPanel(ctx);

        buildMenus();

        // Unread dots: sent-to tools get a dot until they are shown.
        ctx.addSendListener(tool -> SwingUtilities.invokeLater(() -> badgeTool(tool)));
        tabs.addChangeListener(e -> clearBadge(tabs.getSelectedIndex()));
        // A count of what has not been looked at yet, as in "Collaborator (3)": it stays, on
        // whichever tab the user is, until each item has been looked at.
        ctx.addCountListener((tool, n) -> SwingUtilities.invokeLater(() -> countTool(tool, n)));
        built = true;
    }

    /**
     * A tool that arrives after the window is built: the shell enters it among
     * the modules, so it is saved, restored and shut down with the others,
     * and gives it its tab and menus as a built-in tool does. Rebuilding the
     * menus also lists it under View. Must be called on the event thread.
     */
    @Override public void toolAdded(ToolModule m) {
        requireBuiltOnEventThread("toolAdded");
        modules.add(m);
        ctx.registerTool(m);
        installTab(m);
        buildMenus();
        menuBar.revalidate();
        menuBar.repaint();
    }

    /** A tool that leaves before the window closes: its tab and menus go, and it is neither saved, restored nor shut down any more. */
    @Override public void toolRemoved(ToolModule m) {
        requireBuiltOnEventThread("toolRemoved");
        int i = indexOfTool(m.name());
        if (i >= 0) tabs.remove(i);
        modules.remove(m);
        ctx.unregisterTool(m);
        buildMenus();
        menuBar.revalidate();
        menuBar.repaint();
    }

    private void requireBuiltOnEventThread(String call) {
        if (!built) throw new IllegalStateException(call + " before buildUi(); use register while the window is still being built");
        if (!SwingUtilities.isEventDispatchThread()) throw new IllegalStateException(call + " must be called on the event thread");
    }

    /** Give one tool its tab: the scanner's go under Settings, one tab alone needs no inner tab bar, and the rest get one. */
    private void installTab(ToolModule m) {
        ToolModule.Tab[] mt = m.tabs();
        if ("scanner".equals(m.name())) {
            // Scan checks live under Settings in the reference layout, not on the tab strip.
            final ToolModule.Tab[] st = mt;
            SettingsDialog.register("Scanner", () -> {
                JTabbedPane inner = new JTabbedPane();
                inner.setFont(Ui.PLAIN);
                for (ToolModule.Tab t : st) inner.addTab(capitalise(t.title()), t.component());
                SettingsDialog.wireLaunchers(inner);
                return inner;
            });
            return;
        }
        JComponent comp;
        if (mt.length == 1 && !m.alwaysTabbed()) {
            comp = mt[0].component();
        } else {
            JTabbedPane inner = new JTabbedPane();
            inner.setFont(Ui.PLAIN);
            inner.setFocusable(false);
            for (ToolModule.Tab t : mt) inner.addTab(t.title(), t.component());
            // A settings sub-tab opens the Settings window rather than
            // showing a page with a button on it.
            SettingsDialog.wireLaunchers(inner);
            comp = inner;
        }
        tabs.addTab(m.name(), comp);
    }

    private void buildMenus() {
        menuBar.removeAll();

        // The reference's entries in the reference's order; what only Open Suite has comes after them.
        JMenu suite = new JMenu("Open Suite");
        suite.setFont(Ui.PLAIN);
        addItem(suite, "Search", e -> new SearchWindow(ctx).setVisible(true));
        suite.addSeparator();
        addItem(suite, "Settings", e -> SettingsDialog.open(this, ctx));
        addItem(suite, "Configuration library", e -> SettingsDialog.open(this, ctx, "Configuration library"));
        suite.add(SettingsDialog.userSettingsMenu(this, ctx));
        suite.addSeparator();
        addItem(suite, "Clickjacking proof of concept", e -> new opensuite.clickjack.ClickjackWindow(ctx, null, null).setVisible(true));
        addItem(suite, "Collaborator client", e -> selectTool("collaborator"));
        suite.addSeparator();
        addItem(suite, "Save state", e -> StateIO.saveDialog(ctx, this));
        addItem(suite, "Restore state", e -> StateIO.restoreDialog(ctx, this));
        suite.addSeparator();
        addItem(suite, "Exit", e -> confirmExit());
        menuBar.add(suite);

        JMenu project = new JMenu("Project");
        project.setFont(Ui.PLAIN);
        project.add(SettingsDialog.projectSettingsMenu(this, ctx));
        addItem(project, "Rename", e -> renameProject());
        addItem(project, "Save copy", e -> saveProjectCopy());
        addItem(project, "Import project file", e -> StateIO.restoreDialog(ctx, this));
        project.addSeparator();
        addItem(project, "Project size", e -> ProjectSizeDialog.show(this, ctx));
        menuBar.add(project);

        for (ToolModule m : modules) {
            JMenu[] ms = m.menus();
            if (ms == null) continue;
            for (JMenu x : ms) { x.setFont(Ui.PLAIN); x.setText(capitalise(x.getText())); menuBar.add(x); }
        }

        JMenu view = new JMenu("View");
        view.setFont(Ui.PLAIN);
        addItem(view, "Restore default tab layout", e -> { if (bottomShowing != null) toggleBottom(bottomShowing, null); tabs.setSelectedIndex(0); });
        view.addSeparator();
        // The tools by name, alphabetically, as the reference lists them.
        java.util.TreeMap<String, Integer> byName = new java.util.TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < tabs.getTabCount(); i++) byName.put(capitalise(plainTitle(tabs.getTitleAt(i))), i);
        for (java.util.Map.Entry<String, Integer> t : byName.entrySet()) {
            final int idx = t.getValue();
            addItem(view, t.getKey(), e -> tabs.setSelectedIndex(idx));
        }
        view.addSeparator();
        // Changing scale relaunches the JVM; the session is written to its
        // project file on the way past, exactly as on exit.
        JMenu size = new JMenu("Text size");
        size.setFont(Ui.PLAIN);
        int shortcut = java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
        JMenuItem bigger = new JMenuItem("Increase text size");
        bigger.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_EQUALS, shortcut));
        bigger.addActionListener(e -> relaunchScaled(currentScale() + 0.25));
        JMenuItem smaller = new JMenuItem("Decrease text size");
        smaller.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_MINUS, shortcut));
        smaller.addActionListener(e -> relaunchScaled(currentScale() - 0.25));
        JMenuItem reset = new JMenuItem("Reset text size");
        reset.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, shortcut));
        reset.addActionListener(e -> relaunchScaled(1.0));
        for (JMenuItem mi : new JMenuItem[]{ bigger, smaller, reset }) { mi.setFont(Ui.PLAIN); size.add(mi); }
        size.addSeparator();
        for (double f : new double[]{1.0, 1.25, 1.5, 2.0}) {
            final double ff = f;
            JMenuItem mi = new JMenuItem((int) (f * 100) + "%");
            mi.setFont(Ui.PLAIN);
            mi.addActionListener(e -> relaunchScaled(ff));
            size.add(mi);
        }
        view.add(size);
        menuBar.add(view);

        JMenu help = new JMenu("Help");
        help.setFont(Ui.PLAIN);
        addItem(help, "Open Suite documentation", e -> AboutDialog.open(Unbuilt.PROJECT_URL + "#readme"));
        addItem(help, "Getting started", e -> showProxyHelp());
        addItem(help, "Using Open Suite", e -> selectTool("discover"));
        help.addSeparator();
        addItem(help, "Support Center", e -> AboutDialog.open(Unbuilt.PROJECT_URL + "/issues"));
        addItem(help, "Release notes", e -> AboutDialog.open(Unbuilt.PROJECT_URL + "/releases"));
        addItem(help, "Report bug", e -> AboutDialog.open(Unbuilt.PROJECT_URL + "/issues/new"));
        addItem(help, "Diagnostics", e -> HelpActions.showDiagnostics(this));
        addItem(help, "Health check for Open Suite's browser", e -> {
            opensuite.proxy.ProxyServer server = null;
            for (ToolModule m : modules) if (m instanceof opensuite.proxy.ProxyTool p) { server = p.server(); break; }
            HelpActions.showBrowserHealth(this, server != null && server.anyRunning(), server != null && server.ca() != null);
        });
        help.addSeparator();
        addItem(help, "About", e -> AboutDialog.show(this));
        addItem(help, "Check for updates", e -> AboutDialog.open(Unbuilt.PROJECT_URL + "/releases/latest"));
        addItem(help, "Clean Open Suite from computer", e -> HelpActions.cleanFromComputer(this, ctx));
        menuBar.add(help);
    }

    /** Rename the project file this session is bound to, keeping its contents. */
    private void renameProject() {
        java.io.File current = ctx.projectFile();
        if (current == null) {
            JOptionPane.showMessageDialog(this,
                    "This session has not been saved as a project. Use Open Suite > save state "
                    + "to save it to a file, then rename it.", "Rename project", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String name = JOptionPane.showInputDialog(this, "New project name:", RecentProjects.baseName(current));
        if (name == null || name.isBlank()) return;
        name = name.trim();
        if (!StateIO.isProjectName(name)) name += StateIO.EXT;
        java.io.File target = new java.io.File(current.getParentFile(), name);
        if (target.equals(current)) return;
        if (target.exists()) {
            JOptionPane.showMessageDialog(this, "A project called " + target.getName() + " already exists.",
                    "Rename project", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try {
            if (current.exists()) java.nio.file.Files.move(current.toPath(), target.toPath());
            ctx.setProjectFile(target);
            RecentProjects.record(RecentProjects.baseName(target), target);
            ctx.alert("suite", "Project renamed to " + target.getName());
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(this, "Could not rename the project: " + e.getMessage(),
                    "Rename project", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Write the current state to another file without rebinding the session to
     * it. First a small dialog chooses what the copy keeps: in-scope items only,
     * which tools' history, the scan cards and the audit bodies; it is also the
     * way to shrink a project, since a copy drops what the filters leave out.
     */
    private void saveProjectCopy() {
        StateIO.SaveOptions opts = StateIO.SaveOptions.fromSettings(ctx);
        JCheckBox inScope = Ui.check("Save in-scope items only", false);
        JCheckBox tasks = Ui.check("Include the scans on the dashboard", true);
        JCheckBox audit = Ui.check("Keep full audit responses", opts.keepAuditBodies);
        java.util.LinkedHashMap<String, JCheckBox> tools = new java.util.LinkedHashMap<>();
        for (opensuite.core.LogEntry e : ctx.store().all()) {
            tools.computeIfAbsent(e.tool(), t -> Ui.check(t, true));
        }
        JPanel toolBox = new JPanel();
        toolBox.setLayout(new BoxLayout(toolBox, BoxLayout.Y_AXIS));
        toolBox.setOpaque(false);
        for (JCheckBox b : tools.values()) { b.setAlignmentX(Component.LEFT_ALIGNMENT); toolBox.add(b); }
        JPanel body = new JPanel();
        body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS));
        body.setBorder(Ui.pad(4, 4, 4, 4));
        JLabel lead = Ui.label("Select the contents of the copy.");
        lead.setAlignmentX(Component.LEFT_ALIGNMENT);
        body.add(lead);
        body.add(Box.createVerticalStrut(10));
        inScope.setAlignmentX(Component.LEFT_ALIGNMENT); body.add(inScope);
        tasks.setAlignmentX(Component.LEFT_ALIGNMENT); body.add(tasks);
        audit.setAlignmentX(Component.LEFT_ALIGNMENT); body.add(audit);
        if (!tools.isEmpty()) {
            body.add(Box.createVerticalStrut(10));
            JLabel th = Ui.label("History from these tools:");
            th.setAlignmentX(Component.LEFT_ALIGNMENT);
            body.add(th);
            toolBox.setBorder(Ui.pad(2, 16, 0, 0));
            toolBox.setAlignmentX(Component.LEFT_ALIGNMENT);
            body.add(toolBox);
        }
        int r = JOptionPane.showOptionDialog(this, body, "Save copy", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, new Object[]{"Choose file...", "Cancel"}, "Choose file...");
        if (r != 0) return;
        opts.inScopeOnly = inScope.isSelected();
        opts.includeTasks = tasks.isSelected();
        opts.keepAuditBodies = audit.isSelected();
        if (!tools.isEmpty()) {
            opts.tools = new java.util.HashSet<>();
            for (var en : tools.entrySet()) if (en.getValue().isSelected()) opts.tools.add(en.getKey());
        }

        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("save copy");
        java.io.File current = ctx.projectFile();
        fc.setSelectedFile(current != null
                ? new java.io.File(current.getParentFile(), RecentProjects.baseName(current) + "-copy" + StateIO.EXT)
                : new java.io.File(StateIO.defaultProjectFileName()));
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        java.io.File f = fc.getSelectedFile();
        if (!StateIO.isProjectName(f.getName())) f = new java.io.File(f.getParentFile(), f.getName() + StateIO.EXT);
        if (f.exists() && JOptionPane.showConfirmDialog(this, "This file already exists. Overwrite it?",
                "save copy", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return;
        try {
            StateIO.save(ctx, f, opts);
            ctx.alert("suite", "Copy saved to " + f.getName() + ", " + ProjectSizeDialog.human(f.length()));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Could not save the copy: " + e.getMessage(),
                    "save copy", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * The tab strip with the top-right tool icons on its tab row, as in the
     * reference: a globe (browser), a console, a magnifier (search) and a gear
     * (settings). The tab UI reserves the right end of the row for them, so the
     * tabs wrap before that point and never sit under the icons. The globe
     * opens the browser, the console the command palette, the magnifier the
     * search window and the gear Settings.
     */
    private JComponent buildCenter() {
        final JPanel tools = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        tools.setOpaque(false);
        // The order honours Settings > User interface > Display > Title bar actions; the gear is always last.
        java.util.Map<String, JButton> actions = new java.util.LinkedHashMap<>();
        actions.put("Open browser", iconButton(ToolIcons.browser(), "Open browser", this::launchBrowser));
        JButton palette = iconButton(ToolIcons.console(), "Command palette (" + (Os.MAC ? "Cmd" : "Ctrl") + "+K)", null);
        palette.addActionListener(e -> openPalette(palette));
        actions.put("Open command palette", palette);
        actions.put("Open search window", iconButton(ToolIcons.search(), "Search", () -> new SearchWindow(ctx).setVisible(true)));
        String order = ctx.settings().get("ui.titleActions", "");
        java.util.List<String> names = order.isEmpty() ? java.util.List.of("Open browser", "Open command palette") : java.util.Arrays.asList(order.split("\\|"));
        for (String n : names) if (actions.containsKey(n)) tools.add(actions.get(n));
        tools.add(iconButton(ToolIcons.gear(), "Settings", () -> SettingsDialog.open(this, ctx)));
        Hotkeys.install(ctx.settings(), this);
        // Ctrl+K (Cmd+K on a Mac) opens the palette from anywhere in the window.
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()), "opensuite.palette");
        getRootPane().getActionMap().put("opensuite.palette", new AbstractAction() {
            @Override public void actionPerformed(java.awt.event.ActionEvent e) { openPalette(palette); }
        });

        final JLayeredPane layer = new JLayeredPane();
        layer.setLayout(null);
        layer.add(tabs, JLayeredPane.DEFAULT_LAYER);
        layer.add(tools, 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();
                tabs.setBounds(0, 0, w, h);
                tabs.doLayout();
                Dimension ts = tools.getPreferredSize();
                int rowH = tabs.getTabCount() > 0
                        ? tabs.getUI().getTabBounds(tabs, 0).height : ts.height;
                tools.setBounds(w - ts.width - 11, Math.max(0, (rowH - ts.height) / 2), ts.width, ts.height);
            }
        });
        return layer;
    }

    /**
     * Launch the bundled browser routed through the proxy, with the CA already
     * trusted: the same action as Open browser on the Proxy tab, reachable from
     * the globe in the top bar.
     */
    /** Open the suite browser; for dialogs that need to record a login. */
    public void launchBrowserPublic() { launchBrowser(); }

    private void launchBrowser() {
        opensuite.proxy.ProxyServer server = null;
        for (ToolModule m : modules) {
            if (m instanceof opensuite.proxy.ProxyTool p) { server = p.server(); break; }
        }
        if (server == null) {
            JOptionPane.showMessageDialog(this, "The proxy is not running, so the browser cannot be launched.",
                    "Open browser", JOptionPane.WARNING_MESSAGE);
            return;
        }
        opensuite.proxy.BrowserSetup.open(this, ctx, server);
    }

    /** A flat, icon-only button for the top-right tool strip. */
    private JButton iconButton(Icon icon, String tip, Runnable action) {
        JButton b = new JButton(icon);
        b.setToolTipText(Ui.tip(tip));
        b.setFocusable(false);
        b.setContentAreaFilled(false);
        b.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 4));
        b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        if (action != null) b.addActionListener(e -> action.run());
        return b;
    }

    /** The command palette: every tool, sub-tab and settings page, searchable. */
    private void openPalette(Component anchor) {
        java.util.Map<String, java.util.List<String>> tools = new java.util.LinkedHashMap<>();
        for (int i = 0; i < tabs.getTabCount(); i++) {
            java.util.List<String> subs = new java.util.ArrayList<>();
            if (tabs.getComponentAt(i) instanceof JTabbedPane inner)
                for (int j = 0; j < inner.getTabCount(); j++) subs.add(inner.getTitleAt(j));
            tools.put(plainTitle(tabs.getTitleAt(i)), subs);
        }
        CommandPalette.show(anchor, ctx, tools, (tool, sub) -> {
            selectTool(tool);
            if (sub != null) {
                int i = indexOfTool(tool);
                if (i >= 0 && tabs.getComponentAt(i) instanceof JTabbedPane inner)
                    for (int j = 0; j < inner.getTabCount(); j++) if (inner.getTitleAt(j).equals(sub)) inner.setSelectedIndex(j);
            }
        });
    }

    // ---- unread badges: a dot after a tool's name when something was sent to it while it was not showing ----

    private static final String DOT = " \u2022";
    private static final java.util.regex.Pattern COUNT = java.util.regex.Pattern.compile(" \\(\\d+\\)$");
    /** A tab's title without its dot or its count: the tool's name. */
    static String plainTitle(String t) {
        if (t.endsWith(DOT)) t = t.substring(0, t.length() - DOT.length());
        return COUNT.matcher(t).replaceFirst("");
    }
    private final java.util.Map<String, Integer> toolCounts = new java.util.HashMap<>();
    /** A tool's title with its count of things not yet looked at, when it has one. */
    private String countedTitle(String name) {
        int n = toolCounts.getOrDefault(name, 0);
        return n > 0 ? name + " (" + n + ")" : name;
    }
    /** Show on a tool's tab how many things in it have not been looked at. */
    public void countTool(String name, int count) {
        int i = indexOfTool(name);
        if (i < 0) return;
        if (count > 0) toolCounts.put(name, count); else toolCounts.remove(name);
        boolean dot = tabs.getTitleAt(i).endsWith(DOT);
        String title = countedTitle(name) + (dot ? DOT : "");
        if (!title.equals(tabs.getTitleAt(i))) tabs.setTitleAt(i, title);
    }
    private int indexOfTool(String name) {
        for (int i = 0; i < tabs.getTabCount(); i++) if (plainTitle(tabs.getTitleAt(i)).equals(name)) return i;
        return -1;
    }
    /** Mark a tool as having unread content, unless it is the one on screen. */
    public void badgeTool(String name) {
        int i = indexOfTool(name);
        if (i < 0 || i == tabs.getSelectedIndex() || tabs.getTitleAt(i).endsWith(DOT)) return;
        tabs.setTitleAt(i, tabs.getTitleAt(i) + DOT);
    }
    private void clearBadge(int i) {
        if (i >= 0 && i < tabs.getTabCount() && tabs.getTitleAt(i).endsWith(DOT)) tabs.setTitleAt(i, countedTitle(plainTitle(tabs.getTitleAt(i))));
    }

    private void showProxyHelp() {
        JOptionPane.showMessageDialog(this,
            "1. Set your browser's HTTP and HTTPS proxy to 127.0.0.1 port " + opensuite.proxy.ProxyListener.DEFAULT_PORT + ".\n" +
            "2. Browse to http://opensuite/ and install the CA certificate.\n" +
            "3. Trust it for identifying websites, then reload your target.\n\n" +
            "Traffic appears on the proxy history tab and builds the target site map.",
            "proxy setup", JOptionPane.INFORMATION_MESSAGE);
    }

    /** Menu titles read as headings, like the tab strip: a leading capital. */
    private static String capitalise(String s) {
        return s == null || s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }

    private void addItem(JMenu menu, String label, java.awt.event.ActionListener l) {
        JMenuItem mi = new JMenuItem(Ui.sentence(label));
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(l);
        menu.add(mi);
    }

    public SuiteContext context() { return ctx; }

    /** The name of the tool whose tab is open, in small letters ("proxy"), or empty. */
    public String selectedTool() {
        int i = tabs.getSelectedIndex();
        return i < 0 ? "" : plainTitle(tabs.getTitleAt(i));
    }

    public void selectTool(String name) {
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (plainTitle(tabs.getTitleAt(i)).equals(name)) { tabs.setSelectedIndex(i); return; }
        }
    }

    public void flashTool(String name) {
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (plainTitle(tabs.getTitleAt(i)).equals(name)) {
                final int idx = i;
                tabs.setBackgroundAt(idx, Theme.CONTROL_TINT);
                Timer t = new Timer(900, e -> tabs.setBackgroundAt(idx, null));
                t.setRepeats(false);
                t.start();
                return;
            }
        }
    }

    private double currentScale() {
        String s = System.getProperty("opensuite.scaled");
        if (s != null) try { return Double.parseDouble(s); } catch (Exception ignored) {}
        return UiScale.desired();
    }

    /** Apply a new scale: save the project first, then relaunch to apply it. */
    private void relaunchScaled(double scale) {
        if (Math.abs(UiScale.clamp(scale) - currentScale()) < 0.001) return;   // already that size: nothing to restart for
        Restart.ask(this, ctx, "the new text size", () -> UiScale.changeTo(scale, Restart.arguments(ctx)), null);
    }

    /** A frame without the desktop's title bar must be told not to cover the desktop's panels. */
    @Override public synchronized void setExtendedState(int state) {
        if ((state & MAXIMIZED_BOTH) == MAXIMIZED_BOTH && isUndecorated()) {
            setMaximizedBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
        }
        super.setExtendedState(state);
    }

    /** Kept for call-site compatibility; the JVM now handles scaling. */
    public void refitAfterScale() {
        if (getExtendedState() == Frame.MAXIMIZED_BOTH) { validate(); repaint(); return; }
        Rectangle screen = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getMaximumWindowBounds();
        int w = Math.min(getWidth(), screen.width);
        int h = Math.min(getHeight(), screen.height);
        setSize(w, h);
        validate();
        repaint();
    }

    /**
     * Close the application: at once when nothing would be lost, and after a
     * question when a scan is running or the project is in no file. The
     * question is drawn inside this window ({@link ExitPrompt}), never as a
     * window of its own, which a desktop may keep hidden underneath.
     */
    private void confirmExit() {
        boolean scanning = false;
        for (opensuite.core.ScanTask t : ctx.tasks())
            // A scan has sites of its own; the two live tasks, which never finish, have none.
            if (t.sites().size() > 0 && t.state() != opensuite.core.ScanTask.State.FINISHED) scanning = true;
        boolean unsaved = ctx.projectFile() == null && (!ctx.store().all().isEmpty() || !ctx.issues().isEmpty());
        String risk = ExitPrompt.risk(scanning, unsaved);
        if (risk.isEmpty() || ctx.settings().getBool("suite.noConfirmClose", false)) { exitNow(); return; }
        ExitPrompt.ask(this, risk, this::exitNow);
    }

    private void exitNow() {
        {
            // A session bound to a project file is written to it on the way out,
            // so nothing done since the last autosave is lost.
            java.io.File project = ctx.projectFile();
            if (project != null) {
                setStatus("Saving project " + project.getName() + "...");
                try {
                    StateIO.save(ctx, project);
                } catch (Exception e) {
                    int again = JOptionPane.showConfirmDialog(this,
                            "Could not save the project to " + project.getName() + ":\n" + e.getMessage()
                            + "\n\nExit anyway and discard unsaved work?",
                            "Save project", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (again != JOptionPane.YES_OPTION) { setStatus(" "); return; }
                }
            }
            for (ToolModule m : modules) {
                try { m.shutdown(); }
                catch (Throwable e) {
                    // Exit continues regardless, but a tool that failed to shut
                    // down (a listener still bound, a socket left open, or an
                    // Error out of its own code) is worth a trace rather than
                    // silence, and must not keep the tools after it from
                    // shutting down or hold the window open.
                    Debug.error("tool '" + m.name() + "' failed to shut down", e);
                }
            }
            AutoBackup.onCleanExit(ctx);
            dispose();
            System.exit(0);
        }
    }
}