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