001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2025 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.gui;
021
022import java.awt.Component;
023import java.awt.Dimension;
024import java.awt.FontMetrics;
025import java.awt.event.ActionEvent;
026import java.awt.event.MouseAdapter;
027import java.awt.event.MouseEvent;
028import java.io.Serial;
029import java.util.ArrayDeque;
030import java.util.ArrayList;
031import java.util.Collection;
032import java.util.Deque;
033import java.util.EventObject;
034import java.util.List;
035import java.util.stream.Collectors;
036
037import javax.swing.AbstractAction;
038import javax.swing.Action;
039import javax.swing.JTable;
040import javax.swing.JTextArea;
041import javax.swing.JTree;
042import javax.swing.KeyStroke;
043import javax.swing.LookAndFeel;
044import javax.swing.table.TableCellEditor;
045import javax.swing.tree.TreePath;
046
047import com.puppycrawl.tools.checkstyle.api.DetailAST;
048import com.puppycrawl.tools.checkstyle.utils.XpathUtil;
049import com.puppycrawl.tools.checkstyle.xpath.ElementNode;
050import com.puppycrawl.tools.checkstyle.xpath.RootNode;
051import com.puppycrawl.tools.checkstyle.xpath.XpathQueryGenerator;
052import net.sf.saxon.trans.XPathException;
053
054/**
055 * This example shows how to create a simple TreeTable component,
056 * by using a JTree as a renderer (and editor) for the cells in a
057 * particular column in the JTable.
058 * <a href=
059 * "https://docs.oracle.com/cd/E48246_01/apirefs.1111/e13403/oracle/ide/controls/TreeTableModel.html">
060 * Original&nbsp;Source&nbsp;Location</a>
061 *
062 * @noinspection ThisEscapedInObjectConstruction
063 * @noinspectionreason ThisEscapedInObjectConstruction - only reference is used and not
064 *      accessed until initialized
065 */
066public final class TreeTable extends JTable {
067
068    /** A unique serial version identifier. */
069    @Serial
070    private static final long serialVersionUID = -8493693409423365387L;
071    /** The newline character. */
072    private static final String NEWLINE = "\n";
073    /** A subclass of JTree. */
074    private final TreeTableCellRenderer tree;
075    /** JTextArea editor. */
076    private JTextArea editor;
077    /** JTextArea xpathEditor. */
078    private JTextArea xpathEditor;
079    /** Line position map. */
080    private List<Integer> linePositionList;
081
082    /**
083     * Creates TreeTable base on TreeTableModel.
084     *
085     * @param treeTableModel Tree table model
086     */
087    public TreeTable(ParseTreeTableModel treeTableModel) {
088        // Create the tree. It will be used as a renderer and editor.
089        tree = new TreeTableCellRenderer(this, treeTableModel);
090
091        // Install a tableModel representing the visible rows in the tree.
092        setModel(new TreeTableModelAdapter(treeTableModel, tree));
093
094        // Force the JTable and JTree to share their row selection models.
095        final ListToTreeSelectionModelWrapper selectionWrapper = new
096                ListToTreeSelectionModelWrapper(this);
097        tree.setSelectionModel(selectionWrapper);
098        setSelectionModel(selectionWrapper.getListSelectionModel());
099
100        // Install the tree editor renderer and editor.
101        setDefaultRenderer(ParseTreeTableModel.class, tree);
102        setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor());
103
104        // No grid.
105        setShowGrid(false);
106
107        // No intercell spacing
108        setIntercellSpacing(new Dimension(0, 0));
109
110        // And update the height of the trees row to match that of
111        // the table.
112        if (tree.getRowHeight() < 1) {
113            // Metal looks better like this.
114            final int height = getRowHeight();
115            setRowHeight(height);
116        }
117
118        setColumnsInitialWidth();
119
120        final Action expand = new AbstractAction() {
121            @Serial
122            private static final long serialVersionUID = -5859674518660156121L;
123
124            @Override
125            public void actionPerformed(ActionEvent event) {
126                expandSelectedNode();
127            }
128        };
129        final KeyStroke stroke = KeyStroke.getKeyStroke("ENTER");
130        final String command = "expand/collapse";
131        getInputMap().put(stroke, command);
132        getActionMap().put(command, expand);
133
134        addMouseListener(new MouseAdapter() {
135            @Override
136            public void mouseClicked(MouseEvent event) {
137                if (event.getClickCount() == 2) {
138                    expandSelectedNode();
139                }
140            }
141        });
142    }
143
144    /**
145     * Do expansion of a tree node.
146     */
147    private void expandSelectedNode() {
148        final TreePath selected = tree.getSelectionPath();
149        makeCodeSelection();
150        generateXpath();
151
152        if (tree.isExpanded(selected)) {
153            tree.collapsePath(selected);
154        }
155        else {
156            tree.expandPath(selected);
157        }
158        tree.setSelectionPath(selected);
159    }
160
161    /**
162     * Make selection of code in a text area.
163     */
164    private void makeCodeSelection() {
165        new CodeSelector(tree.getLastSelectedPathComponent(), editor, linePositionList).select();
166    }
167
168    /**
169     * Generate Xpath.
170     */
171    private void generateXpath() {
172        if (tree.getLastSelectedPathComponent() instanceof DetailAST) {
173            final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent();
174            final String xpath = XpathQueryGenerator.generateXpathQuery(ast);
175            xpathEditor.setText(xpath);
176        }
177        else {
178            xpathEditor.setText("Xpath is not supported yet for javadoc nodes");
179        }
180    }
181
182    /**
183     * Set initial value of width for columns in table.
184     */
185    private void setColumnsInitialWidth() {
186        final FontMetrics fontMetrics = getFontMetrics(getFont());
187        // Six character string to contain "Column" column.
188        final int widthOfSixCharacterString = fontMetrics.stringWidth("XXXXXX");
189        // Padding must be added to width for columns to make them fully
190        // visible in table header.
191        final int padding = 10;
192        final int widthOfColumnContainingSixCharacterString =
193                widthOfSixCharacterString + padding;
194        getColumn("Line").setMaxWidth(widthOfColumnContainingSixCharacterString);
195        getColumn("Column").setMaxWidth(widthOfColumnContainingSixCharacterString);
196        final int preferredTreeColumnWidth =
197                Math.toIntExact(Math.round(getPreferredSize().getWidth() * 0.6));
198        getColumn("Tree").setPreferredWidth(preferredTreeColumnWidth);
199        // Twenty-eight character string to contain "Type" column
200        final int widthOfTwentyEightCharacterString =
201                fontMetrics.stringWidth("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
202        final int preferredTypeColumnWidth = widthOfTwentyEightCharacterString + padding;
203        getColumn("Type").setPreferredWidth(preferredTypeColumnWidth);
204    }
205
206    /**
207     * Select Node by Xpath.
208     */
209    public void selectNodeByXpath() {
210        final DetailAST rootAST = (DetailAST) tree.getModel().getRoot();
211        if (rootAST.hasChildren()) {
212            final String xpath = xpathEditor.getText();
213
214            try {
215                final Deque<DetailAST> nodes =
216                        XpathUtil.getXpathItems(xpath, new RootNode(rootAST))
217                              .stream()
218                              .map(ElementNode.class::cast)
219                              .map(ElementNode::getUnderlyingNode)
220                              .collect(Collectors.toCollection(ArrayDeque::new));
221                updateTreeTable(xpath, nodes);
222            }
223            catch (XPathException exception) {
224                xpathEditor.setText(xpathEditor.getText() + NEWLINE + exception.getMessage());
225            }
226        }
227        else {
228            xpathEditor.setText("No file Opened");
229        }
230    }
231
232    /**
233     * Updates the Treetable by expanding paths in the tree and highlighting
234     * associated code.
235     *
236     * @param xpath the XPath query to show in case of no match
237     * @param nodes the deque of DetailAST nodes to match in TreeTable and XPath editor
238     */
239    private void updateTreeTable(String xpath, Deque<DetailAST> nodes) {
240        if (nodes.isEmpty()) {
241            xpathEditor.setText("No elements matching XPath query '"
242                    + xpath + "' found.");
243        }
244        else {
245            for (DetailAST node : nodes) {
246                expandTreeTableByPath(node);
247                makeCodeSelection();
248            }
249            xpathEditor.setText(getAllMatchingXpathQueriesText(nodes));
250        }
251    }
252
253    /**
254     * Expands path in tree table to given node so that user can
255     * see the node.
256     *
257     * @param node node to expand table by
258     */
259    private void expandTreeTableByPath(DetailAST node) {
260        TreePath path = new TreePath(node);
261        path = path.pathByAddingChild(node);
262        if (!tree.isExpanded(path)) {
263            tree.expandPath(path);
264        }
265        tree.setSelectionPath(path);
266    }
267
268    /**
269     * Generates a String with all matching XPath queries separated
270     * by newlines.
271     *
272     * @param nodes deque of nodes to generate queries for
273     * @return complete text of all XPath expressions separated by newlines.
274     */
275    private static String getAllMatchingXpathQueriesText(Deque<DetailAST> nodes) {
276        return nodes.stream()
277                .map(XpathQueryGenerator::generateXpathQuery)
278                .collect(Collectors.joining(NEWLINE, "", NEWLINE));
279    }
280
281    /**
282     * Overridden to message super and forward the method to the tree.
283     * Since the tree is not actually in the component hierarchy it will
284     * never receive this unless we forward it in this manner.
285     */
286    @Override
287    public void updateUI() {
288        super.updateUI();
289        if (tree != null) {
290            tree.updateUI();
291        }
292        // Use the tree's default foreground and background colors in the
293        // table.
294        LookAndFeel.installColorsAndFont(this, "Tree.background",
295                "Tree.foreground", "Tree.font");
296    }
297
298    /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to
299     * paint the editor. The UI currently uses different techniques to
300     * paint the renderers and editors and overriding setBounds() below
301     * is not the right thing to do for an editor. Returning -1 for the
302     * editing row in this case, ensures the editor is never painted.
303     */
304    @Override
305    public int getEditingRow() {
306        int rowIndex = -1;
307        final Class<?> editingClass = getColumnClass(editingColumn);
308        if (editingClass != ParseTreeTableModel.class) {
309            rowIndex = editingRow;
310        }
311        return rowIndex;
312    }
313
314    /**
315     * Overridden to pass the new rowHeight to the tree.
316     */
317    @Override
318    public void setRowHeight(int newRowHeight) {
319        super.setRowHeight(newRowHeight);
320        if (tree != null && tree.getRowHeight() != newRowHeight) {
321            tree.setRowHeight(getRowHeight());
322        }
323    }
324
325    /**
326     * Returns tree.
327     *
328     * @return the tree that is being shared between the model.
329     */
330    public JTree getTree() {
331        return tree;
332    }
333
334    /**
335     * Sets text area editor.
336     *
337     * @param textArea JTextArea component.
338     */
339    public void setEditor(JTextArea textArea) {
340        editor = textArea;
341    }
342
343    /**
344     * Sets text area xpathEditor.
345     *
346     * @param xpathTextArea JTextArea component.
347     */
348    public void setXpathEditor(JTextArea xpathTextArea) {
349        xpathEditor = xpathTextArea;
350    }
351
352    /**
353     * Sets line positions.
354     *
355     * @param linePositionList positions of lines.
356     */
357    public void setLinePositionList(Collection<Integer> linePositionList) {
358        this.linePositionList = new ArrayList<>(linePositionList);
359    }
360
361    /**
362     * TreeTableCellEditor implementation. Component returned is the
363     * JTree.
364     */
365    private final class TreeTableCellEditor extends BaseCellEditor implements
366            TableCellEditor {
367
368        @Override
369        public Component getTableCellEditorComponent(JTable table,
370                Object value,
371                boolean isSelected,
372                int row, int column) {
373            return tree;
374        }
375
376        /**
377         * Overridden to return false, and if the event is a mouse event
378         * it is forwarded to the tree.
379         *
380         * <p>The behavior for this is debatable, and should really be offered
381         * as a property. By returning false, all keyboard actions are
382         * implemented in terms of the table. By returning true, the
383         * tree would get a chance to do something with the keyboard
384         * events. For the most part this is ok. But for certain keys,
385         * such as left/right, the tree will expand/collapse where as
386         * the table focus should really move to a different column. Page
387         * up/down should also be implemented in terms of the table.
388         * By returning false this also has the added benefit that clicking
389         * outside of the bounds of the tree node, but still in the tree
390         * column will select the row, whereas if this returned true
391         * that wouldn't be the case.
392         *
393         * <p>By returning false we are also enforcing the policy that
394         * the tree will never be editable (at least by a key sequence).
395         *
396         * @see TableCellEditor
397         */
398        @Override
399        public boolean isCellEditable(EventObject event) {
400            if (event instanceof MouseEvent) {
401                for (int counter = getColumnCount() - 1; counter >= 0;
402                     counter--) {
403                    if (getColumnClass(counter) == ParseTreeTableModel.class) {
404                        final MouseEvent mouseEvent = (MouseEvent) event;
405                        final MouseEvent newMouseEvent = new MouseEvent(tree, mouseEvent.getID(),
406                                mouseEvent.getWhen(), mouseEvent.getModifiersEx(),
407                                mouseEvent.getX() - getCellRect(0, counter, true).x,
408                                mouseEvent.getY(), mouseEvent.getClickCount(),
409                                mouseEvent.isPopupTrigger());
410                        tree.dispatchEvent(newMouseEvent);
411                        break;
412                    }
413                }
414            }
415
416            return false;
417        }
418
419    }
420
421}