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.

12.5 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;

/**
 * The window's own title bar, with the top-level menu merged into it: the
 * application icon, the menus, the window title centred across the bar and
 * the minimise, maximise and close buttons at the right. It replaces the
 * desktop's title bar (the frame is undecorated), so it also does what that
 * bar did: drag to move, double click to maximise, and drag any window edge
 * to resize. Settings > Display turns the merge off, which puts the
 * desktop's own title bar and a separate menu strip back.
 */
public final class TitleBar extends JPanel {
    static final int HEIGHT = 35;
    private static final int EDGE = 5;

    private final JFrame frame;
    private final JLabel title = new JLabel();
    private final JComponent west;
    private final JComponent east;

    /** Make {@code frame} draw its own title bar. Call before the frame is first shown. */
    public static void install(JFrame frame, JMenuBar menu) {
        frame.setUndecorated(true);
        frame.getRootPane().setBorder(BorderFactory.createLineBorder(new Color(0x2B, 0x2B, 0x2B)));
        TitleBar bar = new TitleBar(frame, menu);
        frame.getContentPane().add(bar, BorderLayout.NORTH);
        bar.installResizing();
    }

    /** A secondary window's bar: the icon, the title beside it and the three buttons; 34px. */
    public static void install(JFrame frame) {
        frame.setUndecorated(true);
        frame.getRootPane().setBorder(BorderFactory.createLineBorder(new Color(0x2B, 0x2B, 0x2B)));
        TitleBar bar = new TitleBar(frame, null);
        frame.getContentPane().add(bar, BorderLayout.NORTH);
        bar.installResizing();
    }

    private final boolean plain;

    private TitleBar(JFrame frame, JMenuBar menu) {
        super(null);
        this.frame = frame;
        this.plain = menu == null;
        setBackground(Theme.BG);

        JLabel icon = new JLabel(new ImageIcon(AppIcon.images().get(0).getScaledInstance(16, 16, Image.SCALE_SMOOTH)));
        icon.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 5));
        JPanel w = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        w.setOpaque(false);
        w.add(icon);
        if (menu != null) {
            menu.setOpaque(false);
            menu.setBorder(BorderFactory.createEmptyBorder());
            w.add(menu);
        }
        west = centred(w);

        JPanel e = new JPanel(new GridLayout(1, 3));
        e.setOpaque(false);
        e.add(new WindowButton(0));
        e.add(new WindowButton(1));
        e.add(new WindowButton(2));
        east = e;

        title.setFont(Ui.PLAIN);
        title.setForeground(Theme.TEXT);
        title.setText(frame.getTitle());
        frame.addPropertyChangeListener("title", ev -> { title.setText(frame.getTitle()); revalidate(); repaint(); });

        add(west);
        add(title);
        add(east);

        MouseAdapter move = new MouseAdapter() {
            private Point grab;
            @Override public void mousePressed(MouseEvent ev) {
                grab = SwingUtilities.isLeftMouseButton(ev) && !maximised() ? ev.getLocationOnScreen() : null;
                if (grab != null) { Point p = frame.getLocation(); grab.translate(-p.x, -p.y); }
            }
            @Override public void mouseDragged(MouseEvent ev) {
                if (grab == null) return;
                Point s = ev.getLocationOnScreen();
                frame.setLocation(s.x - grab.x, s.y - grab.y);
            }
            @Override public void mouseClicked(MouseEvent ev) {
                if (ev.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(ev)) toggleMaximise();
            }
        };
        for (JComponent c : new JComponent[] { this, title, west, w, icon }) {
            c.addMouseListener(move);
            c.addMouseMotionListener(move);
        }
    }

    private static JComponent centred(JComponent c) {
        JPanel p = new JPanel(new GridBagLayout());
        p.setOpaque(false);
        p.add(c);
        return p;
    }

    @Override public Dimension getPreferredSize() { return new Dimension(200, plain ? HEIGHT - 1 : HEIGHT); }

    @Override public void doLayout() {
        int w = getWidth(), h = getHeight();
        Dimension dw = west.getPreferredSize();
        west.setBounds(0, 0, dw.width, h);
        int ew = 3 * (plain ? HEIGHT - 1 : HEIGHT);
        east.setBounds(w - ew, 0, ew, h);
        // The title is centred on the window, and gives way to the menus and
        // the buttons only when the window is too narrow for that.
        Dimension dt = title.getPreferredSize();
        if (plain) { title.setBounds(dw.width + 3, 0, Math.max(0, Math.min(dt.width, w - ew - dw.width - 11)), h); return; }
        int room = Math.max(0, w - ew - dw.width - 16);
        int tw = Math.min(dt.width, room);
        int x = Math.max(dw.width + 8, Math.min((w - tw) / 2, w - ew - 8 - tw));
        title.setBounds(x, 0, tw, h);
    }

    private boolean maximised() { return (frame.getExtendedState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH; }

    private void toggleMaximise() {
        if (maximised()) {
            frame.setExtendedState(frame.getExtendedState() & ~Frame.MAXIMIZED_BOTH);
        } else {
            // An undecorated frame would otherwise cover the desktop's panels.
            GraphicsConfiguration gc = frame.getGraphicsConfiguration();
            Rectangle b = gc.getBounds();
            Insets in = Toolkit.getDefaultToolkit().getScreenInsets(gc);
            frame.setMaximizedBounds(new Rectangle(in.left, in.top, b.width - in.left - in.right, b.height - in.top - in.bottom));
            frame.setExtendedState(frame.getExtendedState() | Frame.MAXIMIZED_BOTH);
        }
    }

    /** Minimise (0), maximise or restore (1), close (2). */
    private final class WindowButton extends JComponent {
        private final int kind;
        private boolean over;
        WindowButton(int kind) {
            this.kind = kind;
            setToolTipText(kind == 0 ? "Minimise" : kind == 1 ? "Maximise" : "Close");
            addMouseListener(new MouseAdapter() {
                @Override public void mouseEntered(MouseEvent e) { over = true; repaint(); }
                @Override public void mouseExited(MouseEvent e) { over = false; repaint(); }
                @Override public void mouseReleased(MouseEvent e) {
                    if (!SwingUtilities.isLeftMouseButton(e) || !contains(e.getPoint())) return;
                    over = false;
                    repaint();
                    if (kind == 0) frame.setExtendedState(frame.getExtendedState() | Frame.ICONIFIED);
                    else if (kind == 1) toggleMaximise();
                    else frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
                }
            });
        }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            if (over) {
                g2.setColor(kind == 2 ? new Color(0xE8, 0x11, 0x23) : Theme.SURFACE_2);
                g2.fillRect(0, 0, getWidth(), getHeight());
            }
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2.setColor(over && kind == 2 ? Color.WHITE : Theme.TEXT);
            g2.setStroke(new BasicStroke(1.2f));
            double cx = getWidth() / 2.0, cy = getHeight() / 2.0, r = plain ? 4 : 4.5;
            if (kind == 0) g2.draw(new Line2D.Double(cx - r, cy, cx + r, cy));
            else if (kind == 1) g2.draw(new Rectangle2D.Double(cx - r + 0.5, cy - r + 0.5, 2 * r - 1, 2 * r - 1));
            else {
                g2.draw(new Line2D.Double(cx - r, cy - r, cx + r, cy + r));
                g2.draw(new Line2D.Double(cx - r, cy + r, cx + r, cy - r));
            }
            g2.dispose();
        }
    }

    // ---- resizing from the window's edges ----

    private int resizing;        // a Cursor constant while a resize drag is in progress, else 0
    private Rectangle startBounds;
    private Point startMouse;
    private boolean cursorSet;

    private void installResizing() {
        Toolkit.getDefaultToolkit().addAWTEventListener(ev -> {
            if (!(ev instanceof MouseEvent e) || !frame.isShowing()) return;
            if (!(e.getSource() instanceof Component src) || SwingUtilities.getWindowAncestor(src) != frame && src != frame) return;
            Point s;
            try { s = e.getLocationOnScreen(); } catch (IllegalComponentStateException x) { return; }
            switch (e.getID()) {
                case MouseEvent.MOUSE_MOVED -> {
                    int c = maximised() ? 0 : edgeAt(s);
                    if (c != 0) showCursor(c);
                    else if (cursorSet && resizing == 0) hideCursor();
                }
                case MouseEvent.MOUSE_PRESSED -> {
                    int c = maximised() || !SwingUtilities.isLeftMouseButton(e) ? 0 : edgeAt(s);
                    if (c != 0) { resizing = c; startBounds = frame.getBounds(); startMouse = s; e.consume(); }
                }
                case MouseEvent.MOUSE_DRAGGED -> {
                    if (resizing != 0) { resizeTo(s); e.consume(); }
                }
                case MouseEvent.MOUSE_RELEASED -> {
                    if (resizing != 0) {
                        resizing = 0;
                        e.consume();
                        if (edgeAt(s) == 0) hideCursor();
                    }
                }
                default -> { }
            }
        }, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
    }

    /** The glass pane carries the resize cursor and, while it shows, takes the click. */
    private void showCursor(int cursor) {
        JComponent glass = (JComponent) frame.getGlassPane();
        if (glass.getClientProperty("opensuite.glassSwallows") == null) {
            glass.putClientProperty("opensuite.glassSwallows", Boolean.TRUE);
            glass.addMouseListener(new MouseAdapter() { });
            glass.addMouseMotionListener(new MouseAdapter() { });
        }
        glass.putClientProperty(opensuite.ui.theme.FlatSplitPaneUI.GLASS_OWNER, "edge");
        glass.setCursor(Cursor.getPredefinedCursor(cursor));
        glass.setVisible(true);
        cursorSet = true;
    }

    private void hideCursor() {
        JComponent glass = (JComponent) frame.getGlassPane();
        glass.putClientProperty(opensuite.ui.theme.FlatSplitPaneUI.GLASS_OWNER, null);
        glass.setVisible(false);
        glass.setCursor(null);
        cursorSet = false;
    }

    private int edgeAt(Point screen) {
        Rectangle b = frame.getBounds();
        if (!b.contains(screen)) return 0;
        boolean l = screen.x - b.x < EDGE, r = b.x + b.width - screen.x <= EDGE;
        boolean t = screen.y - b.y < EDGE, d = b.y + b.height - screen.y <= EDGE;
        if (t && l) return Cursor.NW_RESIZE_CURSOR;
        if (t && r) return Cursor.NE_RESIZE_CURSOR;
        if (d && l) return Cursor.SW_RESIZE_CURSOR;
        if (d && r) return Cursor.SE_RESIZE_CURSOR;
        if (l) return Cursor.W_RESIZE_CURSOR;
        if (r) return Cursor.E_RESIZE_CURSOR;
        if (t) return Cursor.N_RESIZE_CURSOR;
        if (d) return Cursor.S_RESIZE_CURSOR;
        return 0;
    }

    private void resizeTo(Point s) {
        int dx = s.x - startMouse.x, dy = s.y - startMouse.y;
        Rectangle b = new Rectangle(startBounds);
        Dimension min = new Dimension(640, 400);
        boolean west = resizing == Cursor.W_RESIZE_CURSOR || resizing == Cursor.NW_RESIZE_CURSOR || resizing == Cursor.SW_RESIZE_CURSOR;
        boolean east = resizing == Cursor.E_RESIZE_CURSOR || resizing == Cursor.NE_RESIZE_CURSOR || resizing == Cursor.SE_RESIZE_CURSOR;
        boolean north = resizing == Cursor.N_RESIZE_CURSOR || resizing == Cursor.NW_RESIZE_CURSOR || resizing == Cursor.NE_RESIZE_CURSOR;
        boolean south = resizing == Cursor.S_RESIZE_CURSOR || resizing == Cursor.SW_RESIZE_CURSOR || resizing == Cursor.SE_RESIZE_CURSOR;
        if (east) b.width = Math.max(min.width, startBounds.width + dx);
        if (south) b.height = Math.max(min.height, startBounds.height + dy);
        if (west) { int w = Math.max(min.width, startBounds.width - dx); b.x = startBounds.x + startBounds.width - w; b.width = w; }
        if (north) { int h = Math.max(min.height, startBounds.height - dy); b.y = startBounds.y + startBounds.height - h; b.height = h; }
        frame.setBounds(b);
        frame.validate();
    }
}