481N/A/*
553N/A * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
481N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
481N/A *
481N/A * This code is free software; you can redistribute it and/or modify it
481N/A * under the terms of the GNU General Public License version 2 only, as
481N/A * published by the Free Software Foundation.
481N/A *
481N/A * This code is distributed in the hope that it will be useful, but WITHOUT
481N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
481N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
481N/A * version 2 for more details (a copy is included in the LICENSE file that
481N/A * accompanied this code).
481N/A *
481N/A * You should have received a copy of the GNU General Public License version
481N/A * 2 along with this work; if not, write to the Free Software Foundation,
481N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
481N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
553N/A * or visit www.oracle.com if you need additional information or have any
553N/A * questions.
481N/A */
481N/A
481N/Aimport java.awt.BorderLayout;
481N/Aimport java.awt.Color;
481N/Aimport java.awt.Dimension;
481N/Aimport java.awt.EventQueue;
481N/Aimport java.awt.Font;
481N/Aimport java.awt.GridBagConstraints;
481N/Aimport java.awt.GridBagLayout;
481N/Aimport java.awt.Rectangle;
481N/Aimport java.awt.event.ActionEvent;
481N/Aimport java.awt.event.ActionListener;
481N/Aimport java.awt.event.MouseAdapter;
481N/Aimport java.awt.event.MouseEvent;
481N/Aimport java.io.File;
481N/Aimport java.io.IOException;
481N/Aimport java.io.PrintStream;
481N/Aimport java.io.PrintWriter;
481N/Aimport java.io.StringWriter;
481N/Aimport java.lang.reflect.Field;
481N/Aimport java.lang.reflect.Modifier;
481N/Aimport java.nio.charset.Charset;
481N/Aimport java.util.ArrayList;
481N/Aimport java.util.Collections;
481N/Aimport java.util.HashMap;
481N/Aimport java.util.HashSet;
481N/Aimport java.util.Iterator;
481N/Aimport java.util.List;
481N/Aimport java.util.Map;
481N/Aimport java.util.Set;
481N/Aimport javax.swing.DefaultComboBoxModel;
481N/Aimport javax.swing.JComboBox;
481N/Aimport javax.swing.JComponent;
481N/Aimport javax.swing.JFrame;
481N/Aimport javax.swing.JLabel;
481N/Aimport javax.swing.JPanel;
481N/Aimport javax.swing.JScrollPane;
481N/Aimport javax.swing.JTextArea;
481N/Aimport javax.swing.JTextField;
481N/Aimport javax.swing.SwingUtilities;
481N/Aimport javax.swing.event.CaretEvent;
481N/Aimport javax.swing.event.CaretListener;
481N/Aimport javax.swing.text.BadLocationException;
481N/Aimport javax.swing.text.DefaultHighlighter;
481N/Aimport javax.swing.text.Highlighter;
481N/Aimport javax.tools.Diagnostic;
481N/Aimport javax.tools.DiagnosticListener;
481N/Aimport javax.tools.JavaFileObject;
481N/Aimport javax.tools.StandardJavaFileManager;
481N/A
481N/Aimport com.sun.source.tree.CompilationUnitTree;
481N/Aimport com.sun.source.util.JavacTask;
481N/Aimport com.sun.tools.javac.api.JavacTool;
481N/Aimport com.sun.tools.javac.code.Flags;
481N/Aimport com.sun.tools.javac.tree.JCTree;
481N/Aimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
481N/Aimport com.sun.tools.javac.tree.JCTree.JCNewClass;
481N/Aimport com.sun.tools.javac.tree.JCTree.JCVariableDecl;
481N/Aimport com.sun.tools.javac.tree.TreeInfo;
481N/Aimport com.sun.tools.javac.tree.TreeScanner;
481N/A
481N/Aimport static com.sun.tools.javac.util.Position.NOPOS;
481N/A
481N/A/**
481N/A * Utility and test program to check validity of tree positions for tree nodes.
481N/A * The program can be run standalone, or as a jtreg test. In standalone mode,
481N/A * errors can be displayed in a gui viewer. For info on command line args,
481N/A * run program with no args.
481N/A *
481N/A * <p>
481N/A * jtreg: Note that by using the -r switch in the test description below, this test
481N/A * will process all java files in the langtools/test directory, thus implicitly
481N/A * covering any new language features that may be tested in this test suite.
481N/A */
481N/A
481N/A/*
481N/A * @test
481N/A * @bug 6919889
481N/A * @summary assorted position errors in compiler syntax trees
492N/A * @run main TreePosTest -q -r -ef ./tools/javac/typeAnnotations -ef ./tools/javap/typeAnnotations -et ANNOTATED_TYPE .
481N/A */
481N/Apublic class TreePosTest {
481N/A /**
481N/A * Main entry point.
481N/A * If test.src is set, program runs in jtreg mode, and will throw an Error
481N/A * if any errors arise, otherwise System.exit will be used, unless the gui
481N/A * viewer is being used. In jtreg mode, the default base directory for file
481N/A * args is the value of ${test.src}. In jtreg mode, the -r option can be
481N/A * given to change the default base directory to the root test directory.
481N/A */
481N/A public static void main(String... args) {
481N/A String testSrc = System.getProperty("test.src");
481N/A File baseDir = (testSrc == null) ? null : new File(testSrc);
481N/A boolean ok = new TreePosTest().run(baseDir, args);
481N/A if (!ok) {
481N/A if (testSrc != null) // jtreg mode
481N/A throw new Error("failed");
481N/A else
481N/A System.exit(1);
481N/A }
481N/A }
481N/A
481N/A /**
481N/A * Run the program. A base directory can be provided for file arguments.
481N/A * In jtreg mode, the -r option can be given to change the default base
481N/A * directory to the test root directory. For other options, see usage().
481N/A * @param baseDir base directory for any file arguments.
481N/A * @param args command line args
481N/A * @return true if successful or in gui mode
481N/A */
481N/A boolean run(File baseDir, String... args) {
481N/A if (args.length == 0) {
481N/A usage(System.out);
481N/A return true;
481N/A }
481N/A
481N/A List<File> files = new ArrayList<File>();
481N/A for (int i = 0; i < args.length; i++) {
481N/A String arg = args[i];
481N/A if (arg.equals("-encoding") && i + 1 < args.length)
481N/A encoding = args[++i];
481N/A else if (arg.equals("-gui"))
481N/A gui = true;
481N/A else if (arg.equals("-q"))
481N/A quiet = true;
481N/A else if (arg.equals("-v"))
481N/A verbose = true;
481N/A else if (arg.equals("-t") && i + 1 < args.length)
481N/A tags.add(args[++i]);
481N/A else if (arg.equals("-ef") && i + 1 < args.length)
481N/A excludeFiles.add(new File(baseDir, args[++i]));
492N/A else if (arg.equals("-et") && i + 1 < args.length)
492N/A excludeTags.add(args[++i]);
481N/A else if (arg.equals("-r")) {
481N/A if (excludeFiles.size() > 0)
481N/A throw new Error("-r must be used before -ef");
481N/A File d = baseDir;
481N/A while (!new File(d, "TEST.ROOT").exists()) {
481N/A d = d.getParentFile();
481N/A if (d == null)
481N/A throw new Error("cannot find TEST.ROOT");
481N/A }
481N/A baseDir = d;
481N/A }
481N/A else if (arg.startsWith("-"))
481N/A throw new Error("unknown option: " + arg);
481N/A else {
481N/A while (i < args.length)
481N/A files.add(new File(baseDir, args[i++]));
481N/A }
481N/A }
481N/A
481N/A for (File file: files) {
481N/A if (file.exists())
481N/A test(file);
481N/A else
481N/A error("File not found: " + file);
481N/A }
481N/A
481N/A if (fileCount != 1)
481N/A System.err.println(fileCount + " files read");
481N/A if (errors > 0)
481N/A System.err.println(errors + " errors");
481N/A
481N/A return (gui || errors == 0);
481N/A }
481N/A
481N/A /**
481N/A * Print command line help.
481N/A * @param out output stream
481N/A */
481N/A void usage(PrintStream out) {
481N/A out.println("Usage:");
481N/A out.println(" java TreePosTest options... files...");
481N/A out.println("");
481N/A out.println("where options include:");
481N/A out.println("-gui Display returns in a GUI viewer");
481N/A out.println("-q Quiet: don't report on inapplicable files");
481N/A out.println("-v Verbose: report on files as they are being read");
481N/A out.println("-t tag Limit checks to tree nodes with this tag");
481N/A out.println(" Can be repeated if desired");
481N/A out.println("-ef file Exclude file or directory");
492N/A out.println("-et tag Exclude tree nodes with given tag name");
481N/A out.println("");
481N/A out.println("files may be directories or files");
481N/A out.println("directories will be scanned recursively");
481N/A out.println("non java files, or java files which cannot be parsed, will be ignored");
481N/A out.println("");
481N/A }
481N/A
481N/A /**
481N/A * Test a file. If the file is a directory, it will be recursively scanned
481N/A * for java files.
481N/A * @param file the file or directory to test
481N/A */
481N/A void test(File file) {
481N/A if (excludeFiles.contains(file)) {
481N/A if (!quiet)
481N/A error("File " + file + " excluded");
481N/A return;
481N/A }
481N/A
481N/A if (file.isDirectory()) {
481N/A for (File f: file.listFiles()) {
481N/A test(f);
481N/A }
481N/A return;
481N/A }
481N/A
481N/A if (file.isFile() && file.getName().endsWith(".java")) {
481N/A try {
481N/A if (verbose)
481N/A System.err.println(file);
481N/A fileCount++;
481N/A PosTester p = new PosTester();
481N/A p.test(read(file));
481N/A } catch (ParseException e) {
481N/A if (!quiet) {
481N/A error("Error parsing " + file + "\n" + e.getMessage());
481N/A }
481N/A } catch (IOException e) {
481N/A error("Error reading " + file + ": " + e);
481N/A }
481N/A return;
481N/A }
481N/A
481N/A if (!quiet)
481N/A error("File " + file + " ignored");
481N/A }
481N/A
807N/A // See CR: 6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
807N/A StringWriter sw = new StringWriter();
807N/A PrintWriter pw = new PrintWriter(sw);
807N/A Reporter r = new Reporter(pw);
807N/A JavacTool tool = JavacTool.create();
807N/A StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
807N/A
481N/A /**
481N/A * Read a file.
481N/A * @param file the file to be read
481N/A * @return the tree for the content of the file
481N/A * @throws IOException if any IO errors occur
481N/A * @throws TreePosTest.ParseException if any errors occur while parsing the file
481N/A */
481N/A JCCompilationUnit read(File file) throws IOException, ParseException {
481N/A JavacTool tool = JavacTool.create();
807N/A r.errors = 0;
481N/A Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
481N/A JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
481N/A Iterable<? extends CompilationUnitTree> trees = task.parse();
481N/A pw.flush();
481N/A if (r.errors > 0)
481N/A throw new ParseException(sw.toString());
481N/A Iterator<? extends CompilationUnitTree> iter = trees.iterator();
481N/A if (!iter.hasNext())
481N/A throw new Error("no trees found");
481N/A JCCompilationUnit t = (JCCompilationUnit) iter.next();
481N/A if (iter.hasNext())
481N/A throw new Error("too many trees found");
481N/A return t;
481N/A }
481N/A
481N/A /**
481N/A * Report an error. When the program is complete, the program will either
481N/A * exit or throw an Error if any errors have been reported.
481N/A * @param msg the error message
481N/A */
481N/A void error(String msg) {
481N/A System.err.println(msg);
481N/A errors++;
481N/A }
481N/A
481N/A /** Number of files that have been analyzed. */
481N/A int fileCount;
481N/A /** Number of errors reported. */
481N/A int errors;
481N/A /** Flag: don't report irrelevant files. */
481N/A boolean quiet;
481N/A /** Flag: report files as they are processed. */
481N/A boolean verbose;
481N/A /** Flag: show errors in GUI viewer. */
481N/A boolean gui;
481N/A /** Option: encoding for test files. */
481N/A String encoding;
481N/A /** The GUI viewer for errors. */
481N/A Viewer viewer;
481N/A /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
481N/A * are analyzed. */
481N/A Set<String> tags = new HashSet<String>();
481N/A /** Set of files and directories to be excluded from analysis. */
481N/A Set<File> excludeFiles = new HashSet<File>();
492N/A /** Set of tag names to be excluded from analysis. */
492N/A Set<String> excludeTags = new HashSet<String>();
481N/A /** Table of printable names for tree tag values. */
481N/A TagNames tagNames = new TagNames();
481N/A
481N/A /**
481N/A * Main class for testing assertions concerning tree positions for tree nodes.
481N/A */
481N/A private class PosTester extends TreeScanner {
481N/A void test(JCCompilationUnit tree) {
481N/A sourcefile = tree.sourcefile;
481N/A endPosTable = tree.endPositions;
481N/A encl = new Info();
481N/A tree.accept(this);
481N/A }
481N/A
481N/A @Override
481N/A public void scan(JCTree tree) {
481N/A if (tree == null)
481N/A return;
481N/A
481N/A Info self = new Info(tree, endPosTable);
492N/A if (check(encl, self)) {
481N/A // Modifiers nodes are present throughout the tree even where
481N/A // there is no corresponding source text.
481N/A // Redundant semicolons in a class definition can cause empty
481N/A // initializer blocks with no positions.
481N/A if ((self.tag == JCTree.MODIFIERS || self.tag == JCTree.BLOCK)
481N/A && self.pos == NOPOS) {
481N/A // If pos is NOPOS, so should be the start and end positions
481N/A check("start == NOPOS", encl, self, self.start == NOPOS);
481N/A check("end == NOPOS", encl, self, self.end == NOPOS);
481N/A } else {
481N/A // For this node, start , pos, and endpos should be all defined
481N/A check("start != NOPOS", encl, self, self.start != NOPOS);
481N/A check("pos != NOPOS", encl, self, self.pos != NOPOS);
481N/A check("end != NOPOS", encl, self, self.end != NOPOS);
481N/A // The following should normally be ordered
481N/A // encl.start <= start <= pos <= end <= encl.end
481N/A // In addition, the position of the enclosing node should be
481N/A // within this node.
481N/A // The primary exceptions are for array type nodes, because of the
481N/A // need to support legacy syntax:
481N/A // e.g. int a[]; int[] b[]; int f()[] { return null; }
481N/A // and because of inconsistent nesting of left and right of
481N/A // array declarations:
481N/A // e.g. int[][] a = new int[2][];
481N/A check("encl.start <= start", encl, self, encl.start <= self.start);
481N/A check("start <= pos", encl, self, self.start <= self.pos);
481N/A if (!(self.tag == JCTree.TYPEARRAY
721N/A && (encl.tag == JCTree.VARDEF ||
721N/A encl.tag == JCTree.METHODDEF ||
721N/A encl.tag == JCTree.TYPEARRAY))) {
481N/A check("encl.pos <= start || end <= encl.pos",
481N/A encl, self, encl.pos <= self.start || self.end <= encl.pos);
481N/A }
481N/A check("pos <= end", encl, self, self.pos <= self.end);
481N/A if (!(self.tag == JCTree.TYPEARRAY && encl.tag == JCTree.TYPEARRAY)) {
481N/A check("end <= encl.end", encl, self, self.end <= encl.end);
481N/A }
481N/A }
481N/A }
481N/A
481N/A Info prevEncl = encl;
481N/A encl = self;
481N/A tree.accept(this);
481N/A encl = prevEncl;
481N/A }
481N/A
481N/A @Override
481N/A public void visitVarDef(JCVariableDecl tree) {
481N/A // enum member declarations are desugared in the parser and have
481N/A // ill-defined semantics for tree positions, so for now, we
481N/A // skip the synthesized bits and just check parts which came from
481N/A // the original source text
481N/A if ((tree.mods.flags & Flags.ENUM) != 0) {
481N/A scan(tree.mods);
481N/A if (tree.init != null) {
481N/A if (tree.init.getTag() == JCTree.NEWCLASS) {
481N/A JCNewClass init = (JCNewClass) tree.init;
481N/A if (init.args != null && init.args.nonEmpty()) {
481N/A scan(init.args);
481N/A }
481N/A if (init.def != null && init.def.defs != null) {
481N/A scan(init.def.defs);
481N/A }
481N/A }
481N/A }
481N/A } else
481N/A super.visitVarDef(tree);
481N/A }
481N/A
492N/A boolean check(Info encl, Info self) {
492N/A if (excludeTags.size() > 0) {
492N/A if (encl != null && excludeTags.contains(tagNames.get(encl.tag))
492N/A || excludeTags.contains(tagNames.get(self.tag)))
492N/A return false;
492N/A }
492N/A return tags.size() == 0 || tags.contains(tagNames.get(self.tag));
481N/A }
481N/A
481N/A void check(String label, Info encl, Info self, boolean ok) {
481N/A if (!ok) {
481N/A if (gui) {
481N/A if (viewer == null)
481N/A viewer = new Viewer();
481N/A viewer.addEntry(sourcefile, label, encl, self);
481N/A }
481N/A
481N/A String s = self.tree.toString();
481N/A String msg = sourcefile.getName() + ": " + label + ": " +
481N/A "encl:" + encl + " this:" + self + "\n" +
481N/A s.substring(0, Math.min(80, s.length())).replaceAll("[\r\n]+", " ");
481N/A error(msg);
481N/A }
481N/A }
481N/A
481N/A JavaFileObject sourcefile;
481N/A Map<JCTree, Integer> endPosTable;
481N/A Info encl;
481N/A
481N/A }
481N/A
481N/A /**
481N/A * Utility class providing easy access to position and other info for a tree node.
481N/A */
481N/A private class Info {
481N/A Info() {
481N/A tree = null;
481N/A tag = JCTree.ERRONEOUS;
481N/A start = 0;
481N/A pos = 0;
481N/A end = Integer.MAX_VALUE;
481N/A }
481N/A
481N/A Info(JCTree tree, Map<JCTree, Integer> endPosTable) {
481N/A this.tree = tree;
481N/A tag = tree.getTag();
481N/A start = TreeInfo.getStartPos(tree);
481N/A pos = tree.pos;
481N/A end = TreeInfo.getEndPos(tree, endPosTable);
481N/A }
481N/A
481N/A @Override
481N/A public String toString() {
481N/A return tagNames.get(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
481N/A }
481N/A
481N/A final JCTree tree;
481N/A final int tag;
481N/A final int start;
481N/A final int pos;
481N/A final int end;
481N/A }
481N/A
481N/A /**
481N/A * Names for tree tags.
481N/A * javac does not provide an API to convert tag values to strings, so this class uses
481N/A * reflection to determine names of public static final int values in JCTree.
481N/A */
481N/A private static class TagNames {
481N/A String get(int tag) {
481N/A if (map == null) {
481N/A map = new HashMap<Integer, String>();
481N/A Class c = JCTree.class;
481N/A for (Field f : c.getDeclaredFields()) {
481N/A if (f.getType().equals(int.class)) {
481N/A int mods = f.getModifiers();
481N/A if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
481N/A try {
481N/A map.put(f.getInt(null), f.getName());
481N/A } catch (IllegalAccessException e) {
481N/A }
481N/A }
481N/A }
481N/A }
481N/A }
481N/A String name = map.get(tag);
481N/A return (name == null) ? "??" : name;
481N/A }
481N/A
481N/A private Map<Integer, String> map;
481N/A }
481N/A
481N/A /**
481N/A * Thrown when errors are found parsing a java file.
481N/A */
481N/A private static class ParseException extends Exception {
481N/A ParseException(String msg) {
481N/A super(msg);
481N/A }
481N/A }
481N/A
481N/A /**
481N/A * DiagnosticListener to report diagnostics and count any errors that occur.
481N/A */
481N/A private static class Reporter implements DiagnosticListener<JavaFileObject> {
481N/A Reporter(PrintWriter out) {
481N/A this.out = out;
481N/A }
481N/A
481N/A public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
481N/A out.println(diagnostic);
481N/A switch (diagnostic.getKind()) {
481N/A case ERROR:
481N/A errors++;
481N/A }
481N/A }
481N/A int errors;
481N/A PrintWriter out;
481N/A }
481N/A
481N/A /**
481N/A * GUI viewer for issues found by TreePosTester. The viewer provides a drop
481N/A * down list for selecting error conditions, a header area providing details
481N/A * about an error, and a text area with the ranges of text highlighted as
481N/A * appropriate.
481N/A */
481N/A private class Viewer extends JFrame {
481N/A /**
481N/A * Create a viewer.
481N/A */
481N/A Viewer() {
481N/A initGUI();
481N/A }
481N/A
481N/A /**
481N/A * Add another entry to the list of errors.
481N/A * @param file The file containing the error
481N/A * @param check The condition that was being tested, and which failed
481N/A * @param encl the enclosing tree node
481N/A * @param self the tree node containing the error
481N/A */
481N/A void addEntry(JavaFileObject file, String check, Info encl, Info self) {
481N/A Entry e = new Entry(file, check, encl, self);
481N/A DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
481N/A m.addElement(e);
481N/A if (m.getSize() == 1)
481N/A entries.setSelectedItem(e);
481N/A }
481N/A
481N/A /**
481N/A * Initialize the GUI window.
481N/A */
481N/A private void initGUI() {
481N/A JPanel head = new JPanel(new GridBagLayout());
481N/A GridBagConstraints lc = new GridBagConstraints();
481N/A GridBagConstraints fc = new GridBagConstraints();
481N/A fc.anchor = GridBagConstraints.WEST;
481N/A fc.fill = GridBagConstraints.HORIZONTAL;
481N/A fc.gridwidth = GridBagConstraints.REMAINDER;
481N/A
481N/A entries = new JComboBox();
481N/A entries.addActionListener(new ActionListener() {
481N/A public void actionPerformed(ActionEvent e) {
481N/A showEntry((Entry) entries.getSelectedItem());
481N/A }
481N/A });
481N/A fc.insets.bottom = 10;
481N/A head.add(entries, fc);
481N/A fc.insets.bottom = 0;
481N/A head.add(new JLabel("check:"), lc);
481N/A head.add(checkField = createTextField(80), fc);
481N/A fc.fill = GridBagConstraints.NONE;
481N/A head.add(setBackground(new JLabel("encl:"), enclColor), lc);
481N/A head.add(enclPanel = new InfoPanel(), fc);
481N/A head.add(setBackground(new JLabel("self:"), selfColor), lc);
481N/A head.add(selfPanel = new InfoPanel(), fc);
481N/A add(head, BorderLayout.NORTH);
481N/A
481N/A body = new JTextArea();
481N/A body.setFont(Font.decode(Font.MONOSPACED));
481N/A body.addCaretListener(new CaretListener() {
481N/A public void caretUpdate(CaretEvent e) {
481N/A int dot = e.getDot();
481N/A int mark = e.getMark();
481N/A if (dot == mark)
481N/A statusText.setText("dot: " + dot);
481N/A else
481N/A statusText.setText("dot: " + dot + ", mark:" + mark);
481N/A }
481N/A });
481N/A JScrollPane p = new JScrollPane(body,
481N/A JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
481N/A JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
481N/A p.setPreferredSize(new Dimension(640, 480));
481N/A add(p, BorderLayout.CENTER);
481N/A
481N/A statusText = createTextField(80);
481N/A add(statusText, BorderLayout.SOUTH);
481N/A
481N/A pack();
481N/A setLocationRelativeTo(null); // centered on screen
481N/A setVisible(true);
481N/A setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
481N/A }
481N/A
481N/A /** Show an entry that has been selected. */
481N/A private void showEntry(Entry e) {
481N/A try {
481N/A // update simple fields
481N/A setTitle(e.file.getName());
481N/A checkField.setText(e.check);
481N/A enclPanel.setInfo(e.encl);
481N/A selfPanel.setInfo(e.self);
481N/A // show file text with highlights
481N/A body.setText(e.file.getCharContent(true).toString());
481N/A Highlighter highlighter = body.getHighlighter();
481N/A highlighter.removeAllHighlights();
481N/A addHighlight(highlighter, e.encl, enclColor);
481N/A addHighlight(highlighter, e.self, selfColor);
481N/A scroll(body, getMinPos(enclPanel.info, selfPanel.info));
481N/A } catch (IOException ex) {
481N/A body.setText("Cannot read " + e.file.getName() + ": " + e);
481N/A }
481N/A }
481N/A
481N/A /** Create a test field. */
481N/A private JTextField createTextField(int width) {
481N/A JTextField f = new JTextField(width);
481N/A f.setEditable(false);
481N/A f.setBorder(null);
481N/A return f;
481N/A }
481N/A
481N/A /** Add a highlighted region based on the positions in an Info object. */
481N/A private void addHighlight(Highlighter h, Info info, Color c) {
481N/A int start = info.start;
481N/A int end = info.end;
481N/A if (start == -1 && end == -1)
481N/A return;
481N/A if (start == -1)
481N/A start = end;
481N/A if (end == -1)
481N/A end = start;
481N/A try {
481N/A h.addHighlight(info.start, info.end,
481N/A new DefaultHighlighter.DefaultHighlightPainter(c));
481N/A if (info.pos != -1) {
481N/A Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
481N/A h.addHighlight(info.pos, info.pos + 1,
481N/A new DefaultHighlighter.DefaultHighlightPainter(c2));
481N/A }
481N/A } catch (BadLocationException e) {
481N/A e.printStackTrace();
481N/A }
481N/A }
481N/A
481N/A /** Get the minimum valid position in a set of info objects. */
481N/A private int getMinPos(Info... values) {
481N/A int i = Integer.MAX_VALUE;
481N/A for (Info info: values) {
481N/A if (info.start >= 0) i = Math.min(i, info.start);
481N/A if (info.pos >= 0) i = Math.min(i, info.pos);
481N/A if (info.end >= 0) i = Math.min(i, info.end);
481N/A }
481N/A return (i == Integer.MAX_VALUE) ? 0 : i;
481N/A }
481N/A
481N/A /** Set the background on a component. */
481N/A private JComponent setBackground(JComponent comp, Color c) {
481N/A comp.setOpaque(true);
481N/A comp.setBackground(c);
481N/A return comp;
481N/A }
481N/A
481N/A /** Scroll a text area to display a given position near the middle of the visible area. */
481N/A private void scroll(final JTextArea t, final int pos) {
481N/A // Using invokeLater appears to give text a chance to sort itself out
481N/A // before the scroll happens; otherwise scrollRectToVisible doesn't work.
481N/A // Maybe there's a better way to sync with the text...
481N/A EventQueue.invokeLater(new Runnable() {
481N/A public void run() {
481N/A try {
481N/A Rectangle r = t.modelToView(pos);
481N/A JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
481N/A r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
481N/A r.height += p.getHeight() * 4 / 5;
481N/A t.scrollRectToVisible(r);
481N/A } catch (BadLocationException ignore) {
481N/A }
481N/A }
481N/A });
481N/A }
481N/A
481N/A private JComboBox entries;
481N/A private JTextField checkField;
481N/A private InfoPanel enclPanel;
481N/A private InfoPanel selfPanel;
481N/A private JTextArea body;
481N/A private JTextField statusText;
481N/A
481N/A private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
481N/A private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
481N/A
481N/A /** Panel to display an Info object. */
481N/A private class InfoPanel extends JPanel {
481N/A InfoPanel() {
481N/A add(tagName = createTextField(20));
481N/A add(new JLabel("start:"));
481N/A add(addListener(start = createTextField(6)));
481N/A add(new JLabel("pos:"));
481N/A add(addListener(pos = createTextField(6)));
481N/A add(new JLabel("end:"));
481N/A add(addListener(end = createTextField(6)));
481N/A }
481N/A
481N/A void setInfo(Info info) {
481N/A this.info = info;
481N/A tagName.setText(tagNames.get(info.tag));
481N/A start.setText(String.valueOf(info.start));
481N/A pos.setText(String.valueOf(info.pos));
481N/A end.setText(String.valueOf(info.end));
481N/A }
481N/A
481N/A JTextField addListener(final JTextField f) {
481N/A f.addMouseListener(new MouseAdapter() {
481N/A @Override
481N/A public void mouseClicked(MouseEvent e) {
481N/A body.setCaretPosition(Integer.valueOf(f.getText()));
481N/A body.getCaret().setVisible(true);
481N/A }
481N/A });
481N/A return f;
481N/A }
481N/A
481N/A Info info;
481N/A JTextField tagName;
481N/A JTextField start;
481N/A JTextField pos;
481N/A JTextField end;
481N/A }
481N/A
481N/A /** Object to record information about an error to be displayed. */
481N/A private class Entry {
481N/A Entry(JavaFileObject file, String check, Info encl, Info self) {
481N/A this.file = file;
481N/A this.check = check;
481N/A this.encl = encl;
481N/A this.self= self;
481N/A }
481N/A
481N/A @Override
481N/A public String toString() {
481N/A return file.getName() + " " + check + " " + getMinPos(encl, self);
481N/A }
481N/A
481N/A final JavaFileObject file;
481N/A final String check;
481N/A final Info encl;
481N/A final Info self;
481N/A }
481N/A }
481N/A}
481N/A