1 /* |
|
2 * Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. |
|
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 * |
|
5 * This code is free software; you can redistribute it and/or modify it |
|
6 * under the terms of the GNU General Public License version 2 only, as |
|
7 * published by the Free Software Foundation. |
|
8 * |
|
9 * This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 * version 2 for more details (a copy is included in the LICENSE file that |
|
13 * accompanied this code). |
|
14 * |
|
15 * You should have received a copy of the GNU General Public License version |
|
16 * 2 along with this work; if not, write to the Free Software Foundation, |
|
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 * |
|
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
|
20 * CA 95054 USA or visit www.sun.com if you need additional information or |
|
21 * have any questions. |
|
22 */ |
|
23 |
|
24 import java.awt.BorderLayout; |
|
25 import java.awt.Color; |
|
26 import java.awt.Dimension; |
|
27 import java.awt.EventQueue; |
|
28 import java.awt.Font; |
|
29 import java.awt.GridBagConstraints; |
|
30 import java.awt.GridBagLayout; |
|
31 import java.awt.Rectangle; |
|
32 import java.awt.event.ActionEvent; |
|
33 import java.awt.event.ActionListener; |
|
34 import java.awt.event.MouseAdapter; |
|
35 import java.awt.event.MouseEvent; |
|
36 import java.io.File; |
|
37 import java.io.IOException; |
|
38 import java.io.PrintStream; |
|
39 import java.io.PrintWriter; |
|
40 import java.io.StringWriter; |
|
41 import java.lang.reflect.Field; |
|
42 import java.lang.reflect.Modifier; |
|
43 import java.nio.charset.Charset; |
|
44 import java.util.ArrayList; |
|
45 import java.util.Collections; |
|
46 import java.util.HashMap; |
|
47 import java.util.HashSet; |
|
48 import java.util.Iterator; |
|
49 import java.util.List; |
|
50 import java.util.Map; |
|
51 import java.util.Set; |
|
52 import javax.swing.DefaultComboBoxModel; |
|
53 import javax.swing.JComboBox; |
|
54 import javax.swing.JComponent; |
|
55 import javax.swing.JFrame; |
|
56 import javax.swing.JLabel; |
|
57 import javax.swing.JPanel; |
|
58 import javax.swing.JScrollPane; |
|
59 import javax.swing.JTextArea; |
|
60 import javax.swing.JTextField; |
|
61 import javax.swing.SwingUtilities; |
|
62 import javax.swing.event.CaretEvent; |
|
63 import javax.swing.event.CaretListener; |
|
64 import javax.swing.text.BadLocationException; |
|
65 import javax.swing.text.DefaultHighlighter; |
|
66 import javax.swing.text.Highlighter; |
|
67 import javax.tools.Diagnostic; |
|
68 import javax.tools.DiagnosticListener; |
|
69 import javax.tools.JavaFileObject; |
|
70 import javax.tools.StandardJavaFileManager; |
|
71 |
|
72 import com.sun.source.tree.CompilationUnitTree; |
|
73 import com.sun.source.util.JavacTask; |
|
74 import com.sun.tools.javac.api.JavacTool; |
|
75 import com.sun.tools.javac.code.Flags; |
|
76 import com.sun.tools.javac.tree.JCTree; |
|
77 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; |
|
78 import com.sun.tools.javac.tree.JCTree.JCNewClass; |
|
79 import com.sun.tools.javac.tree.JCTree.JCVariableDecl; |
|
80 import com.sun.tools.javac.tree.TreeInfo; |
|
81 import com.sun.tools.javac.tree.TreeScanner; |
|
82 |
|
83 import static com.sun.tools.javac.util.Position.NOPOS; |
|
84 |
|
85 /** |
|
86 * Utility and test program to check validity of tree positions for tree nodes. |
|
87 * The program can be run standalone, or as a jtreg test. In standalone mode, |
|
88 * errors can be displayed in a gui viewer. For info on command line args, |
|
89 * run program with no args. |
|
90 * |
|
91 * <p> |
|
92 * jtreg: Note that by using the -r switch in the test description below, this test |
|
93 * will process all java files in the langtools/test directory, thus implicitly |
|
94 * covering any new language features that may be tested in this test suite. |
|
95 */ |
|
96 |
|
97 /* |
|
98 * @test |
|
99 * @bug 6919889 |
|
100 * @summary assorted position errors in compiler syntax trees |
|
101 * @run main TreePosTest -q -r -ef ./tools/javac/typeAnnotations -ef ./tools/javap/typeAnnotations -et ANNOTATED_TYPE . |
|
102 */ |
|
103 public class TreePosTest { |
|
104 /** |
|
105 * Main entry point. |
|
106 * If test.src is set, program runs in jtreg mode, and will throw an Error |
|
107 * if any errors arise, otherwise System.exit will be used, unless the gui |
|
108 * viewer is being used. In jtreg mode, the default base directory for file |
|
109 * args is the value of ${test.src}. In jtreg mode, the -r option can be |
|
110 * given to change the default base directory to the root test directory. |
|
111 */ |
|
112 public static void main(String... args) { |
|
113 String testSrc = System.getProperty("test.src"); |
|
114 File baseDir = (testSrc == null) ? null : new File(testSrc); |
|
115 boolean ok = new TreePosTest().run(baseDir, args); |
|
116 if (!ok) { |
|
117 if (testSrc != null) // jtreg mode |
|
118 throw new Error("failed"); |
|
119 else |
|
120 System.exit(1); |
|
121 } |
|
122 } |
|
123 |
|
124 /** |
|
125 * Run the program. A base directory can be provided for file arguments. |
|
126 * In jtreg mode, the -r option can be given to change the default base |
|
127 * directory to the test root directory. For other options, see usage(). |
|
128 * @param baseDir base directory for any file arguments. |
|
129 * @param args command line args |
|
130 * @return true if successful or in gui mode |
|
131 */ |
|
132 boolean run(File baseDir, String... args) { |
|
133 if (args.length == 0) { |
|
134 usage(System.out); |
|
135 return true; |
|
136 } |
|
137 |
|
138 List<File> files = new ArrayList<File>(); |
|
139 for (int i = 0; i < args.length; i++) { |
|
140 String arg = args[i]; |
|
141 if (arg.equals("-encoding") && i + 1 < args.length) |
|
142 encoding = args[++i]; |
|
143 else if (arg.equals("-gui")) |
|
144 gui = true; |
|
145 else if (arg.equals("-q")) |
|
146 quiet = true; |
|
147 else if (arg.equals("-v")) |
|
148 verbose = true; |
|
149 else if (arg.equals("-t") && i + 1 < args.length) |
|
150 tags.add(args[++i]); |
|
151 else if (arg.equals("-ef") && i + 1 < args.length) |
|
152 excludeFiles.add(new File(baseDir, args[++i])); |
|
153 else if (arg.equals("-et") && i + 1 < args.length) |
|
154 excludeTags.add(args[++i]); |
|
155 else if (arg.equals("-r")) { |
|
156 if (excludeFiles.size() > 0) |
|
157 throw new Error("-r must be used before -ef"); |
|
158 File d = baseDir; |
|
159 while (!new File(d, "TEST.ROOT").exists()) { |
|
160 d = d.getParentFile(); |
|
161 if (d == null) |
|
162 throw new Error("cannot find TEST.ROOT"); |
|
163 } |
|
164 baseDir = d; |
|
165 } |
|
166 else if (arg.startsWith("-")) |
|
167 throw new Error("unknown option: " + arg); |
|
168 else { |
|
169 while (i < args.length) |
|
170 files.add(new File(baseDir, args[i++])); |
|
171 } |
|
172 } |
|
173 |
|
174 for (File file: files) { |
|
175 if (file.exists()) |
|
176 test(file); |
|
177 else |
|
178 error("File not found: " + file); |
|
179 } |
|
180 |
|
181 if (fileCount != 1) |
|
182 System.err.println(fileCount + " files read"); |
|
183 if (errors > 0) |
|
184 System.err.println(errors + " errors"); |
|
185 |
|
186 return (gui || errors == 0); |
|
187 } |
|
188 |
|
189 /** |
|
190 * Print command line help. |
|
191 * @param out output stream |
|
192 */ |
|
193 void usage(PrintStream out) { |
|
194 out.println("Usage:"); |
|
195 out.println(" java TreePosTest options... files..."); |
|
196 out.println(""); |
|
197 out.println("where options include:"); |
|
198 out.println("-gui Display returns in a GUI viewer"); |
|
199 out.println("-q Quiet: don't report on inapplicable files"); |
|
200 out.println("-v Verbose: report on files as they are being read"); |
|
201 out.println("-t tag Limit checks to tree nodes with this tag"); |
|
202 out.println(" Can be repeated if desired"); |
|
203 out.println("-ef file Exclude file or directory"); |
|
204 out.println("-et tag Exclude tree nodes with given tag name"); |
|
205 out.println(""); |
|
206 out.println("files may be directories or files"); |
|
207 out.println("directories will be scanned recursively"); |
|
208 out.println("non java files, or java files which cannot be parsed, will be ignored"); |
|
209 out.println(""); |
|
210 } |
|
211 |
|
212 /** |
|
213 * Test a file. If the file is a directory, it will be recursively scanned |
|
214 * for java files. |
|
215 * @param file the file or directory to test |
|
216 */ |
|
217 void test(File file) { |
|
218 if (excludeFiles.contains(file)) { |
|
219 if (!quiet) |
|
220 error("File " + file + " excluded"); |
|
221 return; |
|
222 } |
|
223 |
|
224 if (file.isDirectory()) { |
|
225 for (File f: file.listFiles()) { |
|
226 test(f); |
|
227 } |
|
228 return; |
|
229 } |
|
230 |
|
231 if (file.isFile() && file.getName().endsWith(".java")) { |
|
232 try { |
|
233 if (verbose) |
|
234 System.err.println(file); |
|
235 fileCount++; |
|
236 PosTester p = new PosTester(); |
|
237 p.test(read(file)); |
|
238 } catch (ParseException e) { |
|
239 if (!quiet) { |
|
240 error("Error parsing " + file + "\n" + e.getMessage()); |
|
241 } |
|
242 } catch (IOException e) { |
|
243 error("Error reading " + file + ": " + e); |
|
244 } |
|
245 return; |
|
246 } |
|
247 |
|
248 if (!quiet) |
|
249 error("File " + file + " ignored"); |
|
250 } |
|
251 |
|
252 /** |
|
253 * Read a file. |
|
254 * @param file the file to be read |
|
255 * @return the tree for the content of the file |
|
256 * @throws IOException if any IO errors occur |
|
257 * @throws TreePosTest.ParseException if any errors occur while parsing the file |
|
258 */ |
|
259 JCCompilationUnit read(File file) throws IOException, ParseException { |
|
260 StringWriter sw = new StringWriter(); |
|
261 PrintWriter pw = new PrintWriter(sw); |
|
262 Reporter r = new Reporter(pw); |
|
263 JavacTool tool = JavacTool.create(); |
|
264 Charset cs = (encoding == null ? null : Charset.forName(encoding)); |
|
265 StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null); |
|
266 Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file); |
|
267 JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files); |
|
268 Iterable<? extends CompilationUnitTree> trees = task.parse(); |
|
269 pw.flush(); |
|
270 if (r.errors > 0) |
|
271 throw new ParseException(sw.toString()); |
|
272 Iterator<? extends CompilationUnitTree> iter = trees.iterator(); |
|
273 if (!iter.hasNext()) |
|
274 throw new Error("no trees found"); |
|
275 JCCompilationUnit t = (JCCompilationUnit) iter.next(); |
|
276 if (iter.hasNext()) |
|
277 throw new Error("too many trees found"); |
|
278 return t; |
|
279 } |
|
280 |
|
281 /** |
|
282 * Report an error. When the program is complete, the program will either |
|
283 * exit or throw an Error if any errors have been reported. |
|
284 * @param msg the error message |
|
285 */ |
|
286 void error(String msg) { |
|
287 System.err.println(msg); |
|
288 errors++; |
|
289 } |
|
290 |
|
291 /** Number of files that have been analyzed. */ |
|
292 int fileCount; |
|
293 /** Number of errors reported. */ |
|
294 int errors; |
|
295 /** Flag: don't report irrelevant files. */ |
|
296 boolean quiet; |
|
297 /** Flag: report files as they are processed. */ |
|
298 boolean verbose; |
|
299 /** Flag: show errors in GUI viewer. */ |
|
300 boolean gui; |
|
301 /** Option: encoding for test files. */ |
|
302 String encoding; |
|
303 /** The GUI viewer for errors. */ |
|
304 Viewer viewer; |
|
305 /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes |
|
306 * are analyzed. */ |
|
307 Set<String> tags = new HashSet<String>(); |
|
308 /** Set of files and directories to be excluded from analysis. */ |
|
309 Set<File> excludeFiles = new HashSet<File>(); |
|
310 /** Set of tag names to be excluded from analysis. */ |
|
311 Set<String> excludeTags = new HashSet<String>(); |
|
312 /** Table of printable names for tree tag values. */ |
|
313 TagNames tagNames = new TagNames(); |
|
314 |
|
315 /** |
|
316 * Main class for testing assertions concerning tree positions for tree nodes. |
|
317 */ |
|
318 private class PosTester extends TreeScanner { |
|
319 void test(JCCompilationUnit tree) { |
|
320 sourcefile = tree.sourcefile; |
|
321 endPosTable = tree.endPositions; |
|
322 encl = new Info(); |
|
323 tree.accept(this); |
|
324 } |
|
325 |
|
326 @Override |
|
327 public void scan(JCTree tree) { |
|
328 if (tree == null) |
|
329 return; |
|
330 |
|
331 Info self = new Info(tree, endPosTable); |
|
332 if (check(encl, self)) { |
|
333 // Modifiers nodes are present throughout the tree even where |
|
334 // there is no corresponding source text. |
|
335 // Redundant semicolons in a class definition can cause empty |
|
336 // initializer blocks with no positions. |
|
337 if ((self.tag == JCTree.MODIFIERS || self.tag == JCTree.BLOCK) |
|
338 && self.pos == NOPOS) { |
|
339 // If pos is NOPOS, so should be the start and end positions |
|
340 check("start == NOPOS", encl, self, self.start == NOPOS); |
|
341 check("end == NOPOS", encl, self, self.end == NOPOS); |
|
342 } else { |
|
343 // For this node, start , pos, and endpos should be all defined |
|
344 check("start != NOPOS", encl, self, self.start != NOPOS); |
|
345 check("pos != NOPOS", encl, self, self.pos != NOPOS); |
|
346 check("end != NOPOS", encl, self, self.end != NOPOS); |
|
347 // The following should normally be ordered |
|
348 // encl.start <= start <= pos <= end <= encl.end |
|
349 // In addition, the position of the enclosing node should be |
|
350 // within this node. |
|
351 // The primary exceptions are for array type nodes, because of the |
|
352 // need to support legacy syntax: |
|
353 // e.g. int a[]; int[] b[]; int f()[] { return null; } |
|
354 // and because of inconsistent nesting of left and right of |
|
355 // array declarations: |
|
356 // e.g. int[][] a = new int[2][]; |
|
357 check("encl.start <= start", encl, self, encl.start <= self.start); |
|
358 check("start <= pos", encl, self, self.start <= self.pos); |
|
359 if (!(self.tag == JCTree.TYPEARRAY |
|
360 && (encl.tag == JCTree.VARDEF || encl.tag == JCTree.TYPEARRAY))) { |
|
361 check("encl.pos <= start || end <= encl.pos", |
|
362 encl, self, encl.pos <= self.start || self.end <= encl.pos); |
|
363 } |
|
364 check("pos <= end", encl, self, self.pos <= self.end); |
|
365 if (!(self.tag == JCTree.TYPEARRAY && encl.tag == JCTree.TYPEARRAY)) { |
|
366 check("end <= encl.end", encl, self, self.end <= encl.end); |
|
367 } |
|
368 } |
|
369 } |
|
370 |
|
371 Info prevEncl = encl; |
|
372 encl = self; |
|
373 tree.accept(this); |
|
374 encl = prevEncl; |
|
375 } |
|
376 |
|
377 @Override |
|
378 public void visitVarDef(JCVariableDecl tree) { |
|
379 // enum member declarations are desugared in the parser and have |
|
380 // ill-defined semantics for tree positions, so for now, we |
|
381 // skip the synthesized bits and just check parts which came from |
|
382 // the original source text |
|
383 if ((tree.mods.flags & Flags.ENUM) != 0) { |
|
384 scan(tree.mods); |
|
385 if (tree.init != null) { |
|
386 if (tree.init.getTag() == JCTree.NEWCLASS) { |
|
387 JCNewClass init = (JCNewClass) tree.init; |
|
388 if (init.args != null && init.args.nonEmpty()) { |
|
389 scan(init.args); |
|
390 } |
|
391 if (init.def != null && init.def.defs != null) { |
|
392 scan(init.def.defs); |
|
393 } |
|
394 } |
|
395 } |
|
396 } else |
|
397 super.visitVarDef(tree); |
|
398 } |
|
399 |
|
400 boolean check(Info encl, Info self) { |
|
401 if (excludeTags.size() > 0) { |
|
402 if (encl != null && excludeTags.contains(tagNames.get(encl.tag)) |
|
403 || excludeTags.contains(tagNames.get(self.tag))) |
|
404 return false; |
|
405 } |
|
406 return tags.size() == 0 || tags.contains(tagNames.get(self.tag)); |
|
407 } |
|
408 |
|
409 void check(String label, Info encl, Info self, boolean ok) { |
|
410 if (!ok) { |
|
411 if (gui) { |
|
412 if (viewer == null) |
|
413 viewer = new Viewer(); |
|
414 viewer.addEntry(sourcefile, label, encl, self); |
|
415 } |
|
416 |
|
417 String s = self.tree.toString(); |
|
418 String msg = sourcefile.getName() + ": " + label + ": " + |
|
419 "encl:" + encl + " this:" + self + "\n" + |
|
420 s.substring(0, Math.min(80, s.length())).replaceAll("[\r\n]+", " "); |
|
421 error(msg); |
|
422 } |
|
423 } |
|
424 |
|
425 JavaFileObject sourcefile; |
|
426 Map<JCTree, Integer> endPosTable; |
|
427 Info encl; |
|
428 |
|
429 } |
|
430 |
|
431 /** |
|
432 * Utility class providing easy access to position and other info for a tree node. |
|
433 */ |
|
434 private class Info { |
|
435 Info() { |
|
436 tree = null; |
|
437 tag = JCTree.ERRONEOUS; |
|
438 start = 0; |
|
439 pos = 0; |
|
440 end = Integer.MAX_VALUE; |
|
441 } |
|
442 |
|
443 Info(JCTree tree, Map<JCTree, Integer> endPosTable) { |
|
444 this.tree = tree; |
|
445 tag = tree.getTag(); |
|
446 start = TreeInfo.getStartPos(tree); |
|
447 pos = tree.pos; |
|
448 end = TreeInfo.getEndPos(tree, endPosTable); |
|
449 } |
|
450 |
|
451 @Override |
|
452 public String toString() { |
|
453 return tagNames.get(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]"; |
|
454 } |
|
455 |
|
456 final JCTree tree; |
|
457 final int tag; |
|
458 final int start; |
|
459 final int pos; |
|
460 final int end; |
|
461 } |
|
462 |
|
463 /** |
|
464 * Names for tree tags. |
|
465 * javac does not provide an API to convert tag values to strings, so this class uses |
|
466 * reflection to determine names of public static final int values in JCTree. |
|
467 */ |
|
468 private static class TagNames { |
|
469 String get(int tag) { |
|
470 if (map == null) { |
|
471 map = new HashMap<Integer, String>(); |
|
472 Class c = JCTree.class; |
|
473 for (Field f : c.getDeclaredFields()) { |
|
474 if (f.getType().equals(int.class)) { |
|
475 int mods = f.getModifiers(); |
|
476 if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) { |
|
477 try { |
|
478 map.put(f.getInt(null), f.getName()); |
|
479 } catch (IllegalAccessException e) { |
|
480 } |
|
481 } |
|
482 } |
|
483 } |
|
484 } |
|
485 String name = map.get(tag); |
|
486 return (name == null) ? "??" : name; |
|
487 } |
|
488 |
|
489 private Map<Integer, String> map; |
|
490 } |
|
491 |
|
492 /** |
|
493 * Thrown when errors are found parsing a java file. |
|
494 */ |
|
495 private static class ParseException extends Exception { |
|
496 ParseException(String msg) { |
|
497 super(msg); |
|
498 } |
|
499 } |
|
500 |
|
501 /** |
|
502 * DiagnosticListener to report diagnostics and count any errors that occur. |
|
503 */ |
|
504 private static class Reporter implements DiagnosticListener<JavaFileObject> { |
|
505 Reporter(PrintWriter out) { |
|
506 this.out = out; |
|
507 } |
|
508 |
|
509 public void report(Diagnostic<? extends JavaFileObject> diagnostic) { |
|
510 out.println(diagnostic); |
|
511 switch (diagnostic.getKind()) { |
|
512 case ERROR: |
|
513 errors++; |
|
514 } |
|
515 } |
|
516 int errors; |
|
517 PrintWriter out; |
|
518 } |
|
519 |
|
520 /** |
|
521 * GUI viewer for issues found by TreePosTester. The viewer provides a drop |
|
522 * down list for selecting error conditions, a header area providing details |
|
523 * about an error, and a text area with the ranges of text highlighted as |
|
524 * appropriate. |
|
525 */ |
|
526 private class Viewer extends JFrame { |
|
527 /** |
|
528 * Create a viewer. |
|
529 */ |
|
530 Viewer() { |
|
531 initGUI(); |
|
532 } |
|
533 |
|
534 /** |
|
535 * Add another entry to the list of errors. |
|
536 * @param file The file containing the error |
|
537 * @param check The condition that was being tested, and which failed |
|
538 * @param encl the enclosing tree node |
|
539 * @param self the tree node containing the error |
|
540 */ |
|
541 void addEntry(JavaFileObject file, String check, Info encl, Info self) { |
|
542 Entry e = new Entry(file, check, encl, self); |
|
543 DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel(); |
|
544 m.addElement(e); |
|
545 if (m.getSize() == 1) |
|
546 entries.setSelectedItem(e); |
|
547 } |
|
548 |
|
549 /** |
|
550 * Initialize the GUI window. |
|
551 */ |
|
552 private void initGUI() { |
|
553 JPanel head = new JPanel(new GridBagLayout()); |
|
554 GridBagConstraints lc = new GridBagConstraints(); |
|
555 GridBagConstraints fc = new GridBagConstraints(); |
|
556 fc.anchor = GridBagConstraints.WEST; |
|
557 fc.fill = GridBagConstraints.HORIZONTAL; |
|
558 fc.gridwidth = GridBagConstraints.REMAINDER; |
|
559 |
|
560 entries = new JComboBox(); |
|
561 entries.addActionListener(new ActionListener() { |
|
562 public void actionPerformed(ActionEvent e) { |
|
563 showEntry((Entry) entries.getSelectedItem()); |
|
564 } |
|
565 }); |
|
566 fc.insets.bottom = 10; |
|
567 head.add(entries, fc); |
|
568 fc.insets.bottom = 0; |
|
569 head.add(new JLabel("check:"), lc); |
|
570 head.add(checkField = createTextField(80), fc); |
|
571 fc.fill = GridBagConstraints.NONE; |
|
572 head.add(setBackground(new JLabel("encl:"), enclColor), lc); |
|
573 head.add(enclPanel = new InfoPanel(), fc); |
|
574 head.add(setBackground(new JLabel("self:"), selfColor), lc); |
|
575 head.add(selfPanel = new InfoPanel(), fc); |
|
576 add(head, BorderLayout.NORTH); |
|
577 |
|
578 body = new JTextArea(); |
|
579 body.setFont(Font.decode(Font.MONOSPACED)); |
|
580 body.addCaretListener(new CaretListener() { |
|
581 public void caretUpdate(CaretEvent e) { |
|
582 int dot = e.getDot(); |
|
583 int mark = e.getMark(); |
|
584 if (dot == mark) |
|
585 statusText.setText("dot: " + dot); |
|
586 else |
|
587 statusText.setText("dot: " + dot + ", mark:" + mark); |
|
588 } |
|
589 }); |
|
590 JScrollPane p = new JScrollPane(body, |
|
591 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, |
|
592 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); |
|
593 p.setPreferredSize(new Dimension(640, 480)); |
|
594 add(p, BorderLayout.CENTER); |
|
595 |
|
596 statusText = createTextField(80); |
|
597 add(statusText, BorderLayout.SOUTH); |
|
598 |
|
599 pack(); |
|
600 setLocationRelativeTo(null); // centered on screen |
|
601 setVisible(true); |
|
602 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
|
603 } |
|
604 |
|
605 /** Show an entry that has been selected. */ |
|
606 private void showEntry(Entry e) { |
|
607 try { |
|
608 // update simple fields |
|
609 setTitle(e.file.getName()); |
|
610 checkField.setText(e.check); |
|
611 enclPanel.setInfo(e.encl); |
|
612 selfPanel.setInfo(e.self); |
|
613 // show file text with highlights |
|
614 body.setText(e.file.getCharContent(true).toString()); |
|
615 Highlighter highlighter = body.getHighlighter(); |
|
616 highlighter.removeAllHighlights(); |
|
617 addHighlight(highlighter, e.encl, enclColor); |
|
618 addHighlight(highlighter, e.self, selfColor); |
|
619 scroll(body, getMinPos(enclPanel.info, selfPanel.info)); |
|
620 } catch (IOException ex) { |
|
621 body.setText("Cannot read " + e.file.getName() + ": " + e); |
|
622 } |
|
623 } |
|
624 |
|
625 /** Create a test field. */ |
|
626 private JTextField createTextField(int width) { |
|
627 JTextField f = new JTextField(width); |
|
628 f.setEditable(false); |
|
629 f.setBorder(null); |
|
630 return f; |
|
631 } |
|
632 |
|
633 /** Add a highlighted region based on the positions in an Info object. */ |
|
634 private void addHighlight(Highlighter h, Info info, Color c) { |
|
635 int start = info.start; |
|
636 int end = info.end; |
|
637 if (start == -1 && end == -1) |
|
638 return; |
|
639 if (start == -1) |
|
640 start = end; |
|
641 if (end == -1) |
|
642 end = start; |
|
643 try { |
|
644 h.addHighlight(info.start, info.end, |
|
645 new DefaultHighlighter.DefaultHighlightPainter(c)); |
|
646 if (info.pos != -1) { |
|
647 Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40% |
|
648 h.addHighlight(info.pos, info.pos + 1, |
|
649 new DefaultHighlighter.DefaultHighlightPainter(c2)); |
|
650 } |
|
651 } catch (BadLocationException e) { |
|
652 e.printStackTrace(); |
|
653 } |
|
654 } |
|
655 |
|
656 /** Get the minimum valid position in a set of info objects. */ |
|
657 private int getMinPos(Info... values) { |
|
658 int i = Integer.MAX_VALUE; |
|
659 for (Info info: values) { |
|
660 if (info.start >= 0) i = Math.min(i, info.start); |
|
661 if (info.pos >= 0) i = Math.min(i, info.pos); |
|
662 if (info.end >= 0) i = Math.min(i, info.end); |
|
663 } |
|
664 return (i == Integer.MAX_VALUE) ? 0 : i; |
|
665 } |
|
666 |
|
667 /** Set the background on a component. */ |
|
668 private JComponent setBackground(JComponent comp, Color c) { |
|
669 comp.setOpaque(true); |
|
670 comp.setBackground(c); |
|
671 return comp; |
|
672 } |
|
673 |
|
674 /** Scroll a text area to display a given position near the middle of the visible area. */ |
|
675 private void scroll(final JTextArea t, final int pos) { |
|
676 // Using invokeLater appears to give text a chance to sort itself out |
|
677 // before the scroll happens; otherwise scrollRectToVisible doesn't work. |
|
678 // Maybe there's a better way to sync with the text... |
|
679 EventQueue.invokeLater(new Runnable() { |
|
680 public void run() { |
|
681 try { |
|
682 Rectangle r = t.modelToView(pos); |
|
683 JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t); |
|
684 r.y = Math.max(0, r.y - p.getHeight() * 2 / 5); |
|
685 r.height += p.getHeight() * 4 / 5; |
|
686 t.scrollRectToVisible(r); |
|
687 } catch (BadLocationException ignore) { |
|
688 } |
|
689 } |
|
690 }); |
|
691 } |
|
692 |
|
693 private JComboBox entries; |
|
694 private JTextField checkField; |
|
695 private InfoPanel enclPanel; |
|
696 private InfoPanel selfPanel; |
|
697 private JTextArea body; |
|
698 private JTextField statusText; |
|
699 |
|
700 private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green |
|
701 private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red |
|
702 |
|
703 /** Panel to display an Info object. */ |
|
704 private class InfoPanel extends JPanel { |
|
705 InfoPanel() { |
|
706 add(tagName = createTextField(20)); |
|
707 add(new JLabel("start:")); |
|
708 add(addListener(start = createTextField(6))); |
|
709 add(new JLabel("pos:")); |
|
710 add(addListener(pos = createTextField(6))); |
|
711 add(new JLabel("end:")); |
|
712 add(addListener(end = createTextField(6))); |
|
713 } |
|
714 |
|
715 void setInfo(Info info) { |
|
716 this.info = info; |
|
717 tagName.setText(tagNames.get(info.tag)); |
|
718 start.setText(String.valueOf(info.start)); |
|
719 pos.setText(String.valueOf(info.pos)); |
|
720 end.setText(String.valueOf(info.end)); |
|
721 } |
|
722 |
|
723 JTextField addListener(final JTextField f) { |
|
724 f.addMouseListener(new MouseAdapter() { |
|
725 @Override |
|
726 public void mouseClicked(MouseEvent e) { |
|
727 body.setCaretPosition(Integer.valueOf(f.getText())); |
|
728 body.getCaret().setVisible(true); |
|
729 } |
|
730 }); |
|
731 return f; |
|
732 } |
|
733 |
|
734 Info info; |
|
735 JTextField tagName; |
|
736 JTextField start; |
|
737 JTextField pos; |
|
738 JTextField end; |
|
739 } |
|
740 |
|
741 /** Object to record information about an error to be displayed. */ |
|
742 private class Entry { |
|
743 Entry(JavaFileObject file, String check, Info encl, Info self) { |
|
744 this.file = file; |
|
745 this.check = check; |
|
746 this.encl = encl; |
|
747 this.self= self; |
|
748 } |
|
749 |
|
750 @Override |
|
751 public String toString() { |
|
752 return file.getName() + " " + check + " " + getMinPos(encl, self); |
|
753 } |
|
754 |
|
755 final JavaFileObject file; |
|
756 final String check; |
|
757 final Info encl; |
|
758 final Info self; |
|
759 } |
|
760 } |
|
761 } |
|
762 |
|