index
int64
repo_id
string
file_path
string
content
string
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/AssertionFailedError.java
package abbot; import java.io.File; import abbot.i18n.Strings; import abbot.script.Step; import abbot.script.Script; /** Indirect usage to avoid too much direct linkage to JUnit. */ public class AssertionFailedError extends junit.framework.AssertionFailedError { private File file; private int line; public AssertionFailedError() { } public AssertionFailedError(String msg) { super(msg); } public AssertionFailedError(String msg, Step step) { super(getMessage(msg, step)); this.file = Script.getFile(step); this.line = Script.getLine(step); } public File getFile() { return file; } public int getLine() { return line; } private static String getMessage(String msg, Step step) { File file = Script.getFile(step); int line = Script.getLine(step); if (file == null || line <= 0) return msg; return Strings.get("step.failure", new Object[] { msg, file, new Integer(line) }); } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/BugReport.java
package abbot; import javax.swing.UIManager; import java.io.*; import abbot.tester.Robot; import abbot.i18n.Strings; /** Exception for reporting unexpected situations in the program. * Automatically generates a message suitable for posting in a bug report. */ public class BugReport extends Error implements Version { private static final String LS = System.getProperty("line.separator"); private static final String BUGREPORT_URL = Strings.get("bugreport.url"); private static String getReportingInfo() { return Strings.get("bugreport.info", new Object[] { LS + BUGREPORT_URL + LS }); } public static String getSystemInfo() { return "" + "abbot version: " + VERSION + LS + " mode: " + Robot.getEventModeDescription() + LS + " OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ") " + LS + " Java version: " + System.getProperty("java.version") + " (vm " + System.getProperty("java.vm.version") + ")" + LS + " Classpath: " + System.getProperty("java.class.path") + LS + "Look and Feel: " + UIManager.getLookAndFeel(); } private String errorMessage; private Throwable throwable; public BugReport(String error) { this(error, null); } public BugReport(String error, Throwable thr) { super(error); this.errorMessage = error; this.throwable = thr; } public String toString() { String exc = ""; if (throwable != null) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); exc = writer.toString(); } return errorMessage + LS + getReportingInfo() + LS + getSystemInfo() + LS + exc; } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/ExitException.java
package abbot; /** Provide a tagging interface and storage for attempted exits from code under test. */ public class ExitException extends SecurityException { private int status; public ExitException(String msg, int status) { super(msg + " (" + status + ") on " + Thread.currentThread()); this.status = status; Log.log("Exit exception created at " + Log.getStack(Log.FULL_STACK, this)); } public int getStatus() { return status; } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/InterruptedAbbotException.java
package abbot; import abbot.tester.FailedException; /** * Record the case where the current thread has been interrupted, * a proxy for the normal */ public class InterruptedAbbotException extends FailedException { // public WaitTimedOutError() { } public InterruptedAbbotException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/Log.java
// $Id: Log.java 2866 2014-08-14 08:37:05Z gdavison $ // Copyright (c) Oculus Technologies Corporation, all rights reserved // ---------------------------------------------------------------------------- package abbot; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Vector; import abbot.util.Tee; /** Various logging, assertion, and debug routines. Typical usage is to include the following code <blockquote><code><pre> public static void main(String[] args) { &nbsp; args = Log.{@link Log#init(String[]) init}(args) &nbsp; ... } </pre></code></blockquote> at an application's main entry point. This way the Log class can remove its options from the full set passed into the application. See the {@link #init(String[]) Log.init} method for initialization options. <p> General usage notes on public functions:<p> <ul> <li>{@link #warn(String)}<br> Programmer warnings; things that you think shouldn't be happening or indicate something might be wrong. Warnings typically mean "Something happened that I didn't expect would happen".<p> <li>{@link #log(String)}<br> Important information that might be needed for later reference; things the user or debugger might be interested in. By default, all messages go here. Logs are made available so that the customer may provide us with an accurate record of software activity.<br> All warnings and failed assertions are written to the log. Debug statements are also written to log in non-release code.<p> <li>{@link #debug(String)}<br> Any messages which might be useful for debugging. </ul> <p> Per-class stack trace depth can be specified when adding a class, e.g. classname[:stack-depth].<p> Extraction of the stack trace and logging to file are performed on a separate thread to minimize performance impact due to filesystem delays. Use {@link #setSynchronous(boolean) setSynchronous(false)} if you want the output to be asynchronous with program execution.<p> @author [email protected] */ public class Log { /** No instantiations. */ protected Log() { } private static final int LOG = 0x0001; private static final int WARN = 0x0002; private static final int DEBUG = 0x0004; private static final class StdErrTee extends Tee { private StdErrTee(PrintStream p1) { super(STDERR, p1); } public String toString() { return "<stderr> and log"; } } private static final class StdOutTee extends Tee { private StdOutTee(PrintStream p1) { super(STDOUT, p1); } public String toString() { return "<stdout> and log"; } } private static class Context extends Throwable { public Throwable thrown; public int type; public Context(int type) { this.type = type; } public Context(int type, Throwable t) { this(type); this.thrown = t; } } private static final String NL = System.getProperty("line.separator"); /** Mnemonic to print all lines of a stack trace. */ public static final int FULL_STACK = 0; /** No stack, just a message. */ public static final int NO_STACK = -1; /** Mnemonic to print the default number of lines of stack trace. */ private static final int CLASS_STACK_DEPTH = -2; private static final String STDOUT_NAME = "<stdout>"; /** Basic warning categories. FIXME use these. public static final int ERROR = 0x0001; public static final int WARNING = 0x0002; public static final int DEBUG = 0x0004; public static final int INFO = 0x0008;*/ /** Whether log output is synchronous */ private static boolean synchronous = true; /** Whether to log messages. Default on so that we capture output until * the log file has been set or not set in <code>#init()</code>. */ private static boolean logMessages = true; /** Whether to send anything to the console. */ private static boolean echoToConsole = true; private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; /** Whether to show threads in debug output. */ private static boolean showThreads = false; /** Default number of lines of stack trace to print. */ private static int debugStackDepth; /** Default number of lines of stack trace to log. */ private static int logStackDepth; /** Default number of lines of exception stack trace to print. */ private static int excStackDepth; /** Show timestamps in the log? */ private static boolean showTimestamp = true; private static java.text.DateFormat timestampFormat = new java.text.SimpleDateFormat("yyMMdd HH:mm:ss:SSS"); /** Strip this out of output, since it doesn't add information to see it repeatedly. */ private static final String COMMON_PREFIX = "com.oculustech.DOME.client"; private static final boolean ECLIPSE = System.getProperty("java.class.path").indexOf("eclipse") != -1; /** Store which class names we want to see debug info for. */ private static Map debugged = new HashMap(); /** Store which class names we don't want to see debug info for */ private static Set notdebugged = new HashSet(); /** Debug all classes? */ private static boolean debugAll; /** Treat inner/anonymous classes as outer class? */ private static boolean debugInner = true; private static final String DEFAULT_LOGFILE_NAME = "co-log.txt"; private static ByteArrayOutputStream preInitLog = new ByteArrayOutputStream(); private static PrintStream logStream; /** Stream which ensures a copy goes to stdout */ private static PrintStream debugStream; /** Stream which ensures a copy goes to stderr */ private static PrintStream warnStream; private static LogThread logThread; private static String logFilename; private static boolean showWarnings = true; private static PrintStream BUFFER = new PrintStream(preInitLog); //private static PrintStream STDOUT_AND_BUFFER = new Tee(STDOUT, BUFFER); static { setDestination(BUFFER); logThread = new LogThread(); logThread.start(); debugStackDepth = Integer. getInteger("co.debug_stack_depth", 1).intValue(); logStackDepth = Integer. getInteger("co.log_stack_depth", NO_STACK).intValue(); excStackDepth = Integer. getInteger("co.exception_stack_depth", FULL_STACK).intValue(); // Make sure the log gets closed on System.exit Runtime.getRuntime().addShutdownHook(new Thread("Log shutdown hook") { public void run() { close(); } }); } /** Debug/log initialization, presumably from the command line. <br>Recognized options: <pre> --debug all | className[:depth] | *.partialClassName[:depth] --no-debug className | *.partialClassName --log <log file name> --no-timestamp --enable-warnings --show-threads --stack-depth <depth> --exception-depth <depth> </pre> */ public static String[] init(String[] args){ logMessages = false; ArrayList newArgs = new ArrayList(); for (int i=0;i < args.length;i++){ if (args[i].equals("--enable-warnings")){ showWarnings = true; setEchoToConsole(true); } else if (args[i].equals("--no-timestamp")) { showTimestamp = false; } else if (args[i].equals("--show-threads")){ showThreads = true; } else if (args[i].equals("--keep-console")){ setEchoToConsole(true); } else if (args[i].equals("--stack-depth")) { if (++i < args.length) { try { debugStackDepth = Integer.parseInt(args[i]); } catch(Exception exc) { } } else { warn("Ignoring --stack-depth with no argument"); } } else if (args[i].equals("--exception-depth")) { if (++i < args.length) { try { excStackDepth = Integer.parseInt(args[i]); } catch(Exception exc) { } } else { warn("Ignoring --exception-depth with no argument"); } } else if (args[i].equals("--debug") || args[i].equals("--no-debug")) { if (++i < args.length) { boolean exclude = args[i].startsWith("--no"); if (exclude) removeDebugClass(args[i]); else { addDebugClass(args[i]); setEchoToConsole(true); } } else { warn("Ignoring " + args[i-1] + " with no argument"); } } else if (args[i].equals("--log")){ String filename = DEFAULT_LOGFILE_NAME; if (++i < args.length) { filename = args[i]; } initLogging(filename); } else { newArgs.add(args[i]); } } return (String[])newArgs.toArray(new String[newArgs.size()]); } /** Is log output enabled? */ public static boolean loggingInitialized() { return logMessages && logStream != null; } private static String hostname = null; private static final String DEFAULT_HOSTNAME = "unknown"; public static String getHostName() { if(hostname == null) { try { hostname = java.net.InetAddress.getLocalHost().getHostName(); } catch(java.net.UnknownHostException e) { hostname = DEFAULT_HOSTNAME; warn("Cannot get hostname, using " + hostname); } } return hostname; } public static String getLogFilename() { return logFilename; } public static PrintStream getLog() { return logStream; } /** Enable log output to the given file. A filename of "-" means stdout. */ public static void initLogging(String filename) { PrintStream ps = STDOUT; logFilename = STDOUT_NAME; if (!"-".equals(filename) && filename != null) { try { ps = new PrintStream(new FileOutputStream(filename), true); logFilename = filename; } catch(IOException e) { STDERR.println("Unable to write to " + filename); STDERR.println("Output will go to the console"); } } setDestination(ps); log("Log started on " + getHostName() + " (directed to " + logFilename + ")"); // Always insert the system information Log.log(getSystemInfo()); } /** Enable log output to the given {@link PrintStream}. */ public static void setDestination(PrintStream ps) { logMessages = true; logStream = ps; // If there's a log file, redirect stdout/stderr there if (logStream == STDOUT) { debugStream = logStream; warnStream = STDERR; } else if (logStream == BUFFER) { debugStream = new StdOutTee(BUFFER); warnStream = new StdErrTee(BUFFER); } else { if (preInitLog.size() > 0) { ps.print(preInitLog.toString()); preInitLog.reset(); } debugStream = new StdOutTee(logStream); warnStream = new StdErrTee(logStream); System.setErr(warnStream); System.setOut(debugStream); if (logFilename != null) { File file = new File(logFilename); STDOUT.println("Output also captured in the log file at " + file.getAbsolutePath()); } } setEchoToConsole(logStream != STDOUT); } public static String getSystemInfo() { Locale loc = Locale.getDefault(); return "System Details:" + NL + " java: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + NL + " os: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + NL + " user.dir: " + System.getProperty("user.dir") + NL + " locale: " + loc.getDisplayName() + " " + "[" + loc.getLanguage() + " " + loc.getCountry() + "]" + NL + "classpath: " + System.getProperty("java.class.path"); } /** Sets the debug stack depth to the given amount */ public static void setDebugStackDepth(int depth) { debugStackDepth = depth; } /** Resets the lists of classes to debug and not debug to be empty, and turns debugAll off. */ public static void clearDebugClasses() { debugged.clear(); debugAll = false; notdebugged.clear(); } /** Indicate that the given class should NOT be debugged (assuming --debug all) */ public static void removeDebugClass(String className) { setClassDebugEnabled(className, false); } /** Indicate that debug messages should be output for the given class. */ public static void addDebugClass(Class class1) { addDebugClass(class1.getName()); } /** Indicate that debug messages should no longer be output for the given * class. */ public static void removeDebugClass(Class class1) { removeDebugClass(class1.getName()); } /** Indicate the class name[:depth] to add to debug output. */ public static void addDebugClass(String className) { if (className.indexOf(":") == -1) addDebugClass(className, CLASS_STACK_DEPTH); else setClassDebugEnabled(className, true); } /** Indicate that debug messages should be output for the given class. */ public static void addDebugClass(String className, int depth){ setClassDebugEnabled(className + ":" + depth, true); } /** Parse the given string, which may should be of the format "class[:depth]" */ private static void setClassDebugEnabled(String id, boolean enable) { int colon = id.indexOf(":"); String className = colon == -1 ? id : id.substring(0, colon); if ("all".equals(className)) { debugAll = enable; if (enable) { notdebugged.clear(); } else { debugged.clear(); } } else { className = getFullClassName(className); int depth = CLASS_STACK_DEPTH; try { depth = colon == -1 ? debugStackDepth : Integer.parseInt(id.substring(colon+1)); } catch (NumberFormatException nfe) { } if (enable) { debugged.put(className, new Integer(depth)); notdebugged.remove(className); debug("Debugging enabled for " + className + " (" + depth + ")"); } else { notdebugged.add(className); debugged.remove(className); debug("Debugging disabled for " + className); } } } /** Returns class from given name/descriptor. Descriptor can be either a fully qualified classname, or a classname beginning with *. with client-specific package and classname following. */ private static String getFullClassName(String className) { if (COMMON_PREFIX != null && className.startsWith("*.")) { className = COMMON_PREFIX + className.substring(1); } return className; } /** Return the requested number of levels of stack trace, not including this call. Returns the full stack trace if LINES is FULL_STACK. Skip the first POP frames of the trace, which is for excluding the innermost stack frames when debug functions make nested calls. The outermost call of getStackTrace itself is always removed from the trace. */ private static String getStackTrace(int pop, int lines) { return getStackTrace(pop, lines, new Throwable("--debug--")); } /** Return the requested number of levels of stack trace, not including this call. Returns the full stack trace if LINES is FULL_STACK. Skip the first POP frames of the trace, which is for excluding the innermost stack frames when debug functions make nested calls. The outermost call of getStackTrace itself is always removed from the trace. Provide an exception to use for the stack trace, rather than using the current program location. */ private static String getStackTrace(int pop, int lines, Throwable thr) { if (lines != NO_STACK) { String stack = getStackTrace(pop, thr); if (lines == FULL_STACK) return stack; return trimStackTrace(stack, lines); } return ""; } /** Return the stack trace contained in the given Throwable. Skip the first POP frames of the trace, which is for excluding the innermost stack frames when debug functions make nested calls. The outermost call of getStackTrace itself is always removed from the trace. */ private static String getStackTrace(int pop, Throwable thr){ OutputStream os = new ByteArrayOutputStream(); PrintStream newStream = new PrintStream(os, true); // OUCH! this is a serious performance hit! thr.printStackTrace(newStream); String trace = os.toString(); // Pop off getStackTrace itself // Skip over any calls to getStackTrace; the JIT sometimes puts a // spurious entry, so don't just stop at the first one. int getLoc = trace.lastIndexOf("getStackTrace"); int at = trace.indexOf("\tat ", getLoc); if (at != -1) trace = trace.substring(at + 3); while (pop-- > 0){ // pop off the calling function at = trace.indexOf("\tat "); if (at != -1) trace = trace.substring(at + 3); } return trace.trim(); } /** Trim the given trace to LINES levels. */ private static String trimStackTrace(String trace, int lines) { // Keep just as many lines as were requested int end = trace.indexOf(")") + 1; boolean all = (lines == FULL_STACK); while (all || --lines > 0) { int index = trace.indexOf("\tat ", end); if (index < 0) break; end = trace.indexOf(")", index) + 1; } return trace.substring(0, end); } /** Return the class corresponding to the first line in the give stack trace. Treat inner/anonymous classes as the enclosing class. */ // FIXME with JIT enabled, stack trace sometimes has spurious junk on the // stack, which will indicate the wrong class... private static String extractClass(String trace){ int paren = trace.indexOf("("); String tmp = paren == -1 ? trace : trace.substring(0, paren); int mstart = tmp.lastIndexOf("."); String cname = mstart == -1 ? tmp : tmp.substring(0, mstart); cname = cname.trim(); if (debugInner) { int sub = cname.indexOf("$"); if (sub != -1) cname = cname.substring(0, sub).trim(); } return cname; } public static boolean isClassDebugEnabled(Class cls) { return isClassDebugEnabled(cls.getName()); } public static boolean isClassDebugEnabled(String className) { return (debugAll || debugged.containsKey(className)) && !notdebugged.contains(className); } static int getClassStackDepth(String cname) { Integer depth = (Integer)debugged.get(cname); if (depth != null && depth.intValue() != CLASS_STACK_DEPTH) return depth.intValue(); return debugStackDepth; } /** Print a debug message. */ public static void debug(String event){ internalDebug(event, new Context(DEBUG)); } /** Print a debug message with the given number of stack lines. */ public static void debug(String event, int lines){ internalDebug(event, new Context(DEBUG), lines); } /** Use this to display debug output for expected or common exceptions. */ public static void debug(Throwable thr) { internalDebug("", new Context(DEBUG, thr)); } /** Issue a debug statement regarding the given {@link Throwable}. */ public static void debug(String m, Throwable e) { internalDebug(m, new Context(DEBUG, e)); } private static void internalDebug(String msg, Context context) { internalDebug(msg, context, CLASS_STACK_DEPTH); } private static void internalDebug(String msg, Context context, int lines) { if (debugged.size() > 0 || debugAll) { internalLog(msg, context, lines, 1, echoToConsole ? debugStream : logStream); } } /** Replace all occurrences of a given expresion with a different string. */ private static String abbreviate(String msg, String expr, String sub) { // Eclipse uses the full classs name for navigation, so don't hide it if (ECLIPSE) return msg; StringBuffer sb = new StringBuffer(msg); int index = msg.indexOf(expr); int len = expr.length(); while (index >= 0){ sb.replace(index, index + len, sub); index = sb.toString().indexOf(expr); } return sb.toString(); } /** Strip out stuff we don't want showing in the message. */ private static String abbreviate(String msg){ if (COMMON_PREFIX != null) msg = abbreviate(msg, COMMON_PREFIX, "*"); return msg; } /** Issue a warning. All warnings go to the log file and the error stream. */ private static void internalWarn(String message, Context context, int depth, int pop){ internalLog(message, context, depth, pop, showWarnings ? warnStream : logStream); } /** Retrieve the given number of lines of the current stack, as a string. */ public static String getStack(int lines){ return getStackTrace(1, lines); } /** Retrieve the full stack from the given Throwable, as a string. */ public static String getStack(Throwable t) { return getStackTrace(Log.FULL_STACK, t); } /** Retrieve the given number of lines of stack from the given Throwable, as a string. */ public static String getStack(int lines, Throwable thr){ return getStackTrace(1, lines, thr); } /** Issue a programmer warning, which will include the source line of the warning. */ public static void warn(String message){ internalWarn(message, new Context(WARN), debugStackDepth, 1); } /** Issue a programmer warning, which will include the source line of the warning. */ public static void warn(String message, Throwable e){ internalWarn(message, new Context(WARN, e), debugStackDepth, 1); } /** Issue a programmer warning, which will include the source line of the warning, and a stack trace with up to the given number of lines. */ public static void warn(String message, int lines){ internalWarn(message, new Context(WARN), lines, 1); } /** Issue a programmer warning, which will include the source line of the original thrown object. */ public static void warn(Throwable thr) { internalWarn("", new Context(WARN, thr), debugStackDepth, 1); } /** Log an exception. */ public static void log(Throwable thr) { internalLog("", new Context(LOG, thr), excStackDepth, 1); } /** Log an exception with a description. */ public static void log(String message, Throwable thr) { internalLog(message, new Context(LOG, thr), excStackDepth, 1); } /** Log a message. */ public static void log(String message){ internalLog(message, new Context(LOG), logStackDepth, 1); } private static void internalLog(String event, Context context, int depth, int pop) { internalLog(event, context, depth, pop, logStream); } private static void internalLog(String event, Context context, int depth, int pop, PrintStream stream){ String thread = Thread.currentThread().getName(); if (synchronous) { logMessage(event, new Date(), context, depth, pop, stream, thread); } else if (logThread != null) { logThread.post(event, thread, new Date(), context, depth, pop, stream); } else { STDERR.println("Message posted after close: " + event); } } static void flush() { while (logThread.queue.size() > 0) { synchronized(logThread.queue) { logThread.queue.notifyAll(); } try { Thread.sleep(10); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } debugStream.flush(); warnStream.flush(); logStream.flush(); } public static void close() { flush(); log("Log closed"); logStream.close(); logThread.terminate(); logThread = null; } private static class LogThread extends Thread { private boolean terminate; private Vector queue = new Vector(); public LogThread() { super("Logging thread"); setDaemon(true); } public void terminate() { synchronized(queue) { terminate = true; queue.notifyAll(); } } public void post(String msg, String threadName, Date date, Context throwable, int depth, int pop, PrintStream output) { synchronized(queue) { if (!terminate) { queue.add(new Object[]{ msg, date, throwable, new int[] { depth, pop }, output, threadName }); queue.notifyAll(); } else { STDERR.println("discarded: " + msg); } } } public void run() { setName("Logging thread (to " + logStream + ")"); while (!terminate) { try { while (queue.size() > 0) { Object[] list = (Object[])queue.get(0); int[] args = (int[])list[3]; logMessage((String)list[0], (Date)list[1], (Context)list[2], args[0], args[1], (PrintStream)list[4], (String)list[5]); queue.remove(0); } synchronized(queue) { if (queue.size() == 0) { queue.wait(); } } } catch(InterruptedException e) { break; } catch(Throwable e) { STDERR.println("Error in logging thread: " + e); e.printStackTrace(); } } } } private static String lastMessage = null; private static int lastMessageRepeatCount = 0; private static String lastMessageTimestamp = null; private static PrintStream lastMessageStream = null; private static void logMessage(String msg, Date date, Context context, int depth, int pop, PrintStream stream, String threadName) { boolean debug = context.type == DEBUG; String trace; if (debug) { trace = getStackTrace(pop, Log.FULL_STACK, context); String cname = extractClass(trace); if (!isClassDebugEnabled(cname)) { return; } if (depth == CLASS_STACK_DEPTH) { trace = trimStackTrace(trace, getClassStackDepth(cname)); } } else { trace = getStackTrace(pop, depth, context); } if (context.thrown != null) { Throwable e = context.thrown; String where = getStackTrace(0, excStackDepth, e); String type = e instanceof Error ? "Error" : "Exception thrown"; trace = type + " at " + where + ": " + e + NL + "\t(caught at " + trace + ")"; if (e instanceof InvocationTargetException) { e = ((InvocationTargetException)e).getTargetException(); where = getStackTrace(0, excStackDepth, e); trace += NL + "Target exception was " + e + " at " + where; } else if (e instanceof UndeclaredThrowableException) { e = ((UndeclaredThrowableException)e).getUndeclaredThrowable(); where = getStackTrace(0, excStackDepth, e); trace += NL + "Undeclared exception was " + e + " at " + where; } else if (e instanceof ExceptionInInitializerError) { e = ((ExceptionInInitializerError)e).getException(); where = getStackTrace(0, excStackDepth, e); trace += NL + "Exception was " + e + " at " + where; } } trace = abbreviate(trace); if (showThreads) { trace = "[" + threadName + "] " + trace; } String timestamp = timestampFormat.format(date); if (showTimestamp) { trace = timestamp + " " + trace; } String output = trace.trim(); if (msg != null && !"".equals(msg)) { output += ":\n\t" + msg; } if (stream == lastMessageStream && (msg == lastMessage || (msg != null && msg.equals(lastMessage)))) { ++lastMessageRepeatCount; lastMessageTimestamp = timestamp; } else { if (lastMessageRepeatCount > 0) { lastMessageStream.println(lastMessageTimestamp + ": Last message repeated " + lastMessageRepeatCount + " times"); lastMessageStream.flush(); } stream.println(output); lastMessage = msg; lastMessageStream = stream; lastMessageRepeatCount = 0; lastMessageTimestamp = timestamp; } } /** Set whether log output is synchronous with program execution. */ public static void setSynchronous(boolean b) { synchronous = b; } /** Set whether to display the current thread of execution. */ public static void setShowThreads(boolean b) { showThreads = b; } /** Set whether messages are echoed to the console in addition to the log. */ public static void setEchoToConsole(boolean b) { echoToConsole = b; } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/NoExitSecurityManager.java
package abbot; public abstract class NoExitSecurityManager extends SecurityManager { private Exception creation; public NoExitSecurityManager() { class CreationLocationException extends Exception { } creation = new CreationLocationException(); } public void checkPermission(java.security.Permission perm, Object context) { // allow everything } public void checkPermission(java.security.Permission perm) { // allow everything } /** * Returns true if the exit has been invoked through a call * of Runtime.exit or Runtime.halt . * * @return true <=> An exit has been invoked through a call of Runtime.exit / Runtime.halt . */ public boolean exitInvoked() { // We only want to disallow Runtime.halt/Runtime.exit // Anything else is ok (e.g. System.runFinalizersOnExit; some VMs do a // check there as well -- 1.3 and prior, I think) String stack = Log.getStack(Log.FULL_STACK); return( (stack.indexOf("java.lang.Runtime.exit") != -1) || (stack.indexOf("java.lang.Runtime.halt") != -1) ); } public void checkExit(int status) { if (exitInvoked()) { exitCalled(status); String msg = "Application exit denied"; Log.log(msg + " from security manager " + "created at " + Log.getStack(Log.FULL_STACK, creation)); throw new ExitException(msg, status); } } /** Implement this method to do any context-specific cleanup. This hook is provided since it may not always be possible to catch the ExitException explicitly (like when it's caught by someone else, or thrown from the event dispatch thread). */ protected abstract void exitCalled(int status); }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/Platform.java
package abbot; import java.util.StringTokenizer; /** Simple utility to figure out what platform we're on, what java version * we're running. */ public class Platform { public static final int JAVA_1_0 = 0x1000; public static final int JAVA_1_1 = 0x1100; public static final int JAVA_1_2 = 0x1200; public static final int JAVA_1_3 = 0x1300; public static final int JAVA_1_4 = 0x1400; public static final int JAVA_1_5 = 0x1500; public static final int JAVA_1_6 = 0x1600; public static final int JAVA_1_7 = 0x1700; public static final int JAVA_1_8 = 0x1800; public static final int JAVA_1_9 = 0x1900; public static final String OS_NAME; public static final String JAVA_VERSION_STRING; public static final int JAVA_VERSION; static { OS_NAME = System.getProperty("os.name"); JAVA_VERSION_STRING = System.getProperty("java.version"); JAVA_VERSION = parse(JAVA_VERSION_STRING); } private static boolean isWindows = OS_NAME.startsWith("Windows"); private static boolean isWindows9X = isWindows && (OS_NAME.indexOf("95") != -1 || OS_NAME.indexOf("98") != -1 || OS_NAME.indexOf("ME") != -1); private static boolean isWindowsXP = isWindows && OS_NAME.indexOf("XP") != -1; private static boolean isMac = System.getProperty("mrj.version") != null; private static boolean isOSX = isMac && OS_NAME.indexOf("OS X") != -1; private static boolean isSunOS = (OS_NAME.startsWith("SunOS") || OS_NAME.startsWith("Solaris")); private static boolean isHPUX = OS_NAME.equals("HP-UX"); private static boolean isLinux = OS_NAME.equals("Linux"); /** No instantiations. */ private Platform() { } private static String strip(String number) { while (number.startsWith("0") && number.length() > 1) number = number.substring(1); return number; } static int parse(String vs) { int version = 0; try { StringTokenizer st = new StringTokenizer(vs, "._"); version = Integer.parseInt(strip(st.nextToken())) * 0x1000; version += Integer.parseInt(strip(st.nextToken())) * 0x100; version += Integer.parseInt(strip(st.nextToken())) * 0x10; version += Integer.parseInt(strip(st.nextToken())); } catch(NumberFormatException nfe) { } catch(java.util.NoSuchElementException nse) { } return version; } // FIXME this isn't entirely correct, maybe should look for a motif class // instead. public static boolean isX11() { return !isOSX && !isWindows; } public static boolean isWindows() { return isWindows; } public static boolean isWindows9X() { return isWindows9X; } public static boolean isWindowsXP() { return isWindowsXP; } public static boolean isMacintosh() { return isMac; } public static boolean isOSX() { return isOSX; } public static boolean isSolaris() { return isSunOS; } public static boolean isHPUX() { return isHPUX; } public static boolean isLinux() { return isLinux; } public static boolean is6OrAfter() { return JAVA_VERSION>=JAVA_1_6; } public static boolean is7OrAfter() { return JAVA_VERSION>=JAVA_1_7; } public static boolean is8OrAfter() { return JAVA_VERSION>=JAVA_1_8; } public static boolean isBefore7() { return JAVA_VERSION<JAVA_1_7; } public static boolean isBefore8() { return JAVA_VERSION<JAVA_1_8; } public static boolean is6() { return JAVA_VERSION>=JAVA_1_6 && JAVA_VERSION<JAVA_1_7; } public static boolean is7() { return JAVA_VERSION>=JAVA_1_7 && JAVA_VERSION<JAVA_1_8; } public static boolean is8() { return JAVA_VERSION>=JAVA_1_8 && JAVA_VERSION<JAVA_1_9; } public static void main(String[] args) { System.out.println("Java version is " + JAVA_VERSION_STRING); System.out.println("Version number is " + Integer.toHexString(JAVA_VERSION)); System.out.println("os.name=" + OS_NAME); } }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/Version.java
package abbot; /** Current version of the framework. */ public interface Version { String VERSION = "1.4.0-SNAPSHOT"; }
0
java-sources/abbot/abbot/1.4.0
java-sources/abbot/abbot/1.4.0/abbot/WaitTimedOutException.java
package abbot; import abbot.tester.FailedException; /** * Record the case where are have failed to wait for something, used to * extend an AssertionError; but now extends FailException so we get the * extra diagnostics. */ public class WaitTimedOutException extends FailedException { // public WaitTimedOutError() { } public WaitTimedOutException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/AWTHierarchy.java
package abbot.finder; import javax.swing.*; import abbot.Log; import abbot.ExitException; import abbot.tester.WindowTracker; import abbot.tester.Robot; import abbot.util.AWT; import java.awt.Component; import java.awt.Container; import java.awt.Window; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; /** Provides access to the current AWT hierarchy. */ public class AWTHierarchy implements Hierarchy { protected static final WindowTracker tracker = WindowTracker.getTracker(); protected static final Collection EMPTY = new ArrayList(); private static Hierarchy defaultHierarchy = null; /** Obtain a default Hierarchy. This method is provided only to support * the deprecated <code>ComponentTester.assertFrameShowing()</code> method. */ public static Hierarchy getDefault() { /*System.out.println("Using default Hierarchy: " + Log.getStack(Log.FULL_STACK));*/ return defaultHierarchy != null ? defaultHierarchy : new AWTHierarchy(); } /** Set the default Hierarchy. This method is provided only to support * the deprecated <code>ComponentTester.assertFrameShowing()</code> method. */ public static void setDefault(Hierarchy h) { defaultHierarchy = h; } /** Returns whether the given component is reachable from any of the root * windows. The default is to consider all components to be contained in * the hierarchy, whether they are reachable or not (NOTE: isReachable is * a distinctly different operation). */ public boolean contains(Component c) { return true; } /** Properly dispose of the given Window, making it and its native * resources available for garbage collection. */ public void dispose(final Window w) { if (AWT.isAppletViewerFrame(w)) { // Don't dispose, it must quit on its own return; } Log.debug("Dispose " + w); Window[] owned = w.getOwnedWindows(); for (int i=0;i < owned.length;i++) { // Window.dispose is recursive; make Hierarchy.dispose recursive // as well. dispose(owned[i]); } if (AWT.isSharedInvisibleFrame(w)) { // Don't dispose, or any child windows which may be currently // ignored (but not hidden) will be hidden and disposed. return; } // Ensure the dispose is done on the swing thread so we can catch any // exceptions. If Window.dispose is called from a non-Swing thread, // it will invokes the dispose action on the Swing thread but in that // case we have no control over exceptions. Runnable action = new Runnable() { public void run() { try { // Distinguish between the abbot framework disposing a // window and anyone else doing so. System.setProperty("abbot.finder.disposal", "true"); w.dispose(); System.setProperty("abbot.finder.disposal", "false"); } catch(NullPointerException npe) { // Catch bug in AWT 1.3.1 when generating hierarchy // events Log.log(npe); } catch(ExitException e) { // Some apps might call System.exit on WINDOW_CLOSED Log.log("Ignoring SUT exit: " + e); } catch(Throwable e) { // Don't allow other exceptions to interfere with // disposal. Log.warn(e); Log.warn("An exception was thrown when disposing " + " the window " + Robot.toString(w) + ". The exception is ignored"); } } }; if (SwingUtilities.isEventDispatchThread()) { action.run(); } else { try { SwingUtilities.invokeAndWait(action); } catch(Exception e) { } } } /** Return all root components in the current AWT hierarchy. */ public Collection getRoots() { return tracker.getRootWindows(); } /** Return all descendents of interest of the given Component. This includes owned windows for Windows, children for Containers. */ public Collection getComponents(Component c) { if (c instanceof Container) { final Container cont = (Container)c; Callable<List> componentListClosure = new Callable<List>() { @Override public List call() { List list = new ArrayList(); list.addAll(Arrays.asList(cont.getComponents())); // Add other components which are not explicitly children, but // that are conceptually descendents if (cont instanceof JMenu) { list.add(((JMenu)cont).getPopupMenu()); } else if (cont instanceof Window) { list.addAll(Arrays.asList(((Window)cont).getOwnedWindows())); } else if (cont instanceof JDesktopPane) { // Add iconified frames, which are otherwise unreachable. // For consistency, they are still considerered children of // the desktop pane. list.addAll(findInternalFramesFromIcons(cont)); } return list; } }; List list = abbot.tester.Robot.callAndWait(cont, componentListClosure); // List list; // // try { // list = componentListClosure.call(); // } catch (Exception e) { // throw new RuntimeException(e); // } return list; } return EMPTY; } private Collection findInternalFramesFromIcons(Container cont) { ArrayList list = new ArrayList(); int count = cont.getComponentCount(); for (int i=0;i < count;i++) { Component child = cont.getComponent(i); if (child instanceof JInternalFrame.JDesktopIcon) { JInternalFrame frame = ((JInternalFrame.JDesktopIcon)child). getInternalFrame(); if (frame != null) list.add(frame); } // OSX puts icons into a dock; handle icon manager situations here else if (child instanceof Container) { list.addAll(findInternalFramesFromIcons((Container)child)); } } return list; } public Container getParent(Component c) { // This call appears to be fairly thread safe Container p = c.getParent(); if (p == null && c instanceof JInternalFrame) { // workaround for bug in JInternalFrame: COMPONENT_HIDDEN is sent // before the desktop icon is set, so // JInternalFrame.getDesktopPane will throw a NPE if called while // dispatching that event. Reported against 1.4.x. JInternalFrame.JDesktopIcon icon = ((JInternalFrame)c).getDesktopIcon(); if (icon != null) { p = icon.getDesktopPane(); } // p = ((JInternalFrame)c).getDesktopPane(); } return p; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/BasicFinder.java
package abbot.finder; import java.awt.Container; import java.awt.Component; import java.awt.Window; import java.util.*; import javax.swing.SwingUtilities; import abbot.i18n.Strings; /** Provides basic component lookup, examining each component in turn. Searches all components of interest in a given hierarchy. */ public class BasicFinder implements ComponentFinder { private Hierarchy hierarchy; private static final ComponentFinder DEFAULT = new BasicFinder(new AWTHierarchy()); public static ComponentFinder getDefault() { return DEFAULT; } private class SingleComponentHierarchy implements Hierarchy { private Component root; private ArrayList list = new ArrayList(); public SingleComponentHierarchy(Container root) { this.root = root; list.add(root); } public Collection getRoots() { return list; } public Collection getComponents(Component c) { return getHierarchy().getComponents(c); } public Container getParent(Component c) { return getHierarchy().getParent(c); } public boolean contains(Component c) { return getHierarchy().contains(c) && SwingUtilities.isDescendingFrom(c, root); } public void dispose(Window w) { getHierarchy().dispose(w); } } public BasicFinder() { this(AWTHierarchy.getDefault()); } public BasicFinder(Hierarchy h) { hierarchy = h; } protected Hierarchy getHierarchy() { return hierarchy; } /** Find a Component, using the given Matcher to determine whether a given component in the hierarchy under the given root is the desired one. */ public Component find(Container root, Matcher m) throws ComponentNotFoundException, MultipleComponentsFoundException { Hierarchy h = root != null ? new SingleComponentHierarchy(root) : getHierarchy(); return find(h, m); } /** Find a Component, using the given Matcher to determine whether a given component in the hierarchy used by this ComponentFinder is the desired one. */ public Component find(Matcher m) throws ComponentNotFoundException, MultipleComponentsFoundException { return find(getHierarchy(), m); } protected Component find(Hierarchy h, Matcher m) throws ComponentNotFoundException, MultipleComponentsFoundException { Set found = new HashSet(); Iterator iter = h.getRoots().iterator(); while (iter.hasNext()) { findMatches(h, m, (Component)iter.next(), found); } if (found.size() == 0) { String msg = Strings.get("finder.not_found", new Object[] { m.toString() }); throw new ComponentNotFoundException(msg); } else if (found.size() > 1) { Component[] list = (Component[]) found.toArray(new Component[found.size()]); if (!(m instanceof MultiMatcher)) { String msg = Strings.get("finder.multiple_found", new Object[] { m.toString() }); throw new MultipleComponentsFoundException(msg, list); } return ((MultiMatcher)m).bestMatch(list); } return (Component)found.iterator().next(); } protected void findMatches(Hierarchy h, Matcher m, Component c, Set found) { if (found.size() == 1 && !(m instanceof MultiMatcher)) return; Iterator iter = h.getComponents(c).iterator(); while (iter.hasNext()) { findMatches(h, m, (Component)iter.next(), found); } if (m.matches(c)) { found.add(c); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentFinder.java
package abbot.finder; import java.awt.*; /** Interface to support looking up existing components based on a number of different criteria. @see Matcher */ public interface ComponentFinder { /** Find a Component, using the given Matcher to determine whether a given component in the hierarchy used by this ComponentFinder is the desired one. <p> Note that {@link MultipleComponentsFoundException} can only be thrown if the {@link Matcher} argument is an instance of {@link MultiMatcher}. */ Component find(Matcher m) throws ComponentNotFoundException, MultipleComponentsFoundException; /** Find a Component, using the given Matcher to determine whether a given component in the hierarchy under the given root is the desired one. <p> Note that {@link MultipleComponentsFoundException} can only be thrown if the {@link Matcher} argument is an instance of {@link MultiMatcher}. */ Component find(Container root, Matcher m) throws ComponentNotFoundException, MultipleComponentsFoundException; }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentNotFoundException.java
package abbot.finder; /** Indicates no component could be found, where one was required. */ public class ComponentNotFoundException extends ComponentSearchException { public ComponentNotFoundException() { } public ComponentNotFoundException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentSearchException.java
package abbot.finder; /** General exception class which encapsulates all failures generated * attempting to find a component in the currently available GUI. */ public class ComponentSearchException extends Exception { public ComponentSearchException() { } public ComponentSearchException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/Hierarchy.java
package abbot.finder; import java.awt.Component; import java.awt.Container; import java.awt.Window; import java.util.Collection; /** Provides access to all components in a hierarchy. */ public interface Hierarchy { /** Provides all root components in the hierarchy. Similar to * Frame.getFrames(). */ Collection getRoots(); /** Returns all sub-components of the given component. What constitutes a * sub-component may vary depending on the Hierarchy implementation. */ Collection getComponents(Component c); /** Return the parent component for the given Component. */ Container getParent(Component c); /** Returns whether the hierarchy contains the given Component. */ boolean contains(Component c); /** Provide proper disposal of the given Window, appropriate to this * Hierarchy. After disposal, the Window and its descendents will no * longer be reachable from this Hierarchy. */ void dispose(Window w); }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/Matcher.java
package abbot.finder; import java.awt.Component; /** Provides an indication whether a Component matches some desired criteria. For use with implementations of {@link ComponentFinder}. You can conveniently inline a custom matcher like so:<br> <pre><code> ComponentFinder finder; ... // Find a label with known text JLabel label = (JLabel)finder.find(new Matcher() { public boolean matches(Component c) { return c instanceof JLabel && "expected text".equals(((JLabel)c).getText()); } }); </code></pre> @see ComponentFinder */ public interface Matcher { /** Return whether the given Component matches some lookup criteria. */ boolean matches(Component c); }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/MultiMatcher.java
package abbot.finder; import java.awt.Component; /** Provides methods for determining the best match among a group of matching components.<p> For use with implementations of {@link ComponentFinder}. You can conveniently inline a custom matcher like so:<br> <pre><code> ComponentFinder finder = BasicFinder.getDefault(); ... // Find the widest label with known text JLabel label = (JLabel)finder.find(new MultiMatcher() { public boolean matches(Component c) { return c instanceof JLabel && "OK".equals(((JLabel)c).getText()); } public Component bestMatch(Component[] candidates) throws MultipleComponentsFoundException { Component biggest = candidates[0]; for (int i=1;i < candidates.length;i++) { if (biggest.getWidth() < candidates[i].getWidth()) biggest = candidates[i]; } return biggest; } }); </code></pre> @see ComponentFinder */ public interface MultiMatcher extends Matcher { /** Returns the best match among all the given candidates, or throws an exception if there is no best match. */ Component bestMatch(Component[] candidates) throws MultipleComponentsFoundException; }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/MultipleComponentsFoundException.java
package abbot.finder; import java.awt.Component; import abbot.tester.Robot; /** Indicates more than one component was found (usually where only one was * desired). */ public class MultipleComponentsFoundException extends ComponentSearchException { Component[] components; public MultipleComponentsFoundException(Component[] list) { components = list; } public MultipleComponentsFoundException(String msg, Component[] list) { super(msg); components = list; } public Component[] getComponents() { return components; } public String toString() { StringBuffer buf = new StringBuffer(super.toString()); buf.append(": "); for (int i=0;i < components.length;i++) { buf.append("\n ("); buf.append(String.valueOf(i)); buf.append(") "); buf.append(Robot.toHierarchyPath(components[i])); buf.append(": "); buf.append(components[i].toString()); } return buf.toString(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/finder/TestHierarchy.java
package abbot.finder; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.SwingUtilities; import abbot.Log; import abbot.util.*; /** Provide isolation of a Component hierarchy to limit consideration to only those Components created during the lifetime of this Hierarchy instance. Extant Components (and any subsequently generated subwindows) are ignored by default.<p> Implicitly auto-filters windows which are disposed (i.e. generate a WINDOW_CLOSED event), but also implicitly un-filters them if they should be shown again. Any Window explicitly disposed with {@link #dispose(Window)} will be ignored permanently.<p> */ public class TestHierarchy extends AWTHierarchy { // Map of components to ignore private Map filtered = new WeakHashMap(); // Map of components implicitly filtered; these will be implicitly // un-filtered if they are re-shown. private Map transientFiltered = new WeakHashMap(); private static boolean trackAppletConsole = Boolean.getBoolean("abbot.applet.track_console"); /** Avoid GC of the weak reference. */ private AWTEventListener listener; /** Create a new TestHierarchy which does not contain any UI * Components which might already exist. */ public TestHierarchy() { this(true); } /** Create a new TestHierarchy, indicating whether extant Components * should be omitted from the Hierarchy. */ public TestHierarchy(boolean ignoreExisting) { if (ignoreExisting) ignoreExisting(); // Watch for introduction of transient dialogs so we can automatically // filter them on dispose (WINDOW_CLOSED). Don't do anything when the // component is simply hidden, since we can't tell whether it will be // re-used. listener = new TransientWindowListener(); } public boolean contains(Component c) { return super.contains(c) && !isFiltered(c); } /** Dispose of the given Window, but only if it currently exists within * the hierarchy. It will no longer appear in this Hierarchy or be * reachable in a hierarchy walk. */ public void dispose(Window w) { if (contains(w)) { super.dispose(w); setFiltered(w, true); } } /** Make all currently extant components invisible to this Hierarchy, * without affecting their current state. */ public void ignoreExisting() { Iterator iter = getRoots().iterator(); while (iter.hasNext()) { setFiltered((Component)iter.next(), true); } } /** Returns all available root Windows, excluding those which have been * filtered. */ public Collection getRoots() { Collection s = super.getRoots(); s.removeAll(filtered.keySet()); return s; } /** Returns all sub-components of the given Component, omitting those * which are currently filtered. */ public Collection getComponents(Component c) { if (!isFiltered(c)) { Collection s = super.getComponents(c); // NOTE: this only removes those components which are directly // filtered, not necessarily those which have a filtered ancestor. s.removeAll(filtered.keySet()); return s; } return EMPTY; } private boolean isWindowFiltered(Component c) { Window w = AWT.getWindow(c); return w != null && isFiltered(w); } /** Returns true if the given component will not be considered when * walking the hierarchy. A Component is filtered if it has explicitly * been filtered via {@link #setFiltered(Component,boolean)}, or if * any <code>Window</code> ancestor has been filtered. */ public boolean isFiltered(Component c) { if (c == null) return false; if ("sun.plugin.ConsoleWindow".equals(c.getClass().getName())) return !trackAppletConsole; return filtered.containsKey(c) || ((c instanceof Window) && isFiltered(c.getParent())) || (!(c instanceof Window) && isWindowFiltered(c)); } /** Indicates whether the given component is to be included in the Hierarchy. If the component is a Window, recursively applies the action to all owned Windows. */ public void setFiltered(Component c, boolean filter) { // Never filter the shared frame if (AWT.isSharedInvisibleFrame(c)) { Iterator iter = getComponents(c).iterator(); while (iter.hasNext()) { setFiltered((Component)iter.next(), filter); } } else { if (filter) { filtered.put(c, Boolean.TRUE); } else { filtered.remove(c); } transientFiltered.remove(c); if (c instanceof Window) { Window[] owned = ((Window)c).getOwnedWindows(); for (int i=0;i < owned.length;i++) { setFiltered(owned[i], filter); } } } } /** Provides for automatic filtering of auto-generated Swing dialogs. */ private class TransientWindowListener implements AWTEventListener { private class DisposeAction implements Runnable { private Window w; public DisposeAction(Window w) { this.w = w; } public void run() { // If the window was shown again since we queued this action, // it will have removed the window from the transientFiltered // set, and we shouldn't filter. if (transientFiltered.containsKey(w)) { setFiltered(w, true); Log.debug("window " + w.getName() + " filtered"); } else { Log.debug("cancel dispose of " + w.getName()); } } } public TransientWindowListener() { // Add a weak listener so we don't leave a listener lingering // about. long mask = WindowEvent.WINDOW_EVENT_MASK | ComponentEvent.COMPONENT_EVENT_MASK; new WeakAWTEventListener(this, mask); } public void eventDispatched(AWTEvent e) { if (e.getID() == WindowEvent.WINDOW_OPENED || (e.getID() == ComponentEvent.COMPONENT_SHOWN && e.getSource() instanceof Window)) { Window w = (Window)e.getSource(); Log.debug("window " + w.getName() + " open/shown"); if (transientFiltered.containsKey(w)) { Log.debug("un-filter window " + w.getName()); setFiltered(w, false); } // Catch new sub-windows of filtered windows (i.e. dialogs // generated by a test harness UI). else if (isFiltered(w.getParent())) { Log.debug("Parent is filtered, filter " + w.getName()); setFiltered(w, true); } } else if (e.getID() == WindowEvent.WINDOW_CLOSED) { final Window w = (Window)e.getSource(); // *Any* window disposal should result in the window being // ignored, at least until it is again displayed. if (!isFiltered(w)) { transientFiltered.put(w, Boolean.TRUE); // Filter this window only *after* any handlers for this // event have finished. Log.debug("queueing dispose of " + w.getName()); SwingUtilities.invokeLater(new DisposeAction(w)); } } } } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/AbstractMatcher.java
package abbot.finder.matchers; import abbot.finder.Matcher; import abbot.util.ExtendedComparator; /** Convenience abstract class to provide regexp-based matching of strings. */ public abstract class AbstractMatcher implements Matcher { /** Provides direct or regexp matching. To match a regular expression, bound the expected string with slashes, e.g. /regular expression/. */ protected boolean stringsMatch(String expected, String actual) { return ExtendedComparator.stringsMatch(expected, actual); } public String toString() { return getClass().getName(); } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/ClassMatcher.java
package abbot.finder.matchers; import java.awt.Component; /** Provides matching of components by class. */ public class ClassMatcher extends AbstractMatcher { private Class cls; private boolean mustBeShowing; public ClassMatcher(Class cls) { this(cls, false); } public ClassMatcher(Class cls, boolean mustBeShowing) { this.cls = cls; this.mustBeShowing = mustBeShowing; } public boolean matches(Component c) { return cls.isAssignableFrom(c.getClass()) && (!mustBeShowing || c.isShowing()); } public String toString() { return "Class matcher (" + cls.getName() + ")"; } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/JMenuItemMatcher.java
package abbot.finder.matchers; import java.awt.Component; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import abbot.finder.Matcher; import abbot.util.ExtendedComparator; import java.util.ArrayList; import java.util.List; /** * Matches a {@link JMenuItem} given a simple label or a menu path of the * format "menu|submenu|menuitem", for example "File|Open|Can of worms". * * @author twall * @version $Id: JMenuItemMatcher.java 2815 2012-01-26 17:37:22Z gdavison $ */ public class JMenuItemMatcher implements Matcher { private String label; public JMenuItemMatcher(String label) { this.label = label; } public static String getPath(JMenuItem item) { Component parent = item.getParent(); if (parent instanceof JPopupMenu) { parent = ((JPopupMenu)parent).getInvoker(); } if (parent instanceof JMenuItem) { return getPath((JMenuItem)parent) + "|" + item.getText(); } return item.getText(); } /** * @param path A path of the form File|Open|Can of worms * @return A list of strings, File, File|Open, File|Open|Can of worms */ public static List splitMenuPath(String path) { // Split the path // int lastFoundIndex = -1; java.util.List selectionPath = new ArrayList(); while ((lastFoundIndex = path.indexOf('|', lastFoundIndex))!=-1) { selectionPath.add(path.substring( 0, lastFoundIndex)); lastFoundIndex = lastFoundIndex + 1; } selectionPath.add(path); return selectionPath; } public boolean matches(Component c) { if (c instanceof JMenuItem) { JMenuItem mi = (JMenuItem)c; String text = mi.getText(); return ExtendedComparator.stringsMatch(label, text) || ExtendedComparator.stringsMatch(label, getPath(mi)); } return false; } public String toString() { return getClass().getSimpleName() + "[" + label + "]"; } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/JMenuMatcher.java
package abbot.finder.matchers; import abbot.finder.Matcher; import abbot.util.ExtendedComparator; import java.awt.Component; import java.util.ArrayList; import java.util.List; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * Extension of JMenuItemMatcher that only matches JMenu rather than * all JMenuItem * * @author gdavison * @version $Id: JMenuMatcher.java 1419 2005-01-05 18:34:48 +0000 (Wed, 05 Jan 2005) twall $ */ public class JMenuMatcher extends JMenuItemMatcher { public JMenuMatcher(String label) { super(label); } public boolean matches(Component c) { if (c instanceof JMenu) { return super.matches(c); } return false; } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/NameMatcher.java
package abbot.finder.matchers; import java.awt.Component; import abbot.util.AWT; /** Provides matching of Components by component name. */ public class NameMatcher extends AbstractMatcher { private String name; /** Construct a matcher that will match any component that has explicitly been assigned the given <code>name</code>. Auto-generated names (e.g. <code>win0</code>, <code>frame3</code>, etc. for AWT (native) based components will not match. */ public NameMatcher(String name) { this.name = name; } /** @return whether the given component has been explicitly assigned the name given in the constructor. */ public boolean matches(Component c) { String cname = c.getName(); if (name == null) return cname == null || AWT.hasDefaultName(c); return stringsMatch(name, cname); } public String toString() { return "Name matcher (" + name + ")"; } }
0
java-sources/abbot/abbot/1.4.0/abbot/finder
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/WindowMatcher.java
package abbot.finder.matchers; import java.awt.*; /** Provides matching of a Window by title or component name. */ public class WindowMatcher extends ClassMatcher { private String id; private boolean mustBeShowing; public WindowMatcher(String id) { this(id, true); } public WindowMatcher(String id, boolean mustBeShowing) { super(Window.class); this.id = id; this.mustBeShowing = mustBeShowing; } public boolean matches(Component c) { return super.matches(c) && (c.isShowing() || !mustBeShowing) && (stringsMatch(id, c.getName()) || (c instanceof Frame && stringsMatch(id, ((Frame)c).getTitle())) || (c instanceof Dialog && stringsMatch(id, ((Dialog)c).getTitle()))); } public String toString() { return "Window matcher (id=" + id + ")"; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/i18n/Strings.java
package abbot.i18n; import java.util.List; import java.lang.ref.WeakReference; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import abbot.Log; import abbot.editor.widgets.TextFormat; /** Provides support for loading localized strings. Bundles may be added by specifying the full resource name or by a simple name located in com.oculustech.i18n.<p> Bundles are searched from most- to least-recently added. */ public class Strings { /** Resources whose name ends with this suffix (".tip") will automatically * be formatted by the tooltip formatter. * @see TextFormat#tooltip */ public static final String TOOLTIP_SUFFIX = ".tip"; /** Resources whose name ends with this suffix (".dlg") will automatically * be formatted by the dialog formatter. * @see TextFormat#dialog */ public static final String DIALOG_SUFFIX = ".dlg"; private static final String PREFIX = Strings.class.getPackage().getName() + "."; private static final String CORE_BUNDLE = "abbot"; private static List bundles = new ArrayList(); static { // Load the default bundle try { addBundle(CORE_BUNDLE); } catch(MissingResourceException e) { String msg = "No resource bundle found in " + CORE_BUNDLE; if (System.getProperty("java.class.path").indexOf("junit") != -1) Log.warn(msg); else throw new Error(msg); } } /** Add the given bundle to the list searched. */ public static ResourceBundle addBundle(String name) throws MissingResourceException { return addBundle(name, null); } /** Add the given bundle to the list searched, loading from the given class loader. The bundle will be weakly referenced. */ public static ResourceBundle addBundle(String name, ClassLoader cl) throws MissingResourceException { boolean wrap = cl != null; if (cl == null) { cl = Strings.class.getClassLoader(); } Locale locale = Locale.getDefault(); ResourceBundle b; try { b = ResourceBundle.getBundle(name, locale, cl); Log.debug("Added resource bundle " + name); } catch(MissingResourceException e) { try { b = ResourceBundle.getBundle(PREFIX + name, locale, cl); Log.debug("Added resource bundle " + PREFIX + name); } catch(MissingResourceException e2) { throw e; } } synchronized(bundles) { bundles.add(0, wrap ? new WeakReference(b) : (Object)b); } return b; } /** Add the given {@link ResourceBundle} as one to be searched. */ public static void addBundle(ResourceBundle b) { synchronized(bundles) { bundles.add(0, b); } } private Strings() { } /** Returns the localized String for the given key, or the key surrounded by '#' if no corresponding localized string is found. */ public static String get(String key) { return get(key, false); } /** Returns the localized string for the given key. If optional is true, return null, otherwise returns the key surrounded by '#' if no corresponding localized string is found. */ public static String get(String key, boolean optional) { String defaultValue = "#" + key + "#"; String value = null; synchronized(bundles) { ListIterator iter = bundles.listIterator(bundles.size()); while (iter.hasPrevious()) { Object bundle = iter.previous(); if (bundle instanceof WeakReference) { bundle = ((WeakReference)bundle).get(); if (bundle == null) { iter.remove(); continue; } } try { value = ((ResourceBundle)bundle).getString(key); } catch(MissingResourceException mre) { } } } if (value == null) { if (!optional) { Log.log("Missing resource '" + key + "'"); value = defaultValue; } } else { if (key.endsWith(TOOLTIP_SUFFIX)) { value = TextFormat.tooltip(value); } else if (key.endsWith(DIALOG_SUFFIX)) { value = TextFormat.dialog(value); } } return value; } /** Returns a formatted localized string for the given key and arguments, or the key if no corresponding localized string is found. Use {@link java.text.MessageFormat} syntax for the format string and arguments. */ public static String get(String key, Object... args) { return new MessageFormat(get(key)).format(args); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/AWTConstants.java
package abbot.tester; import java.awt.Toolkit; import java.awt.event.InputEvent; import abbot.Platform; import abbot.util.AWT; /** Provides shared UI- and action-related constants. */ public interface AWTConstants { int MULTI_CLICK_INTERVAL = 500; // a guess, TODO work out actual value by firing events at a window /** Number of pixels traversed before a drag starts. */ // OSX 10(1.3.1), 5(1.4.1) // Linux/X11: delay+16 // NOTE: could maybe install a drag gesture recognizer, but that's kinda // complex for what you get out of it. int DRAG_THRESHOLD = Platform.isWindows() || Platform.isMacintosh() ? 10 : 16; int BUTTON_MASK = (InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK); int POPUP_MASK = AWT.getPopupMask(); String POPUP_MODIFIER = AWT.getMouseModifiers(POPUP_MASK); boolean POPUP_ON_PRESS = AWT.getPopupOnPress(); int TERTIARY_MASK = AWT.getTertiaryMask(); String TERTIARY_MODIFIER = AWT.getMouseModifiers(TERTIARY_MASK); int MENU_SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); String MENU_SHORTCUT_MODIFIER = AWT.getKeyModifiers(MENU_SHORTCUT_MASK); String MENU_SHORTCUT_STRING = MENU_SHORTCUT_MASK == InputEvent.ALT_MASK ? "alt " : MENU_SHORTCUT_MASK == InputEvent.META_MASK ? "meta " : MENU_SHORTCUT_MASK == InputEvent.SHIFT_MASK ? "shift " : "control "; String MENU_SHORTCUT_KEYCODE = AWT.getKeyCode(AWT.maskToKeyCode(MENU_SHORTCUT_MASK)); // VM also allows ALT, I think int MOVE_MASK = InputEvent.SHIFT_MASK; /** Drag/drop copy mask. */ int COPY_MASK = Platform.isMacintosh() ? InputEvent.ALT_MASK : InputEvent.CTRL_MASK; /** Drag/drop link mask. NOTE: w32 also natively uses ALT, but the VM * doesn't (at least not 1.4.x). */ int LINK_MASK = Platform.isMacintosh() ? InputEvent.ALT_MASK | InputEvent.META_MASK : InputEvent.CTRL_MASK | InputEvent.ALT_MASK; }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/AbstractButtonTester.java
package abbot.tester; import java.awt.Component; import javax.swing.*; public class AbstractButtonTester extends JComponentTester { public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; AbstractButton absButton = ((AbstractButton)comp); String tag = stripHTML(absButton.getText()); if ("".equals(tag) || tag == null) { tag = super.deriveTag(comp); } return tag; } /** AbstractButton click action. */ public void actionClick(final Component c) { /* if (getEventMode() == EM_PROG) { invokeAndWait(new Runnable() { public void run() { ((JButton)c).doClick(); } }); } */ if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; int x = b.getMinimumSize().width / 2; int y = b.getHeight() / 2; super.actionClick(b, x, y); } else { super.actionClick(c); } waitForIdle(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ActionFailedException.java
package abbot.tester; import java.awt.Frame; import java.awt.KeyboardFocusManager; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import javax.swing.FocusManager; /** Indicates that a ComponentTester action failed to execute properly. */ public class ActionFailedException extends FailedException { public ActionFailedException(String msg, Throwable cause) { super(msg, cause); } public ActionFailedException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ButtonTester.java
package abbot.tester; import java.awt.Component; import java.awt.Button; import java.awt.event.ActionEvent; /** Provides Button activation support, since otherwise AWT buttons cannot be * activated in AWT mode. */ public class ButtonTester extends ComponentTester { /** Programmatically clicks the Button if in AWT mode. */ public void click(Component comp, int x, int y, int mask, int count) { if (getEventMode() == EM_AWT) { postEvent(comp, new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, ((Button)comp).getLabel())); } else { super.click(comp, x, y, mask, count); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/CallTimoutFailedException.java
package abbot.tester; import java.awt.Frame; import java.awt.KeyboardFocusManager; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import javax.swing.FocusManager; /** Indicates that a Robot.callAndWait has failed to execute properly. */ public class CallTimoutFailedException extends FailedException { public CallTimoutFailedException(String msg, Throwable cause) { super(msg, cause); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/CheckboxTester.java
package abbot.tester; import java.awt.Checkbox; import java.awt.Component; import java.awt.event.ItemEvent; /** Provides Checkbox activation support, since otherwise AWT buttons cannot be * activated in AWT mode. */ public class CheckboxTester extends ComponentTester { /** Programmatically clicks the Checkbox if in AWT mode. */ public void click(final Component comp, int x, int y, int mask, int count) { if (getEventMode() == EM_AWT) { final Checkbox box = (Checkbox)comp; invokeLater(new Runnable() { public void run() { box.setState(!box.getState()); ItemEvent e = new ItemEvent(box, ItemEvent.ITEM_STATE_CHANGED, box, box.getState() ? 1 : 0); postEvent(box, e); } }); } else { super.click(comp, x, y, mask, count); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ChoiceTester.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import abbot.util.*; /** AWT Choice (ComboBox/picklist) support. */ public class ChoiceTester extends ComponentTester { private int CHOICE_DELAY = Properties.getProperty("abbot.tester.choice_delay", 30000, 0, 60000); private class Listener implements AWTEventListener { public volatile boolean gotChange; private int targetIndex = -1; public Listener(int index) { targetIndex = index; } public void eventDispatched(AWTEvent e) { if (e.getID() == ItemEvent.ITEM_STATE_CHANGED && e.getSource() instanceof Choice) { gotChange = ((Choice)e.getSource()). getSelectedIndex() == targetIndex; } } } /** Select an item by index. */ public void actionSelectIndex(Component c, final int index) { final Choice choice = (Choice)c; int current = choice.getSelectedIndex(); if (current == index) return; // Don't add an item listener, because then we're at the mercy of any // other ItemListener finishing. Don't bother clicking or otherwise // sending events, since the behavior is platform-specific. Listener listener = new Listener(index); new WeakAWTEventListener(listener, ItemEvent.ITEM_EVENT_MASK); choice.select(index); ItemEvent ie = new ItemEvent(choice, ItemEvent.ITEM_STATE_CHANGED, choice.getSelectedObjects()[0], ItemEvent.SELECTED); postEvent(choice, ie); long now = System.currentTimeMillis(); while (!listener.gotChange) { if (System.currentTimeMillis() - now > CHOICE_DELAY) throw new ActionFailedException("Choice didn't fire for " + "index " + index); sleep(); } waitForIdle(); } /** Select an item by its String representation. */ public void actionSelectItem(Component c, String item) { Choice choice = (Choice)c; for (int i=0;i < choice.getItemCount();i++) { if (ExtendedComparator.stringsMatch(choice.getItem(i), item)) { try { actionSelectIndex(c, i); return; } catch(ActionFailedException e) { throw new ActionFailedException("Choice didn't fire for " + "item '" + item + "'"); } } } throw new ActionFailedException("Item '" + item + "' not found in Choice"); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentLocation.java
package abbot.tester; import java.awt.*; import java.util.StringTokenizer; import abbot.i18n.Strings; /** Provides encapsulation of a visible Component-relative location. * "Visible" in this context means currently accessible by the pointer * (possibly via scrolling). A hidden node in a collapsed tree path * would <strong>not</strong> be considered visible. * <p> * This class the specifics of location so that {@link ComponentTester} * primitives * ({@link ComponentTester#actionClick(Component,ComponentLocation)}, * {@link ComponentTester#actionShowPopupMenu(Component,ComponentLocation)}, * etc) may be directed to specific elements of * substructure on a <code>Component</code> (list rows, tree paths, table * cells, substructure values, etc.). * <p> * Classes derived from <code>ComponentLocation</code> should provide * constructors for each type of location indication, e.g. value, index, and * {@link Point}. The {@link #toString()} method should provide an encoded * {@link String} suitable for use by the {@link #parse(String)} method, which * must convert the {@link String} encoding back into a proper * <code>ComponentLocation</code>. * <p> * By convention, {@link Point} locations are specified with (x,y) notation. * Indexed locations should use square brackets, e.g. [i] or [r,c] and * value locations should use a quoted {@link String}, e.g. * '"cuckoo for cocoa puffs"'. The specific syntax allowed will vary by * specific <code>ComponentLocation</code> type. The base * <code>ComponentLocation</code> implementation * supports only the explicit (x,y) notation. * <p> * Recorders * should use the {@link String} value by default for consistency. The * special value {@link #CENTER} is provided to indicate the center of a * {@link Component}. * <p> * The method {@link #badFormat(String)} should provide usage-like information * indicating the acceptable forms of input for this class. * * @see JListLocation * @see JTreeLocation * @see JTableLocation */ public class ComponentLocation { /** Special <code>ComponentLocation</code> encoding which represents the center of the component. */ public static final String CENTER = "(center)"; private Point where = null; /** Create a simple location which represents the center of a component. */ public ComponentLocation() { } /** Create a simple location. */ public ComponentLocation(Point where) { this.where = new Point(where); } /** Convert the abstract location into a concrete one. Returns * a {@link Point} relative to the given {@link Component}. */ public Point getPoint(Component c) throws LocationUnavailableException { return where != null ? new Point(where) : new Point(c.getWidth()/2, c.getHeight()/2); } /** Convert the abstract location into a concrete area, relative * to the given <code>Component</code>. If a point has * been specified, returns a 1x1 rectangle, otherwise returns the * a rectangle at (0, 0) of the Component's size. */ public Rectangle getBounds(Component c) throws LocationUnavailableException { if (where == null) return new Rectangle(0, 0, c.getWidth(), c.getHeight()); return new Rectangle(where.x, where.y, 1, 1); } /** Returns whether the given object is an equivalent * <code>ComponentLocation</code>. */ public boolean equals(Object o) { if (o instanceof ComponentLocation) { ComponentLocation loc = (ComponentLocation)o; return (where == null && loc.where == null) || (where != null && where.equals(loc.where)); } return false; } public String toString() { if (where != null) return "(" + where.x + "," + where.y + ")"; return CENTER; } protected String badFormat(String encoded) { return Strings.get("location.component.bad_format", new Object[] { encoded }); } protected String encodeIndex(int index) { return "[" + index + "]"; } /** Returns whether the given (trimmed) <code>String</code> is an encoded index. */ protected boolean isIndex(String encoded) { return encoded.startsWith("[") && encoded.endsWith("]"); } /** Extract the encoded index. */ protected int parseIndex(String encoded) { try { return Integer.parseInt(encoded. substring(1, encoded.length()-1).trim()); } catch(NumberFormatException e) { throw new IllegalArgumentException(badFormat(encoded)); } } protected String encodeValue(String value) { return "\"" + value + "\""; } /** Returns whether the given (trimmed) <code>String</code> is an encoded value. */ protected boolean isValue(String encoded) { return encoded.startsWith("\"") && encoded.endsWith("\""); } /** Extract the encoded value. */ protected String parseValue(String encoded) { return encoded.substring(1, encoded.length()-1); } /** Convert the given encoding into the proper location. Allowed formats: (x, y) <p> */ public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (encoded.equals(CENTER)) { where = null; return this; } if (encoded.startsWith("(") && encoded.endsWith(")")) { StringTokenizer st = new StringTokenizer(encoded.substring(1, encoded.length()-1), ","); if (st.countTokens() == 2) { try { int x = Integer.parseInt(st.nextToken().trim()); int y = Integer.parseInt(st.nextToken().trim()); where = new Point(x, y); return this; } catch(NumberFormatException nfe) { } } } throw new IllegalArgumentException(badFormat(encoded)); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentMissingException.java
package abbot.tester; /** Indicates that a component required by a ComponentTester action was not * found. */ public class ComponentMissingException extends ActionFailedException { public ComponentMissingException(String msg) { super(msg); } public ComponentMissingException(String msg, Throwable cause) { super(msg, cause); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentNotShowingException.java
package abbot.tester; /** Indicates that a ComponentTester action failed due to the component not * being visible on screen. */ public class ComponentNotShowingException extends ActionFailedException { public ComponentNotShowingException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentTester.java
package abbot.tester; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Frame; import java.awt.Point; import java.awt.event.*; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleIcon; import abbot.BugReport; import abbot.Log; import abbot.WaitTimedOutException; import abbot.finder.AWTHierarchy; import abbot.finder.BasicFinder; import abbot.finder.ComponentFinder; import abbot.finder.ComponentNotFoundException; import abbot.finder.ComponentSearchException; import abbot.finder.Hierarchy; import abbot.finder.MultipleComponentsFoundException; import abbot.finder.matchers.WindowMatcher; import abbot.i18n.Strings; import abbot.script.ComponentReference; import abbot.tester.Robot.ConditionEDTDecorator; import abbot.util.*; /** Provides basic programmatic operation of a {@link Component} and related UI objects such as windows, menus and menu bars throuh action methods. Also provides some useful assertions about properties of a {@link Component}. <p> There are two sets of event-generating methods. The internal, protected methods inherited from {@link abbot.tester.Robot abbot.tester.Robot} are for normal programmatic use within derived Tester classes. No event queue synchronization should be performed except when modifying a component for which results are required for the action itself. <p> The public <code>actionXXX</code> functions are meant to be invoked from a script or directly from a hand-written test. These actions are distinguished by name, number of arguments, and by argument type. The actionX methods will be synchronized with the event dispatch thread when invoked, so you should only do synchronization with waitForIdle when you depend on the results of a particular event prior to sending the next one (e.g. scrolling a table cell into view before selecting it). All public action methods should ensure that the actions they trigger are finished on return, or will be finished before any subsequent actions are requested. <p> <i>Action</i> methods generally represent user-driven actions such as menu selection, table selection, popup menus, etc. All actions should have the following signature: <blockquote> <code>public void actionSpinMeRoundLikeARecord(Component c, ...);</code> <code>public void actionPinchMe(Component c, ComponentLocation loc);</code> </blockquote> <p> It is essential that the argument is of type {@link Component}; if you use a more-derived class, then the actual invocation becomes ambiguous since method parsing doesn't attempt to determine which identically-named method is the most-derived. <p> The {@link ComponentLocation} abstraction allows all derived tester classes to inherit click, popup menu, and drag variants without having to explicitly define new methods for component-specific substructures. The new class need only define the {@link #parseLocation(String)} method, which should return a location specific to the component in question. <p> <i>Assertions</i> are either independent of any component (and should be implemented in this class), or take a component as the first argument, and perform some check on that component. All assertions should have one of the following signatures: <blockquote> <code>public boolean assertMyself(...);</code><br> <code>public boolean assertBorderIsAtrociouslyUgly(Component c, ...);</code> </blockquote> Note that these assertions do not throw exceptions but rather return a <code>boolean</code> value indicating success or failure. Normally these assertions will be wrapped by an abbot.script.Assert step if you want to cause a test failure, or you can manually throw the proper failure exception if the method returns false. <p> <i>Property checks</i> may also be implemented in cases where the component "property" might not be readily available or easily comparable, e.g. see {@link abbot.tester.JPopupMenuTester#getMenuLabels(Component)}. <blockquote> <code>public Object getHairpiece(Component c);</code><br> <code>public boolean isRighteouslyIndignant(Component c);</code> </blockquote> Any non-property methods with the property signature, should be added to the {@link #IGNORED_METHODS} set, since property-like methods are scanned dynamically to populate the {@link abbot.editor.ScriptEditor editor}'s action menus. <p> <a name=Customization> <h2>Extending ComponentTester</h2> Following are the steps required to implement a Tester object for a custom class. <ul> <li><h3>Create the Tester Class</h3> Derive from this class to implement actions and assertions specific to a given component class. Testers for any classes found in the JRE (i.e. in the {@link java.awt} or {@link javax.swing} packages) should be in the {@link abbot.tester abbot.tester} package. Extensions (testers for any <code>Component</code> subclasses not found in the JRE) must be in the <code>abbot.tester.extensions</code> package and be named the name of the <code>Component</code> subclass followed by "Tester". For example, the {@link javax.swing.JButton javax.swing.JButton} tester class is {@link JButtonTester abbot.tester.JButtonTester}, and a tester for <code>org.me.PR0NViewer</code> would be <code>abbot.tester.extensions.PR0NViewerTester</code>. <li><h3>Add Action Methods</h3> Add <code>action</code> methods which effect user actions. See the section on <a href=Naming>naming conventions</a> below. <li><h3>Add Assertion Methods</h3> Add <code>assert</code> methods to access attributes not readily available as properties<br> <li><h3>Add Substructure Support</h3> Add a corresponding <code>ComponentLocation</code> implementation to handle any substructure present in your <code>Component</code>. See {@link ComponentLocation} for details. <li><h3>Add Substructure-handling Methods</h3> <ul> <li>{@link #parseLocation(String)}<br> Convert the given <code>String</code> into an instance of {@link ComponentLocation} specific to your Tester. Here is an example implementation from {@link JListTester}:<br> <code><pre> public ComponentLocation parseLocation(String encoded) { return new JListLocation().parse(encoded); } </pre></code> <li>{@link #getLocation(Component,Point)}<br> Use the given <code>Point</code> to create a {@link ComponentLocation} instance appropriate for the <code>Component</code> substructure available at that location. For example, on a {@link javax.swing.JList}, you would return a {@link JListLocation} based on the stringified value at that location, the row/index at that location, or the raw <code>Point</code>, in order of preference. If a stringified value is unavailable, fall back to an indexed position; if that is not possible (if, for instance, the location is outside the list contents), return a {@link ComponentLocation} based on the raw <code>Point</code>. </ul> <li><h3>Set Editor Properties</h3> Add-on tester classes should set the following system properties so that the actions provided by their tester can be properly displayed in the script editor. For an action <code>actionWiggle</code> provided by class <code>abbot.tester.extensions.PR0NViewerTester</code>, the following properties should be defined:<br> <ul> <li><code>actionWiggle.menu</code> short name for Insert menu <li><code>actionWiggle.desc</code> short description (optional) <li><code>actionWiggle.icon</code> icon for the action (optional) <li><code>PR0NViewerTester.actionWiggle.args</code> javadoc-style description of method, displayed when asking the user for its arguments </ul> Since these properties are global, if your Tester class defines a method which is also defined by another Tester class, you must supply the class name as a prefix to the property. </ul> <p> <a name=MethodNaming> <h2>Method Naming Conventions</h2> Action methods should be named according to the human-centric action that is being performed if at all possible. For example, use <code>actionSelectRow</code> in a List rather than <code>actionSelectIndex</code>. If there's no common usage, or if the usage is too vague or diverse, use the specific terms used in code. For example, {@link JScrollBarTester} uses {@link JScrollBarTester#actionScrollUnitUp(Component) actionScrollUnitUp()} and {@link JScrollBarTester#actionScrollBlockUp(Component) actionScrollBlockUp()}; since there is no common language usage for these concepts (line and page exist, but are not appropriate if what is scrolled is not text). <p> When naming a selection method, include the logical substructure target of the selection in the name (e.g. {@link JTableTester#actionSelectCell(Component,JTableLocation)} JTableTester.actionSelectCell()), since some components may have more than one type of selectable item within them. */ public class ComponentTester extends Robot { /** Add any method names here which should <em>not</em> show up in a dynamically generated list of property methods. */ protected static Set IGNORED_METHODS = new HashSet(); static { // Omit from method lookup deprecated methods or others we want to // ignore IGNORED_METHODS.addAll(Arrays.asList(new String[] { "actionSelectAWTMenuItemByLabel", "actionSelectAWTPopupMenuItemByLabel", "getTag", "getTester", "isOnPopup", "getLocation", })); } /** Maps class names to their corresponding Tester object. */ private static HashMap testers = new HashMap(); /** Establish the given ComponentTester as the one to use for the given * class. This may be used to override the default tester for a given * core class. Note that this will only work with components loaded by * the framework class loader, not those loaded by the class loader for * the code under test. */ public static void setTester(Class forClass, ComponentTester tester) { testers.put(forClass.getName(), tester); } /** Return a shared instance of the appropriate <code>ComponentTester</code> for the given {@link Component}.<p> This method is primarily used by the scripting system, since the appropriate <code>ComponentTester</code> for a given {@link Component} is not known <i>a priori</i>. Coded unit tests should generally just create an instance of the desired type of <code>ComponentTester</code> for local use. */ public static ComponentTester getTester(Component comp) { return comp != null ? getTester(comp.getClass()) : getTester(Component.class); } /** Return a shared instance of the corresponding <code>ComponentTester</code> object for the given {@link Component} class, chaining up the inheritance tree if no specific tester is found for that class.<p> The abbot tester package is searched first, followed by the tester extensions package.<p> This method is primarily used by the scripting system, since the appropriate <code>ComponentTester</code> for a given Component is not known <i>a priori</i>. Coded unit tests should generally just create an instance of the desired type of <code>ComponentTester</code> for local use. */ public static ComponentTester getTester(Class componentClass) { String className = componentClass.getName(); ComponentTester tester = (ComponentTester)testers.get(className); if (tester == null) { if (!Component.class.isAssignableFrom(componentClass)) { String msg = "Class " + className + " is not derived from java.awt.Component"; throw new IllegalArgumentException(msg); } Log.debug("Looking up tester for " + componentClass); String testerName = simpleClassName(componentClass) + "Tester"; Package pkg = ComponentTester.class.getPackage(); String pkgName = ""; if (pkg == null) { Log.warn("ComponentTester.class has null package; " + "the class loader is likely flawed: " + ComponentTester.class.getClassLoader() + ", " + Thread.currentThread().getContextClassLoader(), Log.FULL_STACK); pkgName = "abbot.tester"; } else { pkgName = pkg.getName(); } if (className.startsWith("javax.swing.") || className.startsWith("java.awt.")) { tester = findTester(pkgName + "." + testerName, componentClass); } if (tester == null) { tester = findTester(pkgName + ".extensions." + testerName, componentClass); if (tester == null) { tester = getTester(componentClass.getSuperclass()); } } if (tester != null && !tester.isExtension()) { // Only cache it if it's part of the standard framework, // but cache it for every level that we looked up, so we // don't repeat the effort. testers.put(componentClass.getName(), tester); } } return tester; } /** Return whether this tester is an extension. */ public final boolean isExtension() { return getClass().getName().startsWith("abbot.tester.extensions"); } /** Look up the given class, using special class loading rules to maintain framework consistency. */ private static Class resolveClass(String testerName, Class componentClass) throws ClassNotFoundException { // Extension testers must be loaded in the context of the code under // test. Class cls; if (testerName.startsWith("abbot.tester.extensions")) { // In an OSGI environment it might be that the test classes // are in a different class loader to the UI classes // try { cls = Class.forName(testerName, true, componentClass.getClassLoader()); } catch (ClassNotFoundException cnfe){ // Deal with cases where the ccl is null and throw a new exception // so that clients can properly trace the code back ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl!=null){ cls = Class.forName(testerName, true, ccl); } else { throw new ClassNotFoundException(testerName,cnfe); } } } else { cls = Class.forName(testerName); } Log.debug("Loaded class " + testerName + " with " + cls.getClassLoader()); return cls; } /** Look up the given class with a specific class loader. */ private static ComponentTester findTester(String testerName, Class componentClass) { ComponentTester tester = null; Class testerClass = null; try { testerClass = resolveClass(testerName, componentClass); tester = (ComponentTester)testerClass.newInstance(); } catch(InstantiationException ie) { Log.warn(ie); } catch(IllegalAccessException iae) { Log.warn(iae); } catch(ClassNotFoundException cnf) { //Log.debug("Class " + testerName + " not found"); } catch(ClassCastException cce) { throw new BugReport("Class loader conflict: environment " + ComponentTester.class.getClassLoader() + " vs. " + testerClass.getClassLoader()); } return tester; } /** Derive a tag from the given accessible context if possible, or return * null. */ protected String deriveAccessibleTag(AccessibleContext context) { String tag = null; if (context != null) { if (context.getAccessibleName() != null) { tag = context.getAccessibleName(); } if ((tag == null || "".equals(tag)) && context.getAccessibleIcon() != null && context.getAccessibleIcon().length > 0) { AccessibleIcon[] icons = context.getAccessibleIcon(); tag = icons[0].getAccessibleIconDescription(); if (tag != null) { tag = tag.substring(tag.lastIndexOf("/") + 1); tag = tag.substring(tag.lastIndexOf("\\") + 1); } } } return tag; } /** Default methods to use to derive a component-specific tag. These are * things that will probably be useful in a custom component if the method * is supported. */ private static final String[] tagMethods = { "getLabel", "getTitle", "getText", }; /** Return a reasonable identifier for the given component. Note that this should not duplicate information provided by existing attributes such as title, label, or text. This functionality is provided to assist in identification of non-standard GUI components only. */ public static String getTag(Component comp) { return getTester(comp.getClass()).deriveTag(comp); } /** Returns whether the given class is not a core JRE class. */ protected boolean isCustom(Class c) { return !(c.getName().startsWith("javax.swing.") || c.getName().startsWith("java.awt.")); } /** Determine a component-specific identifier not already defined in other * component attributes. This method should be defined to something * unique for custom UI components. */ public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; Method m; String tag = null; // Try a few default methods for (int i=0;i < tagMethods.length;i++) { // Don't use getText on text components if (((comp instanceof javax.swing.text.JTextComponent) || (comp instanceof java.awt.TextComponent)) && "getText".equals(tagMethods[i])) { continue; } try { m = comp.getClass().getMethod(tagMethods[i], null); String tmp = (String)m.invoke(comp, null); // Don't ever use empty strings for tags if (tmp != null && !"".equals(tmp)) { tag = tmp; break; } } catch(Exception e) { } } // In the absence of any other tag, try to derive one from something // recognizable on one of its ancestors. if (tag == null || "".equals(tag)) { Component parent = comp.getParent(); if (parent != null) { String ptag = getTag(parent); if (ptag != null && !"".equals(tag)) { // Don't use the tag if it's simply the window title; that // doesn't provide any extra information. if (!ptag.endsWith(" Root Pane")) { StringBuffer buf = new StringBuffer(ptag); int under = ptag.indexOf(" under "); if (under != -1) buf = buf.delete(0, under + 7); buf.insert(0, " under "); buf.insert(0, simpleClassName(comp.getClass())); tag = buf.toString(); } } } } return tag; } /** * Wait for an idle AWT event queue. Will return when there are no more * events on the event queue. */ public void actionWaitForIdle() { waitForIdle(); } /** Delay the given number of ms. */ public void actionDelay(int ms) { delay(ms); } /** @deprecated Renamed to {@link #actionSelectAWTMenuItem(Frame,String)}. */ public void actionSelectAWTMenuItemByLabel(Frame menuFrame, String path) { actionSelectAWTMenuItem(menuFrame, path); } /** Selects an AWT menu item ({@link java.awt.MenuItem}) and returns when the invocation has triggered (though not necessarily completed). @param menuFrame @param path either a unique label or the menu path. @see Robot#selectAWTMenuItem(Frame,String) */ public void actionSelectAWTMenuItem(Frame menuFrame, String path) { AWTMenuListener listener = new AWTMenuListener(); new WeakAWTEventListener(listener, ActionEvent.ACTION_EVENT_MASK); selectAWTMenuItem(menuFrame, path); long start = System.currentTimeMillis(); while (!listener.eventFired) { if (System.currentTimeMillis() - start > defaultDelay) { throw new ActionFailedException("Menu item '" + path + "' failed to fire"); } sleep(); } waitForIdle(); } /** @deprecated Renamed to {@link #actionSelectAWTPopupMenuItem(Component,String)}. */ public void actionSelectAWTPopupMenuItemByLabel(Component invoker, String path) { actionSelectAWTPopupMenuItem(invoker, path); } /** Selects an AWT menu item and returns when the invocation has triggered (though not necessarily completed). @see Robot#selectAWTPopupMenuItem(Component,String) */ public void actionSelectAWTPopupMenuItem(Component invoker, String path) { AWTMenuListener listener = new AWTMenuListener(); new WeakAWTEventListener(listener, ActionEvent.ACTION_EVENT_MASK); selectAWTPopupMenuItem(invoker, path); long start = System.currentTimeMillis(); while (!listener.eventFired) { if (System.currentTimeMillis() - start > defaultDelay) { throw new ActionFailedException("Menu item '" + path + "' failed to fire"); } sleep(); } waitForIdle(); } /** Select the given menu item. */ public void actionSelectMenuItem(Component item) { Log.debug("Attempting to select menu item " + toString(item)); selectMenuItem(item); waitForIdle(); } /** Select the given menu item, given its path and a component on the same window. */ public void actionSelectMenuItem(Component sameWindow, String path) { Log.debug("Attempting to select menu item '" + path + "'"); selectMenuItem(sameWindow, path); waitForIdle(); } /** Pop up a menu at the center of the given component and select the given item. */ public void actionSelectPopupMenuItem(Component invoker, String path) { actionSelectPopupMenuItem(invoker, invoker.getWidth()/2, invoker.getHeight()/2, path); } /** Pop up a menu at the given location on the given component and select the given item. */ public void actionSelectPopupMenuItem(Component invoker, ComponentLocation loc, String path) { selectPopupMenuItem(invoker, loc, path); waitForIdle(); } /** Pop up a menu at the given coordinates on the given component and select the given item. */ public void actionSelectPopupMenuItem(Component invoker, int x, int y, String path) { actionSelectPopupMenuItem(invoker, new ComponentLocation(new Point(x, y)), path); } /** Pop up a menu in the center of the given component. */ public void actionShowPopupMenu(Component invoker) { actionShowPopupMenu(invoker, new ComponentLocation()); } /** Pop up a menu in the center of the given component. */ public void actionShowPopupMenu(Component invoker, ComponentLocation loc) { Point where = loc.getPoint(invoker); showPopupMenu(invoker, where.x, where.y); } /** Pop up a menu at the given location on the given component. */ public void actionShowPopupMenu(Component invoker, int x, int y) { showPopupMenu(invoker, x, y); } /** Click on the center of the component. */ public void actionClick(Component comp) { actionClick(comp, new ComponentLocation()); } /** Click on the component at the given location. */ public void actionClick(Component c, ComponentLocation loc) { actionClick(c, loc, InputEvent.BUTTON1_MASK); } /** Click on the component at the given location with the given modifiers. */ public void actionClick(Component c, ComponentLocation loc, int buttons) { actionClick(c, loc, buttons, 1); } /** Click on the component at the given location, with the given * modifiers and click count. */ public void actionClick(final Component c, ComponentLocation loc, int buttons, int count) { // Check the component is neabled before clicking on it, wait if required // wait(new ConditionEDTDecorator(c,new Condition() { public boolean test() { return c.isEnabled(); } public String toString() { return Strings.get("tester.Component.not_enabled", new Object[] { c.toString() }); } }), componentDelay); Point where = loc.getPoint(c); click(c, where.x, where.y, buttons, count); waitForIdle(); } /** Click on the component at the given location (mouse button 1). */ public void actionClick(Component comp, int x, int y) { actionClick(comp, new ComponentLocation(new Point(x, y))); } /** Click on the component at the given location. The buttons mask * should be the InputEvent masks for the desired button, e.g. * {@link InputEvent#BUTTON1_MASK}. ComponentTester also defines * {@link AWTConstants#POPUP_MASK} and {@link AWTConstants#TERTIARY_MASK} for * platform-independent masks for those buttons. Key modifiers other * than {@link InputEvent#ALT_MASK} and {@link InputEvent#META_MASK} may * also be used as a convenience. */ public void actionClick(Component comp, int x, int y, int buttons) { actionClick(comp, x, y, buttons, 1); } /** Click on the component at the given location, specifying buttons and * the number of clicks. The buttons mask should be the InputEvent mask * for the desired button, e.g. * {@link InputEvent#BUTTON1_MASK}. ComponentTester also defines * {@link AWTConstants#POPUP_MASK} and {@link AWTConstants#TERTIARY_MASK} for * platform-independent masks for those buttons. Key modifiers other * than {@link InputEvent#ALT_MASK} and {@link InputEvent#META_MASK} may * also be used as a convenience. */ public void actionClick(Component comp, int x, int y, int buttons, int count) { actionClick(comp, new ComponentLocation(new Point(x, y)), buttons, count); } /** Send a key press event for the given virtual key code to the given Component. */ public void actionKeyPress(Component comp, int keyCode) { actionFocus(comp); actionKeyPress(keyCode); } /** Generate a key press event for the given virtual key code. */ public void actionKeyPress(int keyCode) { keyPress(keyCode); waitForIdle(); } /** Generate a key release event sent to the given component. */ public void actionKeyRelease(Component comp, int keyCode) { actionFocus(comp); actionKeyRelease(keyCode); } /** Generate a key release event. */ public void actionKeyRelease(int keyCode) { keyRelease(keyCode); waitForIdle(); } /** Set the state of the given modifier keys. */ public void actionSetModifiers(int mask, boolean pressed) { setModifiers(mask, pressed); waitForIdle(); } /** * Send the given keystroke, which must be the KeyEvent field name of a * KeyEvent VK_ constant to the program. Sends a key down/up, with no * modifiers. The focus is changed to the target component. */ public void actionKeyStroke(Component c, int keyCode) { actionFocus(c); actionKeyStroke(keyCode, 0); } /** * Send the given keystroke, which must be the KeyEvent field name of a * KeyEvent VK_ constant. Sends a key press and key release, with no * modifiers. Note that this method does not affect the current focus. */ public void actionKeyStroke(int keyCode) { actionKeyStroke(keyCode, 0); } /** * Send the given keystroke, which must be the KeyEvent field name of a * KeyEvent VK_ constant to the program. Sends a key down/up, with the * given modifiers, which should be the InputEvent field name modifier * masks optionally ORed together with "|". The focus is changed to the * target component.<p> */ public void actionKeyStroke(Component c, int keyCode, int modifiers) { actionFocus(c); actionKeyStroke(keyCode, modifiers); } /** * Send the given keystroke, which must be the KeyEvent field name of a * KeyEvent VK_ constant to the program. Sends a key down/up, with the * given modifiers, which should be the InputEvent field name modifier * masks optionally ORed together with "|". Note that this does not * affect the current focus.<p> */ public void actionKeyStroke(int keyCode, int modifiers) { if (Bugs.hasKeyStrokeGenerationBug()) { int oldDelay = getAutoDelay(); setAutoDelay(50); key(keyCode, modifiers); setAutoDelay(oldDelay); delay(100); } else { key(keyCode, modifiers); } waitForIdle(); } /** Send events required to generate the given string on the given * component. This version is preferred over * {@link #actionKeyString(String)}. */ public void actionKeyString(Component c, String string) { actionFocus(c); actionKeyString(string); } /** Send events required to generate the given string. */ public void actionKeyString(String string) { keyString(string); // FIXME waitForIdle isn't always sufficient on OSX with key events if (Bugs.hasKeyStrokeGenerationBug()) { delay(100); } waitForIdle(); } /** Set the focus on to the given component. */ public void actionFocus(Component comp) { focus(comp, true); } /** Move the mouse/pointer to the given location. */ public void actionMouseMove(Component comp, ComponentLocation loc) { Point where = loc.getPoint(comp); mouseMove(comp, where.x, where.y); waitForIdle(); } /** Press mouse button 1 at the given location. */ public void actionMousePress(Component comp, ComponentLocation loc) { actionMousePress(comp, loc, InputEvent.BUTTON1_MASK); } /** Press mouse buttons corresponding to the given mask at the given location. */ public void actionMousePress(Component comp, ComponentLocation loc, int mask) { Point where = loc.getPoint(comp); mousePress(comp, where.x, where.y, mask); waitForIdle(); } /** Release any currently held mouse buttons. */ public void actionMouseRelease() { mouseRelease(); waitForIdle(); } /** Perform a drag action. Derived classes may provide more specific * identifiers for what is being dragged simply by deriving a new class * from ComponentLocation which identifies the appropriate substructure. * For instance, a {@link JTreeLocation} might encapsulate the expansion * control location for the path [root, node A, child B]. */ public void actionDrag(Component dragSource, ComponentLocation loc) { actionDrag(dragSource, loc, "BUTTON1_MASK"); } /** Perform a drag action. Grabs the center of the given component. */ public void actionDrag(Component dragSource) { actionDrag(dragSource, new ComponentLocation()); } /** Perform a drag action with the given modifiers. * @param dragSource source of the drag * @param loc identifies where on the given {@link Component} to begin the * drag. * @param buttons a <code>String</code> representation of key modifiers, * e.g. "ALT|SHIFT", based on the {@link InputEvent#ALT_MASK InputEvent * <code>_MASK</code> fields}. * @deprecated Use the * {@link #actionDrag(Component,ComponentLocation,int) integer modifier mask} * version instead. */ public void actionDrag(Component dragSource, ComponentLocation loc, String buttons) { actionDrag(dragSource, loc, AWT.getModifiers(buttons)); } /** Perform a drag action with the given modifiers. * @param dragSource source of the drag * @param loc identifies where on the given {@link Component} to begin the * drag. * @param buttons one or more of the * {@link InputEvent#BUTTON1_MASK InputEvent <code>BUTTONN_MASK</code> * fields}. */ public void actionDrag(Component dragSource, ComponentLocation loc, int buttons) { Point where = loc.getPoint(dragSource); drag(dragSource, where.x, where.y, buttons); waitForIdle(); } /** Perform a drag action. Grabs at the given explicit location. */ public void actionDrag(Component dragSource, int sx, int sy) { actionDrag(dragSource, new ComponentLocation(new Point(sx, sy))); } /** Perform a drag action. Grabs at the given location with the given * modifiers. * @param dragSource source of the drag * @param sx X coordinate * @param sy Y coordinate * @param buttons a <code>String</code> representation of key modifiers, * e.g. "ALT|SHIFT", based on the {@link InputEvent#ALT_MASK InputEvent * <code>_MASK</code> fields}. * @deprecated Use the * {@link #actionDrag(Component,ComponentLocation,int) ComponentLocation/ * integer modifier mask} version instead. */ public void actionDrag(Component dragSource, int sx, int sy, String buttons) { actionDrag(dragSource, new ComponentLocation(new Point(sx, sy)), buttons); } /** Drag the current dragged object over the given component. */ public void actionDragOver(Component target) { actionDragOver(target, new ComponentLocation()); } /** Drag the current dragged object over the given target/location. */ public void actionDragOver(Component target, ComponentLocation where) { Point loc = where.getPoint(target); dragOver(target, loc.x, loc.y); waitForIdle(); } /** Perform a basic drop action (implicitly causing preceding mouse * drag motion). Drops in the center of the component. */ public void actionDrop(Component dropTarget) { actionDrop(dropTarget, new ComponentLocation()); } /** Perform a basic drop action (implicitly causing preceding mouse * drag motion). */ public void actionDrop(Component dropTarget, ComponentLocation loc) { Point where = loc.getPoint(dropTarget); drop(dropTarget, where.x, where.y); waitForIdle(); } /** Perform a basic drop action (implicitly causing preceding mouse * drag motion). The modifiers represents the set of active modifiers * when the drop is made. */ public void actionDrop(Component dropTarget, int x, int y) { drop(dropTarget, x, y); waitForIdle(); } /** Return whether the component's contents matches the given image. */ public boolean assertImage(Component comp, java.io.File fileImage, boolean ignoreBorder) { java.awt.image.BufferedImage img = capture(comp, ignoreBorder); return new ImageComparator().compare(img, fileImage) == 0; } /** Returns whether a Window corresponding to the given String is * showing. The string may be a plain String or regular expression and * may match either the window title (for Frames or Dialogs) or the * value of {@link Component#getName}. */ public boolean assertFrameShowing(Hierarchy h, String id) { try { ComponentFinder finder = new BasicFinder(h); return finder.find(new WindowMatcher(id, true)) != null; } catch(ComponentNotFoundException e) { return false; } catch(MultipleComponentsFoundException m) { // Might not be the one you want, but that's what the docs say return true; } } /** Returns whether a Window corresponding to the given String is * showing. The string may be a plain String or regular expression and * may match either the window title (for Frames or Dialogs) or the value * of {@link Component#getName}. * @deprecated This method does not specify the proper context for the * lookup. Use {@link #assertFrameShowing(Hierarchy,String)} instead. */ public boolean assertFrameShowing(String id) { return assertFrameShowing(AWTHierarchy.getDefault(), id); } /** Convenience wait for a window to be displayed. The given string may * be a plain String or regular expression and may match either the window * title (for Frames and Dialogs) or the value of {@link Component#getName}. * This method is provided as a convenience for hand-coded tests, since * scripts will use a wait step instead.<p> * The property <code>abbot.robot.component_delay</code> affects the * default timeout. */ public void waitForFrameShowing(final Hierarchy h, final String identifier) { wait(new Condition() { public boolean test() { return assertFrameShowing(h, identifier); } public String toString() { return Strings.get("tester.Component.show_wait", new Object[] { identifier }); } }, componentDelay); } /** Convenience wait for a window to be displayed. The given string may * be a plain String or regular expression and may match either the window * title (for Frames and Dialogs) or the value of {@link Component#getName}. * This method is provided as a convenience for hand-coded tests, since * scripts will use a wait step instead.<p> * The property abbot.robot.component_delay affects the default timeout. * @deprecated This method does not provide sufficient context to reliably * find a component. Use {@link #waitForFrameShowing(Hierarchy,String)} * instead. */ public void waitForFrameShowing(final String identifier) { waitForFrameShowing(AWTHierarchy.getDefault(), identifier); } /** Return whether the Component represented by the given ComponentReference is available. */ public boolean assertComponentShowing(ComponentReference ref) { try { Component c = ref.getComponent(); return isReadyForInput(c); } catch(ComponentSearchException e) { return false; } } /** Wait for the Component represented by the given ComponentReference to become available. The timeout is affected by abbot.robot.component_delay, which defaults to 30s. */ public void waitForComponentShowing(final ComponentReference ref) { wait(new Condition() { public boolean test() { return assertComponentShowing(ref); } public String toString() { return Strings.get("tester.Component.show_wait", new Object[] { ref }); } }, componentDelay); } private Method[] cachedMethods = null; /** Look up methods with the given prefix. Facilitates auto-scanning by * scripts and the script editor. */ private Method[] getMethods(String prefix, Class returnType, boolean componentArgument) { if (cachedMethods == null) { cachedMethods = getClass().getMethods(); } ArrayList methods = new ArrayList(); // Only save one Method for each unique name HashSet names = new HashSet(IGNORED_METHODS); Method[] mlist = cachedMethods; for (int i=0;i < mlist.length;i++) { String name = mlist[i].getName(); if (names.contains(name) || !name.startsWith(prefix)) continue; Class[] params = mlist[i].getParameterTypes(); if ((returnType == null || returnType.equals(mlist[i].getReturnType())) && ((params.length == 0 && !componentArgument) || (params.length > 0 && (Component.class.isAssignableFrom(params[0]) == componentArgument)))) { methods.add(mlist[i]); names.add(name); } } return (Method[])methods.toArray(new Method[methods.size()]); } private Method[] cachedActions = null; /** Return a list of all actions defined by this class that don't depend * on a component argument. */ public Method[] getActions() { if (cachedActions == null) { cachedActions = getMethods("action", void.class, false); } return cachedActions; } private Method[] cachedComponentActions = null; /** Return a list of all actions defined by this class that require * a component argument. */ public Method[] getComponentActions() { if (cachedComponentActions == null) { cachedComponentActions = getMethods("action", void.class, true); } return cachedComponentActions; } private Method[] cachedPropertyMethods = null; /** Return an array of all property check methods defined by this class. * The first argument <b>must</b> be a Component. */ public Method[] getPropertyMethods() { if (cachedPropertyMethods == null) { ArrayList all = new ArrayList(); all.addAll(Arrays.asList(getMethods("is", boolean.class, true))); all.addAll(Arrays.asList(getMethods("has", boolean.class, true))); all.addAll(Arrays.asList(getMethods("get", null, true))); cachedPropertyMethods = (Method[])all.toArray(new Method[all.size()]); } return cachedPropertyMethods; } private Method[] cachedAssertMethods = null; /** Return a list of all assertions defined by this class that don't * depend on a component argument. */ public Method[] getAssertMethods() { if (cachedAssertMethods == null) { cachedAssertMethods = getMethods("assert", boolean.class, false); } return cachedAssertMethods; } private Method[] cachedComponentAssertMethods = null; /** Return a list of all assertions defined by this class that require a * component argument. */ public Method[] getComponentAssertMethods() { if (cachedComponentAssertMethods == null) { cachedComponentAssertMethods = getMethods("assert", boolean.class, true); } return cachedComponentAssertMethods; } /** Quick and dirty strip raw text from html, for getting the basic text from html-formatted labels and buttons. Behavior is undefined for badly formatted html. */ public static String stripHTML(String str) { if (str != null && (str.startsWith("<html>") || str.startsWith("<HTML>"))) { while (str.startsWith("<")) { int right = str.indexOf(">"); if (right == -1) break; str = str.substring(right + 1); } while (str.endsWith(">")) { int right = str.lastIndexOf("<"); if (right == -1) break; str = str.substring(0, right); } } return str; } /** Wait for the given condition, throwing an ActionFailedException if it * times out. */ protected void waitAction(String desc, Condition cond) throws ActionFailedException { try { Robot.wait(cond); } catch(WaitTimedOutException wto) { throw new ActionFailedException(desc); } } /** Return the Component class that corresponds to this * <tt>ComponentTester</tt> * class. For example, * <tt>JComponentTester.getTestedClass(JLabel.class)</tt> * would return <tt>JComponent.class</tt>. */ public Class getTestedClass(Class cls) { while (getTester(cls.getSuperclass()) == this) { cls = cls.getSuperclass(); } return cls; } /** Parse the String representation of a <tt>ComponentLocation</tt> into * the actual <tt>ComponentLocation</tt> object. */ public ComponentLocation parseLocation(String encoded) { return new ComponentLocation().parse(encoded); } /** Return a ComponentLocation for the given Point. Derived classes may * provide something more suitable than an (x, y) coordinate. A * {@link javax.swing.JTree}, for example, might provide a * {@link JTreeLocation} * indicating a path or row in the tree. */ public ComponentLocation getLocation(Component c, Point where) { return new ComponentLocation(where); } private class AWTMenuListener implements AWTEventListener { public volatile boolean eventFired; public void eventDispatched(AWTEvent e) { if (e.getID() == ActionEvent.ACTION_PERFORMED) { eventFired = true; } } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ContainerTester.java
package abbot.tester; /** Hierarchy placeholder for Container. Provides no additional user * actions. */ public class ContainerTester extends ComponentTester { }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/DialogTester.java
package abbot.tester; import java.awt.*; public class DialogTester extends WindowTester { /** Return a unique tag to help identify the given component. */ public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; String tag = ((Dialog)comp).getTitle(); if (tag == null || "".equals(tag)) { tag = super.deriveTag(comp); } return tag; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/FailedException.java
package abbot.tester; import java.awt.Component; import java.awt.Frame; import java.awt.KeyboardFocusManager; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.List; /** * An exception to note that a process has failed in Abbot and we want to presever * the system state. */ public class FailedException extends RuntimeException { public FailedException(Throwable cause) { super(cause); systemState = dumpSystemState(); } public FailedException(String msg, Throwable cause) { super(msg, cause); if (cause instanceof FailedException) { // Don't make a copy of the system state use the one in cause // as that will be closer to where it happened systemState = ((FailedException)cause).getSystemState(); } else { systemState = dumpSystemState(); } } public FailedException(String msg) { super(msg); systemState = dumpSystemState(); } /** * @return The a string which represents the state of the system at the time of the failure * in particular thread conditions and the current swing tree. */ public String getSystemState() { return systemState; } @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); s.print(systemState); } @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); s.print(systemState); } /** * Dump the stacks at the point of failure */ private static String dumpSystemState() { StringWriter sw = new StringWriter(); PrintWriter ps = new PrintWriter(sw); ps.println("\n\n[TOC Focus, AWT Tree, Stack Traces] \n\n"); // Stack traces ps.println("\n\n[[[Dumping Focus]]] \n\n"); KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component next = currentManager.getFocusOwner(); List<Component> tree = new ArrayList<Component>(); while (next!=null) { tree.add(0, next); next = next.getParent(); } ps.printf("Focus owner %s\nFocus root %s\n", tree, currentManager.getCurrentFocusCycleRoot()); ps.println("\n\n[[[Dumping Windows]]] \n\n"); for (Frame frame: Frame.getFrames()) { ps.println("Dumping frame " + frame); frame.list(ps, 2); } ps.println("\n\n[[[Dumping Stack Traces]]] \n\n"); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo ti: threadMXBean.dumpAllThreads(true, true)) { ps.print(ti); // ThreadInfo only prints out the first n lines, so make sure // we write out the rest StackTraceElement ste[] = ti.getStackTrace(); if (ste.length > 8) { ps.println("[Extra stack]"); for (int element = 8; element < ste.length; element++) { ps.println("\tat " + ste[element]); for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getLockedStackDepth() == element) { ps.append("\t- locked " + mi); ps.append('\n'); } } } ps.println("[Extra stack]"); } ps.println(); } long deadlock[] = threadMXBean.findDeadlockedThreads(); if (deadlock != null && deadlock.length > 0) { ps.println("Deadlocked threads : "); for (long d: deadlock) { ps.println(threadMXBean.getThreadInfo(d)); } ps.println(); } long monitorLocked[] = threadMXBean.findMonitorDeadlockedThreads(); if (monitorLocked != null && monitorLocked.length > 0) { ps.println("Monitor locked threads : "); for (long d: monitorLocked) { ps.println(threadMXBean.getThreadInfo(d)); } ps.println(); } return sw.toString(); } protected static String systemState; }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/FileComparator.java
package abbot.tester; import java.io.*; /** * Compare two files or filenames. Original concept contributed by A. Smith * Montebello. * @author asmithmb * @version 1.0 */ public class FileComparator implements java.util.Comparator { /** * Read files into streams and call byte by byte comparison method * @param f1 First File or filename to compare. * @param f2 Second File or filename to compare. */ public int compare(Object f1, Object f2) { if ((f1 == f2) || (f1 != null && f1.equals(f2))) return 0; // Call null < object if (f1 == null) return -1; // Call object > null if (f2 == null) return 1; File file1, file2; if (f1 instanceof File) { file1 = (File)f1; } else if (f1 instanceof String) { file1 = new File((String)f1); } else { throw new IllegalArgumentException("Expecting a File or String"); } if (f2 instanceof File) { file2 = (File)f2; } else if (f2 instanceof String) { file2 = new File((String)f2); } else { throw new IllegalArgumentException("Expecting a File or String"); } if (file1.equals(file2)) { return 0; } if (!file1.exists() || !file1.isFile()) { throw new IllegalArgumentException("File '" + file1 + "' does not exist"); } if (!file2.exists() || !file2.isFile()) { throw new IllegalArgumentException("File '" + file2 + "' does not exist"); } if (file1.length() != file2.length()) { return (int)(file1.length() - file2.length()); } InputStream is1 = null; InputStream is2 = null; try { is1 = new BufferedInputStream(new FileInputStream(file1)); is2 = new BufferedInputStream(new FileInputStream(file2)); int b1 = -2; int b2 = -2; try { while ((b1 = is1.read()) != -1 && (b2 = is2.read()) != -1) { if (b1 != b2) return b1 - b2; b1 = b2 = -2; } } catch(IOException io) { return b1 == -2 ? -1 : 1; } finally { is1.close(); is1 = null; is2.close(); is2 = null; } return 0; } catch(FileNotFoundException fnf) { return is1 == null ? -1 : 1; } catch(IOException io) { return is1 == null ? -1 : 1; } } /** Comparators are equal if they're the same class. */ public boolean equals(Object obj) { return obj == this || (obj != null && obj.getClass().equals(getClass())); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/FileDialogTester.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import abbot.*; import abbot.util.Bugs; /** * Tester for the java.awt.FileDialog. * * @author Vrata Venet, European Space Agency, Madrid-Spain ([email protected]) * @author Tim Wall (twall:users.sf.net) * NOTE: different platforms do different things when the dialog is hidden. * w32 returns null for the file if FileDialog.hide is invoked; other * platforms may leave the file as is. OSX (as of 1.4.2) won't let you hide * the dialog. */ public class FileDialogTester extends DialogTester { /** * This sets the file path for the fd */ public void actionSetFile(Component comp, final String file) { if (null == file || "".equals(file)) throw new IllegalArgumentException("File name in FileDialog should be non-null and non-empty"); final FileDialog dialog = (FileDialog) comp; invokeAndWait(new Runnable() { public void run() { dialog.setFile(file); } }); } public void actionSetDirectory(Component comp, final String dir) { if (null == dir || "".equals(dir)) throw new IllegalArgumentException("File name in FileDialog should be non-null and non-empty"); final FileDialog dialog = (FileDialog) comp; invokeAndWait(new Runnable() { public void run() { dialog.setDirectory(dir); } }); } /** Accept the currently selected file. */ public void actionAccept(Component comp){ Log.debug("accept"); final FileDialog fd = (FileDialog)comp; final String file = fd.getFile(); if (file == null) throw new ActionFailedException("No file selected"); // HACK: // sun.awt.windows.WFileDialogPeer posts an InvocationEvent which sets // the FileDialog's file to null when Dialog.hide is called. // Install an event queue which can catch the posted event and ignore // it. Only fully tested against sun.awt.windows.WFileDialogPeer. FileDialogQueue queue = new FileDialogQueue(); // OSX disposes the FileDialog after hide, which is an event we // can spot fd.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { fd.setFile(file); fd.removeWindowListener(this); } }); try { fd.getToolkit().getSystemEventQueue().push(queue); // 1.4.2 bug workaround: FileDialog.hide doesn't work if (Bugs.fileDialogRequiresDismiss()) { actionKeyStroke(KeyEvent.VK_ESCAPE); } invokeAndWait(new Runnable() { public void run() { fd.setVisible(false); } }); fd.setFile(file); } finally { queue.dispose(); } } private class FileDialogQueue extends EventQueue { private boolean disposed = false; private boolean installed = false; public void dispose() { boolean remove = false; synchronized(this) { if (!disposed) { disposed = true; remove = true; } } if (remove) { try { pop(); } catch(java.util.EmptyStackException e) { Log.warn(e); } } } protected void dispatchEvent(AWTEvent e) { synchronized(this) { if (!installed) { installed = true; String name = Thread.currentThread().getName(); Thread.currentThread().setName(name + " (abbot FileDialogTester)"); } } // Ignore FileDialogPeer events while disposing the dialog if (e.paramString().indexOf("FileDialogPeer") != -1) { Log.debug("ignoring peer event: " + e); // Nothing else to handle, restore the original queue dispose(); } else { super.dispatchEvent(e); } } } /** Close the file dialog without selecting a file. */ public void actionCancel(Component comp) { final FileDialog fd = (FileDialog)comp; if (Platform.isOSX()) { // bug in OSX 1.4.2: activate causes another dialog to appear! //activate(fd); // Assume dialog has focus actionKeyStroke(KeyEvent.VK_ESCAPE); } else { // the w32 native peer sets the file to null on dialog hide, but // other platforms might not, so do it explicitly. fd.setFile(null); invokeAndWait(new Runnable() { public void run() { fd.setVisible(false); } }); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/FrameTester.java
package abbot.tester; import java.awt.*; public class FrameTester extends WindowTester { /** Return a unique tag to help identify the given component. */ public String deriveTag(java.awt.Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; String tag = ((java.awt.Frame)comp).getTitle(); if (tag == null || "".equals(tag)) { tag = super.deriveTag(comp); } return tag; } /** Iconify the given Frame. */ public void actionIconify(Component comp) { iconify((Frame)comp); waitForIdle(); } /** Deiconify the given Frame. */ public void actionDeiconify(Component comp) { deiconify((Frame)comp); waitForIdle(); } /** Maximize the given Frame. */ public void actionMaximize(Component comp) { maximize((Frame)comp); waitForIdle(); } /** Normalize the given Frame. Note that on 1.3.1 systems this may have * no effect after a maximize. */ public void actionNormalize(Component comp) { normalize((Frame)comp); waitForIdle(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ImageComparator.java
package abbot.tester; import abbot.InterruptedAbbotException; import java.awt.Image; import java.awt.image.*; import java.io.*; import javax.swing.ImageIcon; import abbot.Log; import java.net.URL; import javax.imageio.ImageIO; /** This code expects the availability of the com.sun.image.codec.jpeg extensions from the Sun JDK 1.3 or JRE. Original comparison code contributed by asmithmb. author: [email protected], twall */ public class ImageComparator implements java.util.Comparator { public static String IMAGE_SUFFIX; static { // TODO: figure out how to do PNG stuff under 1.3 (w/o ImageIO) try { Class.forName("javax.imageio.ImageIO"); IMAGE_SUFFIX = ".png"; } catch(ClassNotFoundException e) { IMAGE_SUFFIX = ".jpg"; } } private static Image convertToImage(Object obj) throws IOException { if (obj instanceof String) { obj = new File((String)obj); } if (obj instanceof BufferedImage) { // Convert to file and back to avoid unexplained // memory-only BufferedImage differences File tmp = File.createTempFile("ImageComparator", IMAGE_SUFFIX); tmp.deleteOnExit(); writeImage(tmp, (BufferedImage)obj); obj = tmp; } if (obj instanceof File) { obj = new ImageIcon(((File)obj).toURI().toURL()).getImage(); } if (obj instanceof URL) { obj = new ImageIcon((URL)obj).getImage(); } if (obj instanceof Image) { return (Image)obj; } return null; } public static void writeImage(File file, BufferedImage img) throws IOException { if (".png".equals(IMAGE_SUFFIX)) writePNG(file, img); else writeJPEG(file, img); } public static void writePNG(File file, BufferedImage img) throws IOException { javax.imageio.ImageIO.write(img, "png", file); } /** Write the given buffered image to disk. */ public static void writeJPEG(File file, BufferedImage img) throws IOException { FileOutputStream os = new FileOutputStream(file); // Replace code with JDK clean code ImageIO.write(img, "jpeg", os); os.close(); } /** Compare two images. May be BufferedImages or File arguments. */ public int compare(Object obj1, Object obj2) { try { obj1 = convertToImage(obj1); } catch(IOException io) { throw new IllegalArgumentException("Object is not convertable to an Image: " + obj1); } try { obj2 = convertToImage(obj2); } catch(IOException io) { throw new IllegalArgumentException("Object is not convertable to an Image: " + obj2); } Log.debug("Comparing " + obj1 + " and " + obj2); Image image1 = (Image)obj1; int w = image1.getWidth(null); int h = image1.getHeight(null); Image image2 = (Image)obj2; int w2 = image2.getWidth(null); int h2 = image2.getHeight(null); if (w*h != w2*h2) { return w*h - w2*h2; } int[] pixels1 = new int[w*h]; int[] pixels2 = new int[w*h]; PixelGrabber pg1 = new PixelGrabber(image1, 0, 0, w, h, pixels1, 0, w); PixelGrabber pg2 = new PixelGrabber(image2, 0, 0, w, h, pixels2, 0, w); try { pg1.grabPixels(); pg2.grabPixels(); for (int i=0;i < w*h;i++) { if (pixels1[i] != pixels2[i]) { return pixels1[i] - pixels2[i]; } } } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted when comparing images"); } return 0; } /** Comparators are equal if they're the same class. */ public boolean equals(Object obj) { return obj == this || (obj != null && obj.getClass().equals(getClass())); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/InputState.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import java.awt.dnd.*; import java.lang.reflect.*; import java.lang.ref.WeakReference; import java.util.Stack; import javax.swing.SwingUtilities; import abbot.Log; import abbot.util.*; /** Class to keep track of a given input state. Includes mouse/pointer * position and keyboard modifier key state.<p> * Synchronization assumes that any given instance might be called from more * than one event dispatch thread.<p> * NOTE: Java 1.5 introduces MouseState, which provides current mouse coords */ // TODO: add a BitSet with the full keyboard key press state public class InputState { private static final int BUTTON_MASK = (MouseEvent.BUTTON1_MASK |MouseEvent.BUTTON2_MASK |MouseEvent.BUTTON3_MASK); /** Current mouse position, in component coordinates. */ private Point mouseLocation = new Point(0, 0); /** Current mouse position, in screen coordinates. */ private Point mouseLocationOnScreen = new Point(0, 0); /** Keep a stack of mouse-entered components. Note that the pointer is still considered within a frame when the mouse enters a contained component. */ private Stack componentStack = new Stack(); private Stack locationStack = new Stack(); private Stack screenLocationStack = new Stack(); private int buttonsDown; private int modifiersDown; private long lastEventTime; private int clickCount; private Component dragSource; private int dragX, dragY; private EventNormalizer normalizer; public InputState() { long mask = MouseEvent.MOUSE_MOTION_EVENT_MASK |MouseEvent.MOUSE_EVENT_MASK|KeyEvent.KEY_EVENT_MASK; AWTEventListener listener = new SingleThreadedEventListener() { protected void processEvent(AWTEvent event) { update(event); } }; normalizer = new EventNormalizer(); normalizer.startListening(listener, mask); } public synchronized void clear() { componentStack.clear(); locationStack.clear(); buttonsDown = 0; modifiersDown = 0; lastEventTime = 0; clickCount = 0; dragSource = null; } public void dispose() { normalizer.stopListening(); normalizer = null; } /** Explicitly update the internal state. Allows Robot to update the * state with events it has just posted. */ void update(AWTEvent event) { if (event instanceof MouseEvent) { updateState((MouseEvent)event); } else if (event instanceof KeyEvent) { updateState((KeyEvent)event); } } protected void updateState(KeyEvent ke) { // Ignore "old" events if (ke.getWhen() < lastEventTime) return; synchronized(this) { setLastEventTime(ke.getWhen()); setModifiers(ke.getModifiers()); // FIXME add state of individual keys } } protected void updateState(MouseEvent me){ // Ignore "old" events if (me.getWhen() < lastEventTime) { if (Log.isClassDebugEnabled(getClass())) Log.debug("Ignoring " + Robot.toString(me)); return; } Point where = me.getPoint(); // getComponentAt and getLocationOnScreen want the tree lock, so be // careful not to use any additional locks at the same time to avoid // deadlock. Point eventScreenLoc = null; boolean screenLocationFound = true; // Determine the current mouse position in screen coordinates try { eventScreenLoc = AWT.getLocationOnScreen(me.getComponent()); } catch(IllegalComponentStateException e) { // component might be hidden by the time we process this event screenLocationFound = false; } synchronized(this) { setLastEventTime(me.getWhen()); // When a button is released, only that button appears in the // modifier mask int whichButton = me.getModifiers() & BUTTON_MASK; if (me.getID() == MouseEvent.MOUSE_RELEASED) { buttonsDown &= ~whichButton; modifiersDown &= ~whichButton; } else if (me.getID() == MouseEvent.MOUSE_PRESSED) { buttonsDown |= whichButton; modifiersDown |= whichButton; } clickCount = me.getClickCount(); if (me.getID() == MouseEvent.MOUSE_PRESSED) { dragSource = me.getComponent(); dragX = me.getX(); dragY = me.getY(); } else if (me.getID() == MouseEvent.MOUSE_RELEASED || me.getID() == MouseEvent.MOUSE_MOVED) { dragSource = null; } if (me.getID() == MouseEvent.MOUSE_ENTERED) { componentStack.push(new WeakReference(me.getComponent())); locationStack.push(me.getPoint()); screenLocationStack.push(screenLocationFound ? eventScreenLoc : me.getPoint()); } else if (me.getID() == MouseEvent.MOUSE_EXITED) { if (componentStack.empty()) { if (Log.isClassDebugEnabled(getClass())) Log.debug("Got " + Robot.toString(me) + " but component not on stack"); } else { componentStack.pop(); locationStack.pop(); screenLocationStack.pop(); } } if (screenLocationFound) { if (componentStack.empty()) { mouseLocation = null; } else { mouseLocation = new Point(where); } mouseLocationOnScreen.setLocation(eventScreenLoc); mouseLocationOnScreen.translate(where.x, where.y); } } } /** Return the component under the given coordinates in the given parent component. Events are often generated only for the outermost container, so we have to determine if the pointer is actually within a child. Basically the same as Component.getComponentAt, but recurses to the lowest-level component instead of only one level. Point is in component coordinates.<p> The default Component.getComponentAt can return invisible components (JRootPane has an invisible JPanel (glass pane?) which will otherwise swallow everything).<p> NOTE: getComponentAt grabs the TreeLock, so this should *only* be invoked on the event dispatch thread, preferably with no other locks held. Use it elsewhere at your own risk.<p> NOTE: What about drags outside a component? */ public static Component getComponentAt(Component parent, Point p) { Log.debug("Checking " + p + " in " + Robot.toString(parent)); Component c = SwingUtilities.getDeepestComponentAt(parent, p.x, p.y); Log.debug("Deepest is " + Robot.toString(c)); return c; } /** Return the most deeply nested component which currently contains the * pointer. */ public synchronized Component getUltimateMouseComponent() { Component c = getMouseComponent(); if (c != null) { Point p = getMouseLocation(); c = getComponentAt(c, p); } return c; } /** Return the last known Component to contain the pointer, or null if none. Note that this may not correspond to the component that actually shows up in AWTEvents. */ public synchronized Component getMouseComponent() { Component comp = null; if (!componentStack.empty()) { WeakReference ref = (WeakReference)componentStack.peek(); comp = (Component)ref.get(); // Make sure we don't return a component that has gone away. if (comp == null || !comp.isShowing()) { Log.debug("Discarding unavailable component"); componentStack.pop(); locationStack.pop(); screenLocationStack.pop(); comp = getMouseComponent(); if (comp != null) { mouseLocation = (Point)locationStack.peek(); mouseLocationOnScreen = (Point)screenLocationStack.peek(); } } } if (Log.isClassDebugEnabled(getClass())) Log.debug("Current component is " + Robot.toString(comp)); return comp; } public synchronized boolean isDragging() { return dragSource != null; } public synchronized Component getDragSource() { return dragSource; } public synchronized void setDragSource(Component c) { dragSource = c; } public synchronized Point getDragOrigin() { return new Point(dragX, dragY); } public synchronized int getClickCount() { return clickCount; } protected synchronized void setClickCount(int count) { clickCount = count; } public synchronized long getLastEventTime() { return lastEventTime; } protected synchronized void setLastEventTime(long t) { lastEventTime = t; } /** Returns all currently active modifiers. */ public synchronized int getModifiers() { return modifiersDown; } protected synchronized void setModifiers(int m) { modifiersDown = m; } /** Returns the currently pressed key modifiers. */ public synchronized int getKeyModifiers() { return modifiersDown & ~BUTTON_MASK; } public synchronized int getButtons() { return buttonsDown; } protected synchronized void setButtons(int b) { buttonsDown = b; } /** Returns the mouse location relative to the component that currently contains the pointer, or null if outside all components. */ public synchronized Point getMouseLocation() { return mouseLocation != null ? new Point(mouseLocation) : null; } /** Returns the last known mouse location. */ public synchronized Point getMouseLocationOnScreen() { return new Point(mouseLocationOnScreen); } /** Return whether there is a native drag/drop operation in progress. */ public boolean isNativeDragActive() { try { Class cls = Class.forName("sun.awt.dnd.SunDragSourceContextPeer"); Method m = cls.getMethod("checkDragDropInProgress"); try { m.invoke(null); return false; } catch(InvocationTargetException e) { if (e.getTargetException() instanceof InvalidDnDOperationException) { return true; } } } catch(Exception e) { } return false; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JButtonTester.java
package abbot.tester; import javax.swing.JButton; /** * Provides action methods and assertions for {@link JButton}s. * * @author tlroche * @version $Id: JButtonTester.java 1419 2005-01-05 18:34:48Z twall $ */ public class JButtonTester extends AbstractButtonTester { }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JComboBoxTester.java
package abbot.tester; import java.awt.Component; import java.awt.Container; import java.util.ArrayList; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.swing.*; import abbot.Log; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; import abbot.util.AWT; import abbot.finder.*; import abbot.finder.matchers.*; import abbot.tester.Robot.ConditionEDTDecorator; import abbot.util.Condition; import java.util.concurrent.Callable; import javax.accessibility.AccessibleSelection; import javax.swing.plaf.ComboBoxUI; /** * JComboBoxTester for testing JComboBox instances. * * <p>In the case where you need to create a tester for JComboBox subclasses that * use novel components in the popup, for example jtree, you can quickly subclass * this tester to deal with those cases without the need to create a seperate * Recorder. Simply override the selectItemInPopup, getTargetClass, getValueAsStringFromRenderer * and findPopupComponent(Container) to return relavent values for your subclass * of JComboBox.</p> */ public class JComboBoxTester extends JComponentTester { private class PopupNotFoundException extends ActionFailedException { public PopupNotFoundException(String m) { super(m); } } private JListTester listTester = new JListTester(); /** Return an array of strings that represent the combo box list. * Note that the current selection might not be included, since it's * possible to have a custom (edited) entry there that is not included in * the default contents. */ public String[] getContents(JComboBox cb) { ArrayList list = new ArrayList(); for (int i = 0; i < cb.getItemCount(); i++) { list.add(cb.getItemAt(i).toString()); } return (String[])list.toArray(new String[list.size()]); } public void actionSelectIndex(Component comp, final int index) { final JComboBox cb = (JComboBox)comp; Component popup = makePopupVisible(cb); // try { // Not all LAFs use a JList for the popup try { selectIndexInPopup(popup, index); } catch (ComponentNotShowingException cnse) { // Log.warn("Problem selecting item in a combobox, going to retry then throw original exception"); // // popup = makePopupVisible(cb); // try { // selectIndexInPopup(popup, index); // } // catch (ComponentNotShowingException cnse2) { throw cnse; // } } } catch (PopupNotFoundException e) { invokeAndWait(new Runnable() { public void run() { cb.setSelectedIndex(index); if (cb.getUI().isPopupVisible(cb)) cb.getUI().setPopupVisible(cb, false); } }); } // Wait for all the events to processed waitForIdle(); } /** * @param cb The combobox we are working on. * @return The popup componet we have just made visible */ private Component makePopupVisible(final JComboBox cb) { // activate it, if not already showing if (!cb.getUI().isPopupVisible(cb)) { // NOTE: if the index is out of range, the selected item will be // one end or the other of the list. if (cb.isEditable()) { // Location of popup button activator is LAF-dependent invokeAndWait(new Runnable() { public void run() { cb.getUI().setPopupVisible(cb, true); } }); } else { actionClick(cb); } } // Wait for idle after combo box show waitForIdle(); // Wait for the popup component to be visible // final Component popup = findPopupComponent(cb); wait(new ConditionEDTDecorator(cb, new Condition() { public boolean test() { return isReadyForInput(popup); } public String toString() { return Strings.get("tester.JComboBox.popup_not_ready"); } }), defaultDelay / 4); // Ramp up delay as still getting return popup; } /** Provide an override point to select the correct index in whatever index the recording has specified */ protected void selectIndexInPopup(Component popup, int index) { listTester.actionSelectIndex(popup, index); } /** Find the component in the popup raised by this combo box, if the LAF actually uses one. */ public Component findPopupComponent(JComboBox cb) { Component popup = AWT.findActivePopupMenu(); if (popup == null) { long now = System.currentTimeMillis(); while ((popup = AWT.findActivePopupMenu()) == null) { if (System.currentTimeMillis() - now > popupDelay) throw new PopupNotFoundException(Strings.get("tester.JComboBox.popup_not_found")); sleep(); } } final Container popupAsContainer = (Container)popup; Component comp = callAndWait(cb, new Callable<Component>() { @Override public Component call() throws Exception { return findPopupComponent((Container)popupAsContainer); } }); if (comp == null) throw new PopupNotFoundException(Strings.get("tester.JComboBox.popup_not_found")); return comp; } /** * @param sb The combo box we are testing * @return The JList component used to display the combobox */ public JComponent findPopupFromUI(JComboBox sb) { Accessible a = sb.getUI().getAccessibleChild(sb, 0); if (a != null && a instanceof javax.swing.plaf.basic.ComboPopup) { // get the popup list JList list = ((javax.swing.plaf.basic.ComboPopup)a).getList(); return list; } return (JList)findPopupComponent(sb); } /** Find the correct popup component in the container */ protected Component findPopupComponent(Container parent) { try { ComponentFinder finder = BasicFinder.getDefault(); return finder.find(parent, new ClassMatcher(JList.class)); } catch (ComponentSearchException e) { return null; } } /** If the value looks meaningful, return it, otherwise return null. */ public String getValueAsString(JComboBox combo, JComponent popupComponent, Object item, int index) { Component c = combo.getRenderer().getListCellRendererComponent((JList)popupComponent, item, index, true, true); return convertRendererToString(c); } /** Allow the recorder to write out the correct class name. */ public Class getTargetClass() { return JComboBox.class; } public void actionSelectItem(Component comp, final String item) { final JComboBox cb = (JComboBox)comp; final JComponent popup = findPopupFromUI(cb); // Get rid of any previous popup invokeAndWait(comp, new Runnable() { @Override public void run() { if (cb.isPopupVisible()) { cb.hidePopup(); } } }); // Need to be done in one block otherwise the selection might changed boolean alreadySelected = Robot.callAndWait(cb, new Callable<Boolean>() { @Override public Boolean call() throws Exception { final Object obj = cb.getSelectedItem(); if ((obj == null && item == null) || (obj != null && ExtendedComparator.stringsMatch(item, getValueAsString(cb, popup, obj, cb.getSelectedIndex())))) return true; return false; } }); if (alreadySelected) { return; } final GetIndexForItem mo = new JComboBoxTester.GetIndexForItem(cb, popup, item); // Wait for make sure that the combo is populated wait(new ConditionEDTDecorator(cb, new Condition() { public boolean test() { return mo.call() > -1; } public String toString() { return Strings.get("tester.JComboBox.item_not_found", new Object[] { item, dumpList(cb) }); } }), defaultDelay / 4); // Ramp up delay as still getting int matchedIndex = Robot.callAndWait(cb, mo); if (matchedIndex != -1) { actionSelectIndex(comp, matchedIndex); return; } // While actions are supposed to represent real user actions, it's // possible that the current environment does not match sufficiently, // so we need to throw an appropriate exception that can be used to // diagnose the problem. String contents = dumpList(cb); throw new ActionFailedException(Strings.get("tester.JComboBox.item_not_found", new Object[] { item, contents })); } protected String dumpList(final JComboBox cb) { String mid = "["; StringBuffer contents = new StringBuffer(); JComponent list = findPopupFromUI(cb); for (int i = 0; i < cb.getItemCount(); i++) { contents.append(mid); contents.append(getValueAsString(cb, list, cb.getItemAt(i), i)); mid = ", "; } contents.append("]"); return contents.toString(); } /** * Temporary helper interface */ private interface RenderToString { public String render(Object obj, int index); } /** * A method object to access the index for particular item, aid in polling */ private class GetIndexForItem implements Callable<Integer> { private JComboBox _cb; private JComponent _list; private String _item; GetIndexForItem(JComboBox cb, JComponent list, String item) { this._cb = cb; this._list = list; this._item = item; } @Override public Integer call() { RenderToString correctRender = new RenderToString() { @Override public String render(Object obj, int index) { return getValueAsString(_cb, _list, obj, index); } }; int found = find(correctRender); // Previously JComboBoxTester use to default to using toString // so we are going to fall back where to using this so that // the test is some-what backwards'ly compatible if (found == -1) { found = find(new RenderToString() { @Override public String render(Object item, int index) { String value = item.toString(); return value; } }); if (found != -1) { Log.warn("JComboBoxTester falling back to legacy toString code for item matching " + _item.toString() + " but should be " + correctRender.render(_item, found)); } } return found; } private int find(RenderToString render) { int found = -1; for (int i = 0; i < this._cb.getItemCount(); i++) { Object obj = this._cb.getItemAt(i); String objString = render.render(obj, i); Log.debug("Comparing against '" + objString + "'"); if ((obj == null && this._item == null) || (obj != null && ExtendedComparator.stringsMatch(this._item, objString))) { found = i; break; } } return found; } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JComponentTester.java
package abbot.tester; import java.awt.*; import java.awt.event.KeyEvent; import java.util.*; import java.util.List; import javax.accessibility.AccessibleContext; import javax.swing.*; import abbot.*; import abbot.i18n.Strings; import abbot.script.ArgumentParser; import abbot.util.AWT; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Callable; /** Provides auto-scrolling prior to events for JComponent-derived classes. */ // NOTE may eventually need to push ComponentLocation up to Robot, so that // only mousePress and actionDrop need to be overridden. This would be mostly // aesthetic, since making the target point visible is sufficient; having the // entire substructure visible is just more pleasing to the eye. // FIXME may need to override key/focus actions to scroll prior to sending the // events, similar to how click is overridden here public class JComponentTester extends ContainerTester { /** This property is a duplicate of the one in JLabel, which we can't * access. */ private static final String LABELED_BY_PROPERTY = "labeledBy"; /** Derive a tag for identifying this component. */ public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; JComponent jComp = ((JComponent)comp); String tag = null; // If label.setLabelFor has been used, then this component has // a label; use its text JLabel label = (JLabel) ((JComponent)comp).getClientProperty(LABELED_BY_PROPERTY); if (label != null && label.getText() != null && label.getText().length() > 0) { tag = label.getText(); } if (tag == null || "".equals(tag)) { AccessibleContext context = jComp.getAccessibleContext(); tag = deriveAccessibleTag(context); } if (tag == null || "".equals(tag)) { tag = super.deriveTag(comp); } return tag; } /** Scrolls to ensure the substructure is in view before clicking. @deprecated Use {@link #actionClick(Component, ComponentLocation, int, int)} instead. */ public void actionClick(Component c, ComponentLocation loc, String buttons, int count) { actionClick(c, loc, AWT.getModifiers(buttons), count); } /** Scrolls to ensure the substructure is in view before clicking. */ public void actionClick(Component c, ComponentLocation loc, int buttons, int count) { if (c instanceof JComponent) { scrollToVisible(c, loc.getBounds(c)); } super.actionClick(c, loc, buttons, count); } /** @deprecated Use {@link #actionDrag(Component, ComponentLocation, int)} instead. */ public void actionDrag(Component c, ComponentLocation loc, String mods) { actionDrag(c, loc, AWT.getModifiers(mods)); } /** Scrolls to ensure the substructure is in view before starting the * drag. */ public void actionDrag(Component c, ComponentLocation loc, int modifiers) { if (c instanceof JComponent) { scrollToVisible(c, loc.getBounds(c)); } super.actionDrag(c, loc, modifiers); } /** Scrolls to ensure the drop target substructure is in view before dropping (normally handled by autoscroll). */ public void actionDrop(Component c, ComponentLocation loc) { if (c instanceof JComponent) { scrollToVisible(c, loc.getBounds(c)); } super.actionDrop(c, loc); } /** Click in the given part of the component, scrolling the component if * necessary to make the point visible. Performing the scroll here * obviates the need for all derived classes to remember to do it for * actions involving clicks. */ public void mousePress(Component comp, int x, int y, int buttons) { if (comp instanceof JComponent) { scrollToVisible(comp, x, y); } super.mousePress(comp, x, y, buttons); } /** * Scrolls the component so that the coordinate x and y are visible. Has * no effect if the component has no JViewport ancestor. * * @param comp the Component to scroll * @param x the x coordinate to be visible * @param y the y coordinate to be visible */ protected void scrollToVisible(Component comp, int x, int y) { Rectangle rect = new Rectangle(x, y, 1, 1); scrollToVisible(comp, rect); } /** Invoke {@link JComponent#scrollRectToVisible(Rectangle)} on the given {@link JComponent} on the event dispatch thread. */ protected void scrollRectToVisible(final JComponent jc, final Rectangle rect) { Log.debug("Scroll to visible: " + rect); // Ideally, we'd use scrollbar commands to effect the scrolling, // but that gets really complicated for no real gain in function. // Fortunately, Swing's Scrollable makes for a simple solution. // NOTE: absolutely MUST wait for idle in order for the scroll to // finish, and the UI to update so that the next action goes // to the proper location within the scrolled component. invokeAndWait(new Runnable() { public void run() { jc.scrollRectToVisible(rect); } }); } protected boolean isVisible(JComponent c, Rectangle rect) { Rectangle visible = c.getVisibleRect(); return visible.contains(rect); } protected boolean isVisible(JComponent c, int x, int y) { Rectangle visible = c.getVisibleRect(); return visible.contains(x, y); } /** * Scrolls the component so that the given rectangle is visible. Has no * effect if the component has no JViewport ancestor. When this method * returns, the requested rectangle's upper left corner will be visible * (i.e. no {@link #waitForIdle()} is required. * * @param comp the Component to scroll * @param rect the Rectangle to make visible. */ protected void scrollToVisible(Component comp, final Rectangle rect) { final JComponent jc = (JComponent)comp; if (!isVisible(jc, rect)) { scrollRectToVisible(jc, rect); // Need to make at least the upper left corner of the requested // rectangle visible. if (!isVisible(jc, rect.x, rect.y)) { String msg = Strings.get("tester.JComponent.not_visible", new Object[] { new Integer(rect.x), new Integer(rect.y), jc, }); throw new ActionFailedException(msg); } } } /** Make sure the given point is visible. Note that this may have no * effect if the component is not actually in a scroll pane. */ public void actionScrollToVisible(Component comp, ComponentLocation loc) { scrollToVisible(comp, loc.getBounds(comp)); waitForIdle(); } /** Make sure the given point is visible. Note that this may have no * effect if the component is not actually in a scroll pane. */ public void actionScrollToVisible(Component comp, int x, int y) { actionScrollToVisible(comp, new ComponentLocation(new Point(x, y))); } /** Make sure the given rectangle is visible. Note that this may have no * effect if the component is not actually in a scroll pane. */ public void actionScrollToVisible(Component comp, int x, int y, int width, int height) { scrollToVisible(comp, new Rectangle(x, y, width, height)); waitForIdle(); } /** Invoke an action from the component's action map. */ public void actionActionMap(final Component comp, final String name) { focus(comp, true); List<KeyStroke> strokes = callAndWait(comp, new Callable<List<KeyStroke>>(){ @Override public List call() throws Exception { JComponent jc = (JComponent)comp; List<KeyStroke> strokes = new ArrayList<KeyStroke>(); ActionMap am = jc.getActionMap(); // On OSX/1.3.1, some action map keys are actions instead of strings. // On XP/1.4.1, all action map keys are strings. // If we can't look it up with the string key we saved, check all the // actions for a corresponding name. Object action = am.get(name); Object key = name; if (action == null) { Object[] keys = am.allKeys(); for (int i=0;keys != null && i < keys.length;i++) { Object value = am.get(keys[i]); if ((value instanceof Action)) { if (name.equals(((Action)value).getValue(Action.NAME))) { action = value; key = keys[i]; break; } } } } if (action == null) { String available = "Available actions are the following:"; Object[] names = am.allKeys(); if (names != null) { Arrays.sort(names, new java.util.Comparator() { public int compare(Object o1, Object o2) { String n1 = o1.toString(); String n2 = o2.toString(); return n1.compareTo(n2); } }); for (int i=0;i < names.length;i++) { available += "\n" + names[i]; if (!(names[i] instanceof String)) available += " (" + names[i].getClass() + ")"; } } throw new AssertionFailedError("No such action '" + name + "'. " + available); } InputMap im = jc.getInputMap(); KeyStroke[] events = im.allKeys(); for (int i=0;events != null && i < events.length;i++) { KeyStroke ks = events[i]; if (key.equals(im.get(ks))) { strokes.add(ks); } } return strokes; } }); // If we have fouNd somethiNg use it if (strokes.size() > 0) { for (Iterator<KeyStroke> i=strokes.iterator();i.hasNext();) { KeyStroke ks = i.next(); Log.debug("Generating keystroke " + ks + " for action " + name); try { if (ks.getKeyCode() == KeyEvent.VK_UNDEFINED) keyStroke(ks.getKeyChar()); else key(ks.getKeyCode(), ks.getModifiers()); waitForIdle(); return; } catch(IllegalArgumentException e) { // try the next one, if any } } } String msg = "No valid input event found for action with key '" + name + "'"; if (strokes.size() > 0) msg += " (tried " + strokes + ")"; throw new ActionFailedException(msg); } /** Return a shared instance of JComponentTester. */ public static JComponentTester getTester(JComponent c) { return (JComponentTester)ComponentTester.getTester(JComponent.class); } /** * @param cr A custom cell renderer * @return Either the name in the case or a label, or uses reflection to * call "getText" which covers a range of other components and custom * renderers */ public static String convertRendererToString(Component cr) { String string = null; if (cr instanceof JLabel) { String label = ((JLabel)cr).getText(); if (label != null) label = label.trim(); if (!"".equals(label) && !ArgumentParser.isDefaultToString(label)) { string = label; } } else { // Fall back to looking for a generic getText call // This will work for JTextField and JButton for examples // and provides an extension point for other renderes // Class cls = cr.getClass(); String className = cls.getName(); className = className.substring(className.lastIndexOf(".")+1); try { Method method; method = cls.getMethod("getText", new Class[0]); if (method != null) { String label; label = (String)method.invoke(cr, new Object[0]); if (label != null) label = label.trim(); if (!"".equals(label)) { string = label; } } } catch (IllegalAccessException e) { Log.log("Error calling getText on " + className, e); } catch (InvocationTargetException e) { Log.log("Error calling getText on " + className, e); } catch (NoSuchMethodException e) { Log.log("Cannot find getText method on render " + className, e); } } // If we have a string do the argument converter thing // if (string!=null) { String parsed = ArgumentParser.toString(string); String filtered = parsed == ArgumentParser.DEFAULT_TOSTRING ? null : parsed; return filtered; } else { return null; } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JFileChooserTester.java
package abbot.tester; import java.awt.*; import java.io.File; import javax.swing.*; import abbot.finder.*; import abbot.finder.matchers.*; import abbot.i18n.Strings; /** * Tester for the {@link JFileChooser}. * Note: only a small subset of JFileChooser functionality is exposed here. * @author [email protected] */ public class JFileChooserTester extends JComponentTester { private JTextComponentTester tester = new JTextComponentTester(); private ComponentFinder finder = BasicFinder.getDefault(); private Component find(Container chooser, Matcher m) { try { return finder.find(chooser, m); } catch(ComponentSearchException e) { return null; } } private JButton findButton(Container chooser, final String text) { JButton button = (JButton)find(chooser, new ClassMatcher(JButton.class) { public boolean matches(Component c) { return super.matches(c) && text.equals(((JButton)c).getText()); } }); return button; } /** Sets the selected file. */ public void actionSetSelectedFile(Component c, final File file) { final JFileChooser chooser = (JFileChooser)c; int mode = chooser.getFileSelectionMode(); if (mode == JFileChooser.FILES_ONLY && file.isDirectory()) { String msg = Strings.get("tester.JFileChooser.files_only"); throw new ActionFailedException(msg); } if (mode == JFileChooser.DIRECTORIES_ONLY && !file.isDirectory()) { String msg = Strings.get("tester.JFileChooser.dirs_only"); throw new ActionFailedException(msg); } invokeAndWait(new Runnable() { public void run() { chooser.setSelectedFile(file); }}); } /** Sets the text in the file name/path text field. Note that the * {@link JFileChooser} may behave differently depending on what * you actually feed into that field. */ public void actionSetFilename(Component c, String filename) { JTextField tf = (JTextField) find((JFileChooser)c, new ClassMatcher(JTextField.class)); if (tf == null) { String msg = Strings.get("tester.JFileChooser.filename_not_found"); throw new ActionFailedException(msg); } tester.actionEnterText(tf, filename); } /** Sets the current directory from which a file or directory may * be selected. This is not the same thing as setting the * <em>selected</em> directory when in directory selection mode. */ public void actionSetDirectory(Component c, final String path) { final JFileChooser chooser = (JFileChooser)c; invokeAndWait(new Runnable() { public void run() { chooser.setCurrentDirectory(new File(path)); }}); waitForIdle(); } /** Press the approve button. Fails if the button is disabled. */ public void actionApprove(Component c) { // Could invoke chooser.approveSelection, but that doesn't actually // fire the approve button. JFileChooser chooser = (JFileChooser)c; String text = chooser.getApproveButtonText(); if (text == null) { text = chooser.getUI().getApproveButtonText(chooser); } JButton approve = findButton(chooser, text); if (approve == null) { String msg = Strings.get("tester.JFileChooser.approve_not_found"); throw new ActionFailedException(msg); } if (!approve.isEnabled()) { String msg = Strings.get("tester.JFileChooser.approve_not_enabled"); throw new ActionFailedException(msg); } actionClick(approve); } /** Press the cancel button. Fails if the button is disabled. */ public void actionCancel(Component c) { // We could invoke chooser.cancelSelection, but that wouldn't actually // fire the cancel button... JFileChooser chooser = (JFileChooser)c; JButton cancel = findButton(chooser, UIManager.getString("FileChooser.cancelButtonText")); if (cancel == null) { String msg = Strings.get("tester.JFileChooser.cancel_not_found"); throw new ActionFailedException(msg); } if (!cancel.isEnabled()) { String msg = Strings.get("tester.JFileChooser.cancel_not_enabled"); throw new ActionFailedException(msg); } actionClick(cancel); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JInternalFrameTester.java
package abbot.tester; import java.awt.*; import java.beans.PropertyVetoException; import javax.swing.JInternalFrame; public class JInternalFrameTester extends JComponentTester { private class VetoFailure { public PropertyVetoException e = null; } /** Maximize or normalize the given frame. Iconified frames should use * deiconify, not normalize. */ protected void maximize(final JInternalFrame frame, final boolean b) { if (b && !frame.isMaximizable()) throw new ActionFailedException("The given JInternalFrame (" + toString(frame) + ") is not " + "maximizable"); if (!b && frame.isIcon()) throw new ActionFailedException("The given JInternalFrame (" + toString(frame) + ") is " + "iconified and must be " + "deiconified before it can " + "be normalized"); Container clickTarget = frame; if (frame.isIcon()) { clickTarget = frame.getDesktopIcon(); } Point p = getMaximizeLocation(clickTarget); mouseMove(clickTarget, p.x, p.y); if (frame.isIcon()) { iconify(frame, false); } final VetoFailure veto = new VetoFailure(); invokeAndWait(new Runnable() { public void run() { try { frame.setMaximum(b); } catch(PropertyVetoException e) { veto.e = e; } } }); if (veto.e != null) { throw new ActionFailedException("Maximize of " + Robot.toString(frame) + " was vetoed (" + veto.e + ")"); } } public void actionMaximize(Component comp) { maximize((JInternalFrame)comp, true); } public void actionNormalize(Component comp) { maximize((JInternalFrame)comp, false); } /** Iconify/deiconify the given frame. If the frame is already in the * desired state, does nothing. */ protected void iconify(final JInternalFrame frame, final boolean b) { if ((b && frame.isIcon()) || (!b && !frame.isIcon())) return; if (b) { if (!frame.isIconifiable()) throw new ActionFailedException("The given JInternalFrame (" + toString(frame) + ") is not " + "iconifiable"); Point p = getIconifyLocation(frame); mouseMove(frame, p.x, p.y); } else { Container c = frame.getDesktopIcon(); Point p = getIconifyLocation(c); mouseMove(c, p.x, p.y); } final VetoFailure veto = new VetoFailure(); invokeAndWait(new Runnable() { public void run() { try { frame.setIcon(b); } catch(PropertyVetoException e) { veto.e = e; } } }); if (veto.e != null) { throw new ActionFailedException("Iconify of " + Robot.toString(frame) + " was vetoed (" + veto.e + ")"); } } /** Iconify the given Frame. */ public void actionIconify(Component comp) { iconify((JInternalFrame)comp, true); } /** Deiconify the given Frame. */ public void actionDeiconify(Component comp) { iconify((JInternalFrame)comp, false); } /** Move the given internal frame. */ public void actionMove(Component comp, int x, int y) { move((JInternalFrame)comp, x, y); waitForIdle(); } /** Resize the given internal frame. */ public void actionResize(Component comp, int width, int height) { resize((JInternalFrame)comp, width, height); waitForIdle(); } /** Close the internal frame. */ public void actionClose(Component comp) { // This is LAF-specific, so it must be done programmatically. final JInternalFrame frame = (JInternalFrame)comp; if (!frame.isClosable()) throw new ActionFailedException("The given JInternalFrame (" + toString(frame) + ") is not " + "closable"); Point p = getCloseLocation(frame); mouseMove(frame, p.x, p.y); /* final InternalFrameEvent ife = new InternalFrameEvent(frame, InternalFrameEvent. INTERNAL_FRAME_CLOSING); */ // cf. BasicInternalFrameTitlePane#postClosingEvent handling of // close // Seems to be a bug in the handling of internal frame events; they're // not normally posted to the AWT event queue. invokeAndWait(new Runnable() { public void run() { frame.doDefaultCloseAction(); } }); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JLabelTester.java
package abbot.tester; import java.awt.Component; import javax.swing.JLabel; /** Provides action methods and assertions for {@link JLabel}s. */ public class JLabelTester extends JComponentTester { public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; String tag = stripHTML(((JLabel)comp).getText()); if (tag == null || "".equals(tag)) { //$NON-NLS-1$ tag = super.deriveTag(comp); } return tag; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JListLocation.java
package abbot.tester; import java.awt.*; import javax.swing.JList; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; /** Provides encapsulation of the location of a row on a JList (a coordinate, * item index or value). */ public class JListLocation extends ComponentLocation { private Object value; private int row = -1; /** The center of the target list. */ public JListLocation() { } /** Specify location by explicit reference to an object. */ public JListLocation(Object value) { this.value = value; } /** Specify location by string representation of an object. * @see JListTester#valueToString */ public JListLocation(String value) { this((Object)value); } /** Specify location by row in the list. */ public JListLocation(int row) { if (row < 0) { String msg = Strings.get("tester.JList.invalid_index", new Object[] { new Integer(row) }); throw new LocationUnavailableException(msg); } this.row = row; } /** Specify a location by component-relative coordinate. */ public JListLocation(Point where) { super(where); } protected String badFormat(String encoded) { return Strings.get("location.list.bad_format", new Object[] { encoded }); } /** Convert the given index into a coordinate. */ protected Point indexToPoint(JList list, int index) { if (index < 0 || index >= list.getModel().getSize()) { String msg = Strings.get("tester.JList.invalid_index", new Object[] { new Integer(index) }); throw new LocationUnavailableException(msg); } Rectangle rect = list.getCellBounds(index, index); return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } /** Find the first String match in the list and return the index. */ private int valueToIndex(JList list, Object value) { int size = list.getModel().getSize(); if (value instanceof String) { for (int i=0;i < size;i++) { String str = JListTester.valueToString(list, i); if (ExtendedComparator.stringsMatch((String)value, str)) { return i; } } } else { for (int i=0;i < size;i++) { Object el = list.getModel().getElementAt(i); if (el == null && value == null || el != null && el.equals(value)) { return i; } } } return -1; } public int getIndex(JList list) { if (value != null) return valueToIndex(list, value); if (row != -1) { return row; } return list.locationToIndex(super.getPoint(list)); } /** Return a concrete point for the abstract location. */ public Point getPoint(Component c) { JList list = (JList)c; if (value != null || row != -1) { int idx = getIndex(list); if (idx == -1) { throw new LocationUnavailableException(invalidMessage(list)); } return indexToPoint(list, idx); } return super.getPoint(list); } private String invalidMessage(JList list) { if (value != null) { return Strings.get("tester.JList.item_not_found", new Object[] { value, JListTester.dumpList(list) }); } if (row != -1) { return Strings.get("tester.JList.invalid_index", new Object[] { new Integer(row) }); } return Strings.get("tester.JList.point_not_found", new Object[] { super.getPoint(list) }); } public Rectangle getBounds(Component c) { JList list = (JList)c; int index = getIndex(list); if (index == -1) { throw new LocationUnavailableException(invalidMessage(list)); } return list.getCellBounds(index, index); } public boolean equals(Object o) { if (o instanceof JListLocation) { JListLocation loc = (JListLocation)o; if (value != null) return value.equals(loc.value); if (row != -1) return row == loc.row; } return super.equals(o); } public String toString() { if (value != null) return encodeValue(value.toString()); if (row != -1) return encodeIndex(row); return super.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (isValue(encoded)) { value = parseValue(encoded); return this; } if (isIndex(encoded)) { row = parseIndex(encoded); return this; } return super.parse(encoded); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JListTester.java
package abbot.tester; import java.awt.*; import javax.swing.*; import abbot.Log; import abbot.WaitTimedOutException; import abbot.i18n.Strings; import abbot.script.ArgumentParser; import abbot.tester.Robot.ConditionEDTDecorator; import abbot.util.Condition; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** Provide actions and assertions for a {@link JList} component. The {@link JList} substructure is a "row", and {@link JListLocation} provides different identifiers for a row. <ul> <li>Select an item by index <li>Select an item by value (its string representation) </ul> Note that {@link JList} uses "index" and "value" in its API. For convenience, the <code>JListTester</code> API also provides "row" and "item" as synonyms for "index". @see JListLocation */ // TODO multi-select public class JListTester extends JComponentTester { /** Convert the value in the list at the given index into a reasonable string representation, or null if one can not be obtained. */ public static String valueToString(final JList list, final int index) { // Ensure this work is done on the EDT, TODO move this // code up to Robot if we are sure we need to reuse it // Callable renderedToString = new Callable() { public Object call() { Object value = list.getModel().getElementAt(index); Component cr = list.getCellRenderer().getListCellRendererComponent(list, value, index, false, false); String string = convertRendererToString(cr); return string; } }; try { if (EventQueue.isDispatchThread()) { return (String)renderedToString.call(); } else { // TODO make sure we use the correct event queue, this method cannot be static // FutureTask ft = new FutureTask(renderedToString); EventQueue.invokeLater(ft); return (String)ft.get(); } } catch (Exception e) { throw new RuntimeException("Failure to query string value", e); } } /** JList doesn't provide direct access to its contents, so make up for * that oversight. */ public Object getElementAt(JList list, int index) { return list.getModel().getElementAt(index); } /** Return the size of the given list. */ public int getSize(JList list) { return list.getModel().getSize(); } /** Return an array of strings that represents the list's contents. */ public String[] getContents(JList list) { ListModel model = list.getModel(); String[] values = new String[model.getSize()]; for (int i=0;i < values.length;i++) { values[i] = model.getElementAt(i).toString(); } return values; } /** Select the given index. Equivalent to actionSelectRow(c, new JListLocation(index), delay). */ public void actionSelectIndex(Component c, int index, long delay) { actionSelectRow(c, new JListLocation(index), delay); } /** Select the given index. Equivalent to actionSelectRow(c, new JListLocation(index)). */ public void actionSelectIndex(Component c, int index) { actionSelectRow(c, new JListLocation(index)); } /** Select the first item in the list matching the given String representation of the item.<p> Equivalent to actionSelectRow(c, new JListLocation(item), delay). */ public void actionSelectItem(Component c, String item,long delay) { actionSelectRow(c, new JListLocation(item), delay); } /** Select the first item in the list matching the given String representation of the item.<p> Equivalent to actionSelectRow(c, new JListLocation(item)). */ public void actionSelectItem(Component c, String item) { actionSelectRow(c, new JListLocation(item)); } /** Select the first value in the list matching the given String representation of the value.<p> Equivalent to actionSelectRow(c, new JListLocation(value)). */ public void actionSelectValue(Component c, String value) { actionSelectRow(c, new JListLocation(value)); } /** Select the given row. Does nothing if the index is already * selected. */ public void actionSelectRow(Component c, final JListLocation location) { actionSelectRow(c,location, componentDelay); } /** Select the given row. Does nothing if the index is already * selected. */ public void actionSelectRow(Component c, final JListLocation location, long delay) { final JList list = (JList)c; // Wait for the selected location to become avaliable // wait(new ConditionEDTDecorator(c,new Condition() { public boolean test() { int index = location.getIndex(list); return index >= 0 && index < list.getModel().getSize(); } public String toString() { return Strings.get("tester.JList.item_not_found", new Object[] { location.toString(), JListTester.dumpList(list) }); } }), delay); // Select the location // final int targetIndex = location.getIndex(list); if (targetIndex < 0 || targetIndex >= list.getModel().getSize()) { String msg = Strings.get("tester.JList.invalid_index", new Object[] { new Integer(targetIndex) }); throw new ActionFailedException(msg); } if (list.getSelectedIndex() != targetIndex) { Log.debug("Click on index=" + targetIndex); final TemporarySelectionListener tsl = new TemporarySelectionListener(targetIndex); invokeAndWait(list, new Runnable() { @Override public void run() { list.addListSelectionListener(tsl); } }); try { super.actionClick(c, location); // Wait for the selection to have been made, other stuff might happen // after that so all we can say for sure is that for one moment that // the list held that selection, so polling the selected value might // not be enough as the model might be altered by the time we get // to look at it // final Robot.ConditionEDTDecorator condition = new Robot.ConditionEDTDecorator(c, new Condition() { public boolean test() { return tsl.matched; } public String toString() { return Strings.get("tester.JList.item_not_selected", new Object[] { location.toString(), JListTester.dumpList(list), list.getSelectedIndex() }); } }); try { wait(condition, delay/4); } catch (WaitTimedOutException we) { // Now we have a solution for the mouse click issue... // Log.warn("Problem selecting item in a list, going to retry then throw original exception"); // // // We are seeing some intermitttent failures since JDK6u35 so if the selection // // didn't work try again // super.actionClick(c, location); // try { // wait(condition,delay/4); // } // catch (WaitTimedOutException we2) { // // Log.warn("Problem selecting item in a list, going to retry for a second time then throw original exception"); // // // We are seeing some intermitttent failures since JDK6u35 so if the selection // // didn't work try again // super.actionClick(c, location); // try { // wait(condition,delay/4); // } // catch (WaitTimedOutException we3) { throw we; // } // } } } finally { // Make sure we remove the temporary listener invokeAndWait(list, new Runnable() { @Override public void run() { list.removeListSelectionListener(tsl); } }); } } } /** Parse the String representation of a JListLocation into the actual JListLocation object. */ public ComponentLocation parseLocation(String encoded) { return new JListLocation().parse(encoded); } /** Return the value, row, or coordinate location. */ public ComponentLocation getLocation(Component c, Point p) { JList list = (JList)c; int index = list.locationToIndex(p); String value = valueToString(list, index); if (value != null) { return new JListLocation(value); } else if (index != -1) { return new JListLocation(index); } return new JListLocation(p); } public static String dumpList(final JList list) { String mid = "["; StringBuffer contents = new StringBuffer(); ListModel lm = list.getModel(); for (int i=0;i < lm.getSize();i++) { contents.append(mid); contents.append( valueToString(list, i)); mid = ", "; } contents.append("]"); return contents.toString(); } private static class TemporarySelectionListener implements ListSelectionListener { private volatile boolean matched = false; private int targetIndex; public TemporarySelectionListener(int targetIndex) { this.targetIndex = targetIndex; } @Override public void valueChanged(ListSelectionEvent e) { if (e.getFirstIndex() <= targetIndex && targetIndex <= e.getLastIndex()) { matched = true; } } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JMenuItemTester.java
package abbot.tester; import java.awt.Component; import javax.swing.JMenuItem; /** Provide action methods and assertions for {@link JMenuItem}s. */ public class JMenuItemTester extends AbstractButtonTester { public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; return ((JMenuItem)comp).getText(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JPopupMenuTester.java
package abbot.tester; import java.awt.Component; import javax.swing.*; /** Provides access to JPopupMenu contents. No special user actions. */ public class JPopupMenuTester extends JComponentTester { /** Return an identifying tag for the popup menu. */ public String deriveTag(Component comp) { Component invoker = ((JPopupMenu)comp).getInvoker(); return invoker == null ? "Popup menu" : "Popup on " + getTag(invoker); } /** Return the contents of the popup menu as a String array. */ public String[] getMenuLabels(Component comp) { JPopupMenu menu = (JPopupMenu)comp; MenuElement[] els = menu.getSubElements(); String[] result = new String[els.length]; for (int i=0;i < els.length;i++) { Component mi = els[i].getComponent(); if (mi instanceof JMenuItem) { result[i] = ((JMenuItem)mi).getText(); } else { result[i] = "-"; } } return result; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JRootPaneTester.java
package abbot.tester; import java.awt.Component; /** Hierarchy placeholder for JRootPane. There are no specific user * actions. */ public class JRootPaneTester extends JComponentTester { /** * Return a unique identifier for the given Component. There is only * ever one JRootPane for a given Window, so derive from the parent's * tag. */ public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; String tag = null; if (comp.getParent() != null) { String ptag = getTag(comp.getParent()); if (ptag != null && !"".equals(ptag)) tag = ptag + " Root Pane"; } if (tag == null || "".equals(tag)) tag = super.deriveTag(comp); return tag; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JScrollBarTester.java
package abbot.tester; import java.awt.*; import javax.swing.*; import abbot.i18n.*; import java.util.concurrent.Callable; /** Provides user actions on a JScrollPane. */ // TODO: ScrollBarLocation, which provides locations for thumb, arrows, etc // TODO: multi-scroll when arrows pressed and held // TODO: multi-scroll when block (outside thumb) pressed and held public class JScrollBarTester extends JComponentTester { private static final int BLOCK_OFFSET = 4; protected Point getThumbLocation(final JScrollBar bar, final int value) { return callAndWait(bar, new Callable<Point>() { @Override public Point call() throws Exception { boolean horizontal = bar.getOrientation() == JScrollBar.HORIZONTAL; double fraction = (double)value / (bar.getMaximum() - bar.getMinimum()); if (horizontal) { int arrow = bar.getHeight(); return new Point(arrow + (int)(fraction * (bar.getWidth() - 2*arrow)), arrow / 2); } int arrow = bar.getWidth(); return new Point(arrow / 2, arrow + (int)(fraction * (bar.getHeight() - 2*arrow))); } }); } protected Point getUnitLocation(final JScrollBar bar, final boolean up) { return callAndWait(bar, new Callable<Point>() { @Override public Point call() throws Exception { boolean horizontal = bar.getOrientation() == JScrollBar.HORIZONTAL; int arrow = horizontal ? bar.getHeight() : bar.getWidth(); if (up) { return horizontal ? new Point(bar.getWidth() - arrow/2, arrow/2) : new Point(arrow/2, bar.getHeight() - arrow/2); } return new Point(arrow/2, arrow/2); } }); } protected Point getBlockLocation(JScrollBar bar, boolean up) { boolean horizontal = bar.getOrientation() == JScrollBar.HORIZONTAL; Point p = getUnitLocation(bar, up); int offset = up ? BLOCK_OFFSET : -BLOCK_OFFSET; if (horizontal) p.x += offset; else p.y += offset; return p; } protected void scroll(final JScrollBar bar, final int value) { invokeLater(bar, new Runnable() { public void run() { bar.setValue(value); } }); waitForIdle(); } protected void scroll(JScrollBar bar, int count, boolean block) { // For now, do it programmatically, faking the mouse movement and // clicking Point where = block ? getBlockLocation(bar, count >= 0) : getUnitLocation(bar, count >= 0); // Don't really know if this is where the UI puts them // mouseClick(bar, where.x, where.y); mouseMove(bar, where.x, where.y); int value = bar.getValue() + count * (block ? bar.getBlockIncrement() : bar.getUnitIncrement()); scroll(bar, value); } /** Scroll up (or right) one unit (usually a line). */ public void actionScrollUnitUp(Component c) { scroll((JScrollBar)c, 1, false); } /** Scroll down (or left) one unit (usually a line). */ public void actionScrollUnitDown(Component c) { scroll((JScrollBar)c, -1, false); } /** Scroll up (or right) one block (usually a page). */ public void actionScrollBlockUp(Component c) { scroll((JScrollBar)c, 1, true); } /** Scroll down (or left) one block (usually a page). */ public void actionScrollBlockDown(Component c) { scroll((JScrollBar)c, -1, true); } /** Scroll to the given scroll position. */ public void actionScrollTo(Component c, final int position) { JScrollBar bar = (JScrollBar)c; int min = bar.getMinimum(); int max = bar.getMaximum(); if (position < min || position > max) { String msg = Strings.get("tester.JScrollBar.out_of_range", new Object[] { new Integer(position), new Integer(min), new Integer(max), }); throw new ActionFailedException(msg); } Point thumb = getThumbLocation(bar, bar.getValue()); mouseMove(bar, thumb.x, thumb.y); thumb = getThumbLocation(bar, position); mouseMove(bar, thumb.x, thumb.y); scroll(bar, position); } public void actionScrollToMinimum(Component c) { final JScrollBar bar = (JScrollBar)c; scroll(bar, callAndWait(c, new Callable<Integer>() { @Override public Integer call() throws Exception { return bar.getMinimum(); } })); } public void actionScrollToMaximum(Component c) { final JScrollBar bar = (JScrollBar)c; // Not actual value will be maximum - extent scroll(bar, callAndWait(c, new Callable<Integer>() { @Override public Integer call() throws Exception { return bar.getMaximum(); } })); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JSliderTester.java
package abbot.tester; import java.awt.Component; import java.awt.Insets; import java.awt.Point; import javax.swing.*; /** Provides access to all user actions on a JSlider. */ public class JSliderTester extends JComponentTester { private ComponentLocation valueToLocation(JSlider s, int value) { int range = s.getMaximum() - s.getMinimum(); int x = s.getWidth()/2; int y = s.getHeight()/2; Insets insets = s.getInsets(); float percent = (float)(value - s.getMinimum()) / range; if (s.getOrientation() == JSlider.VERTICAL) { int max = s.getHeight() - insets.top - insets.bottom - 1; y = (int)(percent * max); if (!s.getInverted()) { y = max - y; } } else { int max = s.getWidth() - insets.left - insets.right - 1; x = (int)(percent * max); if (s.getInverted()) { x = max - x; } } return new ComponentLocation(new Point(x, y)); } /** Click at the maximum end of the slider. */ public void actionIncrement(Component c) { JSlider s = (JSlider)c; actionClick(c, valueToLocation(s, s.getMaximum())); } /** Click at the minimum end of the slider. */ public void actionDecrement(Component c) { JSlider s = (JSlider)c; actionClick(c, valueToLocation(s, s.getMinimum())); } /** Slide the knob to the requested value. */ public void actionSlide(Component c, final int value) { final JSlider s = (JSlider)c; // can't do drag actions in AWT mode if (getEventMode() == EM_ROBOT) { actionDrag(c, valueToLocation(s, s.getValue())); actionDrop(c, valueToLocation(s, value)); } // the drag is only approximate, so set the value directly invokeAndWait(new Runnable() { public void run() { s.setValue(value); } }); } /** Slide the knob to its maximum. */ public void actionSlideMaximum(Component c) { actionSlide(c, ((JSlider)c).getMaximum()); } /** Slide the knob to its minimum. */ public void actionSlideMinimum(Component c) { actionSlide(c, ((JSlider)c).getMinimum()); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JSpinnerTester.java
package abbot.tester; import java.awt.Component; import java.awt.event.KeyEvent; import javax.swing.*; import javax.swing.text.*; import abbot.finder.BasicFinder; import abbot.finder.matchers.ClassMatcher; import abbot.i18n.Strings; /** Provides access to all user actions on a JSpinner. */ public class JSpinnerTester extends JComponentTester { /** Increment the JSpinner. */ public void actionIncrement(Component c) { actionKeyStroke(c, KeyEvent.VK_UP); } /** Decrement the JSpinner. */ public void actionDecrement(Component c) { actionKeyStroke(c, KeyEvent.VK_DOWN); } /** Set the value of the JSpinner, assuming its editor has a JTextComponent under it somewhere. */ public void actionSetValue(Component c, String value) { JComponent ed = ((JSpinner)c).getEditor(); try { Component tf = BasicFinder.getDefault(). find(ed, new ClassMatcher(JTextComponent.class)); JTextComponentTester t = new JTextComponentTester(); t.actionEnterText(tf, value); t.actionKeyStroke(tf, KeyEvent.VK_ENTER); } catch(Exception e) { String msg = Strings.get("tester.JSpinner.unknown_editor", new String[] { ed.toString() }); throw new ActionFailedException(msg); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JSplitPaneTester.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** Provides user actions on a JSplitPane. */ public class JSplitPaneTester extends JComponentTester { /** Set the divider position proportionally. */ public void actionMoveDivider(Component c, final double proportionalLocation) { JSplitPane split = (JSplitPane)c; int max = split.getMaximumDividerLocation(); int min = split.getMinimumDividerLocation(); int position = min + (int)((max - min) * proportionalLocation); actionMoveDividerAbsolute(split, position); } /** Set the divider position to an absolute position. */ public void actionMoveDividerAbsolute(Component c, final int location) { final JSplitPane split = (JSplitPane)c; int old = split.getDividerLocation(); // Move as close as possible, then programmatically set the position if (split.getOrientation() == JSplitPane.VERTICAL_SPLIT) { mouseMove(c, c.getWidth()/2, old); mousePress(InputEvent.BUTTON1_MASK); mouseMove(c, c.getWidth()/2, location); mouseRelease(); } else { mouseMove(c, old, c.getHeight()/2); mousePress(InputEvent.BUTTON1_MASK); mouseMove(c, location, c.getHeight()/2); mouseRelease(); } invokeAndWait(c, new Runnable() { public void run() { split.setDividerLocation(location); } }); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTabbedPaneLocation.java
package abbot.tester; import java.awt.*; import javax.swing.JTabbedPane; import javax.swing.plaf.TabbedPaneUI; import abbot.Log; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; /** Provides encapsulation of a location on a JTabbedPane (notably a tab). Use the JTabbedPaneLocation#JTabbedPaneLocation(Point) ctor to indicate a specific coordinate. */ public class JTabbedPaneLocation extends ComponentLocation { private String tabName = null; private int index = -1; public JTabbedPaneLocation() { } public JTabbedPaneLocation(String tabName) { this.tabName = tabName; } public JTabbedPaneLocation(int index) { if (index < 0) { String msg = Strings.get("tester.JTabbedPane.invalid_index", new Object[] { new Integer(index) }); throw new LocationUnavailableException(msg); } this.index = index; } public JTabbedPaneLocation(Point p) { super(p); } protected String badFormat(String encoded) { return Strings.get("location.tab.bad_format", new Object[] { encoded }); } /** Convert the given row, col into a coordinate pair. */ private Point indexToPoint(JTabbedPane tabs, int index) { if (index < 0 || index >= tabs.getTabCount()) { String msg = Strings.get("tester.JTabbedPane.invalid_index", new Object[] { new Integer(index) }); throw new LocationUnavailableException(msg); } Log.debug("converting index " + index); TabbedPaneUI ui = tabs.getUI(); Rectangle rect = ui.getTabBounds(tabs, index); // TODO: figure out the effects of tab layout policy // sometimes tabs are not directly visible if (rect == null || rect.x < 0) { throw new TabNotVisibleException(index); } return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } /** Return the row, col of the first object matching the given String. */ private int tabNameToIndex(JTabbedPane tabs, String name) { for (int i=0;i < tabs.getTabCount();i++) { String value = tabs.getTitleAt(i); if (ExtendedComparator.stringsMatch(name, value)) return i; } return -1; } /** @throws TabNotVisibleException if the tab is not visible */ public Point getPoint(Component c) { JTabbedPane tabs = (JTabbedPane)c; int idx = index; if (tabName != null) { if ((idx = tabNameToIndex(tabs, tabName)) == -1) { String msg = Strings.get("tester.JTabbedPane.invalid_name", new Object[] { tabName }); throw new LocationUnavailableException(msg); } } if (idx != -1) { return indexToPoint(tabs, idx); } return super.getPoint(tabs); } /** @throws TabNotVisibleException if the tab is not visible */ public Rectangle getBounds(Component c) { JTabbedPane tabs = (JTabbedPane)c; TabbedPaneUI ui = tabs.getUI(); // kinda hacky Point p = getPoint(tabs); int idx = ui.tabForCoordinate(tabs, p.x, p.y); if (idx != -1) { Rectangle bounds = ui.getTabBounds(tabs, idx); if (bounds == null) { throw new TabNotVisibleException(idx); } return bounds; } return super.getBounds(c); } // FIXME if they correspond to the same tab, are they equal? public boolean equals(Object o) { if (o instanceof JTabbedPaneLocation) { JTabbedPaneLocation loc = (JTabbedPaneLocation)o; if (tabName != null) return tabName.equals(loc.tabName); if (index != -1) return index == loc.index; } return super.equals(o); } public String toString() { if (tabName != null) return encodeValue(tabName); if (index != -1) return encodeIndex(index); return super.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (isValue(encoded)) { tabName = parseValue(encoded); return this; } if (isIndex(encoded)) { index = parseIndex(encoded); return this; } return super.parse(encoded); } /** This exception is thrown if a given tab is not currently visible. Some LAFs may not display all tabs concurrently. OSX, for example, puts tabs that don't fit into a popup menu. */ class TabNotVisibleException extends LocationUnavailableException { public int index; public TabNotVisibleException(int index) { super("Tab " + index + " not visible"); this.index = index; } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTabbedPaneTester.java
package abbot.tester; import java.awt.*; import java.util.ArrayList; import javax.swing.JTabbedPane; import javax.swing.plaf.TabbedPaneUI; import abbot.tester.JTabbedPaneLocation.TabNotVisibleException; import java.util.concurrent.Callable; /** Provides user actions on a JTabbedPane. */ public class JTabbedPaneTester extends JComponentTester { /** Return an array of strings that represent the tabs in the pane. */ public String[] getTabs(final Component comp) { return Robot.callAndWait(comp, new Callable<String[]>() { @Override public String[] call() { JTabbedPane tp = (JTabbedPane)comp; int count = tp.getTabCount(); ArrayList list = new ArrayList(count); for (int i=0;i < count;i++) { list.add(tp.getTitleAt(i)); } return (String[])list.toArray(new String[count]); } }); } public void actionSelectTab(final Component comp, final JTabbedPaneLocation loc) { Point pt; try { // Fix EDT violation, access this point information on the event queue // pt = Robot.callAndWait(comp, new Callable<Point>() { @Override public Point call() { return loc.getPoint(comp); } }); actionClick(comp, new ComponentLocation(pt)); } catch(final TabNotVisibleException e) { // Set the tab directly invokeAndWait(new Runnable() { public void run() { ((JTabbedPane)comp).setSelectedIndex(e.index); }}); } waitForIdle(); } /** Parse the String representation of a JTableLocation into the actual JTableLocation object. */ public ComponentLocation parseLocation(String encoded) { return new JTabbedPaneLocation().parse(encoded); } /** Return (in order of preference) the location corresponding to value, * cell, or coordinate. */ public ComponentLocation getLocation(final Component c, final Point p) { final JTabbedPane tabs = (JTabbedPane)c; final TabbedPaneUI ui = tabs.getUI(); return Robot.callAndWait(c, new Callable<JTabbedPaneLocation>() { public JTabbedPaneLocation call() { int index = ui.tabForCoordinate(tabs, p.x, p.y); if (index != -1) { String name = tabs.getTitleAt(index); return new JTabbedPaneLocation(name); } return new JTabbedPaneLocation(p); } }); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTableHeaderLocation.java
package abbot.tester; import java.awt.*; import javax.swing.table.JTableHeader; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; /** Provides encapsulation of the location of a col on a JTableHeader (a coordinate, * item index or value). */ public class JTableHeaderLocation extends ComponentLocation { private String value = null; private int col = -1; public JTableHeaderLocation() { } public JTableHeaderLocation(String value) { this.value = value; } public JTableHeaderLocation(int col) { if (col < 0) { String msg = Strings.get("tester.JTableHeader.invalid_index", new Object[] { new Integer(col) }); throw new LocationUnavailableException(msg); } this.col = col; } public JTableHeaderLocation(Point where) { super(where); } protected String badFormat(String encoded) { return Strings.get("location.tableheader.bad_format", new Object[] { encoded }); } /** Convert the given index into a coordinate. */ protected Point indexToPoint(JTableHeader header, int index) { if (index < 0 || index >= header.getColumnModel().getColumnCount()) { String msg = Strings.get("tester.JTableHeader.invalid_index", new Object[] { new Integer(index) }); throw new LocationUnavailableException(msg); } Rectangle rect = header.getHeaderRect(index); return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } /** Find the first String match in the columns and return the index. */ private int valueToIndex(JTableHeader header, String value) { int size = header.getColumnModel().getColumnCount(); for (int i=0;i < size;i++) { String str = header.getTable().getModel().getColumnName(i); if (ExtendedComparator.stringsMatch(value, str)) { return i; } } return -1; } public int getIndex(JTableHeader header) { if (value != null) return valueToIndex(header, value); if (col != -1) { return col; } return header.columnAtPoint(super.getPoint(header)); } /** Return a concrete point for the abstract location. */ public Point getPoint(Component c) { JTableHeader header = (JTableHeader)c; if (value != null || col != -1) return indexToPoint(header, getIndex(header)); return super.getPoint(header); } public Rectangle getBounds(Component c) { JTableHeader header = (JTableHeader)c; int index = getIndex(header); if (index == -1) { String msg = Strings.get("tester.JTableHeader.invalid_index", new Object[] { new Integer(index) }); throw new LocationUnavailableException(msg); } return header.getHeaderRect(index); } public boolean equals(Object o) { if (o instanceof JTableHeaderLocation) { JTableHeaderLocation loc = (JTableHeaderLocation)o; if (value != null) return value.equals(loc.value); if (col != -1) return col == loc.col; } return super.equals(o); } public String toString() { if (value != null) return encodeValue(value); if (col != -1) return encodeIndex(col); return super.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (isValue(encoded)) { value = parseValue(encoded); return this; } else if (isIndex(encoded)) { col = parseIndex(encoded); return this; } return super.parse(encoded); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTableHeaderTester.java
package abbot.tester; import java.awt.Component; import java.awt.Point; import javax.swing.table.JTableHeader; /** Provide table header location support, mostly. */ public class JTableHeaderTester extends JComponentTester { /** Parse the String representation of a JTableHeaderLocation into the actual JTableHeaderLocation object. */ public ComponentLocation parseLocation(String encoded) { return new JTableHeaderLocation().parse(encoded); } /** Return (in order of preference) the location corresponding to column name (value), column index, or coordinate. */ public ComponentLocation getLocation(Component c, Point p) { JTableHeader header = (JTableHeader)c; int col = header.columnAtPoint(p); if (col != -1) { String value = header.getTable().getModel().getColumnName(col); if (value != null) { return new JTableHeaderLocation(value); } return new JTableHeaderLocation(col); } return new JTableHeaderLocation(p); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTableLocation.java
package abbot.tester; import java.awt.*; import java.util.StringTokenizer; import javax.swing.JTable; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; /** Provides encapsulation of a location on a JTable (notably a row). Use the JTableLocation#JTableLocation(Point) ctor to indicate a specific coordinate. */ public class JTableLocation extends ComponentLocation { public static class Cell { public int row; public int col; public Cell(int row, int col) { this.row = row; this.col = col; } public boolean equals(Object o) { return (o instanceof Cell) && ((Cell)o).row == row && ((Cell)o).col == col; } public String toString() { return "[" + row + "," + col + "]"; } } protected String value = null; protected Cell cell = null; public JTableLocation() { } public JTableLocation(String value) { this.value = value; } public JTableLocation(int row, int col) { if (row < 0 || col < 0) { String msg = Strings.get("tester.JTable.invalid_cell", new Object[] { new Integer(row), new Integer(col) }); throw new LocationUnavailableException(msg); } cell = new Cell(row, col); } public JTableLocation(Point p) { super(p); } protected String badFormat(String encoded) { return Strings.get("location.table.bad_format", new Object[] { encoded }); } /** Convert the given row, col into a coordinate pair. */ protected Point cellToPoint(JTable table, int row, int col) { if (row < 0 || row >= table.getRowCount() || col < 0 || col >= table.getColumnCount()) { String msg = Strings.get("tester.JTable.invalid_cell", new Object[] { new Integer(row), new Integer(col) }); throw new LocationUnavailableException(msg); } Rectangle rect = getCellBounds(table, row, col); return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } protected Rectangle getCellBounds(JTable table, int row, int col) { return table.getCellRect(row, col, false); } /** Return the row, col of the first object matching the given String. */ private Cell valueToCell(JTable table, String value) { for (int row=0;row < table.getRowCount();row++) { for (int col=0;col < table.getColumnCount();col++) { String str = JTableTester.valueToString(table, row, col); if (ExtendedComparator.stringsMatch(value, str)) { return new JTableLocation.Cell(row, col); } } } String msg = Strings.get("tester.JTable.invalid_value", new Object[] { value }); throw new LocationUnavailableException(msg); } public Point getPoint(Component c) { JTable table = (JTable)c; if (value != null) { Cell tmp = valueToCell(table, value); return cellToPoint(table, tmp.row, tmp.col); } if (cell != null) { return cellToPoint(table, cell.row, cell.col); } return super.getPoint(table); } public Cell getCell(JTable table) { if (value != null) return valueToCell(table, value); if (cell != null) return new Cell(cell.row, cell.col); Point where = super.getPoint(table); return new Cell(table.rowAtPoint(where), table.columnAtPoint(where)); } public Rectangle getBounds(Component c) { JTable table = (JTable)c; Cell cell = getCell(table); if (cell == null) { String msg = Strings.get("tester.JTable.invalid_cell", new Object[] { new Integer(cell.row), new Integer(cell.col), }); throw new LocationUnavailableException(msg); } return getCellBounds(table, cell.row, cell.col); } public boolean equals(Object o) { if (o instanceof JTableLocation) { JTableLocation loc = (JTableLocation)o; if (value != null) return value.equals(loc.value); if (cell != null) return cell.equals(loc.cell); } return super.equals(o); } public String toString() { if (value != null) return encodeValue(value); if (cell != null) return cell.toString(); return super.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (isValue(encoded)) { value = parseValue(encoded); return this; } else if (isIndex(encoded)) { String num = encoded.substring(1, encoded.length()-1).trim(); StringTokenizer st = new StringTokenizer(num, ","); try { int r = Integer.parseInt(st.nextToken().trim()); int c = Integer.parseInt(st.nextToken().trim()); cell = new Cell(r, c); return this; } catch(NumberFormatException e) { throw new IllegalArgumentException(badFormat(encoded)); } } return super.parse(encoded); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTableTester.java
package abbot.tester; import abbot.WaitTimedOutException; import abbot.i18n.Strings; import java.awt.*; import javax.swing.JTable; import abbot.script.ArgumentParser; import abbot.util.Condition; import java.util.concurrent.Callable; /** Provide user actions on a JTable. The JTable substructure is a "Cell", and JTableLocation provides different identifiers for a cell. <ul> <li>Select a cell by row, column index <li>Select a cell by value (its string representation) </ul> @see abbot.tester.JTableLocation */ // TODO: multi-select public class JTableTester extends JComponentTester { /** Convert the value in the list at the given index into a reasonable string representation, or null if one can not be obtained. */ public static String valueToString(final JTable table, final int row, final int col) { // Ensure this work is done on the EDT, TODO move this // code up to Robot if we are sure we need to reuse it // return callAndWait(table,new Callable<String>() { public String call() { Object value = table.getValueAt(row, col); Component cr = table.getCellRenderer(row, col). getTableCellRendererComponent(table, value, false, false, row, col); String string = convertRendererToString(cr); return string; } }); } /** Select the given cell, if not already. */ public void actionSelectCell(Component c, final JTableLocation loc) { actionSelectCell(c,loc,componentDelay); } /** Select the given cell, if not already. */ public void actionSelectCell(Component c, final JTableLocation loc, int timeout) { final JTable table = (JTable)c; final JTableLocation.Cell found[] = new JTableLocation.Cell[1]; try { wait(new Robot.ConditionEDTDecorator(table, new Condition() { public boolean test() { try{ found[0] = loc.getCell(table); return found[0]!=null; } catch (LocationUnavailableException lue) { return false; } } public String toString() { return Strings.get("tester.Component.show_wait", new Object[] { loc.toString() }); } }), timeout); } catch(WaitTimedOutException e) { throw new LocationUnavailableException(e.getMessage()); } // If we have found something select it // JTableLocation.Cell cell = found[0]; if (table.isRowSelected(cell.row) && table.isColumnSelected(cell.col) && table.getSelectedRowCount() == 1) { return; } actionClick(c, loc); } /** * @param c The table to test * @param loc The location to assert exists */ public boolean assertCellExists(Component c, final JTableLocation loc) { return assertCellExists(c, loc, componentDelay); } /** * @param c The table to test * @param loc The location to assert * @param timeout The timeout to use, tends to be low in negative cases */ public boolean assertCellExists(Component c, final JTableLocation loc, int timeout) { final JTable table = (JTable)c; final JTableLocation.Cell found[] = new JTableLocation.Cell[1]; try { wait(new Robot.ConditionEDTDecorator(table, new Condition() { public boolean test() { try{ found[0] = loc.getCell(table); return found[0]!=null; } catch (LocationUnavailableException lue) { return false; } } public String toString() { return Strings.get("tester.Component.show_wait", new Object[] { loc.toString() }); } }), timeout); return true; } catch(WaitTimedOutException e) { return false; } } /** Select the given cell, if not already. Equivalent to actionSelectCell(c, new JTableLocation(row, col)). */ public void actionSelectCell(Component c, int row, int col) { actionSelectCell(c, new JTableLocation(row, col)); } /** Parse the String representation of a JTableLocation into the actual JTableLocation object. */ public ComponentLocation parseLocation(String encoded) { return new JTableLocation().parse(encoded); } /** Return (in order of preference) the location corresponding to value, * cell, or coordinate. */ public ComponentLocation getLocation(Component c, Point p) { JTable table = (JTable)c; int row = table.rowAtPoint(p); int col = table.columnAtPoint(p); if (row != -1 && col != -1) { String value = valueToString(table, row, col); if (value != null) { return new JTableLocation(value); } return new JTableLocation(row, col); } return new JTableLocation(p); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTextComponentTester.java
package abbot.tester; import java.awt.*; import javax.swing.*; import javax.swing.text.*; import abbot.Log; import abbot.Platform; import abbot.i18n.Strings; import abbot.tester.Robot.ConditionEDTDecorator; import abbot.util.Condition; import java.util.concurrent.Callable; import javax.swing.text.DefaultEditorKit; /** Provides actions and assertions {@link JTextComponent}-based * components. */ public class JTextComponentTester extends JComponentTester { /** * @return The text contained in this component */ protected String getTextForComponent(final JTextComponent component) { return callAndWait(component,new Callable<String>() { public String call() { Document doc = component.getDocument(); try { return doc.getText(0, doc.getLength()); } catch (BadLocationException e) { e.printStackTrace(); return ""; } } }); } /** * Type the given text into the given component, replacing any existing * text already there. If the empty string or <code>null</code> is given, * simply removes all existing text. */ public void actionEnterText(Component c, String text) { scrollToVisible(c, 0); actionActionMap(c, DefaultEditorKit.selectAllAction); if (text == null || "".equals(text)) { if (!"".equals(getTextForComponent((JTextComponent)c))) { actionActionMap(c, DefaultEditorKit.deletePrevCharAction); } } else { actionKeyString(c, text); } } /** Click at the given index position. */ public void actionClick(Component tc, int index) { Point where = scrollToVisible(tc, index); actionClick(tc, where.x, where.y); } /** Click at the middle index of the first instance of this text, useful for selecting hyperlinks */ public void actionClick(Component comp, String textToClick) { final JTextComponent tc = (JTextComponent)comp; // Get the text content and try to work out the offset // String componentText = getTextForComponent(tc); int index = componentText.indexOf(textToClick); // If we cannot find the text then fail // if (index==-1) { String msg = Strings.get("tester.JTextComponent.click_text_failed", new Object[] { textToClick }); throw new ActionFailedException(msg); } // Now try to click in the middle of this text // actionClick(tc, index + textToClick.length()/2); } public void actionSetCaretPosition(Component tc, int index) { actionClick(tc, index); } /** Move the pointer to the given index location. Takes care of * auto-scrolling through text. */ // TODO move this to a JTextComponentLocation and rely on existing // mechanisms to do the scrolling. protected Point scrollToVisible(Component c, final int index) { final JTextComponent tc = (JTextComponent)c; try { final Callable<Rectangle> indexToRectangle = new Callable<Rectangle>() { @Override public Rectangle call() throws BadLocationException { Rectangle rect = tc.modelToView(index); return rect; } }; final Callable<Rectangle> visibleRect = new Callable<Rectangle>() { @Override public Rectangle call() throws BadLocationException { return tc.getVisibleRect(); } }; // Wait for the component to contain the index in question // Robot.wait(new ConditionEDTDecorator(c,new Condition() { @Override public boolean test() { try { Rectangle rect = indexToRectangle.call(); return rect!=null; } catch (Exception e) { return false; } } })); // final Rectangle visible = callAndWait(c, visibleRect); Rectangle rect = callAndWait(c, indexToRectangle); Log.debug("visible=" + visible + ", index=" + index + " is at " + rect); if (rect == null) { String msg = Strings.get("tester.zero_size"); throw new ActionFailedException(msg); } // Autoscroll on JTextComponent is a bit flakey if (!visible.contains(rect.x, rect.y)) { scrollRectToVisible(tc, rect); Rectangle newVisible = callAndWait(c,visibleRect); rect = callAndWait(c,indexToRectangle); Log.debug("visible=" + newVisible + " caret=" + rect); if (!newVisible.contains(rect.x, rect.y)) { String msg = Strings.get("tester.JComponent.not_visible", new Object[] { new Integer(rect.x), new Integer(rect.y), tc, }); throw new ActionFailedException(msg); } } return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } // No longer thrown on this event queue // catch(BadLocationException ble) { // String msg = Strings.get("tester.JTextComponent.bad_location", // new Object[] { // ble.getMessage(), // new Integer(index), // tc.getText() // }); // throw new ActionFailedException(msg); // } finally { } } /** Account for differences in scrolling {@link javax.swing.JTextField}. @see JComponentTester#scrollRectToVisible @see JComponent#scrollRectToVisible */ protected void scrollRectToVisible(JComponent c, Rectangle rect) { super.scrollRectToVisible(c, rect); // Taken from JComponent if (!isVisible(c, rect) && c instanceof JTextField) { int dx = c.getX(); int dy = c.getY(); Container parent; for (parent = c.getParent(); !(parent == null) && !(parent instanceof JComponent) && !(parent instanceof CellRendererPane); parent = parent.getParent()) { Rectangle bounds = parent.getBounds(); dx += bounds.x; dy += bounds.y; } if (!(parent == null) && !(parent instanceof CellRendererPane)) { rect.x += dx; rect.y += dy; super.scrollRectToVisible((JComponent)parent, rect); rect.x -= dx; rect.y -= dy; } } } /** Equivalent to JTextComponent.setCaretPosition(int), but operates * through the UI. */ protected void startSelection(Component comp, int index) { final JTextComponent tc = (JTextComponent)comp; // Avoid automatic drag/drop if the selection start is already // part of a selection (OSX has setDragEnabled true by default). if (tc.getSelectionStart() != tc.getSelectionEnd()) { invokeAndWait(new Runnable() { public void run() { tc.setCaretPosition(0); tc.moveCaretPosition(0); } }); } Point where = scrollToVisible(comp, index); mousePress(comp, where.x, where.y); } /** Equivalent to JTextComponent.moveCaretPosition(int), but operates * through the UI. */ protected void endSelection(Component comp, int index) { final JTextComponent tc = (JTextComponent)comp; // Depending on whether we are performing a normal // or revese select we need to nudge the co-ordinate slightly final int caretPos = callAndWait(tc, new Callable<Integer>(){ @Override public Integer call() { return tc.getCaretPosition(); } }); int nudge = 0; if (index < caretPos) { nudge = 0; } else { nudge = -1; } Point where = scrollToVisible(comp, index); // Get the current value based on the caret poss // final Callable<Point> mousePosition = new Callable<Point>() { @Override public Point call() throws BadLocationException { Point rect = tc.getMousePosition(); return rect; } }; // Remove temporarily as this code breaks a few other cases // will fix on next commit // Point mousePos = Robot.callAndWait(tc, mousePosition); // if (mousePos!=null) // { // // In some cases the text will scroll underneath the current component // // so the actual distance dragged is going to be very small if not zero // // so we are going to need to inject some minor moves, just enough // // to trigger the drag on the relavent platform. // // int distance = (int)Math.sqrt( // Math.pow((where.x - mousePos.x), 2) + // Math.pow((where.y - mousePos.y), 2)); // // if (Math.abs(distance) < AWTConstants.DRAG_THRESHOLD) { // mouseMove(comp, where.x - AWTConstants.DRAG_THRESHOLD, where.y); // } // } // mouseMove(comp, where.x, where.y + nudge); if (Platform.isOSX()) delay(75); mouseRelease(); } /** Start a selection at the given index. */ public void actionStartSelection(Component comp, int index) { startSelection(comp, index); waitForIdle(); } /** Terminate a selection on the given index. */ public void actionEndSelection(Component comp, int index) { endSelection(comp, index); waitForIdle(); } /** Select the given text range. @deprecated Use actionSelectText instead. */ public void actionSelect(Component comp, int start, int end) { actionSelectText(comp, start, end); } /** Select the given text range. */ public void actionSelectText(Component comp, int start, int end) { // An idle wait is sometimes required, otherwise the mouse press is // never registered (w32, 1.4) actionStartSelection(comp, start); actionEndSelection(comp, end); // Verify the selection was properly made JTextComponent tc = (JTextComponent)comp; if (!(tc.getSelectionStart() == Math.min(start, end) && tc.getSelectionEnd() == Math.max(start, end))) { String msg = Strings.get("tester.JTextComponent.selection_failed", new Object[] { new Integer(start), new Integer(end), new Integer(tc.getSelectionStart()), new Integer(tc.getSelectionEnd()), }); throw new ActionFailedException(msg); } // Prevent spurious double click events by ensureing next event is the right distance apart delay(AWTConstants.MULTI_CLICK_INTERVAL); } /** Select the given text in the document. */ public void actionSelectText(Component comp, String textToSelect) { final JTextComponent tc = (JTextComponent)comp; // Get the text content and try to work out the offset // String componentText = getTextForComponent(tc); int index = componentText.indexOf(textToSelect); // If we cannot find the text then fail // if (index==-1) { String msg = Strings.get("tester.JTextComponent.selection_text_failed", new Object[] { textToSelect }); throw new ActionFailedException(msg); } // Now try to select that text // actionSelectText(comp, index, index+textToSelect.length()); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTextFieldTester.java
package abbot.tester; import java.awt.*; import javax.swing.*; /** Provides actions and assertions {@link JTextField}-based * components. */ public class JTextFieldTester extends JTextComponentTester { /** * Enter and commit the given text. */ public void actionCommitText(Component c, String text) { actionEnterText(c, text); actionCommit(c); } /** Cause the text field's notify action to be triggered. */ public void actionCommit(Component c) { actionActionMap(c, JTextField.notifyAction); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JToolBarTester.java
package abbot.tester; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Frame; import java.awt.Insets; import java.awt.Point; import java.awt.Window; import java.lang.reflect.Field; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.plaf.ToolBarUI; import javax.swing.plaf.basic.BasicToolBarUI; import abbot.Log; /** * @author [email protected] */ public class JToolBarTester extends JComponentTester { /** @return whether the bar is currently floating. */ public boolean isFloating(JToolBar bar) { ToolBarUI ui = bar.getUI(); if (ui instanceof BasicToolBarUI) return ((BasicToolBarUI)ui).isFloating(); // Have to guess; probably ought to check for sibling components Window w = SwingUtilities.getWindowAncestor(bar); return !(w instanceof Frame) && bar.getParent().getComponentCount() == 1; } /** Drag the tool bar to the given location, causing it to float. * @throws ActionFailedException if the toolbar is not floatable */ public void actionFloat(Component c, int x, int y) { JToolBar bar = (JToolBar)c; if (!bar.isFloatable()) { throw new ActionFailedException("The JToolBar is not floatable"); } if (isFloating(bar)) { throw new ActionFailedException("The JToolBar is already floating"); } Window w = SwingUtilities.getWindowAncestor(c); // NOTE: should x, y be the window coordinates or where the // cursor moves when the jtoolbar is dropped? JToolBarLocation loc = new JToolBarLocation(); actionDrag(c, loc); actionDrop(w, x - w.getX(), y - w.getY()); if (!isFloating(bar)) throw new ActionFailedException("Bar not floated"); } /** Make the given {@link JToolBar} float. */ public void actionFloat(Component c) { Window w = SwingUtilities.getWindowAncestor(c); Point where = w.getLocation(); actionFloat(c, where.x, where.y); } /** Drop the {@link JToolBar} to the requested constraint position, * which must be one of the constants {@link BorderLayout#NORTH NORTH}, * {@link BorderLayout#EAST EAST}, {@link BorderLayout#SOUTH SOUTH}, * or {@link BorderLayout#WEST WEST}. */ public void actionUnfloat(Component c, String constraint) { if (!BorderLayout.NORTH.equals(constraint) && !BorderLayout.EAST.equals(constraint) && !BorderLayout.SOUTH.equals(constraint) && !BorderLayout.WEST.equals(constraint)) { throw new IllegalArgumentException("Invalid drop location"); } JToolBar bar = (JToolBar)c; Container dock = null; Class cls = bar.getUI().getClass(); // try to fly less blind if (bar.getUI() instanceof BasicToolBarUI) { cls = BasicToolBarUI.class; } try { Field f = cls.getDeclaredField("dockingSource"); f.setAccessible(true); dock = (Container)f.get(bar.getUI()); } catch(Exception e) { Log.warn(e); } if (dock == null) { throw new ActionFailedException("Can't determine dock"); } actionDrag(bar, new JToolBarLocation()); actionDrop(dock, new DockLocation(bar, constraint)); if (isFloating(bar)) throw new ActionFailedException("Failed to dock the tool bar (" + constraint + ")"); } /** The only interesting location is where you grab the JToolBar. */ private class JToolBarLocation extends ComponentLocation { public Point getPoint(Component c) { JToolBar bar = (JToolBar)c; Insets insets = bar.getInsets(); int x, y; if (Math.max(Math.max(Math.max(insets.left, insets.top), insets.right), insets.bottom) == insets.left){ x = insets.left/2; y = c.getHeight()/2; } else if (Math.max(Math.max(insets.top, insets.right), insets.bottom) == insets.top) { x = c.getWidth()/2; y = insets.top/2; } else if (Math.max(insets.right, insets.bottom) == insets.right) { x = c.getWidth() - insets.right/2; y = c.getHeight()/2; } else { x = c.getWidth()/2; y = c.getHeight() - insets.bottom/2; } return new Point(x, y); } } private class DockLocation extends ComponentLocation { private String constraint; private JToolBar bar; public DockLocation(JToolBar bar, String constraint) { if (!BorderLayout.NORTH.equals(constraint) && !BorderLayout.EAST.equals(constraint) && !BorderLayout.SOUTH.equals(constraint) && !BorderLayout.WEST.equals(constraint)) { throw new IllegalArgumentException("Invalid dock location"); } this.constraint = constraint; this.bar = bar; } public Point getPoint(Component c) { if (!(c instanceof Container)) { throw new LocationUnavailableException("Dock is not a container"); } Container dock = (Container)c; int x, y; Insets insets = dock.getInsets(); // BasicToolBarUI prioritizes location N/E/W/S by proximity // to the respective border. Close to top border is N, even // if close to the left or right border. int offset = bar.getOrientation() == SwingConstants.HORIZONTAL ? bar.getHeight() : bar.getWidth(); if (BorderLayout.NORTH.equals(constraint)) { x = dock.getWidth()/2; y = insets.top; } else if (BorderLayout.EAST.equals(constraint)) { x = dock.getWidth() - insets.right - 1; y = dock.getHeight()/2; // Make sure we don't get mistaken for NORTH if (y < insets.top + offset) { y = insets.top + offset; } } else if (BorderLayout.WEST.equals(constraint)) { x = insets.left; y = dock.getHeight()/2; // Make sure we don't get mistaken for NORTH if (y < insets.top + offset) { y = insets.top + offset; } } else { x = dock.getWidth()/2; y = dock.getHeight() - insets.bottom - 1; // Make sure we don't get mistaken for EAST or WEST if (x < insets.left + offset) { x = insets.left + offset; } else if (x > dock.getWidth() - insets.right - offset - 1) { x = dock.getWidth() - insets.right - offset - 1; } } return new Point(x, y); } } /** Close a floating toolbar, making it go back to its * original container in its last known location. * @param c the JToolBar instance */ public void actionUnfloat(Component c) { Window w = SwingUtilities.getWindowAncestor(c); close(w); waitForIdle(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTreeLocation.java
package abbot.tester; import java.awt.*; import java.util.Arrays; import javax.swing.JTree; import javax.swing.tree.TreePath; import javax.swing.tree.TreeModel; import abbot.Log; import abbot.i18n.Strings; import abbot.script.ArgumentParser; import abbot.script.parsers.TreePathParser; import abbot.util.ExtendedComparator; import java.util.concurrent.Callable; /** Provides encapsulation of a visible location on a {@link JTree}. * A row index or a {@link String}ified {@link TreePath} (i.e. each * {@link TreePath} component is a {@link String}) or a {@link TreePath} * of {@link Object} may be used to indicate the location. Note that if a * {@link TreePath} is used, the entire path leading up to the designated * node must be viewable at the time the location is used. * @see #findMatchingPath for a description of the matching algorithm. */ // TODO: add flag for "in icon" vs in hit region public class JTreeLocation extends ComponentLocation { private int row = -1; /** TreePath of Strings. */ private TreePath treePath; private boolean inExpansion; /** Create an uninitialized JTreeLocation. If queried for its * {@link Point} will return the default location. */ public JTreeLocation() { } /** Create a JTreeLocation corresponding to the given row, by index. */ public JTreeLocation(int row) { this(row, false); } /** Create a JTreeLocation corresponding to the given row, by index. */ public JTreeLocation(int row, boolean inExpansion) { if (row < 0) { String msg = Strings.get("tester.JTree.row_not_visible", new Object[] { new Integer(row) }); throw new LocationUnavailableException(msg); } this.row = row; this.inExpansion = inExpansion; } /** Create a JTreeLocation corresponding to the given TreePath. The * TreePath must consist of usable String representations that can be * used in later comparisons. The default * &ltclassname&gt;@&lt;hashcode&gt; returned by * {@link Object#toString()} is not usable; if that is all that is * available, refer to the row number instead. */ public JTreeLocation(TreePath treePath) { this(treePath, false); } /** Create a JTreeLocation corresponding to the given TreePath. The * TreePath must consist of usable String representations that can be * used in later comparisons. The default * &lt;classname&gt;@&lt;hashcode&gt; format returned by * {@link Object#toString()} is not usable; if that is all that is * available, refer to the row number instead. */ public JTreeLocation(TreePath treePath, boolean inExpansion) { this.treePath = treePath; this.inExpansion = inExpansion; } public JTreeLocation(Point p) { super(p); } public void setInExpansion(boolean in) { inExpansion = in; } public boolean isInExpansion() { return inExpansion; } /** Convert the given row to an x, y coordinate. @throws LocationUnavailableException if the row is not visible. */ protected Point rowToPoint(final JTree tree, final int row) { TreePath path = Robot.callAndWait(tree, new Callable<TreePath>() { @Override public TreePath call() { return tree.getPathForRow(row); } }); if (path == null) { String msg = Strings.get("tester.JTree.row_not_visible", new Object[] { new Integer(row) }); throw new LocationUnavailableException(msg); } return pathToPoint(tree, path); } /** Convert the given path to an x, y coordinate. @throws LocationUnavailableException if any part of the path is hidden. */ protected Point pathToPoint(final JTree tree, final TreePath path) { final TreePath matchingPath = findMatchingPath(tree, path); Rectangle rect = Robot.callAndWait(tree, new Callable<Rectangle>() { @Override public Rectangle call() { return tree.getPathBounds(matchingPath); } }); if (rect == null) { String msg = Strings.get("tester.JTree.path_not_visible", new Object[] { matchingPath }); throw new LocationUnavailableException(msg); } if (inExpansion) // FIXME this is only an approximation; should probably get the // location from the UI somehow, but it's not available in the API // FIXME this will probably be bogus if the tree rows are really // tall return new Point(rect.x - rect.height/2, rect.y + rect.height/2); return new Point(rect.x + rect.width/2, rect.y + rect.height/2); } /** Return the path represented by this JTree location. @return null if the path can not be found. */ TreePath getPath(final JTree tree) { if (treePath != null) { try { return findMatchingPath(tree, treePath); } catch(LocationUnavailableException e) { return treePath; } } if (row != -1) { return Robot.callAndWait(tree, new Callable<TreePath>() { @Override public TreePath call() { return tree.getPathForRow(row); } }); } final Point where = super.getPoint(tree); return Robot.callAndWait(tree, new Callable<TreePath>() { @Override public TreePath call() { return tree.getPathForLocation(where.x, where.y); } }); } /** Return the row represented by this JTree location. @return -1 if the row is not found. */ int getRow(final JTree tree) { if (treePath != null) { return Robot.callAndWait(tree, new Callable<Integer>() { @Override public Integer call() { return tree.getRowForPath(getPath(tree)); } }); } else if (row != -1) { return row; } final Point where = super.getPoint(tree); return Robot.callAndWait(tree, new Callable<Integer>() { @Override public Integer call() { return tree.getRowForLocation(where.x, where.y); } }); } /** Return a concrete point for the abstract location. */ public Point getPoint(Component c) { JTree tree = (JTree)c; if (treePath != null) { // convert the string-based path to a real path return pathToPoint(tree, treePath); } if (row != -1) { return rowToPoint(tree, row); } return super.getPoint(c); } public Rectangle getBounds(Component c) { final JTree tree = (JTree)c; final int row = getRow(tree); if (row == -1) { Point where = getPoint(c); return new Rectangle(where.x, where.y, 1, 1); } Rectangle rect = Robot.callAndWait(tree, new Callable<Rectangle>() { @Override public Rectangle call() { return tree.getRowBounds(row); } }); if (rect == null) { String msg = Strings.get("tester.JTree.row_not_visible", new Object[] { new Integer(row) }); throw new LocationUnavailableException(msg); } if (inExpansion) { rect.x -= rect.height; rect.width = rect.height; } return rect; } public boolean equals(Object o) { if (o instanceof JTreeLocation) { JTreeLocation loc = (JTreeLocation)o; if (loc.inExpansion != inExpansion) return false; if (treePath != null) { if (treePath.getPathCount() != loc.treePath.getPathCount()) return false; for (int i=0;i < treePath.getPathCount();i++) { if (treePath.getPathComponent(i) == null) { if (loc.treePath.getPathComponent(i) != null) return false; } else if (!treePath.getPathComponent(i). equals(loc.treePath.getPathComponent(i))) { return false; } } return true; } if (row != -1) return row == loc.row; } return super.equals(o); } public String toString() { String s = inExpansion ? "+" : ""; if (treePath != null) { return s + encodeValue(toString(treePath)); } if (row != -1) return s + encodeIndex(row); return super.toString(); } /** * A modified version of toString on path that escapes comma * in the subpaths of the parameters */ private static String toString(TreePath path) { StringBuffer tempSpot = new StringBuffer("["); for (int counter = 0, maxCounter = path.getPathCount(); counter < maxCounter; counter++) { if (counter > 0) tempSpot.append(", "); Object next = path.getPathComponent(counter); // Escape as required // if (next!=null) { String part = next.toString(); next = ArgumentParser.escapeCommas(part); } tempSpot.append(next); } tempSpot.append("]"); return tempSpot.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (encoded.startsWith("+")) { inExpansion = true; encoded = encoded.substring(1); } if (isValue(encoded)) { String path = parseValue(encoded); treePath = (TreePath)new TreePathParser().parse(path); return this; } else if (isIndex(encoded)) { row = parseIndex(encoded); return this; } return super.parse(encoded); } protected String badFormat(String encoded) { return Strings.get("location.tree.bad_format", new Object[] { encoded }); } /** Return whether the given Object matches the final element of the given * TreePath. {@link Object#equals} is attempted first (a * <code>null</code> pattern matches everything), followed by a comparison * of the pattern as a {@link String} (via {@link Object#toString}). The * pattern may be a regular expression bounded by forward slashes. */ private static boolean matchesLastComponent(JTree tree, Object pattern, TreePath path) { // For matching the root node, or for other nodes you don't care about // whether they match if (pattern == null) return true; if (pattern.equals(path.getLastPathComponent())) return true; // Try a string comparison String objString = JTreeTester.valueToString(tree, path); // Derrive a string for the pattern, this might need to be in context of // the path // String patternString; if (pattern instanceof String){ patternString = (String)pattern; } else if (path.getParentPath() != null) { TreePath parent = path.getParentPath(); patternString = JTreeTester.valueToString(tree, parent.pathByAddingChild(pattern)); } else { patternString = pattern.toString(); } return ExtendedComparator.stringsMatch(patternString, objString); } /** Given a {@link TreePath} (which may be composed of objects, string * representations of objects, or regular expressions), return the * equivalent {@link TreePath} for the given {@link JTree} constructed * from objects from the tree's model.<p> * For each element, {@link Object#equals} is attempted first (a * <code>null</code> pattern matches everything), followed by a comparison * of the pattern as a {@link String} (via {@link Object#toString}). The * pattern may be a regular expression bounded by forward slashes. * @throws LocationUnavailableException if no matching path is found. */ public static TreePath findMatchingPath(final JTree tree, TreePath path) { Log.debug("Find path matching " + path); Object[] input = path.getPath(); TreeModel model = tree.getModel(); Object root = model.getRoot(); // If the root is not visible and it doesn't match the first path // element, start the path with the invisible root. if (!tree.isRootVisible() && !matchesLastComponent(tree, input[0], new TreePath(root))) { Object[] tmp = new Object[input.length+1]; System.arraycopy(input, 0, tmp, 1, input.length); tmp[0] = null; // null always matches root input = tmp; } TreePath realPath = findMatchingPath(tree, new TreePath(root), input); if (realPath != null) return realPath; String msg = Strings.get("tester.JTree.path_not_found", new Object[] { path, JTreeTester.dumpTree(tree) }); throw new LocationUnavailableException(msg); } /** Build up the given tree path with Objects from the TreeModel which * match the given array of Objects. */ private static TreePath findMatchingPath(JTree tree, TreePath realPath, Object[] input) { // The given array is a tree path of objects which may or may not be // node objects. Convert them to existing tree objects if necessary. // Return null if any of them are not found. Log.debug("Comparing " + realPath + " with " + input[0] + " from " + java.util.Arrays.asList(input)); final TreeModel model = tree.getModel(); if (!matchesLastComponent(tree, input[0], realPath)) { Log.debug("no root match"); } else { Log.debug("node matched: " + realPath.getLastPathComponent()); if (input.length == 1) return realPath; Object[] subs = new Object[input.length-1]; System.arraycopy(input, 1, subs, 0, subs.length); final Object obj = realPath.getLastPathComponent(); // Talk to the model on the event queue // Object[] children = Robot.callAndWait(tree, new Callable<Object[]>() { @Override public Object[] call() { int count = model.getChildCount(obj); Object ret[] = new Object[count]; for (int i = 0; i < count; i++) { ret[i] = model.getChild(obj, i); } return ret; } }); Log.debug("Obj " + obj + " (" + obj.getClass() + ") has " + children.length); // Find the right child to match for (int i=0;i < children.length;i++) { Object child = children[i]; Log.debug("checking child " + i + " (" + child + ")"); TreePath newPath = findMatchingPath(tree, realPath.pathByAddingChild(child), subs); if (newPath != null) { return newPath; } } Log.debug("No child path matched"); } return null; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/JTreeTester.java
package abbot.tester; import abbot.Log; import java.awt.*; import java.awt.event.InputEvent; import java.lang.reflect.InvocationTargetException; import javax.accessibility.AccessibleContext; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.tree.*; import javax.swing.plaf.basic.BasicTreeUI; import abbot.WaitTimedOutException; import abbot.script.ArgumentParser; import abbot.util.AWT; import abbot.util.Condition; import abbot.i18n.Strings; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import javax.accessibility.AccessibleText; import javax.swing.JComponent; import javax.swing.event.TreeSelectionListener; /** Provide operations on a JTree component. The JTree substructure is a "row", and JTreeLocation provides different identifiers for a row. <ul> <li>Select an item by row index <li>Select an item by tree path (the string representation of the full path). </ul> @see abbot.tester.JTreeLocation */ // TODO: multi-select // TODO: expand/collapse actions public class JTreeTester extends JComponentTester { /** Returns whether the given point is in one of the JTree's node * expansion controls. */ public static boolean isLocationInExpandControl(JTree tree, int x, int y) { int row = tree.getRowForLocation(x, y); if (row == -1) { row = tree.getClosestRowForLocation(x, y); if (row != -1) { Rectangle rect = tree.getRowBounds(row); if (row == tree.getRowCount()-1) { if (y >= rect.y + rect.height) return false; } // An approximation: use a square area to the left of the row // bounds. TreePath path = tree.getPathForRow(row); if (path == null || tree.getModel(). isLeaf(path.getLastPathComponent())) return false; if (tree.getUI() instanceof BasicTreeUI) { try { java.lang.reflect.Method method = BasicTreeUI.class. getDeclaredMethod("isLocationInExpandControl", new Class[] { TreePath.class, int.class, int.class, }); method.setAccessible(true); Object b = method.invoke(tree.getUI(), new Object[] { path, new Integer(x), new Integer(y), }); return b.equals(Boolean.TRUE); } catch(Exception e) { } } // fall back to a best guess //return x >= rect.x - rect.height && x < rect.x; String msg = "Can't determine location of tree expansion " + "control for " + tree.getUI(); throw new LocationUnavailableException(msg); } } return false; } /** Return a unique {@link String} representation of the final component of * the given {@link TreePath}, or <code>null</code> if one can not be * obtained. Assumes the path is visible. */ public static String valueToString(JTree tree, TreePath path) { return valueToString(tree, path, true); } /** Return the {@link String} representation of the final component of the * given {@link TreePath}, or <code>null</code> if one can not be * obtained. Assumes the path is visible. * Optionally include a unique trailing index. */ private static String valueToStringInternal(final JTree tree, final TreePath path, final boolean includeIndex) { Object value = path.getLastPathComponent(); int row = tree.getRowForPath(path); // The default renderer will rely on JTree.convertValueToText Component cr = tree.getCellRenderer(). getTreeCellRendererComponent(tree, value, false, tree.isExpanded(row), tree.getModel().isLeaf(value), row, false); String string = convertRendererToString(cr); if (string == null) { string = tree.convertValueToText(value, false, tree.isExpanded(row), tree.getModel().isLeaf(value), row, false); if (ArgumentParser.isDefaultToString(string)) string = null; } if (string == null) { String s = ArgumentParser.toString(value); string = s == ArgumentParser.DEFAULT_TOSTRING ? null : s; } if (includeIndex) { // If there are preceding siblings which produce the same // string value, obtain one that is unique by adding an index TreePath parentPath = path.getParentPath(); if (parentPath != null) { Object parent = parentPath.getLastPathComponent(); int idx = tree.getModel().getIndexOfChild(parent, value); int count = 0; for (int i=0;i < idx;i++) { Object child = tree.getModel().getChild(parent, i); TreePath childPath = parentPath.pathByAddingChild(child); String text = valueToString(tree, childPath, false); // string == text deals with double null null case if ((string==text) || (string!=null && string.equals(text))) { ++count; } } // If the string is null then ensure that we at least // traces something out // if (count > 0 || string == null) { if (string!=null) { string += "[" + count + "]"; } else { string = "[" + count + "]"; } } } } return string; } /** * @param tree The tree to dump * @return A textual representaiton of the current tree */ public static String dumpTree(final JTree tree) { String treeDump = Robot.callAndWait(tree, new Callable<String>() { @Override public String call() throws Exception { StringBuilder sb = new StringBuilder(); try { dumpTree(sb, tree, new TreePath(tree.getModel().getRoot()), ""); return sb.toString(); } catch (Exception ex) { return "Problem dumping tree,"+ ex.getMessage() + ", so far:\n " + sb.toString(); } } }); return treeDump; } private static void dumpTree(StringBuilder sb, JTree tree, TreePath path, String prefix) { String currentName = JTreeTester.valueToString(tree, path); sb.append(prefix).append(currentName).append('\n'); Object parent = path.getLastPathComponent(); int count = tree.getModel().getChildCount(parent); for (int i = 0; i < count; i++) { dumpTree(sb, tree, new TreePath(path, tree.getModel().getChild(parent, i)) {}, prefix + "-"); } } /** Return the {@link String} representation of the final component of the * given {@link TreePath}, or <code>null</code> if one can not be * obtained. Assumes the path is visible. * Optionally include a unique trailing index. Ensures operation is performed * on EDT */ private static String valueToString(final JTree tree, final TreePath path, final boolean includeIndex) { // Ensure this work is done on the EDT, TODO move this // code up to Robot if we are sure we need to reuse it // return Robot.callAndWait(tree, new Callable<String>() { public String call() { return valueToStringInternal(tree, path, includeIndex); } }); } /** Return the String representation of the given TreePath, or null if one * can not be obtained. Assumes the path is visible. */ public static TreePath pathToStringPath(JTree tree, TreePath path) { if (path == null) return null; String string = valueToString(tree, path); // Special case for a null value when this is a hidden root element // if (string == null && path.getParentPath() == null && !tree.isRootVisible()) { return path; } // // if (string != null) { // Prepend the parent value, if any if (path.getPathCount() > 1) { TreePath parent = pathToStringPath(tree, path.getParentPath()); if (parent == null) return null; return parent.pathByAddingChild(string); } return new TreePath(string); } return null; } /** * Converts a tree location to a tree path safely by invoking the required * methods on the EDT * @param tree * @param location * @return The converted tree path */ private TreePath convertLocationSafelyToPath(final JTree tree, final JTreeLocation location) { return Robot.callAndWait(tree, new Callable<TreePath>() { public TreePath call() { return location.getPath(tree); } }); } /** Click at the given location. If the location indicates a path, ensure it is visible first. */ public void actionClick(Component c, ComponentLocation loc) { if (loc instanceof JTreeLocation) { TreePath path = convertLocationSafelyToPath((JTree)c, (JTreeLocation)loc); if (path != null) makeVisible(c, path); } super.actionClick(c, loc); } /** Select the given row. If the row is already selected, does nothing. */ public void actionSelectRow(final Component c, final ComponentLocation loc) { final JTree tree = (JTree)c; if (loc instanceof JTreeLocation) { final JTreeLocation jTreeLocation = (JTreeLocation)loc; TreePath path = convertLocationSafelyToPath((JTree)c,jTreeLocation); if (path == null) { String msg = Strings.get("tester.JTree.path_not_found", new Object[] { loc, JTreeTester.dumpTree(tree) }); throw new LocationUnavailableException(msg); } makeVisible(c, path); // Scroll to that location, makes the action click easier as the // code in there for scrolling is more fragiles as it doesn't // have access to the tree path. // // Need to fetch path again as data can be different now that // the tree is properly expanded, also needs to be performed // on the EDT // invokeAndWait(new Runnable() { public void run() { tree.scrollPathToVisible(jTreeLocation.getPath(tree)); } }); } // We had an odd failure case that we could never track down // where for small amounts of time we couldn't access the point // setting breakpoints would disturb the flow so we never got to // the bottom on why it wasn't working. // Instead we are using a wait to repeatidy refetch until we get // the location we need final Point whereF[] = new Point[1]; wait(new ConditionEDTDecorator(tree, new Condition() { public boolean test() { try { whereF[0] = loc.getPoint(c); return whereF[0]!=null; } catch (LocationUnavailableException lue) { return false; } } public String toString() { return Strings.get("tester.JTree.path_not_found", new Object[] { loc, JTreeTester.dumpTree(tree) }); } }), defaultDelay / 4); // Ramp up delay as still getting // intermittent failures final Point where = whereF[0]; // Find out what the target row is // final int targetRow = ((JTreeLocation)loc).getRow(tree); // Check, if it is already selected then we can bail, always best to do this after // we have made sure it is visible etc above. // if (Robot.callAndWait(tree, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return tree.isRowSelected(targetRow); } })) { // We can just return as the row is already selected return; } Rectangle rect = Robot.callAndWait(tree, new Callable<Rectangle>() { public Rectangle call() { int row = tree.getRowForLocation(where.x, where.y); if (tree.getLeadSelectionRow() != row || tree.getSelectionCount() != 1) { // NOTE: the row bounds *do not* include the expansion handle return tree.getRowBounds(row); } else { return null; } } }); if (rect!=null) { // Create a listener so we can monitor the selection class TemporaryTreeSelectionListener implements TreeSelectionListener { volatile boolean matched = false; @Override public void valueChanged(TreeSelectionEvent e) { // If the tree matches, all well and good if (tree.getSelectionModel().isRowSelected(targetRow)) { matched = true; } } }; final TemporaryTreeSelectionListener tsl = new TemporaryTreeSelectionListener(); // Add listener, so we can wait until the tree item is checked // invokeAndWait(tree, new Runnable() { public void run() { tree.getSelectionModel().addTreeSelectionListener(tsl); } }); try { // NOTE: if there's no icon, this may start editing actionClick(tree, rect.x + rect.width/2, rect.y + rect.height/2); // Wait for the row to be selected at some point // final Robot.ConditionEDTDecorator condition = new Robot.ConditionEDTDecorator(c, new Condition() { public boolean test() { return tsl.matched; } public String toString() { return Strings.get("tester.JTree.row_not_selected", new Object[] { loc.toString(), dumpTree(tree), Arrays.toString(tree.getSelectionModel().getSelectionRows()) }); } }); try { wait(condition, componentDelay/4); } catch (WaitTimedOutException wte) { throw wte; } } finally { // Remove listener // invokeAndWait(tree, new Runnable() { public void run() { tree.getSelectionModel().removeTreeSelectionListener(tsl); } }); } } else { throw new ActionFailedException(Strings.get("tester.JTree.row_not_selected_location", new Object[] { loc.toString(), dumpTree(tree), Arrays.toString(tree.getSelectionModel().getSelectionRows()) })); } } /** Select the given row. If the row is already selected, does nothing. Equivalent to actionSelectRow(c, new JTreeLocation(row)). */ public void actionSelectRow(Component tree, int row) { actionSelectRow(tree, new JTreeLocation(row)); } /** Simple click on the given row. */ public void actionClickRow(Component tree, int row) { actionClick(tree, new JTreeLocation(row)); } /** Click with modifiers on the given row. @deprecated Use the ComponentLocation version. */ public void actionClickRow(Component tree, int row, String modifiers) { actionClick(tree, new JTreeLocation(row), AWT.getModifiers(modifiers)); } /** Multiple click on the given row. @deprecated Use the ComponentLocation version. */ public void actionClickRow(Component c, int row, String modifiers, int count) { actionClick(c, new JTreeLocation(row), AWT.getModifiers(modifiers), count); } /** Make the given path visible, if possible, and returns whether any * action was taken. * @throws LocationUnavailableException if no corresponding path can be * found. */ protected boolean makeVisible(Component c, TreePath path) { return makeVisible(c, path, false); } private boolean makeVisible(Component c, final TreePath path, boolean expandWhenFound) { return makeVisible(c, path, componentDelay, expandWhenFound); } private boolean makeVisible(Component c, final TreePath path, final int timeout, boolean expandWhenFound) { final JTree tree = (JTree)c; // Match, make visible, and expand the path one component at a time, // from uppermost ancestor on down, since children may be lazily // loaded/created boolean changed = false; if (path.getPathCount() > 1) { changed = makeVisible(c, path.getParentPath(), timeout, true); if (changed) waitForIdle(); } final TreePath realPath = getRealPath(path, timeout, tree); if (expandWhenFound) { Callable<Boolean> realPathExanded = new Callable<Boolean>() { @Override public Boolean call() { return tree.isExpanded(realPath); } }; if (!Robot.callAndWait(tree, realPathExanded)) { // Use this method instead of a toggle action to avoid // any component visibility requirements invokeAndWait(new Runnable() { public void run() { tree.expandPath(realPath); } }); } // Wait for a child to show up try { wait(new ConditionEDTDecorator(tree, new Condition() { public boolean test() { // It is possible that the path has been updated, in the test // case where we saw this change the lazily loaded nodes // are replaced with the new correct nodes on expand // so we need to get hold of the new version // final TreePath updatedPath = getRealPath(path, timeout, tree); final Object o = updatedPath.getLastPathComponent(); return tree.getModel().getChildCount(o) != 0; } public String toString() { return Strings.get("tester.JTree.path_not_shown", new Object[] { path.toString(), dumpTree(tree) }); } }), timeout); changed = true; } catch(WaitTimedOutException e) { throw new LocationUnavailableException(e.getMessage()); } } return changed; } /** * @param path The string path used by abbot * @param timeout Timeout to use on query * @param tree The tree we are working with * @return The real world path for this particular node */ private TreePath getRealPath(final TreePath path, final int timeout, final JTree tree) { // Wait for the node to exist // final TreePath found[] = new TreePath[1]; try { wait(new ConditionEDTDecorator(tree, new Condition() { public boolean test() { try{ found[0] = JTreeLocation.findMatchingPath(tree, path); return found[0]!=null; } catch (LocationUnavailableException lue) { return false; } } public String toString() { return Strings.get("tester.JTree.path_not_shown", new Object[] { path.toString(), dumpTree(tree) }); } }), timeout); } catch(WaitTimedOutException e) { throw new LocationUnavailableException(e.getMessage()); } // final TreePath realPath = found[0]; return realPath; } /** Ensure all elements of the given path are visible. */ public void actionMakeVisible(Component c, TreePath path) { makeVisible(c, path); } /** Select the given path, expanding parent nodes if necessary. */ public void actionSelectPath(Component c, TreePath path) { actionSelectRow(c, new JTreeLocation(path)); } /** Change the open/closed state of the given row, if possible. @deprecated Use the ComponentLocation version instead. */ public void actionToggleRow(Component c, int row) { actionToggleRow(c, new JTreeLocation(row)); } /** Change the open/closed state of the given row, if possible. */ // NOTE: a reasonable assumption is that the toggle control is just to the // left of the row bounds and is roughly a square the dimensions of the // row height. clicking in the center of that square should work. public void actionToggleRow(Component c, ComponentLocation loc) { final JTree tree = (JTree)c; // Accessing the toggle click count is thread safe; but updating // it can fire a properly listener which is going to be an issue in some cases // hence this little class to update the value as required class SetToggleClickCount implements Runnable { int clickCount; public SetToggleClickCount(int clickCount) { this.clickCount = clickCount; } @Override public void run() { tree.setToggleClickCount(clickCount); } } // It turns out that some trees have double click actions on them // so this doesn't work too well. So we are going to increase the click // count to 1 just for the toggle operation, this should make things more // reliable int originalToggleRowCount = tree.getToggleClickCount(); invokeAndWait(new SetToggleClickCount(1)); try { actionClick(tree, loc, InputEvent.BUTTON1_MASK, tree.getToggleClickCount()); } finally { invokeAndWait(new SetToggleClickCount(originalToggleRowCount)); } // // Alternatively, we can reflect into the UI and do a single click // // on the appropriate expand location, but this is safer. // if (tree.getToggleClickCount() != 0) { // actionClick(tree, loc, InputEvent.BUTTON1_MASK, // tree.getToggleClickCount()); // } // else { // // BasicTreeUI provides this method; punt if we can't find it // if (!(tree.getUI() instanceof BasicTreeUI)) // throw new ActionFailedException("Can't toggle row for " // + tree.getUI()); // try { // final java.lang.reflect.Method method = // BasicTreeUI.class. // getDeclaredMethod("toggleExpandState", // new Class[] { // TreePath.class // }); // method.setAccessible(true); // final Point where = loc.getPoint(tree); // Robot.callAndWait(tree, new Callable<Object>() { // public Object call() throws Exception { // return method.invoke(tree.getUI(), new Object[] { // tree.getPathForLocation(where.x, where.y)}); // } // }); // } // catch(Exception e) { // throw new ActionFailedException(e.toString()); // } // } // Make sure all operations have finsished waitForIdle(); } /** Determine whether a given path exists, expanding ancestor nodes as * necessary to find it. * @return Whether the given path on the given tree exists. */ public boolean assertPathExists(Component tree, TreePath path) { return assertPathExists(tree, path, false); } /** Determine whether a given path exists, expanding ancestor nodes as * necessary to find it. * @param invert Whether it invert the sense of this operation, when inverted * it assumed a timeout of zero. * @return Whether the given path on the given tree exists. */ public boolean assertPathExists(Component tree, TreePath path, boolean invert) { return assertPathExists(tree, path, invert ? 0 : componentDelay, invert); } /** Determine whether a given path exists, expanding ancestor nodes as * necessary to find it. * @param timeout How long to wait for the tree path to become avaliable * @param invert Whether it invert the sense of this operation * @return Whether the given path on the given tree exists. */ public boolean assertPathExists(Component tree, TreePath path, int timeout, boolean invert) { try { makeVisible(tree, path, timeout, false); return !invert; } catch(LocationUnavailableException e) { return invert; } } /** Parse the String representation of a JTreeLocation into the actual JTreeLocation object. */ public ComponentLocation parseLocation(String encoded) { return new JTreeLocation().parse(encoded); } /** Convert the coordinate into a more meaningful location. Namely, use a * path, row, or coordinate. */ public ComponentLocation getLocation(final Component c, final Point p) { return Robot.callAndWait(c, new Callable<JTreeLocation>() { @Override public JTreeLocation call() { JTree tree = (JTree)c; if (tree.getRowCount() == 0) return new JTreeLocation(p); Rectangle rect = tree.getRowBounds(tree.getRowCount()-1); int maxY = rect.y + rect.height; if (p.y > maxY) return new JTreeLocation(p); // TODO: ignore clicks to the left of the expansion control, or maybe // embed them in the location. TreePath path = tree.getClosestPathForLocation(p.x, p.y); TreePath stringPath = pathToStringPath(tree, path); if (stringPath != null) { // if the root is hidden, drop it from the path if (!tree.isRootVisible()) { Object[] objs = stringPath.getPath(); Object[] subs = new Object[objs.length-1]; System.arraycopy(objs, 1, subs, 0, subs.length); stringPath = new TreePath(subs); } return new JTreeLocation(stringPath); } int row = tree.getClosestRowForLocation(p.x, p.y); if (row != -1) { return new JTreeLocation(row); } return new JTreeLocation(p); } }); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/KeyStrokeMap.java
package abbot.tester; import java.lang.reflect.*; import java.awt.event.*; import java.util.*; import java.io.*; import javax.swing.KeyStroke; import abbot.Log; import abbot.Platform; /** Provides read of local-specific mappings for virtual keycode-based KeyStrokes to characters and vice versa. The map format is a properties file with each line containing an entry of the form<br> <code>VKNAME.MOD=VALUE</code><br> The VKNAME is the String suffix of the KeyEvent VK_ keycode. MOD is the integer value of the current modifier mask (assumes only a single modifier has any effect on key output, interesting values are considered to be 0, 1, 2, 8). VALUE is the char value of the KEY_TYPED keyChar corresponding to the VK_ keycode and modifiers, as an integer value. */ public class KeyStrokeMap implements KeyStrokeMapProvider { /** Map of Characters to virtual keycode-based KeyStrokes. */ private static Map keycodes = getKeyStrokeMap(); /** Map of keycode-based KeyStrokes to Characters. */ private static Map chars = getCharacterMap(); /** Return the keycode-based KeyStroke corresponding to the given * character, as best we can guess it, or null if we don't know how to * generate it. */ public static KeyStroke getKeyStroke(char ch) { return (KeyStroke)keycodes.get(new Character(ch)); } /** Given a keycode-based KeyStroke, return the equivalent character. * Defined properly for US keyboards only. Please contribute your own. * @return KeyEvent.VK_UNDEFINED if the result is unknown. */ public static char getChar(KeyStroke ks) { Character ch = (Character)chars.get(ks); if (ch == null) { // Try again, but strip all modifiers but shift int mask = ks.getModifiers() & ~KeyEvent.SHIFT_MASK; ks = KeyStroke.getKeyStroke(ks.getKeyCode(), mask); ch = (Character)chars.get(ks); if (ch == null) return KeyEvent.CHAR_UNDEFINED; } return ch.charValue(); } private static KeyStrokeMapProvider generator = null; /** If available, provide a dedicated class to provide mappings between * keystrokes and generated characters. */ private static KeyStrokeMapProvider getGenerator() { if (generator == null) { try { String gname = System.getProperty("abbot.keystroke_map_generator", "abbot.tester.KeyStrokeMap"); if (gname != null) { generator = (KeyStrokeMapProvider) Class.forName(gname).newInstance(); } } catch(Exception e) { Log.warn(e); } } return generator; } private static Map getCharacterMap() { KeyStrokeMapProvider generator = getGenerator(); Map m = generator != null ? generator.loadCharacterMap() : null; return m != null ? m : generateCharacterMappings(); } /** Generate a map from characters to virtual keycode-based KeyStrokes. */ private static Map generateCharacterMappings() { Log.debug("Generating default character mappings"); Map map = new HashMap(); Iterator iter = keycodes.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); map.put(keycodes.get(key), key); } return map; } private static Map getKeyStrokeMap() { KeyStrokeMapProvider generator = getGenerator(); Map m = generator != null ? generator.loadKeyStrokeMap() : null; return m != null ? m : generateKeyStrokeMappings(); } /** * Generate the mapping between characters and key codes. This is * invoked exactly once per VM invocation. * We don't have complete coverage, so if you use this fallback map in AWT * mode some events may be missing that would otherwise be generated in * robot mode. */ private static Map generateKeyStrokeMappings() { Log.debug("Generating default keystroke mappings"); // character, keycode, modifiers int shift = InputEvent.SHIFT_MASK; //int alt = InputEvent.ALT_MASK; //int altg = InputEvent.ALT_GRAPH_MASK; int ctrl = InputEvent.CTRL_MASK; //int meta = InputEvent.META_MASK; // These are assumed to be standard across all keyboards (?) int[][] universalMappings = { { '', KeyEvent.VK_ESCAPE, 0 }, // No escape sequence exists { '\b', KeyEvent.VK_BACK_SPACE, 0 }, { '', KeyEvent.VK_DELETE, 0 }, // None for this one either { '\n', KeyEvent.VK_ENTER, 0 }, { '\r', KeyEvent.VK_ENTER, 0 }, }; // Add to these as needed; note that this is based on a US keyboard // mapping, and will likely fail for others. int[][] mappings = { { ' ', KeyEvent.VK_SPACE, 0, }, { '\t', KeyEvent.VK_TAB, 0, }, { '~', KeyEvent.VK_BACK_QUOTE, shift, }, { '`', KeyEvent.VK_BACK_QUOTE, 0, }, { '!', KeyEvent.VK_1, shift, }, { '@', KeyEvent.VK_2, shift, }, { '#', KeyEvent.VK_3, shift, }, { '$', KeyEvent.VK_4, shift, }, { '%', KeyEvent.VK_5, shift, }, { '^', KeyEvent.VK_6, shift, }, { '&', KeyEvent.VK_7, shift, }, { '*', KeyEvent.VK_8, shift, }, { '(', KeyEvent.VK_9, shift, }, { ')', KeyEvent.VK_0, shift, }, { '-', KeyEvent.VK_MINUS, 0, }, { '_', KeyEvent.VK_MINUS, shift, }, { '=', KeyEvent.VK_EQUALS, 0, }, { '+', KeyEvent.VK_EQUALS, shift, }, { '[', KeyEvent.VK_OPEN_BRACKET, 0, }, { '{', KeyEvent.VK_OPEN_BRACKET, shift, }, // NOTE: The following does NOT produce a left brace //{ '{', KeyEvent.VK_BRACELEFT, 0, }, { ']', KeyEvent.VK_CLOSE_BRACKET, 0, }, { '}', KeyEvent.VK_CLOSE_BRACKET, shift, }, { '|', KeyEvent.VK_BACK_SLASH, shift, }, { ';', KeyEvent.VK_SEMICOLON, 0, }, { ':', KeyEvent.VK_SEMICOLON, shift, }, { ',', KeyEvent.VK_COMMA, 0, }, { '<', KeyEvent.VK_COMMA, shift, }, { '.', KeyEvent.VK_PERIOD, 0, }, { '>', KeyEvent.VK_PERIOD, shift, }, { '/', KeyEvent.VK_SLASH, 0, }, { '?', KeyEvent.VK_SLASH, shift, }, { '\\', KeyEvent.VK_BACK_SLASH, 0, }, { '|', KeyEvent.VK_BACK_SLASH, shift, }, { '\'', KeyEvent.VK_QUOTE, 0, }, { '"', KeyEvent.VK_QUOTE, shift, }, }; HashMap map = new HashMap(); // Universal mappings for (int i=0;i < universalMappings.length;i++) { int[] entry = universalMappings[i]; KeyStroke stroke = KeyStroke.getKeyStroke(entry[1], entry[2]); map.put(new Character((char)entry[0]), stroke); } // If the locale is not en_US/GB, provide only a very basic map and // rely on key_typed events instead Locale locale = Locale.getDefault(); if (!Locale.US.equals(locale) && !Locale.UK.equals(locale)) { Log.debug("Not US: " + locale); return map; } // Basic symbol/punctuation mappings for (int i=0;i < mappings.length;i++) { int[] entry = mappings[i]; KeyStroke stroke = KeyStroke.getKeyStroke(entry[1], entry[2]); map.put(new Character((char)entry[0]), stroke); } // Lowercase for (int i='a';i <= 'z';i++) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_A + i - 'a', 0); map.put(new Character((char)i), stroke); // control characters stroke = KeyStroke.getKeyStroke(KeyEvent.VK_A + i - 'a', ctrl); Character key = new Character((char)(i - 'a' + 1)); // Make sure we don't overwrite something already there if (map.get(key) == null) { map.put(key, stroke); } } // Capitals for (int i='A';i <= 'Z';i++) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_A + i - 'A', shift); map.put(new Character((char)i), stroke); } // digits for (int i='0';i <= '9';i++) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_0 + i - '0', 0); map.put(new Character((char)i), stroke); } return map; } private static Map characterMap = null; private static Map keyStrokeMap = null; private static boolean loaded = false; private static InputStream findMap() { String[] names = getMapNames(); for (int i=0;i < names.length;i++) { Log.debug("Trying " + names[i]); String name = getFilename(names[i]); InputStream is = KeyStrokeMapProvider.class. getResourceAsStream("keymaps/" + name); if (is != null) return is; } return KeyStrokeMapProvider.class. getResourceAsStream("keymaps/default.map"); } private synchronized void loadMaps() { if (loaded) return; Properties props = new Properties(); Map cmap = null; Map kmap = null; try { InputStream is = findMap(); if (is == null) { Log.debug("No appropriate map file found"); loaded = true; return; } props.load(is); Iterator iter = props.keySet().iterator(); cmap = new HashMap(); kmap = new HashMap(); while (iter.hasNext()) { String key = (String)iter.next(); Log.debug("Property " + key + "=" + props.getProperty(key)); try { String codeName = key.substring(0, key.indexOf(".")); int mask = Integer. parseInt(key.substring(key.indexOf(".")+1), 16); int value = Integer.parseInt(props.getProperty(key), 16); Character ch = new Character((char)value); Field field = KeyEvent.class.getField("VK_" + codeName); int code = field.getInt(null); KeyStroke ks = KeyStroke.getKeyStroke(code, mask); // May be more than one KeyStroke mapping to a given key // character; prefer no mask or shift mask over any other // masks. KeyStroke existing = (KeyStroke)kmap.get(ch); if (existing == null || ((existing.getModifiers() != 0 && existing.getModifiers() != KeyEvent.SHIFT_MASK) || (mask == 0 && (existing.getModifiers() != 0 || ks.toString().length() < existing.toString().length())))) { Log.debug("Installing " + ks + " for '" + ch + "'"); kmap.put(ch, ks); } cmap.put(ks, ch); } catch(NumberFormatException e) { // ignore invalid entries } catch(Exception e) { Log.warn(e); } } } catch(IOException io) { } Log.debug("Successfully loaded character/keystroke map"); characterMap = cmap; keyStrokeMap = kmap; loaded = true; } /** Load a map for the current locale to translate a character into a corresponding virtual keycode-based KeyStroke. */ public Map loadCharacterMap() { loadMaps(); return characterMap; } /** Load a map for the current locale to translate a virtual keycode into a character-based KeyStroke. */ public Map loadKeyStrokeMap() { loadMaps(); return keyStrokeMap; } /** Convert a String containing a unique identifier for the map into a * unique filename. */ protected static String getFilename(String base) { //return Integer.toHexString(base.hashCode()) + ".map"; return base + ".map"; } protected static String[] getMapNames() { return getMapStrings(false); } protected static String[] getMapDescriptions() { return getMapStrings(true); } /** Return the keystroke map filenames that should be available for this * locale/OS/VM version/architecture. Assume most changes across locale, * then OS, then VM version, then os version/architecture. */ private static String[] getMapStrings(boolean desc) { ArrayList list = new ArrayList(); Locale locale = Locale.getDefault(); String name = locale.toString(); if (desc) name = "locale=" + name; list.add(0, name); String os = "-" + getOSType(); if (desc) os = " (os=" + System.getProperty("os.name") + ", " + System.getProperty("os.version") + ")"; name += os; list.add(0, name); // Allow the invoker to override the keyStrokeMap to support // case where you are working on a remote machine with a different // local or platform. String override = System.getProperty("abbot.keyStrokeMap"); if (override!=null) { list.add(0, override); } /* String vm = System.getProperty("java.version"); name += " vm=" + vm; list.add(0, name); String version = System.getProperty("os.version"); name += " version=" + version; list.add(0, name); String arch = System.getProperty("os.arch"); name += " arch=" + arch; list.add(0, name); */ return (String[])list.toArray(new String[list.size()]); } private static String getOSType() { return Platform.isMacintosh() ? "mac" : (Platform.isWindows() ? "w32" : "x11"); } /** Return currently available locales. */ public static void main(String[] args) { Locale[] available = Locale.getAvailableLocales(); System.out.println("Available Locales"); for (int i=0;i < available.length;i++) { System.out.print(available[i].toString()); System.out.print(" "); } System.exit(1); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/KeyStrokeMapProvider.java
package abbot.tester; import java.util.Map; /** Provides read/write of local-specific mappings for virtual keycode-based KeyStrokes to characters and vice versa. */ public interface KeyStrokeMapProvider { /** Returns a map for the current locale which translates an Integer * virtual keycode (VK_XXX) into a the Character it produces. May not * necessarily map all keycode/modifier combinations. */ Map loadCharacterMap(); /** Returns a map for the current locale which translates a Character into * a keycode-based KeyStroke. Where multiple keycodes may produce the * same Character output, the simplest keystroke is used. */ Map loadKeyStrokeMap(); }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ListLocation.java
package abbot.tester; import java.awt.*; import abbot.i18n.Strings; import abbot.util.ExtendedComparator; /** Provides encapsulation of the location of a row on a List (a coordinate, * item index or value). */ public class ListLocation extends ComponentLocation { private String value = null; private int row = -1; public ListLocation() { } public ListLocation(String value) { this.value = value; } public ListLocation(int row) { if (row < 0) { String msg = Strings.get("tester.JList.invalid_index", new Object[] { new Integer(row) }); throw new LocationUnavailableException(msg); } this.row = row; } public ListLocation(Point where) { super(where); } protected String badFormat(String encoded) { return Strings.get("location.list.bad_format", new Object[] { encoded }); } /** Find the first String match in the list and return the index. */ private int valueToIndex(List list, String value) { int size = list.getItemCount(); for (int i=0;i < size;i++) { if (ExtendedComparator.stringsMatch(value, list.getItem(i))) { return i; } } return -1; } public int getIndex(List list) { if (value != null) return valueToIndex(list, value); if (row != -1) { return row; } throw new LocationUnavailableException("Can't derive an index from a Point on java.awt.List"); } /** Return a concrete point for the abstract location. */ public Point getPoint(Component c) { List list = (List)c; if (value != null || row != -1) throw new LocationUnavailableException("Can't derive a Point from an index on java.awt.List"); return super.getPoint(list); } public Rectangle getBounds(Component c) { throw new LocationUnavailableException("Can't determine bounds on java.awt.List"); } public boolean equals(Object o) { if (o instanceof ListLocation) { ListLocation loc = (ListLocation)o; if (value != null) return value.equals(loc.value); if (row != -1) return row == loc.row; } return super.equals(o); } public String toString() { if (value != null) return encodeValue(value); if (row != -1) return encodeIndex(row); return super.toString(); } public ComponentLocation parse(String encoded) { encoded = encoded.trim(); if (isValue(encoded)) { value = parseValue(encoded); return this; } else if (isIndex(encoded)) { row = parseIndex(encoded); return this; } return super.parse(encoded); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/ListTester.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import abbot.util.*; import abbot.i18n.Strings; /** Provides actions for <code>java.awt.List</code>. */ // TODO: double-click (actionPerformed) // TODO: multi-select public class ListTester extends ComponentTester { private int LIST_DELAY = Properties.getProperty("abbot.tester.list_delay", 30000, 0, 60000); private class Listener implements AWTEventListener { public volatile boolean selected; private int targetIndex = -1; public Listener(int index, boolean state) { targetIndex = index; selected = !state; } public void eventDispatched(AWTEvent e) { if (e.getID() == ItemEvent.ITEM_STATE_CHANGED && e.getSource() instanceof List) { if (((List)e.getSource()). getSelectedIndex() == targetIndex) { selected = ((ItemEvent)e). getStateChange() == ItemEvent.SELECTED; } } } } /** @deprecated Use actionSelectRow instead. */ public void actionSelectIndex(Component c, int index) { actionSelectRow(c, new ListLocation(index)); } /** Select the row corresponding to the given ListLocation. */ public void actionSelectRow(Component c, ListLocation location) { List list = (List)c; try { int index = location.getIndex(list); if (index < 0 || index >= list.getItemCount()) { String msg = Strings.get("tester.JList.invalid_index", new Object[] { new Integer(index) }); throw new ActionFailedException(msg); } if (list.getSelectedIndex() != index) { setSelected(list, index, true); } } catch(LocationUnavailableException e) { actionClick(c, location); } } protected void setSelected(List list, int index, boolean selected) { Listener listener = new Listener(index, selected); new WeakAWTEventListener(listener, ItemEvent.ITEM_EVENT_MASK); list.select(index); ItemEvent ie = new ItemEvent(list, ItemEvent.ITEM_STATE_CHANGED, list.getSelectedItem(), selected ? ItemEvent.SELECTED : ItemEvent.DESELECTED); postEvent(list, ie); long now = System.currentTimeMillis(); while (listener.selected != selected) { if (System.currentTimeMillis() - now > LIST_DELAY) throw new ActionFailedException("List didn't fire for " + "index " + index + " selection"); sleep(); } waitForIdle(); } /** Parse the String representation of a ListLocation into the actual ListLocation object. */ public ComponentLocation parseLocation(String encoded) { return new ListLocation().parse(encoded); } /** Return the value, row, or coordinate location. */ public ComponentLocation getLocation(Component c, Point p) { throw new LocationUnavailableException("Locations on java.awt.List must be entered manually"); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/LocationUnavailableException.java
package abbot.tester; /** Indicates that a location can't be provided. */ public class LocationUnavailableException extends ActionFailedException { public LocationUnavailableException(String msg) { super(msg); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/Robot.java
package abbot.tester; import abbot.InterruptedAbbotException; import abbot.Log; import abbot.Platform; import abbot.WaitTimedOutException; import abbot.finder.BasicFinder; import abbot.finder.ComponentFinder; import abbot.finder.ComponentNotFoundException; import abbot.finder.Matcher; import abbot.finder.MultipleComponentsFoundException; import abbot.finder.matchers.JMenuItemMatcher; import abbot.finder.matchers.JMenuMatcher; import abbot.i18n.Strings; import abbot.util.AWT; import abbot.util.Bugs; import abbot.util.Condition; import abbot.util.NamedThreadFactory; import abbot.util.Properties; import abbot.util.Reflector; import java.awt.AWTEvent; import java.awt.AWTException; import java.awt.Button; import java.awt.Checkbox; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.Label; import java.awt.MenuBar; import java.awt.MenuComponent; import java.awt.MenuItem; import java.awt.Point; import java.awt.PopupMenu; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ComponentEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.HierarchyEvent; import java.awt.event.InputEvent; import java.awt.event.InputMethodEvent; import java.awt.event.InvocationEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.PaintEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.accessibility.AccessibleAction; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleIcon; import javax.swing.AbstractButton; import javax.swing.FocusManager; import javax.swing.JComponent; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.TitledBorder; import javax.xml.ws.Holder; import sun.awt.SunToolkit; /** Provide a higher level of abstraction for user input (A Better Robot). The Robot's operation may be affected by the following properties:<br> <pre><code>abbot.robot.auto_delay</code></pre><br> Set this to a value representing the millisecond count in between generated events. Usually just set to 100-200 if you want to slow down the playback to simulate actual user input. The default is zero delay.<br> <pre><code>abbot.robot.mode</code></pre><br> Set this to either "robot" or "awt" to designate the desired mode of event generation. "robot" uses java.awt.Robot to generate events, while "awt" stuffs events directly into the AWT event queue.<br> <pre><code>abbot.robot.event_post_delay</code></pre><br> This is the maximum number of ms it takes the system to post an AWT event in response to a Robot-generated event. <pre><code>abbot.robot.default_delay</code></pre><br> Base delay setting, acts as default value for the next two. <pre><code>abbot.robot.popup_delay</code></pre><br> Set this to the maximum time to wait for a menu to appear or be generated. <pre><code>abbot.robot.component_delay</code></pre><br> Set this to the maximum time to wait for a Component to become available. <p> The Robot class provides a generic solution for dealing with asynchronous updates to the UI with the {@link #wait(Condition,long, int)} method. This allows the testing thread to pause until a given component of data value in a component is ready. <p> NOTE: Only use event queue synchronization (e.g. {@link #invokeAndWait(Runnable)} or {@link #waitForIdle()} when a subsequent robot-level action is being applied to the results of a prior action (e.g. focus, deiconify, menu selection). Otherwise, don't introduce a mandatory delay (e.g. use {@link #invokeLater(Runnable)}). <p> NOTE: If a robot action isn't reproduced properly, you may need to introduce either additional events or extra delay. Adding enforced delay for a given platform is usually preferable to generating additional events, so always try that first, but be sure to restrict it to the platform in question. <p> NOTE: Robot actions should <b>never</b> be invoked on the event dispatch thread. */ public class Robot implements AWTConstants { /** Use java.awt.Robot to generate events. */ public static int EM_ROBOT = 0; /** Post events to the AWT event queue. */ public static int EM_AWT = 1; private static final String LABELED_BY_PROPERTY = "labeledBy"; private static final Toolkit toolkit = Toolkit.getDefaultToolkit(); // Max robot delay, in ms private static final int MAX_DELAY = 60000; // TODO: verify this value for X11, etc.; ALT for w32, option for OSX public static final int MOUSELESS_MODIFIER_MASK = InputEvent.ALT_MASK; public static final String MOUSELESS_MODIFIER = AWT.getKeyModifiers(MOUSELESS_MODIFIER_MASK); /** OS X using screenMenuBar actually uses an AWT menu as the live component. The JXXX components exist, but are not effectively active. */ protected static final boolean useScreenMenuBar() { // Ideally we'd install a menu and check where it ended up, since the // property is read once at startup and ignored thereafter. return Platform.isOSX() && (Boolean.getBoolean("com.apple.macos.useScreenMenuBar") || Boolean.getBoolean("apple.laf.useScreenMenuBar")); } /** Base delay setting. */ public static int defaultDelay = Properties.getProperty("abbot.robot.default_delay", 30000, 0, 60000); /** Delay before checking for idle. This allows the system a little time to put a native event onto the AWT event queue. */ private static int eventPostDelay = Properties.getProperty("abbot.robot.event_post_delay", 100, 0, 1000); protected static long IDLE_TIMEOUT = Integer.getInteger("abbot.robot.idle_timeout", 10000).intValue(); protected static int REALSYNC_IDLE_TIMEOUT_DEFAULT = 22000; // This code was generating timeout that were far too long for practical use // so I am going to try with a hardcoded default of 22 seconds // static { // try { // String fieldName; // if (Platform.is7OrAfter()) { // fieldName = "DEFAULT_WAIT_TIME"; // } // else { // fieldName = "WAIT_TIME"; // } // // Field $WAITTIME = SunToolkit.class.getDeclaredField(fieldName); // $WAITTIME.setAccessible(true); // int timeout = $WAITTIME.getInt(SunToolkit.class); // // Field $MAX_ITERS = SunToolkit.class.getDeclaredField("MAX_ITERS"); // $MAX_ITERS.setAccessible(true); // int max_inters = $MAX_ITERS.getInt(SunToolkit.class); // // Assume time out should be just a couple of more interations than // // the timeout we might see if everything has gone wrong // REALSYNC_IDLE_TIMEOUT_DEFAULT = // timeout * (max_inters + 2); // } catch (Exception e) { // Log.warn("Problem defaulting idle time", e); // } // } protected static long REALSYNC_IDLE_TIMEOUT = Integer.getInteger("abbot.robot.realsync_idle_timeout", REALSYNC_IDLE_TIMEOUT_DEFAULT).intValue(); /** Delay before failing to find a popup menu that should appear. */ protected static int popupDelay = Properties.getProperty("abbot.robot.popup_delay", defaultDelay, 0, 60000); // Some platforms require a pause between mouse down and mouse motion protected int DRAG_DELAY = Properties.getProperty("abbot.robot.drag_delay", Platform.isX11() || Platform.isOSX() ? 100 : 0, 0, 60000); /** Delay before jittering the mouse to encourage a popup menu to appear. */ protected static int popupJitterDelay = Properties.getProperty("abbot.robot.popup_jitter_delay", 300, 0, 10000); /** Delay before failing to find a component that should be visible. */ public static int componentDelay = Properties.getProperty("abbot.robot.component_delay", defaultDelay, 0, 60000); /** Number of times to retry a popup menu before we give up. */ public static final int popupRetry = Properties.getProperty("abbot.robot.popup_retry", 1, 0,10); /** With decreased robot auto delay, OSX popup menus don't activate * properly. Indicate the minimum delay for proper operation (determined * experimentally). */ private static final int subMenuDelay = Platform.isOSX() ? 100 : 0; /** How events are generated. */ private static int eventMode = EM_ROBOT; private static boolean verified = false; private static boolean serviceMode = false; // FIXME add one per graphics device? /** The robot used to generate events. */ private static java.awt.Robot robot; private static WindowTracker tracker; /** Current input state. This will either be that of the AWT event queue * or of the robot, depending on the dispatch mode. * Note that the robot state may be different from that seen by the AWT * event queue, since robot events may be as yet unprocessed. */ private static InputState state; /** Suitable inter-event delay for most cases; tests have been run safely * at this value. Should definitely be less than the double-click * threshold.<p> */ private static final int DEFAULT_DELAY = getPreferredRobotAutoDelay(); private static final int SLEEP_INTERVAL = Properties.getProperty("abbot.robot.wait_sleep_interval", 50, 10, 1000); private static int autoDelay = DEFAULT_DELAY; public static int getAutoDelay() { return autoDelay; } /** Returns a functioning instance of java.awt.Robot. If this method * returns null, it should be assumed that java.awt.Robot is unavailable * or non-functional on the current system. */ public static java.awt.Robot getRobot() { initializeRobot(); return serviceMode ? null : robot; } /** Return a singleton InputState object. */ public static InputState getState() { initializeRobot(); return state; } private static synchronized void initializeRobot() { if (state == null) { robot = createRobot(); tracker = WindowTracker.getTracker(); state = new InputState(); } } private static class InterruptibleRobot extends java.awt.Robot { public InterruptibleRobot() throws AWTException { super(); } /** * Sleep, but reset interrupt flag if interrupted */ public synchronized void delay(int ms) { try { TimeUnit.MILLISECONDS.sleep(ms); } catch(InterruptedException ite) { throw new InterruptedAbbotException("Interrupted when running a delay"); } } /** * Wait, but reset interrupt flag if interrupted */ public synchronized void waitForIdle() { if (EventQueue.isDispatchThread()) { throw new IllegalThreadStateException("Only on the event dispatch thread"); } // Post marker event to queue try { SunToolkit.flushPendingEvents(); EventQueue.invokeAndWait( new Runnable() { public void run() { // dummy implementation } } ); } catch(InterruptedException ite) { throw new InterruptedAbbotException("Interrupted when waiting for idle"); } catch(InvocationTargetException ine) { ine.printStackTrace(); } } } private static java.awt.Robot createRobot() { java.awt.Robot robot = null; String mode = System.getProperty("abbot.robot.mode", "robot"); autoDelay = Properties.getProperty("abbot.robot.auto_delay", autoDelay, -1, 60000); try { // Even if the robot doesn't work, we can still use it for some // things. robot = new InterruptibleRobot(); if (autoDelay != -1) { robot.setAutoDelay(autoDelay); } else { autoDelay = robot.getAutoDelay(); } if (!verified) { verified = true; boolean verify = !"false".equals(System.getProperty("abbot.robot.verify")); if (verify && !RobotVerifier.verify(robot)) { // robot doesn't work (w32 service mode) serviceMode = true; System.err.println("Robot non-functional, " + "falling back to AWT mode"); mode = "awt"; } } } catch(AWTException e) { // no robot available, send AWT events System.err.println("Falling back to AWT mode: " + e.getMessage()); mode = "awt"; } if (mode.equals("awt")) { eventMode = EM_AWT; } return robot; } /** Returns the current event-generation mode. */ public static int getEventMode() { initializeRobot(); return eventMode; } public static String getEventModeDescription() { initializeRobot(); String desc = eventMode == EM_ROBOT ? "robot" : "awt"; if (serviceMode) desc += " (service)"; return desc; } /** Set the event-generation mode. @throws IllegalStateException if the requested mode is EM_ROBOT and java.awt.Robot is unavailable in the current environment. */ public static void setEventMode(int mode) { initializeRobot(); if (eventMode != mode) { if (mode == EM_ROBOT && (serviceMode || robot == null)) { String msg = Strings.get("tester.Robot.no_robot_mode"); throw new IllegalStateException(msg); } eventMode = mode; } } public static int getEventPostDelay() { return eventPostDelay; } public static void setEventPostDelay(int delay) { eventPostDelay = Math.min(1000, Math.max(0, delay)); } /** Allow this to be adjusted, mostly for testing. */ public static void setAutoDelay(int ms) { initializeRobot(); ms = Math.min(60000, Math.max(0, ms)); if (eventMode == EM_ROBOT) robot.setAutoDelay(ms); autoDelay = ms; Log.debug("Auto delay set to " + ms); } /** Default constructor. */ public Robot() { initializeRobot(); } /** * Move the mouse to the given location, in screen coordinates. * NOTE: in robot mode, you may need to invoke this with a little jitter. * There are some conditions where a single mouse move will not * generate the necessary enter event on a component (typically a * dialog with an OK button) before a mousePress. See also click(). * NOTE: does 1.4+ need jitter? */ private void mouseMove(int x, int y) { if (eventMode == EM_ROBOT) { Log.debug("ROBOT: Mouse move: (" + x + "," + y + ")"); robot.mouseMove(x, y); } else { // Can't stuff an AWT event for an arbitrary location } } /** Send a button press event. */ public void mousePress(int buttons) { if (eventMode == EM_ROBOT) { Log.debug("ROBOT: Mouse press: " + AWT.getMouseModifiers(buttons)); // OSX 1.4.1 accidentally swaps mb2 and mb3; fix it here robot.mousePress(buttons); } else { Component c = state.getMouseComponent(); if (c == null) { Log.warn("No current mouse component for button press", 4); return; } Point where = state.getMouseLocation(); postMousePress(c, where.x, where.y, buttons); } } /** Send a button release event for button 1. */ public void mouseRelease() { mouseRelease(MouseEvent.BUTTON1_MASK); } /** Send a button release event. */ public void mouseRelease(int buttons) { if (eventMode == EM_ROBOT) { Log.debug("ROBOT: Mouse release: " + AWT.getMouseModifiers(buttons)); robot.mouseRelease(buttons); } else { Component source = state.isDragging() ? state.getDragSource() : (lastMousePress != null ? lastMousePress.getComponent() : state.getMouseComponent()); Point where = state.getMouseLocation(); if (source == null) { Log.warn("Mouse release outside of available frames"); return; } else if (where == null) { if (lastMousePress == null) { Log.warn("No record of most recent mouse press"); return; } where = lastMousePress.getPoint(); } postMouseRelease(source, where.x, where.y, buttons); } } /** Move keyboard focus to the given component. Note that the component may not yet have focus when this method returns. */ public void focus(Component comp) { focus(comp, false); } /** Use an explicit listener, since hasFocus is not always reliable. */ private class FocusWatcher extends FocusAdapter { public volatile boolean focused = false; public FocusWatcher(Component c) { focused = AWT.getFocusOwner() == c; } public void focusGained(FocusEvent f) { focused = true; } public void focusLost(FocusEvent f) { if (focused) { Log.warn("FFF gained focus and lost again"); } focused = false; } } /** Move keyboard focus to the given component. */ public void focus(final Component comp, boolean wait) { if (comp instanceof Window) { Window focusedWindow = AWT.getFocusedWindow(); if (comp == focusedWindow) { return; } } Component currentOwner = AWT.getFocusOwner(); if (currentOwner == comp) { return; } // Check to see if the currentOwner is in fact visibiel if (currentOwner != null && !AWT.getWindow(currentOwner).isVisible()) { Log.warn("FFF Current focued component is not visible\n" + currentOwner.toString()); Log.warn("FFF Going to attempt a hard reset of the focus owner"); invokeAndWait(comp, new Runnable() { public void run() { KeyboardFocusManager kfm = FocusManager.getCurrentKeyboardFocusManager(); kfm.clearGlobalFocusOwner(); } }); waitForIdle(); // Do we still have a problem? Component ownerAfterRest = AWT.getFocusOwner(); if (ownerAfterRest != null && ownerAfterRest == currentOwner) { Log.warn("FFF Focus owner hasn't changed, going to force window show and hide"); final Window parent = AWT.getWindow(ownerAfterRest); Log.warn("FFF window " + parent); invokeAndWait(comp, new Runnable() { public void run() { parent.setVisible(true); } }); waitForIdle(); invokeAndWait(comp, new Runnable() { public void run() { KeyboardFocusManager kfm = FocusManager.getCurrentKeyboardFocusManager(); kfm.clearGlobalFocusOwner(); } }); waitForIdle(); invokeAndWait(comp, new Runnable() { public void run() { parent.setVisible(false); parent.dispose(); } }); waitForIdle(); if (AWT.getFocusOwner() == currentOwner) { Log.warn("FFF Nothing I do seems to make a diffenc, still stuck with previous state"); } } } Log.debug("Focus change"); final FocusWatcher fw = new FocusWatcher(comp); try { // Register a focus watcher on this component invokeAndWait(comp, new Runnable() { @Override public void run() { comp.addFocusListener(fw); } }); // for pointer focus mouseMove(comp, comp.getWidth()/2, comp.getHeight()/2); waitForIdle(); // Make sure the correct window is in front Window w1 = currentOwner != null ? AWT.getWindow(currentOwner) : null; Window w2 = AWT.getWindow(comp); if (w1 != w2) { activate(w2); waitForIdle(); } // NOTE: while it would be nice to have a robot method instead of // requesting focus, clicking to change focus may have // side effects invokeAndWait(comp, new Runnable() { public void run() { boolean possible = comp.requestFocusInWindow(); if (!possible) { comp.requestFocus(); } } }); // waitForIdle(); // if (wait) { try { wait(new ConditionEDTDecorator(comp, new Condition(){ @Override public boolean test() { return fw.focused; } }),componentDelay); } catch (WaitTimedOutException wte) { String msg = Strings.get("tester.Robot.focus_failed", new Object[] { toString(comp) }); throw new ActionFailedException(msg, wte); } } } finally { invokeAndWait(comp, new Runnable() { @Override public void run() { comp.removeFocusListener(fw); } }); } // Wait for idle so we can ignore any side effects // waitForIdle(); } /** Usually only needed when dealing with Applets. */ protected static EventQueue getEventQueue(Component c) { initializeRobot(); if (c != null) { return tracker.getQueue(c); } else { return toolkit.getSystemEventQueue(); } } /** Post a runnable on the given component's event queue. Useful when driving multiple Applets, but is also useful to ensure an operation happens on the event dispatch thread. */ public void invokeLater(Component context, Runnable action) { EventQueue queue = getEventQueue(context); queue.postEvent(new InvocationEvent(toolkit, action)); } /** Post a runnable on the given component's event queue and wait for it to finish. */ public void invokeAndWait(Component c, final Runnable action) { // Original code just perfomed a invoke later then a waitForIdle // which doesn't work in some cases where the scrolling takes some // time as the event queue is empty whilst processing the messages //invokeLater(c, action); // See issue 3396894 // Instead we are going to use our callable code which makes // sure the event is run callAndWait(c, new Callable<Object>() { @Override public Object call() { action.run(); return null; } }); // Make sure any post actions are complete waitForIdle(); } /** @deprecated Method renamed to {@link #invokeLater(Runnable)} * @param action */ public void invokeAction(Runnable action) { invokeLater(action); } /** @deprecated Method renamed to {@link #invokeLater(Component, Runnable)} * @param c * @param action */ public void invokeAction(Component c, Runnable action) { invokeLater(c, action); } /** Run the given action on the event dispatch thread. This should be * used for any non-read-only methods invoked directly on a GUI * component. * NOTE: if you want to use the results of the action, use invokeAndWait * instead. */ public void invokeLater(Runnable action) { invokeLater(null, action); } /** Run the given action on the event dispatch thread, but don't return until it's been run. */ public void invokeAndWait(Runnable action) { invokeAndWait(null, action); } public void keyPress(int keycode) { keyPress(keycode, KeyEvent.CHAR_UNDEFINED); } /** Send a key press event. */ private void keyPress(int keycode, char keyChar) { if (eventMode == EM_ROBOT) { Log.debug("ROBOT: key press " + AWT.getKeyCode(keycode)); try { robot.keyPress(keycode); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("invalid key code " + keycode + " (char " + keyChar + ")"); } } else { int mods = state.getModifiers(); if (AWT.isModifier(keycode)) mods |= AWT.keyCodeToMask(keycode); postKeyEvent(KeyEvent.KEY_PRESSED, mods, keycode, KeyEvent.CHAR_UNDEFINED); // Auto-generate KEY_TYPED events, as best we can int mask = state.getModifiers(); if (keyChar == KeyEvent.CHAR_UNDEFINED) { KeyStroke ks = KeyStroke.getKeyStroke(keycode, mask); keyChar = KeyStrokeMap.getChar(ks); } if (keyChar != KeyEvent.CHAR_UNDEFINED) { postKeyEvent(KeyEvent.KEY_TYPED, mask, KeyEvent.VK_UNDEFINED, keyChar); } } } /** Send a key release event. */ public void keyRelease(int keycode) { if (eventMode == EM_ROBOT) { Log.debug("ROBOT: key release " + AWT.getKeyCode(keycode)); robot.keyRelease(keycode); if (Bugs.hasKeyInputDelay()) { // OSX, empirical int KEY_INPUT_DELAY = 200; if (KEY_INPUT_DELAY > autoDelay) { delay(KEY_INPUT_DELAY - autoDelay); } } } else { int mods = state.getModifiers(); if (AWT.isModifier(keycode)) mods &= ~AWT.keyCodeToMask(keycode); postKeyEvent(KeyEvent.KEY_RELEASED, mods, keycode, KeyEvent.CHAR_UNDEFINED); } } private void postKeyEvent(int id, int modifiers, int keycode, char ch) { Component c = findFocusOwner(); if (c != null) { postEvent(c, new KeyEvent(c, id, System.currentTimeMillis(), modifiers, keycode, ch)); } else { Log.warn("No component has focus, key press discarded"); } } /** Sleep for a little bit, measured in UI time. */ public void sleep() { delay(SLEEP_INTERVAL); } /** Sleep the given duration of ms. */ public static void delay(int ms) { initializeRobot(); // if (eventMode == EM_ROBOT) { while (ms > MAX_DELAY) { robot.delay(MAX_DELAY); ms -= MAX_DELAY; } robot.delay(ms); } else { try { Thread.sleep(ms); } catch(InterruptedException ie) { throw new InterruptedAbbotException("Interrupted during delay"); } } } private static final Runnable EMPTY_RUNNABLE = new Runnable() { public void run() { } }; /** Check for a blocked event queue (symptomatic of an active w32 AWT * popup menu). * @return whether the event queue is blocked. */ protected boolean queueBlocked() { return postInvocationEvent(toolkit.getSystemEventQueue(), toolkit, 200); } /** @return whether we timed out waiting for the invocation to run */ protected boolean postInvocationEvent(EventQueue eq, Toolkit toolkit, long timeout) { class RobotIdleLock { } Object lock = new RobotIdleLock(); synchronized(lock) { eq.postEvent(new InvocationEvent(toolkit, EMPTY_RUNNABLE, lock, true)); long start = System.currentTimeMillis(); try { // NOTE: on fast linux systems when showing a dialog, if we // don't provide a timeout, we're never notified, and the // test will wait forever (up through 1.5.0_05). lock.wait(timeout); return (System.currentTimeMillis() - start) >= IDLE_TIMEOUT; } catch(InterruptedException e) { Log.warn("Invocation lock interrupted"); throw new InterruptedAbbotException("Interrupted during invocation lock"); } } } private static volatile boolean HAS_SUN_TOOLKIT = !Boolean.getBoolean("abbot.DisableSunToolkitWait"); private static ExecutorService REAL_SYNC_POOL = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("SunToolkit.realSync")); private boolean waitForIdle(EventQueue eq) { if (EventQueue.isDispatchThread()) throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread"); // Synchronize with the platform event queue // if (HAS_SUN_TOOLKIT) { try { Future f = REAL_SYNC_POOL.submit(new Runnable() { public void run() { ((SunToolkit)toolkit).realSync(); } }); // We are going to wait for minute or two, and if it hasn't returned then // give it a poke try { f.get(REALSYNC_IDLE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new InterruptedAbbotException("Interrupted while waiting for idle"); } catch (ExecutionException e) { // Robot.<RuntimeException>throwAny(e.getCause()); } catch (TimeoutException e) { Log.warn("Timeout waiting for SunToolkit.realSync method to return", e); // Interrupt the future so we have some chance of recovering // look at the SunToolkit code this should interrupt this lock // in waitForIdle if things goes wrong // // try { // while (!eventDispatched) { // waitLock.wait(); // } // } catch (InterruptedException ie) { // return false; // } f.cancel(true); // We think that the realSync method is stuck because // a timeout happened posting the events to the event queue // due to bug xxxxx, so we are going to use reflection to // try to get hold of the lock object and notify on it try { Field $waitLock = SunToolkit.class.getDeclaredField("waitLock"); $waitLock.setAccessible(true); Object waitLock = $waitLock.get(toolkit); synchronized (waitLock) { waitLock.notifyAll(); } } catch (Throwable th) { Log.warn("Problem trying to poke the SunToolkit.realSync method back into life", th); } } } catch (sun.awt.SunToolkit.OperationTimedOut oto) { Log.warn("Timeout trying to sync with event queue, going to sleep for a little bit"); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { throw new InterruptedAbbotException("Interrupted while waiting for idle"); } } catch (sun.awt.SunToolkit.InfiniteLoop oto) { Log.warn("Inifinte loop trying to sync with event queue, going to sleep for a little bit"); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { throw new InterruptedAbbotException("Interrupted while waiting for idle"); } } catch (NoClassDefFoundError nodef) { Log.warn("Not using the sun toolkit, test likely to be less reliable", nodef); HAS_SUN_TOOLKIT = false; } } // NOTE: as of Java 1.3.1, robot.waitForIdle only waits for the // last event on the queue at the time of this invocation to be // processed. We need better than that. Make sure the given event // queue is empty when this method returns // We always post at least one idle event to allow any current event // dispatch processing to finish. long start = System.currentTimeMillis(); int count = 0; do { if (postInvocationEvent(eq, toolkit, IDLE_TIMEOUT)) { Log.warn("Timed out waiting for idle" + " (posted invocation event): " + IDLE_TIMEOUT + "ms (after " + count + " events)" + " posted to " + eq, Log.FULL_STACK); return false; } if (System.currentTimeMillis() - start > IDLE_TIMEOUT) { Log.warn("Timed out waiting for idle event queue after " + count + " events"); return false; } ++count; // Force a yield sleep(); // NOTE: this does not detect invocation events (i.e. what // gets posted with EventQueue.invokeLater), so if someone // is repeatedly posting one, we might get stuck. Not too // worried, since if a Runnable keeps calling invokeLater // on itself, *nothing* else gets much chance to run, so it // seems to be a bad programming practice. } while (eq.peekEvent() != null); return true; } @SuppressWarnings("unchecked") private static <E extends Throwable> void throwAny(Throwable e) throws E { throw (E)e; } /** * Wait for an idle AWT event queue. Note that this is different from * the implementation of <code>java.awt.Robot.waitForIdle()</code>, which * may have events on the queue when it returns. Do <b>NOT</b> use this * method if there are animations or other continual refreshes happening, * since in that case it may never return.<p> * * @return Whether the waitForIdle timed out or not */ public boolean waitForIdle() { if (eventPostDelay > autoDelay) { delay(eventPostDelay - autoDelay); } Collection queues = tracker.getEventQueues(); if (queues.size() == 1) { return waitForIdle(toolkit.getSystemEventQueue()); } else { // FIXME this resurrects dead event queues Iterator iter = queues.iterator(); while (iter.hasNext()) { EventQueue eq = (EventQueue)iter.next(); boolean hasNextQueue = false; try { Field $nextQueue = EventQueue.class.getDeclaredField("nextQueue"); $nextQueue.setAccessible(true); Object value = $nextQueue.get(eq); hasNextQueue = value!=null; } catch (NoSuchFieldException e) { Log.warn("Problem accessing field EventQueue.nextQueue"); } catch (IllegalAccessException e) { Log.warn("Problem accessing field EventQueue.nextQueue", 2); } // If eq has a nextQueue then ignore it as it isn't currently processing // requests because another queue has been pushed on top of it, // For bug fix 3476008 // if (!hasNextQueue && !waitForIdle(eq)) { return false; } } } return true; } /** Sample the color at the given point on the screen. */ public Color sample(int x, int y) { // Service mode always returns black when sampled if (robot != null && !serviceMode) { // Make sure we sync the graphics Toolkit.getDefaultToolkit().sync(); // return robot.getPixelColor(x, y); } String msg = Strings.get("tester.Robot.no_sample"); throw new UnsupportedOperationException(msg); } /** Sample the color at the given point on the component. */ public Color sample(Component c, int x, int y) { return sample(c, new ComponentLocation(new Point(x, y))); } /** Sample the color at the given location on the component. */ public Color sample(Component c, ComponentLocation loc) { Point p = loc.getPoint(c); Point where = AWT.getLocationOnScreen(c); where.translate(p.x, p.y); return sample(where.x, where.y); } /** Capture the contents of the given rectangle. */ /* NOTE: Text components (and maybe others with a custom cursor) will * capture the cursor. May want to move the cursor out of the component * bounds, although this might cause issues where the component is * responding visually to mouse movement. * Is this an OSX bug? */ public BufferedImage capture(final Rectangle bounds) { Log.debug("Screen capture " + bounds); BufferedImage image = null; if (robot != null) { image = robot.createScreenCapture(bounds); } return image; } /** Capture the contents of the given component, sans any border or * insets. This should only be used on components that do not use a LAF * UI, or the results will not be consistent across platforms. */ public BufferedImage capture(Component comp) { return capture(comp, true); } /** Capture the contents of the given component, optionally including the * border and/or insets. This should only be used on components that do * not use a LAF UI, or the results will not be consistent across * platforms. */ public BufferedImage capture(Component comp, boolean ignoreBorder) { Rectangle bounds = new Rectangle(comp.getSize()); Point loc = AWT.getLocationOnScreen(comp); bounds.setLocation(loc.x, loc.y); Log.debug("Component bounds " + bounds); if (ignoreBorder) { Insets insets = ((Container)comp).getInsets(); if (insets != null) { bounds.x += insets.left; bounds.y += insets.top; bounds.width -= insets.left + insets.right; bounds.height -= insets.top + insets.bottom; Log.debug("Component insets " + insets); } } return capture(bounds); } // Bug workaround support protected void jitter(Component comp, int x, int y) { Log.debug("jitter"); mouseMove(comp, (x > 0 ? x - 1 : x + 1), y); } // Bug workaround support protected void jitter(int x, int y) { mouseMove((x > 0 ? x - 1 : x + 1), y); } /** Move the pointer to the center of the given component. */ public void mouseMove(Component comp) { mouseMove(comp, comp.getWidth() / 2, comp.getHeight() / 2); } /** Wait the given number of ms for the component to be showing and ready. Returns false if the operation times out. */ private boolean waitForComponent(Component c, long delay) { return waitForComponent(c, delay, SLEEP_INTERVAL); } /** Wait the given number of ms for the component to be showing and ready. Returns false if the operation times out. */ private boolean waitForComponent(Component c, long delay, int sleep) { if (!isReadyForInput(c)) { Log.debug("Waiting for component to show: " + toString(c)); long start = System.currentTimeMillis(); // Give the component some time before we go into the loop, // might take a little time //delay(sleep); // Start loop waiting for component to show while (!isReadyForInput(c)) { if (c instanceof JPopupMenu) { // wiggle the mouse over the parent menu item to // ensure the submenu shows Component invoker = ((JPopupMenu)c).getInvoker(); if (invoker instanceof JMenu) { jitter(invoker, invoker.getWidth()/2, invoker.getHeight()/2); } } if (System.currentTimeMillis() - start > delay) { Log.warn("Component " + toString(c) + " (" + Integer.toHexString(c.hashCode()) + ")" + " not ready after " + delay + "ms: " + "showing=" + c.isShowing() + " win ready=" + tracker.isWindowReady(AWT.getWindow(c))); return false; } delay(sleep); } } return true; } /** Move the pointer to the given coordinates relative to the given * component. */ public void mouseMove(Component comp, int x, int y) { if (!waitForComponent(comp, componentDelay)) { String msg = "Can't obtain position of component " + toString(comp); throw new ComponentNotShowingException(msg); } if (eventMode == EM_ROBOT) { try { Point point = AWT.getLocationOnScreen(comp); if (point != null) { point.translate(x, y); mouseMove(point.x, point.y); } } catch(java.awt.IllegalComponentStateException e) { } } else { Component eventSource = comp; int id = MouseEvent.MOUSE_MOVED; boolean outside = false; // When dragging, the event source is always the target of the // original mouse press. if (state.isDragging()) { id = MouseEvent.MOUSE_DRAGGED; eventSource = state.getDragSource(); } else { Point pt = new Point(x, y); eventSource = comp = AWT.retargetMouseEvent(comp, id, pt); x = pt.x; y = pt.y; outside = x < 0 || y < 0 || x >= comp.getWidth() || y >= comp.getHeight(); } Component current = state.getMouseComponent(); if (current != comp) { if (outside && current != null) { Point pt = SwingUtilities.convertPoint(comp, x, y, current); postMouseMotion(current, MouseEvent.MOUSE_EXITED, pt); return; } postMouseMotion(comp, MouseEvent.MOUSE_ENTERED, new Point(x, y)); } Point pt = new Point(x, y); if (id == MouseEvent.MOUSE_DRAGGED) { // Drag coordinates are relative to drag source component pt = SwingUtilities.convertPoint(comp, pt, eventSource); } postMouseMotion(eventSource, id, pt); // Add an exit event if warranted if (outside) { postMouseMotion(comp, MouseEvent.MOUSE_EXITED, new Point(x, y)); } } } /** Move the mouse appropriately to get from the source to the destination. Enter/exit events will be generated where appropriate. */ public void dragOver(Component dst, int x, int y) { mouseMove(dst, x-4, y); mouseMove(dst, x, y); } /** Begin a drag operation using button 1.<p> This method is tuned for native drag/drop operations, so if you get odd behavior, you might try using a simple {@link #mousePress(Component,int,int)} instead. */ public void drag(Component src, int sx, int sy) { drag(src, sx, sy, InputEvent.BUTTON1_MASK); } /** Begin a drag operation using the given button mask.<p> This method is tuned for native drag/drop operations, so if you get odd behavior, you might try using a simple {@link #mousePress(Component,int,int,int)} instead. */ // TODO: maybe auto-switch to robot mode if available? public void drag(Component src, int sx, int sy, int buttons) { if (Bugs.dragDropRequiresNativeEvents() && eventMode != EM_ROBOT && !Boolean.getBoolean("abbot.ignore_drag_error")) { String msg = Strings.get("abbot.Robot.no_drag_available"); if (serviceMode) { // If we start a native drag in this mode, it'll pretty much // lock up the system, apparently with the native AWT libs // starting a thread invisible to the VM that chews up all CPU // time. throw new ActionFailedException(msg); } Log.warn(msg); } Log.debug("drag"); mousePress(src, sx, sy, buttons); if (DRAG_DELAY > autoDelay) { delay(DRAG_DELAY); } if (Platform.isWindows() || Platform.isMacintosh()) { int dx = sx + AWTConstants.DRAG_THRESHOLD < src.getWidth() ? AWTConstants.DRAG_THRESHOLD : 0; int dy = sy + AWTConstants.DRAG_THRESHOLD < src.getHeight() ? AWTConstants.DRAG_THRESHOLD : 0; if (dx == 0 && dy == 0) dx = AWTConstants.DRAG_THRESHOLD; mouseMove(src, sx + dx/4, sy + dy/4); mouseMove(src, sx + dx/2, sy + dy/2); mouseMove(src, sx + dx, sy + dy); mouseMove(src, sx + dx + 1, sy + dy); } else { mouseMove(src, sx + AWTConstants.DRAG_THRESHOLD/2, sy + AWTConstants.DRAG_THRESHOLD/2); mouseMove(src, sx + AWTConstants.DRAG_THRESHOLD, sy + AWTConstants.DRAG_THRESHOLD); mouseMove(src, sx + AWTConstants.DRAG_THRESHOLD/2, sy + AWTConstants.DRAG_THRESHOLD/2); mouseMove(src, sx, sy); } Log.debug("drag started"); } /** End a drag operation, releasing the mouse button over the given target location.<p> This method is tuned for native drag/drop operations, so if you get odd behavior, you might try using a simple {@link #mouseMove(Component,int,int)}, {@link #mouseRelease()} instead. */ public void drop(Component target, int x, int y) { Log.debug("drop"); // Delay between final move and drop to ensure drop ends. int DROP_DELAY = Properties.getProperty("abbot.robot.drop_delay", Platform.isWindows() ? 200 : 0, 0, 60000); dragOver(target, x, y); long start = System.currentTimeMillis(); while (!state.isDragging()) { if (System.currentTimeMillis() - start > eventPostDelay*4) { String msg = Strings.get("Robot.no_current_drag"); throw new ActionFailedException(msg); } sleep(); } if (DROP_DELAY > autoDelay) delay(DROP_DELAY - autoDelay); mouseRelease(state.getButtons()); Log.debug("dropped"); } /** Generate a mouse enter/exit/move/drag for the destination component. * NOTE: The VM automatically usually generates exit events; need a test * to define the behavior, though. */ private void postMouseMotion(Component dst, int id, Point to) { // The VM auto-generates exit events as needed (1.3, 1.4) if (id != MouseEvent.MOUSE_DRAGGED) dst = AWT.retargetMouseEvent(dst, id, to); // Avoid multiple moves to the same location if (state.getMouseComponent() != dst || !to.equals(state.getMouseLocation())) { postEvent(dst, new MouseEvent(dst, id, System.currentTimeMillis(), state.getModifiers(), to.x, to.y, state.getClickCount(), false)); } } /** Type the given keycode with no modifiers. */ public void key(int keycode) { key(keycode, 0); } /** Press or release the appropriate modifiers corresponding to the given mask. */ public void setModifiers(int modifiers, boolean press) { boolean altGraph = (modifiers & InputEvent.ALT_GRAPH_MASK) != 0; boolean shift = (modifiers & InputEvent.SHIFT_MASK) != 0; boolean alt = (modifiers & InputEvent.ALT_MASK) != 0; boolean ctrl = (modifiers & InputEvent.CTRL_MASK) != 0; boolean meta = (modifiers & InputEvent.META_MASK) != 0; if (press) { if (altGraph) keyPress(KeyEvent.VK_ALT_GRAPH); if (alt) keyPress(KeyEvent.VK_ALT); if (shift) keyPress(KeyEvent.VK_SHIFT); if (ctrl) keyPress(KeyEvent.VK_CONTROL); if (meta) keyPress(KeyEvent.VK_META); } else { // For consistency, release in the reverse order of press if (meta) keyRelease(KeyEvent.VK_META); if (ctrl) keyRelease(KeyEvent.VK_CONTROL); if (shift) keyRelease(KeyEvent.VK_SHIFT); if (alt) keyRelease(KeyEvent.VK_ALT); if (altGraph) keyRelease(KeyEvent.VK_ALT_GRAPH); } } /** Type the given keycode with the given modifiers. Modifiers is a mask * from the available InputEvent masks. */ public void key(int keycode, int modifiers) { key(KeyEvent.CHAR_UNDEFINED, keycode, modifiers); } private void key(char ch, int keycode, int modifiers) { Log.debug("key keycode=" + AWT.getKeyCode(keycode) + " mod=" + AWT.getKeyModifiers(modifiers)); boolean isModifier = true; switch(keycode) { case KeyEvent.VK_ALT_GRAPH: modifiers |= InputEvent.ALT_GRAPH_MASK; break; case KeyEvent.VK_ALT: modifiers |= InputEvent.ALT_MASK; break; case KeyEvent.VK_SHIFT: modifiers |= InputEvent.SHIFT_MASK; break; case KeyEvent.VK_CONTROL: modifiers |= InputEvent.CTRL_MASK; break; case KeyEvent.VK_META: modifiers |= InputEvent.META_MASK;break; default: isModifier = false; break; } setModifiers(modifiers, true); if (!isModifier) { keyPress(keycode, ch); keyRelease(keycode); } setModifiers(modifiers, false); if (Bugs.hasKeyStrokeGenerationBug()) delay(100); } /** * Type the given character. Note that this sends the key to whatever * component currently has the focus. */ // FIXME should this be renamed to "key"? public void keyStroke(char ch) { KeyStroke ks = KeyStrokeMap.getKeyStroke(ch); if (ks == null) { // If no mapping is available, we omit press/release events and // only generate a KEY_TYPED event Log.debug("No key mapping for '" + ch + "'"); Component focus = findFocusOwner(); if (focus == null) { Log.warn("No component has focus, keystroke discarded", Log.FULL_STACK); return; } KeyEvent ke = new KeyEvent(focus, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, ch); // Allow any pending robot events to complete; otherwise we // might stuff the typed event before previous robot-generated // events are posted. if (eventMode == EM_ROBOT) waitForIdle(); postEvent(focus, ke); } else { int keycode = ks.getKeyCode(); int mod = ks.getModifiers(); Log.debug("Char '" + ch + "' generated by keycode=" + keycode + " mod=" + mod); key(ch, keycode, mod); } } /** Type the given string. */ public void keyString(String str) { char[] ch = str.toCharArray(); for (int i=0;i < ch.length;i++) { keyStroke(ch[i]); } } public void mousePress(Component comp) { mousePress(comp, InputEvent.BUTTON1_MASK); } public void mousePress(Component comp, int mask) { mousePress(comp, comp.getWidth() / 2, comp.getHeight() / 2, mask); } public void mousePress(Component comp, int x, int y) { mousePress(comp, x, y, InputEvent.BUTTON1_MASK); } /** Mouse down in the given part of the component. All other mousePress methods must eventually invoke this one. */ public void mousePress(Component comp, int x, int y, int mask) { if (eventMode == EM_ROBOT && Bugs.hasRobotMotionBug()) { jitter(comp, x, y); } mouseMove(comp, x, y); if (eventMode == EM_ROBOT) mousePress(mask); else { postMousePress(comp, x, y, mask); } } /** Post a mouse press event to the AWT event queue for the given component. */ private void postMousePress(Component comp, int x, int y, int mask) { long when = lastMousePress != null ? lastMousePress.getWhen() : 0; long now = System.currentTimeMillis(); int count = 1; Point where = new Point(x, y); comp = AWT.retargetMouseEvent(comp, MouseEvent.MOUSE_PRESSED, where); if (countingClicks && comp == lastMousePress.getComponent()) { long delta = now - when; if (delta < AWTConstants.MULTI_CLICK_INTERVAL) { count = state.getClickCount() + 1; } } postEvent(comp, new MouseEvent(comp, MouseEvent.MOUSE_PRESSED, now, state.getKeyModifiers() | mask, where.x, where.y, count, AWTConstants.POPUP_ON_PRESS && (mask & AWTConstants.POPUP_MASK) != 0)); } /** Post a mouse release event to the AWT event queue for the given component. */ private void postMouseRelease(Component c, int x, int y, int mask) { long now = System.currentTimeMillis(); int count = state.getClickCount(); Point where = new Point(x, y); c = AWT.retargetMouseEvent(c, MouseEvent.MOUSE_PRESSED, where); postEvent(c, new MouseEvent(c, MouseEvent.MOUSE_RELEASED, now, state.getKeyModifiers() | mask, where.x, where.y, count, !AWTConstants.POPUP_ON_PRESS && (mask & AWTConstants.POPUP_MASK) != 0)); } /** Click in the center of the given component. */ final public void click(Component comp) { click(comp, comp.getWidth()/2, comp.getHeight()/2); } /** Click in the center of the given component, specifying which button. */ final public void click(Component comp, int mask) { click(comp, comp.getWidth()/2, comp.getHeight()/2, mask); } /** Click in the component at the given location. */ final public void click(Component comp, int x, int y) { click(comp, x, y, InputEvent.BUTTON1_MASK); } /** Click in the component at the given location with the given button. */ final public void click(Component comp, int x, int y, int mask) { click(comp, x, y, mask, 1); } /** Click in the given part of the component. All other click methods * must eventually invoke this one. This method sometimes needs to be * redefined (i.e. JComponent to scroll before clicking). */ public void click(Component comp, int x, int y, int mask, int count) { Log.debug("Click at (" + x + "," + y + ") on " + toString(comp) + (count > 1 ? (" count=" + count) : "")); int keyModifiers = mask & ~AWTConstants.BUTTON_MASK; mask &= AWTConstants.BUTTON_MASK; setModifiers(keyModifiers, true); // Adjust the auto-delay to ensure we actually get a multiple click // In general clicks have to be less than 200ms apart, although the // actual setting is not readable by java that I'm aware of. int oldDelay = getAutoDelay(); if (count > 1 && oldDelay * 2 > 200) { setAutoDelay(0); } long last = System.currentTimeMillis(); mousePress(comp, x, y, mask); while (count-- > 1) { mouseRelease(mask); long delta = System.currentTimeMillis() - last; if (delta > AWTConstants.MULTI_CLICK_INTERVAL) Log.warn("Unexpected delay in multi-click: " + delta); last = System.currentTimeMillis(); mousePress(mask); } setAutoDelay(oldDelay); mouseRelease(mask); setModifiers(keyModifiers, false); } /** @deprecated Renamed to {@link #selectAWTMenuItem(Frame,String)}. */ public void selectAWTMenuItemByLabel(Frame frame, String path) { selectAWTMenuItem(frame, path); } /** Select the given menu item from the given Frame. The given String may be either a label or path of labels, but must uniquely identify the menu item. For example, "Copy" would be valid if there is only one instance of that menu label under the MenuBar, otherwise you would need to specify "Edit|Copy" to ensure the proper selection. Note that this method doesn't require referencing the MenuComponent directly as a parameter. */ public void selectAWTMenuItem(Frame frame, String path) { MenuBar mb = frame.getMenuBar(); if (mb == null) { String msg = Strings.get("tester.Robot.no_menu_bar", new Object[] { toString(frame) }); throw new ActionFailedException(msg); } MenuItem[] items = AWT.findAWTMenuItems(frame, path); if (items.length == 0) { String msg = Strings.get("tester.Robot.no_menu_item", new Object[] { path, toString(frame) }); throw new ActionFailedException(msg); } if (items.length > 1) { String msg = Strings.get("tester.Robot.multiple_menu_items"); throw new ActionFailedException(msg); } selectAWTMenuItem(items[0]); } /** @deprecated Renamed to {@link #selectAWTPopupMenuItem(Component,String)}. */ public void selectAWTPopupMenuItemByLabel(Component invoker, String path) { selectAWTPopupMenuItem(invoker, path); } /** Select the given menu item from a PopupMenu on the given Component. The given String may be either a label or path of labels, but must uniquely identify the menu item. For example, "Copy" would be valid if there is only one instance of that menu label under the MenuBar, otherwise you would need to specify "Edit|Copy" to ensure the proper selection. If there are more than one PopupMenu registerd on the invoking component, you will need to prefix the PopupMenu name as well, e.g. "popup0|Edit|Copy". */ public void selectAWTPopupMenuItem(Component invoker, String path) { try { PopupMenu[] popups = AWT.getPopupMenus(invoker); if (popups.length == 0) throw new ActionFailedException(Strings.get("tester.Robot.awt_popup_missing")); MenuItem[] items = AWT.findAWTPopupMenuItems(invoker, path); if (items.length == 1) { selectAWTPopupMenuItem(items[0]); return; } else if (items.length == 0) { String msg = Strings.get("tester.Robot.no_popup_menu_item", new Object[] { path, toString(invoker) }); throw new ActionFailedException(msg); } String msg = Strings.get("tester.Robot.multiple_menu_items", new Object[] { path }); throw new ActionFailedException(msg); } finally { AWT.dismissAWTPopup(); } } protected void fireAccessibleAction(Component context, final AccessibleAction action, String name) { if (action != null && action.getAccessibleActionCount() > 0) { invokeLater(context, new Runnable() { public void run() { action.doAccessibleAction(0); } }); } else { String msg = Strings.get("tester.Robot.no_accessible_action", new String[] { name }); throw new ActionFailedException(msg); } } private Component getContext(MenuComponent item) { while (!(item.getParent() instanceof Component) && item.getParent() instanceof MenuComponent) item = (MenuComponent)item.getParent(); return (Component)item.getParent(); } /** Select an AWT menu item. */ public void selectAWTMenuItem(MenuComponent item) { // Can't do this through coordinates because MenuComponents don't // store any of that information fireAccessibleAction(getContext(item), item.getAccessibleContext(). getAccessibleAction(), toString(item)); if (queueBlocked()) key(KeyEvent.VK_ESCAPE); } /** Select an AWT popup menu item. */ public void selectAWTPopupMenuItem(MenuComponent item) { // Can't do this through coordinates because MenuComponents don't // store any of that information fireAccessibleAction(getContext(item), item.getAccessibleContext(). getAccessibleAction(), toString(item)); if (queueBlocked()) key(KeyEvent.VK_ESCAPE); } /** Is the given component ready for robot input? */ protected boolean isReadyForInput(Component c) { if (eventMode == EM_AWT) return c.isShowing(); Window w = AWT.getWindow(c); if (w == null) { // throw new ActionFailedException("Component '" + toString(c) // + "' has no Window ancestor"); // Return false in more complicated cases where the component is // visible then not, modifying the code just to return false in this // case // return false; } return c.isShowing() && tracker.isWindowReady(w); } private boolean isOnJMenuBar(Component item) { if (item instanceof javax.swing.JMenuBar) return true; Component parent = item instanceof JPopupMenu ? ((JPopupMenu)item).getInvoker() : item.getParent(); return parent != null && isOnJMenuBar(parent); } /** Find and select the given menu item, by path. */ public void selectMenuItem(Component sameWindow, String path) { Container context=null; String nextPath = null; try { Window window = AWT.getWindow(sameWindow); java.util.List selectionPath = JMenuItemMatcher.splitMenuPath(path); // For each path entry select in turn to make sure we trigger // any lazy loading // int i = selectionPath.size(); context = window; for (int j = 0; j < i; j++) { // If we are at the last item then we are looking // for a menu item, otherwise we are looking for // a menu instead // nextPath = (String)selectionPath.get(j); final ComponentFinder cf = BasicFinder.getDefault(); final Matcher m = (j == i -1) ? new JMenuItemMatcher(nextPath) : new JMenuMatcher(nextPath); final Container innerContext = context; // For the inner class final Holder<Component> foundHolder = new Holder<Component>(); final Holder<ComponentNotFoundException> cnfHolder = new Holder<ComponentNotFoundException>(); final Holder<MultipleComponentsFoundException> mcfHolder = new Holder<MultipleComponentsFoundException>(); try { wait(new Condition(){ @Override public boolean test() { try { final Component component = cf.find(innerContext, m); foundHolder.value = component; return component != null; } catch (ComponentNotFoundException e) { cnfHolder.value = e; return false; } catch (MultipleComponentsFoundException e) { mcfHolder.value = e; return false; } } }); } catch (WaitTimedOutException wtoe) { // Rethrow any exceptions if (mcfHolder.value!=null) { throw mcfHolder.value; } if (cnfHolder.value!=null) { throw cnfHolder.value; } } // Don't care about the hierarchy on this one, since there'll only // ever be one popup active at a time. Component item = foundHolder.value; selectMenuItem(item); waitForIdle(); context = (Container)item; } } catch(ComponentNotFoundException e) { throw new ComponentMissingException("Can't find menu item '" + path + "' by looking for '" + nextPath + "' in " + context,e); } catch(MultipleComponentsFoundException e) { throw new ActionFailedException(e.getMessage()); } } /** Find and select the given menu item. */ public void selectMenuItem(Component item) { Log.debug("Selecting menu item " + toString(item)); Component parent = item.getParent(); JPopupMenu parentPopup = null; if (parent instanceof JPopupMenu) { parentPopup = (JPopupMenu)parent; parent = ((JPopupMenu)parent).getInvoker(); } boolean inMenuBar = parent instanceof javax.swing.JMenuBar; boolean isMenu = item instanceof javax.swing.JMenu; if (isOnJMenuBar(item) && useScreenMenuBar()) { // Use accessibility action instead fireAccessibleAction(item, item.getAccessibleContext(). getAccessibleAction(), toString(item)); return; } // If our parent is a menu, activate it first, if it's not already. if (parent instanceof javax.swing.JMenuItem) { if (parentPopup == null || !parentPopup.isShowing()) { Log.debug("Opening parent menu " + toString(parent)); selectMenuItem(parent); } } // Make sure the appropriate window is in front if (inMenuBar) { final Window win = AWT.getWindow(parent); if (win != null) { // Make sure the window is in front, or its menus may be // obscured by another window. invokeAndWait(win, new Runnable() { public void run() { win.toFront(); } }); // toFront might have side effects such as focus grabbing, make sure the event queue is idle // before we try to do anything else waitForIdle(); // mouseMove(win); } } // Activate the item if (isMenu && !inMenuBar) { // Submenus only require a mouse-over to activate, but do // a click to be certain if (subMenuDelay > autoDelay) { delay(subMenuDelay - autoDelay); } } // Top-level menus and menu items *must* be clicked on Log.debug("Activating menu item " + toString(item)); if (!item.isEnabled()) { throw new ActionFailedException("Menu item " + toString(item) + " is disabled"); } // Try showing the menu item twice try { showMenuItemAndMakeVisible(item, isMenu); } catch (ComponentMissingException cme) { // Try again showMenuItemAndMakeVisible(item, isMenu); } } /** * I extracted the coda of the selectMenuItem method so we can retry one * if we fail, this is to try and work around an irritating intermittent * failure where the menu is not shown. * @param item * @param isMenu */ private void showMenuItemAndMakeVisible(Component item, boolean isMenu) { // Try to bring up the menu item click(item); waitForIdle(); // If this item is a menu, make sure its popup is showing before we // return if (isMenu) { JPopupMenu popup = ((javax.swing.JMenu)item).getPopupMenu(); if (!waitForComponent(popup, popupDelay, popupJitterDelay)) { String msg = "Clicking on '" + ((javax.swing.JMenu)item).getText() + "' never produced a popup menu"; throw new ComponentMissingException(msg); } // for OSX 1.4.1; isShowing set before popup is available if (subMenuDelay > autoDelay) { delay(subMenuDelay - autoDelay); } } } public void selectPopupMenuItem(Component invoker, ComponentLocation loc, String path) { Point where = loc.getPoint(invoker); if (where.x == -1) where.x = invoker.getWidth()/2; if (where.y == -1) where.y = invoker.getHeight()/2; Component popup = showPopupMenu(invoker, where.x, where.y); try { java.util.List selectionPath = JMenuItemMatcher.splitMenuPath(path); // For each path entry select in turn to make sure we trigger // any lazy loading // Container context = (Container)popup; int i = selectionPath.size(); for (int j = 0; j < i; j++) { Matcher m = new JMenuItemMatcher( (String)selectionPath.get(j)); // Don't care about the hierarchy on this one, since there'll only // ever be one popup active at a time. Component item = BasicFinder.getDefault(). find(context, m); selectMenuItem(item); waitForIdle(); context = (Container)item; } } catch(ComponentNotFoundException e) { throw new ComponentMissingException("Can't find menu item '" + path + "'"); } catch(MultipleComponentsFoundException e) { throw new ActionFailedException(e.getMessage()); } } /** Attempt to display a popup menu at center of the component. */ public Component showPopupMenu(Component invoker) { return showPopupMenu(invoker, invoker.getWidth()/2, invoker.getHeight()/2); } /** Attempt to display a popup menu at the given coordinates. */ public Component showPopupMenu(Component invoker, int x, int y) { String where = " at (" + x + "," + y + ")"; int retryCount = popupRetry; ComponentMissingException cme = null; sucess: while ((--retryCount) >= 0) { try { cme = null; Log.debug("Invoking popup " + where + " repeats left " + retryCount); showPopupMenuIntl(invoker, x, y, where); break sucess; } catch (ComponentMissingException cme2) { if (cme2.getMessage().contains("POPUP_MASK")) { Log.warn("Invoking popup failed, repeats left " + retryCount); //Take a breath waitForIdle(); delay(2000); // Hold and possibly repeat the action cme = cme2; } else { throw cme2; } } } // Throw the exception if it has failed at some point if (cme!=null) { throw cme; } // Wait for UI to be ready // Component popup = AWT.findActivePopupMenu(); long start = System.currentTimeMillis(); while (!isReadyForInput(SwingUtilities.getWindowAncestor(popup)) && System.currentTimeMillis() - start > popupDelay) { sleep(); } return popup; } /** For the moment refactor this out so we can retry if this fails **/ private void showPopupMenuIntl(Component invoker, int x, int y, String where) { click(invoker, x, y, AWTConstants.POPUP_MASK); try { wait(new Condition() { public boolean test() { return AWT.findActivePopupMenu()!=null; } public String toString() { return "Cannot find popup menu"; } }, popupDelay, SLEEP_INTERVAL * 4); } catch (WaitTimedOutException wtoe) { String msg = "No popup responded to " + AWTConstants.POPUP_MODIFIER + where + " on " + toString(invoker); throw new ComponentMissingException(msg); } } /** Activate the given window. */ public void activate(final Window win) { Window originalActiveWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager(). getActiveWindow(); if (win==originalActiveWindow) { return; } else if (originalActiveWindow!=null && originalActiveWindow.getParent() == win && AWT.isHeavyweightPopup(originalActiveWindow)) { return; // If we have a popup window on the current window } class ActivateWatcher extends WindowAdapter { volatile boolean active; public ActivateWatcher() { active = callAndWait(win, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return win.isActive(); } }); } @Override public void windowActivated(WindowEvent e) { active = true; } } final ActivateWatcher aw = new ActivateWatcher(); try { // Add listener to check we have an active window invokeAndWait(win, new Runnable() { public void run() { // FIXME figure out why two are sometimes needed win.addWindowListener(aw); } }); // ACTIVATE means window gets keyboard focus. invokeAndWait(win, new Runnable() { // FIXME figure out why two are sometimes needed public void run() { win.toFront(); win.toFront(); } }); // Check this window becomes active try { wait(new ConditionEDTDecorator(win, new Condition() { @Override public boolean test() { return aw.active; } }), componentDelay); } catch (WaitTimedOutException wte) { Window active = KeyboardFocusManager.getCurrentKeyboardFocusManager(). getActiveWindow(); String msg = Strings.get("tester.Robot.activate_failed", new Object[] { toString(win) }); throw new ActionFailedException(msg, wte); } waitForIdle(); // For pointer-focus systems mouseMove(win); } finally { // remove listener to check we have an active window invokeAndWait(win, new Runnable() { public void run() { win.removeWindowListener(aw); } }); } } protected Point getCloseLocation(Container c) { Dimension size = c.getSize(); Insets insets = c.getInsets(); if (Platform.isOSX()) { return new Point(insets.left + 15, insets.top / 2); } return new Point(size.width - insets.right - 10, insets.top / 2); } /** Invoke the window close operation. */ public void close(Window w) { if (w.isShowing()) { // Move to a corner and "pretend" to use the window manager // control try { Point p = getCloseLocation(w); mouseMove(w, p.x, p.y); } catch(Exception e) { // ignore } WindowEvent ev = new WindowEvent(w, WindowEvent.WINDOW_CLOSING); // If the window contains an applet, send the event on the // applet's queue instead to ensure a shutdown from the // applet's context (assists AppletViewer cleanup). Component applet = AWT.findAppletDescendent(w); EventQueue eq = tracker.getQueue(applet != null ? applet : w); eq.postEvent(ev); } } /** Return where the mouse usually grabs to move a window. Center of the * top of the frame is usually a good choice. */ protected Point getMoveLocation(Container c) { Dimension size = c.getSize(); Insets insets = c.getInsets(); return new Point(size.width/2, insets.top/2); } /** Move the given Frame/Dialog to the requested location. */ public void move(Container comp, int newx, int newy) { Point loc = AWT.getLocationOnScreen(comp); moveBy(comp, newx - loc.x, newy - loc.y); } /** Move the given Window by the given amount. */ public void moveBy(final Container comp, final int dx, final int dy) { final Point loc = AWT.getLocationOnScreen(comp); boolean userMovable = userMovable(comp); if (userMovable) { Point p = getMoveLocation(comp); mouseMove(comp, p.x, p.y); mouseMove(comp, p.x + dx, p.y + dy); } invokeAndWait(comp, new Runnable() { public void run() { comp.setLocation(new Point(loc.x + dx, loc.y + dy)); } }); if (userMovable) { Point p = getMoveLocation(comp); mouseMove(comp, p.x, p.y); } } /** Return where the mouse usually grabs to resize a window. The lower * right corner of the window is usually a good choice. */ protected Point getResizeLocation(Container c) { Dimension size = c.getSize(); Insets insets = c.getInsets(); return new Point(size.width-insets.right/2, size.height-insets.bottom/2); } /** Return whether it is possible for the user to move the given component. */ protected boolean userMovable(Component comp) { return comp instanceof Dialog || comp instanceof Frame || canMoveWindows(); } /** Return whether it is possible for the user to resize the given component. */ protected boolean userResizable(Component comp) { if (comp instanceof Dialog) return ((Dialog)comp).isResizable(); if (comp instanceof Frame) return ((Frame)comp).isResizable(); // most X11 window managers allow arbitrary resizing return canResizeWindows(); } /** Resize the given Frame/Dialog to the given size. */ public void resize(Container comp, int width, int height) { Dimension size = comp.getSize(); resizeBy(comp, width - size.width, height - size.height); } /** Resize the given Frame/Dialog by the given amounts. */ public void resizeBy(final Container comp, final int dx, final int dy) { // Fake the pointer motion like we're resizing boolean userResizable = userResizable(comp); if (userResizable) { Point p = getResizeLocation(comp); mouseMove(comp, p.x, p.y); mouseMove(comp, p.x + dx, p.y + dy); } invokeAndWait(comp, new Runnable() { public void run() { comp.setSize(comp.getWidth()+dx, comp.getHeight()+dy); } }); if (userResizable) { Point p = getResizeLocation(comp); mouseMove(comp, p.x, p.y); } } /** Identify the coordinates of the iconify button where we can, returning * (0, 0) if we can't. */ protected Point getIconifyLocation(Container c) { Dimension size = c.getSize(); Insets insets = c.getInsets(); // We know the exact layout of the window manager frames for w32 and // OSX. Currently no way of detecting the WM under X11. Maybe we // could send a WM message (WM_ICONIFY)? Point loc = new Point(); loc.y = insets.top / 2; if (Platform.isOSX()) { loc.x = 35; } else if (Platform.isWindows()) { int offset = Platform.isWindowsXP() ? 64 : 45; loc.x = size.width - insets.right - offset; } return loc; } private static final int MAXIMIZE_BUTTON_OFFSET = Platform.isOSX() ? 25 : Platform.isWindows() ? -20 : 0; /** Identify the coordinates of the maximize button where possible, returning null if not. */ protected Point getMaximizeLocation(Container c) { Point loc = getIconifyLocation(c); loc.x += MAXIMIZE_BUTTON_OFFSET; return loc; } /** Iconify the given Frame. Don't support iconification of Dialogs at * this point (although maybe should). */ public void iconify(final Frame frame) { Point loc = getIconifyLocation(frame); if (loc != null) { mouseMove(frame, loc.x, loc.y); } invokeAndWait(frame, new Runnable() { public void run() { frame.setState(Frame.ICONIFIED); } }); // Wait for the event queue to settle down after this // waitForIdle(); } public void deiconify(Frame frame) { normalize(frame); } public void normalize(final Frame frame) { invokeAndWait(frame, new Runnable() { public void run() { frame.setState(Frame.NORMAL); if (Bugs.hasFrameDeiconifyBug()) frame.setVisible(true); } }); // Wait for the event queue to settle down after this // waitForIdle(); } /** Make the window full size. On 1.3.1, this is not reversible. */ public void maximize(final Frame frame) { Point loc = getMaximizeLocation(frame); if (loc != null) { mouseMove(frame, loc.x, loc.y); } invokeAndWait(frame, new Runnable() { public void run() { // If the maximize is unavailable, set to full screen size // instead. try { if (toolkit.isFrameStateSupported(Frame.MAXIMIZED_BOTH) && !serviceMode) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } else { throw new ActionFailedException("Platform won't maximize"); } } catch(Exception e) { Log.debug("Maximize not supported: " + e); Rectangle rect = frame.getGraphicsConfiguration().getBounds(); frame.setLocation(rect.x, rect.y); frame.setSize(rect.width, rect.height); } } }); // Wait for the event queue to settle down after this // waitForIdle(); } /** Send the given event as appropriate to the event-generation mode. */ public void sendEvent(AWTEvent event) { // Modifiers are ignored, assuming that an event will be // sent that causes modifiers to be sent appropriately. if (eventMode == EM_ROBOT) { int id = event.getID(); Log.debug("Sending event id " + id); if (id >= MouseEvent.MOUSE_FIRST && id <= MouseEvent.MOUSE_LAST) { MouseEvent me = (MouseEvent)event; Component comp = me.getComponent(); if (id == MouseEvent.MOUSE_MOVED) { mouseMove(comp, me.getX(), me.getY()); } else if (id == MouseEvent.MOUSE_DRAGGED) { mouseMove(comp, me.getX(), me.getY()); } else if (id == MouseEvent.MOUSE_PRESSED) { mouseMove(comp, me.getX(), me.getY()); mousePress(me.getModifiers() & AWTConstants.BUTTON_MASK); } else if (id == MouseEvent.MOUSE_ENTERED) { mouseMove(comp, me.getX(), me.getY()); } else if (id == MouseEvent.MOUSE_EXITED) { mouseMove(comp, me.getX(), me.getY()); } else if (id == MouseEvent.MOUSE_RELEASED) { mouseMove(comp, me.getX(), me.getY()); mouseRelease(me.getModifiers() & AWTConstants.BUTTON_MASK); } } else if (id >= KeyEvent.KEY_FIRST && id <= KeyEvent.KEY_LAST) { KeyEvent ke = (KeyEvent)event; if (id == KeyEvent.KEY_PRESSED) { keyPress(ke.getKeyCode()); } else if (id == KeyEvent.KEY_RELEASED) { keyRelease(ke.getKeyCode()); } } else { Log.warn("Event not supported: " + event); } } else { // Post the event to the appropriate AWT event queue postEvent((Component)event.getSource(), event); } } /** Return the symbolic name of the given event's ID. */ public static String getEventID(AWTEvent event) { // Optimize here to avoid field name lookup overhead switch(event.getID()) { case MouseEvent.MOUSE_MOVED: return "MOUSE_MOVED"; case MouseEvent.MOUSE_DRAGGED: return "MOUSE_DRAGGED"; case MouseEvent.MOUSE_PRESSED: return "MOUSE_PRESSED"; case MouseEvent.MOUSE_CLICKED: return "MOUSE_CLICKED"; case MouseEvent.MOUSE_RELEASED: return "MOUSE_RELEASED"; case MouseEvent.MOUSE_ENTERED: return "MOUSE_ENTERED"; case MouseEvent.MOUSE_EXITED: return "MOUSE_EXITED"; case KeyEvent.KEY_PRESSED: return "KEY_PRESSED"; case KeyEvent.KEY_TYPED: return "KEY_TYPED"; case KeyEvent.KEY_RELEASED: return "KEY_RELEASED"; case WindowEvent.WINDOW_OPENED: return "WINDOW_OPENED"; case WindowEvent.WINDOW_CLOSING: return "WINDOW_CLOSING"; case WindowEvent.WINDOW_CLOSED: return "WINDOW_CLOSED"; case WindowEvent.WINDOW_ICONIFIED: return "WINDOW_ICONIFIED"; case WindowEvent.WINDOW_DEICONIFIED: return "WINDOW_DEICONIFIED"; case WindowEvent.WINDOW_ACTIVATED: return "WINDOW_ACTIVATED"; case WindowEvent.WINDOW_DEACTIVATED: return "WINDOW_DEACTIVATED"; case ComponentEvent.COMPONENT_MOVED: return "COMPONENT_MOVED"; case ComponentEvent.COMPONENT_RESIZED: return "COMPONENT_RESIZED"; case ComponentEvent.COMPONENT_SHOWN: return "COMPONENT_SHOWN"; case ComponentEvent.COMPONENT_HIDDEN: return "COMPONENT_HIDDEN"; case FocusEvent.FOCUS_GAINED: return "FOCUS_GAINED"; case FocusEvent.FOCUS_LOST: return "FOCUS_LOST"; case HierarchyEvent.HIERARCHY_CHANGED: return "HIERARCHY_CHANGED"; case HierarchyEvent.ANCESTOR_MOVED: return "ANCESTOR_MOVED"; case HierarchyEvent.ANCESTOR_RESIZED: return "ANCESTOR_RESIZED"; case PaintEvent.PAINT: return "PAINT"; case PaintEvent.UPDATE: return "UPDATE"; case ActionEvent.ACTION_PERFORMED: return "ACTION_PERFORMED"; case InputMethodEvent.CARET_POSITION_CHANGED: return "CARET_POSITION_CHANGED"; case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: return "INPUT_METHOD_TEXT_CHANGED"; default: return Reflector.getFieldName(event.getClass(), event.getID(), ""); } } public static Class getCanonicalClass(Class refClass) { // Don't use classnames from anonymous inner classes... // Don't use classnames from platform LAF classes... String className = refClass.getName(); while (className.indexOf("$") != -1 || className.startsWith("javax.swing.plaf") || className.startsWith("com.apple.mrj")) { refClass = refClass.getSuperclass(); className = refClass.getName(); } return refClass; } /** Provides a more concise representation of the component than the * default Component.toString(). */ public static String toString(Component comp) { if (comp == null) return "(null)"; if (AWT.isTransientPopup(comp)) { boolean tooltip = AWT.isToolTip(comp); if (AWT.isHeavyweightPopup(comp)) { return tooltip ? Strings.get("component.heavyweight_tooltip") : Strings.get("component.heavyweight_popup"); } else if (AWT.isLightweightPopup(comp)) { return tooltip ? Strings.get("component.lightweight_tooltip") : Strings.get("component.lightweight_popup"); } } else if (AWT.isSharedInvisibleFrame(comp)) { return Strings.get("component.default_frame"); } String name = getDescriptiveName(comp); String classDesc = descriptiveClassName(comp.getClass()); if (name == null) { if (AWT.isContentPane(comp)) { name = Strings.get("component.content_pane"); } else if (AWT.isGlassPane(comp)) { name = Strings.get("component.glass_pane"); } else if (comp instanceof JLayeredPane) { name = Strings.get("component.layered_pane"); } else if (comp instanceof JRootPane) { name = Strings.get("component.root_pane"); } else { name = classDesc + " instance"; } } else { name = "'" + name + "' (" + classDesc + ")"; } return name; } /** Provide a string representation of the given component (Component or * MenuComponent. */ public static String toString(Object obj) { if (obj instanceof Component) return toString((Component)obj); else if (obj instanceof MenuBar) return "MenuBar"; else if (obj instanceof MenuItem) return ((MenuItem)obj).getLabel(); return obj.toString(); } protected static String descriptiveClassName(Class cls) { StringBuffer desc = new StringBuffer(simpleClassName(cls)); Class coreClass = getCanonicalClass(cls); String coreClassName = coreClass.getName(); while (!coreClassName.startsWith("java.awt.") && !coreClassName.startsWith("javax.swing.") && !coreClassName.startsWith("java.applet.")) { coreClass = coreClass.getSuperclass(); coreClassName = coreClass.getName(); } if (!coreClass.equals(cls)) { desc.append("/"); desc.append(simpleClassName(coreClass)); } return desc.toString(); } /** Provides the hierarchic path of the given component by component class, e.g. "JFrame:JRootPane:JPanel:JButton". */ public static String toHierarchyPath(Component c) { StringBuffer buf = new StringBuffer(); Container parent = c.getParent(); if (parent != null) { buf.append(toHierarchyPath(parent)); buf.append(":"); } buf.append(descriptiveClassName(c.getClass())); String name = getDescriptiveName(c); if (name != null) { buf.append("("); buf.append(name); buf.append(")"); } else if (parent != null && parent.getComponentCount() > 1 && c instanceof JPanel) { buf.append("["); buf.append(String.valueOf(getIndex(parent, c))); buf.append("]"); } return buf.toString(); } /** Provide a more concise representation of the event than the default * AWTEvent.toString(). */ public static String toString(AWTEvent event) { String name = toString(event.getSource()); String desc = getEventID(event); if (event.getID() == KeyEvent.KEY_PRESSED || event.getID() == KeyEvent.KEY_RELEASED) { KeyEvent ke = (KeyEvent)event; desc += " (" + AWT.getKeyCode(ke.getKeyCode()); if (ke.getModifiers() != 0) { desc += "/" + AWT.getKeyModifiers(ke.getModifiers()); } desc += ")"; } else if (event.getID() == InputMethodEvent.INPUT_METHOD_TEXT_CHANGED) { desc += " (" + ((InputMethodEvent)event).getCommittedCharacterCount() + ")"; } else if (event.getID() == KeyEvent.KEY_TYPED) { char ch = ((KeyEvent)event).getKeyChar(); int mods = ((KeyEvent)event).getModifiers(); desc += " ('" + ch + (mods != 0 ? "/" + AWT.getKeyModifiers(mods) : "") + "')"; } else if (event.getID() >= MouseEvent.MOUSE_FIRST && event.getID() <= MouseEvent.MOUSE_LAST) { MouseEvent me = (MouseEvent)event; if (me.getModifiers() != 0) { desc += " <" + AWT.getMouseModifiers(me.getModifiers()); if (me.getClickCount() > 1) { desc += "," + me.getClickCount(); } desc += ">"; } desc += " (" + me.getX() + "," + me.getY() + ")"; } else if (event.getID() == HierarchyEvent.HIERARCHY_CHANGED) { HierarchyEvent he = (HierarchyEvent)event; long flags = he.getChangeFlags(); String type = ""; String bar = ""; if ((flags & HierarchyEvent.SHOWING_CHANGED) != 0) { type += (he.getComponent().isShowing() ? "" : "!") + "SHOWING"; bar = "|"; } if ((flags & HierarchyEvent.PARENT_CHANGED) != 0) { type += bar + "PARENT:" + toString(he.getComponent().getParent()); bar = "|"; } if ((flags & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) { type += bar + "DISPLAYABILITY"; } desc += " (" + type + ")"; } return desc + " on " + name; } /** Return the numeric event ID corresponding to the given string. */ public static int getEventID(Class cls, String id) { return Reflector.getFieldValue(cls, id); } /** Strip the package from the class name. */ public static String simpleClassName(Class cls) { String name = cls.getName(); int dot = name.lastIndexOf("."); return name.substring(dot+1, name.length()); } private AWTEvent lastEventPosted = null; private MouseEvent lastMousePress = null; private boolean countingClicks = false; /** Post the given event to the corresponding event queue for the given component. */ protected void postEvent(Component comp, AWTEvent ev) { if (Log.isClassDebugEnabled(Robot.class)) Log.debug("POST: " + toString(ev)); if (eventMode == EM_AWT && AWT.isAWTPopupMenuBlocking()) { throw new Error("Event queue is blocked by an active AWT PopupMenu"); } // Force an update of the input state, so that we're in synch // internally. Otherwise we might post more events before this // one gets processed and end up using stale values for those events. state.update(ev); EventQueue q = getEventQueue(comp); q.postEvent(ev); delay(autoDelay); AWTEvent prev = lastEventPosted; lastEventPosted = ev; if (ev instanceof MouseEvent) { if (ev.getID() == MouseEvent.MOUSE_PRESSED) { lastMousePress = (MouseEvent)ev; countingClicks = true; } else if (ev.getID() != MouseEvent.MOUSE_RELEASED && ev.getID() != MouseEvent.MOUSE_CLICKED) { countingClicks = false; } } // Generate a click if there are no events between press/release // Unfortunately, I can only guess how the VM generates them if (eventMode == EM_AWT && ev.getID() == MouseEvent.MOUSE_RELEASED && prev.getID() == MouseEvent.MOUSE_PRESSED) { MouseEvent me = (MouseEvent)ev; AWTEvent click = new MouseEvent(comp, MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), me.getModifiers(), me.getX(), me.getY(), me.getClickCount(), false); postEvent(comp, click); } } /**Wait for the given Condition to return true. The default timeout may * be changed by setting abbot.robot.default_delay. * @throws WaitTimedOutException if the default timeout (30s) is exceeded. * @see Robot#wait(Condition,long,int) Robot.wait For a description of the use of this function to support lazy loading in class files */ public static void wait(Condition condition) { wait(condition, defaultDelay); } /**Wait for the given Condition to return true, waiting for timeout ms. * @throws WaitTimedOutException if the timeout is exceeded. * @see Robot#wait(Condition,long,int) Robot.wait For a description of the use of this function to support lazy loading in class files */ public static void wait(Condition condition, long timeout) { wait(condition, timeout, SLEEP_INTERVAL); } /** * Wait for the given Condition to return true, waiting for timeout ms, * polling at the given interval. This method can be used generically to * support components that are lazily loaded in the context of writing * testers or other testing code. * <p> * Take for example the simple case of trying to select an item in a list. * If the model for this list is populate asynchronously then you may need * to poll the list for a given amount of time until the item appears. This * is very common in an application that contains many long running tasks. * <p> * A general solution to the problem can be seen in this pseudo code: * <pre> * wait(new Condition() * { * public boolean test() * { * return whether the ui element is avaliable * } * }); * performAction(ui element); * </pre> * <p> * If you are writing a tester method then it is a good idea to use a standard * timeout such as {@link Robot#componentDelay}to ensure they are consistently * handled accross different testers. * * @throws WaitTimedOutException if the timeout is exceeded. */ public static void wait(Condition condition, long timeout, int interval) { // Make sure the robot is running initializeRobot(); // long start = System.currentTimeMillis(); while (!condition.test()) { if (Thread.interrupted()) { throw new InterruptedAbbotException("Interrupted waiting for " + condition); } if (System.currentTimeMillis() - start > timeout) { String msg = "Timed out waiting for " + condition; throw new WaitTimedOutException(msg); } delay(interval); } } public void reset() { if (eventMode == EM_ROBOT) { Dimension d = toolkit.getScreenSize(); mouseMove(d.width/2, d.height/2); mouseMove(d.width/2-1, d.height/2-1); } else { // clear any held state state.clear(); } } /** * Helper function to invoke callable statement on EDT * @param callable The code to invoke * @param context The conext component to fetch the event queue from * @return */ public static <T> T callAndWait(Component context, Callable<T> callable) { return callAndWait(context, callable, componentDelay); } /** * Helper function to invoke callable statement on EDT * @param callable The code to invoke * @param context The conext component to fetch the event queue from * @return */ public static <T> T callAndWait(Component context, Callable<T> callable, long timeout) { EventQueue queue = getEventQueue(context); // It turns out that getEventQueue doesn't always keep up with // the changing queue situations so the safest route is to just // see if the current thread in the event queue, if so it should // be safe to invoke directly // // It turns out that EventQueue.isDispatchThread can sometimes lie // if we are in the process of shutting down one thread and poppping // on the other as in the case of Abbot Thread currentThread = Thread.currentThread(); final Class threadClass = currentThread.getClass(); boolean runAsIfThisIsDispatchThread; try { Class clzz = Class.forName("java.awt.EventDispatchThread"); runAsIfThisIsDispatchThread = clzz.isAssignableFrom(threadClass); } catch (ClassNotFoundException e) { runAsIfThisIsDispatchThread = EventQueue.isDispatchThread() && queue == getEventQueue(null); } // Now we have a problem in some test case for example creating a new JFrame on a non event // queue is causing problems, this is a valid case as setVisible or pack as not been called // but it means that the Tree lock is going to be held by another thread temporarily // So we need to test for that and if this is the case then run sychornously as the event // queue will get stuck until this is release. if (context!=null && Thread.holdsLock(context.getTreeLock())) { runAsIfThisIsDispatchThread = true; } try { // Just invoke if we are on the same EDT as the component if (runAsIfThisIsDispatchThread) { return callable.call(); } else { // TODO make sure we use the correct event queue, this method should not be eventually be static // FutureTask<T> ft = new FutureTask<T>(callable); // queue.postEvent(new InvocationEvent(toolkit, ft)); // try { return ft.get( timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException te) { ft.cancel(true); throw new CallTimoutFailedException("Failure to run process on event queue, is it blocked?", te); } } } catch (CallTimoutFailedException e) { throw e; } catch (ExecutionException e) { throw new FailedException("Failure to run process on event queue", e.getCause()); } catch (Exception e) { throw new FailedException("Failure to run process on event queue", e); } } /** * Helper class that invokes a conditions on the EDT */ public static class ConditionEDTDecorator implements Condition { private Condition condition; private Component component; public ConditionEDTDecorator(Component context, Condition condition) { super(); this.condition = condition; this.component = context; } public boolean test() { return callAndWait(component, new Callable<Boolean>() { public Boolean call() { return condition.test() ? Boolean.TRUE : Boolean.FALSE; } }) == Boolean.TRUE; } public String toString() { return "EDT Decorator:\n " + callAndWait(component, new Callable<String>() { @Override public String call() throws Exception { return condition.toString(); } }); } } /** Return the Component which currently owns the focus. */ public Component findFocusOwner() { return AWT.getFocusOwner(); } /** Return a descriptive name for the given component for use in UI * text (may be localized if appropriate and need not be re-usable * across locales. */ public static String getDescriptiveName(Component c) { if (AWT.isSharedInvisibleFrame(c)) return Strings.get("component.default_frame"); String name = getName(c); if (name == null) { if ((name = getTitle(c)) == null) { if ((name = getText(c)) == null) { if ((name = getLabel(c)) == null) { if ((name = getIconName(c)) == null) { } } } } } return name; } public static String getName(Component c) { String name = AWT.hasDefaultName(c) ? null : c.getName(); // Accessibility behaves like what we used to do with getTag. // Not too helpful for our purposes, especially when the // data on which the name is based might be dynamic. /* if (name == null) { AccessibleContext context = c.getAccessibleContext(); if (context != null) name = context.getAccessibleName(); } */ return name; } /** Returns the index of the given component within the given container. */ public static int getIndex(Container parent, Component comp) { if (comp instanceof Window) { // getOwnedWindows is protoected by a synchronized block so this // is probably safe to call // Window[] owned = ((Window)parent).getOwnedWindows(); for (int i=0;i < owned.length;i++) { if (owned[i] == comp) { return i; } } } else { // Getting a list of components need to be protected by the tree lock // at least possibility if this is a problem then we are going to // have to do a callAndWait instead. // synchronized(comp.getTreeLock()) { Component[] children = parent.getComponents(); for (int i = 0; i < children.length; ++i) { if (children[i] == comp) { return i; } } } } return -1; } public static String getText(final Component c) { if (c instanceof AbstractButton) { return ComponentTester.stripHTML(((AbstractButton)c).getText()); } else if (c instanceof JLabel) { return ComponentTester.stripHTML(((JLabel)c).getText()); } else if (c instanceof Label) { return ((Label)c).getText(); } return null; } public static String getLabel(Component c) { String label = null; if (c instanceof JComponent) { Object obj = ((JComponent)c).getClientProperty(LABELED_BY_PROPERTY); // While the default is a JLabel, users may use something else as // the property, so be careful. if (obj != null) { if (obj instanceof JLabel) { label = ((JLabel)obj).getText(); } else if (obj instanceof String) { label = (String)obj; } } } else if (c instanceof Button) { label = ((Button)c).getLabel(); } else if (c instanceof Checkbox) { label = ((Checkbox)c).getLabel(); } return ComponentTester.stripHTML(label); } private static final Object ACCESSIBLE_CONTEXT_CACHE = new Object() {}; public static String getIconName(final Component c) { if (c instanceof JComponent) { // So we had a case where getting hold of the AccessibleContext was causing // work to be done off the event queue; but invoking this code everytime on a particular // component proved to be expense, so using a clientProperty to cache this value, just // calling the method the first time should it not exist. Appears to be a safe thing // to do after a brief review of the swing classes AccessibleContext ac = (AccessibleContext)((JComponent)c).getClientProperty(ACCESSIBLE_CONTEXT_CACHE); // if (ac==null) { ac = callAndWait(c, new Callable<AccessibleContext>() { public AccessibleContext call() { AccessibleContext accessibleContext = c.getAccessibleContext(); ((JComponent)c).putClientProperty(ACCESSIBLE_CONTEXT_CACHE, accessibleContext); return accessibleContext; } }); } else { int i = 0; } // Otherwise we need to access the accessible context return getIconName(ac); } else { // Just don't think this will happen very much return getIconName(c.getAccessibleContext()); } } private static String getIconName(AccessibleContext context) { String icon = null; if (context != null) { AccessibleIcon[] icons = context.getAccessibleIcon(); if (icons != null && icons.length > 0) { icon = icons[0].getAccessibleIconDescription(); if (icon != null) { icon = icon.substring(icon.lastIndexOf("/") + 1); icon = icon.substring(icon.lastIndexOf("\\") + 1); } } } return icon; } public static String getBorderTitle(Component c) { String title = null; if (c instanceof JComponent) { title = getBorderTitle(((JComponent)c).getBorder()); } return title; } /** See javax.swing.JComponent.getBorderTitle. */ private static String getBorderTitle(Border b) { String title = null; if (b instanceof TitledBorder) title = ((TitledBorder)b).getTitle(); else if (b instanceof CompoundBorder) { title = getBorderTitle(((CompoundBorder)b).getInsideBorder()); if (title == null) { title = getBorderTitle(((CompoundBorder)b).getOutsideBorder()); } } return title; } public static String getTitle(Component c) { if (c instanceof Dialog) return ((Dialog)c).getTitle(); else if (c instanceof Frame) return ((Frame)c).getTitle(); else if (c instanceof JInternalFrame) return ((JInternalFrame)c).getTitle(); return null; } /** Returns whether it is possible to resize windows that are not an instance of Frame or Dialog. Most X11 window managers will allow this, but stock Macintosh and Windows do not. */ public static boolean canResizeWindows() { return !Platform.isWindows() && !Platform.isMacintosh(); } /** Returns whether it is possible to move windows that are not an instance of Frame or Dialog. Most X11 window managers will allow this, but stock Macintosh and Windows do not. */ public static boolean canMoveWindows() { return !Platform.isWindows() && !Platform.isMacintosh(); } /** Returns the appropriate auto delay for robot-generated events. */ public static int getPreferredRobotAutoDelay() { // better safe than sorry, and slower and accurate than // fast and inaccurate. /* if (Platform.isWindows() || Platform.isOSX() || Platform.isX11()) return 0; */ // >= 40 causes problems registering a double-click when clicks // are requested separately (due to auto-jitter and other delay // being added on individual clicks). return 30; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/RobotVerifier.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import abbot.util.Bugs; /** Provides methods to verify that the robot on the current platform works * properly. */ public class RobotVerifier { // No instantiations private RobotVerifier() { } private static final String WINDOW_NAME = "Abbot Robot Verification"; /** Auto-detect whether the robot actually works. Use this to tell whether we're in w32 service mode without access to the desktop. @return false if the robot fails. */ public static boolean verify(java.awt.Robot robot) { if (!Bugs.needsRobotVerification()) return true; final int SIZE = 4; Frame f = new Frame(WINDOW_NAME); f.setName(WINDOW_NAME); try { Window w = new Window(f); Color color = new Color(0, 1, 2); w.setBackground(color); w.setName(WINDOW_NAME); w.pack(); // Need try/finally after a pack as component is now allocated. try { w.setSize(SIZE, SIZE); w.setLocation(100, 100); w.setVisible(true); robot.waitForIdle(); WindowTracker tracker = WindowTracker.getTracker(); while (!tracker.isWindowReady(w)) { robot.delay(20); } Color sample = robot.getPixelColor(100, 100); return sample.equals(color); } finally { w.setVisible(false); w.dispose(); } } finally { f.dispose(); } } /** Quick printout of whether the robot works. */ public static void main(String[] args) { try { boolean works = verify(new java.awt.Robot()); System.out.println("Robot is " + (works ? "" : "not ") + "functional"); } catch (AWTException e) { System.out.println("Robot is not available"); } System.exit(0); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/TextComponentTester.java
package abbot.tester; import java.awt.*; import abbot.util.Bugs; /** Provides user actions for TextComponent-derived components. */ public class TextComponentTester extends ComponentTester { /** * Type the given text into the given component, replacing all * text already there. */ public void actionEnterText(Component c, String text) { actionSelectText(c, 0, ((TextComponent)c).getText().length()); actionKeyString(c, text); } /** Set the caret position. */ public void actionSetCaretPosition(Component c, final int index) { final TextComponent tc = (TextComponent)c; invokeLater(c, new Runnable() { public void run() { tc.setCaretPosition(index); } }); } /** Start a selection at the given index. */ public void actionStartSelection(Component c, final int index) { final TextComponent tc = (TextComponent)c; invokeLater(c, new Runnable() { public void run() { tc.setSelectionStart(index); } }); } /** Terminate a selection on the given index. */ public void actionEndSelection(Component c, final int index) { final TextComponent tc = (TextComponent)c; invokeLater(c, new Runnable() { public void run() { tc.setSelectionEnd(index); } }); } /** Select the given text range. */ public void actionSelectText(Component c, final int start, final int end) { final TextComponent tc = (TextComponent)c; invokeAndWait(c, new Runnable() { public void run() { tc.select(start, end); } }); if (Bugs.hasTextComponentSelectionDelay()) delay(100); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/WindowTester.java
package abbot.tester; import java.awt.*; import javax.accessibility.AccessibleContext; import abbot.i18n.Strings; /** Provides user actions on a Window. */ public class WindowTester extends ContainerTester { /** The window's size seems as good an ID as any. If someone has a bunch * of frameless windows floating about, they can come up with a better * ID. */ public String deriveTag(Component comp) { // If the component class is custom, don't provide a tag if (isCustom(comp.getClass())) return null; String tag = null; AccessibleContext context = ((Window)comp).getAccessibleContext(); tag = deriveAccessibleTag(context); if (tag == null || "".equals(tag)) { Dimension size = comp.getSize(); tag = String.valueOf(size.width) + "x" + String.valueOf(size.height); } return tag; } /** Send a WINDOW_CLOSING event to the window, equivalent to the user closing the window through the window manager. Note that this will not necessarily close the window. */ public void actionClose(Component c) { close((Window)c); waitForIdle(); } /** Move the window to the given location. */ public void actionMove(Component w, int screenx, int screeny) { if (!userMovable(w)) throw new ActionFailedException(Strings.get("tester.Window.no_move")); move((Window)w, screenx, screeny); waitForIdle(); } /** Move the window to the given location. */ public void actionMoveBy(Component w, int dx, int dy) { if (!userMovable(w)) throw new ActionFailedException(Strings.get("tester.Window.no_move")); moveBy((Window)w, dx, dy); waitForIdle(); } /** Resize the given window. Note that this will fail on frames or * dialogs which are not resizable. */ public void actionResize(Component w, int width, int height) { if (!userResizable(w)) throw new ActionFailedException(Strings.get("tester.Window.no_resize")); resize((Window)w, width, height); waitForIdle(); } /** Resize the given window. Note that this will fail on frames or * dialogs which are not resizable. */ public void actionResizeBy(Component w, int dx, int dy) { if (!userResizable(w)) throw new ActionFailedException(Strings.get("tester.Window.no_resize")); resizeBy((Window)w, dx, dy); waitForIdle(); } /** Activate the given Window. */ public void actionActivate(Window w) { activate(w); waitForIdle(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/tester/WindowTracker.java
package abbot.tester; import java.awt.*; import java.awt.event.*; import javax.swing.SwingUtilities; import java.lang.ref.*; import java.util.*; import abbot.Log; import abbot.util.AWT; import abbot.util.Properties; import abbot.util.WeakAWTEventListener; import abbot.util.NamedTimer; /** Keep track of all known root windows, and all known showing/hidden/closed * windows. */ public class WindowTracker { private WeakAWTEventListener windowReadyTrackerListener; private WeakAWTEventListener contextTrackerListener; private static class Holder { public static final WindowTracker INSTANCE = new WindowTracker(); } /** Maps unique event queues to the set of root windows found on each queue. */ private Map contexts = new WeakHashMap(); /** Maps components to their corresponding event queues. */ private Map queues; private ContextTracker contextTracker; /** Windows which for which isShowing is true but are not yet ready for input. */ private Map pendingWindows = new WeakHashMap(); /** Windows which we deem are ready to use. */ private Map openWindows = new WeakHashMap(); /** Windows which are not visible. */ private Map hiddenWindows = new WeakHashMap(); /** Windows which have sent a WINDOW_CLOSE event. */ private Map closedWindows = new WeakHashMap(); private WindowReadyTracker windowReadyTracker; private java.awt.Robot robot; static int WINDOW_READY_DELAY = Properties.getProperty("abbot.window_ready_delay", 10000, 0, 60000); private Timer windowReadyTimer; /** Windows which have had an adapter added */ private Map<Window, WindowWatcher> watchers = new WeakHashMap<Window, WindowWatcher>(); /** Only ever want one of these. */ public static WindowTracker getTracker() { return Holder.INSTANCE; } /** Create an instance of WindowTracker which will track all windows * coming and going on the current and subsequent app contexts. * WARNING: if an applet loads this class, it will only ever see stuff in * its own app context. */ WindowTracker() { contextTracker = new ContextTracker(); windowReadyTracker = new WindowReadyTracker(); // hold the event queue references weakly // each queue maps to a set of components (actually a weak hash map to // allow GC of the component keys). contexts.put(Toolkit.getDefaultToolkit().getSystemEventQueue(), new WeakHashMap()); // hold both the component references and the event queues weakly queues = new WeakHashMap(); // Populate stuff that may already have shown/been hidden Frame[] frames = Frame.getFrames(); synchronized(openWindows) { for (int i=0;i < frames.length;i++) { scanExistingWindows(frames[i]); } } try { robot = new java.awt.Robot(); } catch(AWTException e) { } windowReadyTimer = new NamedTimer("Window Ready Timer", true); long mask = WindowEvent.WINDOW_EVENT_MASK | ComponentEvent.COMPONENT_EVENT_MASK; contextTrackerListener = new WeakAWTEventListener(contextTracker, mask); mask = InputEvent.MOUSE_MOTION_EVENT_MASK |InputEvent.MOUSE_EVENT_MASK|InputEvent.PAINT_EVENT_MASK; windowReadyTrackerListener = new WeakAWTEventListener(windowReadyTracker, mask); } public void dispose() { // Remove listener windowReadyTrackerListener.dispose(); contextTrackerListener.dispose(); // Canclet the timer windowReadyTimer.cancel(); } private void scanExistingWindows(Window w) { // Make sure we catch subsequent show/hide events for this window attachWindowWatcherIfRequired(w); Window[] windows = w.getOwnedWindows(); for (int i=0;i < windows.length;i++) { scanExistingWindows(windows[i]); } openWindows.put(w, Boolean.TRUE); if (!w.isShowing()) { hiddenWindows.put(w, Boolean.TRUE); } noteContext(w); } /** Returns whether the window is ready to receive OS-level event input. A window's "isShowing" flag may be set true before the WINDOW_OPENED event is generated, and even after the WINDOW_OPENED is sent the window peer is not guaranteed to be ready. */ public boolean isWindowReady(Window w) { // If this window is null likely that it can't be found so for convienience // return null if (w==null) { return false; } synchronized(openWindows) { if (openWindows.containsKey(w) && !hiddenWindows.containsKey(w)) { return true; } } if (robot != null) checkWindow(w, robot); return false; } /** Return the event queue corresponding to the given component. In most cases, this is the same as Component.getToolkit().getSystemEventQueue(), but in the case of applets will bypass the AppContext and provide the real event queue. */ public EventQueue getQueue(Component c) { // Components above the applet in the hierarchy may or may not share // the same context with the applet itself. while (!(c instanceof java.applet.Applet) && c.getParent() != null) c = c.getParent(); synchronized(contexts) { WeakReference ref = (WeakReference)queues.get(c); EventQueue q = ref != null ? (EventQueue)ref.get() : null; if (q == null) q = c.getToolkit().getSystemEventQueue(); return q; } } /** Returns all known event queues. */ public Collection getEventQueues() { HashSet set = new HashSet(); synchronized(contexts) { set.addAll(contexts.keySet()); Iterator iter = queues.values().iterator(); while (iter.hasNext()) { WeakReference ref = (WeakReference)iter.next(); EventQueue q = (EventQueue)ref.get(); if (q != null) set.add(q); } } return set; } /** Return all available root Windows. A root Window is one * that has a null parent. Nominally this means a list similar to that * returned by Frame.getFrames(), but in the case of an Applet may return * a few Dialogs as well. */ public Collection getRootWindows() { Set set = new HashSet(); // Use Frame.getFrames() here in addition to our watched set, just in // case any of them is missing from our set. synchronized(contexts) { Iterator iter = contexts.keySet().iterator(); while (iter.hasNext()) { EventQueue queue = (EventQueue)iter.next(); Map map = (Map)contexts.get(queue); set.addAll(map.keySet()); } } Frame[] frames = Frame.getFrames(); for (int i=0;i < frames.length;i++) { set.add(frames[i]); } //Log.debug(String.valueOf(list.size()) + " total Frames"); return set; } /** Provides tracking of window visibility state. We explicitly add this * on WINDOW_OPEN and remove it on WINDOW_CLOSE to avoid having to process * extraneous ComponentEvents. */ /*package*/ class WindowWatcher extends WindowAdapter implements ComponentListener { /** * Do not call directly as can cause a stack overflow with multiple attacments to the * listener list */ public WindowWatcher(Window w) { w.addComponentListener(this); w.addWindowListener(this); } public void componentShown(ComponentEvent e) { markWindowShowing((Window)e.getSource()); } public void componentHidden(ComponentEvent e) { synchronized(openWindows) { //Log.log("Marking " + e.getSource() + " hidden"); hiddenWindows.put(e.getSource(), Boolean.TRUE); pendingWindows.remove(e.getSource()); } } public void windowClosed(WindowEvent e) { e.getWindow().removeWindowListener(this); e.getWindow().removeComponentListener(this); // Remove self when we tidy up watchers.remove(e.getWindow()); } public void componentResized(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } } /** Whenever we get a window that's on a new event dispatch thread, take * note of the thread, since it may correspond to a new event queue and * AppContext. */ // FIXME what if it has the same app context? can we check? private class ContextTracker implements AWTEventListener { public void eventDispatched(AWTEvent ev) { ComponentEvent event = (ComponentEvent)ev; Component comp = event.getComponent(); // This is our sole means of accessing other app contexts // (if running within an applet). We look for window events // beyond OPENED in order to catch windows that have already // opened by the time we start listening but which are not // in the Frame.getFrames list (i.e. they are on a different // context). Specifically watch for COMPONENT_SHOWN on applets, // since we may not get frame events for them. if (!(comp instanceof java.applet.Applet) && !(comp instanceof Window)) { return; } int id = ev.getID(); if (id == WindowEvent.WINDOW_OPENED) { noteOpened(comp); } else if (id == WindowEvent.WINDOW_CLOSED) { noteClosed(comp); } else if (id == WindowEvent.WINDOW_CLOSING) { // ignore } // Take note of all other window events else if ((id >= WindowEvent.WINDOW_FIRST && id <= WindowEvent.WINDOW_LAST) || id == ComponentEvent.COMPONENT_SHOWN) { synchronized(openWindows) { if (!getRootWindows().contains(comp) || closedWindows.containsKey(comp)) { noteOpened(comp); } } } // The context for root-level windows may change between // WINDOW_OPENED and subsequent events. synchronized(contexts) { WeakReference ref = (WeakReference)queues.get(comp); if (ref != null && !comp.getToolkit().getSystemEventQueue(). equals(ref.get())) { noteContext(comp); } } } } private class WindowReadyTracker implements AWTEventListener { public void eventDispatched(AWTEvent e) { if (e instanceof MouseEvent) { Component c = (Component)e.getSource(); Window w = c instanceof Window ? (Window)c : SwingUtilities.getWindowAncestor(c); markWindowReady(w); } } } private void noteContext(Component comp) { EventQueue queue = comp.getToolkit().getSystemEventQueue(); synchronized(contexts) { Map map = (Map)contexts.get(queue); if (map == null) { contexts.put(queue, map = new WeakHashMap()); } if (comp instanceof Window && comp.getParent() == null) { map.put(comp, Boolean.TRUE); } queues.put(comp, new WeakReference(queue)); } } private void noteOpened(Component comp) { //Log.log("Noting " + comp + " opened"); noteContext(comp); // Attempt to ensure the window is ready for input before recognizing // it as "open". There is no Java API for this, so we institute an // empirically tested delay. if (comp instanceof Window) { attachWindowWatcherIfRequired((Window)comp); markWindowShowing((Window)comp); // Native components don't receive events anyway... if (comp instanceof FileDialog) { markWindowReady((Window)comp); } } } private void attachWindowWatcherIfRequired(Window win) { if (!watchers.containsKey(win)) { watchers.put(win, new WindowWatcher(win)); } } private void noteClosed(Component comp) { if (comp.getParent() == null) { EventQueue queue = comp.getToolkit().getSystemEventQueue(); synchronized(contexts) { Map whm = (Map)contexts.get(queue); if (whm != null) whm.remove(comp); else { EventQueue foundQueue = null; Iterator iter = contexts.keySet().iterator(); while (iter.hasNext()) { EventQueue q = (EventQueue)iter.next(); Map map = (Map)contexts.get(q); if (map.containsKey(comp)) { foundQueue = q; map.remove(comp); } } if (foundQueue == null) { Log.log("Got WINDOW_CLOSED on " + Robot.toString(comp) + " on a previously unseen context: " + queue + "(" + Thread.currentThread() + ")"); } else { Log.log("Window " + Robot.toString(comp) + " sent WINDOW_CLOSED on " + queue + " but sent WINDOW_OPENED on " + foundQueue); } } } } synchronized(openWindows) { //Log.log("Marking " + comp + " closed"); openWindows.remove(comp); hiddenWindows.remove(comp); closedWindows.put(comp, Boolean.TRUE); pendingWindows.remove(comp); } } /** Mark the given Window as ready for input. Indicate whether any * pending "mark ready" task should be canceled. */ private void markWindowReady(Window w) { synchronized(openWindows) { // If the window was closed after the check timer started running, // it will have canceled the pending ready. // Make sure it's still on the pending list before we actually // mark it ready. if (pendingWindows.containsKey(w)) { //Log.log("Noting " + w + " ready"); closedWindows.remove(w); hiddenWindows.remove(w); openWindows.put(w, Boolean.TRUE); pendingWindows.remove(w); } } } /** Indicate a window has set isShowing true and needs to be marked ready when it is actually ready. */ private void markWindowShowing(final Window w) { synchronized(openWindows) { // At worst, time out and say the window is ready // after the configurable delay TimerTask task = new TimerTask() { public void run() { markWindowReady(w); } }; windowReadyTimer.schedule(task, WINDOW_READY_DELAY); pendingWindows.put(w, task); } } private static int sign = 1; /** Actively check whether the given window is ready for input. * @param robot * @see #isWindowReady */ private void checkWindow(final Window w, java.awt.Robot robot) { // Must avoid frame borders, which are insensitive to mouse // motion (at least on w32). final Insets insets = AWT.getInsets(w); final int width = w.getWidth(); final int height = w.getHeight(); int x = w.getX() + insets.left + (width-(insets.left+insets.right))/2; int y = w.getY() + insets.top + (height-(insets.top+insets.bottom))/2; if (x != 0 && y != 0) { robot.mouseMove(x, y); if (width > height) robot.mouseMove(x + sign, y); else robot.mouseMove(x, y + sign); sign = -sign; } synchronized(openWindows) { if (pendingWindows.containsKey(w) && isEmptyFrame(w)) { // Force the frame to be large enough to receive events SwingUtilities.invokeLater(new Runnable() { public void run() { int nw = Math.max(width, insets.left + insets.right + 3); int nh = Math.max(height, insets.top + insets.bottom + 3); w.setSize(nw, nh); } }); } } } /** We can't get any motion events on an empty frame. */ private boolean isEmptyFrame(Window w) { Insets insets = AWT.getInsets(w); return insets.top + insets.bottom == w.getHeight() || insets.left + insets.right == w.getWidth(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/AWT.java
package abbot.util; import abbot.InterruptedAbbotException; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.text.View; import sun.awt.AppContext; import abbot.Log; import abbot.Platform; import abbot.finder.*; import abbot.finder.matchers.ClassMatcher; import abbot.tester.*; import abbot.tester.Robot; /** Various AWT utilities to facilitate component-oriented operations. */ public class AWT { public static int POPUP_TIMEOUT = 5000; private static Hierarchy hierarchy = new AWTHierarchy(); static { String to = System.getProperty("abbot.finder.popup_timeout"); if (to != null) { try { POPUP_TIMEOUT = Integer.parseInt(to); } catch(Exception e) { } } } private static final Point RELATIVE_OFFSET = new Point(10, 10); /** Set this client property on components which contain a heavyweight * component. Use {@link Boolean#TRUE} as the value. */ public final static String CONTAINS_HEAVYWEIGHT_COMPONENT = "containsHeavyweightComponent"; /** Offset from the position of the currently active window to the * position of a new window. */ public static final Point DEFAULT_CASCADE = new Point(15, 15); /** Return whether the given {@link Point} is visible on any screen. */ public static boolean onScreen(Point p) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = env.getScreenDevices(); for (int i=0;i < gs.length;i++) { GraphicsConfiguration[] gc = gs[i].getConfigurations(); for (int j=0;j < gc.length;j++) { Rectangle r = getVisibleBounds(gc[j]); if (r.contains(p)) return true; } } return false; } /** Returns whether one of the upper corners of the given window is * accessible. */ public static boolean onScreen(Window w) { return onScreen(w.getLocation()) || onScreen(new Point(w.getX() + w.getWidth()-1, w.getY())); } /** Returns the GraphicsConfiguration which contains the given point, * or null if none. */ public static GraphicsConfiguration getGraphicsConfiguration(Point p) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = env.getScreenDevices(); for (int i=0;i < gs.length;i++) { GraphicsConfiguration[] gc = gs[i].getConfigurations(); Rectangle bounds = getVisibleBounds(gc[i]); if (bounds.contains(p)) { return gc[i]; } } return null; } /** Returns a Rectangle spanning all screens. Note that not all pixels * within the rectangle are necessarily on a display.<p> * Includes any toolbar/dashboard regions. */ public static Rectangle getVirtualDisplayBounds(boolean includeInsets) { Rectangle bounds = null; GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = env.getScreenDevices(); for (int i=0;i < gs.length;i++) { GraphicsConfiguration[] gc = gs[i].getConfigurations(); for (int j=0;j < gc.length;j++) { Rectangle r = includeInsets ? gc[j].getBounds() : getVisibleBounds(gc[j]); if (bounds == null) bounds = r; else bounds = bounds.union(r); } } return bounds; } /** Return the visible bounds for the graphics configuration. This will * exclude any permanent menu bar or dashboard decorations. */ public static Rectangle getVisibleBounds(GraphicsConfiguration gc) { Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc); Rectangle r = gc.getBounds(); r.x += insets.left; r.y += insets.top; r.width -= insets.left + insets.right; r.height -= insets.top + insets.bottom; return r; } private static final int SCREEN_MARGIN = 10; /** Ensure the given window is visible on screen. */ public static void ensureOnScreen(Window w) { // One of the upper corners of the window needs to be on screen if (!onScreen(w)) { Rectangle bounds = getVirtualDisplayBounds(false); int x = w.getX(); int y = w.getY(); if (w.getX() + w.getWidth() < bounds.x + SCREEN_MARGIN) { x = bounds.x + SCREEN_MARGIN - w.getWidth(); } if (w.getX() > bounds.x + bounds.width + SCREEN_MARGIN) { x = bounds.x + bounds.width - SCREEN_MARGIN; } if (w.getY() < bounds.y + SCREEN_MARGIN) { y = bounds.y + SCREEN_MARGIN; } if (w.getY() > bounds.y + bounds.height + SCREEN_MARGIN) { y = bounds.y + bounds.height - SCREEN_MARGIN; } w.setLocation(x, y); if (!onScreen(w)) { // If still not on screen, just center it on the default screen centerOnScreen(w); } } } /** Set the position of the window in a platform-specific manner. * Uses Window.setLocationByPlatform if available, otherwise * centers on screen. */ public static void setLocationByPlatform(Window w) { try { Method m = Window.class.getDeclaredMethod("setLocationByPlatform", new Class[] { boolean.class }); m.invoke(w, new Object[] { Boolean.TRUE }); } catch(Exception e) { centerOnScreen(w); } } /** Ensure the given component renders its initial HTML wrapped at the * given preferred width. */ public static void setHTMLPreferredWidth(JComponent c, int width) { // Something of a hack. This property gets set prior to setting // the component's initial size, so we tweak the view to have // a preferred x-axis span to what we want, restoring it after // the initial size has been set. c.addPropertyChangeListener("ancestor", new PropertyChangeListener() { final int PREF_WIDTH = 200; public void propertyChange(PropertyChangeEvent e) { JComponent c = (JComponent)e.getSource(); c.removePropertyChangeListener("ancestor", this); final View view = (View)c.getClientProperty("html"); if (view != null) { final float prefx = view.getPreferredSpan(View.X_AXIS); final float prefy = view.getPreferredSpan(View.Y_AXIS); view.setSize(Math.min(PREF_WIDTH, prefx), prefy); SwingUtilities.invokeLater(new Runnable() { public void run() { view.setSize(prefx, prefy); } }); } } }); } /** Combine the two colors with equal weight. */ public static Color combine(Color c1, Color c2) { return combine(c1, c2, 0.5f); } /** Combine the two colors, giving the requested weight to the first. */ public static Color combine(Color c1, Color c2, float weight) { float w1 = (float)Math.max(Math.min(weight, 1.0), 0); float w2 = 1.0f - w1; return new Color((int)(c1.getRed()*w1 + c2.getRed()*w2), (int)(c1.getGreen()*w1 + c2.getGreen()*w2), (int)(c1.getBlue()*w1 + c2.getBlue()*w2), (int)(c1.getAlpha()*w1 + c2.getAlpha()*w2)); } /** Returns true if there is an active menu on the JFrame (if any) containing the given component. */ public static boolean isMenuActive(Component c) { Frame f = getFrame(c); if (f instanceof JFrame) { JFrame frame = (JFrame)f; JMenuBar mb = frame.getJMenuBar(); if (mb != null) { for (int i=0;i < mb.getMenuCount();i++) { JMenu menu = mb.getMenu(i); if (menu == null) continue; if (menu.isSelected() || menu.isPopupMenuVisible()) return true; } } } return false; } /** * Display a frame relative to the given component. */ public static void showFrameRelative(Frame frame, Component relativeTo) { moveFrameRelativeTo(frame, relativeTo); if (frame.getState() == Frame.ICONIFIED) { frame.setState(Frame.NORMAL); } frame.show(); } /** Center the given {@link Window} on the default screen. */ public static void centerOnScreen(Window window) { Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint(); Rectangle max = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int x = Math.max(center.x - Math.round(window.getWidth()/2f), max.x); int y = Math.max(center.y - Math.round(window.getHeight()/2f), max.y); window.setLocation(new Point(x, y)); } /** Center on the specified frame. */ public static void centerOnFrame(Window window, Frame frame) { int ww = window.getWidth(); int wh = window.getHeight(); int fw = frame.getWidth(); int fh = frame.getHeight(); int x = (int)Math.round((double)(fw - ww) / 2); int y = (int)Math.round((double)(fh - wh) / 2); Point location = frame.getLocationOnScreen(); location.translate(x, y); window.setLocation(location); ensureOnScreen(window); } public static void moveFrameRelativeTo(Frame frame, Component relativeTo) { Point location = RELATIVE_OFFSET; Window reference = null; if (relativeTo != null) { reference = getWindow(relativeTo); } if (reference != null) { location = reference.getLocationOnScreen(); location.translate(RELATIVE_OFFSET.x, RELATIVE_OFFSET.y); } frame.setLocation(location); ensureOnScreen(frame); } /** Return whether the given component either has focus or is the ancestor * of the focused component. */ public static boolean containsFocus(Component c) { KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component owner = mgr.getFocusOwner(); return owner != null && SwingUtilities.isDescendingFrom(owner, c); } /** NOTE: on pointer-focused systems, the frontmost window is not * necessarily the one with focus. */ public static Window getFocusedWindow() { KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); return mgr.getFocusedWindow(); } /** NOTE: NOT necessarily the same thing as the focused window. */ public static Window getActiveWindow() { KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); return mgr.getActiveWindow(); } private static boolean containsHeavyweightComponent(Component root) { if (root instanceof Container) { if (root instanceof JComponent && Boolean.TRUE.equals(((JComponent)root).getClientProperty(CONTAINS_HEAVYWEIGHT_COMPONENT))) { return true; } Container c = (Container)root; for (int i=0;i < c.getComponentCount();i++) { if (containsHeavyweightComponent(c.getComponents()[i])) { return true; } } } return false; } /** @return whether the hierarchy within which the given Component sits * contains a heavyweight component. */ public static boolean hierarchyHasHeavyweightComponent(Component base) { Window w = getWindow(base); return containsHeavyweightComponent(w); } /** Return the {@link Frame} corresponding to the given object. */ public static Frame getFrame(Object o) { Window w = getWindow(o); while (!(w instanceof Frame) && w != null) { w = (Window)w.getParent(); } return w instanceof Frame ? (Frame)w : JOptionPane.getRootFrame(); } /** Return the window corresponding to the given object. */ public static Window getWindow(Object o) { if (o instanceof Component) { Component c = (Component)o; while (c instanceof JMenuItem) { c = c.getParent(); } if (c instanceof JPopupMenu) { return getWindow(((JPopupMenu)c).getInvoker()); } return c instanceof Window ? (Window)c : SwingUtilities.getWindowAncestor(c); } return JOptionPane.getRootFrame(); } /** Return a copy of the given color with a new alpha component. */ public static Color alpha(Color c, int alpha) { return new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha); } /** Find the first instance of the given class under the given component, * or null if none found. */ public static Component find(Component root, final Class type) { return find(root, new ComponentPredicate() { public boolean evaluate(Component o) { return o != null && type.isAssignableFrom(o.getClass()); } }); } /** Cascade the given window based on the currently active {@link Frame}. */ public static void cascade(Window w) { cascade(w, DEFAULT_CASCADE.x, DEFAULT_CASCADE.y); } /** Cascade the given window based on the currently active {@link Frame}. */ public static void cascade(Window w, int xoff, int yoff) { // Make sure we get a frame, not a dialog Frame f = getFrame(getActiveWindow()); if (f != null && f.isShowing()) { w.setLocation(f.getX() + xoff, f.getY() + yoff); ensureOnScreen(w); } else { centerOnScreen(w); } } public static interface ComponentPredicate { /** Return whether the given component is the desired one. */ boolean evaluate(Component c); } /** Find the first component matching the given predicate, * or null if none found. */ public static Component find(Component root, ComponentPredicate test) { if (test.evaluate(root)) return root; if (root instanceof Container) { Component[] kids = ((Container)root).getComponents(); for (int i=0;i < kids.length;i++) { Component c = find(kids[i], test); if (c != null) return c; } } return null; } /** Find the first instance of {@link RootPaneContainer} in the given * container. Basically finds applets. */ public static RootPaneContainer findRootPaneContainer(Container c) { if (c instanceof RootPaneContainer) { return (RootPaneContainer)c; } Component[] kids = c.getComponents(); for (int i=0;i < kids.length;i++) { if (kids[i] instanceof RootPaneContainer) return (RootPaneContainer)kids[i]; if (kids[i] instanceof Container) { RootPaneContainer rcp = findRootPaneContainer((Container)kids[i]); if (rcp != null) return rcp; } } return null; } private AWT() { } /** Return whether the given Component has only its default name set. */ public static boolean hasDefaultName(Component c) { String name = getName(c); if (name == null) return true; if (c instanceof JComponent) { return (c instanceof JLayeredPane && "null.layeredPane".equals(name)) || (c instanceof JPanel && ("null.glassPane".equals(name) || "null.contentPane".equals(name))); } return (c instanceof Button && Regexp.stringMatch("button[0-9]+", name)) || (c instanceof Canvas && Regexp.stringMatch("canvas[0-9]+", name)) || (c instanceof Checkbox && Regexp.stringMatch("checkbox[0-9]+", name)) || (c instanceof Choice && Regexp.stringMatch("choice[0-9]+", name)) || (c instanceof Dialog && Regexp.stringMatch("dialog[0-9]+", name)) || (c instanceof FileDialog && Regexp.stringMatch("filedlg[0-9]+", name)) || (c instanceof Frame && Regexp.stringMatch("frame[0-9]+", name)) || (c instanceof java.awt.List && Regexp.stringMatch("list[0-9]+", name)) || (c instanceof Label && Regexp.stringMatch("label[0-9]+", name)) || (c instanceof Panel && Regexp.stringMatch("panel[0-9]+", name)) || (c instanceof Scrollbar && Regexp.stringMatch("scrollbar[0-9]+", name)) || (c instanceof ScrollPane && Regexp.stringMatch("scrollpane[0-9]+", name)) || (c instanceof TextArea && Regexp.stringMatch("text[0-9]+", name)) || (c instanceof TextField && Regexp.stringMatch("textfield[0-9]+", name)) || (c instanceof Window && Regexp.stringMatch("win[0-9]+", name)); } /** Ensure the given action happens on the event dispatch thread. Any * component modifications must be invoked this way. */ public static void invokeAndWait(Runnable action) { if (EventQueue.isDispatchThread()) { action.run(); } else { try { EventQueue.invokeAndWait(action); } catch(InterruptedException ie) { Log.warn(ie); throw new InterruptedAbbotException("Interrupted during invokeAndWait"); } catch(java.lang.reflect.InvocationTargetException ite) { Log.warn(ite); } } } /** Ensure the given action happens on the event dispatch thread. Any * component modifications must be invoked this way. Note that this is * <b>not</b> the same as EventQueue.invokeLater, since if the current * thread is the dispatch thread, the action is invoked immediately. */ public static void invokeAction(Runnable action) { if (EventQueue.isDispatchThread()) { action.run(); } else { EventQueue.invokeLater(action); } } /** Returns whether the menu component is on a MenuBar. */ public static boolean isOnMenuBar(MenuComponent mc) { if (mc instanceof MenuBar) return true; return mc.getParent() instanceof MenuComponent && isOnMenuBar((MenuComponent)mc.getParent()); } /** Returns the invoker, if any, of the given AWT menu component. Returns null if the menu component is not attached to anything, or if it is within a MenuBar hierarchy. */ public static Component getInvoker(MenuComponent mc) { if (isOnMenuBar(mc)) return null; MenuContainer parent = mc.getParent(); while (parent instanceof MenuComponent) { parent = ((MenuComponent)parent).getParent(); } return parent instanceof Component ? (Component)parent : null; } /** Returns the invoker, if any, of the given component. Returns null if * the component is not on a popup of any sort. */ public static Component getInvoker(Component comp) { if (comp instanceof JPopupMenu) return ((JPopupMenu)comp).getInvoker(); comp = comp.getParent(); return comp != null ? getInvoker(comp) : null; } /** Similar to SwingUtilities.getWindowAncestor(), but returns the * component itself if it is a Window, or the invoker's window if on a * popup. */ public static Window getWindow(Component comp) { if (comp == null) return null; if (comp instanceof Window) return (Window)comp; if (comp instanceof MenuElement) { Component invoker = getInvoker(comp); if (invoker != null) return getWindow(invoker); } return getWindow(hierarchy.getParent(comp)); } /** Returns whether there is an AWT popup menu currently showing. */ public static boolean isAWTPopupMenuBlocking() { // For now, just do a quick check to see if a PopupMenu is active on // w32. Extend it if we find other common situations that might block // the EDT, but for now, keep it simple and restricted to what we've // run into. // NOTE: technically, the popup menu blocks the toolkit, not the EDT, // but in practice it doesn't make much difference since the EDT // depends heavily on the toolkit. return Bugs.showAWTPopupMenuBlocks() && isAWTTreeLockHeld(); } /** Returns whether the AWT Tree Lock is currently held. */ private static boolean isAWTTreeLockHeld() { return isAWTTreeLockHeld(Toolkit.getDefaultToolkit().getSystemEventQueue()); } /** Returns whether the AWT Tree Lock is currently held. */ public static boolean isAWTTreeLockHeld(EventQueue eq) { Frame[] frames = Frame.getFrames(); if (frames.length == 0) return false; // hack based on 1.4.2 java.awt.PopupMenu implementation, // which blocks the event dispatch thread while the popup is visible, // while holding the AWT tree lock // Start another thread which attempts to get the tree lock // If it can't get the tree lock, then there is a popup active in the // current tree. // Any component can provide the tree lock ThreadStateChecker checker = new ThreadStateChecker(frames[0].getTreeLock()); try { checker.start(); // Wait a little bit for the checker to finish int delay = Properties.getProperty("abbot.treelock_wait", 100, 0, 60000); if (checker.isAlive()) checker.join(delay); return checker.isAlive(); } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted when checking for tree lock"); } } /** Ensure any extant AWT popup is dismissed. This should only be called * from off the EDT, since (at least on w32) the EDT is blocked while * an AWT popup is showing. */ // FIXME this sometimes causes the windows menu to display on w32 public static void dismissAWTPopup() { // If we're on the EDT, we know a priori there is no AWT popup if (SwingUtilities.isEventDispatchThread()) return; java.awt.Robot robot = Robot.getRobot(); if (robot != null) { Component c = getFocusOwner(); if (c != null) { Window w = getWindow(c); if (w != null && w.isShowing()) { robot.keyPress(KeyEvent.VK_ESCAPE); robot.keyRelease(KeyEvent.VK_ESCAPE); } } } else { Log.warn("The current system configuation can not automatically dismiss an AWT popup"); } } /** Returns whether the given MenuComponent is on a top-level AWT popup (that is, <i>not</i> under a MenuBar. */ public static boolean isOnPopup(MenuComponent mc) { MenuContainer parent = mc.getParent(); while (parent instanceof MenuComponent) { if (parent instanceof MenuBar) return false; parent = ((MenuComponent)parent).getParent(); } return true; } /** Returns whether the given component is on a top-level popup. A * top-level popup is one generated by a popup trigger, which means popups * generated from a JMenu are not included. */ public static boolean isOnPopup(Component comp) { boolean isWrapper = isTransientPopup(comp); Component invoker = getInvoker(comp); boolean isOnJMenu = invoker instanceof JMenu && invoker.getParent() instanceof JMenuBar; return isWrapper || (invoker != null && !isOnJMenu); } /** Returns whether the given component is a heavyweight popup, that is, a container for a JPopupMenu that is implemented with a heavyweight component (usually a Window). */ public static boolean isHeavyweightPopup(Component c) { if (c instanceof Window) { if (!(c instanceof Dialog) && !(c instanceof Frame)) { String name = getName(c); String cname = c.getClass().getName(); return ("###overrideRedirect###".equals(name) || "###focusableSwingPopup###".equals(name) // These classes are known to be heavyweight popups // javax.swing.DefaultPopupFactory$WindowPopup (1.3) || cname.indexOf("PopupFactory$WindowPopup") != -1 // javax.swing.Popup.HeavyWeightWindow (1.4) || cname.indexOf("HeavyWeightWindow") != -1); } if (c instanceof Window && c instanceof RootPaneContainer && ((RootPaneContainer)c).getRootPane()!=null && ((RootPaneContainer)c).getRootPane().getClientProperty("abbot.customPopup")!=null) { return true; } } return false; } // Work around some components throwing exceptions if getName is // called prematurely private static String getName(Component c) { try { return c.getName(); } catch(Throwable e) { Log.warn(e); return null; } } /** Returns whether the given component is a lightweight popup, that is, a container for a JPopupMenu that is implemented with a lightweight component (usually JPanel). */ public static boolean isLightweightPopup(Component c) { if (c instanceof JPanel) { Window w = SwingUtilities.getWindowAncestor(c); if (w != null && isHeavyweightPopup(w)) return false; JPanel panel = (JPanel)c; Container parent = panel.getParent(); if (parent != null) { if (parent instanceof JLayeredPane) { int layer = JLayeredPane.POPUP_LAYER.intValue(); if (JLayeredPane.getLayer(panel) == layer) return true; } } return panel.getComponentCount() == 1 && panel.getComponents()[0] instanceof JPopupMenu; } return false; } /** Returns whether the given Component is the content pane for a {@link RootPaneContainer}. @see javax.swing.RootPaneContainer#getContentPane */ public static boolean isContentPane(Component c) { if (c.getParent() instanceof JLayeredPane) { JLayeredPane p = (JLayeredPane)c.getParent(); if (p.getParent() instanceof JRootPane) { return ((JRootPane)p.getParent()).getContentPane() == c; } int layer = JLayeredPane.FRAME_CONTENT_LAYER.intValue(); return p.getLayer(c) == layer && !(c instanceof JMenuBar); } return false; } /** Returns whether the given Component is the Glass Pane for a {@link JRootPane}. @see javax.swing.JRootPane#getGlassPane */ public static boolean isGlassPane(Component c) { if (c.getParent() instanceof JRootPane) { JRootPane p = (JRootPane)c.getParent(); return p.getGlassPane() == c; } return false; } /** Return whether the given component is part of the transient wrapper * around a popup. */ public static boolean isTransientPopup(Component c) { return isLightweightPopup(c) || isHeavyweightPopup(c); } private static boolean containsToolTip(Component c) { if (c instanceof JToolTip) return true; if (c instanceof Container) { Component[] kids = ((Container)c).getComponents(); for (int i=0;i < kids.length;i++) { if (containsToolTip(kids[i])) return true; } } return false; } /** Return whether the given component is part of the transient wrapper around a tooltip. */ public static boolean isToolTip(Component c) { return isTransientPopup(c) && containsToolTip(c); } /** Return whether the given component is part of an internal frame's LAF decoration. */ public static boolean isInternalFrameDecoration(Component c) { Component parent = c.getParent(); return (parent instanceof JInternalFrame && !(c instanceof JRootPane)) || (parent != null && (parent.getParent() instanceof JInternalFrame) && (!(parent instanceof JRootPane))); } // Macintosh *used* to map button2 to the popup trigger (circa 1.3) // Not clear when this changed private static final boolean POPUP_ON_BUTTON2 = false; /** Returns the InputEvent mask for the popup trigger button. */ public static int getPopupMask() { return POPUP_ON_BUTTON2 ? InputEvent.BUTTON2_MASK : InputEvent.BUTTON3_MASK; } /** Returns the InputEvent mask for the tertiary button. */ public static int getTertiaryMask() { return POPUP_ON_BUTTON2 ? InputEvent.BUTTON3_MASK : InputEvent.BUTTON2_MASK; } /** Returns whether the platform registers a popup on mouse press. */ public static boolean getPopupOnPress() { // Only w32 is popup on release return !Platform.isWindows(); } private static final PopupMenu[] NO_POPUPS = new PopupMenu[0]; /** Return all AWT popup menus associated with the given component. */ public static PopupMenu[] getPopupMenus(Component c) { // Here's a nice little hack to get access to the popup list on the // given invoker... try { Field field = Component.class.getDeclaredField("popups"); boolean accessible = field.isAccessible(); field.setAccessible(true); Vector popups = (Vector)field.get(c); field.setAccessible(accessible); if (popups != null) return (PopupMenu[])popups.toArray(new PopupMenu[popups.size()]); return NO_POPUPS; } catch(NoSuchFieldException e) { // not gonna happen throw new Error("No field named 'popups' in class Component"); } catch(IllegalAccessException e) { // neither should this throw new Error("Can't access popup for component " + c); } } /** Returns all MenuItems matching the given label or path which are on PopupMenus on the given Component. */ public static MenuItem[] findAWTPopupMenuItems(Component parent, String path) { PopupMenu[] popups = getPopupMenus(parent); ArrayList list = new ArrayList(); for (int i=0;i < popups.length;i++) { list.addAll(findMenuItems(popups[i], path, true)); } return (MenuItem[])list.toArray(new MenuItem[list.size()]); } /** Returns all MenuItems matching the given label or path which are found in the given Frame's MenuBar. */ public static MenuItem[] findAWTMenuItems(Frame frame, String path) { MenuBar mb = frame.getMenuBar(); if (mb != null) { Collection items = findMenuItems(mb, path, true); return (MenuItem[])items.toArray(new MenuItem[items.size()]); } return new MenuItem[0]; } /** Returns a unique path to the given MenuItem. */ public static String getPath(MenuItem item) { String path = getPath(item, false); if (isOnPopup(item) && findAWTPopupMenuItems(getInvoker(item), path).length > 1) { path = getPath(item, true); } return path; } /** Returns a unique path to the given MenuItem. If on a PopupMenu, optionally include the PopupMenu name. */ private static String getPath(MenuItem item, boolean includePopupName) { MenuContainer invoker = getInvoker(item); MenuContainer top; if (invoker == null) { // Find the top-most Menu above this MenuItem top = item.getParent(); while (top instanceof Menu && !(((Menu)top).getParent() instanceof MenuBar)) { top = ((Menu)top).getParent(); } if (top == null) throw new RuntimeException("MenuItem is not attached to the hierarchy"); } else { // Find the containing PopupMenu top = item.getParent(); while (top instanceof Menu && !(((Menu)top).getParent() instanceof Component)) { top = ((Menu)top).getParent(); } } // Return a path to the item, starting at the first top level Menu String path = item.getLabel(); MenuItem mi = item; while (mi.getParent() != top) { mi = (MenuItem)mi.getParent(); path = mi.getLabel() + "|" + path; } if (top instanceof PopupMenu) { if (includePopupName) { // If the popup has the default name, use its index // on the invoker instead. String name = ((PopupMenu)top).getName(); if (Regexp.stringMatch("popup[0-9]+", name)) { PopupMenu[] all = getPopupMenus((Component)invoker); for (int i=0;i < all.length;i++) { if (all[i] == top) { // Make it different from the default name name = "popup#" + i; break; } } } path = name + "|" + path; } } else { path = ((Menu)top).getLabel() + "|" + path; } Log.debug("Path for " + item + " is " + path); return path; } /** Returns all AWT menu items found with the given label; if matchPath is set then the MenuItem path is examined as well as the label. */ private static Collection findMenuItems(MenuContainer mc, String path, boolean matchPath) { if (matchPath) Log.debug("Searching for '" + path + "' on '" + mc); ArrayList list = new ArrayList(); if (mc instanceof MenuBar) { for (int i=0;i < ((MenuBar)mc).getMenuCount();i++) { Menu menu = ((MenuBar)mc).getMenu(i); Log.debug("Scanning '" + menu + "'"); list.addAll(findMenuItems(menu, path, matchPath)); } } else if (mc instanceof Menu) { for (int i=0;i < ((Menu)mc).getItemCount();i++) { MenuItem mi = ((Menu)mc).getItem(i); if (mi instanceof MenuContainer) { Log.debug("Scanning '" + mi + "'"); list.addAll(findMenuItems((MenuContainer)mi, path, matchPath)); } else if (path.equals(mi.getLabel())) { Log.debug("Found '" + mi + "'"); list.add(mi); } else if (matchPath) { if (ExtendedComparator.stringsMatch(path, getPath(mi, false)) || ExtendedComparator.stringsMatch(path, getPath(mi, true))) { Log.debug("Found (path) '" + mi + "'"); list.add(mi); } // TODO: fuzzy matching on the unique id (i.e. drop off or // add the popup menu name. } } } return list; } /** Return the focus owner under the given Window. As of 1.4.x, components will report that they do not have focus if asked from a different AppContext than their own. Account for that here. */ public static Component getFocusOwner() { try { Class cls = Class.forName("java.awt.KeyboardFocusManager"); Field field = cls.getDeclaredField("focusOwner"); boolean accessible = field.isAccessible(); field.setAccessible(true); Component c = (Component)field.get(null); field.setAccessible(accessible); return c; } catch(Exception e) { if(!(e instanceof ClassNotFoundException)) Log.log(e); // FIXME this lookup doesn't seem to work on 1.3! Iterator iter = new AWTHierarchy().getRoots().iterator(); Component focus = null; while (iter.hasNext()) { Window w = (Window)iter.next(); if (w.isShowing() && (focus = getFocusOwner(w)) != null) break; } return focus; } } private static Component getFocusOwner(Window w) { Component focus = w.getFocusOwner(); if (focus == null) { Window[] owned = w.getOwnedWindows(); for (int i=0;i < owned.length;i++) { if ((focus = owned[i].getFocusOwner()) != null) return focus; } } return focus; } /** For debugging purposes only. */ public static AppContext getAppContext(Component c) { try { Field field = Component.class.getDeclaredField("appContext"); boolean accessible = field.isAccessible(); field.setAccessible(true); AppContext appContext = (AppContext)field.get(c); field.setAccessible(accessible); return appContext; } catch(Exception e) { Log.warn(e); return null; } } /** WARNING: This uses 1.3/1.4 implementation details. */ public static boolean eventTypeEnabled(Component c, int id) { // certain AWT components should have events enabled, even if they // claim not to. // NOTE: Checkbox could be included here, obviating the need for // CheckboxTester's AWT-mode function. if (c instanceof Choice) return true; try { AWTEvent ev = new AWTEvent(c, id) { }; Method m = Component.class.getDeclaredMethod("eventEnabled", new Class[] { AWTEvent.class }); m.setAccessible(true); Boolean b = (Boolean)m.invoke(c, new Object[] { ev }); return b.booleanValue(); } catch(Exception e) { Log.warn(e); return true; } } // Don't use the full classname, since anonymous inner classnames // are dependent on order of appearance in the source static final String ROOT_FRAME_CLASSNAME = SwingUtilities.class.getName() + "$"; /** Is the given component the default Swing hidden frame? */ public static boolean isSharedInvisibleFrame(Component c) { // Must perform an additional check, since applets may // have their own version in their AppContext return c instanceof Frame && (c == JOptionPane.getRootFrame() || c.getClass().getName().startsWith(ROOT_FRAME_CLASSNAME)); } public static boolean isAppletViewerFrame(Component c) { return c.getClass().getName().equals("sun.applet.AppletViewer"); } private static final Matcher POPUP_MATCHER = new ClassMatcher(JPopupMenu.class, true); /** Returns the currently active popup menu, if any. If no popup is currently showing, returns null. */ public static JPopupMenu getActivePopupMenu() { try { return (JPopupMenu)BasicFinder.getDefault().find(POPUP_MATCHER); } catch(ComponentSearchException e) { return null; } } /** Find the currently active Swing popup menu, if any, waiting up to POPUP_TIMEOUT ms. Returns null if no popup found. */ public static JPopupMenu findActivePopupMenu() { JPopupMenu popup = getActivePopupMenu(); if (popup == null && !SwingUtilities.isEventDispatchThread()) { long now = System.currentTimeMillis(); while ((popup = getActivePopupMenu()) == null) { if (System.currentTimeMillis() - now > POPUP_TIMEOUT) { break; } try { Thread.sleep(100); } catch(Exception e) { } } } return popup; } /** Safe version of {@link Component#getLocationOnScreen}, which * avoids lockup if an AWT popup menu is showing. The AWT popup * holds the AWT tree lock when showing, which lock is required by * {@link Component#getLocationOnScreen}. */ public static Point getLocationOnScreen(Component c) { if (isAWTTreeLockHeld()) { if (!c.isShowing()) throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); Point loc = new Point(c.getLocation()); if (!(c instanceof Window)) { Container parent = c.getParent(); if (parent == null) throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); Point ploc = getLocationOnScreen(parent); loc.translate(ploc.x, ploc.y); } return loc; } return new Point(c.getLocationOnScreen()); } /** Return whether the given component is part of a transient dialog. * This includes dialogs generated by JFileChooser, JOptionPane, * JColorChooser, and ProgressMonitor.<p> * Note that it is possible to use JOptionPane.createDialog to create a * reusable dialog, so just because it's transient doesn't mean it will be * disposed of when it is hidden.<p> * Note that this won't detect transient Dialogs after their components * have been reassigned to a new transient Dialog. */ public static boolean isTransientDialog(Component c) { if (c instanceof Window) { if (c instanceof JDialog) { Container contentPane = ((JDialog)c).getContentPane(); Component[] kids = contentPane.getComponents(); if (kids.length == 1) { return kids[0] instanceof JOptionPane || kids[0] instanceof JFileChooser || kids[0] instanceof JColorChooser; } } } else if (!(c instanceof JOptionPane // also covers ProgressMonitor || c instanceof JFileChooser || c instanceof JColorChooser)) { Container parent = c.getParent(); return parent != null && isTransientDialog(parent); } return false; } /** Returns the Applet descendent of the given Container, if any. */ public static Applet findAppletDescendent(Container c) { try { return (Applet)BasicFinder.getDefault(). find(c, new ClassMatcher(Applet.class)); } catch(ComponentSearchException e) { return null; } } /** Return whether this is the tertiary button, considering primary to be * button1 and secondary to be the popup trigger button. */ public static boolean isTertiaryButton(int mods) { return ((mods & AWTConstants.BUTTON_MASK) != InputEvent.BUTTON1_MASK) && ((mods & AWTConstants.POPUP_MASK) == 0); } /** Convert the string representation into the actual modifier mask. */ public static int getModifiers(String mods) { int value = 0; if (mods != null && !mods.equals("")) { StringTokenizer st = new StringTokenizer(mods, "| "); while (st.hasMoreTokens()) { String flag = st.nextToken(); // Allow short-form modifiers if (!flag.endsWith("_MASK")) flag = flag + "_MASK"; if (AWTConstants.POPUP_MODIFIER.equals(flag)) value |= AWTConstants.POPUP_MASK; else if (AWTConstants.TERTIARY_MODIFIER.equals(flag)) value |= AWTConstants.TERTIARY_MASK; else if (!flag.equals("0")) value |= Reflector.getFieldValue(InputEvent.class, flag); } } return value; } private static String getModifiers(int flags, boolean isMouse) { // Historical note: // On a mac, ALT+BUTTON1 means BUTTON2; META+BUTTON1 means BUTTON3 int macModifiers = InputEvent.CTRL_MASK|InputEvent.ALT_MASK|InputEvent.META_MASK; boolean isMacButton = isMouse && Platform.isMacintosh() && (flags & macModifiers) != 0; String mods = ""; String or = ""; if ((flags & InputEvent.ALT_GRAPH_MASK) != 0) { mods += or + "ALT_GRAPH_MASK"; or = "|"; flags &= ~InputEvent.ALT_GRAPH_MASK; } if ((flags & InputEvent.BUTTON1_MASK) != 0 && !isMacButton) { mods += or + "BUTTON1_MASK"; or = "|"; flags &= ~InputEvent.BUTTON1_MASK; } // Mask for ALT is the same as MB2 if ((flags & InputEvent.ALT_MASK) != 0 && !isMacButton && !isMouse) { mods += or + "ALT_MASK"; or = "|"; flags &= ~InputEvent.ALT_MASK; } // Mac uses ctrl modifier to get MB2 if ((flags & InputEvent.CTRL_MASK) != 0 && !isMacButton) { mods += or + "CTRL_MASK"; or = "|"; flags &= ~InputEvent.CTRL_MASK; } // Mask for META is the same as MB3 if ((flags & InputEvent.META_MASK) != 0 && !isMacButton && !isMouse) { mods += or + "META_MASK"; or = "|"; flags &= ~InputEvent.META_MASK; } if ((flags & AWTConstants.POPUP_MASK) != 0) { mods += or + "POPUP_MASK"; or = "|"; flags &= ~AWTConstants.POPUP_MASK; } if ((flags & AWTConstants.TERTIARY_MASK) != 0) { mods += or + "TERTIARY_MASK"; or = "|"; flags &= ~AWTConstants.TERTIARY_MASK; } if ((flags & InputEvent.SHIFT_MASK) != 0) { mods += or + "SHIFT_MASK"; or = "|"; flags &= ~InputEvent.SHIFT_MASK; } // Empty strings are confusing and invisible; make it explicit if ("".equals(mods)) mods = "0"; return mods; } public static String getKeyModifiers(int flags) { return getModifiers(flags, false); } public static String getMouseModifiers(int flags) { return getModifiers(flags, true); } /** Convert the integer modifier flags into a string representation. */ public static String getModifiers(InputEvent event) { return getModifiers(event.getModifiers(), event instanceof MouseEvent); } public static String getKeyCode(int keycode) { return Reflector.getFieldName(KeyEvent.class, keycode, "VK_"); } public static int getKeyCode(String code) { return Reflector.getFieldValue(KeyEvent.class, code); } public static boolean isModifier(int keycode) { switch(keycode) { case KeyEvent.VK_META: case KeyEvent.VK_ALT: case KeyEvent.VK_ALT_GRAPH: case KeyEvent.VK_CONTROL: case KeyEvent.VK_SHIFT: return true; default: return false; } } public static int keyCodeToMask(int code) { switch(code) { case KeyEvent.VK_META: return InputEvent.META_MASK; case KeyEvent.VK_ALT: return InputEvent.ALT_MASK; case KeyEvent.VK_ALT_GRAPH: return InputEvent.ALT_GRAPH_MASK; case KeyEvent.VK_CONTROL: return InputEvent.CTRL_MASK; case KeyEvent.VK_SHIFT: return InputEvent.SHIFT_MASK; default: throw new IllegalArgumentException("Keycode is not a modifier: " + code); } } /** Convert the given modifier event mask to the equivalent key code. */ public static int maskToKeyCode(int mask) { switch(mask) { case InputEvent.META_MASK: return KeyEvent.VK_META; case InputEvent.ALT_MASK: return KeyEvent.VK_ALT; case InputEvent.ALT_GRAPH_MASK: return KeyEvent.VK_ALT_GRAPH; case InputEvent.CTRL_MASK: return KeyEvent.VK_CONTROL; case InputEvent.SHIFT_MASK: return KeyEvent.VK_SHIFT; default: throw new IllegalArgumentException("Unrecognized mask '" + mask + "'"); } } /** If a component does not have mouse events enabled, use the first ancestor which does. */ public static Component retargetMouseEvent(Component comp, int id, Point pt) { Point where = pt; while (!(comp instanceof Window) && !eventTypeEnabled(comp, id)) { Log.debug("Retargeting event, " + Robot.toString(comp) + " not interested"); where = SwingUtilities.convertPoint(comp, where.x, where.y, comp.getParent()); comp = comp.getParent(); } pt.setLocation(where); return comp; } public static Insets getInsets(Container c) { try { Insets insets = c.getInsets(); if (insets != null) return insets; } catch(NullPointerException e) { // FileDialog.getInsets() throws (1.4.2_07) } return new Insets(0, 0, 0, 0); } // Try to lock the AWT tree lock; returns immediately if it can private static class ThreadStateChecker extends Thread { public boolean started; private Object lock; public ThreadStateChecker(Object lock) { super("thread state checker"); setDaemon(true); this.lock = lock; } public synchronized void start() { super.start(); try { wait(30000); } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted starting AWT object"); } } public void run() { synchronized(this) { started = true; notifyAll(); } synchronized(lock) { // dummy operation setName(super.getName()); } } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/AWTFixtureHelper.java
package abbot.util; import abbot.InterruptedAbbotException; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Window; import java.awt.event.*; import java.util.Iterator; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import abbot.Log; import abbot.finder.BasicFinder; import abbot.finder.ComponentFinder; import abbot.finder.ComponentNotFoundException; import abbot.finder.ComponentSearchException; import abbot.finder.Hierarchy; import abbot.finder.Matcher; import abbot.finder.MultipleComponentsFoundException; import abbot.finder.TestHierarchy; import abbot.finder.matchers.ClassMatcher; import abbot.finder.matchers.WindowMatcher; import abbot.tester.Robot; import abbot.tester.WindowTracker; import java.awt.Color; import java.awt.Toolkit; /** Provides various facilities for setting up, using, and tearing down * a test involving UI components. * Handles standardized AWTEvent logging and catching exceptions on the * AWT event dispatch thread (EDT). * This class should be used at setup and teardown of your chosen fixture. * @see junit.extensions.abbot.ComponentTestFixture * @see abbot.script.StepRunner */ public class AWTFixtureHelper { /** Typical delay to wait for a robot event to be translated into a Java event. */ public static final int EVENT_GENERATION_DELAY = 5000; public static final int WINDOW_DELAY = 20000; // for slow systems public static final int POPUP_DELAY = 10000; private AWTEventListener listener = null; private SystemState state; private Robot robot; private WindowTracker tracker; private Hierarchy hierarchy; // modifiers set during this helper's lifetime (to be cleared on dispose) private int modifiers; public AWTFixtureHelper() { this(new TestHierarchy()); } /** Create an instance of AWTFixtureHelper which makes a snapshot of the current VM state. */ public AWTFixtureHelper(Hierarchy hierarchy) { // Preserve all system properties to restore them later state = new SystemState(); this.hierarchy = hierarchy; // Install our own event handler, which will forward events thrown on // the event queue try { new EDTExceptionCatcher().install(); } catch(RuntimeException re) { // Not fatal if we can't install, since most tests don't // depend on it. We won't be able to throw errors that were // generated on the event dispatch thread, though. } // Only enable event logging if debug is enabled for this class // Facilitate debugging by logging all events if (Boolean.getBoolean("abbot.fixture.log_events")) { long mask = Properties.getProperty("abbot.fixture.event_mask", Long.MIN_VALUE, Long.MAX_VALUE, abbot.editor.recorder. EventRecorder. RECORDING_EVENT_MASK); Log.log("Using mask value " + mask); listener = new AWTEventListener() { public void eventDispatched(AWTEvent event) { if (listener != null) Log.log(Robot.toString(event)); } }; new WeakAWTEventListener(listener, mask); } robot = new Robot(); tracker = WindowTracker.getTracker(); SystemState.clearLockingKeys(); robot.reset(); if (Bugs.hasMultiClickFrameBug()) robot.delay(500); } public Robot getRobot() { return robot; } public WindowTracker getWindowTracker() { return tracker; } public Hierarchy getHierarchy() { return hierarchy; } /** Returns the last exception thrown on the event dispatch thread, or <code>null</code> if no such exception has been thrown. */ public Throwable getEventDispatchError() { return EDTExceptionCatcher.getThrowable(); } /** Returns the time of the last exception thrown on the event dispatch thread. */ public long getEventDispatchErrorTime() { return EDTExceptionCatcher.getThrowableTime(); } /** Convenience method to set key modifiers. Using this method is * preferred to invoking {@link Robot#setModifiers(int,boolean)} or * {@link Robot#keyPress(int)}, since this method's effects will be * automatically undone at the end of the test. If you use the * {@link Robot} methods, you must remember to release any keys pressed * during the test. * @param modifiers mask indicating which modifier keys to use * @param pressed whether the modifiers should be in the pressed state. */ public void setModifiers(int modifiers, boolean pressed) { if (pressed) this.modifiers |= modifiers; else this.modifiers &= ~modifiers; robot.setModifiers(modifiers, pressed); robot.waitForIdle(); } protected void disposeAll() { Iterator iter = hierarchy.getRoots().iterator(); while (iter.hasNext()) { hierarchy.dispose((Window)iter.next()); } } /** Restore the state that was preserved when this object was created. */ public void restore() { if (AWT.isAWTPopupMenuBlocking()) AWT.dismissAWTPopup(); state.restore(); // Encourage GC of unused components, which reduces the load on // future tests. System.gc(); System.runFinalization(); } /** Dispose all windows created during this object's lifetime and restore * the previous system/UI state, to the extent possible. */ public void dispose() { // WARNING: clear input state prior to disposing windows, // otherwise native drag operations may be left stuck if (robot != null) { if (modifiers != 0) { robot.setModifiers(modifiers, false); modifiers = 0; } int buttons = Robot.getState().getButtons(); if (buttons != 0) { Log.debug("release " + AWT.getMouseModifiers(buttons)); robot.mouseRelease(buttons); } if (robot.getState().isNativeDragActive()) { robot.keyPress(KeyEvent.VK_ESCAPE); robot.keyRelease(KeyEvent.VK_ESCAPE); } // TODO: release *any* keys that were pressed, not just modifiers } disposeAll(); restore(); } /** This method should be invoked to display the component under test. * The frame's size will be its preferred size. This method will return * with the enclosing {@link Frame} is showing and ready for input. */ public Frame showFrame(Component comp) { return showFrame(comp, null); } /** This method should be invoked to display the component under test, * when a specific size of frame is desired. The method will return when * the enclosing {@link Frame} is showing and ready for input. * @param comp * @param size Desired size of the enclosing frame, or <code>null</code> * to make no explicit adjustments to its size. */ public Frame showFrame(Component comp, Dimension size) { return showFrame(comp, size, "Test Frame"); } /** This method should be invoked to display the component under test, * when a specific size of frame is desired. The method will return when * the enclosing {@link Frame} is showing and ready for input. * @param comp * @param size Desired size of the enclosing frame, or <code>null</code> * to make no explicit adjustments to its size. * @param title Title of the wrapping frame */ public Frame showFrame(Component comp, Dimension size, String title) { JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pane = (JPanel)frame.getContentPane(); pane.setBorder(new EmptyBorder(10, 10, 10, 10)); pane.add(comp); showWindow(frame, size, true); return frame; } /** Safely display a window with proper EDT synchronization. This method * blocks until the {@link Window} is showing and ready for input. */ public void showWindow(Window w) { showWindow(w, null, true); } /** Safely display a window with proper EDT synchronization. This method * blocks until the {@link Window} is showing and ready for input. */ public void showWindow(final Window w, final Dimension size) { showWindow(w, size, true); } /** Safely display a window with proper EDT synchronization. This method * blocks until the window is showing. This method will return even when * the window is a modal dialog, since the show method is called on the * event dispatch thread. The window will be packed if the pack flag is * set, and set to the given size if it is non-<code>null</code>.<p> * Modal dialogs may be shown with this method without blocking. */ public void showWindow(final Window w, final Dimension size, final boolean pack) { EventQueue.invokeLater(new Runnable() { public void run() { if (pack) { w.pack(); // Make sure the window is positioned away from // any toolbars around the display borders w.setLocation(100, 100); } if (size != null) w.setSize(size.width, size.height); w.setVisible(true); } }); // Ensure the window is visible before returning waitForWindow(w, true); } /** Return when the window is ready for input or times out waiting. * @param w */ public void waitForWindow(Window w, boolean visible) { long start = System.currentTimeMillis(); while ((Robot.getEventMode() == Robot.EM_ROBOT && visible && !getWindowTracker().isWindowReady(w)) || w.isShowing() != visible) { long elapsed = System.currentTimeMillis() - start; if (elapsed > WINDOW_DELAY) throw new RuntimeException("Timed out waiting for Window to " + (visible ? "open" : "close") + " (" + elapsed + "ms)"); getRobot().sleep(); } getRobot().waitForIdle(); } /** Synchronous, safe hide of a window. The window is ensured to be * hidden ({@link java.awt.event.ComponentEvent#COMPONENT_HIDDEN} or * equivalent has been posted) when this method returns. Note that this * will <em>not</em> trigger a * {@link java.awt.event.WindowEvent#WINDOW_CLOSING} event; use * {@link abbot.tester.WindowTester#actionClose(Component)} * if a window manager window close operation is required. */ public void hideWindow(final Window w) { EventQueue.invokeLater(new Runnable() { public void run() { w.setVisible(false); } }); waitForWindow(w, false); // Not strictly required, but if a test is depending on a window // event listener's actions on window hide/close, better to wait. getRobot().waitForIdle(); } /** Synchronous, safe dispose of a window. The window is ensured to be * disposed ({@link java.awt.event.WindowEvent#WINDOW_CLOSED} has been * posted) when this method returns. */ public void disposeWindow(Window w) { w.dispose(); waitForWindow(w, false); getRobot().waitForIdle(); } /** Convenience for <code>getRobot().invokeAndWait(Runnable)</code>. */ public void invokeAndWait(Runnable runnable) { getRobot().invokeAndWait(runnable); } /** Convenience for <code>getRobot().invokeLater(Runnable)</code>. */ public void invokeLater(Runnable runnable) { getRobot().invokeLater(runnable); } /** Install the given popup on the given component. Takes care of * installing the appropriate mouse handler to activate the popup. */ public void installPopup(Component invoker, final JPopupMenu popup) { invoker.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { mouseReleased(e); } public void mouseClicked(MouseEvent e) { mouseReleased(e); } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); } /** Safely install and display a popup in the center of the given * component, returning when it is visible. Does not install any mouse * handlers not generate any mouse events. */ public void showPopup(final JPopupMenu popup, final Component invoker) { showPopup(popup, invoker, invoker.getWidth()/2, invoker.getHeight()/2); } /** Safely install and display a popup, returning when it is visible. Does not install any mouse handlers not generate any mouse events. */ public void showPopup(final JPopupMenu popup, final Component invoker, final int x, final int y) { EventQueue.invokeLater(new Runnable() { public void run() { popup.show(invoker, x, y); } }); long start = System.currentTimeMillis(); while (!popup.isShowing()) { if (System.currentTimeMillis() - start > POPUP_DELAY) throw new RuntimeException("Timed out waiting for popup to show"); robot.sleep(); } waitForWindow(SwingUtilities.getWindowAncestor(popup), true); } /** Display a modal dialog and wait for it to show. Useful for things * like * {@link javax.swing.JFileChooser#showOpenDialog(java.awt.Component)} or * {@link javax.swing.JOptionPane#showInputDialog(Object)}, or any * other instance where the dialog contents are not predefined and * displaying the dialog involves anything more than * {@link Window#setVisible(boolean) show()/setVisible(true} * (if {@link Window#setVisible(boolean) show()/setVisible(true)} is all * that is required, use the {@link #showWindow(Window)} method instead).<p> * The given {@link Runnable} should contain the code which will show the * modal {@link Dialog} (and thus block); it will be run on the event * dispatch thread.<p> * This method will return when a {@link Dialog} becomes visible which * contains the given component (which may be any component which will * appear on the {@link Dialog}), or the standard timeout (10s) is * reached, at which point a {@link RuntimeException} will be thrown.<p> * For example,<br> <pre><code> final Frame parent = ...; Dialog d = showModalDialog(new Runnable) { public void run() { JOptionPane.showInputDialog(parent, "Hit me"); } }); </code></pre> @see #showWindow(java.awt.Window) @see #showWindow(java.awt.Window,java.awt.Dimension) @see #showWindow(java.awt.Window,java.awt.Dimension,boolean) */ public Dialog showModalDialog(final Runnable showAction) throws ComponentSearchException { return showModalDialog(showAction, new BasicFinder(hierarchy)); } /** Same as {@link #showModalDialog(Runnable)}, but provides a custom * {@link ComponentFinder} to find the dialog. */ public Dialog showModalDialog(final Runnable showAction, ComponentFinder finder) throws ComponentSearchException { final boolean[] modalRun = {false}; final boolean[] invocationFinished = { false }; EventQueue.invokeLater(new Runnable() { public void run() { modalRun[0] = true; try { showAction.run(); } finally { // Detect premature Runnable return invocationFinished[0] = true; } } }); while (!modalRun[0]) { try { Thread.sleep(10); } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted when waiting for dialog"); } } // Wait for any modal dialog to appear Matcher matcher = new ClassMatcher(Dialog.class, true) { public boolean matches(Component c) { return super.matches(c) && ((Dialog)c).isModal() && AWT.containsFocus(c); } }; long start = System.currentTimeMillis(); boolean finished = false; while (true) { try { return (Dialog)finder.find(matcher); } catch(ComponentSearchException e) { if (invocationFinished[0]) { // ensure we do one more check to see if the dialog is there if (finished) break; finished = true; } if (System.currentTimeMillis() - start > 10000) throw new ComponentSearchException("Timed out waiting for dialog to be ready"); robot.sleep(); } } throw new ComponentSearchException("No dialog was displayed (premature return=" + finished + ")"); } /** Returns whether a Component is showing. The ID may be the component * name or, in the case of a Frame or Dialog, the title. Regular * expressions may be used, but must be delimited by slashes, e.g. /expr/. * Returns if one or more matches is found. */ public boolean isShowing(String id) { return isShowing(id, new BasicFinder(hierarchy)); } /** Same as {@link #isShowing(String)}, but uses the given * ComponentFinder to do the lookup. */ public boolean isShowing(String id, ComponentFinder finder) { try { finder.find(new WindowMatcher(id, true)); } catch(ComponentNotFoundException e) { return false; } catch(MultipleComponentsFoundException m) { // Might not be the one you want, but that's what the docs say } return true; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Bugs.java
/* * Copyright 2004 Timothy Wall * */ package abbot.util; import java.awt.Window; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import abbot.Log; import abbot.Platform; import abbot.i18n.Strings; import abbot.tester.Robot; /** Provides extant bug characterization of the current platform. For any bug encountered, there should be a static method indicating whether the bug is expected on the current platform, for example {@link #showAWTPopupMenuBlocks()}. See the source for <code> <a href=../../../../test/abbot/util/BugsTest.java>BugsTest</a></code> for the test implementations. @author twall */ public class Bugs { private static java.util.ArrayList bugList = null; private static boolean gotBug1Event = false; private Bugs() { } /** Returns whether AWT menus have enable/disable problems. */ public static boolean hasMenuDisableBug() { return Platform.isOSX() && Platform.JAVA_VERSION >= Platform.JAVA_1_4 && Platform.JAVA_VERSION < 0x1424; // when it got fixed } /** Returns whether KEY_TYPED events are sent to AWT listeners. */ public static boolean hasInputMethodInsteadOfKeyTyped() { return Platform.isOSX() && Platform.JAVA_VERSION >= Platform.JAVA_1_4 && Platform.JAVA_VERSION < 0x1424; // when it got fixed } /** Returns whether windows send mouse motion events to AWT listeners. */ public static boolean hasMissingWindowMouseMotion() { return Platform.isOSX() && Platform.JAVA_VERSION >= Platform.JAVA_1_4 && Platform.JAVA_VERSION <= 0x1600; // most recent tested } /** Returns whether mouse buttons 2/3 are swapped when using Robot. */ public static boolean hasRobotButtonsSwapped() { return Platform.isOSX() && Platform.JAVA_VERSION >= Platform.JAVA_1_4 && Platform.JAVA_VERSION <= 0x1425; // most recent tested } /** Do we get multiple clicks even when the individual clicks are on * different frames? */ // Will we get incorrectly get multiple clicks on rapid robot clicks? // frame1->click,frame2->click // frame1->click,frame1->hide/show,frame1->click public static boolean hasMultiClickFrameBug() { // w32 (1.3.02) will count it even if it was on a different component! // w32 (1.3.1_06) same // w32 (1.4.1_02) same (sporadic) // OSX (1.3.x, 1.4.1) has the same problem // Haven't seen it on linux return Platform.isWindows() || Platform.isOSX() || Platform.JAVA_VERSION < Platform.JAVA_1_3; } /** Returns whether there may be some scenarios in which the robot does not function properly. */ public static boolean needsRobotVerification() { return Platform.isWindows(); } /** Prior to 1.4.1, hierarchy events are only sent if listeners are added to a given component. */ public static boolean hasHierarchyEventGenerationBug() { return Platform.JAVA_VERSION < Platform.JAVA_1_4; } /** OSX prior to 1.4 has really crappy key input handling. */ public static boolean hasKeyStrokeGenerationBug() { return Platform.isOSX() && Platform.JAVA_VERSION < Platform.JAVA_1_4; } /** Returnes whether there a longer delay required between robot generation and event queue posting for key events. */ public static boolean hasKeyInputDelay() { return Platform.isOSX() && Platform.JAVA_VERSION >= Platform.JAVA_1_4 && Platform.JAVA_VERSION <= 0x1425; } /** Some OSX releases wouldn't restore an iconified Frame. */ public static boolean hasFrameDeiconifyBug() { return Platform.isOSX() && Platform.JAVA_VERSION > 0x1310 && Platform.JAVA_VERSION < 0x1424; } /** OS X (as of 1.3.1, v10.1.5), will sometimes send a click to the wrong component after a mouse move. This continues to be an issue in 1.4.1 <p> Linux x86 (1.3.1) has a similar problem, although it manifests it at different times (need a bug test case for this one). <p> Solaris and HPUX probably share code with the linux VM implementation, so the bug there is probably identical. <p> */ // FIXME add tests to determine presence of bug. public static boolean hasRobotMotionBug() { return Platform.isOSX() || (!Platform.isWindows() && Platform.JAVA_VERSION < Platform.JAVA_1_4) || Boolean.getBoolean("abbot.robot.need_jitter"); } /** Choice popup activates on mouse press, but locks up when the Robot * attempts to post a mouse release. */ public static boolean hasChoiceLockupBug() { return Platform.isOSX() && Platform.JAVA_VERSION < Platform.JAVA_1_4; } /** Robot.keyPress(KeyEvent.VK_ESCAPE doesn't work. */ public static boolean hasEscapeGenerationBug() { return Platform.isOSX() && Platform.JAVA_VERSION < Platform.JAVA_1_4; } /** Returns whether the Java event queue is suspended while an AWT popup is showing. */ public static boolean showAWTPopupMenuBlocks() { return Platform.isWindows() && Platform.JAVA_VERSION <= Platform.JAVA_1_6; } /** Locking key state is reported incorrectly. Later versions (at least 1.4.2_11) throw UnsupportedOperationException). */ public static boolean reportsIncorrectLockingKeyState() { return Platform.isLinux() && Platform.JAVA_VERSION <= 0x1424; } /** Whether drag/drop requires native events. */ // TODO: needs a test public static boolean dragDropRequiresNativeEvents() { return Platform.JAVA_VERSION <= 0x1425; } /** Returns whether a {@link java.awt.FileDialog} requires an explicit dismiss (ok/cancel). Ordinarily {@link Window#dispose()} will work. */ public static boolean fileDialogRequiresDismiss() { return Platform.isOSX() && Platform.JAVA_VERSION <= 0x1600 // not sure exactly when this was fixed || (Platform.isWindows() && Platform.JAVA_VERSION < 0x1412); } /** Returns whether a {@link java.awt.FileDialog} misreports its screen location. */ public static boolean fileDialogMisreportsBounds() { return (Platform.isOSX() && Platform.JAVA_VERSION <= 0x1600) || (Platform.isWindows() && Platform.JAVA_VERSION <= Platform.JAVA_1_5); } public static boolean fileDialogRequiresVisibleFrame() { // Subsequent FileDialogs don't show up if the frame isn't visible, // and a previous non-visible frame was disposed. return Platform.isWindows() && Platform.JAVA_VERSION <= 0x1421; } public static boolean hasTextComponentSelectionDelay() { // TODO: write a test for this one // Select TextComponent text, wait for idle, selection end not updated return (Platform.isLinux() || Platform.isWindows()) && Platform.JAVA_VERSION <= 0x1424; } public static boolean hasNoAWTInputOnTextFieldBug() { return Platform.isLinux() && Platform.JAVA_VERSION < 0x1500 || Platform.isOSX() && Platform.JAVA_VERSION <= 0x1600; } public static boolean locksUpOnScreenCapture() { return Platform.isLinux() && Platform.JAVA_VERSION >= 0x1400 && Platform.JAVA_VERSION <= 0x1505; } /** Check for certain robot-related bugs that will affect Abbot * operation. Returns a String for each bug detected on the current * system. */ public static String[] bugCheck(final Window window) { if (bugList == null) { bugList = new java.util.ArrayList(); final int x = window.getWidth() / 2; final int y = window.getHeight() / 2; if (Platform.isWindows() && !Platform.isWindowsXP() && Platform.JAVA_VERSION < Platform.JAVA_1_4) { Log.debug("Checking for w32 bugs"); final int mask = InputEvent.BUTTON2_MASK; MouseAdapter ma = new MouseAdapter() { public void mouseClicked(MouseEvent e) { gotBug1Event = true; // w32 acceleration settings bug if (e.getX() != x || e.getY() != y) { bugList.add(Strings.get("Bug1")); } // w32 mouse button mapping bug if ((e.getModifiers() & mask) != mask) { bugList.add(Strings.get("Bug2")); } } }; window.addMouseListener(ma); Robot robot = new Robot(); robot.click(window, x, y, mask); robot.waitForIdle(); window.toFront(); // Bogus acceleration may mean the event goes entirely // elsewhere if (!gotBug1Event) { bugList.add(0, Strings.get("Bug1")); } window.removeMouseListener(ma); } else if (Platform.isOSX() && Platform.JAVA_VERSION < 0x1430) { Log.debug("Checking for OSX bugs"); final int mask = InputEvent.BUTTON2_MASK; MouseAdapter ma = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & mask) != mask) { bugList.add(Strings.get("robot.bug3")); } } }; window.addMouseListener(ma); Robot robot = new Robot(); robot.click(window, x, y, mask); robot.waitForIdle(); window.removeMouseListener(ma); } } return (String[])bugList.toArray(new String[bugList.size()]); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Condition.java
package abbot.util; /** Abstract a condition test. */ public interface Condition { /** Return the condition state. */ boolean test(); /** Return a description of what the condition is testing. */ String toString(); }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/EDTExceptionCatcher.java
/* * Copyright (c) 2005 Timothy Wall, All Rights Reserved */ package abbot.util; import abbot.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** Provide access to the most recent exception caught on the event dispatch thread. */ public class EDTExceptionCatcher extends EventDispatchExceptionHandler { private static Throwable throwable = null; private static long when = -1; public void install() { clear(); super.install(); } /** Return the most recent exception caught on the dispatch thread, or <code>null</code> if none has been thrown or the exception has been cleared. Also clears the exception. */ public static Throwable getThrowable() { synchronized (synchronizedBlock) { Throwable t = throwable; clear(); return t; } } /** Returns when the most recent exception was caught on the dispatch thread, or -1 if none has been thrown or the exception has been cleared. */ public static long getThrowableTime() { synchronized (synchronizedBlock) { return when; } } public static void clear() { synchronized (synchronizedBlock) { throwable = null; when = -1; } } /** * Note we are synchronized by synchronizeBlock at this point */ protected void exceptionCaught(Throwable thr) { if (!(thr instanceof ExitException)) { if (thr.getClass().getName().startsWith("sun.awt.SunToolkit")) { Log.warn("Ignoring an exception from the sun toolkit as likely an artifact of a realSyncFailure", thr); return; } if (System.getProperty("java.class.path").indexOf("eclipse") != -1) { Log.warn("An exception was thrown on the EDT: " + thr, thr); } else { Log.log("An exception was thrown on the EDT: " + thr, thr); } synchronized(EDTExceptionCatcher.class) { when = System.currentTimeMillis(); throwable = thr; } } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/EventDispatchExceptionHandler.java
package abbot.util; import java.awt.EventQueue; import javax.swing.SwingUtilities; import abbot.Log; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Handler for uncaught exceptions on any event dispatch thread.<p> * It now uses the Thread.UncaughtExceptionHandler class which introduces * a minor issue in that when this is called the current event queue object * has already been replaced by a new instance. (See the source code for * {@link java.awt.EventDispatchThread#run} for more information). To work around * this a shared synchronization object has been added, although a read/write lock * would also have been a possible design and should be considered if a time out * ends up being required. */ public class EventDispatchExceptionHandler { private static boolean installed = false; private static boolean canInstall = true; /** * Allows sychronization between the current queue and the exception handler * queue of which the only thing we know for sure is that it is definitely not * the AWT event queue, if it ever was. */ private static CountDownLatch instalLatch = new CountDownLatch(1); /** * We need to make sure that we can't query the state of the hander while we are dealing with an exception */ protected static Object synchronizedBlock = new Object() {}; private static Thread.UncaughtExceptionHandler existingHandler; public void install() { if (SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException("Handler must not be installed from the event dispatch thread"); } if (!canInstall) { Log.warn("Can't install event dispatch exception handler"); } else if (!installed) { existingHandler = Thread.getDefaultUncaughtExceptionHandler(); final Thread.UncaughtExceptionHandler swingOnly = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { synchronized (synchronizedBlock) { // So at this point the original thread has died // so we would need to be able to add another exception listener to the thread // that doesn't necessarily exist as yet, so we need to test to see if t is an intance // of EventDispatchThread // and make sure that the existing handler is check for the current thread // boolean isWasEDT = false; Class $parent = t.getClass(); while ($parent!=null && !isWasEDT) { String name = $parent.getName(); if ("java.awt.EventDispatchThread".equals(name)) { isWasEDT = true; } $parent = $parent.getSuperclass(); } if (!isWasEDT) { if (existingHandler!=null) { existingHandler.uncaughtException(t,e); } else { e.printStackTrace(); } } // The exception may be created by a different class loader // so compare by name only if (e instanceof DummyException) { // Install succeeded Log.debug("Installation succeeded"); installed = true; instalLatch.countDown(); return; } // We are assuming that the current thread is the EDT, so delegate to // the existing handler is required if (existingHandler!=null) { existingHandler.uncaughtException(t, e); } else { handle(e); } } } }; try { Thread.currentThread().setDefaultUncaughtExceptionHandler(swingOnly); // Check we can catch the dummy exception // EventQueue.invokeLater(new Runnable() { public void run() { throw new DummyException(); } }); // Does nothing but wait for the previous invocation to finish AWT.invokeAndWait(new Runnable() { public void run() { } }); if (instalLatch.await(30, TimeUnit.SECONDS) && installed) { // Horrah we are good to go int i = 9; } else { // canInstall = false; } } catch (Exception e) { installed = false; canInstall = false; String msg = "The handler for event " + "dispatch thread exceptions could not be installed"; Log.warn(msg, e); throw new RuntimeException(msg, e); } } else { // We are fine, don't install again // Log.debug("Exception handler class already installed"); } } /** Define this to handle the exception as needed. * Default prints a warning to System.err. */ protected void exceptionCaught(Throwable thrown) { System.err.println("Exception caught on event dispatch thread: " + thrown); } /** Handle exceptions thrown on the event dispatch thread. */ public void handle(Throwable thrown) { Log.debug("Handling event dispatch exception: " + thrown); { Log.debug("Handling exception on event dispatch thread: " + thrown + " with " + getClass()); Log.debug(thrown); exceptionCaught(thrown); } Log.debug("Handling done"); } public static boolean isInstalled() { return installed; } private static class DummyException extends RuntimeException { public String toString() { return super.toString() + " " + getClass().getClassLoader(); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/EventNormalizer.java
package abbot.util; import java.awt.*; import java.awt.event.*; import javax.swing.text.*; import java.text.*; import java.util.*; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import abbot.Log; /** Provide an AWTEventListener which normalizes the event stream. <ul> <li>removes modifier key repeats on w32 <li>sends a single WINDOW_CLOSED, instead of one every time dispose is called <li>removes some spurious key events on OSX <li>catches sun.awt.dnd.SunDropTargetEvents during native drags </ul> */ public class EventNormalizer implements AWTEventListener { // Normally we want to ignore these (w32 generates them) private static boolean captureModifierRepeats = Boolean.getBoolean("abbot.capture_modifier_repeats"); private AWTEventListener listener; private WeakAWTEventListener weakListener; private long modifiers; private Map disposedWindows = new WeakHashMap(); private DragAwareEventQueue queue; private long mask; private boolean trackDrag; public EventNormalizer() { this(false); } public EventNormalizer(boolean trackDrag) { this.trackDrag = trackDrag; } public void startListening(AWTEventListener listener, long mask) { Log.debug("start listening, mask=0x" + Integer.toHexString((int)mask)); fnKeyDown = false; lastKeyPress = lastKeyRelease = KeyEvent.VK_UNDEFINED; lastKeyStroke = null; lastKeyChar = KeyEvent.VK_UNDEFINED; lastKeyComponent = null; modifiers = 0; this.listener = listener; this.mask = mask; weakListener = new WeakAWTEventListener(this, mask); if (trackDrag) { queue = new DragAwareEventQueue(); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { Toolkit.getDefaultToolkit().getSystemEventQueue().push(queue); }}); } catch(Exception e) { Log.warn(e); } } Log.debug("normalizer now listening"); } public void stopListening() { if (queue != null) { try { queue.pop(); } catch(EmptyStackException e) { Log.warn(e); } queue = null; } if (weakListener != null) { weakListener.dispose(); weakListener = null; } listener = null; modifiers = 0; } /** For OSX pre-1.4 laptops... */ private boolean fnKeyDown; /** These aid in culling duplicate key events, pre-1.4. */ private int lastKeyPress = KeyEvent.VK_UNDEFINED; private int lastKeyRelease = KeyEvent.VK_UNDEFINED; private KeyStroke lastKeyStroke; private char lastKeyChar = KeyEvent.VK_UNDEFINED; private Component lastKeyComponent; /** Returns whether the event is spurious and should be discarded. */ private boolean isSpuriousEvent(AWTEvent event) { return isDuplicateKeyEvent(event) || isOSXFunctionKey(event) || isDuplicateDispose(event); } // TODO: maybe make this an AWT event listener instead, so we can use one // instance instead of one per window. private class DisposalWatcher extends ComponentAdapter { private Map map; public DisposalWatcher(Map map) { this.map = map; } public void componentShown(ComponentEvent e) { e.getComponent().removeComponentListener(this); map.remove(e.getComponent()); } } // We want to ignore consecutive event indicating window disposal; there // needs to be an intervening SHOWN/OPEN before we're interested again. private boolean isDuplicateDispose(AWTEvent event) { if (event instanceof WindowEvent) { WindowEvent we = (WindowEvent)event; switch(we.getID()) { case WindowEvent.WINDOW_CLOSED: Window w = we.getWindow(); if (disposedWindows.containsKey(w)) { return true; } disposedWindows.put(w, Boolean.TRUE); w.addComponentListener(new DisposalWatcher(disposedWindows)); break; case WindowEvent.WINDOW_CLOSING: break; default: disposedWindows.remove(we.getWindow()); break; } } return false; } /** Flag duplicate key events on pre-1.4 VMs, and repeated modifiers. */ private boolean isDuplicateKeyEvent(AWTEvent event) { int id = event.getID(); if (id == KeyEvent.KEY_PRESSED) { KeyEvent ke = (KeyEvent)event; lastKeyRelease = KeyEvent.VK_UNDEFINED; int code = ke.getKeyCode(); if (code == lastKeyPress) { // Discard duplicate key events; they don't add any // information. // A duplicate key event is sent to the parent frame on // components that don't otherwise consume it (JButton) if (event.getSource() != lastKeyComponent) { lastKeyPress = KeyEvent.VK_UNDEFINED; lastKeyComponent = null; return true; } } lastKeyPress = code; lastKeyComponent = ke.getComponent(); // Don't pass on key repeats for modifier keys (w32) if (AWT.isModifier(code)) { int mask = AWT.keyCodeToMask(code); if ((mask & modifiers) != 0 && !captureModifierRepeats) { return true; } } modifiers = ke.getModifiers(); } else if (id == KeyEvent.KEY_RELEASED) { KeyEvent ke = (KeyEvent)event; lastKeyPress = KeyEvent.VK_UNDEFINED; int code = ke.getKeyCode(); if (code == lastKeyRelease) { if (event.getSource() != lastKeyComponent) { lastKeyRelease = KeyEvent.VK_UNDEFINED; lastKeyComponent = null; return true; } } lastKeyRelease = code; lastKeyComponent = ke.getComponent(); modifiers = ke.getModifiers(); } else if (id == KeyEvent.KEY_TYPED) { KeyStroke ks = KeyStroke.getKeyStrokeForEvent((KeyEvent)event); char ch = ((KeyEvent)event).getKeyChar(); if (ks.equals(lastKeyStroke) || ch == lastKeyChar) { if (event.getSource() != lastKeyComponent) { lastKeyStroke = null; lastKeyChar = KeyEvent.VK_UNDEFINED; lastKeyComponent = null; return true; } } lastKeyStroke = ks; lastKeyChar = ch; lastKeyComponent = ((KeyEvent)event).getComponent(); } else { lastKeyPress = lastKeyRelease = KeyEvent.VK_UNDEFINED; lastKeyComponent = null; } return false; } /** Discard function key press/release on 1.3.1 OSX laptops. */ // FIXME fn pressed after arrow keys results in a RELEASE event private boolean isOSXFunctionKey(AWTEvent event) { if (event.getID() == KeyEvent.KEY_RELEASED) { if (((KeyEvent)event).getKeyCode() == KeyEvent.VK_CONTROL && fnKeyDown) { fnKeyDown = false; return true; } } else if (event.getID() == KeyEvent.KEY_PRESSED) { if (((KeyEvent)event).getKeyCode() == KeyEvent.VK_CONTROL) { int mods = ((KeyEvent)event).getModifiers(); if ((mods & KeyEvent.CTRL_MASK) == 0) { fnKeyDown = true; return true; } } } return false; } protected void delegate(AWTEvent e) { if (Bugs.hasInputMethodInsteadOfKeyTyped()) { if (e.getSource() instanceof JTextComponent && e.getID() == InputMethodEvent.INPUT_METHOD_TEXT_CHANGED) { InputMethodEvent im = (InputMethodEvent)e; if (im.getCommittedCharacterCount() > 0) { AttributedCharacterIterator iter = im.getText(); for (char ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) { e = new KeyEvent((Component)e.getSource(), KeyEvent.KEY_TYPED, System.currentTimeMillis(), (int)modifiers, KeyEvent.VK_UNDEFINED, ch); listener.eventDispatched(e); } return; } } } listener.eventDispatched(e); } /** Event reception callback. */ public void eventDispatched(AWTEvent event) { boolean discard = isSpuriousEvent(event); if (!discard && listener != null) { delegate(event); } } /** Catches native drop target events, which are normally hidden * from AWTEventListeners. */ private class DragAwareEventQueue extends EventQueue { protected void relayDnDEvent(MouseEvent e) { int id = e.getID(); if (id == MouseEvent.MOUSE_MOVED || id == MouseEvent.MOUSE_DRAGGED) { if ((mask & InputEvent.MOUSE_MOTION_EVENT_MASK) != 0) { eventDispatched(e); } } else if (id >= MouseEvent.MOUSE_FIRST && id <= MouseEvent.MOUSE_LAST) { if ((mask & InputEvent.MOUSE_EVENT_MASK) != 0) { eventDispatched(e); } } } public void pop() throws EmptyStackException { if (Toolkit.getDefaultToolkit().getSystemEventQueue() == this) super.pop(); } /** Dispatch native drag/drop events the same way non-native drags * are reported. Enter/Exit are reported with the appropriate source, * while drag and release events use the drag source as the source.<p> * TODO: implement enter/exit events * TODO: change source to drag source, not mouse under */ protected void dispatchEvent(AWTEvent e) { Log.debug("dispatch " + e); if (e.getClass().getName().indexOf("SunDropTargetEvent") != -1) { MouseEvent me = (MouseEvent)e; Component target = SwingUtilities.getDeepestComponentAt(me.getComponent(), me.getX(), me.getY()); if (target != me.getSource()) { Log.debug("Change drag event target"); me = SwingUtilities.convertMouseEvent(me.getComponent(), me, target); } Log.debug("relay " + me); relayDnDEvent(me); } super.dispatchEvent(e); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/ExtendedComparator.java
package abbot.util; import java.lang.reflect.Array; /** Utility class to perform comparisons. */ public class ExtendedComparator { private ExtendedComparator() { } /** Match with a regexp if the pattern contains a ".*" or is bounded by * slashes (/regexp/). Multiline matches are enabled by /(?m)regexp/. * Embedded newlines ("\n") in the match string will then match * end-of-lines. */ // Requiring exact matches eliminates the need to always include the start // "^" and finish "$" symbols. public static boolean stringsMatch(String pattern, String actual) { if (pattern.startsWith("/") && pattern.substring(1).endsWith("/")) { pattern = pattern.substring(1, pattern.length()-1); return Regexp.stringMatch(pattern, actual); } if (pattern.indexOf(".*") != -1) { return Regexp.stringMatch(pattern, actual); } return pattern.equals(actual); } /** Perform element-by-element comparisons of arrays in addition to regular comparisons. */ public static boolean equals(Object obj1, Object obj2) { boolean result = false; if (obj1 == null && obj2 == null) { result = true; } else if (obj1 == null && obj2 != null || obj2 == null && obj1 != null) { result = false; } else if (obj1.equals(obj2)) { result = true; } // If both are strings, check for a regexp match else if (obj1 instanceof String && obj2 instanceof String) { result = stringsMatch((String)obj1, (String)obj2); } else if (obj1.getClass().isArray() && obj2.getClass().isArray()) { if (Array.getLength(obj1) == Array.getLength(obj2)) { result = true; for (int i=0;i < Array.getLength(obj1);i++) { if (!equals(Array.get(obj1, i), Array.get(obj2, i))) { result = false; break; } } } } return result; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/InputStreamHandler.java
package abbot.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import abbot.Log; import abbot.tester.Robot; /** Handle process output. */ public class InputStreamHandler extends Thread { private InputStream stream = null; public InputStreamHandler(InputStream stream) { super("Process Input Stream Handler"); setDaemon(true); this.stream = new BufferedInputStream(stream); } /** Override this method to do something meaningful with the output. */ public void handleBytes(byte[] buf, int count) { } // WARNING: closing a process output stream prematurely may result in // the Process object never detecting its termination! private void close() { try { stream.close(); } catch(IOException io) { Log.debug(io); } } public void run() { int BUFSIZE = 256; byte[] buf = new byte[BUFSIZE]; Log.debug("Stream reader started"); while(true) { try { Log.debug("Reading from stream"); int count = stream.read(buf, 0, buf.length); if (count == -1) { Log.debug("end of stream"); break; } else if (count == 0) { Log.debug("No input, sleeping"); Robot.delay(100); } else if (count > 0) { Log.debug("Got " + count + " bytes"); handleBytes(buf, count); } } catch(IOException io) { // we'll get this when the stream closes Log.debug(io); break; } } close(); Log.debug("stream handler terminating"); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Launcher.java
package abbot.util; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.io.IOException; import abbot.Platform; /** Mail and browser launcher which augments {@link Runtime Runtime.exec} * methods. Provides for built-in email and web browser support. */ public class Launcher { // TODO: provide an array of known mailto: handlers // for now we assume the browsers will make an attempt to handle mailto: private static final String[] HTTP = { "firefox", "galeon", "konqueror", "opera", "mozilla", "netscape", "mosaic", }; /** Perform trickery to get the right contents into the email handler from a mailto: line. */ private static String encodeForMail(String base) { StringBuffer buf = new StringBuffer(base); // Avoid URLEncoder.encode for spaces; it replaces them with plus // signs, which remain pluses when decoded. String SPACE = "--SPACE--"; for (int idx = buf.toString().indexOf(" "); idx != -1;idx = buf.toString().indexOf(" ")) { buf.replace(idx, idx+1, SPACE); } buf = new StringBuffer(URLEncoder.encode(buf.toString())); for (int idx = buf.toString().indexOf(SPACE); idx != -1;idx = buf.toString().indexOf(SPACE)) { if (Platform.isOSX()) { // The "open" command parses spaces buf.replace(idx, idx + SPACE.length(), "%20"); } else { buf.replace(idx, idx + SPACE.length(), " "); } } return buf.toString(); } /** Format a message to the given user with the given subject and message body. */ public static void mail(String user, String subject, String body) throws IOException { mail(user, subject, body, null); } /** Format a message to the given user with the given subject and message body, including a CC list. */ public static void mail(String user, String subject, String body, String cc) throws IOException { mail(user, subject, body, cc, null); } /** Format a message to the given user with the given subject and message body, including CC and BCC lists. */ public static void mail(String user, String subject, String body, String cc, String bcc) throws IOException { StringBuffer mailto = new StringBuffer("mailto:" + user + "?"); if (cc != null) mailto.append("CC=" + cc + "&"); if (bcc != null) mailto.append("BCC=" + bcc + "&"); mailto.append("Subject=" + encodeForMail(subject) + "&" + "Body=" + encodeForMail(body) + ""); open(mailto.toString()); } /** Open the given target URL in the platform's browser. */ public static void open(String target) throws IOException { open(null, target); } /** Use the given command/program to open the given target. */ public static void open(String command, String target) throws IOException { boolean tryBrowsers = false; ArrayList args = new ArrayList(); if (command != null) { args.add(command); } else { if (Platform.isOSX()) { args.add("open"); } else if (Platform.isWindows()) { if (Platform.isWindows9X()) { args.add("command.com"); args.add("/o"); } else { args.add("cmd.exe"); args.add("/c"); args.add("start"); args.add("\"Title\""); } // Always quote the argument, just in case // See MS docs for cmd.exe; &, |, and () must be escaped with // ^ or double-quoted. semicolon and comma are command // argument separators, and probably require quoting as well. target = "\"" + target + "\""; } else { args.add("placeholder"); tryBrowsers = true; } } args.add(target); String[] cmd = (String[])args.toArray(new String[args.size()]); if (!tryBrowsers) { ProcessOutputHandler.exec(cmd); } else { // TODO: choose the appropriate application based on the target // URL format, instead of relying on browsers to do it. for (int i=0;i < HTTP.length;i++) { try { cmd[0] = HTTP[i]; ProcessOutputHandler.exec(cmd); return; } catch(IOException e) { // not found, try another one } } throw new IOException("No target handler found (tried " + Arrays.asList(HTTP) + ")"); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/NamedThreadFactory.java
package abbot.util; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * A simple thread factory to make the management of executor groups easier */ public class NamedThreadFactory implements ThreadFactory { private final AtomicInteger count = new AtomicInteger(1); private final String prefix; private final ThreadGroup group; public NamedThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); prefix = name + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, prefix + count.getAndIncrement()); return t; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/NamedTimer.java
package abbot.util; import java.util.Timer; import java.lang.reflect.Field; import java.util.TimerTask; import java.util.Date; import abbot.Log; /** Prevents misbehaving TimerTasks from canceling the timer thread by throwing exceptions and/or errors. Also extends the basic Timer to use a name for its thread. Naming the timer thread facilitates discerning different threads in a full stack dump.<p> */ public class NamedTimer extends Timer { /** Creates a non-daemon named timer. */ public NamedTimer(final String name) { this(name, false); } /** Creates a named timer, optionally running as a daemon thread. */ public NamedTimer(final String name, boolean isDaemon) { super(isDaemon); schedule(new TimerTask() { public void run() { Thread.currentThread().setName(name); } }, 0); } /** Handle an exception thrown by a TimerTask. The default does nothing. */ protected void handleException(Throwable thrown) { Log.warn(thrown); } // TODO: prevent scheduled tasks from throwing uncaught exceptions and // thus canceling the Timer. // We can easily wrap scheduled tasks with a catcher, but we can't readily // cancel the wrapper when private class ProtectingTimerTask extends TimerTask { private TimerTask task; public ProtectingTimerTask(TimerTask orig) { this.task = orig; } public void run() { if (isCanceled()) { cancel(); } else { try { task.run(); } catch(Throwable thrown) { handleException(thrown); } } } private boolean isCanceled() { boolean canceled = false; final int CANCELED = 3; try { Field f = TimerTask.class.getDeclaredField("state"); f.setAccessible(true); int state = ((Integer)f.get(task)).intValue(); canceled = state == CANCELED; } catch(Exception e) { Log.warn(e); } return canceled; } } public void schedule(TimerTask task, Date time) { super.schedule(new ProtectingTimerTask(task), time); } public void schedule(TimerTask task, Date firstTime, long period) { super.schedule(new ProtectingTimerTask(task), firstTime, period); } public void schedule(TimerTask task, long delay) { super.schedule(new ProtectingTimerTask(task), delay); } public void schedule(TimerTask task, long delay, long period) { super.schedule(new ProtectingTimerTask(task), delay, period); } public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { super.scheduleAtFixedRate(new ProtectingTimerTask(task), firstTime, period); } public void scheduleAtFixedRate(TimerTask task, long delay, long period) { super.scheduleAtFixedRate(new ProtectingTimerTask(task), delay, period); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/NonDelegatingClassLoader.java
package abbot.util; import abbot.Log; /** Provides support for loading a class <i>before</i> checking the parent * class loader for it. If the shouldDelegate method returns false for a * given class name, it will defer to its parent class loader only if the * class is not found in this loader's path. This provides a means for * reloading classes that would otherwise be permanently cached by the app * or boot class loaders.<p> * The name for this class is not quite correct; it <i>will</i> delegate to * its parent if it doesn't find a given class. */ public class NonDelegatingClassLoader extends PathClassLoader { public NonDelegatingClassLoader(String path, ClassLoader parent) { super(path, parent); } /** Returns whether the given class should be given to the parent class * loader to try before this one does. The default implementation always * returns false. Making this method return true will revert to the * standard class loader behavior. */ protected boolean shouldDelegate(String name) { return false; } /** Find the given class in the search path. */ public Class findClass(String name) throws ClassNotFoundException { Log.debug("Looking up " + name + " with " + this); return super.findClass(name); } /** Load the given class, but attempt to load <i>before</i> the parent if shouldDelegate returns false for the given class. */ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (shouldDelegate(name)) { Log.debug("Delegating lookup for " + name); return super.loadClass(name, resolve); } Log.debug("Non-delegating lookup for " + name); Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch(SecurityException se) { Log.debug(se); // We're not allowed to find it, so give it to the parent return super.loadClass(name, resolve); } catch(ClassNotFoundException cnf) { // If we can't find it, maybe the parent can return super.loadClass(name, resolve); } if (resolve) { resolveClass(c); } } else { Log.debug("Class already loaded " + name); } return c; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/PathClassLoader.java
package abbot.util; import java.io.File; import java.net.*; import java.util.StringTokenizer; import java.util.ArrayList; import abbot.Platform; /** Provide a class loader that loads from a custom path. Similar to * sun.misc.Launcher$AppClassLoader (the usual application class loader), * except that it doesn't do the security checks that AppClassLoader does. * If path given is null, uses java.class.path. */ public class PathClassLoader extends java.net.URLClassLoader { private String classPath; private static final Factory factory = new Factory(); /** Create a class loader that loads classes from the given path. */ public PathClassLoader(String path) { this(path, null); } /** Create a class loader that loads classes from the given path. */ public PathClassLoader(String path, ClassLoader parent){ super(getURLs(path != null ? path : System.getProperty("java.class.path"), ":;"), parent, factory); this.classPath = path != null ? path : System.getProperty("java.class.path"); } public String getClassPath() { return classPath; } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { int i = name.lastIndexOf('.'); if(i != -1) { SecurityManager sm = System.getSecurityManager(); if(sm != null) sm.checkPackageAccess(name.substring(0, i)); } return super.loadClass(name, resolve); } /** Returns an array of URLs based on the given classpath string. */ static URL[] getURLs(String p, String separators) { String s = p != null ? p : System.getProperty("java.class.path"); File files[] = s != null ? convertPathToFiles(s, separators) : new File[0]; URL[] urls = new URL[files.length]; for (int i=0;i < urls.length;i++) { try { urls[i] = files[i].toURL(); } catch(MalformedURLException e) { throw new RuntimeException(e.getMessage()); } } return urls; } /** Returns an array of filenames (including path). */ public static String[] convertPathToFilenames(String path) { return convertPathToFilenames(path, ":;"); } /** Convert the given path string into an array of File. */ public static File[] convertPathToFiles(String path, String seps) { String[] names = convertPathToFilenames(path, ":;"); ArrayList files = new ArrayList(); for (int i=0;i < names.length;i++) { files.add(new File(names[i])); } return (File[])files.toArray(new File[files.size()]); } static String[] convertPathToFilenames(String path, String seps) { if (path == null) path = ""; boolean fixDrives = Platform.isWindows() && seps.indexOf(":") != -1; StringTokenizer st = new StringTokenizer(path, seps); ArrayList names = new ArrayList(); while (st.hasMoreTokens()) { String fp = st.nextToken(); // Fix up w32 absolute pathnames if (fixDrives && fp.length() == 1 && st.hasMoreTokens()) { char ch = fp.charAt(0); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { fp += ":" + st.nextToken(); } } names.add(fp); } return (String[])names.toArray(new String[names.size()]); } /** Taken from sun.misc.Launcher. */ private static class Factory implements URLStreamHandlerFactory { private static final String PREFIX = "sun.net.www.protocol"; private Factory() { } public URLStreamHandler createURLStreamHandler(String protocol) { String name = PREFIX + "." + protocol + ".Handler"; try { Class c = Class.forName(name); return (URLStreamHandler)c.newInstance(); } catch(ClassNotFoundException e) { e.printStackTrace(); } catch(InstantiationException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } throw new Error("could not load " + protocol + "system protocol handler"); } } public String toString() { return super.toString() + " (classpath=" + classPath + ")"; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/ProcessOutputHandler.java
package abbot.util; import abbot.InterruptedAbbotException; import abbot.Log; import java.io.File; import java.io.IOException; import java.util.Arrays; /** Provides handling of process output/error streams. */ public class ProcessOutputHandler { public static class ProcessAbnormalExitException extends IOException { private int code; private ProcessAbnormalExitException(String msg, int code) { super(msg); this.code = code; } public int getExitValue() { return code; } } private InputStreamHandler stderr; private InputStreamHandler stdout; private StringBuffer err = new StringBuffer(); public ProcessOutputHandler() { } public ProcessOutputHandler(Process p) { setProcess(p); } public String getError() { return err.toString(); } public synchronized void setProcess(Process p) { stdout = new InputStreamHandler(p.getInputStream()) { public void handleBytes(byte[] buf, int count) { handleOutput(buf, count); } }; stdout.start(); stderr = new InputStreamHandler(p.getErrorStream()) { public void handleBytes(byte[] buf, int count) { err.append(new String(buf, 0, count)); handleError(buf, count); } }; stderr.start(); } /** Override this method to handle stdout output. The default implementation does nothing. */ protected void handleOutput(byte[] buf, int count) { } /** Override this method to handle stderr output. The default implementation does nothing. */ protected void handleError(byte[] buf, int count) { } public synchronized void waitFor() throws InterruptedException { if (stderr != null) stderr.join(); if (stdout != null) stdout.join(); } /** Returns the output of the given command as a String. */ public static String exec(String[] command) throws IOException { return exec(command, null); } /** Returns the output of the given command as a String. */ public static String exec(String[] command, String[] environment) throws IOException { return exec(command, environment, null); } /** Returns the output of the given command as a String. */ public static String exec(String[] command, String[] environment, File dir) throws IOException { final StringBuffer output = new StringBuffer(); Log.debug("Running " + Arrays.asList(command)); Process p = Runtime.getRuntime().exec(command, environment, dir); ProcessOutputHandler handler = new ProcessOutputHandler(p) { public void handleOutput(byte[] buf, int count) { output.append(new String(buf, 0, count)); } }; try { p.waitFor(); } catch (InterruptedException e) { Log.debug(e); throw new InterruptedAbbotException("Interrupted when waiting for process"); } try { handler.waitFor(); } catch (InterruptedException e) { throw new InterruptedAbbotException("Interrupted when waiting for handler"); } int code = p.exitValue(); if (code != 0) { String msg = "Process " + Arrays.asList(command) + " exited with " + code; String err = handler.getError(); if (!"".equals(err)) msg += ":\n" + err; Log.debug(msg); throw new ProcessAbnormalExitException(msg, code); } Log.debug("output=" + output.toString()); return output.toString(); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Properties.java
package abbot.util; public class Properties { /** Load an integer system property, keeping it within the given valid range. */ public static int getProperty(String name, int defValue, int min, int max){ try { int value = Integer.getInteger(name, defValue).intValue(); return Math.max(min, Math.min(max, value)); } catch(NumberFormatException e) { return defValue; } } /** Load a long system property, keeping it within the given valid range. */ public static long getProperty(String name, long min, long max, long defValue){ try { long value = Long.getLong(name, defValue).longValue(); return Math.max(min, Math.min(max, value)); } catch(NumberFormatException e) { return defValue; } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Reflector.java
package abbot.util; import java.lang.reflect.*; import abbot.Log; /** Utility for performing some common reflection tasks. */ public class Reflector { private Reflector() { } /** Convert the value back into a field name. */ // NOTE: since this is an expensive lookup, maybe it should be deferred // until just before needed? public static String getFieldName(Class cls, int value, String prefix) { try { Field[] fields = cls.getFields(); for (int i=0;i < fields.length;i++) { // Perform fastest tests first... if ((fields[i].getModifiers() & Modifier.STATIC) != 0 && (fields[i].getType().equals(Integer.class) || fields[i].getType().equals(int.class)) && fields[i].getInt(null) == value && fields[i].getName().startsWith(prefix) // kind of a hack, but we don't want these two included... && !fields[i].getName().endsWith("_LAST") && !fields[i].getName().endsWith("_FIRST")) { return fields[i].getName(); } } } catch(Exception exc) { Log.log(exc); } throw new IllegalArgumentException("No available field has value " + value); } /** Look up the given static field value. */ public static int getFieldValue(Class cls, String fieldName) { try { Field field = cls.getField(fieldName); return field.getInt(null); } catch(Exception exc) { Log.log(exc); // Don't want to ignore these... throw new IllegalArgumentException("No field " + fieldName + " found in " + cls); } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Regexp.java
package abbot.util; import gnu.regexp.*; import abbot.Log; /** Simple wrapper around the more fully-featured RE class. */ public class Regexp { /** Return whether there is a match for the given regular expression * within the given string. */ public static boolean stringContainsMatch(String regexp, String actual) { try { boolean multiline = false; if (regexp.startsWith("(?m)")) { multiline = true; regexp = regexp.substring(4); } RE e = new RE(regexp, multiline ? RE.REG_MULTILINE|RE.REG_DOT_NEWLINE : 0); REMatch m = e.getMatch(actual); return m != null; } catch(REException exc) { Log.warn(exc); return false; } } /** Return whether the given regular expression matches the given string * exactly. */ public static boolean stringMatch(String regexp, String actual) { if (actual == null) actual = ""; try { boolean multiline = false; if (regexp.startsWith("(?m)")) { multiline = true; regexp = regexp.substring(4); } RE e = new RE(regexp, multiline ? RE.REG_MULTILINE|RE.REG_DOT_NEWLINE : 0); return e.isMatch(actual); } catch(REException exc) { Log.warn(exc); return false; } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/SingleThreadedEventListener.java
package abbot.util; import java.awt.AWTEvent; import java.awt.event.AWTEventListener; import java.util.ArrayList; import javax.swing.SwingUtilities; import abbot.Log; import abbot.tester.Robot; /** Provide an AWTEventListener which ensures all events are handled on the event dispatch thread. This allows the recorders and other listeners to safely manipulate GUI objects without concern for event dispatch thread-safety. <p> Window.show generates WINDOW_OPENED (and possibly hierarchy and other events) to any listeners from whatever thread the method was invoked on. <p> NOTE: Applet runners may run several simultaneous event dispatch threads when displaying multiple applets simultaneously. If this listener is installed in the parent context of those dispatch threads, it will be invoked on each of those threads, possibly simultaneously. */ public abstract class SingleThreadedEventListener implements AWTEventListener { private ArrayList deferredEvents = new ArrayList(); private Runnable action = new Runnable() { public void run() { processDeferredEvents(); } }; /** Event reception callback. */ public void eventDispatched(AWTEvent event) { if (!SwingUtilities.isEventDispatchThread()) { // Often the application under test will invoke Window.show, which // spawns hierarchy events. We want to ensure we respond to those // events on the dispatch thread to avoid deadlock. Log.debug("deferring event handling of " + Robot.toString(event)); synchronized(deferredEvents) { deferredEvents.add(event); } // Ensure that in the absence of any subsequent event thread // events deferred events still get processed. // If regular events are received before this action is run, the // deferred events will be processed prior to those events and the // action will do nothing. SwingUtilities.invokeLater(action); } else { // Ensure any deferred events are processed prior to subsequently // posted events. processDeferredEvents(); processEvent(event); } } /** Process any events that were generated off the event queue but not immediately handled. */ protected void processDeferredEvents() { // Make a copy of the deferred events and empty the queue ArrayList queue = new ArrayList(); synchronized(deferredEvents) { // In the rare case where there are multiple simultaneous dispatch // threads, it's possible for deferred events to get posted while // another event is being processed. At most this will mean a few // events get processed out of order, but they will likely be from // different event dispatch contexts, so it shouldn't matter. queue.addAll(deferredEvents); deferredEvents.clear(); } while (queue.size() > 0) { AWTEvent prev = null; Log.debug("processing deferred event"); // Process any events that were generated prev = (AWTEvent)queue.get(0); queue.remove(0); processEvent(prev); } } /** This method is not protected by any synchronization locks (nor should it be); in the presence of multiple simultaneous event dispatch threads, the listener must be threadsafe. */ protected abstract void processEvent(AWTEvent event); }