1 package net.sourceforge.pmd.util.designer; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 import java.io.BufferedReader; 6 import java.io.File; 7 import java.io.FileReader; 8 import java.io.FileWriter; 9 import java.io.IOException; 10 import java.util.StringTokenizer; 11 12 import javax.swing.JTextPane; 13 14 import net.sourceforge.pmd.ast.SimpleNode; 15 import net.sourceforge.pmd.util.LineGetter; 16 17 public class CodeEditorTextPane extends JTextPane implements LineGetter, ActionListener { 18 19 private static final String SETTINGS_FILE_NAME = System.getProperty("user.home") + System.getProperty("file.separator") + ".pmd_designer"; 20 private static final String LINE_SEPARATOR = System.getProperty("line.separator"); 21 22 public CodeEditorTextPane() { 23 setText(loadCode()); 24 } 25 26 public String getLine(int number) { 27 int count = 1; 28 for (StringTokenizer st = new StringTokenizer(getText(), "\n"); st.hasMoreTokens();) { 29 String tok = st.nextToken(); 30 if (count == number) { 31 return tok; 32 } 33 count++; 34 } 35 throw new RuntimeException("Line number " + number + " not found"); 36 } 37 38 private int getPosition(String[] lines, int line, int column) { 39 int pos = 0; 40 for (int count = 0; count < lines.length;) { 41 String tok = lines[count++]; 42 if (count == line) { 43 int linePos = 0; 44 int i; 45 for (i = 0; linePos < column; i++) { 46 linePos++; 47 if (tok.charAt(i) == '\t') { 48 linePos--; 49 linePos += (8 - (linePos & 07)); 50 } 51 } 52 53 return pos + i - 1; 54 } 55 pos += tok.length() + 1; 56 } 57 throw new RuntimeException("Line " + line + " not found"); 58 } 59 60 public void select(SimpleNode node) { 61 String[] lines = getText().split(LINE_SEPARATOR); 62 setSelectionStart(getPosition(lines, node.getBeginLine(), node.getBeginColumn())); 63 setSelectionEnd(getPosition(lines, node.getEndLine(), node.getEndColumn())+1); 64 requestFocus(); 65 } 66 67 public void actionPerformed(ActionEvent ae) { 68 FileWriter fw = null; 69 try { 70 fw = new FileWriter(new File(SETTINGS_FILE_NAME)); 71 fw.write(getText()); 72 } catch (IOException ioe) { 73 } finally { 74 try { 75 if (fw != null) 76 fw.close(); 77 } catch (IOException ioe) { 78 ioe.printStackTrace(); 79 } 80 } 81 } 82 83 private String loadCode() { 84 BufferedReader br = null; 85 try { 86 br = new BufferedReader(new FileReader(new File(SETTINGS_FILE_NAME))); 87 StringBuffer text = new StringBuffer(); 88 String hold; 89 while ((hold = br.readLine()) != null) { 90 text.append(hold).append(LINE_SEPARATOR); 91 } 92 return text.toString(); 93 } catch (IOException e) { 94 e.printStackTrace(); 95 return ""; 96 } finally { 97 try { 98 if (br != null) br.close(); 99 } catch (IOException e) { 100 e.printStackTrace(); 101 } 102 } 103 } 104 }