001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2015 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.Color; 023import java.util.List; 024 025import javax.swing.JTextArea; 026 027import com.google.common.collect.ImmutableList; 028import com.puppycrawl.tools.checkstyle.api.DetailAST; 029 030/** 031 * Helper class to select a code. 032 * @author unknown 033 */ 034public class CodeSelector { 035 /** DetailAST node. */ 036 private final DetailAST ast; 037 /** Editor. */ 038 private final JTextArea editor; 039 /** Mapping. */ 040 private final List<Integer> lines2position; 041 042 /** 043 * Constructor. 044 * @param ast ast node. 045 * @param editor text area editor. 046 * @param lines2position list to map lines. 047 */ 048 public CodeSelector(final DetailAST ast, final JTextArea editor, 049 final List<Integer> lines2position) { 050 this.ast = ast; 051 this.editor = editor; 052 this.lines2position = ImmutableList.copyOf(lines2position); 053 } 054 055 /** 056 * Set a selection position from AST line and Column. 057 */ 058 public void select() { 059 final int start = lines2position.get(ast.getLineNo()) + ast.getColumnNo(); 060 final int end = findLastPosition(ast); 061 062 editor.setSelectedTextColor(Color.blue); 063 editor.requestFocusInWindow(); 064 editor.setSelectionStart(start); 065 editor.setSelectionEnd(end); 066 editor.transferFocusBackward(); 067 } 068 069 /** 070 * Finds the last position of node without children. 071 * @param astNode DetailAST node. 072 * @return Last position of node without children. 073 */ 074 private int findLastPosition(final DetailAST astNode) { 075 if (astNode.getChildCount() == 0) { 076 return lines2position.get(astNode.getLineNo()) + astNode.getColumnNo() 077 + astNode.getText().length(); 078 } 079 else { 080 return findLastPosition(astNode.getLastChild()); 081 } 082 } 083}