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