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.

10.6 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import java.awt.*;

/**
 * The numbered-tab strip Repeater and Intruder use: each tab carries a close
 * mark, a "+" tab opens a new one, and a search mark and a collapse chevron
 * sit at the right end of the row.
 */
public final class TabStrip {

    /** The shallow upward chevron that folds the strip away: 11 by 7. */
    private static final Icon FOLD = new Icon() {
        @Override public int getIconWidth() { return 11; }
        @Override public int getIconHeight() { return 7; }
        @Override public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2.setColor(Theme.TEXT);
            g2.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
            p.moveTo(x + 0.9, y + 6.1); p.lineTo(x + 5.5, y + 1.0); p.lineTo(x + 10.1, y + 6.1);
            g2.draw(p);
            g2.dispose();
        }
    };
    private TabStrip() {}

    /** Give the tab at {@code index} a title with a close mark. */
    public static void closable(JTabbedPane tabs, int index) {
        if (index < 0) return;
        String title = tabs.getTitleAt(index);
        Component comp = tabs.getComponentAt(index);
        JLabel l = new JLabel(title);
        l.setFont(Ui.PLAIN);
        l.setForeground(Theme.TAB_TEXT_ON);
        JButton x = Glyphs.button(Glyphs.trimmed(Glyphs.cross(13, Theme.TEXT)), "Close tab", () -> {
            int i = tabs.indexOfComponent(comp);
            if (i >= 0 && realTabCount(tabs) > 1) tabs.remove(i);
        });
        x.setBorder(BorderFactory.createEmptyBorder());
        // A pill is its title plus room for the close mark, whether or not the
        // mark is showing: only the selected tab shows it, and the others centre
        // their title in the same width.
        JPanel head = new JPanel(null) {
            @Override public Dimension getPreferredSize() {
                return new Dimension(Math.max(44, l.getPreferredSize().width + 37), opensuite.ui.theme.PillTabbedPaneUI.HEIGHT);
            }
            @Override public void doLayout() {
                boolean sel = tabs.indexOfTabComponent(this) == tabs.getSelectedIndex();
                Dimension d = l.getPreferredSize();
                int h = getHeight(), w = getWidth();
                x.setVisible(sel);
                l.setBounds(sel ? 7 : (w - d.width) / 2 - 1, (h - 3 - d.height) / 2 + 2, d.width, d.height);
                Dimension xd = x.getPreferredSize();
                x.setBounds(w - 17, 9, xd.width, xd.height);
            }
        };
        head.setOpaque(false);
        head.add(l);
        head.add(x);
        if (tabs.getClientProperty(SELECTION_KEY) == null) {
            tabs.putClientProperty(SELECTION_KEY, Boolean.TRUE);
            tabs.addChangeListener(e -> {
                for (int k = 0; k < tabs.getTabCount(); k++) {
                    Component c = tabs.getTabComponentAt(k);
                    if (c != null) { c.invalidate(); c.validate(); c.repaint(); }
                }
            });
        }
        tabs.setTabComponentAt(index, head);
        // Selecting the tab via its header.
        head.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) {
                int i = tabs.indexOfComponent(comp);
                if (i >= 0) tabs.setSelectedIndex(i);
                popup(e);
            }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { popup(e); }
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
                    Object r = tabs.getClientProperty(RENAME_KEY);
                    if (r instanceof java.util.function.Consumer<?> c) accept(c, comp);
                }
            }
            private void popup(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                Object f = tabs.getClientProperty(MENU_KEY);
                if (f instanceof java.util.function.Function<?, ?> fn) {
                    Object m = apply(fn, comp);
                    if (m instanceof JPopupMenu menu) menu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
    }

    private static final String MENU_KEY = "opensuite.tabMenu";
    private static final String SELECTION_KEY = "opensuite.tabSelection";
    private static final String RENAME_KEY = "opensuite.tabRename";

    @SuppressWarnings("unchecked")
    private static Object apply(java.util.function.Function<?, ?> fn, Component comp) {
        return ((java.util.function.Function<Component, Object>) fn).apply(comp);
    }

    @SuppressWarnings("unchecked")
    private static void accept(java.util.function.Consumer<?> c, Component comp) {
        ((java.util.function.Consumer<Component>) c).accept(comp);
    }

    /**
     * Give every closable tab of a pane a right-click menu, built for the tab
     * that was clicked, and an action for a double click on its title.
     */
    public static void tabMenu(JTabbedPane tabs, java.util.function.Function<Component, JPopupMenu> menu,
                               java.util.function.Consumer<Component> onDoubleClick) {
        tabs.putClientProperty(MENU_KEY, menu);
        tabs.putClientProperty(RENAME_KEY, onDoubleClick);
    }

    /** Rename a closable tab: the title and the label drawn in its header. */
    public static void rename(JTabbedPane tabs, int index, String title) {
        if (index < 0 || index >= tabs.getTabCount()) return;
        tabs.setTitleAt(index, title);
        if (tabs.getTabComponentAt(index) instanceof JPanel head) {
            for (Component c : head.getComponents()) {
                if (c instanceof JLabel l) { l.setText(title); break; }
            }
            head.revalidate();
        }
        tabs.revalidate();
        tabs.repaint();
    }

    /** The number of tabs, not counting the "+" tab. */
    public static int count(JTabbedPane tabs) { return realTabCount(tabs); }

    private static int realTabCount(JTabbedPane tabs) {
        int n = 0;
        for (int i = 0; i < tabs.getTabCount(); i++) if (!"+".equals(tabs.getTitleAt(i))) n++;
        return n;
    }

    /**
     * Wrap a tab pane with the "+" tab and the right-hand marks. {@code onNew}
     * runs when the "+" tab is chosen; the new tab is expected to select itself.
     */
    public static JComponent wrap(JTabbedPane tabs, Runnable onNew) {
        // The "+" tab stays last; choosing it opens a new tab instead.
        JPanel plusBody = new JPanel();
        tabs.addTab("+", plusBody);
        tabs.setUI(new opensuite.ui.theme.PillTabbedPaneUI());
        // A theme switch reinstalls the default delegate; put the pills back.
        tabs.addPropertyChangeListener("UI", e -> {
            if (!(tabs.getUI() instanceof opensuite.ui.theme.PillTabbedPaneUI)) tabs.setUI(new opensuite.ui.theme.PillTabbedPaneUI());
        });
        JLabel plus = new JLabel(Glyphs.trimmed(Glyphs.plus(15, Theme.TEXT)));
        plus.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
        tabs.setTabComponentAt(tabs.getTabCount() - 1, plus);
        tabs.addChangeListener(e -> {
            int i = tabs.getSelectedIndex();
            if (i >= 0 && tabs.getComponentAt(i) == plusBody) {
                SwingUtilities.invokeLater(() -> {
                    onNew.run();
                    // Keep "+" last.
                    int p = tabs.indexOfComponent(plusBody);
                    if (p >= 0 && p != tabs.getTabCount() - 1) {
                        tabs.remove(p);
                        tabs.addTab("+", plusBody);
                        tabs.setTabComponentAt(tabs.getTabCount() - 1, plus);
                    }
                    if (tabs.getSelectedComponent() == plusBody && tabs.getTabCount() > 1) tabs.setSelectedIndex(tabs.getTabCount() - 2);
                });
            }
        });
        // Any tab added later also keeps "+" at the end.
        tabs.addContainerListener(new java.awt.event.ContainerAdapter() {
            @Override public void componentAdded(java.awt.event.ContainerEvent e) {
                int p = tabs.indexOfComponent(plusBody);
                if (p >= 0 && p != tabs.getTabCount() - 1) SwingUtilities.invokeLater(() -> {
                    int q = tabs.indexOfComponent(plusBody);
                    if (q >= 0 && q != tabs.getTabCount() - 1) {
                        Component sel = tabs.getSelectedComponent();
                        tabs.remove(q);
                        tabs.addTab("+", plusBody);
                        tabs.setTabComponentAt(tabs.getTabCount() - 1, plus);
                        if (sel != null && sel != plusBody) tabs.setSelectedComponent(sel);
                    }
                });
            }
        });

        final JPanel marks = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        marks.setOpaque(false);
        JButton find = Glyphs.button(Glyphs.trimmed(Glyphs.searchLeft(16, Theme.TEXT)), "Search tabs", () -> {
            String q = JOptionPane.showInputDialog(tabs, "Tab name or number:");
            if (q == null || q.isBlank()) return;
            for (int i = 0; i < tabs.getTabCount(); i++) if (tabs.getTitleAt(i).toLowerCase().contains(q.toLowerCase())) { tabs.setSelectedIndex(i); return; }
        });
        JButton fold = Glyphs.button(FOLD, "Collapse the tab strip", () -> tabs.setTabPlacement(tabs.getTabPlacement() == JTabbedPane.TOP ? JTabbedPane.BOTTOM : JTabbedPane.TOP));
        find.setBorder(BorderFactory.createEmptyBorder());
        fold.setBorder(BorderFactory.createEmptyBorder());
        marks.add(find);
        marks.add(Box.createHorizontalStrut(9));
        marks.add(fold);

        final JLayeredPane layer = new JLayeredPane();
        layer.setLayout(null);
        layer.add(tabs, JLayeredPane.DEFAULT_LAYER);
        layer.add(marks, 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 d = marks.getPreferredSize();
                marks.setBounds(w - d.width - 13, Math.max(0, (46 - d.height) / 2), d.width, d.height);
            }
        });
        return layer;
    }
}