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.1 KB
Raw Blame
package opensuite.ui.settings;

import opensuite.core.Settings;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * A small editable table persisted in one settings key: rows are lines, cells
 * are tab-separated. An optional leading "Enabled" column is a checkbox. Add
 * and Edit open a form built from the column names; extra buttons (Up, Down,
 * Paste URL, Load ...) can be asked for. Used by every settings table that has
 * no model of its own: platform authentication, DNS overrides, certificates,
 * API keys, scheduled tasks.
 */
public final class KeyedTable extends JPanel {

    private final Settings settings;
    private final String key;
    private final String[] cols;
    private final boolean enabledColumn;
    private final List<String[]> rows = new ArrayList<>();
    /**
     * Built in the constructor, not here. A field initialiser runs before the
     * constructor body, so a model created at this point would be handed to a
     * JTable that immediately asks it how many columns it has, while the
     * column names were still null. Every settings page carrying one of these
     * tables threw on the way open.
     */
    private final AbstractTableModel model;
    private final JTable table;

    /**
     * @param cols          column names; if the first is "Enabled" it becomes a checkbox column
     * @param buttons       which buttons to show, from: Add, Edit, Remove, Up, Down, Paste URL, Load ...
     */
    public KeyedTable(Settings settings, String key, String[] cols, int height, String... buttons) {
        super(new BorderLayout(8, 0));
        this.settings = settings;
        this.key = key;
        this.cols = cols;
        this.enabledColumn = cols.length > 0 && "Enabled".equals(cols[0]);
        this.model = new AbstractTableModel() {
            @Override public int getRowCount() { return rows.size(); }
            @Override public int getColumnCount() { return KeyedTable.this.cols.length; }
            @Override public String getColumnName(int c) { return KeyedTable.this.cols[c]; }
            @Override public Class<?> getColumnClass(int c) { return enabledColumn && c == 0 ? Boolean.class : String.class; }
            @Override public boolean isCellEditable(int r, int c) { return enabledColumn && c == 0; }
            @Override public Object getValueAt(int r, int c) {
                String v = c < rows.get(r).length ? rows.get(r)[c] : "";
                return enabledColumn && c == 0 ? !"false".equals(v) : v;
            }
            @Override public void setValueAt(Object v, int r, int c) {
                if (enabledColumn && c == 0) { rows.get(r)[0] = String.valueOf(Boolean.TRUE.equals(v)); save(); }
            }
        };
        this.table = new JTable(model);
        setOpaque(false);
        load();
        Ui.styleTable(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        List<JButton> bs = new ArrayList<>();
        for (String b : buttons.length == 0 ? new String[]{"Add", "Edit", "Remove"} : buttons) {
            JButton btn = Ui.button(b);
            switch (b) {
                case "Add" -> btn.addActionListener(e -> { String[] r = adder != null ? adder.get() : form(null); if (r != null) { rows.add(r); save(); model.fireTableDataChanged(); } });
                case "Edit" -> btn.addActionListener(e -> { int i = table.getSelectedRow(); if (i >= 0) { String[] r = form(rows.get(i)); if (r != null) { rows.set(i, r); save(); model.fireTableDataChanged(); } } });
                case "Remove" -> btn.addActionListener(e -> { int i = table.getSelectedRow(); if (i >= 0) { rows.remove(i); save(); model.fireTableDataChanged(); } });
                case "Up" -> btn.addActionListener(e -> move(-1));
                case "Down" -> btn.addActionListener(e -> move(1));
                case "Paste URL" -> btn.addActionListener(e -> {
                    try {
                        Object t = Toolkit.getDefaultToolkit().getSystemClipboard().getData(java.awt.datatransfer.DataFlavor.stringFlavor);
                        if (t != null) { String[] r = blank(); r[enabledColumn ? 1 : 0] = String.valueOf(t).trim(); rows.add(r); save(); model.fireTableDataChanged(); }
                    } catch (Exception ignore) { }
                });
                case "Load ..." -> btn.addActionListener(e -> {
                    JFileChooser fc = new opensuite.ui.FileChooser();
                    if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
                    try {
                        for (String line : java.nio.file.Files.readAllLines(fc.getSelectedFile().toPath())) {
                            if (line.isBlank()) continue;
                            String[] r = blank(); r[enabledColumn ? 1 : 0] = line.strip(); rows.add(r);
                        }
                        save(); model.fireTableDataChanged();
                    } catch (java.io.IOException ex) { JOptionPane.showMessageDialog(this, "Could not read the file: " + ex.getMessage()); }
                });
                default -> { }
            }
            bs.add(btn);
        }
        this.buttonList = bs;
        this.scroll = Ui.scroll(table);
        this.height = height < 150 ? 150 : height;
        table.putClientProperty(Ui.KEEP_WIDTHS, Boolean.TRUE);
        arrange();
    }

    private final List<JButton> buttonList;
    private final JScrollPane scroll;
    private int width = 540, height, buttonWidth = 87, pitch = 27, gap = 5;

    private final java.util.Set<String> locked = new java.util.HashSet<>();

    /** Columns the form neither shows nor changes: they are set when the row is made. */
    public KeyedTable lock(String... columns) { locked.addAll(java.util.Arrays.asList(columns)); return this; }

    private java.util.function.Supplier<String[]> adder;

    /** Make new rows some other way than the form: the supplier returns the row, or null to add nothing. */
    public KeyedTable adder(java.util.function.Supplier<String[]> adder) { this.adder = adder; return this; }

    /** What the buttons say, in the order they were asked for. */
    public KeyedTable labels(String... texts) {
        for (int i = 0; i < texts.length && i < buttonList.size(); i++) buttonList.get(i).setText(texts[i]);
        return this;
    }

    /** The table's size on the page; its arrow doubles the height to show more rows. */
    public KeyedTable size(int width, int height) { this.width = width; this.height = height; arrange(); return this; }

    /** How wide the buttons are, how far apart their tops stand, and how far the table is from them. */
    public KeyedTable buttons(int width, int pitch, int gap) { this.buttonWidth = width; this.pitch = pitch; this.gap = gap; arrange(); return this; }

    /** The widths of the columns as shown, in order. */
    public KeyedTable widths(int... widths) { Ui.exactWidths(table, widths); return this; }

    /** Keep a column out of the table; it is still asked for when a row is added or edited. */
    /** What a double-click on a row does; it is given the row's cells. */
    public KeyedTable onOpen(java.util.function.Consumer<String[]> open) {
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                if (e.getClickCount() == 2 && row >= 0) open.accept(rows.get(table.convertRowIndexToModel(row)));
            }
        });
        return this;
    }

    /** Read the rows again from the settings, after something else changed them. */
    public void reload() { load(); model.fireTableDataChanged(); }

    public KeyedTable hide(String column) {
        for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
            javax.swing.table.TableColumn c = table.getColumnModel().getColumn(i);
            if (column.equals(cols[c.getModelIndex()])) { table.removeColumn(c); break; }
        }
        return this;
    }

    private void arrange() {
        removeAll();
        // A table that is only read has no buttons beside it.
        if (buttonList.isEmpty()) {
            setLayout(new BorderLayout());
            add(opensuite.ui.Sections.withArrow(scroll, width, height), BorderLayout.CENTER);
            return;
        }
        setLayout(new BorderLayout(gap, 0));
        JPanel column = new JPanel(new GridLayout(buttonList.size(), 1, 0, pitch - 22));
        column.setOpaque(false);
        for (JButton b : buttonList) { b.setPreferredSize(new Dimension(buttonWidth + 4 * Ui.fontGrowth(), Ui.tall(22))); column.add(b); }
        JPanel top = new JPanel(new BorderLayout());
        top.setOpaque(false);
        top.add(column, BorderLayout.NORTH);
        add(top, BorderLayout.WEST);
        add(opensuite.ui.Sections.withArrow(scroll, width, height), BorderLayout.CENTER);
    }

    private String[] blank() {
        String[] r = new String[cols.length];
        java.util.Arrays.fill(r, "");
        if (enabledColumn) r[0] = "true";
        return r;
    }

    private void move(int d) {
        int i = table.getSelectedRow(), to = i + d;
        if (i < 0 || to < 0 || to >= rows.size()) return;
        String[] r = rows.remove(i);
        rows.add(to, r);
        save(); model.fireTableDataChanged();
        table.setRowSelectionInterval(to, to);
    }

    private final java.util.Map<String, String[]> choices = new java.util.HashMap<>();

    /** A column whose value is one of a fixed few: the form offers them in a list. */
    public KeyedTable choices(String column, String... values) { choices.put(column, values); return this; }

    private String[] form(String[] editing) {
        int from = enabledColumn ? 1 : 0;
        JComponent[] fields = new JComponent[cols.length];
        java.util.List<Object> formParts = new ArrayList<>();
        for (int c = from; c < cols.length; c++) {
            if (locked.contains(cols[c])) continue;
            String value = editing == null || c >= editing.length ? "" : editing[c];
            if (choices.containsKey(cols[c])) {
                JComboBox<String> box = Ui.combo(choices.get(cols[c]));
                for (String v : choices.get(cols[c])) if (v.equalsIgnoreCase(value)) box.setSelectedItem(v);
                fields[c] = box;
            } else if (cols[c].toLowerCase().contains("password")) {
                JPasswordField pf = Ui.passwordField(value);
                pf.setFont(Ui.PLAIN);
                fields[c] = pf;
            } else {
                fields[c] = Ui.field(value);
            }
            formParts.add(cols[c] + ":");
            formParts.add(fields[c]);
        }
        JPanel f = Ui.form(formParts.toArray());
        f.setBorder(Ui.pad(10, 10, 10, 10));
        int ok = JOptionPane.showConfirmDialog(this, f, (editing == null ? "Add" : "Edit") + " entry", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return null;
        String[] r = blank();
        if (editing != null && enabledColumn) r[0] = editing[0];
        for (int c = from; c < cols.length; c++) {
            if (fields[c] == null) { r[c] = editing != null && c < editing.length ? editing[c] : ""; continue; }
            r[c] = fields[c] instanceof JPasswordField pf ? new String(pf.getPassword())
                    : fields[c] instanceof JComboBox<?> box ? String.valueOf(box.getSelectedItem())
                    : ((JTextField) fields[c]).getText().strip();
        }
        return r;
    }

    private void load() {
        rows.clear();
        String v = settings.get(key, "");
        if (v.isEmpty()) return;
        for (String line : v.split("\n")) {
            if (line.isEmpty()) continue;
            String[] cells = line.split("\t", -1);
            String[] r = blank();
            System.arraycopy(cells, 0, r, 0, Math.min(cells.length, r.length));
            rows.add(r);
        }
    }

    private void save() {
        StringBuilder sb = new StringBuilder();
        for (String[] r : rows) sb.append(String.join("\t", r).replace("\n", " ")).append('\n');
        settings.set(key, sb.toString());
    }

    public List<String[]> rows() { return new ArrayList<>(rows); }
    public JTable table() { return table; }
}