001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2021 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.util.ArrayDeque;
029import java.util.ArrayList;
030import java.util.Deque;
031import java.util.EventObject;
032import java.util.List;
033
034import javax.swing.AbstractAction;
035import javax.swing.Action;
036import javax.swing.JTable;
037import javax.swing.JTextArea;
038import javax.swing.JTree;
039import javax.swing.KeyStroke;
040import javax.swing.LookAndFeel;
041import javax.swing.table.TableCellEditor;
042import javax.swing.tree.TreePath;
043
044import com.puppycrawl.tools.checkstyle.api.DetailAST;
045import com.puppycrawl.tools.checkstyle.xpath.XpathQueryGenerator;
046
047/**
048 * This example shows how to create a simple TreeTable component,
049 * by using a JTree as a renderer (and editor) for the cells in a
050 * particular column in the JTable.
051 *
052 * <a href=
053 * "https://docs.oracle.com/cd/E48246_01/apirefs.1111/e13403/oracle/ide/controls/TreeTableModel.html">
054 * Original&nbsp;Source&nbsp;Location</a>
055 *
056 * @noinspection ThisEscapedInObjectConstruction
057 */
058public final class TreeTable extends JTable {
059
060    /** A unique serial version identifier. */
061    private static final long serialVersionUID = -8493693409423365387L;
062    /** A subclass of JTree. */
063    private final TreeTableCellRenderer tree;
064    /** JTextArea editor. */
065    private JTextArea editor;
066    /** JTextArea xpathEditor. */
067    private JTextArea xpathEditor;
068    /** Line position map. */
069    private List<Integer> linePositionMap;
070
071    /**
072     * Creates TreeTable base on TreeTableModel.
073     *
074     * @param treeTableModel Tree table model
075     */
076    public TreeTable(ParseTreeTableModel treeTableModel) {
077        // Create the tree. It will be used as a renderer and editor.
078        tree = new TreeTableCellRenderer(this, treeTableModel);
079
080        // Install a tableModel representing the visible rows in the tree.
081        setModel(new TreeTableModelAdapter(treeTableModel, tree));
082
083        // Force the JTable and JTree to share their row selection models.
084        final ListToTreeSelectionModelWrapper selectionWrapper = new
085                ListToTreeSelectionModelWrapper(this);
086        tree.setSelectionModel(selectionWrapper);
087        setSelectionModel(selectionWrapper.getListSelectionModel());
088
089        // Install the tree editor renderer and editor.
090        setDefaultRenderer(ParseTreeTableModel.class, tree);
091        setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor());
092
093        // No grid.
094        setShowGrid(false);
095
096        // No intercell spacing
097        setIntercellSpacing(new Dimension(0, 0));
098
099        // And update the height of the trees row to match that of
100        // the table.
101        if (tree.getRowHeight() < 1) {
102            // Metal looks better like this.
103            setRowHeight(getRowHeight());
104        }
105
106        setColumnsInitialWidth();
107
108        final Action expand = new AbstractAction() {
109            private static final long serialVersionUID = -5859674518660156121L;
110
111            @Override
112            public void actionPerformed(ActionEvent event) {
113                expandSelectedNode();
114            }
115        };
116        final KeyStroke stroke = KeyStroke.getKeyStroke("ENTER");
117        final String command = "expand/collapse";
118        getInputMap().put(stroke, command);
119        getActionMap().put(command, expand);
120
121        addMouseListener(new MouseAdapter() {
122            @Override
123            public void mouseClicked(MouseEvent event) {
124                if (event.getClickCount() == 2) {
125                    expandSelectedNode();
126                }
127            }
128        });
129    }
130
131    /**
132     * Do expansion of a tree node.
133     */
134    private void expandSelectedNode() {
135        final TreePath selected = tree.getSelectionPath();
136        makeCodeSelection();
137        generateXpath();
138
139        if (tree.isExpanded(selected)) {
140            tree.collapsePath(selected);
141        }
142        else {
143            tree.expandPath(selected);
144        }
145        tree.setSelectionPath(selected);
146    }
147
148    /**
149     * Make selection of code in a text area.
150     */
151    private void makeCodeSelection() {
152        new CodeSelector(tree.getLastSelectedPathComponent(), editor, linePositionMap).select();
153    }
154
155    /**
156     * Generate Xpath.
157     */
158    private void generateXpath() {
159        if (tree.getLastSelectedPathComponent() instanceof DetailAST) {
160            final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent();
161            final int beginPos = 4;
162            String xpath = XpathQueryGenerator.generateXpathQuery(ast);
163            final int length = xpath.length();
164            xpath = xpath.substring(beginPos, length);
165            xpathEditor.setText(xpath);
166        }
167        else {
168            xpathEditor.setText("Xpath is not supported yet for javadoc nodes");
169        }
170    }
171
172    /**
173     * Set initial value of width for columns in table.
174     */
175    private void setColumnsInitialWidth() {
176        final FontMetrics fontMetrics = getFontMetrics(getFont());
177        // Six character string to contain "Column" column.
178        final int widthOfSixCharacterString = fontMetrics.stringWidth("XXXXXX");
179        // Padding must be added to width for columns to make them fully
180        // visible in table header.
181        final int padding = 10;
182        final int widthOfColumnContainingSixCharacterString =
183                widthOfSixCharacterString + padding;
184        getColumn("Line").setMaxWidth(widthOfColumnContainingSixCharacterString);
185        getColumn("Column").setMaxWidth(widthOfColumnContainingSixCharacterString);
186        final int preferredTreeColumnWidth =
187                Math.toIntExact(Math.round(getPreferredSize().getWidth() * 0.6));
188        getColumn("Tree").setPreferredWidth(preferredTreeColumnWidth);
189        // Twenty eight character string to contain "Type" column
190        final int widthOfTwentyEightCharacterString =
191                fontMetrics.stringWidth("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
192        final int preferredTypeColumnWidth = widthOfTwentyEightCharacterString + padding;
193        getColumn("Type").setPreferredWidth(preferredTypeColumnWidth);
194    }
195
196    /**
197     * Search node by Xpath.
198     *
199     * @param root {@code DetailAST} root ast element
200     * @param xpath {@code String} xpath query
201     * @param nodes {@code Deque<DetailAST>} stack of nodes in selection path
202     * @return {@code boolean} node found or not
203     */
204    private static boolean search(DetailAST root, String xpath, Deque<DetailAST> nodes) {
205        boolean result = false;
206        if (xpath.equals(XpathQueryGenerator.generateXpathQuery(root))) {
207            nodes.push(root);
208            result = true;
209        }
210        else {
211            DetailAST child = root.getFirstChild();
212            while (child != null) {
213                if (search(child, xpath, nodes)) {
214                    nodes.push(root);
215                    result = true;
216                    break;
217                }
218                child = child.getNextSibling();
219            }
220        }
221        return result;
222    }
223
224    /**
225     * Select Node by Xpath.
226     */
227    public void selectNodeByXpath() {
228        final DetailAST rootAST = (DetailAST) tree.getModel().getRoot();
229        if (rootAST.hasChildren()) {
230            final String xpath = "/EOF" + xpathEditor.getText();
231            final Deque<DetailAST> nodes = new ArrayDeque<>();
232            if (search(rootAST, xpath, nodes)) {
233                TreePath path = new TreePath(nodes.pop());
234                while (!nodes.isEmpty()) {
235                    path = path.pathByAddingChild(nodes.pop());
236                    if (!tree.isExpanded(path)) {
237                        tree.expandPath(path);
238                    }
239                    tree.setSelectionPath(path);
240                    makeCodeSelection();
241                }
242            }
243            else {
244                xpathEditor.setText(xpathEditor.getText() + "\n^ wrong xpath query");
245            }
246        }
247        else {
248            xpathEditor.setText("No file Opened");
249        }
250    }
251
252    /**
253     * Overridden to message super and forward the method to the tree.
254     * Since the tree is not actually in the component hierarchy it will
255     * never receive this unless we forward it in this manner.
256     */
257    @Override
258    public void updateUI() {
259        super.updateUI();
260        if (tree != null) {
261            tree.updateUI();
262        }
263        // Use the tree's default foreground and background colors in the
264        // table.
265        LookAndFeel.installColorsAndFont(this, "Tree.background",
266                "Tree.foreground", "Tree.font");
267    }
268
269    /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to
270     * paint the editor. The UI currently uses different techniques to
271     * paint the renderers and editors and overriding setBounds() below
272     * is not the right thing to do for an editor. Returning -1 for the
273     * editing row in this case, ensures the editor is never painted.
274     */
275    @Override
276    public int getEditingRow() {
277        int rowIndex = -1;
278        final Class<?> editingClass = getColumnClass(editingColumn);
279        if (editingClass != ParseTreeTableModel.class) {
280            rowIndex = editingRow;
281        }
282        return rowIndex;
283    }
284
285    /**
286     * Overridden to pass the new rowHeight to the tree.
287     */
288    @Override
289    public void setRowHeight(int newRowHeight) {
290        super.setRowHeight(newRowHeight);
291        if (tree != null && tree.getRowHeight() != newRowHeight) {
292            tree.setRowHeight(getRowHeight());
293        }
294    }
295
296    /**
297     * Returns tree.
298     *
299     * @return the tree that is being shared between the model.
300     */
301    public JTree getTree() {
302        return tree;
303    }
304
305    /**
306     * Sets text area editor.
307     *
308     * @param textArea JTextArea component.
309     */
310    public void setEditor(JTextArea textArea) {
311        editor = textArea;
312    }
313
314    /**
315     * Sets text area xpathEditor.
316     *
317     * @param xpathTextArea JTextArea component.
318     */
319    public void setXpathEditor(JTextArea xpathTextArea) {
320        xpathEditor = xpathTextArea;
321    }
322
323    /**
324     * Sets line position map.
325     *
326     * @param linePositionMap Line position map.
327     */
328    public void setLinePositionMap(List<Integer> linePositionMap) {
329        this.linePositionMap = new ArrayList<>(linePositionMap);
330    }
331
332    /**
333     * TreeTableCellEditor implementation. Component returned is the
334     * JTree.
335     */
336    private class TreeTableCellEditor extends BaseCellEditor implements
337            TableCellEditor {
338
339        @Override
340        public Component getTableCellEditorComponent(JTable table,
341                Object value,
342                boolean isSelected,
343                int row, int column) {
344            return tree;
345        }
346
347        /**
348         * Overridden to return false, and if the event is a mouse event
349         * it is forwarded to the tree.
350         *
351         * <p>The behavior for this is debatable, and should really be offered
352         * as a property. By returning false, all keyboard actions are
353         * implemented in terms of the table. By returning true, the
354         * tree would get a chance to do something with the keyboard
355         * events. For the most part this is ok. But for certain keys,
356         * such as left/right, the tree will expand/collapse where as
357         * the table focus should really move to a different column. Page
358         * up/down should also be implemented in terms of the table.
359         * By returning false this also has the added benefit that clicking
360         * outside of the bounds of the tree node, but still in the tree
361         * column will select the row, whereas if this returned true
362         * that wouldn't be the case.
363         *
364         * <p>By returning false we are also enforcing the policy that
365         * the tree will never be editable (at least by a key sequence).
366         *
367         * @see TableCellEditor
368         */
369        @Override
370        public boolean isCellEditable(EventObject event) {
371            if (event instanceof MouseEvent) {
372                for (int counter = getColumnCount() - 1; counter >= 0;
373                     counter--) {
374                    if (getColumnClass(counter) == ParseTreeTableModel.class) {
375                        final MouseEvent mouseEvent = (MouseEvent) event;
376                        final MouseEvent newMouseEvent = new MouseEvent(tree, mouseEvent.getID(),
377                                mouseEvent.getWhen(), mouseEvent.getModifiersEx(),
378                                mouseEvent.getX() - getCellRect(0, counter, true).x,
379                                mouseEvent.getY(), mouseEvent.getClickCount(),
380                                mouseEvent.isPopupTrigger());
381                        tree.dispatchEvent(newMouseEvent);
382                        break;
383                    }
384                }
385            }
386
387            return false;
388        }
389
390    }
391
392}