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