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.

4.5 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

/**
 * The editor keyboard shortcuts the reference provides on its request and
 * response editors: undo and redo, and delete-line. Native Swing already gives
 * word and paragraph navigation, select-all and clipboard actions, so only the
 * ones Swing lacks are added here.
 *
 * <p>The text transforms are pure static methods so they can be tested without
 * a display.
 */
public final class EditorKeys {
    private EditorKeys() {}

    private static final int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();

    /** A component's undo history, and while set, the group its edits gather in instead. */
    private static final String UNDO = "opensuite.undo", GROUP = "opensuite.undo.group";

    /**
     * Make the edits {@code change} makes to {@code c} one step in its undo
     * history, so a single Ctrl+Z takes them all back.
     */
    public static void asOneEdit(JTextComponent c, Runnable change) {
        CompoundEdit group = new CompoundEdit();
        c.putClientProperty(GROUP, group);
        try {
            change.run();
        } finally {
            c.putClientProperty(GROUP, null);
            group.end();
            if (group.canUndo() && c.getClientProperty(UNDO) instanceof UndoManager undo) undo.addEdit(group);
        }
    }

    /** Install undo/redo (Ctrl+Z / Ctrl+Y) and delete-line (Ctrl+D) on an editable component. */
    public static void install(JTextComponent c) {
        if (!c.isEditable()) return;

        UndoManager undo = new UndoManager();
        undo.setLimit(500);
        c.getDocument().addUndoableEditListener(e -> {
            if (c.getClientProperty(GROUP) instanceof CompoundEdit group) group.addEdit(e.getEdit());
            else undo.addEdit(e.getEdit());
        });
        c.putClientProperty(UNDO, undo);

        InputMap im = c.getInputMap();
        ActionMap am = c.getActionMap();

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, MASK), "opensuite-undo");
        am.put("opensuite-undo", new AbstractAction() {
            @Override public void actionPerformed(ActionEvent e) { if (undo.canUndo()) undo.undo(); }
        });
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, MASK), "opensuite-redo");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, MASK | KeyEvent.SHIFT_DOWN_MASK), "opensuite-redo");
        am.put("opensuite-redo", new AbstractAction() {
            @Override public void actionPerformed(ActionEvent e) { if (undo.canRedo()) undo.redo(); }
        });

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, MASK), "opensuite-delete-line");
        am.put("opensuite-delete-line", new AbstractAction() {
            @Override public void actionPerformed(ActionEvent e) {
                try {
                    int caret = c.getCaretPosition();
                    Result r = deleteLine(c.getText(), caret);
                    c.setText(r.text());
                    c.setCaretPosition(Math.min(r.caret(), c.getText().length()));
                } catch (RuntimeException ignored) {
                    // A document in an odd state must not propagate out of a key press.
                }
            }
        });
    }

    /** The text and caret after a transform. */
    public record Result(String text, int caret) {}

    /**
     * Delete the line the caret sits on, including its trailing newline, and
     * leave the caret at the start of what was the next line.
     */
    public static Result deleteLine(String text, int caret) {
        if (text == null) return new Result("", 0);
        caret = Math.max(0, Math.min(caret, text.length()));
        int start = text.lastIndexOf('\n', caret - 1) + 1;   // first char of this line
        int end = text.indexOf('\n', caret);                 // the line's newline, or -1
        int cut = end < 0 ? text.length() : end + 1;         // delete the newline too
        String out = text.substring(0, start) + text.substring(cut);
        // Keep the caret at the same column position on the line that moves up,
        // clamped to that line's length.
        int col = caret - start;
        int nextEnd = out.indexOf('\n', start);
        int nextLineLen = (nextEnd < 0 ? out.length() : nextEnd) - start;
        int newCaret = start + Math.min(col, Math.max(0, nextLineLen));
        return new Result(out, Math.min(newCaret, out.length()));
    }
}