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