1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2019 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.gui;
21  
22  import java.awt.Component;
23  import java.awt.Dimension;
24  import java.awt.FontMetrics;
25  import java.awt.event.ActionEvent;
26  import java.awt.event.MouseAdapter;
27  import java.awt.event.MouseEvent;
28  import java.util.ArrayList;
29  import java.util.EventObject;
30  import java.util.List;
31  
32  import javax.swing.AbstractAction;
33  import javax.swing.Action;
34  import javax.swing.JTable;
35  import javax.swing.JTextArea;
36  import javax.swing.JTree;
37  import javax.swing.KeyStroke;
38  import javax.swing.LookAndFeel;
39  import javax.swing.table.TableCellEditor;
40  import javax.swing.tree.TreePath;
41  
42  /**
43   * This example shows how to create a simple TreeTable component,
44   * by using a JTree as a renderer (and editor) for the cells in a
45   * particular column in the JTable.
46   *
47   * <a href=
48   * "https://docs.oracle.com/cd/E48246_01/apirefs.1111/e13403/oracle/ide/controls/TreeTableModel.html">
49   * Original&nbsp;Source&nbsp;Location</a>
50   *
51   * @noinspection ThisEscapedInObjectConstruction
52   */
53  public final class TreeTable extends JTable {
54  
55      private static final long serialVersionUID = -8493693409423365387L;
56      /** A subclass of JTree. */
57      private final TreeTableCellRenderer tree;
58      /** JTextArea editor. */
59      private JTextArea editor;
60      /** Line position map. */
61      private List<Integer> linePositionMap;
62  
63      /**
64       * Creates TreeTable base on TreeTableModel.
65       * @param treeTableModel Tree table model
66       */
67      public TreeTable(ParseTreeTableModel treeTableModel) {
68          // Create the tree. It will be used as a renderer and editor.
69          tree = new TreeTableCellRenderer(this, treeTableModel);
70  
71          // Install a tableModel representing the visible rows in the tree.
72          setModel(new TreeTableModelAdapter(treeTableModel, tree));
73  
74          // Force the JTable and JTree to share their row selection models.
75          final ListToTreeSelectionModelWrapper selectionWrapper = new
76                  ListToTreeSelectionModelWrapper(this);
77          tree.setSelectionModel(selectionWrapper);
78          setSelectionModel(selectionWrapper.getListSelectionModel());
79  
80          // Install the tree editor renderer and editor.
81          setDefaultRenderer(ParseTreeTableModel.class, tree);
82          setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor());
83  
84          // No grid.
85          setShowGrid(false);
86  
87          // No intercell spacing
88          setIntercellSpacing(new Dimension(0, 0));
89  
90          // And update the height of the trees row to match that of
91          // the table.
92          if (tree.getRowHeight() < 1) {
93              // Metal looks better like this.
94              setRowHeight(getRowHeight());
95          }
96  
97          setColumnsInitialWidth();
98  
99          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 }