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