1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package groovy.ui;
47
48 import groovy.lang.GroovyShell;
49
50 import java.awt.Color;
51
52 import javax.swing.JTextPane;
53 import javax.swing.text.Style;
54 import javax.swing.text.StyleConstants;
55 import javax.swing.text.StyleContext;
56 import javax.swing.text.StyledDocument;
57
58 /***
59 * Base class for console
60 *
61 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
62 * @version $Revision: 1.6 $
63 */
64 public abstract class ConsoleSupport {
65
66 Style promptStyle;
67 Style commandStyle;
68 Style outputStyle;
69 private GroovyShell shell;
70 int counter;
71
72 protected void addStylesToDocument(JTextPane outputArea) {
73 StyledDocument doc = outputArea.getStyledDocument();
74
75 Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
76
77 Style regular = doc.addStyle("regular", def);
78 StyleConstants.setFontFamily(def, "Monospaced");
79
80 promptStyle = doc.addStyle("prompt", regular);
81 StyleConstants.setForeground(promptStyle, Color.BLUE);
82
83 commandStyle = doc.addStyle("command", regular);
84 StyleConstants.setForeground(commandStyle, Color.MAGENTA);
85
86 outputStyle = doc.addStyle("output", regular);
87 StyleConstants.setBold(outputStyle, true);
88 }
89
90 public Style getCommandStyle() {
91 return commandStyle;
92 }
93
94 public Style getOutputStyle() {
95 return outputStyle;
96 }
97
98 public Style getPromptStyle() {
99 return promptStyle;
100 }
101
102 public GroovyShell getShell() {
103 if (shell == null) {
104 shell = new GroovyShell();
105 }
106 return shell;
107 }
108
109 protected Object evaluate(String text) {
110 String name = "Script" + counter++;
111 try {
112 return getShell().evaluate(text, name);
113 }
114 catch (Exception e) {
115 handleException(text, e);
116 return null;
117 }
118 }
119
120 protected abstract void handleException(String text, Exception e);
121 }