index
int64
repo_id
string
file_path
string
content
string
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/SystemState.java
package abbot.util; import java.awt.AWTException; import java.awt.Toolkit; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.PrintStream; import java.util.Properties; import javax.swing.UIManager; import abbot.Log; /** Preserve and restore system state. This includes the following: <ul> <li><code>System.out/err</code> streams <li><code>System</code> properties <li>Security manager </ul> */ public class SystemState { public static final int LOCKING_CODES[] = { KeyEvent.VK_CAPS_LOCK, KeyEvent.VK_NUM_LOCK, KeyEvent.VK_SCROLL_LOCK, KeyEvent.VK_KANA_LOCK }; private Properties oldProps; private PrintStream oldOut; private PrintStream oldErr; private SecurityManager oldsm; private String oldLookAndFeel; private boolean lockingKeys[]; private static Robot robot = null; static { try { robot = new Robot(); } catch(AWTException e) { } } /** Take a snapshot of the current System state for later restoration. */ public SystemState() { lockingKeys = new boolean[LOCKING_CODES.length]; Toolkit toolkit = Toolkit.getDefaultToolkit(); for (int i=0;i < LOCKING_CODES.length;i++) { try { lockingKeys[i] = toolkit.getLockingKeyState(LOCKING_CODES[i]); } catch(UnsupportedOperationException e) { // Nothing much we can do } } oldLookAndFeel = UIManager.getLookAndFeel().getClass().getName(); oldOut = System.out; oldErr = System.err; System.setOut(new ProtectedStream(oldOut)); System.setErr(new ProtectedStream(oldErr)); oldProps = (Properties)System.getProperties().clone(); oldsm = System.getSecurityManager(); } /** Restore the state captured in the ctor. */ public void restore() { // As per issue it is not always possible to reset the security manager // in this case when JDeveloper is running under the Netbeans window manager // so we can first of all check that the manager has not been changes // and then catch the exception an ignore it if this has been blocked SecurityManager currentsm = System.getSecurityManager(); if (oldsm != currentsm) { try { System.setSecurityManager(oldsm); } catch (SecurityException se) { Log.warn("Couldn't reset security manager " + se); } } System.setProperties(oldProps); System.setOut(oldOut); System.setErr(oldErr); try { UIManager.setLookAndFeel(oldLookAndFeel); } catch(Exception e) { Log.warn("Could not restore LAF: " + e); } Toolkit toolkit = Toolkit.getDefaultToolkit(); for (int i=0;i < LOCKING_CODES.length;i++) { try { boolean state = toolkit.getLockingKeyState(LOCKING_CODES[i]); if (state != lockingKeys[i]) { try { toolkit.setLockingKeyState(LOCKING_CODES[i], lockingKeys[i]); } catch(UnsupportedOperationException e) { if (robot != null) { try { robot.keyPress(LOCKING_CODES[i]); robot.keyRelease(LOCKING_CODES[i]); } catch(IllegalArgumentException ex) { // ignore } } } } } catch(UnsupportedOperationException e) { // Oh, well } } } /** Provide a wrapper that prevents the original stream from being closed. */ private class ProtectedStream extends PrintStream { private boolean closed = false; public ProtectedStream(PrintStream original) { super(original); } public void flush() { if (!closed) super.flush(); } public void close() { closed = true; } public void write(int b) { if (!closed) super.write(b); } public void write(byte[] buf, int off, int len) { if (!closed) super.write(buf, off, len); } } /** Clear all locking keys. */ public static void clearLockingKeys() { Toolkit toolkit = Toolkit.getDefaultToolkit(); for (int i=0;i < LOCKING_CODES.length;i++) { try { if (toolkit.getLockingKeyState(LOCKING_CODES[i])) { try { toolkit.setLockingKeyState(LOCKING_CODES[i], false); } catch(UnsupportedOperationException e) { if (robot != null) { try { robot.keyPress(LOCKING_CODES[i]); robot.keyRelease(LOCKING_CODES[i]); } catch(IllegalArgumentException ex) { // ignore } } } } } catch(UnsupportedOperationException e) { // can't read locking keys state, so do nothing } } } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/Tee.java
/* * Copyright (c) 2006 Timothy Wall, All Rights Reserved */ package abbot.util; import java.io.PrintStream; /** Splits a {@link PrintStream} into two targets. Useful for making * a copy of stream go somewhere else, such as redirecting stdout/stderr * to a file. */ public class Tee extends PrintStream { private PrintStream tee; private PrintStream tee2; private boolean splitting; public Tee(PrintStream p1, PrintStream p2) { super(p1); tee2 = p1; tee = p2; } public synchronized void write(int b) { if (splitting) { super.write(b); } else { splitting = true; super.write(b); tee.write(b); } } public synchronized void write(byte[] b, int o, int l) { if (splitting) { super.write(b, o, l); } else { splitting = true; super.write(b, o, l); tee.write(b, o, l); splitting = false; } } public synchronized void flush() { super.flush(); tee.flush(); } public synchronized void close() { super.close(); tee.close(); } public synchronized void print(boolean b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(char b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(int b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(long b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(float b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(double b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(char[] b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(String b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void print(Object b) { if (splitting) { super.print(b); } else { splitting = true; super.print(b); tee.print(b); splitting = false; } } public synchronized void println() { if (splitting) { super.println(); } else { splitting = true; super.println(); tee.println(); splitting = false; } } public synchronized void println(boolean x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(char x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(int x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(long x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(float x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(double x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(byte[] x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(String x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public synchronized void println(Object x) { if (splitting) { super.println(x); } else { splitting = true; super.println(x); tee.println(x); splitting = false; } } public String toString() { return "Tee " + tee2 + " and " + tee; } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/ThreadTerminatingSecurityManager.java
package abbot.util; import java.security.Permission; import java.util.*; import abbot.NoExitSecurityManager; /** Provides a method for terminating threads over which you otherwise have no * control. Usually works.<p> * NOTE: Still needs some work; if main script editor exits from the event * dispatch thread, an exception is thrown and the exit aborted. Perhaps * ignore event dispatch threads? */ public abstract class ThreadTerminatingSecurityManager extends NoExitSecurityManager { public class ThreadTerminatedException extends SecurityException { } private Map terminatedGroups = new WeakHashMap(); private boolean isTerminated(Thread t) { Iterator iter = terminatedGroups.keySet().iterator(); while (iter.hasNext()) { ThreadGroup group = (ThreadGroup)iter.next(); ThreadGroup thisGroup = t.getThreadGroup(); if (thisGroup != null && group.parentOf(thisGroup)) { return true; } } return false; } /** Ensure ThreadTermination exceptions are thrown for any thread in the * given group when any such thread causes the security manager to be * invoked. */ public void terminateThreads(ThreadGroup group) { if (group == null) throw new NullPointerException("Thread group must not be null"); terminatedGroups.put(group, Boolean.TRUE); // maybe do an interrupt/notify; but be careful b/c you might block // trying to sycnhronize on the thread if (group.activeCount() == 0) { try { group.destroy(); } catch(IllegalThreadStateException e) { } } } /** Throw ThreadTerminated for any thread marked for termination. */ public void checkPermission(Permission perm, Object context) { if (isTerminated(Thread.currentThread())) throw new ThreadTerminatedException(); super.checkPermission(perm, context); } /** Throw ThreadTerminated for any thread marked for termination. */ public void checkPermission(Permission perm) { if (isTerminated(Thread.currentThread())) throw new ThreadTerminatedException(); super.checkPermission(perm); } }
0
java-sources/abbot/abbot/1.4.0/abbot
java-sources/abbot/abbot/1.4.0/abbot/util/WeakAWTEventListener.java
package abbot.util; import java.awt.*; import java.awt.event.*; import java.lang.ref.*; /** Provides add-and-forget listening to the AWT event queue. * Provides an AWTEventListener which will automatically disconnect the * target listener when the target gets garbage-collected. Once the target * is GC'd, this listener will remove itself from the AWT event listener list. */ public class WeakAWTEventListener implements AWTEventListener { private WeakReference listener; public WeakAWTEventListener(AWTEventListener l, long mask) { listener = new WeakReference(l); Toolkit.getDefaultToolkit().addAWTEventListener(this, mask); } /** * @return For testing purposes return whether the listener has been disposed */ public boolean isDisposed() { return listener.get()==null; } public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(this); } public void eventDispatched(AWTEvent e) { AWTEventListener l = (AWTEventListener)listener.get(); if (l != null) { l.eventDispatched(e); } else { dispose(); } } }
0
java-sources/abbot/abbot/1.4.0/junit/extensions
java-sources/abbot/abbot/1.4.0/junit/extensions/abbot/ComponentTestFixture.java
package junit.extensions.abbot; import abbot.tester.Robot; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.reflect.*; import java.util.Iterator; import javax.swing.*; import javax.swing.border.EmptyBorder; import junit.framework.TestCase; import abbot.*; import abbot.finder.*; import abbot.finder.matchers.*; import abbot.tester.*; import abbot.tester.Robot; import abbot.util.*; import java.util.concurrent.Callable; import junit.framework.AssertionFailedError; import org.junit.Assert; /** Fixture for testing AWT and/or JFC/Swing components under JUnit. Ensures * proper setup and cleanup for a GUI environment. Provides methods for * automatically placing a GUI component within a frame and properly handling * Window showing/hiding (including modal dialogs). Catches exceptions thrown * on the event dispatch thread and rethrows them as test failures.<p> * Use {@link #showFrame(Component)} * when testing individual components, or * {@link #showWindow(Window)} * when testing a {@link Frame}, {@link Dialog}, or {@link Window}.<p> * Any member fields you define which are classes derived from any of the * classes in {@link #DISPOSE_CLASSES} will be automatically set to null after * the test is run.<p> * <bold>WARNING:</bold> Any tests which use significant or scarce resources * and reference them in member fields should explicitly null those fields in * the tearDown method if those classes are not included or derived from those * in {@link #DISPOSE_CLASSES}. Otherwise the resources will not be subject * to GC until the {@link TestCase} itself and any containing * {@link junit.framework.TestSuite} is * disposed (which, in the case of the standard JUnit test runners, is * <i>never</i>). */ public abstract class ComponentTestFixture extends TestCase { public class EventDispatchException extends InvocationTargetException { private EventDispatchException(Throwable t) { super(t, "An exception was thrown on the event dispatch thread: " + t.toString()); } public void printStackTrace() { getTargetException().printStackTrace(); } public void printStackTrace(PrintStream p) { getTargetException().printStackTrace(p); } public void printStackTrace(PrintWriter p) { getTargetException().printStackTrace(p); } } /** Simple matcher that may be used to verify that a specific component is found by a given ComponentFinder. */ protected class ComponentMatcher implements Matcher { private Component component; public ComponentMatcher(Component c) { component = c; } public boolean matches(Component c) { return c == component; } } /** Typical delay to wait for a robot event to be translated into a Java event. */ public static final int EVENT_GENERATION_DELAY = AWTFixtureHelper.EVENT_GENERATION_DELAY; public static final int WINDOW_DELAY = AWTFixtureHelper.WINDOW_DELAY; public static final int POPUP_DELAY = AWTFixtureHelper.POPUP_DELAY; /** Any member data derived from these classes will be automatically set to <code>null</code> after the test has run. This enables GC of said classes without GC of the test itself (the default JUnit runners never release their references to the tests) or requiring explicit <code>null</code>-setting in the {@link TestCase#tearDown()} method. */ protected static final Class[] DISPOSE_CLASSES = { Component.class, ComponentTester.class }; private AWTFixtureHelper fixtureHelper; private Throwable edtException; private long edtExceptionTime; private ComponentFinder finder; private Hierarchy hierarchy; /** Return an Abbot {@link abbot.tester.Robot} for basic event generation. */ protected Robot getRobot() { return fixtureHelper.getRobot(); } /** Return a WindowTracker instance. */ protected WindowTracker getWindowTracker() { return fixtureHelper.getWindowTracker(); } /** * Waits until a value equals to the value produced by the closure * @param message The message is display if we fail * @param expectedValue The expected value * @param eventualValue The closure that fetched the value we are testing against */ public static <T> void assertEqualsEventually(final String message, final T expectedValue, final Callable<T> eventualValue) { try { abbot.tester.Robot.wait( new abbot.tester.Robot.ConditionEDTDecorator(null, new Condition() { @Override public boolean test() { try { Assert.assertEquals( message, expectedValue, eventualValue.call()); return true; } catch (Throwable e) { return false; } } })); } catch (WaitTimedOutException wtoe) { try { Assert.assertEquals( message, expectedValue, eventualValue.call()); } catch (Exception e) { AssertionFailedError ae = new AssertionFailedError("Failure to process assertion"); ae.initCause(e); throw ae; } } } /** * Waits until a value produce by the closure is true * @param message The message is display if we fail * @param eventualValue The expected value, true of false */ public static void assertTrueEventually(final String message, final Callable<Boolean> eventualValue) { assertEqualsEventually(message, Boolean.TRUE, eventualValue); } /** Convenience method to sleep for a UI interval * (same as getRobot().sleep()). */ protected void sleep() { getRobot().sleep(); } /** 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. */ protected Frame showFrame(Component comp) { return fixtureHelper.showFrame(comp, null, getName()); } /** 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. */ protected Frame showFrame(Component comp, Dimension size) { return fixtureHelper.showFrame(comp, size, getName()); } /** Safely display a window with proper EDT synchronization. This method * blocks until the {@link Window} is showing and ready for input. */ protected 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. */ protected 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. */ protected void showWindow(final Window w, final Dimension size, final boolean pack) { fixtureHelper.showWindow(w, size, pack); } /** Return when the window is ready for input or times out waiting. * @param w */ protected void waitForWindow(Window w, boolean visible) { fixtureHelper.waitForWindow(w, visible); } /** 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. */ protected void hideWindow(final Window w) { fixtureHelper.hideWindow(w); } /** 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. */ protected void disposeWindow(Window w) { fixtureHelper.disposeWindow(w); } /** 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. */ protected void setModifiers(int modifiers, boolean pressed) { fixtureHelper.setModifiers(modifiers, pressed); } /** Convenience for <code>getRobot().invokeAndWait(Runnable)</code>. */ protected void invokeAndWait(Runnable runnable) { fixtureHelper.invokeAndWait(runnable); } /** Convenience for <code>getRobot().invokeLater(Runnable)</code>. */ protected void invokeLater(Runnable runnable) { fixtureHelper.invokeLater(runnable); } /** Install the given popup on the given component. Takes care of * installing the appropriate mouse handler to activate the popup. */ protected void installPopup(Component invoker, final JPopupMenu popup) { fixtureHelper.installPopup(invoker, popup); } /** 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. */ protected 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. */ protected void showPopup(final JPopupMenu popup, final Component invoker, final int x, final int y) { fixtureHelper.showPopup(popup, invoker, x, y); } /** Display a modal dialog and wait for it to show. Useful for things * like {@link JFileChooser#showOpenDialog(Component)} or * {@link JOptionPane#showInputDialog(Component,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) */ protected Dialog showModalDialog(final Runnable showAction) throws ComponentSearchException { return fixtureHelper.showModalDialog(showAction, getFinder()); } /** Similar to {@link #showModalDialog(Runnable)}, * but provides for the case where some of the {@link Dialog}'s contents * are known beforehand.<p> * @deprecated Use {@link #showModalDialog(Runnable)} instead. */ protected Dialog showModalDialog(Runnable showAction, Component contents) throws Exception { return showModalDialog(showAction); } /** 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. */ protected boolean isShowing(String id) { try { getFinder().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; } /** Construct a test case with the given name. */ public ComponentTestFixture(String name) { super(name); } /** Default Constructor. The name will be automatically set from the selected test method. */ public ComponentTestFixture() { } /** Ensure proper test harness setup and teardown that won't * be inadvertently overridden by a derived class. */ protected void fixtureSetUp() throws Throwable { hierarchy = createHierarchy(); finder = new BasicFinder(hierarchy); fixtureHelper = new AWTFixtureHelper(hierarchy) { // backward-compatibility protected void disposeAll() { ComponentTestFixture.this.disposeAll(); } }; } /** Handles restoration of system state. Automatically disposes of any Components used in the test. */ protected void fixtureTearDown() throws Throwable { edtExceptionTime = fixtureHelper.getEventDispatchErrorTime(); edtException = fixtureHelper.getEventDispatchError(); fixtureHelper.dispose(); fixtureHelper = null; clearTestFields(); // Explicitly set these null, since the test fixture instance may // be kept around by the test runner hierarchy = null; finder = null; } /** Dispose of all extant windows. * @deprecated This functionality is now deferred to AWTFixtureHelper */ protected void disposeAll() { Iterator iter = hierarchy.getRoots().iterator(); while (iter.hasNext()) { hierarchy.dispose((Window)iter.next()); } } /** Clears all non-static {@link TestCase} fields which are instances of * any class found in {@link #DISPOSE_CLASSES}. */ private void clearTestFields() { try { Field[] fields = getClass().getDeclaredFields(); for (int i=0;i < fields.length;i++) { if ((fields[i].getModifiers() & Modifier.STATIC) == 0) { fields[i].setAccessible(true); for (int c=0;c < DISPOSE_CLASSES.length;c++) { Class cls = DISPOSE_CLASSES[c]; if (cls.isAssignableFrom(fields[i].getType())) { fields[i].set(this, null); } } } } } catch(Exception e) { Log.warn(e); } } /** Override the default <code>junit.framework.TestCase#RunBare()</code> * to ensure proper test harness setup and teardown that won't * likely be accidentally overridden by a derived class. * <p> * If any exceptions are thrown on the event dispatch thread, they count * as errors. They will not, however supersede any failures/errors * thrown by the test itself unless thrown prior to the main test * failure. */ public void runBare() throws Throwable { if (Boolean.getBoolean("abbot.skip_ui_tests")) { return; } Throwable exception = null; long exceptionTime = -1; try { try { fixtureSetUp(); super.runBare(); } catch(Throwable e) { exception = e; } finally { Log.log("tearing down fixture: " + getName()); try { fixtureTearDown(); } catch(Throwable tearingDown) { if (exception == null) exception = tearingDown; } } if (exception != null) throw exception; } catch(Throwable e) { exceptionTime = System.currentTimeMillis(); exception = e; } finally { // Cf. StepRunner.runStep() // Any EDT exception which occurred *prior* to when the // exception on the main thread was thrown should be used // instead. if (edtException != null && (exception == null || edtExceptionTime < exceptionTime)) { exception = new EventDispatchException(edtException); } } if (exception != null) { throw exception; } } /** Provide for derived classes to provide their own Hierarchy. */ protected Hierarchy createHierarchy() { return new TestHierarchy(); } /** Obtain a component finder to look up components. */ protected ComponentFinder getFinder() { return finder; } /** Obtain a consistent hierarchy. */ protected Hierarchy getHierarchy() { return hierarchy; } }
0
java-sources/abbot/abbot/1.4.0/junit/extensions
java-sources/abbot/abbot/1.4.0/junit/extensions/abbot/RepeatHelper.java
package junit.extensions.abbot; import java.util.ArrayList; import junit.extensions.RepeatedTest; import junit.framework.*; import abbot.Log; /** Convenience functions to wrap a given test case such that individual methods may be run with heavy repetition, and default suites run with light repetition. */ public class RepeatHelper extends TestHelper { private static int repeatCount = 1; // no instantiations protected RepeatHelper() { } protected static String[] parseArgs(String[] args) { ArrayList list = new ArrayList(); for (int i=0;i < args.length;i++) { try { repeatCount = Integer.parseInt(args[i]); } catch(NumberFormatException e) { list.add(args[i]); } } return (String[])list.toArray(new String[list.size()]); } public static void runTests(String[] args, Class testClass) { args = Log.init(args); args = parseArgs(args); args = TestHelper.parseArgs(args); try { System.err.printf("\nRunning %s, %d times\n", testClass.getName(), repeatCount); Test test = collectTests(args, testClass); if (repeatCount > 1) test = new RepeatedTest(test, repeatCount); runTest(test); } catch(Exception e) { System.err.println(e.getMessage()); System.exit(-2); } } }
0
java-sources/abbot/abbot/1.4.0/junit/extensions
java-sources/abbot/abbot/1.4.0/junit/extensions/abbot/SizeOf.java
package junit.extensions.abbot; import abbot.InterruptedAbbotException; import java.util.ArrayList; public class SizeOf { /** For use with constructors which require arguments. */ public static interface ObjectCreator { Object create(); } private static class ClassCreator implements ObjectCreator { private Class cls; public ClassCreator(Class cls) { this.cls = cls; } public Object create() { try { return cls.newInstance(); } catch(IllegalAccessException e) { String msg = "No-argument constructor is " + "private for " + cls; throw new IllegalArgumentException(msg); } catch(InstantiationException e) { String msg = "Can't create an instance of " + cls; throw new IllegalArgumentException(msg); } catch(Exception e) { e.printStackTrace(); String msg = "Can't obtain size of " + cls; throw new IllegalArgumentException(msg); } } } private static final int GCCOUNT = 2; private static void gc() { try { System.gc(); Thread.sleep(100); System.runFinalization(); Thread.sleep(100); } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted when waiting for gc"); } } private static void gc(int n) { for (int i=0;i < n;i++) { gc(); } } public static long getMemoryUse() { gc(GCCOUNT); long total = Runtime.getRuntime().totalMemory(); long free = Runtime.getRuntime().freeMemory(); return total - free; } /** Return the approximate size in bytes of the object returned by the given ObjectCreator. */ public static long sizeof(ObjectCreator oc) { final int SIZE = 1000; ArrayList list = new ArrayList(SIZE); long before = getMemoryUse(); for (int i=0;i < SIZE;i++) { list.add(oc.create()); } long after = getMemoryUse(); return (after - before) / SIZE; } /** Return the approximate size in bytes of an instance of the given class. The class <em>must</em> provide a no-args constructor. */ public static long sizeof(Class cls) { return sizeof(new ClassCreator(cls)); } /** Display the approximate size (in bytes) of the class given in the first argument. */ public static void main(String[] args) { try { if (args.length != 1) { System.err.println("Use with a single class name argument"); System.exit(1); } Class cls = Class.forName(args[0]); System.out.println("Class " + cls.getName() + " size is " + sizeof(cls) + " bytes"); } catch(Throwable e) { e.printStackTrace(); System.exit(1); } } }
0
java-sources/abbot/abbot/1.4.0/junit/extensions
java-sources/abbot/abbot/1.4.0/junit/extensions/abbot/TestHelper.java
package junit.extensions.abbot; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Locale; import junit.framework.*; import junit.textui.*; import abbot.Log; /** Provides automatic test suite generation given command-line arguments. * Also allows for a single test to be run if it is specified. Supports "-v" * (verbose) to display each test's name prior to running the test (aids in * identifying which test failed when the VM crashes). * The locale may be set explicitly by the following system properties: * <ul> * <li>abbot.locale.language * <li>abbot.locale.country * <li>abbot.locale.variant * </ul> */ public class TestHelper { protected TestHelper() { } /** Returns the classpath directory in which the given class is found. */ public static File getClasspathDirectory(Class test) { URL url = test.getResource("/" + test.getName().replace('.','/') + ".class"); try { // 1.4+ only return new File(URLDecoder.decode(url.getFile(), "UTF-8")).getParentFile(); } catch(UnsupportedEncodingException e) { // ain't gonna happen throw new Error(e.toString()); } } public static TestSuite generateSuite(Class[] classes) { TestSuite suite = new TestSuite(); for (int i=0;i < classes.length;i++) { try { java.lang.reflect.Method suiteMethod = classes[i].getMethod("suite", null); suite.addTest((Test)suiteMethod.invoke(null, null)); } catch(Exception exc) { suite.addTest(new TestSuite(classes[i])); } } return suite; } private static boolean printTestNames = false; protected static String[] parseArgs(String[] args) { String language = System.getProperty("abbot.locale.language"); if (language != null) { String country = System.getProperty("abbot.locale.country", ""); String variant = System.getProperty("abbot.locale.language", ""); Locale locale = new Locale(language, country, variant); Locale.setDefault(locale); System.out.println("Using locale " + locale.getDisplayName()); } ArrayList newArgs = new ArrayList(); for (int i=0;i < args.length;i++) { if (args[i].equals("-v")) printTestNames = true; else { newArgs.add(args[i]); } } return (String[])newArgs.toArray(new String[newArgs.size()]); } protected static Test collectTests(String[] args, Class testClass) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { Test test; if (args.length == 1 && args[0].startsWith("test")) { try { test = (Test)testClass.newInstance(); ((TestCase)test).setName(args[0]); } catch(InstantiationException e) { test = (Test)testClass.getConstructor(new Class[]{ String.class }).newInstance(new Object[] { args[0] }); } } else { try { test = (Test)testClass.getMethod("suite", null). invoke(null, null); } catch(Exception exc) { test = new TestSuite(testClass); } } return test; } protected static void runTest(Test test) { try { TestRunner runner = new TestRunner(new ResultPrinter(System.out) { public void startTest(Test test) { if (printTestNames) getWriter().print(test.toString()); super.startTest(test); } public void endTest(Test test) { super.endTest(test); if (printTestNames) getWriter().println(); } }); try { TestResult r = runner.doRun(test, false); if (!r.wasSuccessful()) System.exit(-1); System.exit(0); } catch(Throwable thr) { System.err.println(thr.getMessage()); System.exit(-2); } } catch(Exception exc) { System.err.println(exc.getMessage()); System.exit(-2); } } public static void runTests(String[] args, Class testClass) { args = Log.init(args); args = parseArgs(args); try { runTest(collectTests(args, testClass)); } catch(Exception e) { System.err.println(e.getMessage()); System.exit(-2); } } }
0
java-sources/abbot/abbot/1.4.0/junit/extensions
java-sources/abbot/abbot/1.4.0/junit/extensions/abbot/Timer.java
package junit.extensions.abbot; /** Time and performance measurement utilities. @author twall */ public class Timer { /** Time base for elapsed time calculations. */ private long start; /** Basic constructor which sets the timer base to the current time. */ public Timer() { reset(); } /** Return the number of milliseconds elapsed since the last timer reset. */ public long elapsed() { return System.currentTimeMillis() - start; } /** Return the length of time elapsed to run the given runnable. */ public long elapsed(Runnable action) { long start = System.currentTimeMillis(); action.run(); return System.currentTimeMillis() - start; } /** Set the start time to the current time. */ public void reset() { start = System.currentTimeMillis(); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ActionMapModel.java
package abbot.editor; import javax.swing.ActionMap; import javax.swing.table.AbstractTableModel; import abbot.i18n.Strings; public class ActionMapModel extends AbstractTableModel { public static ActionMapModel EMPTY = new ActionMapModel() { public int getRowCount() { return 1; } public Object getValueAt(int row, int col) { return col == 0 ? Strings.get("actionmap.unavailable") : ""; } }; private static final String[] COLUMN_NAMES = { Strings.get("actionmap.key"), Strings.get("actionmap.value"), }; private ActionMap map; public ActionMapModel() { this(new ActionMap()); } public ActionMapModel(ActionMap map) { this.map = map; } public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { Object[] keys = map.allKeys(); return keys == null ? 0 : keys.length; } public int getColumnCount() { return 2; } public Object getValueAt(int row, int col) { Object key = map.allKeys()[row]; return col == 0 ? key : map.get(key); } public boolean isCellEditable(int row, int col) { return false; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/CompactHierarchy.java
package abbot.editor; import abbot.Log; import java.awt.*; import javax.swing.*; import java.util.*; import abbot.util.AWT; import abbot.finder.Hierarchy; import java.lang.reflect.Field; import java.util.concurrent.Callable; /** Provides a condensed, more easily readable version of the original hierarchy. */ // TODO: figure out how to more cleanly put popups under their invokers (maybe // have to scan the whole hierarchy each time). public class CompactHierarchy implements Hierarchy { private boolean compact = true; private Hierarchy hierarchy; public CompactHierarchy(Hierarchy original) { this.hierarchy = original; } public void setCompact(boolean compact) { this.compact = compact; } public boolean isCompact() { return compact; } public Collection getRoots() { return hierarchy.getRoots(); } public Container getParent(Component c) { // In the component hierarchy, show popup menus directly beneath their // invoker if (compact && c instanceof JPopupMenu) { Component invoker = ((JPopupMenu)c).getInvoker(); if (invoker instanceof Container) return (Container)invoker; } if (compact && c instanceof JToolTip) { return ((JToolTip)c).getComponent(); } Container parent = hierarchy.getParent(c); if (compact) { while (parent != null && isElided(parent)) { parent = getParent(parent); } } return parent; } public boolean contains(Component c) { return hierarchy.contains(c); } public void dispose(Window w) { hierarchy.dispose(w); } /** Returns whether the given component is completely ignored (including its children) in the hierarchy. */ private boolean isIgnored(Component c) { if (AWT.isTransientPopup(c)) return true; return c instanceof JScrollBar && c.getParent() instanceof JScrollPane; } /** Returns whether the given component is omitted from the component * hierarchy when compact is turned on (its children may be shown). * For example, a JScrollPane's viewport is elided so that the scrolled * content shows up directly beneath the scroll pane. */ private boolean isElided(Component c) { // JPanel or JWindow transient popups if (AWT.isTransientPopup(c)) { return true; } if (c instanceof Container) { // Only windows that are heavyweight popups are elided if (c instanceof Window) return false; if (c instanceof JPopupMenu && ((JPopupMenu)c).getInvoker() instanceof JMenu) return true; // Content pane on heavyweight popup if (AWT.isContentPane(c) && AWT.isTransientPopup(SwingUtilities.getWindowAncestor(c))) return true; } Container parent = c.getParent(); if (parent instanceof JScrollPane) { // Ignore scrollbars and viewport, but not headers return c instanceof JScrollBar || c instanceof JViewport; } return parent instanceof RootPaneContainer || parent instanceof JRootPane; } /** Provide a list of a Component's children, sans any transient popups * Keep track of any popups encountered. */ // heavyweights are subwindows of Window? // lightweights are subpanels of Window? public Collection getComponents(final Component c) { if (c == null || !(c instanceof Container)) return new ArrayList(); ArrayList list = new ArrayList(); if (compact) { // Display menu contents directly beneath menus if (c instanceof JMenu) { // Make sure this work is done on the event queue as per 3495968 JPopupMenu popupMenu = abbot.tester.Robot.callAndWait(c, new Callable<JPopupMenu>() { @Override public JPopupMenu call() { // Sometime, in particular using Netbeans the popupMenu // call might have side effects, so just access the field // directly to understand the current state of the object // if it hasn't already been created. JPopupMenu menu = null; try { Field $popupMenu = JMenu.class.getDeclaredField("popupMenu"); $popupMenu.setAccessible(true); menu = (JPopupMenu)$popupMenu.get(c); } catch (Exception ex) { Log.warn(ex); } if (menu==null) { menu = ((JMenu)c).getPopupMenu(); } return menu; } }); return getComponents(popupMenu); } } Iterator iter = hierarchy.getComponents(c).iterator(); while (iter.hasNext()) { Component k = (Component)iter.next(); if (compact && isElided(k)) { // Only add children if the component itself is not totally // ignored. if (!isIgnored(k)) { list.addAll(getComponents(k)); } } else { list.add(k); } } list.addAll(findInvokerPopups(c)); return list; } /** Scan for popups which have been invoked by the given invoker. */ private Collection findInvokerPopups(Component invoker) { ArrayList popups = new ArrayList(); Window root = AWT.getWindow(invoker); // heavyweight popups are sub-windows of the invoker's window Collection parents = new ArrayList(Arrays.asList(root.getOwnedWindows())); // lightweight popups show up on the window's layered pane if (root instanceof JWindow || root instanceof JFrame || root instanceof JDialog) { JRootPane rp = ((RootPaneContainer)root).getRootPane(); // work around VM bug on RootPaneContainer.getLayeredPane() // which sometimes results in a NPE if (rp != null) { JLayeredPane lp = rp.getLayeredPane(); if (lp != null) { parents.addAll(Arrays.asList(lp.getComponents())); } } } Iterator iter = parents.iterator(); while (iter.hasNext()) { Component c = (Component)iter.next(); JComponent popup = findInvokedPopup(invoker, c); if (popup != null) { popups.add(popup); } } return popups; } /** Returns the invoked popup found under the given parent (if any). */ private JComponent findInvokedPopup(Component invoker, Component parent) { if (AWT.isTransientPopup(parent)) { JComponent popup = findPopup((Container)parent); if (popup != null && (!(popup instanceof JPopupMenu) || !(getParent(popup) instanceof JMenu))) { if (getParent(popup) == invoker) { return popup; } } } return null; } /** Return the popup descendent of the given known transient popup * container. */ private JComponent findPopup(Container c) { JComponent popup = null; Component[] kids = c.getComponents(); for (int i=0;i < kids.length && popup == null;i++) { if (kids[i] instanceof JPopupMenu || kids[i] instanceof JToolTip) { popup = (JComponent)kids[i]; } else if (kids[i] instanceof Container) { popup = findPopup((Container)kids[i]); } } return popup; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentBrowser.java
package abbot.editor; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Method; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.tree.*; import javax.swing.table.*; import abbot.*; import abbot.editor.editors.XMLEditor; import abbot.editor.widgets.*; import abbot.finder.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Resolver; import abbot.tester.Robot; /** Browse an existing component hierarchy. Thanks to the JFCUnit guys for * the basis for this code. */ // FIXME put the component reference ID into a label, not in the status public class ComponentBrowser extends JPanel implements ActionListener { private int TAB_HIERARCHY = 0; private int TAB_REFERENCE = 1; private JButton refreshButton; private JCheckBox filterButton; private JButton addAssertButton; private JButton addSampleButton; private JCheckBox filterPropertiesCheckBox; private Resolver resolver; private ComponentTree componentTree; private JTable propTable; private ReferencesModel refModel; private JTable refTable; private ComponentPropertyModel propertyModel; private JTable attributeTable; private ReferenceAttributeModel attributeModel; private JTable inputMapTable; private JTable actionMapTable; private boolean filter = true; private JTabbedPane tabs; private JTabbedPane tabs2; /** Currently selected component. */ private Component selectedComponent = null; /** Is the currently selected component "fake"? */ private boolean fakeComponent = false; /** Currently selected reference. */ private ComponentReference selectedReference = null; private LocalHierarchy hierarchy; /** * Default constructor */ public ComponentBrowser(Resolver r, Hierarchy h) { this.resolver = r; this.hierarchy = new LocalHierarchy(h); setName("browser"); equip(this); setSelectedComponent(null); setSelectedReference(null); } /** * Method to create required widgets/components and populate * the content pane with them. * * @param pane The content pane to which the created objects have to * be added into. */ private void equip(Container pane) { setLayout(new BorderLayout()); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createLeftPanel(), createRightPanel()); // prefer tree over property table split.setResizeWeight(1.0); split.setDividerSize(4); split.setBorder(null); pane.add(split, BorderLayout.CENTER); } private JPanel createHierarchyView() { JPanel pane = new JPanel(new BorderLayout()); componentTree = new ComponentTree(hierarchy); componentTree.setName("browser.hierarchy"); componentTree.addTreeSelectionListener(new TreeSelectionListener(){ public void valueChanged(TreeSelectionEvent e) { if (!ignoreHierarchyChange) { setSelectedComponent(getSelectedComponentFromTree()); } } }); JScrollPane scroll = new JScrollPane(componentTree); scroll.getViewport().setBackground(componentTree.getBackground()); pane.add(scroll, BorderLayout.CENTER); refreshButton = new JButton(Strings.get("browser.hierarchy.reload")); refreshButton.addActionListener(this); filterButton = new JCheckBox(Strings.get("browser.hierarchy.concise")); filterButton.addActionListener(this); filterButton.setSelected(filter); filterButton.setToolTipText(Strings.get("browser.hierarchy.filter.tip")); JPanel buttons = new JPanel(); buttons.setBorder(new EmptyBorder(0, 0, 0, 0)); buttons.add(refreshButton); buttons.add(filterButton); JPanel leftJustify = new JPanel(new BorderLayout()); leftJustify.setBorder(new EmptyBorder(0, 0, 0, 0)); leftJustify.add(buttons, BorderLayout.WEST); pane.add(leftJustify, BorderLayout.SOUTH); return pane; } /** Set the resolver on which the references list is based. */ public void setResolver(Resolver resolver) { this.resolver = resolver; refModel = new ReferencesModel(resolver); refTable.setModel(refModel); } private Component createReferenceView() { // FIXME need buttons for new/delete (delete only enabled if the // reference is entirely unused refModel = new ReferencesModel(resolver); refTable = new JTable(refModel) { public void setRowSelectionInterval(int start, int end) { super.setRowSelectionInterval(start, end); // Make sure the selection is always visible. Rectangle cellRect = getCellRect(start, 0, true); if (cellRect != null) super.scrollRectToVisible(cellRect); } }; refTable.setName("browser.references"); refTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); refTable.setDefaultEditor(ComponentReference.class, new XMLEditor()); refTable.clearSelection(); ListSelectionListener lsl = new ListSelectionListener() { public void valueChanged(ListSelectionEvent lse) { if (!lse.getValueIsAdjusting()) { referenceListSelectionChanged(lse); } } }; refTable.getSelectionModel().addListSelectionListener(lsl); JScrollPane scroll = new JScrollPane(refTable); scroll.getViewport().setBackground(refTable.getBackground()); return scroll; } /** * Create a tabbed pane for browsing either existing components or * component references. * * @return A JPanel for the left side of the main frame */ private Component createLeftPanel() { tabs = new JTabbedPane() { public Dimension getPreferredSize() { return new Dimension(250, 200); } }; tabs.add(Strings.get("Hierarchy"), createHierarchyView()); tabs.setToolTipTextAt(0, Strings.get("browser.hierarchy.tip")); tabs.add(Strings.get("References"), createReferenceView()); tabs.setToolTipTextAt(1, Strings.get("browser.references.tip")); tabs.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { tabChanged(e); } }); return tabs; } /** * Create the property browser/selection table. * * @return A JPanel for the right side of the main frame */ private Component createRightPanel() { JPanel pane = new JPanel(new BorderLayout()); propertyModel = new ComponentPropertyModel(); propTable = new JTable(propertyModel); propTable.setName("browser.properties"); propTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); propTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); propTable.setDefaultRenderer(Object.class, new PropertyRenderer()); ListSelectionListener lsl = new ListSelectionListener() { public void valueChanged(ListSelectionEvent lse) { if (!lse.getValueIsAdjusting()) { enableAssertSampleButtons(); } } }; propTable.getSelectionModel().addListSelectionListener(lsl); addAssertButton = new JButton(""); addAssertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { firePropertyCheck(false); } }); addAssertButton.setEnabled(false); updateAssertText(false, false); addSampleButton = new JButton(Strings.get("SampleProperty")); addSampleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { firePropertyCheck(true); } }); addSampleButton.setEnabled(false); String waitKeyName = KeyEvent.getKeyText(ScriptEditor.KC_WAIT); String invertKeyName = KeyEvent.getKeyText(ScriptEditor.KC_INVERT); String tip = Strings.get("AssertPropertyTip", new Object[] { invertKeyName, waitKeyName, }); addAssertButton.setToolTipText(TextFormat.tooltip(tip)); tip = Strings.get("SamplePropertyTip"); addSampleButton.setToolTipText(TextFormat.tooltip(tip)); filterPropertiesCheckBox = new JCheckBox(Strings.get("Filter")); filterPropertiesCheckBox.addActionListener(this); filterPropertiesCheckBox.setEnabled(true); filterPropertiesCheckBox.setSelected(true); filterPropertiesCheckBox.setToolTipText(Strings.get("browser.properties.filter.tip")); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(addAssertButton); buttonsPanel.add(addSampleButton); buttonsPanel.add(filterPropertiesCheckBox); JPanel leftJustify = new JPanel(new BorderLayout()); leftJustify.setBorder(new EmptyBorder(0, 0, 0, 0)); leftJustify.add(buttonsPanel, BorderLayout.WEST); JScrollPane scroll = new JScrollPane(propTable); scroll.getViewport().setBackground(propTable.getBackground()); scroll.setColumnHeaderView(propTable.getTableHeader()); pane.add(scroll, BorderLayout.CENTER); pane.add(leftJustify, BorderLayout.SOUTH); attributeModel = new ReferenceAttributeModel(); attributeModel.addTableModelListener(new AttributeListener()); attributeTable = new JTable(attributeModel); JScrollPane scroll1 = new JScrollPane(attributeTable); scroll1.getViewport().setBackground(attributeTable.getBackground()); inputMapTable = new JTable(InputMapModel.EMPTY); JScrollPane scroll2 = new JScrollPane(inputMapTable); scroll2.getViewport().setBackground(inputMapTable.getBackground()); actionMapTable = new JTable(ActionMapModel.EMPTY); JScrollPane scroll3 = new JScrollPane(actionMapTable); scroll3.getViewport().setBackground(actionMapTable.getBackground()); tabs2 = new JTabbedPane() { public Dimension getPreferredSize() { return new Dimension(300, 150); } }; tabs2.add(Strings.get("browser.properties"), pane); tabs2.setToolTipTextAt(0, Strings.get("browser.properties.tip")); tabs2.add(Strings.get("browser.attributes"), scroll1); tabs2.setToolTipTextAt(1, Strings.get("browser.attributes.tip")); tabs2.add(Strings.get("browser.inputmap"), scroll2); tabs2.setToolTipTextAt(2, Strings.get("browser.inputmap.tip")); tabs2.add(Strings.get("browser.actionmap"), scroll3); tabs2.setToolTipTextAt(3, Strings.get("browser.actionmap.tip")); return tabs2; } public void updateAssertText(boolean isWait, boolean invert) { addAssertButton.setText(Strings.get(isWait ? "WaitProperty" : "AssertProperty", new Object[]{ invert ? Strings.get("assert.not_equals") : Strings.get("assert.equals") })); } /** Select the given reference in the current view. */ public void setSelectedReference(ComponentReference ref) { setSelectedReferenceImpl(ref, true); } /** Select the given reference in the current view. */ public void setSelectedReferenceImpl(ComponentReference ref, boolean selectTab) { if (ref != selectedReference) { selectedReference = ref; updateReferenceSelection(ref); Component c = ref != null ? getComponentForReference(ref) : null; if (c != selectedComponent) { selectedComponent = c; updateComponentSelection(c); } fireSelectionChanged(); } // Display the page if required if (selectTab && ref != null && showingHierarchy()) { tabs.setSelectedIndex(TAB_REFERENCE); } } /** Select the given component (and make it visible) in the current view. Update the auxiliary view components appropriately. If showing component references and the given component doesn't have one, switch the view to the hierarchy. */ public void setSelectedComponent(Component comp) { selectedComponent = comp; ComponentReference ref = null; if (comp != null && resolver.getHierarchy().contains(comp)) { ref = resolver.getComponentReference(comp); } if (ref != selectedReference) { selectedReference = ref; updateReferenceSelection(ref); } if (!showingHierarchy()) { tabs.setSelectedIndex(TAB_HIERARCHY); } updateComponentSelection(comp); fireSelectionChanged(); } /** Return the row index of the given component reference. */ private int getRow(ComponentReference ref) { if (ref != null) { for (int i=0;i < refTable.getRowCount();i++) { ComponentReference value = (ComponentReference) refTable.getValueAt(i, 0); if (ref == value) { return i; } } } return -1; } /** Flag to avoid responding to list/tree selection changes when they're * made programmatically instead of by the user. */ private boolean ignoreHierarchyChange = false; private boolean ignoreReferenceChange = false; /** Set the appropriate selection in the reference list. */ private void updateReferenceSelection(ComponentReference ref) { if (!showingHierarchy()) { int row = getRow(ref); ignoreReferenceChange = true; if (row == -1) { refTable.clearSelection(); } else { refTable.setRowSelectionInterval(row, row); } ignoreReferenceChange = false; } updateAttributesList(); updatePropertyList(); } /** Set the appropriate selection in the component hierarchy tree. */ private void updateComponentSelection(Component comp) { if (showingHierarchy()) { ignoreHierarchyChange = true; if (comp == null) { componentTree.clearSelection(); } else { TreePath path = componentTree.getPath(comp); ComponentNode node = (ComponentNode)path.getLastPathComponent(); if (node.getUserObject() != comp) { setCompactDisplay(false); path = componentTree.getPath(comp); } componentTree.setSelectionPath(path); } ignoreHierarchyChange = false; } updateAttributesList(); updatePropertyList(); } /** * Utility method showing whether a component node has been selected or * not. */ public boolean isComponentSelected() { if (showingHierarchy()) { return (ComponentNode) componentTree.getLastSelectedPathComponent() != null; } return refTable.getSelectedRow() != -1; } /** When re-enabled, perform a reload of the tree. */ public void setEnabled(boolean state) { super.setEnabled(state); if (state) refresh(); } public void refresh() { SwingUtilities.invokeLater(new Runnable() { public void run() { componentTree.reload(null); } }); } /** Convert the component reference into an actual component, creating a * dummy one if the real one is not available. */ private Component getComponentForReference(ComponentReference ref) { Component comp = null; fakeComponent = false; try { comp = ref.getComponent(); } catch(ComponentSearchException e) { if (e instanceof MultipleComponentsFoundException) { // FIXME query the user to select the right one? // the right one may not exist at this point in time. MultipleComponentsFoundException mc = (MultipleComponentsFoundException)e; Component[] list = mc.getComponents(); String warning = "Multiple components found for " + ref.toXMLString() + ": "; for (int i=0;i < list.length;i++) { warning += "\n" + Robot.toHierarchyPath(mc.getComponents()[i]); } Log.warn(warning); } try { fakeComponent = true; comp = (Component) (Class.forName(ref.getRefClassName())).newInstance(); comp.setName(Strings.get("browser.hierarchy.proxy", new Object[] { ref.getID() })); if (comp instanceof Window) { // make sure it never appears in the hierarchy hierarchy.filter(comp); componentTree.reload(); } } catch(Exception exc) { // Not much we can do here; we require a no-args constructor // FIXME show a warning dialog } } return comp; } public boolean showingHierarchy() { return tabs.getSelectedIndex() == TAB_HIERARCHY; } /** Returns the currently selected reference. */ public ComponentReference getSelectedReference() { return selectedReference; } /** Returns which component is currently selected. */ public Component getSelectedComponent() { return selectedComponent; } /** Sets whether uninteresting components are elided from the display. */ public void setCompactDisplay(boolean compact) { filter = compact; filterButton.setSelected(filter); hierarchy.setCompact(filter); componentTree.setHierarchy(hierarchy); } /** Returns whether the current display mode is compact. */ public boolean isCompactDisplay() { return filter; } /** * Generic action handler for buttons. */ public void actionPerformed(ActionEvent e) { if(e.getSource() == refreshButton) { refresh(); } else if(e.getSource() == filterButton) { setCompactDisplay(!filter); } else if(e.getSource() == filterPropertiesCheckBox) { updatePropertyList(); } } private void updateAttributesList() { attributeModel.setReference(selectedReference); } private void updatePropertyList() { int row = propTable.getSelectedRow(); String savedProperty = row == -1 ? "" : (String)propTable. getValueAt(row, ComponentPropertyModel.PROPERTY_NAME); addAssertButton.setEnabled(false); addSampleButton.setEnabled(false); Component comp = showingHierarchy() || selectedReference != null ? selectedComponent : null; propertyModel.setComponent(comp, filterPropertiesCheckBox.isSelected()); for (row=0;row < propTable.getRowCount();row++) { String prop = (String)propTable. getValueAt(row, ComponentPropertyModel.PROPERTY_NAME); if (prop.equals(savedProperty)) { propTable.setRowSelectionInterval(row, row); Rectangle rect = propTable.getCellRect(row, 0, true); propTable.scrollRectToVisible(rect); enableAssertSampleButtons(); break; } } if (comp instanceof JComponent) { InputMap im = ((JComponent)comp).getInputMap(); ActionMap am = ((JComponent)comp).getActionMap(); inputMapTable.setModel(new InputMapModel(im)); actionMapTable.setModel(new ActionMapModel(am)); } else { inputMapTable.setModel(InputMapModel.EMPTY); actionMapTable.setModel(ActionMapModel.EMPTY); } inputMapTable.repaint(); actionMapTable.repaint(); } /** Returns the Component represented by the current tree selection. */ private Component getSelectedComponentFromTree() { ComponentNode node = (ComponentNode) componentTree.getLastSelectedPathComponent(); Component comp = node != null ? node.getComponent() : null; return comp; } private ComponentReference getReferenceAt(int row) { return (ComponentReference)refTable.getValueAt(row, 0); } /** Returns the component reference represented by the current selection * in the reference list. */ private ComponentReference getSelectedReferenceFromList() { int refrow = refTable.getSelectedRow(); return refrow == -1 ? null : getReferenceAt(refrow); } public void enableAssertSampleButtons() { int row = propTable.getSelectedRow(); addAssertButton.setEnabled(row != -1 && isComponentSelected()); addSampleButton.setEnabled(row != -1 && isComponentSelected()); } /** Called when a the reference list selection changes, and when the property list changes. */ public void referenceListSelectionChanged(ListSelectionEvent e) { if (!ignoreReferenceChange) { setSelectedReferenceImpl(getSelectedReferenceFromList(), false); } } /** Invoked when the hierarchy/reference tab changes. */ public void tabChanged(ChangeEvent e) { if (showingHierarchy()) { // If we were viewing a fake component in the reference view, // switch to no component selection in the hierarchy view if (fakeComponent) { fakeComponent = false; setSelectedComponent(null); } else { updateComponentSelection(selectedComponent); } } else { // Bug on OSX always leaves a selection in the reference list // Avoid it by explicitly setting the selection if we can if (selectedReference == null && refTable.getRowCount() > 0) { setSelectedReference(getReferenceAt(0)); } else { updateReferenceSelection(selectedReference); } } } private ArrayList listeners = new ArrayList(); public void addSelectionListener(ComponentBrowserListener cbl) { ArrayList list = new ArrayList(listeners); list.add(cbl); listeners = list; } public void removeSelectionListener(ComponentBrowserListener cbl) { ArrayList list = new ArrayList(listeners); list.remove(cbl); listeners = list; } protected void fireSelectionChanged() { Iterator iter = listeners.iterator(); while (iter.hasNext()) { ((ComponentBrowserListener)iter.next()). selectionChanged(this, selectedComponent, selectedReference); } } protected void firePropertyCheck(boolean sample) { int row = propTable.getSelectedRow(); if (row == -1 || selectedComponent == null) return; Method m = (Method) propertyModel.getValueAt(row, ComponentPropertyModel.METHOD_OBJECT); Object value = propertyModel.getValueAt(row, ComponentPropertyModel.PROPERTY_VALUE); Iterator iter = listeners.iterator(); while (iter.hasNext()) { ((ComponentBrowserListener)iter.next()). propertyAction(this, m, value, sample); } } /** Provides filtering of another hierarchy to remove locally-spawned * throwaway components. */ private class LocalHierarchy extends CompactHierarchy { private Map filtered = new WeakHashMap(); private Hierarchy raw = new AWTHierarchy(); public LocalHierarchy(Hierarchy h) { super(h); } public Collection getRoots() { Collection roots = isCompact() ? super.getRoots() : raw.getRoots(); roots.removeAll(filtered.keySet()); return roots; } public Collection getComponents(Component c) { Collection kids = isCompact() ? super.getComponents(c) : raw.getComponents(c); kids.removeAll(filtered.keySet()); return kids; } public boolean contains(Component c) { return (isCompact() ? super.contains(c) : raw.contains(c)) && !filtered.containsKey(c); } public void filter(Component c) { filtered.put(c, Boolean.TRUE); } } private class AttributeListener implements TableModelListener { private boolean messaging = false; public void tableChanged(TableModelEvent e) { // Preserve the reference table selection // NOTE: only really need to message on ID changes, since that's // the only thing displayed in the reference table. // NOTE: does anything other than the Script use the cref id? // first arg of most actions, what else? if (!messaging) { messaging = true; ComponentReference ref = selectedReference; refModel.fireTableDataChanged(); setSelectedReferenceImpl(ref, false); messaging = false; } } } /** To be invoked when an underlying component reference has changed. */ public void referencesChanged() { if (SwingUtilities.isEventDispatchThread()) refModel.fireTableDataChanged(); else { SwingUtilities.invokeLater(new Runnable() { public void run() { referencesChanged(); } }); } } private class PropertyRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JComponent c = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); value = propertyModel.getValueAt(row, ComponentPropertyModel.ACCESSIBLE); if( isSelected ) { c.setBackground( table.getSelectionBackground() ); c.setForeground( table.getSelectionForeground() ); } else { c.setBackground( table.getBackground() ); c.setForeground( table.getForeground() ); } if( (column == 1) && Boolean.TRUE.equals( value ) ) { setToolTipText( Strings.get( "Inaccessible" ) ); c.setBackground( Color.gray ); } /* if (column == 1 && Boolean.TRUE.equals(value)) { setToolTipText(Strings.get("Inaccessible")); c.setBackground(Color.gray); } else { c.setBackground(UIManager.getColor("Table.background")); } */ return c; } protected void setValue(Object value) { String str = ArgumentParser.toString(value); setToolTipText(str); super.setValue(str == ArgumentParser.DEFAULT_TOSTRING ? value.toString() : str); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentBrowserListener.java
package abbot.editor; import java.awt.Component; import abbot.script.ComponentReference; public interface ComponentBrowserListener { public void selectionChanged(ComponentBrowser src, Component comp, ComponentReference ref); public void propertyAction(ComponentBrowser src, java.lang.reflect.Method m, Object value, boolean sample); }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentNode.java
package abbot.editor; import java.awt.*; import java.util.*; import javax.swing.tree.*; import abbot.finder.*; import abbot.i18n.Strings; import abbot.tester.Robot; /** Provides a JTree-compatible node model for displaying a given hierarchy. */ public class ComponentNode extends DefaultMutableTreeNode { private Hierarchy hierarchy; private Map map; private boolean loaded; /** Constructor for the root node of a hierarchy. */ public ComponentNode(Hierarchy hierarchy) { super(null, true); this.hierarchy = hierarchy; map = new WeakHashMap(); } protected ComponentNode(ComponentNode parent, Object obj) { super(obj, (obj == null || obj instanceof Container || obj instanceof MenuContainer)); hierarchy = parent.hierarchy; map = parent.map; map.put(obj, this); } public ComponentNode(ComponentNode parent, Component comp) { this(parent, (Object)comp); } public ComponentNode(ComponentNode parent, MenuComponent comp) { this(parent, (Object)comp); } public ComponentNode(ComponentNode parent, MenuItem comp) { this(parent, (Object)comp); } public TreeNode getChildAt(int index) { load(); return super.getChildAt(index); } public int getChildCount() { load(); return super.getChildCount(); } public void reload() { reload(hierarchy); } public void reload(Hierarchy hierarchy) { this.hierarchy = hierarchy; map.clear(); loaded = false; } private void load() { if (loaded) return; loaded = true; removeAllChildren(); Object obj = getUserObject(); if(isRoot()) { Iterator iter = hierarchy.getRoots().iterator(); while (iter.hasNext()) { add(new ComponentNode(this, (Component)iter.next())); } } else if(obj instanceof Container) { // Specially handle AWT MenuBar if (obj instanceof Frame) { Frame f = (Frame)obj; if (f.getMenuBar() != null) { add(new ComponentNode(this, f.getMenuBar())); } } Collection children = hierarchy.getComponents(getComponent()); Iterator iter = children.iterator(); while (iter.hasNext()) { add(new ComponentNode(this, (Component)iter.next())); } } // Specially handle AWT menus else if(obj instanceof MenuBar) { MenuBar mb = (MenuBar)obj; for (int i=0;i < mb.getMenuCount();i++) { add(new ComponentNode(this, mb.getMenu(i))); } } else if(obj instanceof Menu) { Menu menu = (Menu)obj; for (int i=0;i < menu.getItemCount();i++) { add(new ComponentNode(this, menu.getItem(i))); } } } /** Return the component that appears as a parent in the ComponentNode * hierarchy. */ Component getParent(Component c) { return hierarchy.getParent(c); } /** Returns the Component represented, or null if this is either the root * or a java.awt.MenuComponent. */ public Component getComponent() { if (getUserObject() instanceof Component) return (Component)getUserObject(); return null; } public int hashCode() { return(isRoot() ? super.hashCode() : getUserObject().hashCode()); } /** Return true if the represented components are the same. */ public boolean equals(Object other) { return this == other || ((other instanceof ComponentNode) && (getUserObject() == ((ComponentNode)other).getUserObject())); } public String toString() { if(isRoot()) { return getChildCount() == 0 ? Strings.get("NoComponents") : Strings.get("AllFrames"); } return Robot.toString(getUserObject()); } /** Return the nearest node corresponding to the given component. Behavior is undefined if the node is not reachable from the root node. If the component is elided in the underlying hierarchy, returns the nearest parent node that is not elided. */ public ComponentNode getNode(Component comp) { if (comp == null) { return (ComponentNode)getRoot(); } ComponentNode node = (ComponentNode)map.get(comp); if (node == null) { Component parentComp = getParent(comp); ComponentNode parent = getNode(parentComp); if (parent == null) { return getNode(parentComp); } // Fall back to parent if no child matches. node = parent; for (int i=0;i < parent.getChildCount();i++) { ComponentNode child = (ComponentNode)parent.getChildAt(i); if (child.getComponent() == comp) { node = child; break; } } } return node; } /** Return the TreePath for the given Component, assuming it is in the same hierarchy as this node. Returns as much of the ancestor path as is available in the hierarchy. */ public TreePath getPath(Component comp) { ComponentNode node = getNode(comp); return new TreePath(node.getPath()); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentPropertyModel.java
package abbot.editor; import java.awt.*; import java.lang.reflect.*; import java.util.*; import javax.swing.table.DefaultTableModel; import abbot.Log; import abbot.i18n.Strings; import abbot.script.PropertyCall; import abbot.tester.ComponentTester; class ComponentPropertyModel extends DefaultTableModel { public static final int PROPERTY_NAME = 0; public static final int PROPERTY_VALUE = 1; public static final int ACCESSIBLE = 2; public static final int METHOD_OBJECT = 3; private static Set filteredMethods = new HashSet(); static { // Indicate things that aren't particularly interesting filteredMethods.addAll(Arrays.asList(new String[] { // Component "getAccessibleContext", "getAlignmentX", "getAlignmentY", "getColorModel", "getComponentListeners", "getComponentOrientation", "getDropTarget", "getFocusListeners", "getGraphics", "getGraphicsConfiguration", "getHierarchyBoundsListeners", "getHierarchyListeners", "getInputContext", "getInputMethodListeners", "getInputMethodRequests", "getKeyListeners", "getMouseListeners", "getMouseMotionListeners", "getMouseWheelListeners", "getParent", "getPeer", "getToolkit", "getTreeLock", // Container "getComponents", "getContainerListeners", // JComponent "getActionMap", "getAncestorListeners", "getAutoscrolls", "getBufferStrategy", "getDebugGraphicsOptions", "getInputMap", "getInputVerifier", "getPropertyChangeListeners", "getRegisteredKeyStrokes", "getRootPane", "getTopLevelAncestor", "getUIClassID", "getVerifyInputWhenFocusTarget", "getVetoableChangeListeners", "getVisibleRect", "isFocusCycleRoot", "isOpaque", "isOptimizedDrawingEnabled", "isPaintingTile", "isPreferredSizeSet", "isRequestFocusEnabled", "isValidateRoot", // Window "getOwnedWindows", "getWindowFocusListeners", "getWindowListeners", "getWindowStateListeners", // Frame "getFrames", })); } private Map noAccess = new WeakHashMap(); /** Install the given filtered property method properties. Add-on ComponentTester classes should invoke this for the list of property methods they want to appear in the filtered property list. */ public static void setFilteredPropertyMethods(String[] methods) { filteredMethods.addAll(Arrays.asList(methods)); } /** Create a model with two columns, the property name and the property * value. */ public ComponentPropertyModel() { super(new Object[]{ Strings.get("Name"), Strings.get("Value") }, 0); } public void clear() { // The setNumRows() method is required to be compatible with JDK // 1.2.2 and should be replaced with setRowCount() for 1.3 and above. //propTableModel.setNumRows(0); setRowCount(0); } public void setComponent(Component comp) { setComponent(comp, true); } /** The current list of property methods and values corresponds to this * component. */ private Component currentComponent = null; /** Whether the current list is filtered. */ private boolean filtered = false; /** Update the list of property methods based on the newly selected component. */ public void setComponent(Component comp, boolean filter) { Class cls = comp != null ? comp.getClass() : null; if (currentComponent == comp && filter == filtered) return; clear(); currentComponent = comp; filtered = filter; Method[] all = getPropertyMethods(cls, filter); Arrays.sort(all, new Comparator() { public int compare(Object o1, Object o2) { String n1 = getPropertyName(((Method)o1).getName()); String n2 = getPropertyName(((Method)o2).getName()); return n1.compareTo(n2); } }); Object[] noArgs = new Object[0]; Object[] oneArg = new Object[] { comp }; for (int i=0;i < all.length;i++) { Method method = all[i]; Object value = ""; try { Object target = comp; Object[] args = noArgs; if (ComponentTester.class. isAssignableFrom(method.getDeclaringClass())) { target = ComponentTester.getTester(comp); args = oneArg; } if ((method.getModifiers() & Modifier.PUBLIC) == 0 || (method.getDeclaringClass().getModifiers() & Modifier.PUBLIC) == 0) { noAccess.put(method, Boolean.TRUE); method.setAccessible(true); } value = method.invoke(target, args); } catch(IllegalArgumentException e) { value = "<illegal argument>"; Log.debug(e); } catch(InvocationTargetException e) { value = "<target exception>"; Log.debug(e); } catch(IllegalAccessException e) { // method was somehow protected? value = "<not accessible>"; Log.debug(e); } addRow(new Object[] { method, value }); } fireTableDataChanged(); } Method[] getPropertyMethods(Class cls, boolean filter) { if (cls == null) return new Method[0]; // Make sure we only get one of each named method HashMap processed = new HashMap(); Method[] methods = cls.getMethods(); for(int i = 0; i < methods.length; i++) { if (isGetterMethod(methods[i], false) && !processed.containsKey(methods[i].getName())) { if (filter && filteredMethods.contains(methods[i].getName())) { continue; } processed.put(methods[i].getName(), methods[i]); } } // Now look up propert accessors provided by the corresponding // ComponentTester class. ComponentTester tester = ComponentTester.getTester(cls); methods = tester.getPropertyMethods(); for (int i=0;i < methods.length;i++) { if (!processed.containsKey(methods[i].getName())) { // Properties provided by the ComponentTester are never // filtered. processed.put(methods[i].getName(), methods[i]); } } return (Method[])processed.values().toArray(new Method[processed.size()]); } /** * Method to check if the method specified on the class * is a "getter" for an attribute of that class * * @param method The method to be tested * @return true if the method is a "getter" */ private boolean isGetterMethod(Method method, boolean isTester) { Class[] types = method.getParameterTypes(); int argc = types.length; return ((isTester && argc == 1 && Component.class.isAssignableFrom(types[0])) || (!isTester && argc == 0)) && PropertyCall.isPropertyMethod(method); } /** * Method to "extract" the property name from the method name * following the convention specified for a bean * * @param methodName The name of the method * @return The name of the attribute */ private String getPropertyName(String methodName) { String propName = methodName; if (methodName.startsWith("get") || methodName.startsWith("has")) { propName = methodName.substring(3); } else if(methodName.startsWith("is")) { propName = methodName.substring(2); } return propName.substring(0, 1).toLowerCase() + propName.substring(1); } public boolean isCellEditable(int row, int col) { return false; } /** Display the property name column apropriately. */ public Object getValueAt(int row, int col) { // The Method object is in column zero, we want only the property part // to appear. if (col == PROPERTY_NAME) { Method m = (Method)super.getValueAt(row, col); return getPropertyName(m.getName()); } if (col == METHOD_OBJECT) { return (Method)super.getValueAt(row, 0); } if (col == ACCESSIBLE) { Method m = ((Method)getValueAt(row, METHOD_OBJECT)); return noAccess.get(m) != null ? Boolean.TRUE : Boolean.FALSE; } return super.getValueAt(row, col); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentTree.java
package abbot.editor; import abbot.finder.Hierarchy; import abbot.util.AWT; import abbot.util.WeakAWTEventListener; import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.AWTEventListener; import java.awt.event.ComponentEvent; import java.awt.event.ContainerEvent; import java.awt.event.WindowEvent; import java.net.URL; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.concurrent.*; import javax.swing.CellRendererPane; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreePath; /** Provides a Tree view into a given Hierarchy of components. Refreshes its display based on changes to the default AWT hierarchy. The selection path is preserved to the extent possible across changes in the hierarchy. */ public class ComponentTree extends JTree { private Hierarchy hierarchy; private ComponentNode root; private HierarchyMonitor monitor; private DefaultTreeModel model; private transient boolean ignoreSelectionChanges; /** Hash of class name to icon. */ private ComponentTreeIcons icons = new ComponentTreeIcons(); /** Supports optionally suppressing selection notifications while the hierarchy is reloading. */ private class SelectionModel extends DefaultTreeSelectionModel { private transient boolean settingSelection; protected void fireValueChanged(TreeSelectionEvent e) { if (settingSelection || ignoreSelectionChanges) return; super.fireValueChanged(e); } } private class HierarchyMonitor implements AWTEventListener { public void eventDispatched(AWTEvent ev) { Component compToReload = null; switch (ev.getID()) { case WindowEvent.WINDOW_OPENED: case WindowEvent.WINDOW_CLOSED: case ComponentEvent.COMPONENT_SHOWN: { Component c = ((ComponentEvent)ev).getComponent(); if (hierarchy.contains(c)) { compToReload = hierarchy.getParent(c); } break; } case ContainerEvent.COMPONENT_ADDED: case ContainerEvent.COMPONENT_REMOVED: { ContainerEvent e = (ContainerEvent)ev; Component c = e.getComponent(); Window w = AWT.getWindow(c); // CellRendererPanes send out these events in swarms, // every time they repaint a cell, so ignore them if (!(c instanceof CellRendererPane) && hierarchy.contains(c) && w != null && hierarchy.contains(w)) { // TODO: delay reload on tooltip hide to allow access to // the tooltip; otherwise the tooltip will go away and be // removed from the tree as soon as the cursor moves to // the tree to manipulate it. compToReload = c; } break; } default: break; } if (compToReload != null) { toProcess.add(compToReload); EventQueue.invokeLater(new Runnable() { @Override public void run() { reloadToProcess(); } }); } } } private class Renderer extends DefaultTreeCellRenderer { public Renderer() { URL url = getClass().getResource("icons/component.gif"); if (url != null) { setLeafIcon(new ImageIcon(url)); } url = getClass().getResource("icons/container.gif"); if (url != null) { setOpenIcon(new ImageIcon(url)); setClosedIcon(new ImageIcon(url)); } } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean exp, boolean leaf, int row, boolean focus) { Component c = super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, focus); if (c instanceof JLabel) { JLabel label = (JLabel)c; Icon icon = null; if (value == root) { URL url = getClass().getResource("icons/hierarchy-root.gif"); if (url != null) icon = new ImageIcon(url); } else { Component c1 = ((ComponentNode)value).getComponent(); if (c1 != null) { icon = icons.getIcon(c1.getClass()); } } if (icon != null) { label.setIcon(icon); } } return c; } } public ComponentTree(Hierarchy h) { super(new ComponentNode(h)); setSelectionModel(new SelectionModel()); setCellRenderer(new Renderer()); setShowsRootHandles(true); setScrollsOnExpand(true); hierarchy = h; model = (DefaultTreeModel)getModel(); root = (ComponentNode)model.getRoot(); monitor = new HierarchyMonitor(); long mask = ContainerEvent.CONTAINER_EVENT_MASK | ComponentEvent.COMPONENT_EVENT_MASK | WindowEvent.WINDOW_EVENT_MASK; new WeakAWTEventListener(monitor, mask); } public void setHierarchy(Hierarchy h) { hierarchy = h; root.reload(h); reload(); } /** Set the current selection path, ensuring that it is visible. */ public void setSelectionPath(TreePath path) { super.setSelectionPath(path); makeVisible(path); Rectangle rect = getPathBounds(path); if (rect != null) scrollRectToVisible(rect); } /** Returns the path to the given component. If the component does not * exist in the current hierarchy, returns as much of its parent path as * does exist. */ public TreePath getPath(Component comp) { return root.getPath(comp); } /** Reloads the entire hierarchy. */ public void reload() { reload(null); } /** * A list of components that are yet to be processed */ private Queue<Component> toProcess = new LinkedBlockingQueue<Component>(); /** * Reloads the elements in the toProcess list */ private void reloadToProcess() { Component next; while ((next = toProcess.poll())!=null) { reload(next); } } /** * Using an identity hash map rather than a normal one to * prevent any equals methods being called. */ private Map<Component, Component> currentlyProccessing = new IdentityHashMap<Component, Component>(); /** Reloads the hierarchy starting at the given component. */ public void reload(Component comp) { // Prevent possible stack overflows because of components being added // as we walk the tree if (currentlyProccessing.containsKey(comp)) { return; } else { try { // Store this element in the set so that we don't get // stuck in a look if getting child elements has side effects currentlyProccessing.put(comp, comp); // Process nodes ComponentNode node = comp != null ? root.getNode(comp) : root; TreePath path = getSelectionPath(); Component selected = path == null ? null : ((ComponentNode)path.getLastPathComponent()).getComponent(); if (node == null) node = root; // suppress selection change notifications until we're certain we // can't restore the original selection. ignoreSelectionChanges = true; node.reload(); model.reload(node); if (selected != null) { TreePath newPath = root.getPath(selected); // if the selection is exactly the same as it was before the // reload, suppress selection change notifications ignoreSelectionChanges = path.equals(newPath); setSelectionPath(newPath); } ignoreSelectionChanges = false; } finally { currentlyProccessing.remove(comp); } } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ComponentTreeIcons.java
package abbot.editor; import java.awt.Component; import javax.swing.*; import java.util.*; import java.net.URL; /** Provides JTree icons for different Components. */ class ComponentTreeIcons { private Map icons = new HashMap(); public Icon getIcon(Class cls) { String className = cls.getName(); int lastdot = className.lastIndexOf("."); String simpleName = lastdot != -1 ? className.substring(lastdot+1).toLowerCase() : className; Icon icon = (Icon)icons.get(className); if (icon == null) { URL url = getClass().getResource("icons/" + className + ".gif"); if (url == null) { url = getClass().getResource("icons/" + simpleName + ".gif"); } if (url == null) { if (Component.class.equals(cls)) return null; icon = getIcon(cls.getSuperclass()); } else { icon = new ImageIcon(url); } if (icon != null) { icons.put(className, icon); } } return icon; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/Costello.java
package abbot.editor; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import abbot.Platform; import abbot.i18n.Strings; /** Simple splash screen for the script editor. */ public class Costello { private static final String BUNDLE = "abbot.editor.i18n.costello"; static { // Don't need robot verification System.setProperty("abbot.robot.verify", "false"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Costello"); if (Platform.JAVA_VERSION < Platform.JAVA_1_4) { // Mac OSX setup stuff System.setProperty("com.apple.mrj.application.growbox.intrudes", "true"); System.setProperty("com.apple.macos.use-file-dialog-packages", "true"); System.setProperty("com.apple.macos.useScreenMenuBar", "true"); } else { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); } Strings.addBundle(BUNDLE); } private static class SplashScreen extends JWindow { boolean disposeOK = false; /** @deprecated */ public void hide() { if (disposeOK) { super.hide(); } } public void dispose() { if (disposeOK) { super.dispose(); } } } private static SplashScreen splash = null; public static Window getSplashScreen() { return splash; } /** Note that this "main" is typical of many Swing apps, in that it does window showing and disposal directly from the main thread. Running the editor under itself should provide a reasonable test for handling that scenario. */ public static void main(String[] args) { EditorContext ec = new EditorContext(args); showCostello(ec); } /** Invoke the costello editor with an editor configuration to give more fine grained control */ public static void showCostello(EditorContext ec) { // In non embedded case set look and feel if (!ec.isEmbedded()) { try { String lafClass = System.getProperty("abbot.editor.look_and_feel", "system"); if ("system".equals(lafClass)) lafClass = UIManager.getSystemLookAndFeelClassName(); if (lafClass != null && !"".equals(lafClass) && !"default".equals(lafClass)) UIManager.setLookAndFeel(lafClass); } catch(Exception e) { } } splash = new SplashScreen(); JLabel label = new LogoLabel(); // Add a beveled border on non-Mac platforms if (!Platform.isOSX()) { Border b = new CompoundBorder(new SoftBevelBorder(BevelBorder.RAISED), label.getBorder()); label.setBorder(b); } splash.getContentPane().add(label); splash.pack(); Rectangle screen = splash.getGraphicsConfiguration().getBounds(); Dimension size = splash.getSize(); Point loc = new Point(screen.x + (screen.width - size.width) / 2, screen.y + (screen.height - size.height) / 2); splash.setLocation(loc); splash.setVisible(true); try { ScriptEditor.showEditor(ec); } finally { splash.disposeOK = true; // NOTE: disposal in main still screws us up, because the dispose // does an invokeAndWait... java.awt.EventQueue.invokeLater(new Runnable() { public void run() { splash.dispose(); splash = null; } }); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/CustomCheckBoxMenuItem.java
package abbot.editor; import java.beans.*; import javax.swing.*; import abbot.Log; import abbot.editor.actions.*; import abbot.editor.widgets.Mnemonic; /** A custom JCheckBoxMenuItem that listens to the selected * state of its toggle action, reflecting its state when the action changes. */ public class CustomCheckBoxMenuItem extends JCheckBoxMenuItem { private PropertyChangeListener pcl; public CustomCheckBoxMenuItem(EditorToggleAction a) { super(a); setName((String)a.getValue(EditorAction.NAME)); Integer i = (Integer)a.getValue(EditorAction.MNEMONIC_INDEX); if (i != null) Mnemonic.setDisplayedMnemonicIndex(this, i.intValue()); // prior to 1.4, the accelerator key is not automatically set setAccelerator((KeyStroke)a.getValue(Action.ACCELERATOR_KEY)); } protected void configurePropertiesFromAction(javax.swing.Action a) { super.configurePropertiesFromAction(a); boolean s = a!= null && ((EditorToggleAction)a).isSelected(); super.setSelected(s); } protected PropertyChangeListener createActionPropertyChangeListener(Action a) { pcl = super.createActionPropertyChangeListener(a); return new CustomCheckBoxPropertyListener(); } private class CustomCheckBoxPropertyListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { Log.debug("Got action prop change: " + e.getPropertyName() + ":" + e.getNewValue()); pcl.propertyChange(e); if (e.getPropertyName().equals(EditorToggleAction.STATE)) { Boolean val = (Boolean)e.getNewValue(); CustomCheckBoxMenuItem.this. setSelected(val == Boolean.TRUE); } else if (e.getPropertyName().equals(EditorAction.MNEMONIC_INDEX)) { Integer i = (Integer)e.getNewValue(); int index = i != null ? i.intValue() : -1; Mnemonic.setDisplayedMnemonicIndex(CustomCheckBoxMenuItem.this, index); } } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/EditorConstants.java
package abbot.editor; /** Provide Editor action key names and menu keys. Action names are looked up via {@link abbot.i18n.Strings#get(String)} by prepending the string <code>"actions."</code>. NOTE: to add a new editor action, define a key for it here and an action for it in ScriptEditor. Add to the action map in ScriptEditor.initActions, then (optionally) add it to the menu layout in ScriptEditor.initMenus. */ public interface EditorConstants { String MENU_FILE = "menus.file"; String MENU_EDIT = "menus.edit"; String MENU_TEST = "menus.test"; String MENU_INSERT = "menus.insert"; String MENU_CAPTURE = "menus.capture"; String MENU_HELP = "menus.help"; String ACTION_PREFIX = "actions."; String ACTION_EDITOR_ABOUT = "editor-about"; String ACTION_EDITOR_EMAIL = "editor-email"; String ACTION_EDITOR_BUGREPORT = "editor-submit-bug"; String ACTION_EDITOR_WEBSITE = "editor-website"; String ACTION_EDITOR_USERGUIDE = "editor-userguide"; String ACTION_EDITOR_QUIT = "editor-quit"; String ACTION_SCRIPT_OPEN = "script-open"; String ACTION_SCRIPT_NEW = "script-new"; String ACTION_SCRIPT_DUPLICATE = "script-duplicate"; String ACTION_SCRIPT_SAVE = "script-save"; String ACTION_SCRIPT_SAVE_AS = "script-save-as"; String ACTION_SCRIPT_RENAME = "script-rename"; String ACTION_SCRIPT_CLOSE = "script-close"; String ACTION_SCRIPT_DELETE = "script-delete"; String ACTION_SCRIPT_CLEAR = "script-clear"; String ACTION_STEP_DELETE = "step-delete"; String ACTION_STEP_CUT = "step-cut"; String ACTION_STEP_COPY = "step-copy"; String ACTION_STEP_PASTE = "step-paste"; String ACTION_STEP_MOVE_UP = "step-move-up"; String ACTION_STEP_MOVE_DOWN = "step-move-down"; String ACTION_STEP_GROUP = "step-group"; String ACTION_SELECT_TESTSUITE = "select-testsuite"; String ACTION_EXPORT_HIERARCHY = "export-hierarchy"; String ACTION_RUN = "run"; String ACTION_RUN_TO = "run-to"; String ACTION_RUN_SELECTED = "run-selected"; String ACTION_RUN_LAUNCH = "run-launch"; String ACTION_RUN_TERMINATE = "run-terminate"; String ACTION_GET_VMARGS = "run-get-vmargs"; String ACTION_TOGGLE_FORKED = "toggle-forked"; String ACTION_TOGGLE_SLOW_PLAYBACK = "toggle-slow-playback"; String ACTION_TOGGLE_AWT_MODE = "toggle-awt-mode"; String ACTION_TOGGLE_STOP_ON_FAILURE = "toggle-stop-on-failure"; String ACTION_TOGGLE_STOP_ON_ERROR = "toggle-stop-on-error"; String ACTION_INSERT_LAUNCH = "insert-launch"; String ACTION_INSERT_APPLET = "insert-applet"; String ACTION_INSERT_TERMINATE = "insert-terminate"; String ACTION_INSERT_CALL = "insert-call"; String ACTION_INSERT_SAMPLE = "insert-sample"; String ACTION_INSERT_SEQUENCE = "insert-sequence"; String ACTION_INSERT_SCRIPT = "insert-script"; String ACTION_INSERT_FIXTURE = "insert-fixture"; String ACTION_INSERT_COMMENT = "insert-comment"; String ACTION_INSERT_EXPRESSION = "insert-expression"; String ACTION_INSERT_ANNOTATION = "insert-annotation"; String ACTION_DYNAMIC = "dynamic-actions"; String ACTION_CAPTURE_IMAGE = "capture-image"; String ACTION_CAPTURE_COMPONENT = "capture-component"; String ACTION_SELECT_COMPONENT = "select-component"; String ACTION_CAPTURE_FOCUSED_COMPONENT = "capture-focused-component"; String ACTION_SELECT_FOCUSED_COMPONENT = "select-focused-component"; String ACTION_CAPTURE = "capture"; String ACTION_CAPTURE_ALL = "capture-all"; }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/EditorContext.java
package abbot.editor; import abbot.finder.TestHierarchy; import abbot.script.Script; import java.awt.Component; import java.io.File; import java.util.HashSet; import java.util.Set; /** * Provide a transport for the editor context. This is usefull in cases where * the costello editor is invoked inside of another application. It can also * be used to provide further editor customization, for example a new file * template, depending on the context. */ public class EditorContext { private String _arguments[]; private boolean _embedded; private TestHierarchy _hierarchy = null; private SecurityManager _securityManager = null; private File _newFileTemplate = null; private FileSystemHelper _fileSystemHelper = new FileSystemHelper(); public EditorContext(String[] arguments) { _arguments = arguments; } public EditorContext() { _arguments = new String[0]; } // // Getters and setters // public String[] getArguments() { return (String[])_arguments.clone(); } public void setArguments(String[] arguments) { _arguments = arguments; } /** * @return Whether the costello editor is being embdeed in another application */ public boolean isEmbedded() { return _embedded; } /** * @param embedded Whether costello is embedded in another application */ public void setEmbedded(boolean embedded) { _embedded = embedded; } /** * @return A hierarchy that can preconfigured to filter certain components * ignoreExisting call. This is usefull in the embedded case. */ public TestHierarchy getTestHierarchy() { return _hierarchy; } /** * @param hierarchy A hierarchy that can preconfigured to filter certain components * @throws IllegalStateException if we are not in an embedded mode */ public void setTestHierarchy(TestHierarchy hierarchy) { if (!isEmbedded()) { throw new IllegalStateException("Only value when Costello is to be embedded"); } _hierarchy = hierarchy; } /** * @param newFileTemplate The file to be used when creating new * scripts. */ public void setNewFileTemplate(File newFileTemplate) { if (!newFileTemplate.exists()) { throw new IllegalArgumentException("File doesn't exist"); } if (!Script.isScript(newFileTemplate)) { throw new IllegalArgumentException("File doesn't appears to be a script"); } _newFileTemplate = newFileTemplate; } /** * @return The file to be used */ public File getNewFileTemplate() { return _newFileTemplate; } /** * @param securityManager The secutiry manager for this context */ public void setSecurityManager(SecurityManager securityManager) { _securityManager = securityManager; } /** * @return The security manage for this context */ public SecurityManager getSecurityManager() { return _securityManager; } /** * @param helper A file system helper for this context, usefull for the * case where the costello editor is emdedded in an IDE */ public void setFileSysteHelper(FileSystemHelper helper) { _fileSystemHelper = helper; } /** * @return A file system helper for this context */ public FileSystemHelper getFileSystemHelper() { return _fileSystemHelper; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/FileSystemHelper.java
package abbot.editor; import java.io.File; /** * This class is provided as part of the EditorContext object and allows the * editor to make certain request of the ownining context. */ public class FileSystemHelper { /** * When the script editor is saving scripts it uses this function to ensure * that the file is writable. This is usefull in the context of source control * system that require a checkout operation before a file can be written to. * By default this method does nothing as the actions permitted by {@link File} are * rather limited. * * @param file The file that is being requested to make writable * @return Whether the file can be written so, by default just return the file state */ public boolean makeWritable(File file) { return file.exists() ? file.canWrite() : true; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/HierarchyWriter.java
package abbot.editor; import java.awt.*; import java.io.*; import java.util.*; import abbot.script.*; import abbot.finder.Hierarchy; /** Provides support for writing out a GUI hierarchy as XML. */ public class HierarchyWriter { private Hierarchy hierarchy; public HierarchyWriter(Hierarchy h) { this.hierarchy = h; } /** Write to the given writer the GUI hierarchy represented by the given * set of root windows. */ public void writeHierarchy(Writer writer) throws IOException { Resolver r = new Script(hierarchy); writer.write("<awtHierarchy>\r\n"); Iterator iter = hierarchy.getRoots().iterator(); while (iter.hasNext()) { writeComponent(writer, r, (Window)iter.next(), 1); } writer.write("</awtHierarchy>\r\n"); writer.close(); } // FIXME should include java.awt.MenuBar private void writeComponent(Writer writer, Resolver r, Component c, int level) throws IOException { ComponentReference ref = new ComponentReference(r, c); final String INDENT = " "; String xml = ref.toXMLString(); for (int i=0;i < level;i++) { writer.write(INDENT); } Collection set = hierarchy.getComponents(c); if (set.size() != 0) { writer.write(xml.substring(0, xml.length() - 2)); writer.write(">\r\n"); Iterator iter = set.iterator(); while (iter.hasNext()) { writeComponent(writer, r, (Component)iter.next(), level + 1); } for (int i=0;i < level;i++) { writer.write(INDENT); } writer.write("</component>\r\n"); } else { writer.write(xml); writer.write("\r\n"); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/InputMapModel.java
package abbot.editor; import javax.swing.InputMap; import javax.swing.KeyStroke; import javax.swing.table.AbstractTableModel; import abbot.i18n.Strings; public class InputMapModel extends AbstractTableModel { public static InputMapModel EMPTY = new InputMapModel() { public int getRowCount() { return 1; } public Object getValueAt(int row, int col) { return col == 0 ? Strings.get("inputmap.unavailable") : ""; } }; private static final String[] COLUMN_NAMES = { Strings.get("inputmap.key"), Strings.get("inputmap.value"), }; private InputMap map; public InputMapModel() { this(new InputMap()); } public InputMapModel(InputMap map) { this.map = map; } public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { KeyStroke[] keys = map.allKeys(); return keys == null ? 0 : keys.length; } public int getColumnCount() { return 2; } public Object getValueAt(int row, int col) { KeyStroke key = map.allKeys()[row]; return col == 0 ? key : map.get(key); } public boolean isCellEditable(int row, int col) { return false; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/LogoLabel.java
package abbot.editor; /** Provides the abbot/costello logo. */ import javax.swing.*; import javax.swing.border.*; import abbot.i18n.Strings; class LogoLabel extends JLabel { private static final String PATH = "icons/abbot.gif"; public LogoLabel() { super(Strings.get("Splash"), JLabel.CENTER); java.net.URL url = getClass().getResource(PATH); if (url == null) System.err.println("Logo not found at " + PATH); else setIcon(new ImageIcon(url)); setVerticalTextPosition(JLabel.BOTTOM); setHorizontalTextPosition(JLabel.CENTER); setBorder(new EmptyBorder(4,4,4,4)); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/LookAndFeelPreserver.java
package abbot.editor; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import abbot.util.*; /** Preserves the current LAF for a given component hierarchy. */ public class LookAndFeelPreserver { private LookAndFeel laf; private Map owned = new WeakHashMap(); /** Avoid GC of weak reference. */ private AWTEventListener listener; private Frame frame; /** This panel detects any global attempts to set the UI for all components. It can then restore the proper LAF for all registered components. We use this pseudo-listener instead of listening to a "lookAndFeel" property change since the UI components may have updateUI called an arbitrary time (or not at all) after UIManager.setLookAndFeel is called (which triggers the property change notification). */ private JPanel trigger; public LookAndFeelPreserver(Component c) { this(UIManager.getLookAndFeel(), c); } public LookAndFeelPreserver(final LookAndFeel laf, Component c) { this.laf = laf; add(c); listener = new AWTEventListener() { public void eventDispatched(AWTEvent e) { if (e.getID() == ContainerEvent.COMPONENT_ADDED) { componentAdded(((ContainerEvent)e).getChild()); } } }; new WeakAWTEventListener(listener, AWTEvent.CONTAINER_EVENT_MASK); String name = "updateComponentTreeUI Listener"; frame = new Frame(name); frame.setName(name); trigger = new JPanel() { private boolean initialized; { initialized = true; } public void updateUI() { if (initialized) { SwingUtilities.invokeLater(new LAFRestorer(laf, owned)); } } }; frame.add(trigger); } /** Add a component on which to preserve the LAF. */ public void add(final Component c) { owned.put(c, Boolean.TRUE); if (c instanceof Window) { Window[] subs = ((Window)c).getOwnedWindows(); for (int i=0;i < subs.length;i++) { add(subs[i]); } } } private void componentAdded(Component c) { Window w = AWT.getWindow(c); if (w != null) { if (owned.containsKey(w) || owned.containsKey(w.getParent())) { if (!owned.containsKey(w)) add(w); SwingUtilities.invokeLater(new LAFRestorer(laf, c)); } } } private static class LAFRestorer implements Runnable { private LookAndFeel laf; private Map map; public LAFRestorer(LookAndFeel laf, Component c) { this(laf, new WeakHashMap()); map.put(c, Boolean.TRUE); } public LAFRestorer(LookAndFeel laf, Map map) { this.laf = laf; this.map = map; } public void run() { LookAndFeel current = UIManager.getLookAndFeel(); if (current != laf && current != null && !current.equals(laf)) { try { UIManager.setLookAndFeel(laf); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { Component c = (Component)iter.next(); SwingUtilities.updateComponentTreeUI(c); } UIManager.setLookAndFeel(current); } catch(UnsupportedLookAndFeelException e) { // ignore } } } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/OSXAdapter.java
package abbot.editor; import java.awt.Frame; import java.awt.event.ActionEvent; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import java.util.WeakHashMap; import javax.swing.Action; import abbot.Log; /** Provide access to OSX application hooks. Compilable on all platforms. */ public class OSXAdapter implements InvocationHandler { private static Object APPLICATION; private static synchronized Object application() { if (APPLICATION == null) { String cname = "com.apple.eawt.Application"; try { APPLICATION = Class.forName(cname).newInstance(); } catch(Exception e) { throw new Error("Can't load class " + cname + ": " + e); } } return APPLICATION; } /** Values are auto-generated proxy OSX listener. */ private static Map adapters = new WeakHashMap(); private WeakReference source; private Action about; private Action prefs; private Action quit; private Object listener; public static boolean isMac() { return System.getProperty("os.name").toLowerCase().startsWith("mac"); } private OSXAdapter(Frame context, Action quit, Action about, Action prefs) { this.source = new WeakReference(context); this.quit = quit; this.about = about; this.prefs = prefs; try { Object app = application(); Class iface = Class.forName("com.apple.eawt.ApplicationListener"); listener = Proxy.newProxyInstance(OSXAdapter.class.getClassLoader(), new Class[] { iface }, this); Method m = app.getClass().getDeclaredMethod("addApplicationListener", new Class[] { iface }); m.invoke(app, new Object[] { listener }); enablePrefs(prefs != null); Object old = adapters.put(context, this); if (old instanceof OSXAdapter) { ((OSXAdapter)old).unregister(); } } catch(Exception e) { Log.warn(e); } } private void unregister() { try { Object app = application(); Class iface = Class.forName("com.apple.eawt.ApplicationListener"); Method m = app.getClass().getDeclaredMethod("removeApplicationListener", new Class[] { iface }); m.invoke(app, new Object[] { listener }); } catch(Exception e) { Log.warn(e); } } private static final Class[] BOOL_ARGS = new Class[] { boolean.class, }; private void setHandled(Object event, boolean handled) { try { Method m = event.getClass().getDeclaredMethod("setHandled", BOOL_ARGS); m.invoke(event, new Object[] { new Boolean(handled) }); } catch(Exception e) { Log.warn(e); } } /** Returns non-null only if the owner frame is active or if there * are no active frames. */ private Object getSource() { Object src = source.get(); if (src == null) { unregister(); } else { Frame[] frames = Frame.getFrames(); for (int i=0;i < frames.length;i++) { if (frames[i].isActive()) { if (src == frames[i]) { return src; } } } } // It wasn't for our frame, so don't process the event return null; } private ActionEvent createEvent(Object src, Action action) { return new ActionEvent(src, ActionEvent.ACTION_PERFORMED, (String)action.getValue(Action.NAME), System.currentTimeMillis(), 0); } public void handleAbout(Object e) { setHandled(e, true); if (about != null) { Object src = getSource(); if (src != null) { about.actionPerformed(createEvent(src, about)); } } } public void handlePreferences(Object e) { setHandled(e, true); if (prefs!= null) { Object src = getSource(); if (src != null) { prefs.actionPerformed(createEvent(src, prefs)); } } } public void handleQuit(Object e) { // You MUST setHandled(false) if you want to delay or cancel the quit. // This is important for cross-platform development -- have a // universal quit routine that chooses whether or not to quit, so the // functionality is identical on all platforms. This example simply // cancels the AppleEvent-based quit and defers to that universal // method. setHandled(e, false); Object src = getSource(); if (src != null) { quit.actionPerformed(createEvent(src, quit)); } } /** User clicked on application in the Dock. */ public void handleReOpenApplication(Object e) { } public void handleOpenApplication(Object e) { } public void handleOpenFile(Object e) { } public void handlePrintFile(Object e) { } /** Register the given special frame actions with OSX. About and prefs * actions may be null, but quit must be non-null. */ public static void register(Frame owner, Action quit, Action about, Action prefs) { if (isMac()) { if (owner == null) throw new NullPointerException("Parent Frame may not be null"); if (quit == null) throw new NullPointerException("Quit action may not be null"); new OSXAdapter(owner, quit, about, prefs); } } /** Unregister the given frame's actions. */ public static void unregister(Frame owner) { if (isMac()) { Object listener = adapters.get(owner); if (listener != null) { Object adapter = Proxy.getInvocationHandler(listener); if (adapter instanceof OSXAdapter) { ((OSXAdapter)adapter).unregister(); } } } } /** Another static entry point for EAWT functionality. Sets the enabled * stste of the "Preferences..." menu item in the application menu. */ public static void enablePrefs(boolean enabled) { if (isMac()) { try { Object app = application(); Method m = app.getClass().getDeclaredMethod("setEnabledPreferencesMenu", BOOL_ARGS); m.invoke(app, new Object[] { new Boolean(enabled) }); } catch(Exception e) { Log.warn(e); } } } /** Handle all calls from the host OS. */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if ("handleAbout".equals(name)) { handleAbout(args[0]); } else if ("handlePreferences".equals(name)) { handlePreferences(args[0]); } else if ("handleQuit".equals(name)) { handleQuit(args[0]); } else if ("handleReOpenApplication".equals(name)) { handleReOpenApplication(args[0]); } else if ("handleOpenApplication".equals(name)) { handleOpenApplication(args[0]); } else if ("handleOpenFile".equals(name)) { handleOpenFile(args[0]); } else if ("handlePrintFile".equals(name)) { handlePrintFile(args[0]); } else { throw new Error("Unimplemented method " + method); } return null; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/Preferences.java
package abbot.editor; import java.io.*; import java.util.Properties; import abbot.Log; public class Preferences extends Properties { public static final String PROPS_FILENAME = ".abbot.properties"; private File file; public Preferences() { this(PROPS_FILENAME); } public Preferences(String filename) { file = new File(new File(System.getProperty("user.home")), filename); load(); } public int getIntegerProperty(String name, int defaultValue) { String prop = getProperty(name); if (prop != null) { try { return Integer.parseInt(prop); } catch(Exception e) { Log.warn(e); } } return defaultValue; } private void load() { if (file.exists()) { try { load(new BufferedInputStream(new FileInputStream(file))); } catch(IOException io) { Log.warn(io); } } } public void save() { try { store(new BufferedOutputStream(new FileOutputStream(file)), "Abbot view preferences"); } catch(IOException io) { Log.warn(io); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ReferenceAttributeModel.java
package abbot.editor; import javax.swing.table.*; import java.util.*; import abbot.i18n.Strings; import abbot.script.*; /** Provides a table model for ComponentReference attributes. */ public class ReferenceAttributeModel extends AbstractTableModel { private ComponentReference reference; private static String[] COLUMN_NAMES = { Strings.get("attribute.name"), Strings.get("attribute.value") }; public void setReference(ComponentReference ref) { reference = ref; fireTableDataChanged(); } public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { return reference == null ? 0 : reference.getAttributes().values().size(); } public int getColumnCount() { return 2; } public Object getValueAt(int row, int col) { Map.Entry entry = (Map.Entry) reference.getAttributes().entrySet().toArray()[row]; return col == 0 ? entry.getKey() : entry.getValue(); } public void setValueAt(Object value, int row, int col) { if (col == 1) { String key = (String)getValueAt(row, 0); reference.setAttribute(key, (String)value); fireTableCellUpdated(row, col); } } public boolean isCellEditable(int row, int col) { return col == 1; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ReferencesModel.java
package abbot.editor; import javax.swing.table.AbstractTableModel; import abbot.script.*; /** Formats a list of ComponentReferences for display in a table. */ class ReferencesModel extends AbstractTableModel { private Resolver resolver; public ReferencesModel(Resolver resolver) { this.resolver = resolver; } public synchronized int getRowCount() { return resolver.getComponentReferences().size(); } public synchronized int getColumnCount() { return 1; } /** Returns the entry object at the given row. */ public Object getValueAt(int row, int column) { return resolver.getComponentReferences().toArray()[row]; } public String getColumnName(int col) { return ""; } public boolean isCellEditable(int row, int col) { return false; } public Class getColumnClass(int col) { if (col == 0) return ComponentReference.class; return Object.class; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ScriptEditor.java
package abbot.editor; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.reflect.*; import java.net.URL; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.event.*; import junit.extensions.abbot.*; import abbot.BugReport; import abbot.Log; import abbot.ExitException; import abbot.NoExitSecurityManager; import abbot.AssertionFailedError; import abbot.Platform; import abbot.editor.actions.*; import abbot.editor.editors.*; import abbot.editor.recorder.*; import abbot.editor.widgets.*; import abbot.editor.widgets.TextField; import abbot.finder.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Action; import abbot.script.Resolver; import abbot.tester.*; import abbot.tester.Robot; import abbot.util.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; /** * This is the 'model' behind the script editor UI.<p> * * Acts as a resolver, using the currently in-context script as the component * resolver. <p> */ /* To add new actions, add the action to the list in initActions(), * and optionally add it to the menu layout in initMenus. Define a name for * it in EditorConstants, and an inner Action class for it which uses that * name. */ // Apologies for the extreme cruftiness and lack of proper factoring. This // was written at the same time as the underlying framework, and refactored // (sort of) into model/view at the same time, so it's hardly a shining // example of clean design. Don't know if it would have been any better // written TDD, though. public class ScriptEditor implements ActionListener, Resolver, EditorConstants { private static int selectKey; private static int captureKey; private static int captureImageKey; static { try { new EventExceptionHandler().install(); } catch(Exception e) { // Ignore for now } String key = System.getProperty("abbot.editor.select_key", "CONTROL"); selectKey = KeyStroke.getKeyStroke(key).getKeyCode(); key = System.getProperty("abbot.editor.capture_key", "F2"); captureKey = KeyStroke.getKeyStroke(key).getKeyCode(); key = System.getProperty("abbot.editor.capture_image_key", "F3"); captureImageKey = KeyStroke.getKeyStroke(key).getKeyCode(); } // if set, log all events, even those going to filtered components private static final boolean LOG_ALL_EVENTS = Boolean.getBoolean("abbot.editor.log_all_events"); private static final long FIXTURE_EVENT_MASK = Long.getLong("abbot.fixture.event_mask", EventRecorder.RECORDING_EVENT_MASK).longValue(); /** Key to use to invert an assertion/wait. */ public static final int KC_INVERT = KeyEvent.VK_SHIFT; /** Key to use to insert a wait instead of an assertion. Use option key on mac, control key anywhere else. */ public static final int KC_WAIT = Platform.isMacintosh() ? KeyEvent.VK_ALT : KeyEvent.VK_CONTROL; /** Flag for informational status. */ private static final int INFO = 0; /** Flag to indicate a warning. */ private static final int WARN = 1; /** Flag to indicate an error. */ private static final int ERROR = 2; /** Flag to indicate a script failure. */ private static final int FAILURE = 3; /** Prefixes for different types of status messages. */ private static final String[] statusFormat = { "Normal", "Warning", "Error", "Failure" }; private static final Color[] statusColor = { Color.black, Color.orange.darker(), Color.red, Color.red, }; private ArrayList insertActions = new ArrayList(); private ArrayList assertActions = new ArrayList(); private ArrayList waitActions = new ArrayList(); private ArrayList captureActions = new ArrayList(); /** Adapter for representing the script itself, providing access to * individual script steps. */ private ScriptModel scriptModel; private ScriptTable scriptTable; private SecurityManager securityManager; private SecurityManager oldSecurityManager; private int nonce; /** Keep all application under test threads in the same group to make them * easier to track. */ private ThreadGroup appGroup; private TestHierarchy hierarchy; private Hierarchy oldHierarchy; private Recorder[] recorders; private SpinningDialWaitIndicator waiter; /** Allow exits from anywhere until the editor is fully initialized. */ private boolean rootIsExiting = true; private boolean exiting; private boolean hiding; private boolean ignoreStepEvents; /** Whether to ignore incoming AWT events. */ private boolean ignoreEvents; /** Is there a script or launch step currently running? */ private boolean isScriptRunning; /** When was some portion of the app exercised? */ private long lastLaunchTime; /** Are we trying to capture an image? */ private boolean capturingImage; /** What component is currently "selected" for capture? */ private Component captureComponent; private Component innermostCaptureComponent; private Highlighter highlighter; /** Is this the first editor launched, or one under test? */ private boolean isRootEditor = true; /** AWT input state. */ private static InputState state = Robot.getState(); /** Generic filter to select a test script. */ private ScriptFilter filter = new ScriptFilter(); /** Current test case class (should derive from AWTTestCase). */ private Class testClass; /** Current test suite. */ private ScriptTestSuite testSuite; /** Current test script. */ private Script testScript; /** Is the current script a temporary placeholder? */ private File tempFile; /** Runner used to execute the script. */ private StepRunner runner; /** Current set of scripts, based on the test suite (if any). */ private List testScriptList; /** Currently selected component. Note that this may be a dummy * component. */ private Component selectedComponent; /** Currently selected reference, if any. */ private ComponentReference selectedReference; /** Are we currently recording events? */ private boolean recording; /** The current recorder to pass events for capture. */ private Recorder recorder; /** Since recorder starts with a key release, and stops with a key press, make sure we don't start immediately after stopping. */ private boolean justStoppedRecording; /** Need to be able to set the combo box selection w/o reacting to the * resulting posted action. */ private boolean ignoreComboBox; /** Where to stop. */ private Step stopStep; // GUI components private JFileChooser chooser; private ScriptEditorFrame view; private ComboBoxModel model; private boolean invertAssertions; private boolean waitAssertions; private ActionMap actionMap; private String name; /** The edtiro configuration */ private EditorContext editorConfiguration; /** * Constructs a ScriptEditor which handles script editing logic. * ScriptEditorFrame provides the view/controller. * @see ScriptEditorFrame */ public ScriptEditor(EditorContext ec) { editorConfiguration = ec; // if (ec.isEmbedded()) { name = "Script Editor (emdedded)"; } else if (Boolean.getBoolean("abbot.framework.launched")) { isRootEditor = false; name = "Script Editor (under test)"; } else { System.setProperty("abbot.framework.launched", "true"); name = "Script Editor (root)"; } // TODO: clean this up actionMap = initActions(); hierarchy = initContext(isRootEditor); recorders = initRecorders(); view = initFrame(isRootEditor); hierarchy.setFiltered(view, true); updateDynamicActions(view); view.setComponentBrowser(createComponentBrowser()); addEventHandlers(view); // Clear the status only if there were no errors if (view.getStatus().equals(Strings.get("Initializing"))) { setStatus(Strings.get("Ready")); } rootIsExiting = false; } /** Provides a convenient menu setup definition. Use a defined action name to indicate that action's place within the menu. Null values indicate menu separators. */ private String[][] initMenus() { ArrayList fileMenu = new ArrayList(); ArrayList helpMenu = new ArrayList(); fileMenu.addAll(Arrays.asList(new String[] { MENU_FILE, ACTION_SCRIPT_NEW, ACTION_SCRIPT_DUPLICATE, ACTION_SCRIPT_OPEN, null, ACTION_SCRIPT_SAVE, ACTION_SCRIPT_SAVE_AS, ACTION_SCRIPT_RENAME, ACTION_SCRIPT_CLOSE, null, ACTION_SCRIPT_DELETE, })); helpMenu.add(MENU_HELP); if (!Platform.isOSX()) { fileMenu.add(null); fileMenu.add(ACTION_EDITOR_QUIT); helpMenu.add(ACTION_EDITOR_ABOUT); } helpMenu.addAll(Arrays.asList(new String[] { ACTION_EDITOR_USERGUIDE, ACTION_EDITOR_WEBSITE, ACTION_EDITOR_EMAIL, ACTION_EDITOR_BUGREPORT, })); return new String[][] { (String[])fileMenu.toArray(new String[fileMenu.size()]), { MENU_EDIT, ACTION_STEP_CUT, ACTION_STEP_COPY, ACTION_STEP_PASTE, ACTION_STEP_DELETE, null, ACTION_STEP_MOVE_UP, ACTION_STEP_MOVE_DOWN, ACTION_STEP_GROUP, null, ACTION_SELECT_COMPONENT, ACTION_SELECT_FOCUSED_COMPONENT, null, ACTION_SCRIPT_CLEAR, }, { MENU_TEST, ACTION_RUN, ACTION_RUN_TO, ACTION_RUN_SELECTED, null, ACTION_EXPORT_HIERARCHY, null, ACTION_RUN_LAUNCH, ACTION_RUN_TERMINATE, null, ACTION_TOGGLE_STOP_ON_FAILURE, ACTION_TOGGLE_STOP_ON_ERROR, ACTION_TOGGLE_FORKED, ACTION_GET_VMARGS, ACTION_TOGGLE_SLOW_PLAYBACK, ACTION_TOGGLE_AWT_MODE, }, { MENU_INSERT, ACTION_INSERT_ANNOTATION, ACTION_INSERT_APPLET, ACTION_INSERT_CALL, ACTION_INSERT_COMMENT, ACTION_INSERT_EXPRESSION, ACTION_INSERT_LAUNCH, ACTION_INSERT_FIXTURE, ACTION_INSERT_SAMPLE, ACTION_INSERT_SCRIPT, ACTION_INSERT_SEQUENCE, ACTION_INSERT_TERMINATE, }, { MENU_CAPTURE, }, (String[])helpMenu.toArray(new String[helpMenu.size()]), }; } // All editor actions should be defined here private ActionMap initActions() { javax.swing.Action[] actions = { new EditorAboutAction(), new EditorEmailAction(), new EditorBugReportAction(), new EditorWebsiteAction(), new EditorUserGuideAction(), new EditorQuitAction(), new ScriptOpenAction(), new ScriptNewAction(), new ScriptDuplicateAction(), new ScriptSaveAction(), new ScriptSaveAsAction(), new ScriptRenameAction(), new ScriptCloseAction(), new ScriptDeleteAction(), new ScriptClearAction(), new StepCutAction(), new StepCopyAction(), new StepPasteAction(), new StepDeleteAction(), new StepMoveUpAction(), new StepMoveDownAction(), new StepGroupAction(), new RunAction(), new RunToAction(), new RunSelectedAction(), new RunLaunchAction(), new RunTerminateAction(), new GetVMArgsAction(), new SelectTestSuiteAction(), new ExportHierarchyAction(), new ToggleForkedAction(), new InsertLaunchAction(), new InsertFixtureAction(), new InsertAppletAction(), new InsertTerminateAction(), new InsertCallAction(), new InsertSampleAction(), new InsertSequenceAction(), new InsertScriptAction(), new InsertCommentAction(), new InsertExpressionAction(), new InsertAnnotationAction(), new ToggleStopOnFailureAction(), new ToggleStopOnErrorAction(), new ToggleSlowPlaybackAction(), new ToggleAWTModeAction(), new CaptureImageAction(), new CaptureComponentAction(), new SelectComponentAction(), new CaptureFocusedComponentAction(), new SelectFocusedComponentAction(), }; ActionMap map = new ActionMap(); for (int i=0;i < actions.length;i++) { Object key = actions[i].getValue(EditorAction.ACTION_KEY); map.put(key, actions[i]); } return map; } /** * Add event handlers to their respective components */ private void addEventHandlers(final ScriptEditorFrame view) { scriptTable.getSelectionModel(). addListSelectionListener(new ScriptTableSelectionHandler()); scriptTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if ((me.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { if (view.getEditor() == null) setStepEditor(); } } }); MouseListener ml = new MouseAdapter() { public void mouseClicked(MouseEvent me) { if ((me.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { int size = scriptTable.getRowCount(); scriptTable.clearSelection(); scriptTable.setCursorLocation(size); } } }; view.addMouseListener(ml); view.getTestScriptSelector().addItemListener(new ScriptSelectorItemHandler()); view.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quitApplication(); } }); if (Platform.isOSX()) { // Mac has it's own dedicated Quit/About menu items OSXAdapter.register(view, actionMap.get(ACTION_EDITOR_QUIT), actionMap.get(ACTION_EDITOR_ABOUT), null); } } /** * Determines if the editor is testing itself and initializes the * security manager accordingly. */ private TestHierarchy initContext(boolean isRoot) { TestHierarchy hierarchy = editorConfiguration.getTestHierarchy(); if (hierarchy==null) { hierarchy = new TestHierarchy() { private String desc = "Test hierarchy for " + name; public String toString() { return desc; } }; } // eventually this should go away; all hierarchy usage should be // explicit. oldHierarchy = AWTHierarchy.getDefault(); if (isRoot) { AWTHierarchy.setDefault(hierarchy); initSecurityManager(); try { new EventExceptionHandler().install(); } catch(Exception e) { Log.warn(e); } } return hierarchy; } private Recorder[] initRecorders() { // Use the editor as the resolver, since the actual resolver will // be the currently scoped script. Recorder[] recorders = new Recorder[] { new EventRecorder(this, false), new EventRecorder(this, true), }; ActionListener recorderListener = new ActionListener() { public void actionPerformed(final ActionEvent event) { setStatus(event.getActionCommand()); } }; for (int i=0;i < recorders.length;i++) { recorders[i].addActionListener(recorderListener); } return recorders; } /** Initialize the primary editor frame. */ private ScriptEditorFrame initFrame(final boolean isRoot) { scriptModel = new ScriptModel() { public boolean isCellEditable(int row, int col) { return false; } }; runner = new EditorStepRunner(); runner.setTerminateOnError(false); runner.addStepListener(new StepListener() { public void stateChanged(StepEvent ev) { if (ignoreStepEvents) return; reflectScriptExecutionState(ev); } }); // Customize the ScriptTable so we can vary the color of any given // step based on our last run status (of which the table itself should // be ignorant). scriptTable = new ScriptTable(scriptModel) { public Color getStepColor(Step step, boolean selected) { Color color = super.getStepColor(step, selected); // Make the stop step appear a different color if (step == stopStep) { Color stopColor = getSelectionBackground().darker(); color = stopColor; } Throwable thr = runner.getError(step); if (thr != null) { Color tint = (thr instanceof AssertionFailedError) ? statusColor[ScriptEditor.FAILURE] : statusColor[ScriptEditor.ERROR]; if (step instanceof Sequence) { color = color.brighter(); } if (selected) { color = mixColors(color, tint); } else { color = tint; } } return color; } }; // Override default "cut" action in table ActionMap amap = scriptTable.getActionMap(); amap.put("delete", actionMap.get(ACTION_STEP_DELETE)); amap.put("cut", actionMap.get(ACTION_STEP_CUT)); amap.put("copy", actionMap.get(ACTION_STEP_COPY)); amap.put("paste", actionMap.get(ACTION_STEP_PASTE)); InputMap imap = scriptTable.getInputMap(); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "toggle"); // Only allow the script editor to dispose of the frame String prefFile = Preferences.PROPS_FILENAME; if (!isRoot) { prefFile += ".tmp"; } Preferences prefs = new Preferences(prefFile); String title = Strings.get("ScriptEditor.title", new Object[] {""}); ScriptEditorFrame f = new ScriptEditorFrame(initMenus(), actionMap, this, title, scriptTable, prefs) { /** @deprecated Don't allow code under test to hide the editor. */ public void hide() { if (hiding || isDisposeFromRootEditor()) { hiding = false; super.hide(); } } public void dispose() { // Need to prevent arbitrary disposal by the code under test. // Only allow the dispose if one of the following is true: // a) we triggered it (exiting == true) // b) the root script editor is disposing us if (exiting || isDisposeFromRootEditor()) { super.dispose(); } } public String getName() { String name = super.getName(); if (isRoot) name += " (root)"; return name; } }; return f; } /** Provide a color that is a mix of the two given colors. */ private Color mixColors(Color c1, Color c2) { return new Color((c1.getRed() + c2.getRed())/2, (c1.getGreen() + c2.getGreen())/2, (c1.getBlue() + c2.getBlue())/2); } /** Return whether the root editor disposed of this instance. */ private boolean isDisposeFromRootEditor() { // FIXME cf how applets prevent disposal of embedded frame // AWTHierarchy surrounds disposal calls with the property // abbot.finder.disposal set to "true" return !isRootEditor && Boolean.getBoolean("abbot.finder.disposal"); } private void createAsserts(ArrayList list, ComponentTester tester, boolean wait) { list.clear(); Method[] methods = tester.getAssertMethods(); for (int i = 0; i < methods.length; i++) { list.add(new TesterMethodAction(tester, methods[i], wait)); } methods = tester.getComponentAssertMethods(); if (list.size() != 0 && methods.length != 0) list.add(null); for (int i = 0; i < methods.length; i++) { list.add(new TesterMethodAction(tester, methods[i], wait)); } methods = tester.getPropertyMethods(); if (list.size() != 0 && methods.length != 0) list.add(null); for (int i = 0; i < methods.length; i++) { String name = methods[i].getName(); if (name.startsWith("is")) name = name.substring(2); else if (name.startsWith("get") || name.startsWith("has")) name = name.substring(3); list.add(new TesterMethodAction(tester, methods[i], wait)); } } /** Return a script step encapsulating an image comparison. * Assumes the script context is not null. */ private Step captureComponentImage(Component comp) { Step step = null; ComponentTester tester = ComponentTester.getTester(comp); java.awt.image.BufferedImage img = tester.capture(comp, !(comp instanceof Window)); try { // Save the image file relative to the current context ComponentReference ref = addComponent(comp); File scriptFile = ((Script)getResolverContext()).getFile(); File newFile = new File(getResolverContext().getDirectory(), scriptFile.getName() + "-" + ref.getID() + ImageComparator.IMAGE_SUFFIX); int index = 1; while (newFile.exists()) { newFile = new File(getResolverContext().getDirectory(), scriptFile.getName() + "-" + ref.getID() + "-" + index++ + ImageComparator.IMAGE_SUFFIX); } ImageComparator.writeImage(newFile, img); // Note that the pathname is saved relative to the script // context. step = new Assert(getResolverContext(), null, ComponentTester.class.getName(), "assertImage", new String[] { ref.getID(), newFile.getName(), "true" }, "true", false); } catch(IOException io) { Log.warn(io); } return step; } /** Start recording, launching the code under test if necessary. */ private void startRecording(Recorder rec) { Log.debug("Starting recorder"); boolean noWindows = countShowingWindows(null) == 0; boolean canLaunch = testScript != null && testScript.hasLaunch() && !isAppLaunched(); if (noWindows && !canLaunch) { // Can't launch, and there are no windows to // record on, so show a warning view.showError(Strings.get("NoWindows.title"), Strings.get("NoWindows")); } else { if (recorder != null) stopRecording(true); Log.debug("Now recording with " + rec); recording = true; recorder = rec; setStatus("Please wait..."); // Apply an input blocking mask to show the recorder is busy //waiter = new SpinningDialWaitIndicator(view); //waiter.setText("Recording..."); // get us out of the way // FIXME this puts us WAY back on linux; this is only a // problem in that the status bar is often hidden // Maybe make a floating status while the recorder is // running. // Only go back if the app is already up, otherwise the // about-to-be-launched app is hidden. if (!noWindows) view.toBack(); recorder.start(); if (noWindows) { launch(false); } } } /** Stop recording and update the recorder actions' state. */ private void stopRecording(boolean discardRecording) { Log.debug("Stopping recorder"); recording = false; int type = INFO; String extended = null; String status = Strings.get(discardRecording ? "RecorderCanceled" : "RecorderFinished"); try { recorder.terminate(); } catch(RecordingFailedException e) { String msg = Strings.get("editor.recording.stop_failure"); Throwable error = e.getCause() instanceof BugReport ? e.getCause() : new BugReport(msg, e.getCause()); Log.log("Recording stop failure: " + error.toString()); view.showWarning(msg); status = error.getMessage(); extended = error.toString(); type = ERROR; } try { if (!discardRecording) { Step step = recorder.getStep(); // Ignore empty results if (!(step instanceof Sequence && ((Sequence)step).size() == 0)) { addStep(step); } } } finally { recorder = null; if (waiter != null) { waiter.dispose(); waiter = null; } } view.toFront(); setStatus(status, extended, type); } private RecordAllAction recordAllAction; private RecordAllAction recordAllMotionAction; private void updateDynamicActions(ScriptEditorFrame view) { Class cls = selectedComponent == null ? Component.class : selectedComponent.getClass(); ComponentTester tester = ComponentTester.getTester(cls); // assert submenu createAsserts(assertActions, tester, false); // wait submenu createAsserts(waitActions, tester, true); // insert submenu (only include one instance of each uniquely-named // method. insertActions.clear(); Map map = new HashMap(); Method[] methods = tester.getActions(); for (int i=0;i < methods.length;i++) { TesterMethodAction action = new TesterMethodAction(tester, methods[i], true); map.put(action.getName(), action); } methods = tester.getComponentActions(); for (int i = 0; i < methods.length; i++) { TesterMethodAction action = new TesterMethodAction(tester, methods[i], true); map.put(action.getName(), action); } insertActions.addAll(map.values()); // capture actions captureActions.clear(); recordAllAction = new RecordAllAction(ACTION_CAPTURE, recorders[0], false); captureActions.add(recordAllAction); recordAllMotionAction = new RecordAllAction(ACTION_CAPTURE_ALL, recorders[1], true); captureActions.add(recordAllMotionAction); captureActions.add(null); captureActions.add(new CaptureImageAction()); captureActions.add(new CaptureComponentAction()); captureActions.add(new CaptureFocusedComponentAction()); view.populateInsertMenu(insertActions); view.populateAssertMenu(assertActions); view.populateWaitMenu(waitActions); view.populateCaptureMenu(captureActions); } private void setSelected(String which, boolean select) { javax.swing.Action action = actionMap.get(which); if (action != null) { ((EditorToggleAction)action).setSelected(select); } else { Log.warn("Toggle action " + which + " is missing"); } } private void setEnabled(String which, boolean enable) { javax.swing.Action action; if (which == ACTION_DYNAMIC) { ArrayList[] lists = new ArrayList[] { captureActions, waitActions, assertActions, insertActions }; for (int i=0;i < lists.length;i++) { Iterator iter = lists[i].iterator(); while (iter.hasNext()) { action = (javax.swing.Action)iter.next(); if (action != null) action.setEnabled(enable); } } } else { action = actionMap.get(which); if (action != null) { action.setEnabled(enable); } else { Log.warn("Action " + which + " is missing"); } } } /** * Initalize the componentBrowser and listeners to the scriptTable */ private ComponentBrowser createComponentBrowser() { ComponentBrowser cb = new ComponentBrowser(this, hierarchy); cb.setEnabled(false); cb.addSelectionListener(new ComponentBrowserListener() { public void selectionChanged(ComponentBrowser src, Component comp, ComponentReference ref) { setSelectedComponent(comp, ref); } public void propertyAction(ComponentBrowser src, Method m, Object value, boolean sample) { if (selectedComponent == null) return; addPropertyMethodCall(m, value, sample); } }); return cb; } /** * Install a new security manager to prevent launched applications * from exiting the JVM. This is only a partial solution; ideally * we'd like to be able to kill all the launched app's threads, or force * an unload of the class and reload it. * Should only be installed once, in the root editor context. */ private void initSecurityManager() { if (Boolean.getBoolean("abbot.no_security_manager")) return; securityManager = editorConfiguration.getSecurityManager(); if (securityManager==null) { securityManager = new EditorSecurityManager(); } try { oldSecurityManager = System.getSecurityManager(); System.setSecurityManager(securityManager); } catch(Exception e) { oldSecurityManager = securityManager = null; Log.warn(e); } } /** Respond to various components. */ public void actionPerformed(ActionEvent ev) { if (ev.getSource() == view.getTestScriptSelector() && !ignoreComboBox) { Script script = (Script) view.getTestScriptSelector().getSelectedItem(); if (script != testScript) setScript(script); } else if (ev.getSource() == view.getTestScriptDescription()) { if (testScript != null) { JTextField tf = view.getTestScriptDescription(); String desc = tf.getText(); if ("".equals(desc)) { String cmd = ev.getActionCommand(); if (!TextField.isDocumentAction(cmd)) { tf.setText(testScript.getDefaultDescription()); testScript.setDescription(null); } } else if (!desc.equals(testScript.getDefaultDescription())) { testScript.setDescription(desc); } } } else { Log.warn("Unrecognized event: " + ev.getActionCommand() + "(" + ev.getID() + ")"); } } /** Remove the selected step. */ private void deleteSelection() { int row = scriptTable.getSelectedRow(); if (row == -1) { Log.warn("Unexpected delete state"); return; } List<Step> stepsToRemove = scriptTable.getSelectedSteps(); // Remove elements as required removeStepsFromModel(row, stepsToRemove); } /** Remove the selected step. */ private void copySelection(boolean cut) { int row = scriptTable.getSelectedRow(); if (row == -1) { Log.warn("Unexpected cut state"); return; } List<Step> stepsToRemove = scriptTable.getSelectedSteps(); // Build a string of the selected characters // StringBuilder sb = new StringBuilder(); for (Step nextStep : stepsToRemove) { sb.append(Step.toXMLString(nextStep)); sb.append("\n"); } // Remove elements as required if (cut) { removeStepsFromModel(row, stepsToRemove); } // Place the text on the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(sb.toString()), null); // setActionsEnabledState(); setStatus(""); } private void removeStepsFromModel(int row, List<Step> stepsToRemove) { // Remove the steps from the model scriptModel.removeSteps(stepsToRemove); int count = scriptTable.getRowCount(); if (count > 0) { if (row >= count) row = count - 1; scriptTable.setRowSelectionInterval(row, row); scriptTable.setCursorLocation(row + 1); } } /** Remove the selected step. */ private void pasteSteps() { int row = scriptTable.getSelectedRow(); if (row == -1) { Log.warn("Unexpected paste state"); return; } // String status = ""; // Right lets get hold of the steps Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transferable = clipboard.getContents(null); if (transferable!=null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String st = (String)transferable.getTransferData(DataFlavor.stringFlavor); // Make this string into a sequence so we can parse it String sequenceString = "<sequence>\n" + st + "</sequence>"; Sequence sequence = Sequence.createSequenceFromString(scriptModel.getScriptOf(row), sequenceString); Step step = scriptModel.getStepAt(row); Sequence parent; int index; if (step instanceof Sequence && scriptModel.isOpen(step)) { parent = (Sequence)step; index = 0; } else { parent = scriptModel.getParent(step); index = parent.indexOf(step) +1; } scriptModel.insertSteps( parent, sequence.steps(), index); } catch (Exception ex) { Log.warn(ex); status = ex.getMessage(); } } setActionsEnabledState(); setStatus(status); } private void moveSelectionUp() { scriptTable.moveUp(); setActionsEnabledState(); } /** Move the selected step down. */ private void moveSelectionDown() { scriptTable.moveDown(); setActionsEnabledState(); } /** Put the current selection into a sequence. */ private void groupSelection() { int row = scriptTable.getSelectedRow(); Sequence seq = new Sequence(getResolverContext(), (String)null); List list = scriptTable.getSelectedSteps(); Step first = (Step)list.get(0); Sequence parent = scriptModel.getParent(first); int index = parent.indexOf(first); scriptModel.removeSteps(list); Iterator iter = list.iterator(); Step last = parent; while (iter.hasNext()) { last = (Step)iter.next(); seq.addStep(last); } scriptModel.insertStep(parent, seq, index); scriptModel.toggle(row); scriptTable.setRowSelectionInterval(row, scriptModel.getRowOf(last)); setActionsEnabledState(); } /** Insert a launch step. */ void insertLaunch() { Step step = new Launch(getResolverContext(), LaunchEditor.HELP_DESC, "abbot.editor.ScriptEditor", "main", new String[] { "[]" }, ".", false); addStep(step); } /** Insert an applet step. */ void insertApplet() { Step step = new Appletviewer(getResolverContext(), AppletviewerEditor.HELP_DESC, "your.applet.class.here", new HashMap(), null, null, null); addStep(step); } /** Insert a terminate step. */ void insertTerminate() { Step step = new Terminate(getResolverContext(), (String) null); scriptTable.setCursorLocation(scriptTable.getRowCount()); addStep(step); } private void insertCall(boolean sample) { if (sample) { addStep(new Sample(getResolverContext(), (String)null, Strings.get("YourClassName"), Strings.get("YourMethodName"), null, Strings.get("YourPropertyName"))); } else { addStep(new Call(getResolverContext(), (String)null, Strings.get("YourClassName"), Strings.get("YourMethodName"), null)); } } /** Insert a new, empty sequence. */ private void insertSequence() { addStep(new Sequence(getResolverContext(), (String) null, null)); } private void insertComment() { addStep(new Comment(getResolverContext(), "")); } private void insertExpression() { addStep(new Expression(getResolverContext(), "")); } private void insertAnnotation() { addStep(new Annotation(getResolverContext(), "")); } /** Insert another script as a step in this one. */ private void insertScript(boolean fixture) { JFileChooser chooser = getChooser(filter); chooser.setCurrentDirectory(getWorkingDirectory()); if (chooser.showOpenDialog(view) == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.exists()) { try { file.createNewFile(); } catch(IOException e) { view.showError(e.toString()); } } Script script = fixture ? new Fixture(file.getAbsolutePath(), hierarchy) : new Script(file.getAbsolutePath(), hierarchy); try { script.load(); addStep(script); } catch (Exception exc) { view.showError(exc.toString()); } } } /** Returns the current test suite's directory, if available, the directory of the current script, if available, or the current working directory. If the current script has not yet been saved, uses the current working directory. */ private File getWorkingDirectory() { return testSuite != null ? testSuite.getDirectory() : (testScript != null && !editingTempFile() ? testScript.getDirectory() : new File(System.getProperty("user.dir"))); } /** Return a file chooser that filters for test scripts. */ // FIXME some open, close operations should be sticky w/r/t // last directory used private JFileChooser getChooser(FileFilter f) { if (chooser == null) { chooser = new JFileChooser(); chooser.setCurrentDirectory(getWorkingDirectory()); } chooser.setFileFilter(f); return chooser; } /** Set the test case to the one corresponding to the given index. */ private void setScript(int index) { if (getScripts().size() == 0) { setScript((Script) null); if (testSuite != null) setStatus(Strings.get("NoScripts"), null, WARN); } else { if (index >= getScripts().size()) index = getScripts().size() - 1; setScript(getScriptAt(index)); } } private void setScript(Script script) { if (script == testScript && script != null) return; Log.debug("Setting script to '" + script + "'"); if (script != null) { try { script.load(); } catch(InvalidScriptException ise) { Log.warn(ise); setScript((String)null); view.showError("Invalid Script", ise.toString()); return; } catch(Exception e) { setScript((String)null); Log.warn(e); return; } } if (testScript != null) { UIContext context = testScript.getUIContext(); if (context != null && !context.equivalent(runner.getCurrentContext())) runner.terminate(); } testScript = script; scriptTable.clearSelection(); scriptModel.setScript(script); if (script == null) { scriptTable.setCursorLocation(0); scriptTable.setEnabled(false); view.getTestScriptDescription().setText(""); view.getTestScriptDescription().setEnabled(false); setStatus(Strings.get("NoScript")); } else { scriptTable.setEnabled(true); scriptTable.setCursorLocation(script.hasLaunch() ? 1 : 0); if (chooser != null) { chooser.setCurrentDirectory(script.getDirectory()); } view.getTestScriptDescription().setText(script.getDescription()); view.getTestScriptDescription().setEnabled(true); setStatus(Strings.get("editor.editing_script", new Object[] { testScript.getName() })); } setActionsEnabledState(); ignoreComboBox = true; view.getTestScriptSelector().setSelectedItem(testScript); ignoreComboBox = false; updateTitle(); } /** Update the state of all actions. This method should be invoked after * any GUI state change. */ private void setActionsEnabledState() { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { setActionsEnabledState(); } }); return; } boolean haveScript = testScript != null; boolean haveSelection = scriptTable.getSelectedRow() != -1; boolean notEmdedded = !editorConfiguration.isEmbedded(); setEnabled(ACTION_SCRIPT_OPEN, true); setEnabled(ACTION_TOGGLE_STOP_ON_FAILURE, haveScript); setSelected(ACTION_TOGGLE_STOP_ON_FAILURE, haveScript && runner.getStopOnFailure()); setEnabled(ACTION_TOGGLE_STOP_ON_ERROR, haveScript); setSelected(ACTION_TOGGLE_STOP_ON_ERROR, haveScript && runner.getStopOnError()); setEnabled(ACTION_TOGGLE_FORKED, haveScript); setSelected(ACTION_TOGGLE_FORKED, haveScript && testScript.isForked()); setEnabled(ACTION_GET_VMARGS, haveScript && testScript.isForked()); setEnabled(ACTION_TOGGLE_SLOW_PLAYBACK, haveScript); setSelected(ACTION_TOGGLE_SLOW_PLAYBACK, haveScript && testScript.isSlowPlayback()); setEnabled(ACTION_TOGGLE_AWT_MODE, haveScript); setSelected(ACTION_TOGGLE_AWT_MODE, haveScript && testScript.isAWTMode()); setEnabled(ACTION_RUN, haveScript); setEnabled(ACTION_RUN_TO, haveScript && haveSelection); setEnabled(ACTION_RUN_SELECTED, haveScript && haveSelection && isAppLaunched()); setEnabled(ACTION_EXPORT_HIERARCHY, haveScript && isAppLaunched()); setEnabled(ACTION_RUN_LAUNCH, haveScript && notEmdedded && testScript.hasLaunch() && !isAppLaunched()); setEnabled(ACTION_RUN_TERMINATE, isAppLaunched() && notEmdedded); setEnabled(ACTION_SCRIPT_NEW, true); setEnabled(ACTION_SCRIPT_DUPLICATE, haveScript); setEnabled(ACTION_SCRIPT_SAVE, haveScript); setEnabled(ACTION_SCRIPT_SAVE_AS, haveScript); setEnabled(ACTION_SCRIPT_RENAME, haveScript); setEnabled(ACTION_SCRIPT_DELETE, haveScript); setEnabled(ACTION_SCRIPT_CLOSE, haveScript); setEnabled(ACTION_STEP_CUT, haveScript && haveSelection); setEnabled(ACTION_STEP_COPY, haveScript && haveSelection); // Only allow string pastes, hope it works Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); boolean stringOnClipboard; try { stringOnClipboard = clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor); } catch (IllegalArgumentException iae) { // if we cannot access the clipboard give up. stringOnClipboard = false; } setEnabled(ACTION_STEP_PASTE, haveScript && haveSelection && (stringOnClipboard)); setEnabled(ACTION_STEP_DELETE, haveScript && haveSelection); setEnabled(ACTION_STEP_MOVE_UP, haveScript && haveSelection && scriptTable.canMoveUp()); setEnabled(ACTION_STEP_MOVE_DOWN, haveScript && haveSelection && scriptTable.canMoveDown()); setEnabled(ACTION_STEP_GROUP, haveScript && haveSelection); setEnabled(ACTION_SCRIPT_CLEAR, haveScript); setEnabled(ACTION_INSERT_LAUNCH, notEmdedded && haveScript && !testScript.hasLaunch()); setEnabled(ACTION_INSERT_FIXTURE, haveScript && !testScript.hasLaunch()); setEnabled(ACTION_INSERT_APPLET, notEmdedded && haveScript && !testScript.hasLaunch()); setEnabled(ACTION_INSERT_TERMINATE, notEmdedded && haveScript && !testScript.hasTerminate()); setEnabled(ACTION_INSERT_SCRIPT, haveScript); setEnabled(ACTION_INSERT_CALL, haveScript); setEnabled(ACTION_INSERT_SAMPLE, haveScript); setEnabled(ACTION_INSERT_SEQUENCE, haveScript); setEnabled(ACTION_INSERT_COMMENT, haveScript); setEnabled(ACTION_INSERT_EXPRESSION, haveScript); setEnabled(ACTION_INSERT_ANNOTATION, haveScript); setEnabled(ACTION_DYNAMIC, haveScript); view.getComponentBrowser().setEnabled(!isScriptRunning); } /** Set the current test script. */ void setScript(String filename) { Script script = filename != null ? new Script(filename, hierarchy) : null; setScript(script); } /** Indicate the component and/or reference currently in use. */ private void setSelectedComponent(Component c, ComponentReference ref) { if (c == selectedComponent && ref == selectedReference) return; boolean updateActions = c != selectedComponent; selectedComponent = c; selectedReference = ref; String status; if (ref != null) { status = Strings.get(c == null ? "ComponentReferenceX" : "ComponentReference", new Object[] { ref.getID() }); } else if (c != null) { status = hierarchy.contains(c) ? Strings.get("UnreferencedComponent") : Strings.get("editor.component_filtered"); } else { status = Strings.get("NoComponent"); } setStatus(status); if (updateActions) { updateDynamicActions(view); } } private void setTestSuite(String suiteClassname) { setTestSuite(suiteClassname, null); } /** Sets the currently selected test suite, updating all gui components appropriately. */ private void setTestSuite(String suiteClassname, ClassLoader cl) { if (cl == null) cl = getClass().getClassLoader(); Log.debug("Setting test suite to " + suiteClassname); testSuite = null; testScriptList = null; if (suiteClassname != null) { try { // FIXME use a dynamic class loader so we can reload after // changes to the suite/fixture class. Class cls = Class.forName(suiteClassname, true, cl); if (!ScriptFixture.class.isAssignableFrom(cls) && !ScriptTestSuite.class.isAssignableFrom(cls)) { view.showWarning(Strings.get("editor.wrong_class", new Object[] { cls.getName() })); } else { testClass = cls; Method suiteMethod = null; testSuite = null; try { suiteMethod = testClass.getMethod("suite", new Class[0]); testSuite = (ScriptTestSuite) suiteMethod.invoke(null); } catch (NoSuchMethodException nsm) { view.showError(nsm.toString()); testSuite = null; } catch (InvocationTargetException ite) { view.showError(ite.toString()); } catch (IllegalAccessException iae) { view.showError(iae.toString()); } } } catch (ClassNotFoundException e) { view.showWarning(Strings.get("editor.suite_not_found", new Object[] { suiteClassname })); } } if (testSuite == null) { view.getCurrentTestSuiteLabel().setText(Strings.get("NoSuite")); model = new DefaultComboBoxModel(); view.getTestScriptSelector().setModel(model); view.getTestScriptSelector().setEnabled(false); model.setSelectedItem(null); } else { view.getTestScriptSelector().setEnabled(true); view.getCurrentTestSuiteLabel().setText(testSuite.toString()); Object oldSelection = view.getTestScriptSelector().getSelectedItem(); ignoreComboBox = true; view.getTestScriptSelector().setEnabled(true); // Workaround for indexing bug on OSX view.getTestScriptSelector().setSelectedItem(null); List list = getScripts(); Object[] data = list.toArray(new Object[list.size()]); model = new DefaultComboBoxModel(data); view.getTestScriptSelector().setModel(model); // If the test suite didn't actually change, then keep the old // selection. if (getScripts().contains(oldSelection)) model.setSelectedItem(oldSelection); ignoreComboBox = false; } } /** Set the frame title to the default. */ private void updateTitle() { String title = Strings.get("ScriptEditor.title", new Object[] { testScript != null ? (" (" + testScript.getName() + ")") : "" }); view.setTitle(title); } /** Pull up a dialog with all available test suites. */ private void browseTests() { ClassLoader cl = getContextClassLoader(); String path = cl instanceof PathClassLoader ? ((PathClassLoader)cl).getClassPath() : null; if (path == null) path = System.getProperty("java.class.path"); TestSelector selector = new TestSelector(view, path); selector.setVisible(true); String className = selector.getSelectedItem(); if (className != null && checkSaveBeforeClose()) { terminate(); boolean none = className.equals(TestSelector.TEST_NONE); setTestSuite(none ? null : className, cl); setScript(0); if (none) { setStatus(Strings.get("editor.no_suite")); } } } /** @return true if it's ok to exit. */ protected boolean checkSaveBeforeClose() { // query save/cancel/exit if (testScript != null && (testScript.isDirty())) { int opt = view.showConfirmation(Strings.get("ScriptModified"), JOptionPane.YES_NO_CANCEL_OPTION); if (opt == JOptionPane.CANCEL_OPTION || opt == JOptionPane.CLOSED_OPTION) { return false; } else if (opt == JOptionPane.YES_OPTION) { saveScript(); } } return true; } private void closeScript() { if (!checkSaveBeforeClose()) return; setScript((Script)null); } /** Quit the application. */ void quitApplication() { if (!checkSaveBeforeClose()) return; Log.debug("editor quit" + (isRootEditor ? " (root)" : "")); dispose(); if (isRootEditor) { rootIsExiting = true; } else { AWTHierarchy.setDefault(oldHierarchy); } if (!editorConfiguration.isEmbedded()) { System.exit(0); } } /** Set the contents of the status message. */ public void setStatus(String msg) { setStatus(msg, null, INFO); } /** Set the contents of the status message to the given exception. */ private String getStackTrace(Throwable thr) { StringWriter writer = new StringWriter(); thr.printStackTrace(new PrintWriter(writer)); return writer.toString(); } /** Set the contents of the status message. */ public void setStatus(String msg, String extended, int type) { String text = Strings.get(statusFormat[type], new Object[] { msg }); view.setStatus(text, extended, statusColor[type]); // Save all messages to the log Log.log(text); } private void setStatusForStep(Step step) { if (step == null) { setStatus(""); return; } Throwable error = runner.getError(step); boolean fromScript = step == testScript; String msg = error != null ? error.toString() : null; String inStep = Strings.get("InStep", new Object[] { step }); String where = Strings.get("StepAt", new Object[] { Script.getFile(step), new Integer(Script.getLine(step)) }) + "\n"; // Don't need location info for these if (error instanceof AssertionFailedError && ((AssertionFailedError)error).getLine() != 0) { where = ""; } String extended = null; int type = INFO; if (error != null) { Log.log(error); boolean isFailure = (error instanceof AssertionFailedError); type = isFailure ? FAILURE : ERROR; extended = getStackTrace(error); // If we're not stopping on failure, don't mention it // specifically if (fromScript) { if ((isFailure && !runner.getStopOnFailure()) || (!isFailure && !runner.getStopOnError())) { msg = Strings.get(isFailure ? "ScriptFailure" : "ScriptError"); } else { // Otherwise ignore messages from the script itself return; } } else { extended = inStep + "\n" + where + extended; } } else if (fromScript) { msg = Strings.get("ScriptSuccess"); } // If nothing interesting happened, leave the status alone if (msg != null) setStatus(msg, extended, type); } /** Return a ComponentReference corresponding to the currently selected Component or ComponentReference, creating one if necessary. */ private String getSelectedComponentID() { String id = null; if (selectedReference != null) { id = selectedReference.getID(); } else if (selectedComponent != null) { ComponentReference ref = addComponent(selectedComponent); id = ref.getID(); setStatus(Strings.get("ComponentReference", new Object[] {id})); } return id; } /** Add either an Action or an Assert method provided by the given Tester. */ private void addTesterCall(Method method, ComponentTester tester, boolean wait, String docs) { boolean invert = invertAssertions; Class[] params = method.getParameterTypes(); String id = getSelectedComponentID(); Class componentClass = selectedComponent != null ? selectedComponent.getClass() : null; boolean componentArg0 = params.length > 0 && Component.class.isAssignableFrom(params[0]); String argString = view.showInputDialog(Strings.get("IdentifyArguments"), docs, componentArg0 ? id : null); if (argString == null) return; String[] args = ArgumentParser.parseArgumentList(argString); try { insertTesterCall(tester, method, componentClass, id, args, wait, invert); } catch (IllegalArgumentException iae) { Log.warn(iae); } catch (NoSuchReferenceException nsr) { Log.warn(nsr); } } /** Invoked after the user has selected a component and a property for * it. */ private void addPropertyMethodCall(Method method, Object value, boolean sample) { String id = getSelectedComponentID(); String methodName = method.getName(); String[] args = ComponentTester.class. isAssignableFrom(method.getDeclaringClass()) ? new String[] { id } : null; String targetClassName = method.getDeclaringClass().getName(); if (sample) { String varName = Strings.get("YourPropertyName"); Sample step = args == null ? new Sample(getResolverContext(), null, methodName, id, varName) : new Sample(getResolverContext(), null, targetClassName, methodName, args, varName); addStep(step); } else { String expectedValue = ArgumentParser.toString(value); Assert step = args == null ? new Assert(getResolverContext(), null, methodName, id, expectedValue, invertAssertions) : new Assert(getResolverContext(), null, targetClassName, methodName, args, expectedValue, invertAssertions); step.setWait(waitAssertions); addStep(step); } } /** Returns null if not found. */ public String getComponentID(Component comp) { ComponentReference ref = getComponentReference(comp); return ref != null ? ref.getID() : null; } /** Insert a new step at the current cursor location. */ void addStep(Step step) { Sequence parent = scriptTable.getCursorParent(); int index = scriptTable.getCursorParentIndex(); scriptModel.insertStep(parent, step, index); int row = scriptModel.getRowOf(step); scriptTable.setRowSelectionInterval(row, row); scriptTable.setCursorLocation(row + 1); setActionsEnabledState(); } /** Create a new script. */ private void newScript(boolean copyFixture) { if (!checkSaveBeforeClose()) return; File file = editorConfiguration.getNewFileTemplate(); if (file==null) { try { file = File.createTempFile(Script.UNTITLED_FILE, ".xml"); tempFile = file; } catch(IOException io) { JFileChooser chooser = getChooser(filter); File dir = getWorkingDirectory(); chooser.setCurrentDirectory(dir); chooser.setSelectedFile(new File(dir, Script.UNTITLED_FILE + ".xml")); if (chooser.showSaveDialog(view) != JFileChooser.APPROVE_OPTION) { return; } file = chooser.getSelectedFile(); } } if (!file.exists() || file.isFile()) { newScript(file, copyFixture); } else { // FIXME display an error } } /** Create a new script at the given filename, or open it if it already * exists. Optionally copies the fixture from the current script. */ void newScript(File file, boolean copyFixture) { if (!checkSaveBeforeClose()) return; try { boolean insert = file.createNewFile() || file.length() == 0; Script srcFixture = testScript; setScript(file.getAbsolutePath()); if (insert) { if (!copyFixture || srcFixture == null) { insertTerminate(); insertLaunch(); } else { copyFixture(srcFixture); } } setStatus(Strings.get(copyFixture ? "FixtureDuplicated" : "NewScriptCreated", new Object[] { file.getName() })); } catch(IOException io) { view.showError("File Error", io.toString()); } } /** Copy the fixture from the given script into the current one. */ public void copyFixture(Script src) { Step first = src.getStep(0); Step last = src.getStep(src.size() - 1); if (first instanceof UIContext) { setStatus(Strings.get("editor.adding_launch")); addStep(first); } if (src.size() > 1 && (src.getStep(1) instanceof Assert)) { Assert wait = (Assert)src.getStep(1); if (wait.isWait() && wait.getMethodName().equals("assertFrameShowing")) { setStatus(Strings.get("editor.adding_wait")); addStep(wait); } } if (last instanceof Terminate) { setStatus(Strings.get("editor.adding_terminate")); addStep(last); } } /** Launch the GUI under test. */ private void launch(boolean terminateRecorder) { if (testScript == null) { Log.warn("null testScript"); return; } ignoreStepEvents = true; invertAssertions = false; waitAssertions = false; view.setAssertOptions(waitAssertions, invertAssertions); // Clean up any extant windows if (terminateRecorder && recorder != null) { // Assume we want to keep the results stopRecording(false); } // FIXME time out and flag an error if the launch never returns // (even if threaded, it should return at some point) runSteps(testScript, true, "actions.run-launch", new Runnable() { public void run() { ignoreStepEvents = false; } }); } /** Do everything we can to dispose of the application under test. */ private void terminate() { if (recorder != null) { // Assume we want to keep the results stopRecording(false); } scriptTable.clearSelection(); try { runner.terminate(); } catch(Throwable e) { Log.warn(e); } } private void openScript() { if (!checkSaveBeforeClose()) return; JFileChooser chooser = getChooser(filter); chooser.setCurrentDirectory(getWorkingDirectory()); if (testScript != null) { chooser.setSelectedFile(testScript.getFile()); } if (chooser.showOpenDialog(view) == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); openScript(file); } if (!getScripts().contains(testScript) && model != null) { model.setSelectedItem(null); } } /** * Perform the actual open operation */ void openScript(File file) { try { setScript(file.getAbsolutePath()); } catch (InvalidScriptException ise) { view.showError(ise.getMessage()); } } private void stopOnFailureToggle() { if (testScript != null) { runner.setStopOnFailure(!runner.getStopOnFailure()); } } private void stopOnErrorToggle() { if (testScript != null) { runner.setStopOnError(!runner.getStopOnError()); } } private void forkedToggle() { if (testScript != null) { testScript.setForked(!testScript.isForked()); } setActionsEnabledState(); } private void getVMArgs() { String args = view.showInputDialog(Strings.get("GetVMArgs.title"), Strings.get("GetVMArgs.msg"), testScript.getVMArgs()); if (args != null) { testScript.setVMArgs(args); } } private void slowPlaybackToggle() { if (testScript != null) { testScript.setSlowPlayback(!testScript.isSlowPlayback()); } } private void awtModeToggle() { if (testScript != null) { testScript.setAWTMode(!testScript.isAWTMode()); } } private void runScript(Step stopAt) { if (testScript == null) { Log.warn("null testScript"); return; } Log.debug("Running test case " + testScript); stopStep = stopAt; // runSteps(testScript, false, "actions.run", new Runnable() { public void run() { // Nothing } }); } private void exportHierarchy() { JFileChooser chooser = getChooser(null); if (chooser.showSaveDialog(view) == JFileChooser.APPROVE_OPTION) { setStatus(Strings.get("actions.export-hierarchy.start")); final File file = chooser.getSelectedFile(); new Thread("Hierarchy Export") { public void run() { HierarchyWriter hw = new HierarchyWriter(hierarchy); try { FileWriter writer = new FileWriter(file); hw.writeHierarchy(writer); } catch(IOException io) { view.showError(Strings.get("SaveFailed.title"), io.toString()); } setStatus(Strings.get("actions.export-hierarchy.finish")); } }.start(); } } private void runSelectedSteps() { final List stepList = scriptTable.getSelectedSteps(); if (testScript == null || stepList == null || stepList.size() == 0 || !isAppLaunched()) { Log.warn("inconsistent program state"); return; } Sequence steps = new Sequence(getResolverContext(), null, stepList); final int row0 = scriptModel.getRowOf((Step)stepList.get(0)); final int row1 = scriptModel.getRowOf((Step)stepList.get(steps.size()-1)); runSteps(steps, false, "actions.run-selected", new Runnable() { public void run() { scriptTable.setRowSelectionInterval(row0, row1); } }); } /** * Run a set of test steps, making sure that the costello editor * is hidden and shown consistently. */ private void runSteps(final Step which, final boolean launch, final String messagePrefix, final Runnable onCompletion) { setStatus(Strings.get(messagePrefix+".start")); // Send the abbot window to the back // but only if we already have test windows showing otherwise // we might end up hiding upcoming app windows // boolean noWindows = countShowingWindows(null) == 0; if (!noWindows && !launch) { view.toBack(); } runStepsActual(which, launch, Strings.get(messagePrefix+".finish"), new Runnable() { public void run() { if (!launch) view.toFront(); onCompletion.run(); } }); } /** Invoke the given test script. All test execution is done on a dedicated * thread/thread group to avoid interfering with the event dispatch thread. */ private void runStepsActual(final Step which, final boolean launch, final String completionMessage, final Runnable onCompletion) { Log.debug("running " + which); setActionsEnabledState(); lastLaunchTime = System.currentTimeMillis(); //waiter = new SpinningDialWaitIndicator(view); //waiter.setText("Running..."); Runnable action = new LaunchAction(which, onCompletion, completionMessage, launch); String groupName = "AUT Thread Group for " + this + ":" + nonce++; if (appGroup == null) { appGroup = new ThreadGroup(groupName) { public void uncaughtException(Thread t, Throwable thrown) { if (!(thrown instanceof ExitException) && !(thrown instanceof ThreadDeath)) { Log.warn("Application thread exception not caught: " + t); Log.warn(thrown); } } }; } Thread launcher = new Thread(appGroup, action, "Script runner:" + nonce); launcher.setDaemon(true); view.getComponentBrowser().setEnabled(false); view.setEditor(null); isScriptRunning = true; launcher.start(); } /** Remove all contents from the current script. */ private void clearScript() { if (testScript == null) { Log.warn("null testScript"); return; } if (view.showConfirmation(Strings.get("editor.confirm.clear_script")) == JOptionPane.YES_OPTION) { scriptTable.clearSelection(); scriptTable.setCursorLocation(0); testScript.clear(); scriptModel.setScript(testScript); } } /** Delete the currently selected script/test case. */ private void deleteScript() { if (testScript == null) { Log.warn("null testScript"); return; } if (view.showConfirmation(Strings.get("editor.confirm.delete_script")) == JOptionPane.YES_OPTION) { File file = testScript.getFile(); int index = view.getTestScriptSelector().getSelectedIndex(); file.delete(); setTestSuite(testClass.getName(), testClass.getClassLoader()); setScript(index); } } /** Change the file backing the current script/test case, renaming * its file if <code>rename</code> is true, or saving to a new destination * if not. */ private void saveAsScript(boolean rename) { if (testScript == null) { Log.warn("null testScript"); return; } File oldFile = testScript.getFile(); JFileChooser chooser = getChooser(filter); chooser.setCurrentDirectory(getWorkingDirectory()); // FIXME make sure it falls within the test suite's script set? //chooser.setFileFilter(testScript.getFileFilter()); Log.debug("Showing save dialog"); if (chooser.showSaveDialog(view) == JFileChooser.APPROVE_OPTION) { Log.debug("Accepted"); File newFile = chooser.getSelectedFile(); if (rename) { if (!oldFile.renameTo(newFile)) { view.showError(Strings.get("editor.save.rename_failed", new Object[] { oldFile, newFile })); return; } } testScript.setFile(newFile); saveScript(); updateTitle(); if (testSuite != null && testSuite.accept(newFile)) { setTestSuite(testClass.getName(), testSuite.getClass().getClassLoader()); } else{ setTestSuite(null); } if (rename) { setStatus(Strings.get("ScriptRename", new Object[]{ newFile.getName() })); } else { setStatus(Strings.get("ScriptSaved", new Object[]{ newFile.getName() })); } // Combo box doesn't know that the script has changed its // toString view.getTestScriptSelector().repaint(); // Default script description reflects the path String text = testScript != null ? testScript.getDescription() : ""; view.getTestScriptDescription().setText(text); } } private boolean editingTempFile() { return testScript != null && testScript.getFile().equals(tempFile); } /** Save the current script/test case state to disk. */ private void saveScript() { if (testScript == null) { Log.warn("null testScript"); return; } // If the file is a temporary file, prompt for its real location if (editingTempFile()) { // This will recurse back into saveScript, so we're done Log.debug("Directory is temporary directory, need to rename"); saveAsScript(false); return; } File file = testScript.getFile(); File parent = file.getParentFile(); // Try to ensure that the file and parent are writable, these operations // might fail so we still might get a failure later on. // FileSystemHelper fileSystemHelper = editorConfiguration.getFileSystemHelper(); // boolean canWrite = (!file.exists() && fileSystemHelper.makeWritable(parent)) || (file.exists() && fileSystemHelper.makeWritable(file)); if (!canWrite) { String msg = Strings.get("NoFilePermission", new Object[] { file.toString() }); view.showError(Strings.get("SaveFailed.title"), msg); } else { try { setStatus(Strings.get("Saving", new Object[] { file })); saveNestedScripts(testScript); setStatus(Strings.get("Saved", new Object[] { file })); } catch (IOException exc) { view.showError(Strings.get("SaveFailed.title"), exc.toString()); } } } void saveNestedScripts(Sequence seq) throws IOException { if (seq instanceof Script) { Script script = (Script)seq; File file = script.getFile(); // Make sure that the file can be written to // if (!editorConfiguration.getFileSystemHelper().makeWritable(file)) { throw new IOException( Strings.get("NoFilePermission", new Object[] { file.toString() })); } // Save the script script.save(); } Iterator iter = seq.steps().iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); if (step instanceof Sequence) { saveNestedScripts((Sequence)step); } } } private EventNormalizer normalizer = new EventNormalizer(); /** Start listening to GUI events. */ private void startListening() { normalizer.startListening(new SingleThreadedEventListener() { protected void processEvent(AWTEvent event) { ScriptEditor.this.processEvent(event); } }, FIXTURE_EVENT_MASK); view.getComponentBrowser().setEnabled(true); } /** Return the number of windows that are showing. */ private int countShowingWindows(Window root) { int count = root != null && root.isShowing() ? 1 : 0; Iterator iter = root == null ? hierarchy.getRoots().iterator() : hierarchy.getComponents(root).iterator(); while (iter.hasNext()) { Component c = (Component)iter.next(); if (c instanceof Window) { count += countShowingWindows((Window)c); } } return count; } private int DONT_CARE = -1; private boolean isKeyPress(AWTEvent event, int code, int modifiers) { return event.getID() == KeyEvent.KEY_PRESSED && ((KeyEvent)event).getKeyCode() == code && (((KeyEvent)event).getModifiers() == modifiers || modifiers == DONT_CARE); } private boolean isKeyRelease(AWTEvent event, int code, int modifiers) { return event.getID() == KeyEvent.KEY_RELEASED && ((KeyEvent)event).getKeyCode() == code && (((KeyEvent)event).getModifiers() == modifiers || modifiers == DONT_CARE); } /** The editor does many things with the event stream, including logging * events, passing them off to the recorder, and updating its internal * state. */ private void processEvent(AWTEvent event) { Object src = event.getSource(); boolean isComponent = src instanceof Component; boolean isFiltered = isComponent && hierarchy.isFiltered((Component)src); // Keep a log of all events we see on non-filtered components if (isRootEditor) { if ((LOG_ALL_EVENTS || (!isFiltered && !ignoreEvents)) && Boolean.getBoolean("abbot.fixture.log_events")) { Log.log("ED: " + Robot.toString(event) + " (" + Thread.currentThread() + ")"); } } // Allow only component events and AWT menu actions if (!isComponent && !(src instanceof MenuComponent)) { Log.warn("Source not a Component or MenuComponent: " + event); return; } // If the script is running (or even being launched), the code // under test may do things that should really be done on the event // dispatch thread (initial component show and such). // If this is the case, defer mucking about with AWT until the code // under test has stabilized. if (isScriptRunning) { return; } if (!handleEditorTransient(event) && !handleRecordingControl(event) && !handleImageCaptureControl(event) && !handleComponentSelection(event) && recorder != null && recording && !isFiltered) { Log.debug("recorder process event"); try { recorder.record(event); } catch(RecordingFailedException e) { // Stop recording, but keep what we've got so far stopRecording(false); String msg = Strings.get("editor.recording.failure"); Throwable error = e.getCause() instanceof BugReport ? e.getCause() : new BugReport(msg, e.getCause()); Log.log("Recording failure: " + error.toString()); setStatus(error.getMessage(), error.toString(), ERROR); view.showWarning(msg); } } updateComponents(event); } private long lastTimeCtrlPressed = 0; private int lastTimeCtrlPressedModifiers = -1; private boolean handleComponentSelection(AWTEvent event) { Component ultimateComponent = state.getUltimateMouseComponent(); if (ultimateComponent != null && !hierarchy.isFiltered(ultimateComponent)) { // We are going to try and detect the double tap here // so that we can have a key that no-one else is going // to worry about boolean doubleTapCtrl = false; if (event instanceof KeyEvent && ((KeyEvent)event).getID() == KeyEvent.KEY_PRESSED && ((KeyEvent)event).getKeyCode() == KeyEvent.VK_CONTROL) { KeyEvent ke = (KeyEvent)event; long currentTimeCtrlPressed = ke.getWhen(); int currentModifiers = ke.getModifiers(); if ((currentTimeCtrlPressed-lastTimeCtrlPressed < 500) && currentModifiers == lastTimeCtrlPressedModifiers) { doubleTapCtrl = true; } lastTimeCtrlPressed = currentTimeCtrlPressed; lastTimeCtrlPressedModifiers = currentModifiers; } // This is for mouse based selections // boolean keySelect = doubleTapCtrl && isKeyPress(event, selectKey, KeyEvent.CTRL_MASK); boolean mouseSelect = event.getID() == MouseEvent.MOUSE_PRESSED && AWT.isTertiaryButton(((MouseEvent)event).getModifiers()); boolean makeReference = doubleTapCtrl && isKeyPress(event, selectKey, KeyEvent.CTRL_MASK | KeyEvent.ALT_MASK); if (keySelect || mouseSelect || makeReference) { Component selected = event instanceof MouseEvent ? InputState.getComponentAt((Component)event.getSource(), ((MouseEvent)event).getPoint()) : ultimateComponent; selectComponent(selected, makeReference); return true; } // We can also use the CTRL key to mean use the current focused component // rather than one the mouse is pointing at // boolean keySelectFocus = doubleTapCtrl && isKeyPress(event, selectKey, KeyEvent.SHIFT_MASK | KeyEvent.CTRL_MASK); boolean makeReferenceFocus = doubleTapCtrl && isKeyPress(event, selectKey, KeyEvent.SHIFT_MASK | KeyEvent.ALT_MASK | KeyEvent.CTRL_MASK); if (keySelectFocus || makeReferenceFocus) { FocusManager currentManager = FocusManager.getCurrentManager(); Component focusOwner = currentManager.getFocusOwner(); if (focusOwner!=null) { selectComponent(focusOwner, makeReferenceFocus); return true; } } } return false; } /** Update the state of components whose appearance depends on keyboard * state. * @param event */ private void updateComponents(AWTEvent event) { // Adjust the state of the assert/sample options if (isKeyPress(event, KC_INVERT, DONT_CARE)) { invertAssertions = true; view.setAssertOptions(waitAssertions, invertAssertions); } else if (isKeyRelease(event, KC_INVERT, DONT_CARE)) { invertAssertions = false; view.setAssertOptions(waitAssertions, invertAssertions); } else if (isKeyPress(event, KC_WAIT, DONT_CARE)) { waitAssertions = true; view.setAssertOptions(waitAssertions, invertAssertions); } else if (isKeyRelease(event, KC_WAIT, DONT_CARE)) { waitAssertions = false; view.setAssertOptions(waitAssertions, invertAssertions); } } private boolean handleEditorTransient(AWTEvent event) { // Make sure we filter any transient windows generated by the // script editor's frame. This avoids some of the hierarchy event // NPEs present on pre-1.4 VMs. if (event.getID() == WindowEvent.WINDOW_OPENED && ((WindowEvent)event).getWindow().getParent() == view) { hierarchy.setFiltered(((WindowEvent)event).getWindow(), true); view.getComponentBrowser().refresh(); return true; } return false; } private boolean handleImageCaptureControl(AWTEvent event) { Object src = event.getSource(); boolean isComponent = event.getSource() instanceof Component; boolean isFiltered = isComponent && hierarchy.isFiltered((Component)event.getSource()); Component ultimateComponent = state.getUltimateMouseComponent(); if (capturingImage) { // Cancel an image capture on ESC if (isKeyRelease(event, KeyEvent.VK_ESCAPE, 0)) { imageCaptureCancel(); } else if (captureComponent != null && isKeyPress(event, KeyEvent.VK_UP, 0) && !(src instanceof Window)) { imageCaptureSelect(true); } else if (captureComponent != null && isKeyPress(event, KeyEvent.VK_DOWN, 0) && !(src instanceof Window)) { imageCaptureSelect(false); } else if (isKeyRelease(event, captureImageKey, KeyEvent.SHIFT_MASK) && !isFiltered && testScript != null && ultimateComponent != null) { imageCapture(); } return true; } else if (isKeyRelease(event, captureImageKey, KeyEvent.SHIFT_MASK) && !isFiltered && testScript != null && ultimateComponent != null) { imageCaptureStart(ultimateComponent); return true; } return false; } private boolean handleRecordingControl(AWTEvent e) { boolean editorActivated = e.getID() == WindowEvent.WINDOW_ACTIVATED && e.getSource() == view; boolean appGone = isAppLaunched() && countShowingWindows(null) == 0 && (appGroup != null && appGroup.activeCount() == 0) && System.currentTimeMillis() - lastLaunchTime > 7500; if (appGone) Log.debug("Code under test no longer running"); boolean isComponent = e.getSource() instanceof Component; boolean isFiltered = isComponent && hierarchy.isFiltered((Component)e.getSource()); if (isKeyPress(e, captureKey, KeyEvent.SHIFT_MASK) || editorActivated || appGone) { Log.debug("stop recording trigger"); if (recording) { stopRecording(false); justStoppedRecording = true; if (capturingImage) imageCaptureCancel(); } else { justStoppedRecording = false; } return true; } // Start recording all events on alt+shift+F2 else if (isKeyRelease(e, captureKey, KeyEvent.SHIFT_MASK | KeyEvent.ALT_MASK)) { Log.debug("start recording trigger"); if (!isFiltered && !recording && !justStoppedRecording) { Log.debug("Start recording events (+motion)"); startRecording(recorders[1]); return true; } } // Start recording on shift+F2 else if (isKeyRelease(e, captureKey, KeyEvent.SHIFT_MASK)) { Log.debug("start recording trigger"); if (!isFiltered && !recording && !justStoppedRecording) { Log.debug("Start recording events"); startRecording(recorders[0]); return true; } } return false; } private void selectComponent(Component c, boolean makeReference) { Log.debug("Selected: " + Robot.toString(c)); // We usually want the combo box itself, not its LAF button if (c != null && (c.getParent() instanceof JComboBox)) c = c.getParent(); ComponentReference newReference = null; if (makeReference && getResolverContext() != null) { newReference = getResolverContext().addComponent(c); // FIXME tell the reference browser that the list of references // has changed. } view.getComponentBrowser().setSelectedComponent(c); // Select the new reference // if (newReference!=null) { view.getComponentBrowser().setSelectedReference(newReference); } } private void imageCaptureStart(Component ultimateComponent) { Log.debug("image capture locate"); recording = false; capturingImage = true; captureComponent = ultimateComponent; innermostCaptureComponent = captureComponent; if (captureComponent instanceof JComponent) { highlighter = new Highlighter((JComponent)captureComponent); } setStatus("Image capture target is " + Robot.toString(captureComponent)); } private void imageCaptureCancel() { Log.debug("stop image capture command"); highlighter.dispose(); setStatus("Image capture canceled"); captureComponent = innermostCaptureComponent = null; capturingImage = false; } private void imageCaptureSelect(boolean up) { if (up) { Log.debug("image capture move up"); Component parent = captureComponent.getParent(); if (parent instanceof JComponent && !(captureComponent instanceof JLayeredPane)) { Log.debug("Changing from " + Robot.toString(captureComponent) + " to " + Robot.toString(parent)); highlighter.dispose(); highlighter = new Highlighter((JComponent)parent); captureComponent = parent; } } else { Log.debug("image capture move down"); if (captureComponent instanceof Container) { Component[] subs = ((Container)captureComponent).getComponents(); for (int i=0;i < subs.length;i++) { if (SwingUtilities. isDescendingFrom(innermostCaptureComponent, subs[i]) && subs[i] instanceof JComponent) { Log.debug("Changing from " + Robot.toString(captureComponent) + " to " + Robot.toString(subs[i])); highlighter.dispose(); highlighter = new Highlighter((JComponent)subs[i]); captureComponent = subs[i]; break; } } } } setStatus("Image capture target is " + Robot.toString(captureComponent)); } private void imageCapture() { Log.debug("image capture snapshot"); setStatus("Capturing image..."); view.repaint(); highlighter.dispose(); // Must wait for the highlight to go away new Thread("wait for repaint") { public void run() { while (Toolkit.getDefaultToolkit().getSystemEventQueue(). peekEvent() != null) { try { sleep(10); } catch(InterruptedException e) { Thread.currentThread().interrupt();} } SwingUtilities.invokeLater(new Runnable() { public void run() { Step step = captureComponentImage(captureComponent); if (step != null) { // If we capture while recording, add it to the // recorder's stream. Otherwise, add it directly. if (recorder != null) { recorder.insertStep(step); } else { addStep(step); } } setStatus("Capturing image...done"); captureComponent = innermostCaptureComponent = null; capturingImage = false; } }); } }.start(); } /** Return a List of script filenames in the current suite. */ private List getScripts() { if (testScriptList == null) { testScriptList = getScripts(testSuite); } return testScriptList; } /** Return a List of script filenames contained in the given Test. */ private List getScripts(junit.framework.Test node) { ArrayList names = new ArrayList(); if (node == null) { } else if (node instanceof ScriptFixture) { names.add(((ScriptFixture)node).getName()); } else if (node instanceof junit.framework.TestSuite) { Enumeration e = ((junit.framework.TestSuite) node).tests(); while (e.hasMoreElements()) { junit.framework.Test test = (junit.framework.Test) e.nextElement(); names.addAll(getScripts(test)); } } else if (node instanceof junit.extensions.TestDecorator) { junit.framework.Test base = ((junit.extensions.TestDecorator)node).getTest(); names.addAll(getScripts(base)); } //Log.debug("Test scripts under " + node + ": " + names.size()); return names; } /** Returns the test case at the given index. */ private Script getScriptAt(int index) { List filenames = getScripts(); if (index >= filenames.size()) index = filenames.size() - 1; return new Script((String)filenames.get(index), hierarchy); } /** Create a new step and insert it at the cursor. */ private void insertTesterCall(ComponentTester tester, Method method, Class componentClass, String id, String[] argList, boolean wait, boolean invert) throws NoSuchReferenceException { String expectedResult = "true"; String methodName = method.getName(); if (methodName.startsWith("assert")) { Assert step; if (id == null) { // Built-in ComponentTester assertion step = new Assert(getResolverContext(), null, method.getDeclaringClass().getName(), methodName, argList, expectedResult, invert); } else { // Property method on a component ComponentReference ref = getComponentReference(id); if (ref == null) throw new NoSuchReferenceException(id); step = new Assert(getResolverContext(), null, methodName, argList, method.getDeclaringClass(), expectedResult, invert); } step.setWait(wait); addStep(step); } else if (methodName.startsWith("action")) { if (id == null) { // non-component action addStep(new Action(getResolverContext(), null, methodName, argList)); } else { ComponentReference ref = getComponentReference(id); if (ref == null) throw new NoSuchReferenceException(id); addStep(new Action(getResolverContext(), null, methodName, argList, method.getDeclaringClass())); } } else { // It's an tester-provided property method ComponentReference ref = getComponentReference(id); if (ref == null) throw new NoSuchReferenceException(id); addStep(new Assert(getResolverContext(), null, methodName, argList, tester.getTestedClass(componentClass), expectedResult, invert)); } } /** Update the UI to reflect the current state of the script's * execution. */ private void reflectScriptExecutionState(StepEvent ev) { Step step = ev.getStep(); String cmd = ev.getType(); Log.debug("Got step event " + ev); if (cmd.equals(StepEvent.STEP_START)) { if (step == stopStep) { runner.stop(); stopStep = null; } if (step != testScript) { final int row = scriptModel.getRowOf(step); if (row == -1) { // Step not visible, ignore } else { SwingUtilities.invokeLater(new Runnable() { public void run() { scriptTable.setRowSelectionInterval(row, row); scriptTable.setCursorLocation(row + 1); Rectangle rect = scriptTable. getCellRect(row, 0, true); scriptTable.scrollRectToVisible(rect); } }); } int i = testScript.indexOf(step); if (i != -1) { setStatus(Strings.get("RunningStep", new Object[] { String.valueOf(i+1), String.valueOf(testScript.size()) })); } } } else if (cmd.equals(StepEvent.STEP_FAILURE) || cmd.equals(StepEvent.STEP_ERROR)) { // Make sure the table updates its colors final int index = scriptModel.getRowOf(step); if (index != -1) { // FIX EDT voilation // AWT.invokeAndWait(new Runnable() { public void run() { scriptModel.fireTableRowsUpdated(index, index); } }); } setStatusForStep(step); } } Resolver getResolverContext() { return scriptTable.getScriptContext(); } /** From abbot.Resolver. */ public ComponentReference getComponentReference(String refid) { return getResolverContext() != null ? getResolverContext().getComponentReference(refid) : null; } /** From abbot.Resolver. */ public ComponentReference getComponentReference(Component comp) { return getResolverContext() != null ? getResolverContext().getComponentReference(comp) : null; } /** From abbot.Resolver. */ public void addComponentReference(ComponentReference ref) { if (getResolverContext() == null) { throw new RuntimeException(Strings.get("NoContext")); } getResolverContext().addComponentReference(ref); } /** From abbot.Resolver. */ public ComponentReference addComponent(Component comp) { if (getResolverContext() == null) { throw new RuntimeException(Strings.get("NoContext")); } return getResolverContext().addComponent(comp); } /** From abbot.Resolver. */ public Collection getComponentReferences() { if (getResolverContext() == null) { return new HashSet(); } return getResolverContext().getComponentReferences(); } /** From abbot.Resolver. */ public String getContext(Step step) { Resolver r = getResolverContext(); if (r != null) return r.getContext(step); return "unknown"; } /** From abbot.Resolver. */ public File getDirectory() { if (getResolverContext() == null) { return new File(System.getProperty("user.dir")); } return getResolverContext().getDirectory(); } /** From abbot.Resolver. */ public void setProperty(String name, Object value) { if (getResolverContext() != null) { getResolverContext().setProperty(name, value); } } /** From abbot.Resolver. */ public Object getProperty(String name) { if (getResolverContext() != null) { return getResolverContext().getProperty(name); } return null; } /** From abbot.Resolver. */ public ClassLoader getContextClassLoader() { if (getResolverContext() != null) { return getResolverContext().getContextClassLoader(); } return Thread.currentThread().getContextClassLoader(); } public Hierarchy getHierarchy() { return hierarchy; } public String toString() { return name; } private void stepSelectionChanged() { // ensure the stop step colorization gets cleared stopStep = null; setStepEditor(); setActionsEnabledState(); } // FIXME this is slow on OSX private void setStepEditor(Step step) { final StepEditor editor; ignoreEvents = true; if (step != null && (editor = StepEditor.getEditor(step)) != null) { view.setEditor(editor); // make sure the script model listens to changes from the // step editor editor.addStepChangeListener(new StepChangeListener() { public void stepChanged(Step step) { int row = scriptModel.getRowOf(step); if (row != -1) scriptModel.fireTableRowsUpdated(row, row); } }); } else { Log.debug("No editor available for '" + step + "'"); view.setEditor(null); } ignoreEvents = false; // Update the component browser if the context changes view.getComponentBrowser().setResolver(getResolverContext()); } private static String usage() { return ScriptEditor.class.getName() + " [suite classname]"; } private class LaunchAction implements Runnable { private final Step which; private final Runnable onCompletion; private final String completionMessage; private final boolean launch; private LaunchAction(Step which, Runnable onCompletion, String completionMessage, boolean launch) { this.which = which; this.onCompletion = onCompletion; this.completionMessage = completionMessage; this.launch = launch; } public void run() { try { if (launch) { if (which instanceof Script) { UIContext context = which instanceof UIContext ? (UIContext)which : ((Script)which).getUIContext(); if (context != null) context.launch(runner); } } else { runner.run(which); } if (completionMessage != null) setStatus(completionMessage); } catch(Throwable e) { // launch didn't work, get rid of it if (launch) terminate(); setStatus(e.getMessage(), getStackTrace(e), ERROR); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (waiter != null) { waiter.dispose(); waiter = null; } isScriptRunning = false; setActionsEnabledState(); if (onCompletion != null) { onCompletion.run(); } } }); } } /** * This class responds to changes in the script table's selection. */ private class ScriptTableSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent ev) { if (ev.getValueIsAdjusting() || isScriptRunning) return; stepSelectionChanged(); } } private void setStepEditor() { Step step = scriptTable.getSelectedRowCount() == 1 ? scriptModel.getStepAt(scriptTable.getSelectedRow()) : null; setStepEditor(step); setStatusForStep(step); setActionsEnabledState(); } /** * Handle the current test case/script selection from the current test * suite (if any). */ private class ScriptSelectorItemHandler implements ItemListener { public void itemStateChanged(ItemEvent e) { if (ItemEvent.SELECTED == e.getStateChange() && !ignoreComboBox) { if (checkSaveBeforeClose()) { setScript(new Script((String)e.getItem(), hierarchy)); } else { setScript(testScript); } } } } /** Provide a global editor context for anyone else that wants to display * an appropriate dialog message. */ // FIXME move to ScriptEditorFrame private static ScriptEditor editor = null; /** This action shows an input dialog to collect arguments for a given * method on a ComponentTester class and adds an assertion or action to * the current script. */ private class TesterMethodAction extends EditorAction implements Comparable { private Method method; private ComponentTester tester; private boolean wait; public TesterMethodAction(ComponentTester t, Method m, boolean w) { super(m.getName()); putValue(NAME, getName(m)); putValue(SMALL_ICON, getIcon(m)); wait = w; tester = t; method = m; } public int compareTo(Object o) { if (o instanceof TesterMethodAction) { return getName().compareTo(((TesterMethodAction)o).getName()); } return 0; } public void actionPerformed(ActionEvent ev) { addTesterCall(method, tester, wait, getArgumentsDescription()); } /** Return the human-readable menu name for the action. */ private String getName(Method m) { String name = m.getName(); // First try the resource bundle, then a system property String menu = Strings.get(name + ".menu", true); if (menu == null) { menu = System.getProperty(name + ".menu"); // Default to the stripped-down method name if (menu == null) { if (name.startsWith("action") || name.startsWith("assert")) menu = name.substring(6); else if (name.startsWith("is")) menu = name.substring(2); else if (name.startsWith("get")) menu = name.substring(3); else menu = name; // Break up words if we can menu = TextFormat.wordBreak(menu); } } return menu; } private Icon getIcon(Method m) { // This loads the icon if it's in a jar file. Doesn't seem to work // when loading from a raw class file in the classpath. Icon icon = null; String path = Strings.get(m.getName() + ".icon", true); if (path == null) { path = System.getProperty(m.getName() + ".icon"); } if (path != null) { URL url = ScriptEditor.class.getResource(path); if (url == null) { url = ScriptEditor.class.getResource("icons/" + path + ".gif"); } if (url != null) { icon = new ImageIcon(url); } } return icon; } /** Provide a description of required arguments for this method. */ private String getArgumentsDescription() { String name = method.getName(); String cname = Robot.simpleClassName(method.getDeclaringClass()); String args = Strings.get(cname + "." + name + ".args", true); if (args == null) { args = System.getProperty(cname + "." + name + ".args"); if (args == null) { args = method.toString(); } } return args; } public String getName() { return (String)getValue(NAME); } public int hashCode() { return getName().hashCode(); } public boolean equals(Object o) { return o instanceof TesterMethodAction && getName().equals(((TesterMethodAction)o).getName()); } } /** Security manager to prevent applications under test from exiting. * StepRunner provides one of these, but we need to do additional * checking in the context of the script editor. */ private class EditorSecurityManager extends NoExitSecurityManager { public void checkRead(String file) { // avoid annoying drive A: bug on w32 } /** We do additional checking to allow exit from the editor itself. */ public void checkExit(int status) { // Only allow exits by the root script editor if (!rootIsExiting) { super.checkExit(status); } } protected void exitCalled(int status) { terminate(); } } private void hideView() { hiding = true; view.setVisible(false); } private void showView() { hiding = false; view.setVisible(true); } private void disposeView() { // Close this frame; flag to the view to allow it to be disposed exiting = true; view.dispose(); } void dispose() { // Close any application under test terminate(); normalizer.stopListening(); hideView(); disposeView(); // Get rid of the security manager if (securityManager != null) { System.setSecurityManager(oldSecurityManager); securityManager = null; } } private static void bugCheck() { Window w = Costello.getSplashScreen(); if (w != null) { // Test for bugs that the user should know about String[] bugs = Bugs.bugCheck(Costello.getSplashScreen()); for (int i=0;i < bugs.length;i++) { String title = Strings.get("BugWarning.title"); String msg = TextFormat.dialog(bugs[i]); JOptionPane.showMessageDialog(w, msg, title, JOptionPane.WARNING_MESSAGE); } } } /** Launch the script editor, with an argument of either a test suite * class or a script filename. */ public static void main(String[] args) { showEditor(new EditorContext(args)); } /** * Launch the script editor, with an argument that represents a variety * of editor customizations. */ public static void showEditor(EditorContext ec) { try { String args[] = Log.init(ec.getArguments()); bugCheck(); if (args.length > 1) { if (ec.isEmbedded()) { JOptionPane.showMessageDialog( null, "Invalid arguments when invoking abbot"); return; } else { System.err.println("usage: " + usage()); System.exit(1); } } editor = new ScriptEditor(ec); // Load the requested script or suite String arg = args.length == 1 ? args[0] : null; if (arg != null && new File(arg).exists() && Script.isScript(new File(arg))) { editor.setTestSuite(null); editor.setScript(arg); } else { editor.setTestSuite(arg); editor.setScript(0); } // Make sure everything currently extant is // ignored in the test hierarchy. // Skip this step if the context provides a test hierarchy editor.hierarchy.ignoreExisting(); editor.view.pack(); editor.view.setVisible(true); // Don't start listening to events until we're done generating them // (the "show" above can trigger deadlocks when the framework is // under test). editor.startListening(); } catch(Throwable e) { if (editor != null) editor.dispose(); System.err.println("Unexpected exception trying to launch " + "the script editor"); e.printStackTrace(); System.exit(1); } } /** * @return Returns whether the code under test is currently launched. */ private boolean isAppLaunched() { // Override for embeded cases if (editorConfiguration.isEmbedded()){ return true; } if (testScript != null) { UIContext ctxt = testScript.getUIContext(); if (ctxt != null) return ctxt.isLaunched(); } return false; } private class RecordAllAction extends EditorAction { private Recorder recorder; public RecordAllAction(String actionName, Recorder rec, boolean extraModifier) { super(actionName); recorder = rec; int mask = InputEvent.SHIFT_MASK; if (extraModifier) mask |= InputEvent.ALT_MASK; putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(captureKey, mask)); } public void actionPerformed(ActionEvent ev) { Log.debug("Menu action: start recording due to " + ev.getActionCommand()); startRecording(recorder); } } private class EditorAboutAction extends EditorAction { public EditorAboutAction() { super(ACTION_EDITOR_ABOUT); } public void actionPerformed(ActionEvent e) { view.showAboutBox(); } } private class EditorEmailAction extends EditorAction { public EditorEmailAction() { super(ACTION_EDITOR_EMAIL); } public void actionPerformed(ActionEvent e) { new Thread("mailing-list") { public void run() { try { Launcher.mail(Strings.get("editor.email.list"), Strings.get("editor.email.subject"), Strings.get("editor.email.body", new Object[] { BugReport.getSystemInfo() })); } catch(IOException e) { view.showWarning(e.getMessage()); } } }.start(); } } private class EditorBugReportAction extends EditorAction { public EditorBugReportAction() { super(ACTION_EDITOR_BUGREPORT); } public void actionPerformed(ActionEvent e) { new Thread("bug-report") { public void run() { try { Launcher.open(Strings.get("editor.submit_bug")); } catch(IOException e) { view.showWarning(e.getMessage()); } } }.start(); } } private class EditorWebsiteAction extends EditorAction { public EditorWebsiteAction() { super(ACTION_EDITOR_WEBSITE); } public void actionPerformed(ActionEvent e) { new Thread("mailing-list") { public void run() { try { Launcher.open(Strings.get("editor.website")); } catch(IOException e) { view.showWarning(e.getMessage()); } } }.start(); } } private class EditorUserGuideAction extends EditorAction { public EditorUserGuideAction() { super(ACTION_EDITOR_USERGUIDE); } public void actionPerformed(ActionEvent e) { new Thread("mailing-list") { public void run() { try { Launcher.open(Strings.get("editor.userguide")); } catch(IOException e) { view.showWarning(e.getMessage()); } } }.start(); } } private class EditorQuitAction extends EditorAction { public EditorQuitAction() { super(ACTION_EDITOR_QUIT); } public void actionPerformed(ActionEvent e) { quitApplication(); } } private class ScriptNewAction extends EditorAction { public ScriptNewAction() { super(ACTION_SCRIPT_NEW); } public void actionPerformed(ActionEvent e) { newScript(false); } } private class ScriptDuplicateAction extends EditorAction { public ScriptDuplicateAction() { super(ACTION_SCRIPT_DUPLICATE); } public void actionPerformed(ActionEvent e) { newScript(true); } } private class ScriptOpenAction extends EditorAction { public ScriptOpenAction() { super(ACTION_SCRIPT_OPEN); } public void actionPerformed(ActionEvent e) { openScript(); } } private class ScriptClearAction extends EditorAction { public ScriptClearAction() { super(ACTION_SCRIPT_CLEAR); } public void actionPerformed(ActionEvent e) { clearScript(); } } private class ScriptDeleteAction extends EditorAction { public ScriptDeleteAction() { super(ACTION_SCRIPT_DELETE); } public void actionPerformed(ActionEvent e) { deleteScript(); } } private class ScriptSaveAction extends EditorAction { public ScriptSaveAction() { super(ACTION_SCRIPT_SAVE); } public void actionPerformed(ActionEvent e) { saveScript(); } } private class ScriptSaveAsAction extends EditorAction { public ScriptSaveAsAction() { super(ACTION_SCRIPT_SAVE_AS); } public void actionPerformed(ActionEvent e) { saveAsScript(false); } } private class ScriptRenameAction extends EditorAction { public ScriptRenameAction() { super(ACTION_SCRIPT_RENAME); } public void actionPerformed(ActionEvent e) { saveAsScript(true); } } private class ScriptCloseAction extends EditorAction { public ScriptCloseAction() { super(ACTION_SCRIPT_CLOSE); } public void actionPerformed(ActionEvent e) { closeScript(); } } private class StepCutAction extends EditorAction { public StepCutAction() { super(ACTION_STEP_CUT); } public void actionPerformed(ActionEvent e) { copySelection(true); } } private class StepCopyAction extends EditorAction { public StepCopyAction() { super(ACTION_STEP_COPY); } public void actionPerformed(ActionEvent e) { copySelection(false); } } private class StepPasteAction extends EditorAction { public StepPasteAction() { super(ACTION_STEP_PASTE); } public void actionPerformed(ActionEvent e) { pasteSteps(); } } private class StepDeleteAction extends EditorAction { public StepDeleteAction() { super(ACTION_STEP_DELETE); // Remove the extra modifiers putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0)); } public void actionPerformed(ActionEvent e) { deleteSelection(); } } private class StepMoveUpAction extends EditorAction { public StepMoveUpAction() { super(ACTION_STEP_MOVE_UP); } public void actionPerformed(ActionEvent e) { moveSelectionUp(); } } private class StepMoveDownAction extends EditorAction { public StepMoveDownAction() { super(ACTION_STEP_MOVE_DOWN); } public void actionPerformed(ActionEvent e) { moveSelectionDown(); } } private class StepGroupAction extends EditorAction { public StepGroupAction() { super(ACTION_STEP_GROUP); } public void actionPerformed(ActionEvent e) { groupSelection(); } } private class RunAction extends EditorAction { public RunAction() { super(ACTION_RUN); } public void actionPerformed(ActionEvent e) { runScript(null); } } private class RunSelectedAction extends EditorAction { public RunSelectedAction() { super(ACTION_RUN_SELECTED); } public void actionPerformed(ActionEvent e) { runSelectedSteps(); } } private class RunToAction extends EditorAction { public RunToAction() { super(ACTION_RUN_TO); } public void actionPerformed(ActionEvent e) { runScript(scriptTable.getSelectedStep()); } } private class ExportHierarchyAction extends EditorAction { public ExportHierarchyAction() { super(ACTION_EXPORT_HIERARCHY); } public void actionPerformed(ActionEvent e) { exportHierarchy(); } } private class SelectTestSuiteAction extends EditorAction { public SelectTestSuiteAction() { super(ACTION_SELECT_TESTSUITE); } public void actionPerformed(ActionEvent e) { browseTests(); } } private class RunLaunchAction extends EditorAction { public RunLaunchAction() { super(ACTION_RUN_LAUNCH); } public void actionPerformed(ActionEvent e) { launch(true); } } private class RunTerminateAction extends EditorAction { public RunTerminateAction() { super(ACTION_RUN_TERMINATE); } public void actionPerformed(ActionEvent e) { terminate(); } } private class InsertLaunchAction extends EditorAction { public InsertLaunchAction() { super(ACTION_INSERT_LAUNCH); } public void actionPerformed(ActionEvent e) { insertLaunch(); } } private class InsertFixtureAction extends EditorAction { public InsertFixtureAction() { super(ACTION_INSERT_FIXTURE); } public void actionPerformed(ActionEvent e) { insertScript(true); } } private class InsertAppletAction extends EditorAction { public InsertAppletAction() { super(ACTION_INSERT_APPLET); } public void actionPerformed(ActionEvent e) { insertApplet(); } } private class InsertTerminateAction extends EditorAction { public InsertTerminateAction() { super(ACTION_INSERT_TERMINATE); } public void actionPerformed(ActionEvent e) { insertTerminate(); } } private class InsertCallAction extends EditorAction { public InsertCallAction() { super(ACTION_INSERT_CALL); } public void actionPerformed(ActionEvent e) { insertCall(false); } } private class InsertSampleAction extends EditorAction { public InsertSampleAction() { super(ACTION_INSERT_SAMPLE); } public void actionPerformed(ActionEvent e) { insertCall(true); } } private class InsertSequenceAction extends EditorAction { public InsertSequenceAction() { super(ACTION_INSERT_SEQUENCE); } public void actionPerformed(ActionEvent e) { insertSequence(); } } private class InsertScriptAction extends EditorAction { public InsertScriptAction() { super(ACTION_INSERT_SCRIPT); } public void actionPerformed(ActionEvent e) { insertScript(false); } } private class InsertCommentAction extends EditorAction { public InsertCommentAction() { super(ACTION_INSERT_COMMENT); } public void actionPerformed(ActionEvent e) { insertComment(); } } private class InsertExpressionAction extends EditorAction { public InsertExpressionAction() { super(ACTION_INSERT_EXPRESSION); } public void actionPerformed(ActionEvent e) { insertExpression(); } } private class InsertAnnotationAction extends EditorAction { public InsertAnnotationAction() { super(ACTION_INSERT_ANNOTATION); } public void actionPerformed(ActionEvent e) { insertAnnotation(); } } private class GetVMArgsAction extends EditorAction { public GetVMArgsAction() { super(ACTION_GET_VMARGS); } public void actionPerformed(ActionEvent e) { getVMArgs(); } } private class SelectComponentAction extends EditorAction { public SelectComponentAction() { super(ACTION_SELECT_COMPONENT); // putValue(ACCELERATOR_KEY, // KeyStroke.getKeyStroke(selectKey, InputEvent.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { // This is really only for documentation purposes; there is // nothing to capture if the menu item can be activated, since // the editor has focus when the menu is selected. view.showWarning(Strings.get("actions.select-component.desc")); } } private class CaptureComponentAction extends EditorAction { public CaptureComponentAction() { super(ACTION_CAPTURE_COMPONENT); // putValue(ACCELERATOR_KEY, // KeyStroke.getKeyStroke(selectKey, // InputEvent.CTRL_MASK | InputEvent.ALT_MASK)); } public void actionPerformed(ActionEvent e) { // This is really only for documentation purposes; there is // nothing to capture if the menu item can be activated, since // the editor has focus when the menu is selected. view.showWarning(Strings.get("actions.capture-component.desc")); } } private class SelectFocusedComponentAction extends EditorAction { public SelectFocusedComponentAction() { super(ACTION_SELECT_FOCUSED_COMPONENT); // putValue(ACCELERATOR_KEY, // KeyStroke.getKeyStroke(selectKey, InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { // This is really only for documentation purposes; there is // nothing to capture if the menu item can be activated, since // the editor has focus when the menu is selected. view.showWarning(Strings.get("actions.select-focused-component.desc")); } } private class CaptureFocusedComponentAction extends EditorAction { public CaptureFocusedComponentAction() { super(ACTION_CAPTURE_FOCUSED_COMPONENT); // putValue(ACCELERATOR_KEY, // KeyStroke.getKeyStroke(selectKey, // InputEvent.SHIFT_MASK // |InputEvent.ALT_MASK // |InputEvent.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { // This is really only for documentation purposes; there is // nothing to capture if the menu item can be activated, since // the editor has focus when the menu is selected. view.showWarning(Strings.get("actions.capture-focused-component.desc")); } } private class CaptureImageAction extends EditorAction { public CaptureImageAction() { super(ACTION_CAPTURE_IMAGE); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(captureImageKey, InputEvent.SHIFT_MASK)); } public void actionPerformed(ActionEvent e) { // This is really only for documentation purposes; there is // nothing to capture if the menu item can be activated, since // the editor has focus when the menu is selected. view.showWarning(Strings.get("actions.capture-image.desc")); } } private class ToggleForkedAction extends EditorToggleAction { public ToggleForkedAction() { super(ACTION_TOGGLE_FORKED); } public void actionPerformed(ActionEvent e) { forkedToggle(); } } private class ToggleSlowPlaybackAction extends EditorToggleAction { public ToggleSlowPlaybackAction() { super(ACTION_TOGGLE_SLOW_PLAYBACK); } public void actionPerformed(ActionEvent e) { slowPlaybackToggle(); } } private class ToggleAWTModeAction extends EditorToggleAction { public ToggleAWTModeAction() { super(ACTION_TOGGLE_AWT_MODE); } public void actionPerformed(ActionEvent e) { awtModeToggle(); } } private class ToggleStopOnErrorAction extends EditorToggleAction { public ToggleStopOnErrorAction() { super(ACTION_TOGGLE_STOP_ON_ERROR); } public void actionPerformed(ActionEvent e) { stopOnErrorToggle(); } } private class ToggleStopOnFailureAction extends EditorToggleAction { public ToggleStopOnFailureAction() { super(ACTION_TOGGLE_STOP_ON_FAILURE); } public void actionPerformed(ActionEvent e) { stopOnFailureToggle(); } } private class EditorStepRunner extends StepRunner { /** We use a single runner througout the editor's lifetime, * so one saved UI context will suffice. */ public EditorStepRunner() { super(new AWTFixtureHelper()); } public Hierarchy getHierarchy() { return ScriptEditor.this.hierarchy; } public void terminate() { super.terminate(); setActionsEnabledState(); view.getComponentBrowser().refresh(); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ScriptEditorFrame.java
package abbot.editor; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import abbot.*; import abbot.editor.actions.*; import abbot.editor.widgets.*; import abbot.i18n.Strings; import javax.swing.text.JTextComponent; /** * Provides the primary frame for the Costello script editor. Maintains the * LAF used when first created, restoring it temporarily when displaying any * new components. * * FIXME needs major refactoring: * Export actions (via ActionMap) * Use generic menu setup provided by a special array of actions * * @author Kyle Girard, twall */ public class ScriptEditorFrame extends JFrame implements EditorConstants, abbot.Version { private static int STEP_EDITOR_MIN_HEIGHT = 75; private JLabel currentTestSuiteLabel; private JTextField testScriptDescription; private JButton testSuiteSelectionButton; private JButton runButton; private JComboBox testScriptSelector; // script on left, step editor on right private JSplitPane scriptSplit; // script split above, component browser below private JSplitPane scriptBrowserSplit; private ScriptTable scriptTable; private JTextComponent statusBar; private JDialog statusWindow; private boolean statusShown; private JTextArea statusText; private ComponentBrowser componentBrowser; private ActionMap actionMap; private Preferences prefs; private ImageIcon logo; private JMenu insertMenu; private int INSERT_BASE_COUNT; private JMenu captureMenu; private JMenu actionMenu; private TwoStateEditorMenu assertMenu; private TwoStateEditorMenu waitMenu; private JDialog aboutBox; private JPanel lastEditor; /** * Constructs a ScriptEditorFrame with a title and a scriptable */ public ScriptEditorFrame(String[][] menus, ActionMap actionMap, ActionListener listener, String title, ScriptTable scriptTable, Preferences preferences) { super(title); setName("ScriptEditor"); prefs = preferences; this.scriptTable = scriptTable; this.actionMap = actionMap; java.net.URL url = getClass().getResource("icons/abbot.gif"); logo = new ImageIcon(url); setIconImage(logo.getImage()); // Allow us to cancel out of a close. setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); initComponents(listener); setJMenuBar(createMenus(menus)); // LookAndFeelPreserver causes OSX to chew CPU cycles if (!Platform.isMacintosh() && !Boolean.getBoolean("costello.no_laf_restore")) { // Make sure we always use the same LAF, regardless of changes made by // the code under test. getRootPane().putClientProperty("LAFpreserver", new LookAndFeelPreserver(this)); } } private JMenuBar createMenus(String[][] menus) { JMenuBar menuBar = new JMenuBar(); for (int i=0;i < menus.length;i++) { String[] keys = menus[i]; if (keys.length > 0) { JMenu menu = new EditorMenu(keys[0]); for (int j=1;j < keys.length;j++) { String key = keys[j]; if (key == null) { menu.add(new JSeparator()); } else { Action action = actionMap.get(key); menu.add(createMenuItem(action)); } } if (i == menus.length-1) { menuBar.add(Box.createHorizontalGlue()); } menuBar.add(menu); } } return menuBar; } /** * Returns the componentBrowser. * @return ComponentBrowser */ public ComponentBrowser getComponentBrowser() { return componentBrowser; } /** * Sets the componentBrowser. * @param componentBrowser The componentBrowser to set */ public void setComponentBrowser(ComponentBrowser componentBrowser) { this.componentBrowser = componentBrowser; scriptBrowserSplit.setBottomComponent(componentBrowser); } /** * Returns the scriptTable. * @return ScriptTable */ public ScriptTable getScriptTable() { return scriptTable; } public String getStatus() { return statusBar.getText(); } /** Set the initial size based on saved prefs. */ private void setInitialBounds() { Log.debug("bounds=" + getBounds()); Dimension size = new Dimension(prefs.getIntegerProperty("width", getWidth()), prefs.getIntegerProperty("height", getHeight())); if (size.width < 200 || size.height < 200) { Log.warn("Size is rather small: " + size + ", using defaults"); } else { setSize(size); } Rectangle screen = getGraphicsConfiguration().getBounds(); int x = screen.x + (screen.width - getWidth()) / 2; int y = screen.y + (screen.height - getHeight()) / 2; Point where = new Point(prefs.getIntegerProperty("x", x), prefs.getIntegerProperty("y", y)); setLocation(where); int split1 = prefs.getIntegerProperty("split.script.stepeditor", -1); if (split1 < 10 || split1 > getHeight() - 10) split1 = -1; scriptSplit.setDividerLocation(split1); int split2 = prefs.getIntegerProperty("split.script.browser", -1); if (split2 < 10 || split2 > getWidth() - 10) split2 = -1; scriptBrowserSplit.setDividerLocation(split2); Log.debug("post=" + getBounds() + " split1=" + split1 + " split2=" + split2); } /** Save size and position information before hiding. */ boolean firstShow = true; /** @deprecated */ public void show() { if (firstShow) { firstShow = false; setInitialBounds(); } super.show(); } /** @deprecated */ public void hide() { if (isShowing()) { prefs.setProperty("x", String.valueOf(getX())); prefs.setProperty("y", String.valueOf(getY())); prefs.setProperty("width", String.valueOf(getWidth())); prefs.setProperty("height", String.valueOf(getHeight())); prefs.setProperty("split.script.stepeditor", String.valueOf(scriptSplit.getDividerLocation())); prefs.setProperty("split.script.browser", String.valueOf(scriptBrowserSplit.getDividerLocation())); prefs.save(); } super.hide(); } /** Set the text for the status window. The first argument is the short text and the second is additional optional text to be displayed in a larger dialog. */ public void setStatus(final String msg, final String extended, final Color color) { // Nothing is EDT safe with the more modern repaint managers // note invokeAction more like invokeLater abbot.util.AWT.invokeAction(new Runnable() { @Override public void run() { statusBar.setText(msg); statusText.setText(msg + (extended != null ? "\n" + extended : "")); if (!color.equals(statusBar.getForeground())) { statusBar.setForeground(color); statusText.setForeground(color); if (statusWindow.isShowing()) resizeStatusWindow(); } } }); } public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); Rectangle screen = getGraphicsConfiguration().getBounds(); pref.width = Math.min(pref.width, screen.width); pref.height = Math.min(pref.height, screen.height); return pref; } /** * Returns the testSuiteDescription. * @return JLabel */ public JLabel getCurrentTestSuiteLabel() { return currentTestSuiteLabel; } /** * Returns the testScriptSelector. * @return JComboBox */ public JComboBox getTestScriptSelector() { return testScriptSelector; } /** * Returns the testScriptDescription. * @return JTextField */ public JTextField getTestScriptDescription() { return testScriptDescription; } private void initComponents(ActionListener al) { JPanel pane = (JPanel)getContentPane(); JPanel top = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS)); top.setBorder(new EmptyBorder(4,4,4,4)); { JLabel suiteLabel = new JLabel(getString("AbbotSuite")) { public Dimension getMaximumSize() { return super.getPreferredSize(); } }; suiteLabel.setHorizontalAlignment(SwingConstants.RIGHT); currentTestSuiteLabel = new JLabel(getString("NoSuite")); currentTestSuiteLabel.setHorizontalAlignment(SwingConstants.LEFT); top.add(suiteLabel); top.add(Box.createHorizontalStrut(8)); top.add(currentTestSuiteLabel); top.add(Box.createHorizontalGlue()); top.add(Box.createHorizontalStrut(8)); Action action = actionMap.get(ScriptEditor.ACTION_SELECT_TESTSUITE); if (action != null) { testSuiteSelectionButton = new EditorButton(action); top.add(testSuiteSelectionButton); top.add(Box.createHorizontalStrut(8)); } action = actionMap.get(ScriptEditor.ACTION_RUN); if (action != null) { runButton = new EditorButton(action); top.add(runButton); } } JPanel center = new JPanel(new BorderLayout()); { testScriptSelector = new JComboBox(); JPanel scriptPane = new JPanel(new BorderLayout()); { testScriptDescription = new abbot.editor.widgets.TextField(""); testScriptDescription.addActionListener(al); String tip = TextFormat. tooltip(Strings.get("editor.script_description.tip")); testScriptDescription.setToolTipText(tip); JScrollPane scroll = new JScrollPane(scriptTable) { public Dimension getPreferredSize() { return new Dimension(250, 200); } public Dimension getMinimumSize() { return new Dimension(250, super.getMinimumSize().height); } }; scroll.setBorder(null); scroll.getViewport().setBackground(scriptTable.getBackground()); scriptSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // script gets extra space scriptSplit.setResizeWeight(1.0); scriptSplit.setDividerSize(4); scriptSplit.setBorder(null); scriptSplit.setLeftComponent(scroll); scriptBrowserSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // script gets extra space scriptBrowserSplit.setResizeWeight(1.0); scriptBrowserSplit.setDividerSize(4); scriptBrowserSplit.setBorder(null); scriptBrowserSplit.setTopComponent(scriptSplit); scriptPane.add(testScriptDescription, BorderLayout.NORTH); scriptPane.add(scriptBrowserSplit, BorderLayout.CENTER); } //center.add(buttons, BorderLayout.NORTH); center.add(testScriptSelector, BorderLayout.NORTH); center.add(scriptPane, BorderLayout.CENTER); } statusText = new JTextArea(""); statusText.setEditable(false); statusText.setBackground(getContentPane().getBackground()); statusText.setColumns(80); statusText.setLineWrap(true); statusText.setWrapStyleWord(true); statusWindow = createStatusWindow(); JPanel wp = (JPanel)statusWindow.getContentPane(); wp.add(new JScrollPane(statusText)); statusBar = new JTextField(getString("Initializing")); statusBar.setEditable(false); statusBar.setBackground(getContentPane().getBackground()); statusBar.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { boolean hasMoreText = !statusBar.getText().equals(statusText.getText()); boolean hasWideText = statusBar.getPreferredSize().width > statusBar.getSize().width; Log.debug("has more=" + hasMoreText + ", hasWide=" + hasWideText); if (hasMoreText || hasWideText) { resizeStatusWindow(); statusWindow.setVisible(true); resizeStatusWindow(); } } }); statusBar.setToolTipText(getString("Status.tip")); pane.setLayout(new BorderLayout()); pane.setBorder(new EmptyBorder(4,4,4,4)); pane.add(top, BorderLayout.NORTH); pane.add(center, BorderLayout.CENTER); pane.add(statusBar, BorderLayout.SOUTH); componentBrowser = null; } /** Create a checkbox or regular menu item as appropriate. */ private JMenuItem createMenuItem(javax.swing.Action action) { JMenuItem item = action instanceof EditorToggleAction ? (JMenuItem)new CustomCheckBoxMenuItem((EditorToggleAction)action) : (JMenuItem)new EditorMenuItem(action); return item; } public void showAboutBox() { if (aboutBox == null) { String title = Strings.get("actions.editor-about.title"); aboutBox = new JDialog(this, title, true); JPanel pane = (JPanel)aboutBox.getContentPane(); pane.setLayout(new BorderLayout()); pane.add(new LogoLabel(), BorderLayout.CENTER); JLabel label = new JLabel(VERSION); label.setHorizontalAlignment(SwingConstants.CENTER); pane.add(label, BorderLayout.SOUTH); pane.setBorder(new EmptyBorder(4,4,4,4)); aboutBox.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { aboutBox.setVisible(false); } }); aboutBox.pack(); aboutBox.setResizable(false); } // Center on the parent frame aboutBox.setLocation(getLocation().x + getWidth()/2 - aboutBox.getWidth()/2, getLocation().y + getHeight()/2 - aboutBox.getHeight()*2/3); aboutBox.setVisible(true); } public void setAssertOptions(boolean wait, boolean invert) { getComponentBrowser().updateAssertText(wait, invert); assertMenu.setSecondary(invert); waitMenu.setSecondary(invert); } private void populateMenu(JMenu menu, ArrayList actions) { Iterator iter = actions.iterator(); while (iter.hasNext()) { Action action = (Action)iter.next(); if (action == null) menu.add(new JSeparator()); else { JMenuItem mi = new EditorMenuItem(action); menu.add(mi); } } } /** Fill the menu with available actionXXX methods for the given class. */ public void populateInsertMenu(ArrayList actions) { if (INSERT_BASE_COUNT == 0) { INSERT_BASE_COUNT = insertMenu.getItemCount(); } else { while (insertMenu.getItemCount() > INSERT_BASE_COUNT) { insertMenu.remove(INSERT_BASE_COUNT); } } insertMenu.add(new JSeparator()); insertMenu.add(actionMenu = new EditorMenu("menus.insert-action")); insertMenu.add(assertMenu = new TwoStateEditorMenu("menus.insert-assert", "menus.insert-assert.neg")); insertMenu.add(waitMenu = new TwoStateEditorMenu("menus.insert-wait", "menus.insert-wait.neg")); Collections.sort(actions); populateMenu(actionMenu, actions); } /** Fill the menu with available assertXXX methods for the given class. */ public void populateAssertMenu(ArrayList actions) { assertMenu.removeAll(); populateMenu(assertMenu, actions); } /** Same as populateAssertMenu, but makes them waits instead. */ public void populateWaitMenu(ArrayList actions) { waitMenu.removeAll(); populateMenu(waitMenu, actions); } /** Create the list of recordable GUI actions. */ public void populateCaptureMenu(ArrayList actions) { captureMenu.removeAll(); populateMenu(captureMenu, actions); } public JPanel getEditor() { return lastEditor; } public void setEditor(final JPanel editor) { if (editor != null) { // preserve the divider location as the editor is changed JScrollPane scroll = new JScrollPane(editor); int loc = scriptSplit.getDividerLocation(); scroll.getViewport().setBackground(editor.getBackground()); Dimension minSize = editor.getMinimumSize(); minSize.height = STEP_EDITOR_MIN_HEIGHT; scroll.getViewport().setMinimumSize(minSize); scriptSplit.setRightComponent(scroll); // Preserve the divider location as the editor changes if (lastEditor != null) scriptSplit.setDividerLocation(loc); } else { scriptSplit.setRightComponent(null); } lastEditor = editor; } /** If a resource happens to be missing, use its key instead. */ private static String getString(String key) { String value = Strings.get(key); if (value == null) value = key; return value; } private void resizeStatusWindow() { statusWindow.setResizable(true); statusWindow.pack(); if (!statusShown) { Dimension size = statusWindow.getSize(); Point vwhere = getLocationOnScreen(); if (size.width < getWidth()) { size.width = getWidth(); statusWindow.setSize(size); } Point where = new Point(); where.x = vwhere.x + 10; where.y = vwhere.y + getHeight() - size.height; if (where.y < vwhere.y + 10) { where.y = vwhere.y + 10; } statusWindow.setLocation(where); statusShown = true; } statusWindow.setResizable(false); statusWindow.repaint(); } private JDialog createStatusWindow() { JDialog dialog = new JDialog(this, Strings.get("Status.title"), false) { public Dimension getMaximumSize() { Dimension max = super.getMaximumSize(); Rectangle screen = getGraphicsConfiguration().getBounds(); max.height = Math.min(Math.min(max.height, screen.height * 3 / 4), ScriptEditorFrame.this. getMaximumSize().height); max.width = Math.min(Math.min(max.width, screen.width * 3 / 4), ScriptEditorFrame.this. getMaximumSize().width); Log.debug("maximum size is " + max); return max; } public Dimension getMinimumSize() { Dimension min = super.getMinimumSize(); min.height = Math.max(150, min.height); Log.debug("minimum size is " + min); return min; } public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); pref.width = Math.min(pref.width, ScriptEditorFrame.this. getPreferredSize().width); Log.debug("preferred size is " + pref); return pref; } }; return dialog; } /** Display a confirmation dialog. */ public int showConfirmation(String msg) { return showConfirmation(msg, JOptionPane.YES_NO_OPTION); } /** Display a confirmation dialog. */ public int showConfirmation(String msg, int opts) { msg = TextFormat.dialog(msg); return JOptionPane.showConfirmDialog(this, msg, Strings.get("Confirm"), opts); } /** Global facility for obtaining a user input String. */ public String showInputDialog(String title, String msg, String initial) { msg = TextFormat.dialog(msg); return (String)JOptionPane.showInputDialog(this, msg, title, JOptionPane.PLAIN_MESSAGE, null, null, initial); } /** Global facility for message dialogs. */ public void showMessage(String title, String msg) { msg = TextFormat.dialog(msg); JOptionPane.showMessageDialog(this, msg); } /** Global facility for warning dialog. */ public void showWarning(String msg) { showWarning(Strings.get("Warning.title"), msg); } /** Global facility for warning dialog. */ public void showWarning(String title, String msg) { msg = TextFormat.dialog(msg); JOptionPane.showMessageDialog(this, msg, title, JOptionPane.WARNING_MESSAGE); } /** Global facility for error dialogs. */ public void showError(String msg) { showError(Strings.get("Error.title"), msg); } /** Global facility for error dialogs. */ public void showError(String title, String msg) { msg = TextFormat.dialog(msg); JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE); } private class EditorMenu extends JMenu { public EditorMenu(String key) { super(getString(key)); setName(key); // sort of a hack; update member variables when these special // menus get created. if (key.equals(MENU_INSERT)) { insertMenu = this; } else if (key.equals(MENU_CAPTURE)) { captureMenu = this; } setMnemonic(key); } protected void setMnemonic(String key) { Mnemonic mnemonic = Mnemonic.getMnemonic(Strings.get(key)); mnemonic.setMnemonic(this); // This can go away once the properties files have been // updated to use ampersands instead of VK keycodes if (mnemonic.keycode == KeyEvent.VK_UNDEFINED) { int code = EditorAction.getMnemonic(key); if (code != KeyEvent.VK_UNDEFINED) { setMnemonic(code); } } } } private class TwoStateEditorMenu extends EditorMenu { private String primary, secondary; public TwoStateEditorMenu(String primary, String secondary) { super(primary); this.primary = primary; this.secondary = secondary; } public void setSecondary(boolean state) { setMnemonic(state ? secondary : primary); } } private class EditorButton extends JButton { public EditorButton(Action action) { super(action); setName((String)action.getValue(EditorAction.NAME)); Integer i = (Integer)action.getValue(EditorAction.MNEMONIC_INDEX); if (i != null) Mnemonic.setDisplayedMnemonicIndex(this, i.intValue()); } } private class EditorMenuItem extends JMenuItem { public EditorMenuItem(Action action) { super(action); setName((String)action.getValue(EditorAction.NAME)); Integer i = (Integer)action.getValue(EditorAction.MNEMONIC_INDEX); if (i != null) Mnemonic.setDisplayedMnemonicIndex(this, i.intValue()); // prior to 1.4, the accelerator key is not automatically set setAccelerator((KeyStroke)action.getValue(Action.ACCELERATOR_KEY)); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ScriptModel.java
package abbot.editor; import java.io.IOException; import java.util.*; import javax.swing.table.AbstractTableModel; import org.jdom.Element; import abbot.Log; import abbot.script.*; /** Formats a Script for display in a table. Keeps track of * "open" nodes to create a tree-like display * NOTE: this is a brute-force implementation with no attempts at * optimization. But it's a very simple tree+table implementation. */ class ScriptModel extends AbstractTableModel { private HashSet openSequences = new HashSet(); private HashMap parents = new HashMap(); private Script script = null; private ArrayList rows = new ArrayList(); /** Encapsulate information we need to manipulate a row. Note that Entry * objects exist only for those steps which are "visible", i.e. children * of closed sequences have no Entry. */ private class Entry implements XMLifiable { public Step step; public Sequence parent; public int nestingDepth; public Entry(Step step, Sequence parent, int nestingDepth) { this.step = step; this.parent = parent; this.nestingDepth = nestingDepth; } /** What to display. */ public String toString() { String str = step.toString(); if ((step instanceof Script) && !step.getDescription().startsWith("Script")) { str += " - " + step.getDescription(); } return str; } /** What to edit. */ public String toEditableString() { return step.toEditableString(); } public Element toXML() { return step.toXML(); } } public ScriptModel() { this(null); } public ScriptModel(Script script) { setScript(script); } private void layout(boolean scanParents) { if (scanParents) mapParents(script); rows.clear(); if (script != null) { addSubRows(script, 0); } //Log.debug("Layout finished with " + rows.size() + " rows"); fireTableDataChanged(); } /** Remove the given step from the script. */ public synchronized void removeStep(Step step) { getParent(step).removeStep(step); openSequences.remove(step); layout(true); } /** Remove all the given steps. If any are not found, an exception is thrown before any changes are made. */ public synchronized void removeSteps(List steps) { Iterator iter = steps.iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); getParent(step); } iter = steps.iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); getParent(step).removeStep(step); openSequences.remove(step); } layout(true); } /** Insert the given step at the given index in its parent. */ public synchronized void insertStep(Sequence parent, Step step, int index) { parent.addStep(index, step); layout(true); } /** Insert the steps into the given sequence at the given index. */ public synchronized void insertSteps(Sequence parent, List steps, int index) { Iterator iter = steps.iterator(); while (iter.hasNext()) { parent.addStep(index++, (Step)iter.next()); } layout(true); } private Entry getEntry(int row) { if (row > rows.size() -1 || row < 0) throw new IllegalArgumentException("Row " + row + " out of bounds (" + rows.size() + " available)"); return (Entry)rows.get(row); } /** Returns -1 if the step is not found or not visible. */ public synchronized int getRowOf(Step step) { if (step != script) { //Log.debug("Checking " + rows.size() + " rows"); for (int i=0;i < rows.size();i++) { Entry entry = getEntry(i); if (entry.step.equals(step)) { return i; } Log.debug("Not in " + entry.step); } Log.debug("Step " + step + " not found in (maybe not visible)"); } return -1; } /** Return whether the given row is "open". */ public synchronized boolean isOpen(int row) { return openSequences.contains(getEntry(row).step); } public synchronized boolean isOpen(Step step) { return openSequences.contains(step); } /** Toggle the open state of the node, if it's a sequence. */ public synchronized void toggle(int row) { Step step = getEntry(row).step; if (step instanceof Sequence) { if (openSequences.contains(step)) openSequences.remove(step); else openSequences.add(step); layout(false); } } /** Set the script to display. Don't allow any model accesses until this method has completed. */ public synchronized void setScript(Script script) { //Log.debug("Setting table model script to " + script); this.script = script; openSequences.clear(); if (script != null) { openSequences.add(script); } layout(true); //Log.debug("Model has " + rows.size() + " rows"); } public synchronized int getRowCount() { if (script == null) return 0; return rows.size(); } public int getColumnCount() { return 1; } public synchronized Step getStepAt(int row) { return getEntry(row).step; } private void validate(int row, int col) { if (row < 0 || row > getRowCount()-1) throw new IllegalArgumentException("Invalid row " + row); if (col != 0) throw new IllegalArgumentException("Invalid column " + col); } /** Returns the step at the given row. */ public synchronized Object getValueAt(int row, int col) { validate(row, col); return getStepAt(row); } /** Assumes value is XML for a script step. */ // FIXME: I don't think this is used any longer now that editors are // available for all script steps. public synchronized void setValueAt(Object value, int row, int col) { validate(row, col); if (col == 0) { //Log.debug("Setting value at " + row + " to " + value); Entry entry = getEntry(row); if (entry.step instanceof Script) { // FIXME maybe use a file chooser instead? //Log.debug("Set script value to " + value); Script old = (Script)entry.step; Script step = new Script((String)value, script.getHierarchy()); step.setRelativeTo(old.getRelativeTo()); Sequence parent = entry.parent != null ? entry.parent : script; parent.setStep(parent.indexOf(old), step); layout(true); } else if (entry.step instanceof Sequence) { String desc = (String)value; if (!"".equals(desc) && !entry.step.getDescription().equals(desc)) { entry.step.setDescription(desc); } } else { try { Step step = Step.createStep(script, (String)value); Sequence parent = entry.parent != null ? entry.parent : script; parent.setStep(parent.indexOf(entry.step), step); layout(true); } catch(IllegalArgumentException e) { Log.warn(e); } catch(InvalidScriptException e) { // Edit rejected Log.warn(e); } catch(IOException e) { Log.warn(e); } } } } public String getColumnName(int col) { return ""; } public Class getColumnClass(int col) { if (col == 0) return Entry.class; return Object.class; } public Script getScript() { return script; } public synchronized int getNestingDepthAt(int row) { return row < 0 || row >= getRowCount() ? 0 : getEntry(row).nestingDepth; } public synchronized Script getScriptOf(int row) { validate(row, 0); Entry entry = getEntry(row); Sequence parent = entry.parent; while (!(parent instanceof Script)) parent = getParent(parent); return (Script)parent; } /** Return the parent sequence of the given step. */ public synchronized Sequence getParent(Step step) { Sequence seq = (Sequence)parents.get(step); if (seq == null) { throw new IllegalArgumentException("Step " + step + " not found in " + getScript()); } return seq; } /** Keep track of the parent for any given step to aid in editing. */ private void mapParents(Sequence seq) { if (seq == null) return; else if (seq == getScript()) { parents.clear(); } Iterator iter = seq.steps().iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); parents.put(step, seq); if (step instanceof Sequence) { mapParents((Sequence)step); } } } /** Add row entries corresponding to the contents of the given sequence * if it's toggled open. */ private void addSubRows(Sequence seq, int level) { if (openSequences.contains(seq)) { //Log.debug("Adding " + seq.steps().size() + " rows"); Iterator iter = seq.steps().iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); //Log.debug("Adding " + step); rows.add(new Entry(step, seq, level)); if (step instanceof Sequence) { addSubRows((Sequence)step, level + 1); } } } } /** Move the given steps and all between them to the new location. If the steps are being moved later in the same sequence, the index represents the target index <i>before</i> the move. */ public synchronized void moveSteps(Sequence parent, List steps, int index) { Step indexStep = index < parent.size() ? parent.getStep(index) : null; // Remove all, then insert all; otherwise moving steps down in a // sequence would fail Iterator iter = steps.iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); getParent(step).removeStep(step); } iter = steps.iterator(); index = indexStep != null ? parent.indexOf(indexStep) : parent.size(); while (iter.hasNext()) { Step step = (Step)iter.next(); parent.addStep(index++, step); } layout(true); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/ScriptTable.java
package abbot.editor; import java.awt.*; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.net.URL; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.table.*; import abbot.Log; import abbot.script.*; /** Provides a component to edit a test script. A cursor indicates where insertions will be positioned. Supports drag & drop within the component itself.<p> Actions supported:<br> move-rows-up<br> move-rows-down<br> toggle<br> */ public class ScriptTable extends JTable implements Autoscroll { private int cursorRow = 0; private Sequence cursorParent = null; private int cursorParentIndex = 0; private int cursorDepth = 0; private boolean isDragging = false; private DragSource dragSource; private DragSourceListener dragSourceListener; private static Icon openIcon; private static Icon closedIcon; private static int baseIndent; private static final int MARGIN = 4; static { URL url1 = ScriptTable.class.getResource("icons/triangle-dn.gif"); URL url2 = ScriptTable.class.getResource("icons/triangle-rt.gif"); if (url1 != null && url2 != null) { openIcon = new ImageIcon(url1); closedIcon = new ImageIcon(url2); } else { BasicTreeUI ui = (BasicTreeUI)(new JTree().getUI()); openIcon = ui.getExpandedIcon(); closedIcon = ui.getCollapsedIcon(); } baseIndent = openIcon.getIconWidth(); } private ScriptModel model; public ScriptTable() { this(new ScriptModel()); } public ScriptTable(ScriptModel scriptModel) { super(scriptModel); setSelectionModel(new SelectionModel()); model = scriptModel; TableCellRenderer cr = new ScriptTableCellRenderer(); setDefaultRenderer(Object.class, cr); Dimension spacing = getIntercellSpacing(); spacing.height = 2; setIntercellSpacing(spacing); initDragDrop(); // Detect clicks on the table in order to position the cursor // and expand entries. MouseListener ml = new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (me.getModifiers() != InputEvent.BUTTON1_MASK) return; if (me.getClickCount() == 2) { int row = rowAtPoint(me.getPoint()); Log.debug("Toggling row at " + row); toggle(row); } else { click(me.getPoint()); } } }; addMouseListener(ml); // Set up our custom actions; note that there are no default input // bindings ActionMap map = getActionMap(); map.put("move-rows-up", new AbstractAction() { public void actionPerformed(ActionEvent ev) { moveUp(); } }); map.put("move-rows-down", new AbstractAction() { public void actionPerformed(ActionEvent ev) { moveDown(); } }); map.put("toggle", new AbstractAction() { public void actionPerformed(ActionEvent ev) { int selRow = getSelectedRow(); if (selRow != -1) { toggle(selRow); } } }); } /** Toggle the open/closed state of a sequence. */ public void toggle(int row) { int[] rows = getSelectedRows(); if (rows.length > 0) { int anchor = getSelectionModel().getAnchorSelectionIndex(); Step first = model.getStepAt(rows[0]); int lastRow = rows[rows.length-1]; Step last = model.getStepAt(lastRow); Step afterLast = lastRow < getRowCount() - 1 ? model.getStepAt(lastRow + 1) : null; clearSelection(); model.toggle(row); int index0 = model.getRowOf(first); int index1 = model.getRowOf(last); // If the last step in the selection becomes hidden, change the // selection and the cursor position. if (index1 == -1) { index1 = afterLast == null ? row : model.getRowOf(afterLast) - 1; } if (anchor == index0) { Log.debug("Updating selection to " + index0 + " to " + index1); setRowSelectionInterval(index0, index1); } else { Log.debug("Updating selection to " + index1 + " to " + index0); setRowSelectionInterval(index1, index0); } } else { model.toggle(row); } } /** Return the bounding for the given cell. If the step at the given row * is contained within a sequence, the rect will be offset to the right. */ public Rectangle getCellRect(int row, int col, boolean includeBorder) { Rectangle rect = super.getCellRect(row, col, includeBorder); int indent = getIndentation(row); rect.x += indent; rect.width -= indent; return rect; } /** Return the number of pixels offset from the left edge of the table for the given row. */ public int getIndentation(int row) { return getDepthIndentation(model.getNestingDepthAt(row)); } /** Return the number of pixels offset from the left edge of the table for the given level of indentation. */ public int getDepthIndentation(int depth) { return baseIndent * depth; } private void click(Point pt) { int row = rowAtPoint(pt); if (row == -1) { clearSelection(); setCursorLocation(getRowCount()); } else { Rectangle rect = getCellRect(row, 0, true); // If the click is on the open/close icon, then toggle if ((model.getStepAt(row) instanceof Sequence) && pt.x >= rect.x && pt.x < rect.x + baseIndent && pt.y > rect.y + rect.height / MARGIN && pt.y < rect.y + rect.height * (MARGIN-1)/MARGIN) { toggle(row); } else { setCursorLocation(pt); } } } private void initDragDrop() { int action = DnDConstants.ACTION_MOVE; dragSource = DragSource.getDefaultDragSource(); DragGestureListener dgl = new DGListener(); dragSource.createDefaultDragGestureRecognizer(this, action, dgl); dragSourceListener = new DSListener(); DropTarget dt = new DropTarget(this, new DTListener()); dt.setDefaultActions(DnDConstants.ACTION_MOVE); } /** Determine what the background color for the given step should be. */ protected Color getStepColor(Step step, boolean selected) { return selected ? getSelectionBackground() : getBackground(); } /** Returns the script context of the currently selected row. */ public Script getScriptContext() { int row = getSelectedRow(); if (row == -1) return model.getScript(); return model.getScriptOf(row); } /** Returns the row number of the cursor. The number of cursor locations * is one greater than the number of table * entries. */ public int getCursorRow() { return cursorRow; } /** Returns the target parent of the current cursor location. */ public Sequence getCursorParent() { return cursorParent; } /** Returns the target index within the parent of the current cursor location. */ public int getCursorParentIndex() { return cursorParentIndex; } protected Rectangle getCursorBounds() { Insets insets = getInsets(); Dimension d = getSize(); Dimension m = getIntercellSpacing(); if (m.height == 0) m.height = 1; int width = d.width - insets.left - insets.right; int row = Math.min(cursorRow, getRowCount()-1); Rectangle cellRect = super.getCellRect(row, 0, false); int y = cellRect.y; if (cursorRow == getRowCount()) y += cellRect.height + m.height; int indent = getDepthIndentation(cursorDepth); return new Rectangle(indent, y - m.height, width - indent, m.height); } /** Given an arbitrary point within the table, return the nearest valid row for the cursor to be placed. */ private int getCursorRowAtPoint(Point where) { int row = rowAtPoint(where); if (row == -1) { row = where.y < 0 ? 0 : getRowCount(); } else { Rectangle rect = super.getCellRect(row, 0, true); if (where.getY() > rect.y + rect.height / 2) ++row; } // When dragging, don't put the cursor somewhere which would produce // no effect, or which would be illegal. if (isDragging) { int selStart = getSelectedRow(); int count = getSelectedRowCount(); if (row > selStart && row <= selStart + count) { if (row > count / 2 && selStart + count + 1 < getRowCount()) { row = selStart + count + 1; } else { row = selStart; } } } return row; } // FIXME sometimes the cursor row leads the selected row by two public void setCursorLocation(Point where) { int row = getCursorRowAtPoint(where); setCursorLocation(row, where.x); } /** Set the cursor location, using the given indentation to determine the * appropriate target parent sequence. */ private void setCursorLocation(int row, int indentation) { Rectangle oldRect = getCursorBounds(); Script script = model.getScript(); if (script == null) return; // Can't position the cursor after a terminate step if (script.hasTerminate() && row == getRowCount()) --row; else if (script.hasLaunch() && row == 0) ++row; cursorRow = row; Sequence parent = script; int index = row == getRowCount() ? parent.size() : parent.indexOf(model.getStepAt(row)); int depth = 0; if (row > 0) { // Place the cursor based on the previous step Step prev = model.getStepAt(row - 1); if (model.isOpen(prev)) { parent = (Sequence)prev; index = 0; // Depth is one greater than the depth of the parent depth = model.getNestingDepthAt(row - 1) + 1; } else { parent = model.getParent(prev); index = parent.indexOf(prev) + 1; depth = model.getNestingDepthAt(row - 1); } int indent = getDepthIndentation(depth); // Shift up the hierarchy until we reach the appropriate // indentation level. while (indent > indentation && parent != script) { Sequence nextUp = model.getParent(parent); index = nextUp.indexOf(parent) + 1; parent = nextUp; indent = getDepthIndentation(--depth); } } cursorParent = parent; cursorParentIndex = index; cursorDepth = depth; if (oldRect != null) repaint(oldRect); repaint(getCursorBounds()); } /** Set the cursor location to a reasonable target for the given row. */ public void setCursorLocation(int row) { setCursorLocation(row, 0); } protected void drawCursor(Graphics g, int row) { g.setColor(Color.green); ((Graphics2D)g).fill(getCursorBounds()); } /** We paint a cursor where insertions will take effect. */ public void paint(Graphics g) { super.paint(g); drawCursor(g, cursorRow == getRowCount() ? cursorRow-1 : cursorRow); } public void autoscroll(Point pt) { Rectangle bounds = getBounds(); Log.debug("autoscroll at " + pt + " bounds " + bounds); // Figure out which row we're on. int row = rowAtPoint(pt); if (row < 0) return; if (pt.y + bounds.y <= AUTOSCROLL_MARGIN) { if (row > 0) --row; } else { if (row < getRowCount() - 1) ++row; } scrollRectToVisible(getCellRect(row, 0, true)); } private static final int AUTOSCROLL_MARGIN = 12; public Insets getAutoscrollInsets() { // Calculate the insets for the JTree, not the viewport the tree is // in. Rectangle tree = getBounds(); Rectangle view = getParent().getBounds(); return new Insets(view.y - tree.y + AUTOSCROLL_MARGIN, view.x - tree.x + AUTOSCROLL_MARGIN, tree.height - view.height - view.y + tree.y + AUTOSCROLL_MARGIN, tree.width - view.width - view.x + tree.x + AUTOSCROLL_MARGIN); } private class ScriptTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean sel, boolean focus, int row, int col) { // We know that the default renderer for a JTable // is a subclass of JLabel JLabel renderer = (JLabel) super.getTableCellRendererComponent(table, value, sel, focus, row, col); Step step = model.getStepAt(row); Icon icon = null; if (step instanceof Sequence) { icon = model.isOpen(row) ? openIcon : closedIcon; } renderer.setIcon(icon); super.setBackground(getStepColor(step, sel)); setOpaque(true); return renderer; } } /** Return the first selected step. */ public Step getSelectedStep() { return getSelectedRowCount() > 0 ? model.getStepAt(getSelectedRow()) : null; } /** Return the set of selected steps, restricted to siblings of the first selected row. */ public List<Step> getSelectedSteps() { ArrayList<Step> list = new ArrayList<Step>(); int[] rows = getSelectedRows(); if (rows.length > 0) { Step step = model.getStepAt(rows[0]); Sequence parent = model.getParent(step); for (int i=0;i < rows.length;i++) { step = model.getStepAt(rows[i]); if (model.getParent(step) == parent) { list.add(step); } } } return list; } public boolean canMoveDown() { int[] rows = getSelectedRows(); int max = getRowCount() - (model.getScript().hasTerminate() ? 2 : 1); return rows[rows.length-1] < max; } public boolean canMoveUp() { int row = getSelectedRow(); int min = model.getScript().hasLaunch() ? 1 : 0; return row > min && !(model.getStepAt(row) instanceof Terminate); } /** Move the selected step(s) up. If the previous row is part of an open * sequence, move to the end of the sequence. Otherwise, switch places * with the step at the previous row. */ public void moveUp() { if (!canMoveUp()) return; List list = getSelectedSteps(); int leadRow = getSelectedRow(); Step lead = (Step)list.get(0); Sequence parent = model.getParent(lead); Step prev = model.getStepAt(leadRow - 1); int targetIndex = 0; // If the previous row to the selection is its parent, move previous // to the parent. if (parent.indexOf(lead) == 0) { Log.debug("Move out of sequence"); Sequence newParent = model.getParent(parent); targetIndex = newParent.indexOf(parent); parent = newParent; } // Is the previous step part of an open sequence? else if (model.isOpen(prev)) { Log.debug("Move to previous empty open sequence"); parent = (Sequence)prev; targetIndex = 0; } else if (model.getParent(prev) != parent) { Log.debug("Move to previous open sequence"); parent = model.getParent(prev); targetIndex = parent.indexOf(prev) + 1; } else { Log.debug("Move previous"); targetIndex = parent.indexOf(prev); } moveSelectedRows(parent, targetIndex); } /** Move the currently selected rows down one row. */ public void moveDown() { if (!canMoveDown()) { Log.warn("Unexpected move down state"); return; } List list = getSelectedSteps(); Step lead = (Step)list.get(0); Sequence leadParent = model.getParent(lead); int[] rows = getSelectedRows(); Step next = model.getStepAt(rows[rows.length-1] + 1); Sequence parent = model.getParent(next); // Default behavior moves after the next step int targetIndex = parent.indexOf(next) + 1; // If the next step after the selection is not a sibling, // make the group a sibling to its old parent if (leadParent != parent) { Sequence nextParent = model.getParent(leadParent); targetIndex = nextParent.indexOf(leadParent) + 1; parent = nextParent; } // If the next step is an open sequence, move into it else if (model.isOpen(next)) { parent = (Sequence)next; targetIndex = 0; } moveSelectedRows(parent, targetIndex); } /** Move the currently selected rows into the given parent at the given index. */ public void moveSelectedRows(Sequence parent, int index) { List steps = getSelectedSteps(); Step first = (Step)steps.get(0); if (parent.indexOf(first) == index) return; ListSelectionModel lsm = getSelectionModel(); boolean firstIsAnchor = getSelectedRow() == lsm.getAnchorSelectionIndex(); model.moveSteps(parent, steps, index); int firstRow = model.getRowOf(first); if (firstIsAnchor) lsm.setSelectionInterval(firstRow, firstRow + steps.size() - 1); else lsm.setSelectionInterval(firstRow + steps.size() - 1, firstRow); } private class DGListener implements DragGestureListener { public void dragGestureRecognized(DragGestureEvent e) { Point where = e.getDragOrigin(); int firstRow = getSelectedRow(); if (firstRow == -1) return; if ((e.getDragAction() & DnDConstants.ACTION_MOVE) != 0) { Transferable tf = getSelectedRowCount() > 1 ? new StepTransferable(getSelectedSteps()) : new StepTransferable(getSelectedStep()); try { Rectangle rect = getCellRect(firstRow, 0, true); int count = getSelectedRowCount(); rect.height *= count; Point offset = new Point(rect.x - where.x, rect.y - where.y); rect.x = rect.y = 0; BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.gray); --rect.width;--rect.height; graphics.draw(rect); graphics.dispose(); e.startDrag(DragSource.DefaultMoveDrop, image, offset, tf, dragSourceListener); isDragging = true; } catch(InvalidDnDOperationException exc) { Log.warn(exc); } } } } /** Listens to events coming from the source of the drag action. */ private class DSListener implements DragSourceListener { public void dragDropEnd(DragSourceDropEvent e) { Log.debug("drag drop end " + e.getDropAction()); // OSX bug makes this fail, so do it in the target listener instead if (!e.getDropSuccess()) { Log.debug("drop failed"); } } public void dragEnter(DragSourceDragEvent e) { Log.debug( "drag enter " + e.getDropAction()); DragSourceContext context = e.getDragSourceContext(); // intersection of the users selected action, and the source and // target actions int action = e.getDropAction(); if ((action & DnDConstants.ACTION_MOVE) != 0) { context.setCursor(DragSource.DefaultMoveDrop); } else { context.setCursor(DragSource.DefaultMoveNoDrop); } } public void dragOver(DragSourceDragEvent e) { } public void dragExit(DragSourceEvent e) { } public void dropActionChanged(DragSourceDragEvent e) { Log.debug("action changed " + e.getDropAction()); DragSourceContext context = e.getDragSourceContext(); context.setCursor(DragSource.DefaultMoveNoDrop); } } /** Listens to events coming from the target of the drag action. */ private class DTListener implements DropTargetListener { public void dragEnter(DropTargetDragEvent e) { if (!isDragAcceptable(e)) { e.rejectDrag(); } else { e.acceptDrag(DnDConstants.ACTION_MOVE); } } public void dragExit(DropTargetEvent e) { } public void dropActionChanged(DropTargetDragEvent e) { if (!isDragAcceptable(e)) { e.rejectDrag(); } else { e.acceptDrag(DnDConstants.ACTION_MOVE); } } public void dragOver(DropTargetDragEvent e) { Log.debug("drag over target " + e.getDropAction()); if (isDragAcceptable(e)) { e.acceptDrag(DnDConstants.ACTION_MOVE); Rectangle last = getCursorBounds(); setCursorLocation(e.getLocation()); Rectangle current = getCursorBounds(); paintImmediately(last); paintImmediately(current); } else { e.rejectDrag(); } } public void drop(DropTargetDropEvent e) { Log.debug("drop successful " + e.getDropAction()); if (!isDropAcceptable(e)) { e.rejectDrop(); } else { e.acceptDrop(DnDConstants.ACTION_MOVE); moveSelectedRows(cursorParent, cursorParentIndex); } e.dropComplete(true); } public boolean isDragAcceptable(DropTargetDragEvent e) { Log.debug("drag action is " + e.getDropAction()); return e.isDataFlavorSupported(StepTransferable.STEP_FLAVOR); } public boolean isDropAcceptable(DropTargetDropEvent e) { Log.debug("drop action is " + e.getDropAction()); return e.isDataFlavorSupported(StepTransferable.STEP_FLAVOR); } } /** If any sub-steps of a sequence are selected, they <i>all</i> must be selected. Also select all children when selecting an open sequence. */ private class SelectionModel extends DefaultListSelectionModel { public SelectionModel() { setSelectionMode(SINGLE_INTERVAL_SELECTION); } private void fixSelection() { if (getSelectedRowCount() == 0 || (getSelectedRowCount() == 1 && !model.isOpen(getSelectedRow()))) { return; } // Ensure the first selection has at maximum the minimum depth // Ensure the row after the last selection has at minimum the // minimum depth. int anchor = getAnchorSelectionIndex(); int lead = getLeadSelectionIndex(); int lo, hi; if (anchor < lead) { lo = anchor; hi = lead; } else { lo = lead; hi = anchor; } int loDepth = model.getNestingDepthAt(lo); int minDepth = loDepth; for (int i=lo+1;i <= hi;i++) { minDepth = Math.min(minDepth, model.getNestingDepthAt(i)); } if (loDepth > minDepth) { for (int i=lo-1;i >= 0;i--) { if (model.getNestingDepthAt(i) == minDepth) { Log.debug("Changing low end to " + i); if (lo == anchor) setSelectionInterval(lo = i, hi); else setSelectionInterval(hi, lo = i); break; } } } int last = hi + 1; while (last < getRowCount() && model.getNestingDepthAt(last) > minDepth) { ++last; } if (last > hi + 1) { Log.debug("Changing hi end to " + (last - 1)); if (hi == lead) setSelectionInterval(lo, last - 1); else setSelectionInterval(last - 1, lo); } } public void addSelectionInterval(int index0, int index1) { super.addSelectionInterval(index0, index1); fixSelection(); } public void removeSelectionInterval(int index0, int index1) { super.removeSelectionInterval(index0, index1); fixSelection(); } public void setAnchorSelectionIndex(int index) { super.setAnchorSelectionIndex(index); fixSelection(); } public void setLeadSelectionIndex(int index) { super.setLeadSelectionIndex(index); fixSelection(); } public void setSelectionInterval(int index0, int index1) { super.setSelectionInterval(index0, index1); fixSelection(); } public void insertIndexInterval(int index, int length, boolean bfore) { super.insertIndexInterval(index, length, bfore); fixSelection(); } public void removeIndexInterval(int idx0, int idx1) { super.removeIndexInterval(idx0, idx1); fixSelection(); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/StepTransferable.java
package abbot.editor; import java.awt.datatransfer.*; import java.util.*; import abbot.script.Step; public class StepTransferable implements Transferable { public static final DataFlavor STEP_FLAVOR = new DataFlavor("application/x-java-serialized-object;class=abbot.script.Step", "Abbot script step"); public static final DataFlavor STEP_LIST_FLAVOR = new DataFlavor("application/x-java-serialized-object;class=java.util.ArrayList", "List of Abbot script steps"); // A single step is available as itself or as a list private static final DataFlavor[] FLAVORS = { STEP_FLAVOR, STEP_LIST_FLAVOR, }; // Can't get a list as a single step private static final DataFlavor[] LIST_FLAVORS = { STEP_LIST_FLAVOR }; private static List FLAVOR_LIST = Arrays.asList(FLAVORS); private static List LIST_FLAVOR_LIST = Arrays.asList(LIST_FLAVORS); private Step step; private List steps; private List flavorList; private DataFlavor[] flavors; public StepTransferable(Step step) { this.step = step; this.steps = new ArrayList(); steps.add(step); flavorList = FLAVOR_LIST; flavors = FLAVORS; } public StepTransferable(List steps) { this.step = null; this.steps = steps; flavorList = LIST_FLAVOR_LIST; flavors = LIST_FLAVORS; } public DataFlavor[] getTransferDataFlavors() { return flavors; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavorList.contains(flavor); } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.isMimeTypeEqual(STEP_FLAVOR.getMimeType())) { if (step != null) return step; } else if (flavor.isMimeTypeEqual(STEP_LIST_FLAVOR.getMimeType())) { return steps; } throw new UnsupportedFlavorException(flavor); } public String toString() { return "Transferable " + (step != null ? step.toString() : "List of Steps"); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/editor/TestSelector.java
package abbot.editor; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.*; import junit.runner.*; import abbot.Log; import abbot.i18n.Strings; import abbot.util.PathClassLoader; import abbot.editor.widgets.ArrayEditor; import junit.extensions.abbot.ScriptTestCollector; import org.junit.runner.manipulation.Sorter; /** * A test class selector. A simple dialog to pick the name of a test suite. * Allows user to set the class path searched for script suite classes. * Thanks to JUnit for this code. */ public class TestSelector extends JDialog { /** If the selected item is this value, then use no test case class. */ public static final String TEST_NONE = "<None>"; private JList fList; private ArrayEditor pathEditor; private JButton fOk; private String fSelectedItem; /** * Renders TestFailures in a JList */ static class TestCellRenderer extends DefaultListCellRenderer { Icon fLeafIcon; Icon fSuiteIcon; public TestCellRenderer() { fLeafIcon= UIManager.getIcon("Tree.leafIcon"); fSuiteIcon= UIManager.getIcon("Tree.closedIcon"); } public Component getListCellRendererComponent( JList list, Object value, int modelIndex, boolean isSelected, boolean cellHasFocus) { Component c= super.getListCellRendererComponent(list, value, modelIndex, isSelected, cellHasFocus); String displayString= displayString((String)value); if (displayString.startsWith("AllTests")) setIcon(fSuiteIcon); else setIcon(fLeafIcon); setText(displayString); return c; } public static String displayString(String className) { int typeIndex= className.lastIndexOf('.'); if (typeIndex < 0) return className; return className.substring(typeIndex+1) + " - " + className.substring(0, typeIndex); } public static boolean matchesKey(String s, char ch) { return ch == Character.toUpperCase(s.charAt(typeIndex(s))); } private static int typeIndex(String s) { int typeIndex= s.lastIndexOf('.'); int i= 0; if (typeIndex > 0) i= typeIndex+1; return i; } } protected class DoubleClickListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { okSelected(); } } } protected class KeySelectListener extends KeyAdapter { public void keyTyped(KeyEvent e) { keySelectTestClass(e.getKeyChar()); } } public TestSelector(Frame parent, String classPath) { super(parent, true); setSize(350, 300); setResizable(false); setLocationRelativeTo(parent); setTitle(Strings.get("TestSelector.title")); fList= new JList(); fList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fList.setCellRenderer(new TestCellRenderer()); setCollector(classPath); JScrollPane listScroll = new JScrollPane(fList); String[] paths = PathClassLoader.convertPathToFilenames(classPath); pathEditor = new ArrayEditor(paths); JScrollPane scroll = new JScrollPane(pathEditor); JPanel path = new JPanel(new BorderLayout()); JLabel label = new JLabel(Strings.get("selector.classpath")); path.add(label, BorderLayout.NORTH); path.add(scroll, BorderLayout.CENTER); JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, listScroll, path); split.setBorder(null); JButton cancel = new JButton(UIManager.getString("OptionPane.cancelButtonText")); JButton none = new JButton(Strings.get("None")); JLabel desc = new JLabel(Strings.get("SelectTest")); fOk = new JButton(UIManager.getString("OptionPane.okButtonText")); fOk.setEnabled(false); getRootPane().setDefaultButton(fOk); defineLayout(desc, split, fOk, none, cancel); addListeners(fOk, none, cancel); } public void setCollector(String classPath) { // Ensure abbot.jar is always in the class path String fallback = System.getProperty("java.class.path"); if (fallback.indexOf("abbot.jar") == -1) { fallback = System.getProperty("abbot.class.path"); if (fallback==null || fallback.indexOf("abbot.jar") == -1) { Log.warn("abbot.jar not found in classpath"); } } classPath += System.getProperty("path.separator") + fallback; ClassLoader cl = new PathClassLoader(classPath); ScriptTestCollector collector = new ScriptTestCollector(cl); final Object[] list = createTestList(collector).toArray(); setTestList(list); } private void setTestList(final Object[] list) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { setTestList(list); } }); return; } try { getParent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); fList.setModel(new AbstractListModel() { public int getSize() { return list.length; } public Object getElementAt(int i) { return list[i]; } }); } finally { getParent().setCursor(Cursor.getDefaultCursor()); } } private void addListeners(final JButton ok, JButton none, JButton cancel) { cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); none.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fSelectedItem = TEST_NONE; dispose(); } }); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { okSelected(); } }); fList.addMouseListener(new DoubleClickListener()); fList.addKeyListener(new KeySelectListener()); fList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { checkEnableOK(e); } }); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); pathEditor.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] values = pathEditor.getValues(); final StringBuffer buf = new StringBuffer(); for (int i=0;i < values.length;i++) { buf.append(values[i]); buf.append(System.getProperty("path.separator")); } new Thread("Available classes loader") { public void run() { setCollector(buf.toString()); } }.start(); } }); } private void defineLayout(Component desc, Component center, Component ok, Component none, Component cancel) { getContentPane().setLayout(new BorderLayout()); ((JPanel)getContentPane()).setBorder(new EmptyBorder(4,4,4,4)); getContentPane().add(desc, BorderLayout.NORTH); getContentPane().add(center, BorderLayout.CENTER); JPanel buttons = new JPanel(new GridLayout(1, 0)); buttons.add(ok); buttons.add(none); buttons.add(cancel); getContentPane().add(buttons, BorderLayout.SOUTH); } public void checkEnableOK(ListSelectionEvent e) { fOk.setEnabled(fList.getSelectedIndex() != -1); } public void okSelected() { fSelectedItem= (String)fList.getSelectedValue(); dispose(); } public boolean isEmpty() { return fList.getModel().getSize() == 0; } public void keySelectTestClass(char ch) { ListModel model= fList.getModel(); if (!Character.isJavaIdentifierStart(ch)) return; for (int i= 0; i < model.getSize(); i++) { String s= (String)model.getElementAt(i); if (TestCellRenderer.matchesKey(s, Character.toUpperCase(ch))) { fList.setSelectedIndex(i); fList.ensureIndexIsVisible(i); return; } } Toolkit.getDefaultToolkit().beep(); } public String getSelectedItem() { return fSelectedItem; } private List createTestList(ScriptTestCollector collector) { Enumeration each= collector.collectTests(); Vector v= new Vector(); Vector displayVector= new Vector(); while(each.hasMoreElements()) { String s= (String)each.nextElement(); v.add(s); displayVector.add(TestCellRenderer.displayString(s)); } if (v.size() > 0) { Collections.sort(displayVector); } // Sorter.sortStrings(displayVector, 0, // displayVector.size()-1, // new ParallelSwapper(v)); return new ArrayList(v); } // private class ParallelSwapper implements Sorter.Swapper { // Vector fOther; // // ParallelSwapper(Vector other) { // fOther= other; // } // public void swap(Vector values, int left, int right) { // Object tmp= values.elementAt(left); // values.setElementAt(values.elementAt(right), left); // values.setElementAt(tmp, right); // Object tmp2= fOther.elementAt(left); // fOther.setElementAt(fOther.elementAt(right), left); // fOther.setElementAt(tmp2, right); // } // } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/Command.java
package abbot.editor.actions; public interface Command { public void execute(); }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/CommandHistory.java
package abbot.editor.actions; import java.util.ArrayList; /** Keep a history of commands, enabling potentially unlimited undo. This class is not synchronized.<p> Note that undo is itself an undoable action.<p> */ public class CommandHistory { private ArrayList list = new ArrayList(); /** The index of the most recent command "undone", or the size of the * history if the most recent action was "execute". */ private int cursor = 0; private Command get(int idx) { return ((Command)list.get(idx)); } public boolean canUndo() { return cursor > 0 && (get(cursor-1) instanceof Undoable); } public void undo() throws NoUndoException { if (canUndo()) { UndoableCommand undoable = (UndoableCommand)get(--cursor); undoable.undo(); // Add the undo to the end of the history list.add(new CommandComplement(undoable)); } else { // Reset the cursor to the end of the history cursor = list.size(); throw new NoUndoException(); } } /** Add the given command to the command history. */ public void add(Command command) { // If the command can't be undone, then clear the undo history if (!(command instanceof Undoable)) { clear(); } list.add(command); // Put the cursor at the end of the command history cursor = list.size(); } public void clear() { list.clear(); cursor = 0; } /** Simple wrapper around an existing command to swap the sense of its execute/undo. */ private class CommandComplement implements UndoableCommand { private UndoableCommand cmd; public CommandComplement(UndoableCommand orig) { cmd = orig; } public void execute() { cmd.undo(); } public void undo() { cmd.execute(); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/EditorAction.java
package abbot.editor.actions; import java.awt.event.*; import java.net.URL; import javax.swing.*; import abbot.Log; import abbot.Platform; import abbot.editor.*; import abbot.editor.widgets.*; import abbot.i18n.Strings; /** Encapsulate GUI attributes for an editor action. */ public abstract class EditorAction extends AbstractAction implements EditorConstants { /** Key to refer to the action in ActionMaps; <strong>not</strong> the same as the NAME property which is typically used for labels. */ public static final String ACTION_KEY = "action-key"; public static final String LARGE_ICON = "large-icon"; public static final String MNEMONIC_INDEX = "mnemonic-index"; public EditorAction(String actionKey) { super(actionKey); putValue(ACTION_KEY, actionKey); String key = ACTION_PREFIX + actionKey; Mnemonic mnemonic = Mnemonic.getMnemonic(Strings.get(key)); mnemonic.setMnemonic(this); if (mnemonic.index != -1) putValue(MNEMONIC_INDEX, new Integer(mnemonic.index)); // Check deprecated usage if (mnemonic.keycode == KeyEvent.VK_UNDEFINED) { int mn = getMnemonic(key); if (mn != KeyEvent.VK_UNDEFINED) putValue(MNEMONIC_KEY, new Integer(mn)); } String desc = Strings.get(key + ".desc", true); if (!"".equals(desc) && desc != null) { putValue(SHORT_DESCRIPTION, TextFormat.tooltip(desc)); } String longDesc = Strings.get(key + ".ldesc", true); if (!"".equals(longDesc) && longDesc != null) { putValue(LONG_DESCRIPTION, TextFormat.tooltip(longDesc)); } else { putValue(LONG_DESCRIPTION, getValue(SHORT_DESCRIPTION)); } String iconName = Strings.get(key + ".icon", true); if (!"".equals(iconName) && iconName != null) { putValue(SMALL_ICON, getIcon(iconName, 16)); putValue(LARGE_ICON, getIcon(iconName, 24)); } String accelerator = Strings.get(key + ".acc", true); if (!"".equals(accelerator) && accelerator != null) { accelerator = abbot.tester.AWTConstants.MENU_SHORTCUT_STRING + accelerator; try { // In case the accelerator given is garbage... putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(accelerator)); } catch(Exception e) { Log.warn("Bad accelerator '" + accelerator + "': " + e); } } } /** @deprecated Encode the mnemonic into the localized label instead. */ public static int getMnemonic(String key) { int code = KeyEvent.VK_UNDEFINED; // No (visible) mnemonics on OSX if (Platform.isOSX()) return code; String mnemonic = Strings.get(key + ".mn", true); if (!"".equals(mnemonic) && mnemonic != null) { if (!mnemonic.startsWith("VK_")) { mnemonic = "VK_" + mnemonic; } try { code = abbot.util.AWT.getKeyCode(mnemonic); } catch(IllegalArgumentException e) { String msg = Strings.get("editor.bad_mnemonic", new Object[] { mnemonic, key + ".mn", java.util.Locale.getDefault(), e.toString() }); // TODO: format this into an email message Log.warn(msg); } } return code; } /** * Returns the Icon associated with the given name from the available * resources. * * @param name Base name of the icon file e.g., help for help16.gif * @param size Size in pixels of the icon from the filename, or zero if * none, e.g. 16 for help16.gif or 0 for help.gif. * @return an ImageIcon or null if no corresponding icon resource is found. */ private ImageIcon getIcon(String name, int size) { String ABBOT_IMAGE_DIR = "/abbot/editor/icons/"; String base = ABBOT_IMAGE_DIR + name; URL url = getClass().getResource(base + ".gif"); if (url == null) { url = getClass().getResource(base + size + ".gif"); } ImageIcon icon = url != null ? new ImageIcon(url) : null; return icon; } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/EditorToggleAction.java
package abbot.editor.actions; import java.awt.event.*; /** Encapsulate GUI attributes for an editor action. */ public class EditorToggleAction extends EditorAction { public static final String STATE = "STATE"; public EditorToggleAction(String base) { super(base); setSelected(false); } // FIXME public void actionPerformed(ActionEvent ev) { setSelected(!isSelected()); //super.actionPerformed(ev); } public boolean isSelected() { return getValue(STATE) == Boolean.TRUE; } public void setSelected(boolean state) { putValue(STATE, state ? Boolean.TRUE : Boolean.FALSE); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/NoUndoException.java
package abbot.editor.actions; public class NoUndoException extends Exception { }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/Undoable.java
package abbot.editor.actions; public interface Undoable { public void undo(); }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/actions/UndoableCommand.java
package abbot.editor.actions; public interface UndoableCommand extends Command, Undoable { }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/ActionEditor.java
package abbot.editor.editors; import java.lang.reflect.Method; import java.util.ArrayList; import abbot.script.Action; /** Provide convenient editing of a Action step. */ public class ActionEditor extends CallEditor { public ActionEditor(Action action) { super(action); } // FIXME return the editor menu names instead protected String[] getMethodNames(Method[] methods) { ArrayList list = new ArrayList(); for (int i=0;i < methods.length;i++) { if (methods[i].getName().startsWith("action")) list.add(methods[i].getName()); } return (String[])list.toArray(new String[list.size()]); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/AnnotationEditor.java
package abbot.editor.editors; import java.awt.event.ActionEvent; import javax.swing.*; import abbot.*; import abbot.i18n.Strings; import abbot.script.Annotation; /** A Annotation only has its description available for editing. */ public class AnnotationEditor extends StepEditor { private Annotation annotation; private JTextArea text; private JButton reposition; private JCheckBox userDismiss; private JComboBox relative; public AnnotationEditor(Annotation annotation) { super(annotation); this.annotation = annotation; text = addTextArea(Strings.get("AnnotationText"), annotation.getText()); relative = addComponentSelector(Strings.get("AnchorComponent"), annotation.getRelativeTo(), annotation.getResolver(), true); reposition = addButton(Strings.get("Reposition")); userDismiss = addCheckBox(Strings.get("UserDismiss"), annotation.getUserDismiss()); } /** An editor component changed, respond to it by updating the step. */ public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == text) { annotation.setText(text.getText()); fireStepChanged(); } else if (src == relative) { annotation.setRelativeTo((String)relative.getSelectedItem()); fireStepChanged(); } else if (src == reposition) { try { annotation.showAnnotation(); fireStepChanged(); } catch(Exception e) { // FIXME show a dialog instead Log.warn(e); } } else if (src == userDismiss) { annotation.setUserDismiss(userDismiss.isSelected()); if (annotation.isShowing()) annotation.showAnnotation(); fireStepChanged(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/AppletviewerEditor.java
package abbot.editor.editors; import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; import abbot.i18n.Strings; import abbot.script.Appletviewer; import abbot.editor.widgets.ArrayEditor; /** Provide convenient editing of an applet launch step. */ public class AppletviewerEditor extends StepEditor { public static final String HELP_DESC = Strings.get("editor.applet.desc"); private Appletviewer applet; private JTextField code; private ArrayEditor params; private JTextField codebase; private JTextField archive; private JTextField width; private JTextField height; public AppletviewerEditor(Appletviewer applet) { super(applet); this.applet = applet; code = addTextField(Strings.get("editor.applet.code"), applet.getCode()); width = addTextField(Strings.get("editor.applet.width"), applet.getWidth()); height = addTextField(Strings.get("editor.applet.height"), applet.getHeight()); // For some reason, if we *don't* futz with the layout of // width/height, the pane never reconfigures properly for the array // editor. Component c; ArrayList list = new ArrayList(); while ((c = getComponent(getComponentCount()-1)) != code) { remove(c); list.add(c); } JPanel p = new JPanel(); //p.setBorder(new TitledBorder(Strings.get("editor.applet.size"))); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); for (int i=list.size()-1;i >= 0;i--) { p.add((Component)list.get(i)); if (i != 0) p.add(Box.createHorizontalStrut(MARGIN)); } add(p); params = addArrayEditor(Strings.get("editor.applet.params"), applet.getParamsAsArray()); codebase = addTextField(Strings.get("editor.applet.codebase"), applet.getCodebase()); archive = addTextField(Strings.get("editor.applet.archive"), applet.getArchive()); } public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == code) { applet.setCode(code.getText()); fireStepChanged(); } else if (src == params) { Object[] values = params.getValues(); Map map = new HashMap(); for (int i=0;i < values.length;i++) { String v = (String)values[i]; int eq = v.indexOf("="); if (eq != -1) { String key = v.substring(0, eq); String value = v.substring(eq+1); map.put(key, value); } } applet.setParams(map); fireStepChanged(); } else if (src == codebase) { String value = codebase.getText(); if ("".equals(value)) value = null; applet.setCodebase(value); fireStepChanged(); } else if (src == archive) { String value = archive.getText(); if ("".equals(value)) value = null; applet.setArchive(value); fireStepChanged(); } else if (src == width) { String value = width.getText(); if ("".equals(value)) value = null; try { Integer.parseInt(value); applet.setWidth(value); width.setForeground(DEFAULT_FOREGROUND); fireStepChanged(); } catch(NumberFormatException e) { width.setForeground(ERROR_FOREGROUND); } } else if (src == height) { String value = height.getText(); if ("".equals(value)) value = null; try { Integer.parseInt(value); applet.setHeight(value); width.setForeground(DEFAULT_FOREGROUND); fireStepChanged(); } catch(NumberFormatException e) { width.setForeground(ERROR_FOREGROUND); } } else { super.actionPerformed(ev); } // Remove the default placeholder description if (HELP_DESC.equals(applet.getDescription())) { applet.setDescription(null); fireStepChanged(); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/AssertEditor.java
package abbot.editor.editors; import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.tester.ComponentTester; /** Provide convenient editing of an Assert step. */ public class AssertEditor extends PropertyCallEditor { private Assert step; private JTextField value; private JCheckBox invert; private JCheckBox wait; private JTextField timeout = null; private JTextField interval = null; private int optionsIndex; public AssertEditor(Assert step) { super(step); this.step = step; value = addTextField(Strings.get("ExpectedResult"), step.getExpectedResult()); value.setName(TAG_VALUE); invert = addCheckBox(Strings.get("Invert"), step.isInverted()); invert.setName(TAG_INVERT); wait = addCheckBox(Strings.get("WaitToggle"), step.isWait()); wait.setName(TAG_WAIT); // Put wait/invert side by side Component c; while ((c = getComponent(getComponentCount()-1)) != value) { remove(c); } JPanel p = new JPanel(); p.setLayout(new GridLayout(0, 2)); p.add(invert); p.add(wait); add(p); optionsIndex = getComponentCount(); configureWaitOptionFields(); } /** Add in assertXXX methods to the list already generated. */ protected Collection getComponentTesterMethods(ComponentTester tester) { ArrayList list = new ArrayList(Arrays.asList(tester.getPropertyMethods())); list.addAll(Arrays.asList(tester.getAssertMethods())); list.addAll(Arrays.asList(tester.getComponentAssertMethods())); return list; } private void configureWaitOptionFields() { if (step.isWait()) { if (timeout == null) { timeout = addTextField(Strings.get("Timeout"), String.valueOf(step.getTimeout()), String.valueOf(Assert.DEFAULT_TIMEOUT)); timeout.setName(TAG_TIMEOUT); interval = addTextField(Strings.get("PollInterval"), String.valueOf(step.getPollInterval()), String.valueOf(Assert.DEFAULT_INTERVAL)); interval.setName(TAG_POLL_INTERVAL); } } else if (timeout != null) { // remove them while (getComponentCount() > optionsIndex) { remove(getComponentCount()-1); } timeout = interval = null; } revalidate(); repaint(); } protected boolean validateTimeout(String value) { try { step.setTimeout(Long.parseLong(value)); timeout.setForeground(DEFAULT_FOREGROUND); return true; } catch(NumberFormatException nfe) { timeout.setForeground(ERROR_FOREGROUND); } return false; } protected boolean validateInterval(String value) { try { step.setPollInterval(Long.parseLong(value)); interval.setForeground(DEFAULT_FOREGROUND); return true; } catch(NumberFormatException nfe) { interval.setForeground(ERROR_FOREGROUND); } return false; } public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == value) { step.setExpectedResult(value.getText()); fireStepChanged(); } else if (src == invert) { step.setInverted(!step.isInverted()); fireStepChanged(); } else if (src == wait) { step.setWait(!step.isWait()); configureWaitOptionFields(); fireStepChanged(); } else if (src == timeout) { String value = timeout.getText(); if (validateTimeout(value)) fireStepChanged(); } else if (src == interval) { String value = interval.getText(); if (validateInterval(value)) fireStepChanged(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/CallEditor.java
package abbot.editor.editors; import java.awt.event.*; import java.lang.reflect.*; import java.util.*; import javax.swing.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.editor.widgets.*; /** Provide an editor for call steps. @author Blake Christensen <[email protected]> @author [email protected] */ // TODO: add a help button for the selected method public class CallEditor extends StepEditor { private Call call; protected JTextField target; protected JComboBox method; protected ArrayEditor arguments; private String[] names = new String[0]; private boolean fieldChanging; public CallEditor(Call call) { super(call); this.call = call; target = addTextField(Strings.get("TargetClass"), call.getTargetClassName(), null, true); // Delay updates to increate perofmrance in large applications target.setName(TAG_CLASS); method = addComboBox(Strings.get("Method"), call.getMethodName(), getMethodNames()); method.setName(TAG_METHOD); arguments = addArrayEditor(Strings.get("Arguments"), call.getArguments()); arguments.setName(TAG_ARGS); } protected Call getCall() { return call; } /** Provide a list of method names corresponding to the current target class. Be careful overloading this method, since it is called from the Constructor. */ protected String[] getMethodNames() { try { Class cls = call.getTargetClass(); String[] names = getMethodNames(getMethods(cls, Modifier.PUBLIC)); Arrays.sort(names); return names; } // You get this in the case of an action where the value is not a Component or ComponentReference catch (IllegalArgumentException ae) { // TODO update the status bar with this information // we don't seem to have a reference to the ScriptEditor at this point to do this return new String[0]; } catch(ClassNotFoundException e) { return new String[0]; } } protected Class getTargetClass() throws ClassNotFoundException { try { return call.getTargetClass(); } catch(NoClassDefFoundError e) { throw new ClassNotFoundException(e.getMessage()); } } /** Return all public member and static methods. */ protected Map getMethods(Class cls, int mask) { HashMap processed = new HashMap(); while (cls != null) { Method[] methods = cls.getDeclaredMethods(); for (int i=0;i < methods.length;i++) { if ((methods[i].getModifiers() & mask) == mask) { processed.put(methods[i].getName(), methods[i]); } } cls = cls.getSuperclass(); } return processed; } /** Convert the given array of methods into an array of strings. Subclasses can do additional filtering here. */ protected String[] getMethodNames(Map methods) { return (String[])methods.keySet().toArray(new String[methods.size()]); } protected void validateTargetClass() { try { call.getTargetClass(); target.setForeground(DEFAULT_FOREGROUND); } catch(ClassNotFoundException e) { target.setForeground(ERROR_FOREGROUND); } catch(NoClassDefFoundError e) { target.setForeground(ERROR_FOREGROUND); } } protected void validateMethod() { try { call.getMethod(); method.setForeground(DEFAULT_FOREGROUND); } catch(IllegalArgumentException e) { method.setForeground(ERROR_FOREGROUND); } catch(NoSuchMethodException e) { method.setForeground(ERROR_FOREGROUND); } catch(ClassNotFoundException e) { method.setForeground(ERROR_FOREGROUND); } catch(NoClassDefFoundError e) { target.setForeground(ERROR_FOREGROUND); } } /** Sychronize the UI with the Call data. */ private void availableMethodsChanged() { fieldChanging = true; String[] newNames = getMethodNames(); // Ensure there's a selected item Object current = method.getSelectedItem(); if (current == null) current = call.getMethodName(); boolean changed = newNames.length != names.length; for (int i=0;i < newNames.length && !changed;i++) { changed = !newNames[i].equals(names[i]); } if (changed) { method.setModel(new DefaultComboBoxModel(newNames)); String name = call.getMethodName(); if (!name.equals(current)) method.setSelectedItem(name); names = newNames; } fieldChanging = false; } /** Sychronize the UI with the Call data. */ protected void targetClassChanged() { fieldChanging = true; target.setText(call.getTargetClassName()); fieldChanging = false; availableMethodsChanged(); validateTargetClass(); validateMethod(); } /** Sychronize the UI with the Call data. */ protected void methodChanged() { if (!call.getMethodName().equals(method.getSelectedItem())) method.setSelectedItem(call.getMethodName()); validateMethod(); } /** Sychronize the UI with the Call data. */ protected void argumentsChanged() { arguments.setValues(call.getArguments()); validateMethod(); } public void actionPerformed(ActionEvent ev) { if (fieldChanging) return; Object src = ev.getSource(); if (src == target) { String cname = target.getText().trim(); if (!cname.equals(call.getTargetClassName())) { call.setTargetClassName(cname); availableMethodsChanged(); validateTargetClass(); validateMethod(); fireStepChanged(); } } else if (src == method) { String name = (String)method.getSelectedItem(); if (!call.getMethodName().equals(name) && name != null) { call.setMethodName(name); validateMethod(); fireStepChanged(); } } else if (src == arguments) { // FIXME check method signature and do component field if the // first arg is a component, do popup from available refs // FIXME check arguments against method signature Object[] values = arguments.getValues(); String[] svalues = new String[values.length]; System.arraycopy(values, 0, svalues, 0, values.length); call.setArguments(svalues); validateMethod(); fireStepChanged(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/CommentEditor.java
package abbot.editor.editors; import java.awt.event.ActionEvent; import javax.swing.JTextArea; import abbot.script.Comment; /** A Comment only has its description available for editing. */ public class CommentEditor extends StepEditor { private Comment comment; private JTextArea description; public CommentEditor(Comment comment) { super(comment); this.comment = comment; // remove the default description remove(getComponentCount()-1); description = addTextArea(null, comment.getDescription()); } public void actionPerformed(ActionEvent ev) { if (ev.getSource() == description) { comment.setDescription(description.getText()); fireStepChanged(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/EventEditor.java
package abbot.editor.editors; import javax.swing.*; import abbot.Log; import abbot.script.*; /** Edit a raw AWTEvent. */ public class EventEditor extends StepEditor { private Event event; JComboBox type; JComboBox kind; JComboBox cref; private boolean ignoreCombo = false; JTextField xValue; JTextField yValue; JTextField keyCode; public EventEditor(Event event) { super(event); this.event = event; String idtype = event.getType(); String idkind = event.getKind(); String[] typeValues = { "Mouse Event", "Key Event" }; ignoreCombo = true; type = addComboBox("Type", typeValues[0], typeValues); type.setEnabled(false); type.setEditable(false); Resolver resolver = event.getResolver(); String refid = event.getComponentID(); if ("MouseEvent".equals(idtype)) { String[] kindValues = { "MOUSE_PRESSED", "MOUSE_RELEASED", "MOUSE_MOVED", "MOUSE_DRAGGED" }; kind = addComboBox("Kind", idkind, kindValues); kind.setEditable(false); kind.setEnabled(false); cref = addComponentSelector("On Component", refid, resolver, false); xValue = addTextField("X", event.getAttribute(XMLConstants.TAG_X)); yValue = addTextField("Y", event.getAttribute(XMLConstants.TAG_Y)); } else if ("KeyEvent".equals(idtype)) { type.setSelectedItem(typeValues[1]); String[] kindValues = { "KEY_PRESSED", "KEY_RELEASED" }; kind = addComboBox("Kind", idkind, kindValues); kind.setEditable(false); cref = addComponentSelector("On Component", refid, resolver, false); // FIXME make a popup w/all keycodes keyCode = addTextField("Key Code", event.getAttribute(XMLConstants.TAG_KEYCODE)); } else { Log.warn("Unhandled ID type: " + idtype); } ignoreCombo = false; } public void actionPerformed(java.awt.event.ActionEvent ev) { Object src = ev.getSource(); if (src == cref) { event.setComponentID((String)cref.getSelectedItem()); fireStepChanged(); } else if (src == kind) { if (!ignoreCombo) { event.setAttribute(XMLConstants.TAG_KIND, (String)kind.getSelectedItem()); fireStepChanged(); } } else if (src == xValue) { try { int value = Integer.parseInt(xValue.getText()); event.setAttribute(XMLConstants.TAG_X, String.valueOf(value)); xValue.setForeground(DEFAULT_FOREGROUND); fireStepChanged(); } catch(NumberFormatException nfe) { xValue.setForeground(ERROR_FOREGROUND); } } else if (src == yValue) { try { int value = Integer.parseInt(yValue.getText()); event.setAttribute(XMLConstants.TAG_Y, String.valueOf(value)); yValue.setForeground(DEFAULT_FOREGROUND); fireStepChanged(); } catch(NumberFormatException nfe) { yValue.setForeground(ERROR_FOREGROUND); } } else if (src == keyCode) { try { String codestr = keyCode.getText().trim(); event.setAttribute(XMLConstants.TAG_KEYCODE, codestr); keyCode.setForeground(DEFAULT_FOREGROUND); fireStepChanged(); } catch(IllegalArgumentException iae) { keyCode.setForeground(ERROR_FOREGROUND); } } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/ExpressionEditor.java
package abbot.editor.editors; import java.awt.*; import java.awt.event.*; import javax.swing.JTextArea; import javax.swing.JButton; import abbot.i18n.Strings; import abbot.script.Expression; import javax.script.ScriptException; /** A Expression only has its description available for editing. */ public class ExpressionEditor extends StepEditor { private Expression step; private JTextArea expr; private JButton run; private Color DEFAULT_FG; private JTextArea status; public ExpressionEditor(Expression step) { super(step); this.step = step; remove(getComponentCount()-1); expr = addTextArea(null, step.getExpression()); expr.setName("expression.text"); expr.setColumns(80); expr.setToolTipText(Strings.get("expression.text.tip")); expr.setLineWrap(false); run = addButton(Strings.get("expression.eval")); run.setToolTipText(Strings.get("expression.eval.tip")); DEFAULT_FG = expr.getForeground(); expr.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER && (e.getModifiers() & InputEvent.SHIFT_MASK) != 0) { run.doClick(); } } }); // TODO: properly format for readability status = new JTextArea(); status.setBorder(null); status.setForeground(Color.red); status.setBackground(getBackground()); status.setLineWrap(true); status.setEditable(false); add(status); } public Dimension getPreferredSize() { Insets insets = getInsets(); Dimension size = super.getPreferredSize(); size.width = expr.getPreferredSize().width; if (insets != null) { size.width += insets.left + insets.right; } return size; } public void actionPerformed(ActionEvent ev) { if (ev.getSource() == expr) { expr.setForeground(DEFAULT_FG); expr.setToolTipText(Strings.get("expression.text.tip")); step.setExpression(expr.getText()); status.setText(""); fireStepChanged(); } else if (ev.getSource() == run) { expr.setForeground(DEFAULT_FG); expr.setToolTipText(Strings.get("expression.text.tip")); status.setText(""); new Thread("expression runner") { public void run() { try { step.run(); } catch(Throwable e) { if (e instanceof ScriptException) expr.setForeground(Color.red); status.setText(e.getMessage()); } fireStepChanged(); } }.start(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/FixtureEditor.java
/* * Copyright (c) 2005 Oculus Technologies Corporation, All Rights Reserved */ package abbot.editor.editors; import abbot.script.*; /** Simplified version of {@link ScriptEditor}. * @author twall * */ public class FixtureEditor extends ScriptEditor { /** * @param script */ public FixtureEditor(Fixture script) { super(script); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/ImportButton.java
/** * Name........: ImportButton * Description.: Button allowing to import an Eclipse project configuration. * Author......: Daniel Kasmeroglu * E-Mail......: [email protected] */ package abbot.editor.editors; import net.sf.ant4eclipse.tools.jdt.*; import net.sf.ant4eclipse.model.jdt.launch.*; import net.sf.ant4eclipse.model.platform.resource.*; import abbot.script.*; import abbot.i18n.*; import javax.swing.*; import java.awt.event.*; import java.io.*; /** * Button allowing to import an Eclipse project configuration. */ public class ImportButton extends JButton implements ActionListener { private JFileChooser launchfilechooser; private JFileChooser workspacefilechooser; private LaunchFileFilter launchfilefilter; private WorkspaceFileFilter workspacefilefilter; private LaunchEditor editor; private Launch launch; /** * Initialises this button which will be placed on the supplied editor. * * @param launcheditor * The editor which receives this button. * @param launchstep * The step that will be edited. */ public ImportButton(LaunchEditor launcheditor, Launch launchstep) { super(Strings.get("eclipse.import")); editor = launcheditor; launch = launchstep; launchfilechooser = new JFileChooser(); workspacefilechooser = new JFileChooser(); launchfilefilter = new LaunchFileFilter(); launchfilechooser.setFileFilter(launchfilefilter); workspacefilechooser.setFileFilter(workspacefilefilter); workspacefilechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); addActionListener(this); } /** * {@inheritDoc} */ public void actionPerformed( ActionEvent evt ) { if (importEclipse()) { editor.fireStepChanged(); } } /** * Enforces the user to select the workspace. * * @param projectname * The name of the project used within the launch configuration. * @return The location of the workspace or null if none has been selected. */ private File selectWorkspace(String projectname) { workspacefilefilter.setProjectName(projectname); File result = null; int option = workspacefilechooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { result = workspacefilechooser.getSelectedFile(); } return (result); } /** * Locates the workspace directory which may be parental to the Java launch * configuration. * * @param file * The directory to start from. * @return The location of the workspace directory or null. */ private File locateWorkspace(File file) { if (file == null) { return (null); } File metadata = new File(file, ".metadata"); if (metadata.isDirectory()) { return (file); } return (locateWorkspace(file.getParentFile())); } /** * Runs the import process of an Eclipse launch configuration. * * @return true <=> A launch configuration could be imported. */ private boolean importEclipse() { boolean result = false; // load the launch configuration first JavaApplicationLaunchConfiguration launchconfig = selectLaunchConfiguration(); if (launchconfig != null) { // try to locate the workspace (potentially a parental directory) File workspacedir = locateWorkspace(launchconfig.getLaunchFile().getParentFile()); if (workspacedir == null) { // the user must select the workspace directory workspacedir = selectWorkspace(launchconfig.getProjectName()); } if (workspacedir != null) { // try to resolve the classpath Workspace workspace = Workspace.getWorkspace(workspacedir); String cp = loadClasspath(workspace, launchconfig); File projectlocation = workspace.getChild(launchconfig .getProjectName()); String progargs = launchconfig.getProgramArguments(); if (progargs == null) { progargs = ""; } String[] splitted = progargs.split(" "); StringBuffer argsbuffer = new StringBuffer(); for (int i = 0; i < splitted.length; i++) { if (i > 0) { argsbuffer.append(" "); } File file = new File(projectlocation, splitted[i]); if (file.exists()) { splitted[i] = "[" + file.getAbsolutePath() + "]"; } else { splitted[i] = "[" + splitted[i] + "]"; } argsbuffer.append(splitted[i]); } // modify the step launch.setArguments(argsbuffer.toString()); launch.setClasspath(cp); launch.setTargetClassName(launchconfig.getMainType()); // ant4eclipse assures the File.pathSeparator editor.classpath.setValues(cp.split(File.pathSeparator)); editor.target.setText(launchconfig.getMainType()); editor.arguments.setValues(splitted); result = true; } } return (result); } /** * Resolves the classpath from a Java launch configuration. * * @param workspace * The workspace which is used for the Eclipse project. * @param launchconfig * The launch configuration providing the necessary data. * @return The resolved classpath. * @pre workspace != null * @pre launchconfig != null * @post result != null */ private String loadClasspath(Workspace workspace, JavaApplicationLaunchConfiguration launchconfig) { ResolvedPathEntry[] entries = null; try { entries = RuntimeClasspathResolver.resolveRuntimeClasspath( workspace, launchconfig, false); } catch (FileParserException ex) { /** * @todo [15-Apr-2006:KASI] There should be a proper error message * here. */ return (""); } StringBuffer buffer = new StringBuffer(); boolean added = false; for (int i = 0; i < entries.length; i++) { // we're checking for resolved entries since containers like JRE // don't need to be added here, since Abbot doesn't support specific // runtime information if (entries[i].isResolved()) { if (added) { buffer.append(File.pathSeparator); } buffer.append(entries[i].getResolvedEntryAsFile() .getAbsolutePath()); added = true; } } return (buffer.toString()); } /** * Selects and loads launch configuration file. * * @return The launching configuration information. */ private JavaApplicationLaunchConfiguration selectLaunchConfiguration() { JavaApplicationLaunchConfiguration result = null; int option = launchfilechooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { File location = launchfilechooser.getSelectedFile(); if (location.isFile()) { try { LaunchFileParser parser = new LaunchFileParser(location); AbstractLaunchConfiguration config = parser .getLaunchConfiguration(); if (config instanceof JavaApplicationLaunchConfiguration) { result = (JavaApplicationLaunchConfiguration) config; } } catch (FileParserException ex) { ex.printStackTrace(); } } } return (result); } /** * FileFilter implementation used to select Eclipse launch configuration * files. */ private static class LaunchFileFilter extends javax.swing.filechooser.FileFilter { /** * {@inheritDoc} */ public boolean accept(File file) { if (file.isDirectory()) { return (true); } /** * @todo [13-Apr-2006:KASI] There should be OS specific comparison * (upper/lower/ignore). */ String name = file.getName(); return (name.endsWith(".launch")); } /** * {@inheritDoc} */ public String getDescription() { return ("Eclipse Launch Configuration (*.launch)"); } } /* ENDCLASS */ /** * FileFilter implementation used to select an Eclipse workspace. */ private static class WorkspaceFileFilter extends javax.swing.filechooser.FileFilter { private String project; private String relative; /** * Initializes this FileFilter which is used to select a Workspace. */ public WorkspaceFileFilter() { project = null; relative = null; } /** * Changes the name of the currently used projectname. * * @param newproject * The name of the currently used projectname. * @pre newproject.length() > 0 */ public void setProjectName(String newproject) { project = newproject; relative = ".plugins/org.eclipse.core.resources/.projects/" + project; } /** * {@inheritDoc} */ public boolean accept(File file) { if (file.isDirectory()) { File child = new File(file, ".metadata"); if (child.isDirectory()) { File projectdir = new File(child, relative); return (projectdir.isDirectory()); } } return (false); } /** * {@inheritDoc} */ public String getDescription() { return ("Eclipse Workspace"); } } /* ENDCLASS */ } /* ENDCLASS */
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/LaunchEditor.java
/** * Name........: LaunchEditor * Description.: Provide convenient editing of a launch step. * Author......: Timothy Wall * E-Mail......: [email protected] */ package abbot.editor.editors; import abbot.editor.widgets.*; import abbot.script.*; import abbot.i18n.*; import abbot.util.*; import javax.swing.*; import java.awt.event.*; import java.lang.reflect.*; import java.util.*; /** * Provide convenient editing of a launch step. */ public class LaunchEditor extends CallEditor { public static final String HELP_DESC = Strings.get("FixClassname"); private Launch launch; protected ArrayEditor classpath; private JCheckBox thread; private JButton importeclipse; /** * Initializes this editor which is used to edit the supplied step. * * @param launch * The launch step that will be edited. */ public LaunchEditor(Launch launch) { super(launch); this.launch = launch; String[] paths = PathClassLoader.convertPathToFilenames(launch .getClasspath()); // FIXME extend ArrayEditor to use file choosing buttons instead of // text fields alone classpath = addArrayEditor(Strings.get("Classpath"), paths); classpath.setName(TAG_CLASSPATH); thread = addCheckBox(Strings.get("Thread"), launch.isThreaded()); thread.setName(TAG_THREADED); // the stuff used to import an eclipse launch configuration try { Class classobj = Class.forName("abbot.editor.editors.ImportButton"); Constructor constructor = classobj.getConstructor(new Class[] {LaunchEditor.class, Launch.class}); importeclipse = (JButton) constructor.newInstance(new Object[] {this, launch}); add(importeclipse); } catch (Throwable t) { // just don't embed the import button } } /** * Display only the public static member functions. */ protected String[] getMethodNames(Method[] mlist) { ArrayList list = new ArrayList(); int mask = Modifier.PUBLIC | Modifier.STATIC; for (int i = 0; i < mlist.length; i++) { if ((mlist[i].getModifiers() & mask) == mask) { list.add(mlist[i].getName()); } } return (String[]) list.toArray(new String[list.size()]); } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); if (src == classpath) { Object[] values = classpath.getValues(); String cp = null; if (values.length > 0) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < values.length; i++) { if (i > 0) { buf.append(System.getProperty("path.separator")); } String path = (String) values[i]; if ("".equals(path)) { path = "."; } buf.append(path); } cp = buf.toString(); } launch.setClasspath(cp); // Changing the classpath may affect whether the class/method are // valid. validateTargetClass(); validateMethod(); fireStepChanged(); } else if (src == thread) { launch.setThreaded(!launch.isThreaded()); fireStepChanged(); } else { super.actionPerformed(evt); } // Remove the default placeholder description if (HELP_DESC.equals(launch.getDescription())) { launch.setDescription(null); fireStepChanged(); } } } /* ENDCLASS */
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/PropertyCallEditor.java
package abbot.editor.editors; import java.awt.Component; import java.awt.event.ActionEvent; import java.lang.reflect.*; import java.util.*; import javax.swing.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.tester.ComponentTester; /** Provide convenient editing of a PropertyCall step. */ public abstract class PropertyCallEditor extends CallEditor { private JComboBox component; private PropertyCall call; public PropertyCallEditor(PropertyCall call) { super(call); this.call = call; component = addComponentSelector(Strings.get("ComponentID"), call.getComponentID(), call.getResolver(), true); component.setName(TAG_COMPONENT); } /** Get the class of the current component target, if any. */ protected Class getComponentTargetClass(Class cls) { String[] args = getCall().getArguments(); if (args.length == 1) { String id = args[0]; ComponentReference ref = getCall().getResolver().getComponentReference(id); if (ref != null) { try { return getCall().resolveClass(ref.getRefClassName()); } catch(ClassNotFoundException e) { } } } return null; } /** If the target is Component or ComponentTester, provide a merge of property-like methods from both. */ protected Map getMethods(Class cls, int mask) { boolean isTester = ComponentTester.class.isAssignableFrom(cls); boolean isComponent = Component.class.isAssignableFrom(cls); Class componentClass = isTester ? getComponentTargetClass(cls) : (isComponent ? cls : null); Class testerClass = isTester ? cls : (isComponent ? ComponentTester.getTester(componentClass).getClass() : null); if (!isTester && !isComponent) return super.getMethods(cls, mask); Map map = new HashMap(); if (componentClass != null) { Iterator iter = super.getMethods(componentClass, mask).values().iterator(); while (iter.hasNext()) { Method m = (Method)iter.next(); if (PropertyCall.isPropertyMethod(m)) { map.put(m.getName(), m); } } } // Scan the corresponding component tester for additional property // methods try { ComponentTester tester = componentClass != null ? ComponentTester.getTester(componentClass) : (ComponentTester)testerClass.newInstance(); Iterator iter = getComponentTesterMethods(tester).iterator(); while (iter.hasNext()) { Method m = (Method)iter.next(); String methodName = m.getName(); // If there is a property already defined, then defer to the component class not the tester // if (!map.containsKey(methodName)) { map.put(methodName, m); } } } catch(Exception e) { } return map; } protected boolean includeMethod(Class cls, Method m) { return true; } protected Collection getComponentTesterMethods(ComponentTester tester) { return Arrays.asList(tester.getPropertyMethods()); } /** Synchronize the component selector with the PropertyCall data. */ protected void componentChanged() { component.setSelectedItem(call.getComponentID()); } public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == component) { String id = (String)component.getSelectedItem(); if (id != null) id = id.trim(); if ("".equals(id)) { id = null; } ComponentReference ref = call.getResolver().getComponentReference(id); String tcn = ref != null ? ref.getRefClassName() : Component.class.getClass().getName(); call.setComponentID(id); call.setTargetClassName(tcn); call.setArguments(new String[0]); targetClassChanged(); argumentsChanged(); fireStepChanged(); } else if (src == method) { super.actionPerformed(ev); // When the method changes to or from a ComponentTester // pseudo-property method, we need to change the target class. try { Class cls = call.getTargetClass(); String methodName = (String)method.getSelectedItem(); Map methods = getMethods(cls, Modifier.PUBLIC); Method m = (Method)methods.get(methodName); if (m != null) { Class newClass = m.getDeclaringClass(); if (ComponentTester.class.isAssignableFrom(newClass) && Component.class.isAssignableFrom(cls)) { String id = call.getComponentID(); if (id != null) { call.setArguments(new String[] { id }); argumentsChanged(); } call.setComponentID(null); call.setTargetClassName(newClass.getName()); componentChanged(); targetClassChanged(); fireStepChanged(); } else if (Component.class.isAssignableFrom(newClass) && ComponentTester.class.isAssignableFrom(cls) && call.getArguments().length == 1) { newClass = getComponentTargetClass(cls); String id = call.getArguments()[0]; call.setArguments(new String[0]); call.setComponentID(id); call.setTargetClassName(newClass.getName()); argumentsChanged(); componentChanged(); targetClassChanged(); fireStepChanged(); } } } catch(ClassNotFoundException e) { // don't care } } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/SampleEditor.java
package abbot.editor.editors; import java.awt.event.ActionEvent; import javax.swing.JTextField; import abbot.i18n.Strings; import abbot.script.Sample; /** Provide convenient editing of a Sample step. */ public class SampleEditor extends PropertyCallEditor { private Sample step; private JTextField property; public SampleEditor(Sample step) { super(step); this.step = step; property = addTextField(Strings.get("PropertyName"), step.getPropertyName()); } public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == property) { String name = property.getText().trim(); if (!"".equals(name)) { step.setPropertyName(name); fireStepChanged(); } } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/ScriptEditor.java
package abbot.editor.editors; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.*; import abbot.Log; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Script; import abbot.editor.EditorConstants; import abbot.editor.widgets.Mnemonic; /** Provide convenient editing of a Script step. */ public class ScriptEditor extends SequenceEditor { private Script script; private JTextField path; private JCheckBox fork; private JTextField vmargs; public ScriptEditor(Script script) { super(script); this.script = script; path = addTextField(Strings.get("FilePath"), script.getFilename()); if (!(script instanceof Fixture)) { fork = addCheckBox("", script.isForked()); String key = EditorConstants.ACTION_PREFIX + EditorConstants.ACTION_TOGGLE_FORKED; Mnemonic mnemonic = Mnemonic.getMnemonic(Strings.get(key)); mnemonic.setMnemonic(fork); addVMArgs(); } } private void addVMArgs() { if (script.isForked()) { vmargs = addTextField(Strings.get("VMArgs"), script.getVMArgs()); } else if (vmargs != null) { while (getComponent(getComponentCount()-1) != fork) { remove(getComponentCount()-1); } vmargs = null; } revalidate(); repaint(); } public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == path) { String filename = path.getText().trim(); File file = new File(script.getRelativeTo(), filename); script.setFile(file); try { script.load(); } catch(Exception exc) { Log.warn(exc); } fireStepChanged(); } else if (src == fork) { script.setForked(!script.isForked()); addVMArgs(); fireStepChanged(); } else if (src == vmargs) { String text = vmargs.getText(); if ("".equals(text)) text = null; script.setVMArgs(text); fireStepChanged(); } else { super.actionPerformed(ev); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/SequenceEditor.java
package abbot.editor.editors; import abbot.script.Sequence; /** Provide convenient editing of a Sequence step. */ public class SequenceEditor extends StepEditor { public SequenceEditor(Sequence seq) { super(seq); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/StepChangeListener.java
package abbot.editor.editors; import abbot.script.Step; /** Provide a data change notification when a Step changes. */ public interface StepChangeListener { void stepChanged(Step step); }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/StepEditor.java
package abbot.editor.editors; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Constructor; import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import abbot.Log; import abbot.i18n.Strings; import abbot.script.*; import abbot.editor.widgets.ArrayEditor; import abbot.editor.widgets.TextArea; import abbot.editor.widgets.TextField; /** Provide base-level step editor support with step change notification. */ // NOTE: this should really be done with beans instead... public abstract class StepEditor extends JPanel implements ActionListener, Scrollable, XMLConstants { private Step step; private JLabel label; JTextField description; private LayoutManager layout; private ArrayList listeners = new ArrayList(); protected static final int MARGIN = 4; private boolean fieldChanging = false; protected static Color DEFAULT_FOREGROUND = null; protected static Color ERROR_FOREGROUND = Color.red; public StepEditor(Step step) { setBorder(new EmptyBorder(2,2,2,2)); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); layout = getLayout(); this.step = step; label = new JLabel(step.getXMLTag()); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setToolTipText(step.getUsage()); add(label); description = addTextField(null, step.getDescription()); description.setName(TAG_DESC); description.setToolTipText(Strings.get("editor.step.description.tip")); if (DEFAULT_FOREGROUND == null) { DEFAULT_FOREGROUND = description.getForeground(); } } /** Keep a reasonable minimum width. */ public Dimension getMinimumSize() { Dimension min = super.getMinimumSize(); min.width = 200; return min; } /** Keep a reasonable minimum width. */ public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width = 200; return size; } /** We don't want to become infinitely wide due to text fields. */ public Dimension getMaximumSize() { Dimension max = super.getMaximumSize(); max.width = 400; return max; } protected JCheckBox addCheckBox(String title, boolean value) { JCheckBox cb = new JCheckBox(title); cb.setSelected(value); cb.addActionListener(this); add(cb); return cb; } /** Provide a combo box that short-circuits unnecessary and problem-causing event notifications. */ private class ComboBox extends JComboBox { private JTextField editor; private boolean configuringEditor; public ComboBox() { } public ComboBox(ComboBoxModel model) { super(model); } public ComboBox(Object[] values) { super(values); } public void addImpl(Component c, Object constraints, int index) { if (c instanceof JTextField) { editor = (JTextField)c; TextField.decorate(editor); } super.addImpl(c, constraints, index); } /** Disallow recursive calls, which occur when someone sets the combo box contents in response to the combo box selection. */ public void configureEditor(ComboBoxEditor editor, Object item) { // Avoids IllegalStateExceptions from the text field ("Attempt to // mutate in notification" errors). if (!configuringEditor) { configuringEditor = true; super.configureEditor(editor, item); configuringEditor = false; } } /** Sets the foreground color of the editor text. */ public void setForeground(Color c) { if (editor != null) { editor.setForeground(c); } } /** Overridden to prevent recursive calls. */ public void fireActionEvent() { if (!fieldChanging) { fieldChanging = true; super.fireActionEvent(); fieldChanging = false; } } /** Overridden to prevent recursive calls. */ public void fireItemStateChanged(ItemEvent e) { if (!fieldChanging) { fieldChanging = true; super.fireItemStateChanged(e); fieldChanging = false; } } } private static final String NONE = "<None>"; private class RefModel extends AbstractListModel implements ComboBoxModel { private Resolver resolver; private boolean includeNone; private Object selected; private Collection set; public RefModel(Resolver r, boolean includeNone) { resolver = r; this.includeNone = includeNone; set = resolver.getComponentReferences(); } public Object getElementAt(int i) { checkContents(); if (includeNone) { if (i == 0) return NONE; --i; } return ((ComponentReference)set.toArray()[i]).getID(); } public int getSize() { checkContents(); int size = set.size(); return includeNone ? size + 1 : size; } public void setSelectedItem(Object o) { if (o instanceof ComponentReference) o = ((ComponentReference)o).getID(); else if (o == null) o = NONE; selected = o; checkContents(); } public Object getSelectedItem() { checkContents(); return selected == NONE ? null : selected; } // Always check whether this model is synched with the resolver's set // of references. private void checkContents() { Collection current = resolver.getComponentReferences(); if (set.size() != current.size()) { set = current; if (!fieldChanging) { fieldChanging = true; fireContentsChanged(this, 0, set.size()-1); fieldChanging = false; } } } } protected JComboBox addComponentSelector(String title, String refid, Resolver resolver, boolean allowNone) { // NOTE: the combo box has no method of refreshing its contents when // references are added/removed/changed in the resolver JComboBox cb = new ComboBox(new RefModel(resolver, allowNone)); cb.setSelectedItem(refid); cb.addActionListener(this); add(title, cb); return cb; } protected JComboBox addComboBox(String title, Object value, Object[] values) { JComboBox cb = new ComboBox(values); cb.setEditable(true); cb.setSelectedItem(value); cb.addActionListener(this); add(title, cb); return cb; } protected JTextField addTextField(String title, String value) { return addTextField(title, value, null); } protected JTextField addTextField(String title, String value, String defaultValue) { return addTextField(title, value, defaultValue, false); } protected JTextField addTextField(String title, String value, String defaultValue, boolean delayedUpdate) { JTextField field = new abbot.editor.widgets.TextField(value, defaultValue, delayedUpdate); field.addActionListener(this); add(title, field); return field; } protected ArrayEditor addArrayEditor(String title, Object[] values) { ArrayEditor ed = new ArrayEditor(values); ed.addActionListener(this); // Make sure we resize/repaint when items are added or removed ed.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand() != ArrayEditor.ACTION_ITEM_CHANGED) { revalidate(); repaint(); } } }); add(title, ed); return ed; } protected JButton addButton(String title) { JButton button = new JButton(title); button.addActionListener(this); add(button); return button; } protected JTextArea addTextArea(String title, String value) { final TextArea text = new TextArea(value != null ? value : ""); text.setLineWrap(true); text.setWrapStyleWord(true); text.setBorder(UIManager.getBorder("TextField.border")); text.addActionListener(this); text.setRows(10); add(title, new JScrollPane( text, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); return text; } /** Automatically remove the strut spacing and the component. */ public void remove(Component comp) { if (getLayout() == layout) { Component[] children = super.getComponents(); for (int i=1;i < children.length;i++) { if (children[i] == comp) { super.remove(children[i-1]); break; } } } super.remove(comp); } /** Auto-add a label with a component. */ public Component add(String name, Component comp) { if (name != null) { JLabel label = new JLabel(name); label.setLabelFor(comp); add(label); } return add(comp); } /** Automatically add a vertical struct with a component. */ public Component add(Component comp) { if (getLayout() == layout) { super.add(Box.createVerticalStrut(MARGIN)); if (comp instanceof JComponent) { ((JComponent)comp).setAlignmentX(JComponent.LEFT_ALIGNMENT); } } return super.add(comp); } /** Respond to UI changes by updating the step data. */ public void actionPerformed(ActionEvent ev) { Object src = ev.getSource(); if (src == description) { // When the description is cleared (but only when entered by ENTER // or FOCUS events), reset it to the default String text = description.getText(); String cmd = ev.getActionCommand(); if ("".equals(text)) { if (!TextField.isDocumentAction(ev.getActionCommand())) { SwingUtilities.invokeLater(new Runnable() { public void run() { description.setText(step.getDefaultDescription()); description.selectAll(); } }); step.setDescription(null); fireStepChanged(); } } // Only explicitly set the step data if the data is different // from the default. else if (cmd == TextField.ACTION_TEXT_REVERTED || !text.equals(step.getDefaultDescription())) { step.setDescription(text); fireStepChanged(); } } } public void addStepChangeListener(StepChangeListener scl) { synchronized(listeners) { listeners.add(scl); } } public void removeStepChangeListener(StepChangeListener scl) { synchronized(listeners) { listeners.remove(scl); } } /** This method should be invoked after any change to step data. */ protected void fireStepChanged() { synchronized(listeners) { Iterator iter = listeners.iterator(); while (iter.hasNext()) { StepChangeListener scl = (StepChangeListener)iter.next(); scl.stepChanged(step); } } // The default description may have changed; ensure the text field is // up to date if (!description.getText().equals(step.getDescription())) { description.setText(step.getDescription()); } } /** Return the appropriate editor panel for the given Step. * Custom editors must be named after the step class name, and be defined * in the abbot.editor.editors package, e.g. abbot.script.Launch expects * abbot.editor.editors.LaunchEditor, abbot.script.Assert expects * abbot.editor.editors.AssertEditor. */ public static StepEditor getEditor(Step step) { Class stepClass = step.getClass(); Log.debug("Looking up editor for " + step + " using " + stepClass); String className = stepClass.getName(); className = "abbot.editor.editors." + className.substring(className.lastIndexOf(".") + 1) + "Editor"; try { Log.debug("Trying " + className); Class cls = Class.forName(className); Class[] types = new Class[] { stepClass }; Constructor ctor = cls.getConstructor(types); return (StepEditor)ctor.newInstance(new Object[] { step }); } catch(ClassNotFoundException e) { // ignore this one } catch(Exception e) { Log.warn(e); } return null; } /** Always maintain the minimum width. */ public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableBlockIncrement(Rectangle visible, int orient, int direction) { return orient == SwingConstants.HORIZONTAL ? visible.width : visible.height; } public boolean getScrollableTracksViewportHeight() { return false; } public boolean getScrollableTracksViewportWidth() { return true; } public int getScrollableUnitIncrement(Rectangle visible, int orient, int direction) { return orient == SwingConstants.HORIZONTAL ? 10 : description.getSize().height; } public String toString() { return getClass().getName() + " for " + label.getText(); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/editors/XMLEditor.java
package abbot.editor.editors; import java.awt.Component; import java.awt.event.*; import java.util.EventObject; import javax.swing.*; import javax.swing.table.TableCellEditor; import javax.swing.tree.TreeCellEditor; import abbot.script.XMLifiable; /** * An editor for an XMLifiable object. * It'd be nice to provide a real XML editor here... */ public class XMLEditor extends AbstractCellEditor implements TableCellEditor, TreeCellEditor { private JTextField textField = new JTextField(); protected JComponent editorComponent = textField; protected EditorDelegate delegate; protected int clickCountToStart = 1; /** * Constructs an XMLEditor that uses a text field. */ public XMLEditor() { this.clickCountToStart = 2; delegate = new EditorDelegate() { /** Set the contents of the editor based on the original object. */ public void setValue(Object value) { if (value instanceof XMLifiable) { value = ((XMLifiable)value).toEditableString(); } textField.setText((value != null) ? value.toString() : ""); } public Object getCellEditorValue() { return textField.getText(); } }; textField.addActionListener(delegate); } /** * Returns the component used to edit this editor's value. * * @return the editor Component */ public Component getComponent() { return editorComponent; } /** * Specifies the number of clicks needed to start editing. * * @param count an int specifying the number of clicks needed to start * editing * @see #getClickCountToStart */ public void setClickCountToStart(int count) { clickCountToStart = count; } /** * ClickCountToStart controls the number of clicks required to start * editing. */ public int getClickCountToStart() { return clickCountToStart; } public Object getCellEditorValue() { return delegate.getCellEditorValue(); } public boolean isCellEditable(EventObject anEvent) { return delegate.isCellEditable(anEvent); } public boolean shouldSelectCell(EventObject anEvent) { return delegate.shouldSelectCell(anEvent); } public boolean stopCellEditing() { return delegate.stopCellEditing(); } public void cancelCellEditing() { delegate.cancelCellEditing(); } // // Implementing the TreeCellEditor Interface // public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { String stringValue = tree.convertValueToText(value, isSelected, expanded, leaf, row, false); delegate.setValue(stringValue); return editorComponent; } // // Implementing the CellEditor Interface // public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { delegate.setValue(value); return editorComponent; } // // Protected EditorDelegate class // protected class EditorDelegate implements ActionListener, ItemListener { protected Object value; public Object getCellEditorValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean isCellEditable(EventObject anEvent) { if (anEvent instanceof MouseEvent) { return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart; } return true; } public boolean shouldSelectCell(EventObject anEvent) { return true; } public boolean startCellEditing(EventObject anEvent) { return true; } public boolean stopCellEditing() { fireEditingStopped(); return true; } public void cancelCellEditing() { fireEditingCanceled(); } public void actionPerformed(ActionEvent e) { XMLEditor.this.stopCellEditing(); } public void itemStateChanged(ItemEvent e) { XMLEditor.this.stopCellEditing(); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/AbstractButtonRecorder.java
package abbot.editor.recorder; import java.awt.Component; import java.awt.event.InputEvent; import abbot.script.*; /** * Record basic semantic events you might find on an AbstractButton. This * class handles a click on the button. */ public class AbstractButtonRecorder extends JComponentRecorder { public AbstractButtonRecorder(Resolver resolver) { super(resolver); } /** Usually don't bother tracking drags/drops on buttons. */ protected boolean canDrag() { return false; } /** Usually aren't interested in multiple clicks on a button. */ protected boolean canMultipleClick() { return false; } /** Create a button-specific click action. */ protected Step createClick(Component target, int x, int y, int mods, int count) { // No need to store the coordinates, the center of the button is just // fine. Only care about button 1, though. ComponentReference cr = getResolver().addComponent(target); if (mods == 0 || mods == InputEvent.BUTTON1_MASK) return new Action(getResolver(), null, "actionClick", new String[] { cr.getID() }, javax.swing.AbstractButton.class); return null; } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/AbstractInternalFrameWatcher.java
package abbot.editor.recorder; import java.awt.AWTEvent; import java.awt.event.*; import javax.swing.JInternalFrame; import javax.swing.event.*; public abstract class AbstractInternalFrameWatcher extends InternalFrameAdapter implements ComponentListener { public AbstractInternalFrameWatcher(JInternalFrame f) { f.addInternalFrameListener(this); f.addComponentListener(this); } protected abstract void dispatch(AWTEvent e); public void componentHidden(ComponentEvent e) { // Ensure this listener doesn't hang around after the frame goes // away. e.getComponent().removeComponentListener(this); ((JInternalFrame)e.getComponent()).removeInternalFrameListener(this); } public void internalFrameClosing(InternalFrameEvent e) { dispatch(e); e.getInternalFrame().removeInternalFrameListener(this); e.getInternalFrame().removeComponentListener(this); } public void internalFrameIconified(InternalFrameEvent e) { dispatch(e); } public void internalFrameDeiconified(InternalFrameEvent e) { dispatch(e); } public void componentShown(ComponentEvent e) { } public void componentResized(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/ButtonRecorder.java
package abbot.editor.recorder; import java.awt.*; import abbot.script.*; /** * Record simple clicks on a Button component. <p> */ public class ButtonRecorder extends ComponentRecorder { public ButtonRecorder(Resolver resolver) { super(resolver); } /** Don't need to store any position or modifier information. */ protected Step createClick(Component target, int x, int y, int mods, int count) { ComponentReference cr = getResolver().addComponent(target); return new Action(getResolver(), null, "actionClick", new String[] { cr.getID() }); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/CheckboxRecorder.java
package abbot.editor.recorder; import java.awt.*; import abbot.script.*; /** * Record basic click a Checkbox component. <p> */ public class CheckboxRecorder extends ComponentRecorder { public CheckboxRecorder(Resolver resolver) { super(resolver); } /** Don't need to store any position or modifier information. */ protected Step createClick(Component target, int x, int y, int mods, int count) { ComponentReference cr = getResolver().addComponent(target); return new Action(getResolver(), null, "actionClick", new String[] { cr.getID() }); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/ChoiceRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import abbot.Log; import abbot.script.*; /** * Record basic semantic events you might find on an Choice component. <p> */ public class ChoiceRecorder extends ComponentRecorder { private Choice choice = null; /** If selection is null when finished, no step will be generated. */ private String selection = null; private ItemListener listener = null; public ChoiceRecorder(Resolver resolver) { super(resolver); } protected void init(int recordingType) { super.init(recordingType); choice = null; selection = null; listener = null; } /** Also accept ItemEvents, since the ChoiceTester will not generate any explicit clicks to control the component. */ protected boolean isClick(AWTEvent e) { if (e instanceof ItemEvent) { return true; } return super.isClick(e); } /** Track click -> select ->click, cancelable by ESC or by clicking away from the component.<p> NOTE: press->drag->release produces an identical set of events<br> OSX 1.3.1:<br> MOUSE_PRESSED<br> (ITEM_STATE_CHANGED)|MOUSE_RELEASED|KEY_RELEASED<br> The ItemEvent never makes it to the AWT listener. */ protected boolean parseClick(AWTEvent event) { // Have to check here since we handle the ItemEvent artificially if (isFinished()) { Log.debug("already finished"); return false; } if (choice == null) { // Parse immediate selections (programmatic/tester driven) if (event instanceof ItemEvent) { choice = (Choice)event.getSource(); selection = ((ItemEvent)event).getItem().toString(); Log.debug("selection=" + selection); setFinished(true); } else { choice = (Choice)event.getSource(); listener = new ItemListener() { public void itemStateChanged(ItemEvent ev) { Log.debug("item event"); if (ev.getStateChange() == ItemEvent.SELECTED) { selection = ev.getItem().toString(); Log.debug("selection=" + selection); choice.removeItemListener(this); setFinished(true); } } }; choice.addItemListener(listener); setStatus("Waiting for selection"); } } else if (event.getID() == KeyEvent.KEY_RELEASED && (((KeyEvent)event).getKeyCode() == KeyEvent.VK_SPACE || ((KeyEvent)event).getKeyCode() == KeyEvent.VK_ENTER)) { Log.debug("enter"); setFinished(true); } else if (event.getID() == KeyEvent.KEY_RELEASED && ((KeyEvent)event).getKeyCode() == KeyEvent.VK_ESCAPE) { Log.debug("cancel"); selection = null; setFinished(true); } else { Log.debug("Event ignored"); } if (isFinished() && choice != null) { choice.removeItemListener(listener); listener = null; } // Events are always consumed by the Choice return true; } protected Step createStep() { Step step = null; if (getRecordingType() == SE_CLICK) { if (selection != null) step = createSelection(choice, selection); } else { step = super.createStep(); } return step; } protected Step createSelection(Choice target, String selection) { ComponentReference cr = getResolver().addComponent(choice); return new Action(getResolver(), null, "actionSelectItem", new String[] { cr.getID(), selection }, java.awt.Choice.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/ComponentRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.text.JTextComponent; import abbot.BugReport; import abbot.Log; import abbot.Platform; import abbot.finder.matchers.JMenuItemMatcher; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Action; import abbot.script.Resolver; import abbot.tester.*; import abbot.tester.Robot; import abbot.util.AWT; /** * Record basic semantic events you might find on any component. This class * handles the following actions:<p> * <ul> * <li>window actions * <li>popup menus * <li>click * <li>typed keys * <li>basic drag and drop * <li>InputMethod events (extended character input) * </ul> * Clicks, popup menus, and drag/drop actions may be based on coordinates or * component substructure (cell, row, tab, etc) locations. * * <h3>Window Actions</h3> * While these nominally might be handled in a WindowRecorder, they are so * common that it's easier to handle here instead. Currently supports * tracking show/hide/activate. TODO: move/resize/iconfify/deiconify. * <h3>Popup Menus</h3> * Currently only the click/select/click sequence is supported. The * press/drag/release version shouldn't be hard to implement, though. * <h3>Click</h3> * Simple press/release on a component, storing the exact coordinate of the * click. Most things with selectability will want to override this. Culling * accidental intervening drags would be nice but probably not worth the * effort or complexity (better just to be less sloppy with your mouse). * <h3>Key Type</h3> * Capture only events that result in actual output. No plain modifiers, * shortcuts, or mnemonics. * <h3>Drag/Drop</h3> * Basic drag from one component and drop on another, storing exact * coordinates of the press/release actions. Should definitely override this * to represent your component's internal objects (e.g. cells in a table). * Note that these are two distinct actions, even though they always appear * together. The source is responsible for identifying the drag, and the * target is responsible for identifying the drop. * <h3>InputMethod</h3> * Catch extended character input. */ // NOTE: Mac OSX robot will actually generate key modifiers prior // to button2/3 // NOTE: Mac OSX CTRL/ALT+MB1 invokes MB2 // CTRL+MB1->CTRL+MB2 // ALT+MB1->MB2 // TODO: test recorders by sending an event stream; test platform stream // by generating robot events and verifying stream seen; this splits the // tests into separate concerns. public class ComponentRecorder extends SemanticRecorder { private static final String[] TYPES = { "any", "window", "menu", "click", "key", "drag", "drop", "text", "input method" }; /** Mappings for special keys. */ private static java.util.HashMap specialMap; static { // Make explicit some special key mappings which we DON'T want to save // as the resulting characters (b/c they may not actually be // characters, or they're not particularly good to save as // characters. int[][] mappings = { { '\t', KeyEvent.VK_TAB }, { '', KeyEvent.VK_ESCAPE }, // No escape sequence exists { '\b', KeyEvent.VK_BACK_SPACE }, { '', KeyEvent.VK_DELETE }, // No escape sequence exists { '\n', KeyEvent.VK_ENTER }, { '\r', KeyEvent.VK_ENTER }, }; specialMap = new java.util.HashMap(); for (int i=0;i < mappings.length;i++) { specialMap.put(String.valueOf((char)mappings[i][0]), AWT.getKeyCode(mappings[i][1])); } } // For windows private Window window = null; private boolean isClose = false; // For key events private char keychar = KeyEvent.CHAR_UNDEFINED; private int modifiers; // For clicks private Component target; private Component forwardedTarget; private int x, y; private boolean released; private int clickCount; // For menu events private Component invoker; private int menux, menuy; private MenuItem awtMenuTarget; private Component menuTarget; private boolean isPopup; private boolean hasAWTPopup; private MenuListener menuListener; private boolean menuCanceled; // For drag events // This class is responsible for handling drag/drop once the action has // been recognized by a derived class private Component dragSource; private int dragx, dragy; // For drop events private Component dropTarget; private int dropx, dropy; // InputMethod private ArrayList imKeyCodes = new ArrayList(); private StringBuffer imText = new StringBuffer(); /** Keep a short-term memory of windows we've seen open/close already. */ private static WeakHashMap closeEventWindows = new WeakHashMap(); private static WeakHashMap openEventWindows = new WeakHashMap(); /** Create a ComponentRecorder for use in capturing the semantics of a GUI * action. */ public ComponentRecorder(Resolver resolver) { super(resolver); } /** Does the given event indicate a window was shown? */ protected boolean isOpen(AWTEvent event) { int id = event.getID(); // 1.3 VMs may generate a WINDOW_OPEN without a COMPONENT_SHOWN // (see EventRecorderTest.testClickWithDialog) // NOTE: COMPONENT_SHOWN precedes WINDOW_OPENED, but we don't really // care in this case, since we're just recording the event, not // watching for the component's validity. if (((id == WindowEvent.WINDOW_OPENED && !openEventWindows.containsKey(event.getSource())) || id == ComponentEvent.COMPONENT_SHOWN)) { return true; } return false; } /** Does the given event indicate a window was closed? */ protected boolean isClose(AWTEvent event) { int id = event.getID(); // Window.dispose doesn't generate a HIDDEN event, but it does // generate a WINDOW_CLOSED event (1.3/1.4) if (((id == WindowEvent.WINDOW_CLOSED && !closeEventWindows.containsKey(event.getSource())) || id == ComponentEvent.COMPONENT_HIDDEN)) { return true; } return false; } /** Returns whether this ComponentRecorder wishes to accept the given * event. If the event is accepted, the recorder must invoke init() with * the appropriate semantic event type. */ public boolean accept(AWTEvent event) { int rtype = SE_NONE; if (isWindowEvent(event)) { rtype = SE_WINDOW; } else if (isMenuEvent(event)) { rtype = SE_MENU; } else if (isKeyTyped(event)) { rtype = SE_KEY; } else if (isClick(event)) { rtype = SE_CLICK; } else if (isDragDrop(event)) { rtype = SE_DROP; } else if (isInputMethod(event)) { rtype = SE_IM; } else { if (Log.isClassDebugEnabled(ComponentRecorder.class)) Log.debug("Ignoring " + Robot.toString(event)); } init(rtype); boolean accepted = rtype != SE_NONE; if (accepted && Log.isClassDebugEnabled(ComponentRecorder.class)) Log.debug("Accepted " + ComponentTester.toString(event)); return accepted; } /** Test whether the given event is a trigger for a window event. * Allow derived classes to change definition of a click. */ protected boolean isWindowEvent(AWTEvent event) { // Ignore activate and deactivate. They are unreliable. // We only want open/close events on non-tooltip and non-popup windows return (event.getSource() instanceof Window) && !AWT.isHeavyweightPopup((Window)event.getSource()) && !isToolTip(event.getSource()) && (isClose(event) || isOpen(event)); } /** * Return true if the given event source is a tooltip. * Such events look like window events, but we check for them before other * kinds of window events so as to be able to filter them out. * <P> * TODO: emit steps to confirm value of tooltip? * <P> * @param source the object to examine * @return true if this event source is a tooltip */ protected boolean isToolTip(Object source){ // Tooltips appear to be a direct subclass of JWindow and // have a single component of class JToolTip if (source instanceof JWindow && !(source instanceof JFrame)){ Container pane = ((JWindow)source).getContentPane(); while (pane.getComponentCount() == 1){ Component child = pane.getComponent(0); if (child instanceof JToolTip) return true; if (!(child instanceof Container)) break; pane = (Container)child; } } return false; } protected boolean isMenuEvent(AWTEvent event) { if (event.getID() == ActionEvent.ACTION_PERFORMED && event.getSource() instanceof java.awt.MenuItem) { return true; } else if (event.getID() == MouseEvent.MOUSE_PRESSED) { MouseEvent me = (MouseEvent)event; return me.isPopupTrigger() || ((me.getModifiers() & AWTConstants.POPUP_MASK) != 0) || me.getSource() instanceof JMenu; } return false; } protected boolean isKeyTyped(AWTEvent event) { return event.getID() == KeyEvent.KEY_TYPED; } /** Test whether the given event is a trigger for a mouse button click. * Allow derived classes to change definition of a click. */ protected boolean isClick(AWTEvent event) { if (event.getID() == MouseEvent.MOUSE_PRESSED) { MouseEvent me = (MouseEvent)event; return (me.getModifiers() & MouseEvent.BUTTON1_MASK) != 0; } return false; } /** Test whether the given event precurses a drop. */ protected boolean isDragDrop(AWTEvent event) { return event.getID() == MouseEvent.MOUSE_DRAGGED; } /** Default to recording a drag if it looks like one. */ // FIXME may be some better detection, like checking for DND interfaces. */ protected boolean canDrag() { return true; } /** Default to waiting for multiple clicks. */ protected boolean canMultipleClick() { return true; } /** Is this the start of an input method event? */ private boolean isInputMethod(AWTEvent event) { // NOTE: HALF_WIDTH signals start of kanji input // NOTE: Mac uses input method for some dual-keystroke chars (option-e) return (event.getID() == KeyEvent.KEY_RELEASED && ((KeyEvent)event).getKeyCode() == KeyEvent.VK_HALF_WIDTH) || event.getID() == InputMethodEvent.INPUT_METHOD_TEXT_CHANGED; } /** Provide standard parsing of mouse button events. */ protected boolean parseClick(AWTEvent event) { boolean consumed = true; int id = event.getID(); if (id == MouseEvent.MOUSE_PRESSED) { Log.debug("Parsing mouse down"); MouseEvent me = (MouseEvent)event; if (clickCount == 0) { target = me.getComponent(); x = me.getX(); y = me.getY(); modifiers = me.getModifiers(); clickCount = 1; // Add the component immediately, just in case it gets removed // from the hierarchy as a result of the click. getResolver().addComponent(target); } else { if (target == me.getComponent()) { clickCount = me.getClickCount(); } else if (!released) { // It's possible to get two consecutive MOUSE_PRESSED // events for different targets (e.g. double click on a // table cell to get the default editor) (OSX 1.3.1, XP // 1.4.1_01). Ignore the second click, since it is // artificial, and wait for the original click to finish. // i.e. w32 1.3.1 // MOUSE_PRESSED JTable // MOUSE_PRESSED JTextField // FOCUS_LOST JTable // FOCUS_GAINED JTextField // MOUSE_EXITED JTable // MOUSE_ENTERED JTextField // MOUSE_RELEASED JTable // MOUSE_RELEASED JTextField forwardedTarget = me.getComponent(); } } released = false; } else if (id == MouseEvent.MOUSE_RELEASED) { Log.debug("Parsing mouse up"); released = true; // Optionally disallow multiple clicks if (!canMultipleClick()) setFinished(true); } else if (id == MouseEvent.MOUSE_CLICKED) { // optionally wait for multiple clicks if (!canMultipleClick()) setFinished(true); } else if (id == MouseEvent.MOUSE_EXITED) { Log.debug("exit event, released=" + released); if (event.getSource() != target || released) { consumed = false; setFinished(true); } else if (!released) { // May not see any DRAGGED events if it's a native drag; // 1.3 posts MOUSE_EXITED after MOUSE_PRESSED, no drag events if (clickCount == 1) { setRecordingType(SE_DRAG); consumed = dragStarted(target, x, y, modifiers, (MouseEvent)event); } } } else if (id == MouseEvent.MOUSE_ENTERED) { if (event.getSource() == target && !released) { // nothing } else if (event.getSource() != forwardedTarget) { consumed = false; setFinished(true); } } else if (id == MouseEvent.MOUSE_DRAGGED && canDrag()) { Log.debug("Changing click to drag start"); MouseEvent me = (MouseEvent)event; Point where = SwingUtilities.convertPoint(me.getComponent(), me.getX(), me.getY(), target); int threshold = Integer.getInteger("abbot.capture.drag_threshold", 5).intValue(); if (Math.abs(where.x - x) >= threshold || Math.abs(where.y - y) >= threshold) { // Was actually a drag; pass off to drag handler setRecordingType(SE_DRAG); consumed = dragStarted(target, x, y, modifiers, me); } else { Log.debug("Drag too small: " + me + " (from " + dragSource + " (" + x + ", " + y + "))"); } } // These events will not prevent a multi-click from being registered. else if ((id >= ComponentEvent.COMPONENT_FIRST && id <= ComponentEvent.COMPONENT_LAST) || (event instanceof ContainerEvent) || (event instanceof FocusEvent) || (id == HierarchyEvent.HIERARCHY_CHANGED && (((HierarchyEvent)event).getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == 0)) { // Ignore most hierarchy change and component events between // clicks. // The focus event is sporadic on w32 1.4.1_02 } else { // All other events should cause the click to finish, // but don't register a click unless we've received the release // event. if (released) { consumed = false; setFinished(true); } } return consumed; } protected boolean parseWindowEvent(AWTEvent event) { boolean consumed = true; isClose = isClose(event); // Keep track of window open/close state so we don't parse the same // semantic event twice (e.g. COMPONENT_SHOWN + WINDOW_OPENED or // multiple WINDOW_CLOSED events). if (isClose) { closeEventWindows.put(event.getSource(), Boolean.TRUE); openEventWindows.remove(event.getSource()); } else { openEventWindows.put(event.getSource(), Boolean.TRUE); closeEventWindows.remove(event.getSource()); } Log.log("close=" + isClose + " (" + Robot.toString(event) + ")"); window = (Window)event.getSource(); setFinished(true); return consumed; } protected boolean parseKeyEvent(AWTEvent e) { int id = e.getID(); boolean consumed = true; if (id == KeyEvent.KEY_TYPED) { KeyEvent typed = (KeyEvent)e; target = typed.getComponent(); keychar = typed.getKeyChar(); modifiers = typed.getModifiers(); if ((modifiers & KeyEvent.ALT_MASK) == KeyEvent.ALT_MASK) { Log.debug("Waiting for potential focus accelerator on '" + keychar + "'"); } else { // Ignore KEY_TYPED input for control and alt modifiers, since // the generated characters are not accepted as text input. // Add others if you encounter them, but err on the side of // accepting input that can later be removed. if ((modifiers & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK || (modifiers & InputEvent.ALT_MASK) == InputEvent.ALT_MASK) { Log.debug("Ignoring modifiers: " + modifiers); setRecordingType(SE_NONE); } setFinished(true); } } else if (id == FocusEvent.FOCUS_LOST) { // Ignore and wait for FOCUS_GAINED } else if (id == FocusEvent.FOCUS_GAINED) { // Looks like a focus accelerator focus change. Ignore the // KEY_TYPED event. Object o = e.getSource(); char ch = KeyEvent.CHAR_UNDEFINED; if (o instanceof JTextComponent) { ch = ((JTextComponent)o).getFocusAccelerator(); Log.debug("focus accelerator is '" + ch + "'"); } if (Character.toUpperCase(ch) == Character.toUpperCase(keychar)) { setRecordingType(SE_NONE); setFinished(true); } else { setFinished(true); consumed = false; } } else { setRecordingType(SE_NONE); setFinished(true); consumed = false; } return consumed; } /** Base implementation handles context (popup) menus. */ protected boolean parseMenuSelection(AWTEvent event) { int id = event.getID(); boolean consumed = true; // press, release, show, [move, show,] press, release // press, [drag, show,] release (FIXME not done) // ACTION_PERFORMED and ITEM_STATE_CHANGED are only // produced by AWT components (wxp/1.4.2) if (id == ActionEvent.ACTION_PERFORMED || id == ItemEvent.ITEM_STATE_CHANGED) { awtMenuTarget = (MenuItem)event.getSource(); invoker = AWT.getInvoker(awtMenuTarget); // If there is no invoker, the selection came from the MenuBar if (invoker != null) { isPopup = true; } Log.debug("AWT menu selection, invoker=" + Robot.toString(invoker)); if (event instanceof ActionEvent) { modifiers = ((ActionEvent)event).getModifiers(); } else { // ItemEvent doesn't report modifiers, so ask use internal // tracking to see if any modifiers are active. modifiers = Robot.getState().getModifiers(); } setFinished(true); } else if (id == MouseEvent.MOUSE_PRESSED) { MouseEvent me = (MouseEvent)event; // On the first press, we haven't yet set the invoker, which // is either a JMenu or the component holding the popup. if (invoker == null) { invoker = me.getComponent(); menux = me.getX(); menuy = me.getY(); modifiers = me.getModifiers(); isPopup = me.isPopupTrigger(); // Must add the listener now, b/c on w32 release/click events // are not generated until *after* the awt popup selection. if (isPopup || (modifiers & AWTConstants.POPUP_MASK) != 0) { hasAWTPopup = addMenuListener(invoker); } // It's possible for a popup menu to be triggered by some // other event (e.g. a button click). Assume that action is // already recorded and simply make note of the appropriate // menu selection. if (invoker instanceof JMenuItem && !(invoker instanceof JMenu)) { menuTarget = invoker; invoker = null; menux = menuy = -1; modifiers = 0; isPopup = true; } } else if (event.getSource() instanceof JMenu) { // ignore } else if (event.getSource() instanceof JMenuItem) { // Click to select the menu item; this will be the second // press event received menuTarget = (Component)event.getSource(); } else { // Mouse press in something other than the menu, assume it was // canceled. // Popup was canceled. Discard subsequent release/click. menuCanceled = true; setStatus("Popup menu selection canceled"); } Log.log("Menu mouse press"); } else if (id == MouseEvent.MOUSE_RELEASED) { MouseEvent me = (MouseEvent)event; // The menu target won't be set until the second mouse press if (menuCanceled) { setRecordingType(SE_NONE); setFinished(true); } else if (menuTarget == null) { // This is the first mouse release if (!isPopup) { isPopup = me.isPopupTrigger(); } } else { if (menuTarget != null) setFinished(true); } Log.log("Menu mouse release"); } else if (id == MouseEvent.MOUSE_CLICKED && isPopup) { // If it was a popup trigger, make sure there was a popup, // otherwise record it as a click. // Note that we won't likely get any events with an AWT popup, so // just assume it was invoked if there is one. if (!hasAWTPopup && AWT.findActivePopupMenu() == null) { setRecordingType(SE_CLICK); target = invoker; x = menux; y = menuy; setFinished(true); } } else { Log.debug("Ignoring " + ComponentTester.toString(event)); } return consumed; } protected boolean parseDrop(AWTEvent event) { int id = event.getID(); switch(id) { case MouseEvent.MOUSE_DRAGGED: case MouseEvent.MOUSE_ENTERED: updateDropTarget((MouseEvent)event); break; case MouseEvent.MOUSE_RELEASED: updateDropTarget((MouseEvent)event); setFinished(true); break; case MouseEvent.MOUSE_MOVED: setFinished(true); break; case MouseEvent.MOUSE_EXITED: // ignore this; wait for the next event to get // a new drop target break; default: if (Log.isClassDebugEnabled(ComponentRecorder.class)) Log.debug("Ignoring " + ComponentTester.toString(event)); } return true; } /** Non-native drags use the drag source as the source for all mouse events * during the drag except for enter/exit events. Native drags use the * parent window as the source for all SunDropTargetEvents. In both cases, * extract the actual target and location relative to the target. */ private void updateDropTarget(MouseEvent me) { dropTarget = SwingUtilities.getDeepestComponentAt(me.getComponent(), me.getX(), me.getY()); Point where = SwingUtilities.convertPoint(me.getComponent(), me.getX(), me.getY(), dropTarget); dropx = where.x; dropy = where.y; } protected boolean parseInputMethod(AWTEvent event) { boolean consumed = true; int id = event.getID(); if (id == KeyEvent.KEY_RELEASED) { KeyEvent ke = (KeyEvent)event; int code = ke.getKeyCode(); switch (code) { case KeyEvent.VK_HALF_WIDTH: // This indicates the input method start (for kanji, anyway) break; case KeyEvent.VK_FULL_WIDTH: // This indicates the input method end (for kanji, anyway) Log.log("Captured " + imText); setFinished(true); break; case KeyEvent.VK_ALT_GRAPH: case KeyEvent.VK_CONTROL: case KeyEvent.VK_SHIFT: case KeyEvent.VK_META: case KeyEvent.VK_ALT: Log.debug("Modifier indicates end of InputMethod"); consumed = true; setFinished(true); break; default: // Consume other key release events, assuming there was no // corresponding key press event. imKeyCodes.add(new Integer(code)); break; } } else if (event instanceof InputMethodEvent) { InputMethodEvent ime = (InputMethodEvent)event; if (id == InputMethodEvent.INPUT_METHOD_TEXT_CHANGED) { if (ime.getCommittedCharacterCount() > 0) { AttributedCharacterIterator iter = ime.getText(); StringBuffer sb = new StringBuffer(); for (char ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) { sb.append(ch); } target = (Component)ime.getSource(); imText.append(sb.toString()); Log.debug("Partial capture " + sb.toString()); } setFinished(true); } } else { consumed = false; setFinished(true); } return consumed; } /** Handle an event. Return whether the event was consumed. */ public boolean parse(AWTEvent event) { if (Log.isClassDebugEnabled(ComponentRecorder.class)) Log.debug("Parsing " + ComponentTester.toString(event) + " as " + TYPES[getRecordingType()]); // Default handling is event consumed, and assume not finished boolean consumed = true; switch(getRecordingType()) { case SE_WINDOW: consumed = parseWindowEvent(event); break; case SE_KEY: consumed = parseKeyEvent(event); break; case SE_CLICK: consumed = parseClick(event); break; case SE_MENU: consumed = parseMenuSelection(event); break; case SE_DROP: consumed = parseDrop(event); break; case SE_IM: consumed = parseInputMethod(event); break; default: Log.warn("Unknown input type: " + getRecordingType()); // error break; } if (isFinished()) { try { Step step = createStep(); setStep(step); Log.log("Semantic event recorded: " + step); } catch(Throwable thr) { String msg = Strings.get("editor.recording.error"); BugReport br = new BugReport(msg, thr); Log.log("Semantic recorder error: " + br.toString()); setStatus(Strings.get("editor.see_console")); setRecordingType(SE_NONE); throw br; } } return consumed; } /** Returns whether the first drag motion event should be consumed. * Derived classes may override this to provide custom drag behavior. * Default behavior saves the drag initiation event by itself. */ protected boolean dragStarted(Component target, int x, int y, int modifiers, MouseEvent dragEvent) { dragSource = target; dragx = x; dragy = y; setFinished(true); return false; } /** Returns the script step generated from the events recorded so far. */ protected Step createStep() { Step step = null; int type = getRecordingType(); Log.debug("Creating step for semantic recorder, type: " + (type >= 0 && type < TYPES.length ? TYPES[getRecordingType()] : String.valueOf(type))); switch(type) { case SE_WINDOW: step = createWindowEvent(window, isClose); break; case SE_MENU: if (awtMenuTarget != null) { if (invoker == null) { MenuContainer mc = awtMenuTarget.getParent(); while (mc instanceof MenuComponent && !(mc instanceof Component)) { mc = ((MenuComponent)mc).getParent(); } if (mc == null) { throw new Error("AWT MenuItem " + awtMenuTarget + " has no Component ancestor"); } invoker = (Component)mc; } step = createAWTMenuSelection(invoker, awtMenuTarget, isPopup); } else if (isPopup) { step = createPopupMenuSelection(invoker, menux, menuy, menuTarget); } else if (menuTarget != null) { step = createMenuSelection(menuTarget); } break; case SE_KEY: { if (keychar != KeyEvent.CHAR_UNDEFINED) { step = createKey(target, keychar, modifiers); } else { step = null; } break; } case SE_CLICK: { step = createClick(target, x, y, modifiers, canMultipleClick() ? clickCount : 1); break; } case SE_DRAG: { step = createDrag(dragSource, dragx, dragy); break; } case SE_DROP: step = createDrop(dropTarget, dropx, dropy); break; case SE_IM: if (imText.length() > 0) step = createInputMethod(target, imKeyCodes, imText.toString()); else { Log.debug("Input method resulted in no text"); step = null; } break; default: step = null; break; } return step; } /** Create a wait for the window show/hide. Use an appropriate identifier string, which might be the name, title, or component reference. */ protected Step createWindowEvent(Window window, boolean isClose) { ComponentReference ref = getResolver().addComponent(window); String method = "assertComponentShowing"; Assert step = new Assert(getResolver(), null, ComponentTester.class.getName(), method, new String[] { ref.getID() }, "true", isClose); step.setWait(true); return step; } protected Step createMenuSelection(Component menuItem) { // For for issue 3411849, record the full path to // the menu item to make sure that lazily loaded // menu items are selected. // Get the owning window, in the case of a heavyweight // popup make sure we go up just one more level Window owningWindow = SwingUtilities.getWindowAncestor(menuItem); if (owningWindow.getClass().getName().startsWith("javax.swing.Popup")) { owningWindow = (Window)owningWindow.getParent(); } ComponentReference cr = getResolver().addComponent(owningWindow); String path = JMenuItemMatcher.getPath((JMenuItem)menuItem); Step step = new Action(getResolver(), null, "actionSelectMenuItem", new String[] { cr.getID(), path }); return step; } protected Step createAWTMenuSelection(Component parent, MenuItem menuItem, boolean isPopup) { ComponentReference ref = getResolver().addComponent(parent); String method = "actionSelectAWTMenuItem"; if (isPopup) method = "actionSelectAWTPopupMenuItem"; // Get a unique path for the MenuItem String path = AWT.getPath(menuItem); // Do a quick search on the invoker for other popups. If there are // duplicates, include the menu item name Step step = new Action(getResolver(), null, method, new String[] { ref.getID(), path }); return step; } protected Step createPopupMenuSelection(Component invoker, int x, int y, Component menuItem) { Step step; if (invoker != null) { ComponentReference inv = getResolver().addComponent(invoker); JMenuItem mi = (JMenuItem)menuItem; String where = getLocationArgument(invoker, x, y); step = new Action(getResolver(), null, "actionSelectPopupMenuItem", new String[] { inv.getID(), where, JMenuItemMatcher.getPath(mi) }, invoker.getClass()); } else { ComponentReference ref = getResolver().addComponent(menuItem); step = new Action(getResolver(), null, "actionSelectMenuItem", new String[] { ref.getID() }); } return step; } protected Step createKey(Component comp, char keychar, int mods) { ComponentReference cr = getResolver().addComponent(comp); // NOTE: Any keys which might have effects as key press/release should // be encoded as a keystroke, rather than a keystring. // NOTE: We encode strings rather than integer values, since the // names are more useful. String code = (String)specialMap.get(String.valueOf(keychar)); if (code != null) { String[] args = mods != 0 ? new String[] { cr.getID(), code, AWT.getKeyModifiers(mods) } : new String[] { cr.getID(), code }; return new Action(getResolver(), null, "actionKeyStroke", args); } return new Action(getResolver(), null, "actionKeyString", new String[] { cr.getID(), String.valueOf(keychar) }); } protected Step createDrop(Component comp, int x, int y) { Step step = null; if (comp != null) { ComponentReference cr = getResolver().addComponent(comp); String where = getLocationArgument(comp, x, y); step = new Action(getResolver(), null, "actionDrop", new String[] { cr.getID(), where }, comp.getClass()); } return step; } protected Step createDrag(Component comp, int x, int y) { ComponentReference ref = getResolver().addComponent(comp); String where = getLocationArgument(comp, x, y); Step step = new Action(getResolver(), null, "actionDrag", new String[] { ref.getID(), where, }, comp.getClass()); return step; } /** Create a click event with the given event information. */ protected Step createClick(Component target, int x, int y, int mods, int count) { Log.debug("creating click"); ComponentReference cr = getResolver().addComponent(target); ArrayList args = new ArrayList(); args.add(cr.getID()); args.add(getLocationArgument(target, x, y)); if ((mods != 0 && mods != MouseEvent.BUTTON1_MASK) || count > 1) { // NOTE: this currently saves POPUP or TERTIARY, rather than // an explicit button 2 or 3. I figure that makes more sense // than a hard coded button number. args.add(AWT.getMouseModifiers(mods)); if (count > 1) { args.add(String.valueOf(count)); } } return new Action(getResolver(), null, "actionClick", (String[])args.toArray(new String[args.size()]), target.getClass()); } protected Step createInputMethod(Component comp, ArrayList codes, String text) { Log.debug("Text length is " + text.length()); ComponentReference ref = getResolver().addComponent(comp); return new Action(getResolver(), null, "actionKeyString", new String[] { ref.getID(), text }); } protected void init(int recordingType) { super.init(recordingType); target = null; forwardedTarget = null; released = false; clickCount = 0; keychar = KeyEvent.CHAR_UNDEFINED; invoker = null; awtMenuTarget = null; isPopup = false; hasAWTPopup = false; menuListener = null; menuTarget = null; menuCanceled = false; dragSource = dropTarget = null; window = null; isClose = false; imKeyCodes.clear(); imText.delete(0, imText.length()); } /** Invoke when end of the semantic event has been seen. */ protected void setFinished(boolean state) { MenuListener listener = null; synchronized(this) { super.setFinished(state); listener = menuListener; menuListener = null; } if (listener != null) listener.dispose(); } private boolean addMenuListener(Component invoker) { PopupMenu[] popups = AWT.getPopupMenus(invoker); if (popups.length > 0) { menuListener = new MenuListener(popups); return true; } return false; } private class MenuListener implements ItemListener { private ArrayList items = new ArrayList(); public MenuListener(PopupMenu[] popups) { for (int i=0;i < popups.length;i++) { addRecursive(popups[i]); } } private void addRecursive(Menu menu) { for (int i=0;i < menu.getItemCount();i++) { MenuItem item = menu.getItem(i); if (item instanceof Menu) addRecursive((Menu)item); else if (item instanceof CheckboxMenuItem) { ((CheckboxMenuItem)item).addItemListener(this); items.add(item); } } } public void itemStateChanged(ItemEvent e) { dispose(); parse(e); } public void dispose() { while (items.size() > 0) { ((CheckboxMenuItem)items.get(0)).removeItemListener(this); items.remove(0); } } } /** Obtain the String representation of the Component-specific location. */ protected String getLocationArgument(Component c, int x, int y) { return getLocation(c, x, y).toString(); } /** Obtain a more precise location than the given coordinate, if * possible. */ protected ComponentLocation getLocation(Component c, int x, int y) { ComponentTester tester = ComponentTester.getTester(c); return tester.getLocation(c, new Point(x, y)); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/ContainerRecorder.java
package abbot.editor.recorder; import abbot.script.Resolver; /** * Record basic semantic events you might find on an Container. <p> */ public class ContainerRecorder extends ComponentRecorder { public ContainerRecorder(Resolver resolver) { super(resolver); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/DialogRecorder.java
package abbot.editor.recorder; import java.awt.*; import abbot.script.*; /** * Record basic semantic events you might find on an Window. <p> */ public class DialogRecorder extends WindowRecorder { public DialogRecorder(Resolver resolver) { super(resolver); } protected Step createResize(Window window, Dimension size) { Step step = null; if (((Dialog)window).isResizable()) { ComponentReference ref = getResolver().addComponent(window); step = new Action(getResolver(), null, "actionResize", new String[] { ref.getID(), String.valueOf(size.width), String.valueOf(size.height), }, Dialog.class); } return step; } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/EventRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.text.MessageFormat; import java.util.*; import javax.swing.*; import abbot.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Action; import abbot.script.Event; import abbot.script.Resolver; import abbot.tester.Robot; import abbot.util.AWT; /** * Provides recording of raw AWT events and high-level semantic events. * This is the main controller for any SemanticRecorder objects. */ // TODO: Are there other instances (cf JInternalFrame) where we'd like this // recorder to be the listener to other events? // TODO: add internal frame listener, re-post events when heard // TODO: discard events on LAF pieces of internal frames // TODO: extract filters as plugins // TODO: run all semantic recorder tests through this class, using canned // event streams instead of robot-generated events; keep the robot-generated // event streams, though, to test whether the stream has changed public class EventRecorder extends Recorder implements SemanticEvents { private static final String ANY_KEY = null; private static final int EITHER = 0; private static final int PRESS = 1; private static final int RELEASE = 2; private boolean captureMotion; private long lastStepTime; ArrayList steps = new ArrayList(); /** Put all built-in recorder classes here. Don't worry though, 'cause if * it doesn't get added here it'll get found dynamically. */ private static final Class[] recorderClasses = { AbstractButton.class, Component.class, Container.class, Dialog.class, Frame.class, JComboBox.class, JComponent.class, JInternalFrame.class, JList.class, JMenuItem.class, JTabbedPane.class, JTable.class, JTree.class, Window.class, }; /** Create a Recorder for use in capturing raw AWTEvents. Indicate * whether mouse motion should be captured, and what semantic event type * to capture. */ public EventRecorder(Resolver resolver, boolean captureMotion) { super(resolver); this.captureMotion = captureMotion; // Install existing semantic recorders for (int i=0;i < recorderClasses.length;i++) { getSemanticRecorder(recorderClasses[i]); } } /** Return the name of the type of GUI action to be recorded. */ public String toString() { return captureMotion ? Strings.get("actions.capture-all") : Strings.get("actions.capture"); } public void start() { super.start(); steps.clear(); MessageFormat mf = new MessageFormat(Strings.get("RecordingX")); setStatus(mf.format(new Object[] { toString() })); lastStepTime = getLastEventTime(); } private boolean isKey(Step step, String code, int type) { boolean match = false; if (step instanceof Event) { Event se = (Event)step; match = "KeyEvent".equals(se.getType()) && (type == EITHER || (type == PRESS && "KEY_PRESSED".equals(se.getKind())) || (type == RELEASE && "KEY_RELEASED".equals(se.getKind()))) && (code == ANY_KEY || code.equals(se.getAttribute(XMLConstants.TAG_KEYCODE))); } return match; } private boolean isKeyString(Step step) { return (step instanceof Action) && ((Action)step).getMethodName().equals("actionKeyString"); } private boolean isKeyStroke(Step step, String keycode) { if (step instanceof Action) { Action action = (Action)step; if (action.getMethodName().equals("actionKeyStroke")) { String[] args = action.getArguments(); return (keycode == ANY_KEY || (args.length > 1 && args[1].equals(keycode)) || (keycode.startsWith("VK_NUMPAD") && args[1].equals("VK_" + keycode.substring(9)))); } } return false; } private void removeTerminalShift() { // Remove the terminal SHIFT keypress if (steps.size() > 0) { Step step = (Step)steps.get(steps.size()-1); while (isKey(step, "VK_SHIFT", PRESS)) { steps.remove(step); if (steps.size() == 0) break; step = (Step)steps.get(steps.size()-1); } } } /** Eliminate redundant modifier keys surrounding keystrokes or * keystrings. */ private void removeExtraModifiers() { setStatus("Removing extra modifiers"); for (int i=0;i < steps.size();i++) { Step step = (Step)steps.get(i); if (isKey(step, ANY_KEY, PRESS)) { Event se = (Event)step; String cs = se.getAttribute(XMLConstants.TAG_KEYCODE); int code = AWT.getKeyCode(cs); boolean remove = false; boolean foundKeyStroke = false; if (AWT.isModifier(code)) { for (int j=i+1;j < steps.size();j++) { Step next = (Step)steps.get(j); if (isKey(next, cs, RELEASE)) { if (foundKeyStroke) { steps.remove(j); remove = true; } break; } else if (isKeyStroke(next, ANY_KEY) || isKeyString(next)) { foundKeyStroke = true; remove = true; } else if (!isKey(next, ANY_KEY, EITHER)) { break; } } } if (remove) { steps.remove(i--); } } } } /** Combine multiple keystroke actions into keystring actions. */ private void coalesceKeyStrings() { setStatus("Coalescing key strings"); for (int i=0;i < steps.size();i++) { Step step = (Step)steps.get(i); if (isKeyString(step)) { int j = i; while (++j < steps.size()) { Step next = (Step)steps.get(j); if (isKeyString(next)) { Action action = (Action)step; String[] args1 = action.getArguments(); String[] args2 = ((Action)next).getArguments(); action.setArguments(new String[] { args1[0], args1[1] + args2[1] }); setStatus("Joining '" + args1[1] + "' and '" + args2[1] + "'"); steps.remove(j--); } else { setStatus("Next step is not a key string: " + next); break; } } } } } /** Eliminate redundant key press/release events surrounding a keytyped * event. */ private void coalesceKeyEvents() { setStatus("Coalescing key events"); for (int i=0;i < steps.size();i++) { Step step = (Step)steps.get(i); if (isKey(step, ANY_KEY, PRESS)) { // In the case of modifiers, remove only if the presence of // the key down/up is redundant. Event se = (Event)step; String cs = se.getAttribute(XMLConstants.TAG_KEYCODE); int code = AWT.getKeyCode(cs); // OSX option modifier should be ignored, since it is used to // generate input method events. boolean isOSXOption = Platform.isOSX() && code == KeyEvent.VK_ALT; if (AWT.isModifier(code) && !isOSXOption) continue; // In the case of non-modifier keys, walk the steps until we // find the key release, then optionally replace the key press // with a keystroke, or remove it if the keystroke was already // recorded. This sorts out jumbled key press/release events. boolean foundKeyStroke = false; boolean foundRelease = false; for (int j=i+1;j < steps.size();j++) { Step next = (Step)steps.get(j); // If we find the release, remove it and this if (isKey(next, cs, RELEASE)) { foundRelease = true; String target = ((Event)next).getComponentID(); steps.remove(j); steps.remove(i); // Add a keystroke only if we didn't find any key // input between press and release (except on OSX, // where the option key generates input method events // which aren't recorded). if (!foundKeyStroke && !isOSXOption) { String mods = se.getAttribute(XMLConstants.TAG_MODIFIERS); String[] args = (mods == null || "0".equals(mods) ? new String[] { target, cs } : new String[] { target, cs, mods}); Step typed = new Action(getResolver(), null, "actionKeyStroke", args); steps.add(i, typed); setStatus("Insert artifical " + typed); } else { setStatus("Removed redundant key events (" + cs + ")"); --i; } break; } else if (isKeyStroke(next, ANY_KEY) || isKeyString(next)) { foundKeyStroke = true; // If it's a numpad keycode, use the numpad // keycode instead of the resulting numeric character // keystroke. if (cs.startsWith("VK_NUMPAD")) { foundKeyStroke = false; steps.remove(j--); } } } // We don't like standalone key presses if (!foundRelease) { setStatus("Removed extraneous key press (" + cs + ")"); steps.remove(i--); } } } } // Required for OS X, remove modifier keys when they're only used to // invoke MB2/3 private boolean pruneButtonModifier = false; private int lastButton = 0; /** Used only on Mac OS, to remove key modifiers that are used to simulate * mouse buttons 2 and 3. Returns whether the event should be ignored. */ private boolean pruneClickModifiers(AWTEvent event) { lastButton = 0; boolean ignoreEvent = false; if (event.getID() == MouseEvent.MOUSE_PRESSED) { MouseEvent me = (MouseEvent)event; int buttons = me.getModifiers() & (MouseEvent.BUTTON2_MASK|MouseEvent.BUTTON3_MASK); pruneButtonModifier = buttons != 0; lastButton = buttons; } else if (event.getID() == KeyEvent.KEY_RELEASED && pruneButtonModifier) { pruneButtonModifier = false; KeyEvent ke = (KeyEvent)event; int code = ke.getKeyCode(); if ((code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_ALT && (lastButton & MouseEvent.BUTTON2_MASK) != 0) || (code == KeyEvent.VK_META && (lastButton & MouseEvent.BUTTON3_MASK) != 0)) { if (steps.size() > 1) { Step step = (Step)steps.get(steps.size()-2); if ((code == KeyEvent.VK_CONTROL && isKey(step, "VK_CONTROL", PRESS) || (code == KeyEvent.VK_ALT && isKey(step, "VK_ALT", PRESS))) || (code == KeyEvent.VK_META && isKey(step, "VK_META", PRESS))) { // might be another one steps.remove(steps.size()-2); pruneButtonModifier = true; ignoreEvent = true; } } } } return ignoreEvent; } /** Ignore any key presses at the end of the recording. */ private void removeTrailingKeyPresses() { while (steps.size() > 0 && isKey((Step)steps.get(steps.size()-1), ANY_KEY, PRESS)) { steps.remove(steps.size()-1); } } /** Remove keypress events preceding and following ActionMap actions. */ private void removeShortcutModifierKeyPresses() { int current = 0; int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); String modifier = AWT.getKeyCode(AWT.maskToKeyCode(mask)); while (current < steps.size()) { Step step = (Step)steps.get(current); if (isKey(step, modifier, PRESS)) { Log.debug("Found possible extraneous modifier"); int keyDown = current; Action action = null; while (++current < steps.size()) { step = (Step)steps.get(current); if (step instanceof Action) { if ("actionActionMap". equals(((Action)step).getMethodName())) { action = (Action)step; continue; } } else if (isKey(step, modifier, RELEASE)) { if (action != null) { Log.debug("Removing extraneous shortcut modifier"); steps.remove(current); steps.remove(keyDown); current = keyDown - 1; } } break; } } ++current; } } /** Insert an arbitrary script step into the currently recorded stream. */ public void insertStep(Step step) { steps.add(step); if ((step instanceof Assert) && ((Assert)step).getMethodName().equals("assertFrameShowing")) { long timeout = ((Assert)step).getTimeout(); long delta = System.currentTimeMillis() - lastStepTime; if (delta > timeout) timeout += delta; ((Assert)step).setTimeout(timeout); } lastStepTime = getLastEventTime(); } /** * Return a sequence containing all the semantic and basic events captured * thus far. */ protected Step createStep() { removeTerminalShift(); coalesceKeyEvents(); removeExtraModifiers(); coalesceKeyStrings(); removeShortcutModifierKeyPresses(); removeTrailingKeyPresses(); return new Sequence(getResolver(), null, steps); } /** The current semantic recorder, if any. */ private SemanticRecorder semanticRecorder = null; /** Return whether an event was generated. Assumes a SemanticRecorder is active. @throws RecordingFailedException if an error was encountered. */ private boolean saveSemanticEvent() throws RecordingFailedException { Log.log("Storing event from current semantic recorder"); try { Step step = semanticRecorder.getStep(); if (step != null) { insertStep(step); setStatus("Added " + step); } else { setStatus("No semantic event found, events skipped"); } semanticRecorder = null; return step != null; } catch(BugReport bug) { throw new RecordingFailedException(bug); } catch(Exception e) { Log.log("Recording failed when saving action: " + e); String msg = Strings.get("editor.recording.exception"); throw new RecordingFailedException(new BugReport(msg, e)); } } public void terminate() throws RecordingFailedException { Log.log("EventRecorder terminated"); if (semanticRecorder != null) { saveSemanticEvent(); } } /** Handle an event. This can either be ignored or contribute to the * recording. * For a given event, if no current semantic recorder is active, * select one based on the event's component. If the semantic recorder * accepts the event, then it is used to consume each subsequent event, * until its recordEvent method returns true, indicating that the semantic * event has completed. */ protected void recordEvent(AWTEvent event) throws RecordingFailedException { // Discard any key/button release events at the start of the recording. if (steps.size() == 0 && event.getID() == KeyEvent.KEY_RELEASED) { Log.log("Ignoring initial release event"); return; } SemanticRecorder newRecorder = null; // Process extraneous key modifiers used to simulate mouse buttons // Only check events while we have no semantic recorder, though, // because we wish to ignore everything between the modifiers if (Platform.isMacintosh() && semanticRecorder == null) { if (pruneClickModifiers(event)) return; } if (semanticRecorder == null) { SemanticRecorder sr = (event.getSource() instanceof Component) ? getSemanticRecorder((Component)event.getSource()) // Use ComponentRecorder for MenuComponents : getSemanticRecorder(Component.class); if (sr.accept(event)) { semanticRecorder = newRecorder = sr; setStatus("Recording semantic event with " + sr); if (event.getSource() instanceof JInternalFrame) { // Ideally, adding an extra listener would be done by the // JInternalFrameRecorder, but the object needs more state // than is available to the recorder (notably to be able // to send events to the primary recorder). If something // else turns up similar to this, then the EventRecorder // should be made available to the semantic recorders. // // Must add a listener, since COMPONENT_HIDDEN is not sent // on JInternalFrame close (1.4.1). JInternalFrame f = (JInternalFrame)event.getSource(); new InternalFrameWatcher(f); } } } // If we're currently recording a semantic event, continue to do so if (semanticRecorder != null) { boolean consumed = semanticRecorder.record(event); boolean finished = semanticRecorder.isFinished(); if (finished) { Log.debug("Semantic recorder is finished"); saveSemanticEvent(); } // If not consumed, need to check for semantic recorder (again) // (but avoid recursing indefinitely) if (!consumed && newRecorder == null) { Log.debug("Event was not consumed, parse it again"); recordEvent(event); } } else { captureRawEvent(event); } } /** Capture the given event as a raw event. */ private void captureRawEvent(AWTEvent event) { // FIXME maybe measure time delay between events and insert delay // events? int id = event.getID(); boolean capture = false; switch(id) { case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: capture = true; break; case KeyEvent.KEY_PRESSED: case KeyEvent.KEY_RELEASED: KeyEvent e = (KeyEvent)event; capture = e.getKeyCode() != KeyEvent.VK_UNDEFINED; if (!capture) { Log.warn("VM bug: no valid keycode on key " + (id == KeyEvent.KEY_PRESSED ? "press" : "release")); } break; case MouseEvent.MOUSE_ENTERED: case MouseEvent.MOUSE_EXITED: case MouseEvent.MOUSE_MOVED: case MouseEvent.MOUSE_DRAGGED: capture = captureMotion; break; default: break; } if (capture) { Event step = new Event(getResolver(), null, event); insertStep(step); setStatus("Added event " + step); } } /** Events of interest when recording all actions. */ public static final long RECORDING_EVENT_MASK = AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK /*| AWTEvent.PAINT_EVENT_MASK*/ /*| AWTEvent.HIERARCHY_EVENT_MASK | AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK*/ | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK // required for non-standard input | AWTEvent.INPUT_METHOD_EVENT_MASK // For java.awt.Choice selections | AWTEvent.ITEM_EVENT_MASK // required to capture MenuItem actions | AWTEvent.ACTION_EVENT_MASK; /** Return the events of interest to this Recorder. */ public long getEventMask() { return RECORDING_EVENT_MASK; } /** Maps component classes to corresponding semantic recorders. */ private HashMap semanticRecorders = new HashMap(); /** Return the semantic recorder for the given component. */ private SemanticRecorder getSemanticRecorder(Component comp) { // FIXME extract into AWT.getLAFParent? // Account for LAF implementations that use a JButton on top // of the combo box if ((comp instanceof JButton) && (comp.getParent() instanceof JComboBox)) { comp = comp.getParent(); } // Account for LAF components of JInternalFrame else if (AWT.isInternalFrameDecoration(comp)) { while (!(comp instanceof JInternalFrame)) comp = comp.getParent(); } return getSemanticRecorder(comp.getClass()); } /** Return the semantic recorder for the given component class. */ private SemanticRecorder getSemanticRecorder(Class cls) { if (!(Component.class.isAssignableFrom(cls))) { throw new IllegalArgumentException("Class must derive from " + "Component"); } SemanticRecorder sr = (SemanticRecorder)semanticRecorders.get(cls); if (sr == null) { Class ccls = Robot.getCanonicalClass(cls); if (ccls != cls) { sr = getSemanticRecorder(ccls); // Additionally cache the mapping from the non-canonical class semanticRecorders.put(cls, sr); return sr; } String cname = Robot.simpleClassName(cls); try { cname = "abbot.editor.recorder." + cname + "Recorder"; Class recorderClass = Class.forName(cname); Constructor ctor = recorderClass.getConstructor(new Class[] { Resolver.class, }); sr = (SemanticRecorder)ctor.newInstance(new Object[] { getResolver() }); sr.addActionListener(getListener()); } catch(InvocationTargetException e) { Log.warn(e); } catch(NoSuchMethodException e) { sr = getSemanticRecorder(cls.getSuperclass()); } catch(InstantiationException e) { sr = getSemanticRecorder(cls.getSuperclass()); } catch(IllegalAccessException iae) { sr = getSemanticRecorder(cls.getSuperclass()); } catch(ClassNotFoundException cnf) { sr = getSemanticRecorder(cls.getSuperclass()); } // Cache the results for future reference semanticRecorders.put(cls, sr); } return sr; } /** Special adapter to catch events on JInternalFrame instances. */ private class InternalFrameWatcher extends AbstractInternalFrameWatcher { public InternalFrameWatcher(JInternalFrame f) { super(f); } protected void dispatch(AWTEvent e) { record(e); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/FileDialogRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.WindowEvent; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import abbot.script.*; /** * Recorder for the java.awt.FileDialog. Since this is a native component and * no java events are generated other than window open/close, the only things * to take note of are the following:<br> * <ul> * <li>Changes to the directory * <li>Changes to the file * <li>Whether the user hits OK or Cancel * </ul> * @author Vrata Venet, European Space Agency, Madrid-Spain ([email protected]) */ public class FileDialogRecorder extends DialogRecorder{ private FileDialog dialog; // must make a ref immediately, since once the dialog is dismissed it // is no longer considered in the hierarchy and prevents us making a ref private ComponentReference ref; private Map newRefs = new HashMap(); private String originalFile; private String originalDir; /** Create a FileDialogRecorder for use in capturing the semantics of a GUI * action. */ public FileDialogRecorder(Resolver resolver) { super(resolver); } protected void init(int type) { super.init(type); dialog = null; ref = null; newRefs.clear(); originalFile = null; originalDir = null; } /** Override the default window parsing to consume everything between dialog open and close. */ protected boolean parseWindowEvent(AWTEvent event) { boolean consumed = true; if (event.getSource() instanceof FileDialog) { if (isOpen(event)) { dialog = (FileDialog)event.getSource(); ref = ComponentReference.getReference(getResolver(), dialog, newRefs); originalFile = dialog.getFile(); originalDir = dialog.getDirectory(); } // The FileDialogTester uses some event listener hacks to set the // correct state on dialog close; make sure we record after that // listener is finished. if (event instanceof FileDialogTerminator) setFinished(true); else if (event.getSource() == dialog && isClose(event)) { AWTEvent terminator = new FileDialogTerminator(dialog, event.getID()); dialog.getToolkit().getSystemEventQueue(). postEvent(terminator); } } return consumed; } /** Create one or more steps corresponding to what was done to the file dialog. If the directory is non-null, the directory was changed. If the file is non-null, the file was accepted. */ protected Step createFileDialogEvents(FileDialog d, String oldDir, String oldFile) { String file = d.getFile(); boolean accepted = file != null; boolean fileChanged = accepted && !file.equals(oldFile); String dir = d.getDirectory(); boolean dirChanged = dir != oldDir && (dir == null || !dir.equals(oldDir)); String desc = d.getMode() == FileDialog.SAVE ? "Save File" : "Load File"; if (accepted) desc += " (" + file + ")"; else desc += " (canceled)"; getResolver().addComponentReference(ref); for (Iterator i=newRefs.values().iterator();i.hasNext();) { getResolver().addComponentReference((ComponentReference)i.next()); } Sequence seq = new Sequence(getResolver(), desc); if (dirChanged) { seq.addStep(new Action(getResolver(), null, "actionSetDirectory", new String[] { ref.getID(), dir }, FileDialog.class)); } if (accepted) { Step accept = new Action(getResolver(), null, "actionAccept", new String[] { ref.getID() }, FileDialog.class); if (fileChanged) { seq.addStep(new Action(getResolver(), null, "actionSetFile", new String[] { ref.getID(), file }, FileDialog.class)); seq.addStep(accept); } else { return accept; } } else { Step cancel = new Action(getResolver(), null, "actionCancel", new String[] { ref.getID() }, FileDialog.class); if (dirChanged) seq.addStep(cancel); else return cancel; } return seq; } protected Step createStep() { if (getRecordingType() == SE_WINDOW) { return createFileDialogEvents(dialog, originalDir, originalFile); } return super.createStep(); } private class FileDialogTerminator extends WindowEvent { public FileDialogTerminator(FileDialog fd, int id) { super(fd, id); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/FrameRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.WindowEvent; import abbot.Log; import abbot.script.*; /** * Record basic semantic events you might find on an Window. <p> */ public class FrameRecorder extends WindowRecorder { private Frame frame; private int newState; public FrameRecorder(Resolver resolver) { super(resolver); } private int WINDOW_STATE_CHANGED = 9 + WindowEvent.WINDOW_FIRST; protected synchronized void init(int recordingType) { super.init(recordingType); frame = null; } /** Additionally handle state change events (1.4 and later). */ protected boolean isWindowEvent(AWTEvent event) { return ((event.getSource() instanceof Frame) && event.getID() == WINDOW_STATE_CHANGED) || super.isWindowEvent(event); } protected boolean parseWindowEvent(AWTEvent event) { int id = event.getID(); boolean consumed = true; if (id == WINDOW_STATE_CHANGED) { frame = (Frame)event.getSource(); newState = getExtendedState(frame); setFinished(true); } else { consumed = super.parseWindowEvent(event); } return consumed; } protected Step createStep() { if (getRecordingType() == SE_WINDOW && frame != null) { return createFrameStateChange(frame, newState); } return super.createStep(); } protected Step createFrameStateChange(Frame frame, int newState) { ComponentReference ref = getResolver().addComponent(frame); return new Action(getResolver(), null, newState == Frame.NORMAL ? "actionNormalize" : "actionMaximize", new String[] { ref.getID() }, Frame.class); } protected Step createResize(Window window, Dimension size) { Step step = null; if (((Frame)window).isResizable()) { ComponentReference ref = getResolver().addComponent(window); step = new Action(getResolver(), null, "actionResize", new String[] { ref.getID(), String.valueOf(size.width), String.valueOf(size.height), }, Frame.class); } return step; } protected int getExtendedState(Frame frame) { try { Integer state = (Integer) Frame.class.getMethod("getExtendedState", new Class[] { }). invoke(frame, new Object[] { }); Log.debug("State is " + state); return state.intValue(); } catch(Exception e) { return frame.getState(); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JComboBoxRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import javax.swing.*; import abbot.Log; import abbot.script.*; import abbot.script.Action; import abbot.tester.*; import abbot.util.AWT; /** * Record basic semantic events you might find on an JComboBox. <p> * <ul> * <li>Select an item by value (toString representation) * <li>Enter a value (if editable) (not done) * </ul> */ public class JComboBoxRecorder extends JComponentRecorder { private JComboBox combo = null; private JComponent popupComponent = null; private int index = -1; private ActionListener listener = null; public JComboBoxRecorder(Resolver resolver) { super(resolver); } /** Make sure we only operate on a JComboBox. */ public boolean accept(AWTEvent event) { if (isClick(event) && getComboBox(event) == null) { return false; } return super.accept(event); } protected void init(int recordingType) { super.init(recordingType); combo = null; popupComponent = null; index = -1; listener = null; } /** Return the JComboBox for the given event, or null if none. */ private JComboBox getComboBox(AWTEvent event) { Component comp = (Component)event.getSource(); // Depends somewhat on LAF; sometimes the combo box is itself the // button, sometimes a panel containing the button. if (comp instanceof javax.swing.JButton) comp = comp.getParent(); if (comp instanceof JComboBox) return (JComboBox)comp; return null; } protected boolean canMultipleClick() { return false; } /** Parse clicks to cancel the recording if we get a click that's not in the JList (or ESC). */ protected boolean parseClick(AWTEvent event) { if (isFinished()) { return false; } // FIXME add key-based activation/termination? boolean consumed = true; if (combo == null) { combo = getComboBox(event); listener = new ActionListener() { public void actionPerformed(ActionEvent ev) { index = combo.getSelectedIndex(); if (!combo.isPopupVisible()) { combo.removeActionListener(listener); setFinished(true); } } }; combo.addActionListener(listener); setStatus("Waiting for selection"); } else if (event.getID() == KeyEvent.KEY_RELEASED && (((KeyEvent)event).getKeyCode() == KeyEvent.VK_SPACE || ((KeyEvent)event).getKeyCode() == KeyEvent.VK_ENTER)) { index = combo.getSelectedIndex(); setFinished(true); } // Cancel via click somewhere else else if (event.getID() == MouseEvent.MOUSE_PRESSED && !AWT.isOnPopup((Component)event.getSource()) && combo != getComboBox(event)) { setFinished(true); consumed = false; } // Cancel via ESC key else if (event.getID() == KeyEvent.KEY_RELEASED && ((KeyEvent)event).getKeyCode() == KeyEvent.VK_ESCAPE) { setStatus("Selection canceled"); setFinished(true); } else { Log.debug("Event ignored"); } JComboBoxTester tester = (JComboBoxTester) ComponentTester.getTester(combo); if (popupComponent == null)// should be possible even if not visible && combo.isPopupVisible()) { popupComponent = tester.findPopupFromUI(combo); } if (isFinished()) { combo.removeActionListener(listener); listener = null; } return consumed; } protected Step createStep() { Step step = null; if (getRecordingType() == SE_CLICK) { step = createSelection(combo, index); } else { step = super.createStep(); } return step; } protected Step createSelection(JComboBox combo, int index) { Step step = null; if (combo != null && index != -1) { ComponentReference cr = getResolver().addComponent(combo); JComboBoxTester tester = (JComboBoxTester) ComponentTester.getTester(combo); String value = tester.getValueAsString(combo, popupComponent, combo.getItemAt(index), index); if (value == null) { step = new Action(getResolver(), null, "actionSelectIndex", new String[] { cr.getID(), String.valueOf(index) }, tester.getTargetClass()); } else { step = new Action(getResolver(), null, "actionSelectItem", new String[] { cr.getID(), value }, tester.getTargetClass()); } } return step; } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JComponentRecorder.java
package abbot.editor.recorder; import java.awt.AWTEvent; import java.awt.event.KeyEvent; import javax.swing.*; import abbot.Log; import abbot.script.*; import abbot.tester.Robot; import java.util.concurrent.Callable; /** * Record basic semantic events you might find on an JComponent. <p> * * Watches for events that trigger an action from the component's action map. * As of 1.3.1, KEY_TYPED and KEY_RELEASED events can trigger an action. */ public class JComponentRecorder extends ContainerRecorder { private JComponent target; private String actionKey; public static final int SE_ACTION_MAP = 20; public JComponentRecorder(Resolver resolver) { super(resolver); } protected void init(int rtype) { super.init(rtype); target = null; actionKey = null; } /** Add handling for JComponent input-mapped actions. */ public boolean accept(AWTEvent event) { boolean accepted; if ((event instanceof KeyEvent) && (event.getSource() instanceof JComponent) && isMappedEvent((KeyEvent)event)) { init(SE_ACTION_MAP); accepted = true; } else { accepted = super.accept(event); } return accepted; } protected javax.swing.Action getAction(KeyEvent ke) { JComponent comp = (JComponent)ke.getComponent(); Object binding = getBindingForKeyEvent(comp, ke); return binding != null ? getActionForComponent(comp, binding) : null; } private Object getBindingForKeyEvent(final JComponent comp, final KeyEvent ke) { return Robot.callAndWait(comp, new Callable<Object>() { @Override public Object call() throws Exception { KeyStroke ks = KeyStroke.getKeyStrokeForEvent(ke); Object binding = comp.getInputMap().get(ks); return binding; } }); } /** * Make sure this happeds o the event queue */ private javax.swing.Action getActionForComponent(final JComponent comp, final Object binding) { return Robot.callAndWait(comp, new Callable<javax.swing.Action>() { @Override public javax.swing.Action call() throws Exception { return comp.getActionMap().get(binding); } }); } protected boolean isMappedEvent(KeyEvent ke) { return getAction(ke) != null; } /** Add handling for JComponent input-mapped actions. */ public boolean parse(AWTEvent event) { boolean consumed = true; switch(getRecordingType()) { case SE_ACTION_MAP: consumed = parseActionMapEvent(event); break; default: consumed = super.parse(event); break; } return consumed; } /** Add handling for JComponent input-mapped actions. */ protected boolean parseActionMapEvent(AWTEvent event) { if (target == null) { target = (JComponent)event.getSource(); Object binding = getBindingForKeyEvent(target,(KeyEvent) event); Log.debug("Binding is " + binding + " (" + binding.getClass() + ")"); if (binding instanceof String) { actionKey = (String)binding; } else { // 1.3 and prior sometimes used the actions themselves // as the key javax.swing.Action action = getActionForComponent(target,binding); actionKey = (String)action.getValue(javax.swing.Action.NAME); } Log.debug("KeyEvent '" + event + "' mapped to " + actionKey); } // Make sure the entire KEY_PRESSED/KEY_TYPED/KEY_RELEASED // sequence is eaten // NOTE: This assumes that no component expects to respond to both the // key shortcut AND accept the key input. if (event.getID() == KeyEvent.KEY_RELEASED) { setFinished(true); } return true; } /** Add handling for JComponent input-mapped actions. */ protected Step createStep() { Step step; switch(getRecordingType()) { case SE_ACTION_MAP: step = createActionMap(target, actionKey); break; default: step = super.createStep(); break; } return step; } /** Create a JComponent input-mapped action invocation. */ protected Step createActionMap(JComponent target, String actionKey) { ComponentReference cr = getResolver().addComponent(target); return new abbot.script.Action(getResolver(), null, "actionActionMap", new String[] { cr.getID(), actionKey }, JComponent.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JInternalFrameRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.ComponentEvent; import javax.swing.JInternalFrame; import javax.swing.event.InternalFrameEvent; import abbot.Log; import abbot.script.*; import abbot.tester.ComponentTester; import abbot.util.AWT; /** * Handle the recording of events related to an internal frame * (JInternalFrame). Like instances of Window, we must insert * waits for the showing and hiding of internal frames. * <P> * NOTE: InternalFrameEvents are not normally posted to the AWT event queue. * @author pickens * @author twall */ public class JInternalFrameRecorder extends JComponentRecorder { private JInternalFrame frame; private String type; private static final String UNKNOWN = "unknown"; private static final String SHOW = "show"; private static final String HIDE = "hide"; private static final String CLOSE = "close"; private static final String ICONIFY = "iconify"; private static final String DEICONIFY = "deiconify"; private static final String MOVE = "move"; private static final String RESIZE = "resize"; public static final int SE_INTERNAL_FRAME = SE_ACTION_MAP + 1; public static final int SE_DECORATION = SE_INTERNAL_FRAME + 1; /** * Constructor for JInternalFrameRecorder. * @param resolver */ public JInternalFrameRecorder(Resolver resolver) { super(resolver); } protected void init(int rtype) { super.init(rtype); frame = null; type = UNKNOWN; } /** * @see abbot.editor.recorder.ComponentRecorder#accept(java.awt.AWTEvent) */ public boolean accept(AWTEvent event) { int id = event.getID(); Log.debug("Source is " + event.getSource()); if (event.getSource() instanceof JInternalFrame) { if (id == ComponentEvent.COMPONENT_SHOWN || id == ComponentEvent.COMPONENT_HIDDEN || id == ComponentEvent.COMPONENT_MOVED || id == ComponentEvent.COMPONENT_RESIZED || id == InternalFrameEvent.INTERNAL_FRAME_CLOSING || id == InternalFrameEvent.INTERNAL_FRAME_ICONIFIED || id == InternalFrameEvent.INTERNAL_FRAME_DEICONIFIED) { init(SE_INTERNAL_FRAME); return true; } } else if (AWT.isInternalFrameDecoration((Component)event.getSource())) { init(SE_DECORATION); return true; } return false; } public boolean parse(AWTEvent event) { boolean consumed = true; switch(getRecordingType()) { case SE_INTERNAL_FRAME: consumed = parseInternalFrameAction(event); break; case SE_DECORATION: setFinished(true); break; default: consumed = super.parse(event); break; } return consumed; } protected boolean parseInternalFrameAction(AWTEvent event) { frame = (JInternalFrame)event.getSource(); switch(event.getID()) { case ComponentEvent.COMPONENT_SHOWN: type = SHOW; break; case ComponentEvent.COMPONENT_HIDDEN: type = HIDE; break; case ComponentEvent.COMPONENT_RESIZED: type = RESIZE; break; case ComponentEvent.COMPONENT_MOVED: type = MOVE; break; case InternalFrameEvent.INTERNAL_FRAME_CLOSING: type = CLOSE; break; case InternalFrameEvent.INTERNAL_FRAME_ICONIFIED: type = ICONIFY; break; case InternalFrameEvent.INTERNAL_FRAME_DEICONIFIED: type = DEICONIFY; break; default: throw new IllegalArgumentException("Unrecognized event: " + event); } setFinished(true); return true; } protected Step createStep() { Step step; switch(getRecordingType()) { case SE_INTERNAL_FRAME: step = createInternalFrameAction(frame, type); break; case SE_DECORATION: step = null; break; default: step = super.createStep(); break; } return step; } protected Step createInternalFrameAction(JInternalFrame target, String type) { ComponentReference ref = getResolver().addComponent(target); if (type == SHOW || type == HIDE) { Assert step = new Assert(getResolver(), null, ComponentTester.class.getName(), "assertComponentShowing", new String[] { ref.getID() }, "true", type == HIDE); step.setWait(true); return step; } else if (type == MOVE) { Point loc = target.getLocation(); return new Action(getResolver(), null, "actionMove", new String[] { ref.getID(), String.valueOf(loc.x), String.valueOf(loc.y) }, JInternalFrame.class); } else if (type == RESIZE) { Dimension size = target.getSize(); return new Action(getResolver(), null, "actionResize", new String[] { ref.getID(), String.valueOf(size.width), String.valueOf(size.height) }, JInternalFrame.class); } else { String action = type == CLOSE ? "actionClose" : ((type == ICONIFY) ? "actionIconify" : "actionDeiconify"); return new Action(getResolver(), null, action, new String[] { ref.getID() }, JInternalFrame.class); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JListRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.InputEvent; import java.util.ArrayList; import javax.swing.JList; import abbot.script.*; /** * Record basic semantic events you might find on an JList. <p> * <ul> * <li>Select a cell * </ul> */ public class JListRecorder extends JComponentRecorder { public JListRecorder(Resolver resolver) { super(resolver); } /** Create a click referencing the String value that was clicked. */ protected Step createClick(Component target, int x, int y, int mods, int count) { JList list = (JList)target; ComponentReference cr = getResolver().addComponent(target); String methodName = "actionSelectRow"; ArrayList args = new ArrayList(); args.add(cr.getID()); args.add(getLocationArgument(list, x, y)); if (list.locationToIndex(new Point(x, y)) == -1) { methodName = "actionClick"; } if ((mods != 0 && mods != InputEvent.BUTTON1_MASK) || count > 1) { methodName = "actionClick"; args.add(abbot.util.AWT.getMouseModifiers(mods)); if (count > 1) { args.add(String.valueOf(count)); } } return new Action(getResolver(), null, methodName, (String[])args.toArray(new String[args.size()]), javax.swing.JList.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JMenuItemRecorder.java
package abbot.editor.recorder; import java.awt.AWTEvent; import abbot.script.Resolver; /** * Override AbstractButton behavior, since we expect to grab a menu selection * instead of a click. */ public class JMenuItemRecorder extends AbstractButtonRecorder { public JMenuItemRecorder(Resolver resolver) { super(resolver); } /** Regular clicks get treated as a menu event. */ protected boolean isMenuEvent(AWTEvent e) { return isClick(e); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JTabbedPaneRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.MouseEvent; import javax.swing.JTabbedPane; import javax.swing.JMenuItem; import javax.swing.plaf.TabbedPaneUI; import abbot.Platform; import abbot.tester.ComponentLocation; import abbot.tester.JTabbedPaneLocation; import abbot.script.*; /** * Record basic semantic events you might find on an JTabbedPane. <p> * <ul> * <li>Select a tab. * </ul> */ public class JTabbedPaneRecorder extends JComponentRecorder { private JTabbedPane tabbedPane; public JTabbedPaneRecorder(Resolver resolver) { super(resolver); } public boolean accept(AWTEvent event) { if (isClick(event)) { MouseEvent me = (MouseEvent)event; JTabbedPane tp = tabbedPane = (JTabbedPane)me.getComponent(); TabbedPaneUI ui = tp.getUI(); int index = ui.tabForCoordinate(tp, me.getX(), me.getY()); if (index != -1) { setStatus("Selecting tab '" + tp.getTitleAt(index)); init(SE_CLICK); return true; } if (Platform.isOSX()) { int xmin = tp.getWidth(); int xmax = 0; int ymin = tp.getHeight(); int ymax = 0; for (int i=0;i < tp.getTabCount();i++) { Rectangle rect = ui.getTabBounds(tp, i); if (rect.x >= 0) { xmin = Math.min(rect.x, xmin); xmax = Math.max(rect.x + rect.width, xmax); ymin = Math.min(rect.y, ymin); ymax = Math.max(rect.y + rect.height, ymax); } } if (me.getX() > xmax && me.getX() < tp.getWidth() - xmin && me.getY() >= ymin && me.getY() <= ymax) { // Expect a popup menu, then let popup menu recording take // over. init(SE_MENU); return true; } } } return super.accept(event); } /** Special case for OSX tab selection from popup menu. */ protected Step createMenuSelection(Component menuItem) { ComponentReference ref = getResolver().addComponent(tabbedPane); ComponentLocation loc = new JTabbedPaneLocation(((JMenuItem)menuItem).getText()); Step step = new Action(getResolver(), null, "actionSelectTab", new String[] { ref.getID(), loc.toString(), }); return step; } /** Parse clicks, notably those that select a tab. */ protected Step createClick(Component target, int x, int y, int mods, int count) { ComponentReference cr = getResolver().addComponent(target); JTabbedPane tp = (JTabbedPane)target; TabbedPaneUI ui = tp.getUI(); int index = ui.tabForCoordinate(tp, x, y); if (index != -1) { // NOTE only tab selections are allowed for when clicking on tabs; // no multi-clicks or other buttons are saved, although nothing // prevents manual generation of such actions. return new Action(getResolver(), null, "actionSelectTab", new String[] { cr.getID(), getLocationArgument(tp, x, y), }, javax.swing.JTabbedPane.class); } return super.createClick(target, x, y, mods, count); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JTableRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JTable; import abbot.script.*; /** * Record basic semantic events you might find on an JTable. <p> * <ul> * <li>Click one or more times in a cell * </ul> */ public class JTableRecorder extends JComponentRecorder { public JTableRecorder(Resolver resolver) { super(resolver); } /** Normally, a click in a table results in selection of a given cell. */ protected Step createClick(Component target, int x, int y, int mods, int count) { JTable table = (JTable)target; Point where = new Point(x, y); int row = table.rowAtPoint(where); int col = table.columnAtPoint(where); ComponentReference cr = getResolver().addComponent(target); String methodName = "actionSelectCell"; ArrayList args = new ArrayList(); args.add(cr.getID()); args.add(getLocationArgument(table, x, y)); if (row == -1 || col == -1) { methodName = "actionClick"; } if ((mods != 0 && mods != MouseEvent.BUTTON1_MASK) || count > 1) { methodName = "actionClick"; args.add(abbot.util.AWT.getMouseModifiers(mods)); if (count > 1) { args.add(String.valueOf(count)); } } return new Action(getResolver(), null, methodName, (String[])args.toArray(new String[args.size()]), javax.swing.JTable.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JTextComponentRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import javax.swing.text.JTextComponent; import abbot.Log; import abbot.script.*; /** * Record basic semantic events you might find on an JTextComponent. <p> */ public class JTextComponentRecorder extends JComponentRecorder { private JTextComponent target; private int startIndex; private int endIndex; public static final int SE_SELECTION = 30; public JTextComponentRecorder(Resolver resolver) { super(resolver); } protected void init(int rtype) { super.init(rtype); target = null; startIndex = -1; endIndex = -1; } /** Don't store the action "default-typed"; store the key event instead. */ protected boolean isMappedEvent(KeyEvent ev) { if (super.isMappedEvent(ev)) { javax.swing.Action action = getAction(ev); return !"default-typed".equals(action.getValue(javax.swing.Action.NAME)); } return false; } /** Coalesce initial click with subsequent drags to produce a * selection. */ protected boolean dragStarted(Component target, int x, int y, int modifiers, MouseEvent dragEvent) { Log.debug("Tracking text selection"); setRecordingType(SE_DROP); this.target = (JTextComponent)target; startIndex = this.target.viewToModel(new Point(x, y)); // Concatenate drag/release with the original click return true; } protected boolean parseDrop(AWTEvent event) { boolean consumed = super.parseDrop(event); if (event.getID() == MouseEvent.MOUSE_DRAGGED) { MouseEvent me = (MouseEvent)event; endIndex = target.viewToModel(me.getPoint()); } else if (event.getID() == MouseEvent.MOUSE_RELEASED) { endIndex = target.viewToModel(((MouseEvent)event).getPoint()); setFinished(true); } return consumed; } protected Step createStep() { Step step; if (getRecordingType() == SE_DROP) { step = createDrop(target, startIndex, endIndex); } else { step = super.createStep(); } return step; } /** The text component click should click on the text index instead of a mouse coordinate. */ protected Step createClick(Component comp, int x, int y, int mods, int count) { if (mods == MouseEvent.BUTTON1_MASK && count == 1) { ComponentReference cr = getResolver().addComponent(comp); JTextComponent tc = (JTextComponent)comp; int index = tc.viewToModel(new Point(x, y)); return new Action(getResolver(), null, "actionClick", new String[] { cr.getID(), String.valueOf(index), }, JTextComponent.class); } return super.createClick(comp, x, y, mods, count); } protected Step createDrop(Component comp, int start, int end) { ComponentReference cr = getResolver().addComponent(comp); return new Action(getResolver(), null, "actionSelectText", new String[] { cr.getID(), String.valueOf(start), String.valueOf(end) }, JTextComponent.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/JTreeRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JTree; import abbot.script.*; import abbot.tester.*; /** * Record basic semantic events you might find on an JTree. <p> * <ul> * <li>Click one or more times in a cell * </ul> */ public class JTreeRecorder extends JComponentRecorder { public JTreeRecorder(Resolver resolver) { super(resolver); } /** Normally, a click in a tree results in selection of a given row. */ protected Step createClick(Component target, int x, int y, int mods, int count) { JTree tree = (JTree)target; ComponentReference cr = getResolver().addComponent(target); String methodName = "actionSelectRow"; ArrayList args = new ArrayList(); args.add(cr.getID()); args.add(getLocationArgument(target, x, y)); if (tree.getRowForLocation(x, y) == -1) { if (JTreeTester.isLocationInExpandControl(tree, x, y) && count == 1) methodName = "actionToggleRow"; else methodName = "actionClick"; } if ((mods != 0 && mods != MouseEvent.BUTTON1_MASK) || count > 1) { methodName = "actionClick"; args.add(abbot.util.AWT.getMouseModifiers(mods)); if (count > 1) { args.add(String.valueOf(count)); } } return new Action(getResolver(), null, methodName, (String[])args.toArray(new String[args.size()]), javax.swing.JTree.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/Recorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import abbot.*; import abbot.i18n.Strings; import abbot.script.*; import abbot.script.Resolver; import abbot.tester.Robot; /** * The <code>Recorder</code> provides a mechanism for recording an event stream and * generating a sequence of script steps from that stream. * <p> * NOTE: when writing a recorder, be very careful not to test for * platform-specific behavior, and avoid being susceptible to * platform-specific bugs. Please make sure the recorder works on both * pointer-focus and click-to-focus window managers, as well as on at least * two platforms.<p> */ public abstract class Recorder { private ActionListener al; private Resolver resolver; private long lastEventTime = 0; /** Create a Recorder for use in converting events into script steps. */ public Recorder(Resolver resolver) { this.resolver = resolver; } /** The recorder supports zero or one listeners. */ public void addActionListener(ActionListener al) { this.al = al; } protected ActionListener getListener() { return al; } /** Start recording a new event stream. */ public void start() { lastEventTime = System.currentTimeMillis(); } /** Indicate the end of the current event input stream. */ public abstract void terminate() throws RecordingFailedException; public long getLastEventTime() { return lastEventTime; } /** Create a step or sequence of steps based on the event stream so far. */ protected abstract Step createStep(); /** Return a step or sequence of steps representing the steps created thus far, or null if none. */ public Step getStep() { return createStep(); } /** Insert an arbitrary step into the recording stream. */ public void insertStep(Step step) { // Default does nothing } /** Process the given event. @throws RecordingFailedException if an error was encountered and recording should discontinue. */ public void record(java.awt.AWTEvent event) throws RecordingFailedException { if (Log.isClassDebugEnabled(getClass())) Log.debug("REC: " + Robot.toString(event)); lastEventTime = System.currentTimeMillis(); try { recordEvent(event); } catch(RecordingFailedException e) { throw e; } catch(Throwable thrown) { Log.log("REC: Unexpected failure: " + thrown); String msg = Strings.get("editor.recording.exception"); throw new RecordingFailedException(new BugReport(msg, thrown)); } } /** Implement this to actually handle the event. @throws RecordingFailedException if an error was encountered and recording should be discontinued. */ protected abstract void recordEvent(AWTEvent event) throws RecordingFailedException; /** Return the events of interest to this Recorder. */ public long getEventMask() { return -1; } /** @return the {@link Resolver} to be used by this <code>Recorder</code>. */ protected Resolver getResolver() { return resolver; } /** Indicate the current recording state, so that the status may be * displayed elsewhere. */ protected void setStatus(String msg) { if (al != null) { ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, msg); al.actionPerformed(event); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/RecordingFailedException.java
package abbot.editor.recorder; import java.lang.annotation.Documented; public class RecordingFailedException extends RuntimeException { public RecordingFailedException(String msg, Throwable cause) { super(msg, cause); } public RecordingFailedException(Throwable thr) { super(thr.getMessage(), thr); } @Deprecated() public Throwable getReason() { return getCause(); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/SemanticEvents.java
package abbot.editor.recorder; /** Provide mnemonic constants for different types of semantic events. */ public interface SemanticEvents { /** No event recognized. */ static final int SE_NONE = -1; /** Any event recognized. */ static final int SE_ANY = 0; /** Window show/hide/move/resize/activate. */ static final int SE_WINDOW = 1; /** Standard or popup menu */ static final int SE_MENU = 2; /** Mouse down/up. */ static final int SE_CLICK = 3; /** Key typed events. */ static final int SE_KEY = 4; /** Generic drag event. Usually invoked from another handler. */ static final int SE_DRAG = 5; /** Generic drop event. Wait for drag to terminate. */ static final int SE_DROP = 6; /** Text input (multiple keystrokes). */ static final int SE_TEXT = 7; /** Input method input (extended character input). */ static final int SE_IM = 8; }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/SemanticRecorder.java
package abbot.editor.recorder; import java.awt.AWTEvent; import java.awt.event.*; import java.util.ArrayList; import abbot.*; import abbot.script.*; import abbot.script.Resolver; /** * Template for recording AWTEvents and converting them into an appropriate * semantic event. The EventRecorder class decides which SemanticRecorder to * use and handles cancel/termination. Implementations should be named * AbstractButtonRecorder, JTableRecorder, etc. The semantic recorders will * be dynamically loaded based on the component receiving a given event * (compare to ComponentTester).<p> * See EventRecorder for implementation details. */ public abstract class SemanticRecorder implements SemanticEvents { private ActionListener al; private Resolver resolver; protected ArrayList events = new ArrayList(); private Step step = null; private int recordingType = SE_NONE; private BugReport bug; private volatile boolean isFinished; /** Create a SemanticRecorder for use in capturing the semantics of a GUI * action. */ public SemanticRecorder(Resolver resolver) { this.resolver = resolver; } /** Supports at most one listener. */ public void addActionListener(ActionListener al) { this.al = al; } public int getRecordingType() { return recordingType; } protected void setRecordingType(int type) { recordingType = type; } protected void init(int recordingType) { events.clear(); step = null; bug = null; setFinished(false); setRecordingType(recordingType); } /** Returns whether this SemanticRecorder wishes to accept the given event * and subsequent events. */ public abstract boolean accept(AWTEvent event); /** * Handle an event. Returns whether the event was consumed. */ final public boolean record(java.awt.AWTEvent event) { if (!isFinished()) { try { if (parse(event)) { // Maintain a list of all events parsed for future // reference events.add(event); return true; } } catch(BugReport br) { setFinished(true); bug = br; } } return false; } /** Handle an event. Return true if the event has been consumed. * Returning false usually means that isFinished() will return true. */ public abstract boolean parse(AWTEvent event); /** Return the Resolver to be used by this recorder. */ protected Resolver getResolver() { return resolver; } /** Returns the script step generated from the events recorded so far. If * no real action resulted, may return null (for example, a mouse press on * a button which releases outside the button). */ public synchronized Step getStep() throws BugReport { if (bug != null) throw bug; if (step == null) { step = createStep(); } return step; } /** Create a step based on the events received thus far. Returns null if * no semantic event or an imcomplete event has been detected. */ protected abstract Step createStep(); /** * Add the given step. Should be used when the recorder detects a * complete semantic event sequence. After this point, the recorder will * no longer accept events. */ protected synchronized void setStep(Step newStep) { events.clear(); step = newStep; } /** Return whether this recorder has finished recording the current * semantic event. */ public boolean isFinished() { return isFinished; } /** Invoke when end of the semantic event has been seen. */ protected synchronized void setFinished(boolean state) { isFinished = state; } /** Indicate the current recording state, so that the status may be * displayed elsewhere. */ protected void setStatus(String msg) { if (al != null) { ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, msg); al.actionPerformed(event); } } /* public String toString() { return getClass().toString(); } */ }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/recorder/WindowRecorder.java
package abbot.editor.recorder; import java.awt.*; import java.awt.event.*; import abbot.script.*; import abbot.tester.WindowTracker; /** * Record basic semantic events you might find on an Window. <p> */ public class WindowRecorder extends ContainerRecorder { private Window window; private Point where; private Dimension size; public WindowRecorder(Resolver resolver) { super(resolver); } protected void init(int recordingType) { super.init(recordingType); window = null; where = null; size = null; } protected boolean isWindowEvent(AWTEvent event) { return (event.getSource() instanceof Window // Checking for window ready avoids picking up // spurious resize events on first window show && ((Window)event.getSource()).isShowing() && WindowTracker.getTracker(). isWindowReady((Window)event.getSource()) && (event.getID() == ComponentEvent.COMPONENT_MOVED || event.getID() == ComponentEvent.COMPONENT_RESIZED)) || event.getID() == WindowEvent.WINDOW_CLOSING || super.isWindowEvent(event); } protected boolean parseWindowEvent(AWTEvent event) { int id = event.getID(); boolean consumed = true; if (id == ComponentEvent.COMPONENT_MOVED) { window = (Window)event.getSource(); where = window.getLocationOnScreen(); setFinished(true); } else if (id == ComponentEvent.COMPONENT_RESIZED) { window = (Window)event.getSource(); size = window.getSize(); setFinished(true); } else if (id == WindowEvent.WINDOW_CLOSING) { window = (Window)event.getSource(); setFinished(true); } else { consumed = super.parseWindowEvent(event); } return consumed; } protected Step createStep() { Step step; if (getRecordingType() == SE_WINDOW && window != null) { if (where != null) { step = createMove(window, where); } else if (size != null) { step = createResize(window, size); } else { step = createClose(window); } } else { step = super.createStep(); } return step; } protected Step createClose(Window window) { ComponentReference ref = getResolver().addComponent(window); return new Action(getResolver(), null, "actionClose", new String[] { ref.getID() }, Window.class); } protected Step createMove(Window window, Point where) { // If the window is not yet showing, ignore it if (!WindowTracker.getTracker().isWindowReady(window)) return null; ComponentReference ref = getResolver().addComponent(window); return new Action(getResolver(), null, "actionMove", new String[] { ref.getID(), String.valueOf(where.x), String.valueOf(where.y) }, Window.class); } protected Step createResize(Window window, Dimension size) { // If the window is not yet showing, ignore it if (!window.isShowing()) return null; ComponentReference ref = getResolver().addComponent(window); return new Action(getResolver(), null, "actionResize", new String[] { ref.getID(), String.valueOf(size.width), String.valueOf(size.height), }, Window.class); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/AbstractAnimatedIcon.java
package abbot.editor.widgets; import java.awt.Component; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.ref.WeakReference; import javax.swing.Timer; /** Provide animation of auto-generated animations. Makes use of the repaint * tracking structure established by {@link AnimatedIcon}. */ public abstract class AbstractAnimatedIcon extends AnimatedIcon { private static final int DEFAULT_INTERVAL = 1000/24; private Timer timer; private int repaintInterval; private int frame; private int frameCount; protected AbstractAnimatedIcon() { this(0); } protected AbstractAnimatedIcon(int frameCount) { this(frameCount, DEFAULT_INTERVAL); } protected AbstractAnimatedIcon(int frameCount, int interval) { this.frameCount = frameCount; setFrameInterval(interval); } /** Ensure the timer stops running, so it, too can be GC'd. */ protected void finalize() { timer.stop(); } /** Setting a frame interval of zero stops automatic animation. */ public void setFrameInterval(int interval) { repaintInterval = interval; if (interval != 0) { if (timer == null) { timer = new Timer(interval, new AnimationUpdater(this)); timer.setRepeats(true); } else { timer.setDelay(interval); } } else if (timer != null) { timer.stop(); timer = null; } } public int getFrameInterval() { return repaintInterval; } /** Returns the total number of frames. */ public int getFrameCount() { return frameCount; } /** Advance to the next animation frame. */ public void nextFrame() { setFrame(getFrame() + 1); } /** Set the current animation frame number. */ public void setFrame(int f) { this.frame = f; if (frameCount != 0) frame = frame % frameCount; repaint(); } /** Returns the current animation frame number. */ public int getFrame() { return frame; } /** Implement this method to paint the icon. */ protected abstract void paintFrame(Component c, Graphics g, int x, int y); public abstract int getIconWidth(); public abstract int getIconHeight(); protected synchronized void registerRepaintArea(Component c, int x, int y, int w, int h) { if (timer != null && !timer.isRunning()) { timer.start(); } super.registerRepaintArea(c, x, y, w, h); } private static class AnimationUpdater implements ActionListener { private WeakReference ref; public AnimationUpdater(AbstractAnimatedIcon icon) { this.ref = new WeakReference(icon); } public void actionPerformed(ActionEvent e) { AbstractAnimatedIcon icon = (AbstractAnimatedIcon)ref.get(); if (icon != null) { icon.nextFrame(); } } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/AbstractComponentDecorator.java
package abbot.editor.widgets; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JComponent; import javax.swing.JLayeredPane; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; import javax.swing.border.LineBorder; /** Provide a method for consistently augmenting the appearance of a given * component by painting something on it <i>after</i> the component itself * gets painted. If not explicitly removed via {@link #dispose}, an instance * of this object will live as long as its target component.<p> * By default, the decorator matches the location and size of the decorated * component, but the bounds can be adjusted by overriding * {@link #getDecorationBounds()}. The {@link #synch()} method should be called * whenever the bounds returned by {@link #getDecorationBounds()} would change. * <p> * The decoration is clipped to the bounds set on the decoration, which does * not necessarily need to be the same as the decorated component's bounds. The * decoration may extend beyond the decorated component bounds, or it may be * reduced to a smaller region. */ // NOTE: OSX 1.6 lacks hierarchy events that w32 sends on layer changes // TODO: should probably do some locking on Component.getTreeLock() // TODO: synch underlying cursor when decorator covers more than // one component; the cursor should change if the decoration exceeds the // component's bounds (add mouse listener?) public abstract class AbstractComponentDecorator { public static final Rectangle DEFAULT_BOUNDS = null; public static final int TOP = 0; // Disabled for now, since it doesn't work properly private static final int BOTTOM = -1; /** Account for the difference between the decorator actual origin * and the logical origin we want to pass to the {@link #paint} method. */ private Point originOffset = new Point(0, 0); private Painter painter; private JComponent component; private Container parent; private Component layerRoot; private Listener listener; private int layerOffset; private int position; private Rectangle bounds; /** Create a decorator for the given component. */ public AbstractComponentDecorator(JComponent c) { this(c, 1); } /** Create a decorator for the given component, indicating the layer * offset from the target component. Negative values mean the decoration * is painted <em>before</em> the target component is painted. */ public AbstractComponentDecorator(JComponent c, int layerOffset) { this(c, layerOffset, TOP); } /** Create a decorator with the given position within its layer. * Use {@link #TOP} to cover other decorations, or {@link #BOTTOM} * to be covered by other decorations.<p> * WARNING: BOTTOM doesn't currently work, probably a JLayeredPane bug * in either the code or documentation. * @see JLayeredPane */ public AbstractComponentDecorator(JComponent c, int layerOffset, int position) { component = c; this.layerOffset = layerOffset; this.position = position; this.bounds = DEFAULT_BOUNDS; parent = c.getParent(); painter = new Painter(); listener = new Listener(); component.addHierarchyListener(listener); component.addComponentListener(listener); attach(); } /** Set the text to be displayed when the mouse is over the decoration. * @see JComponent#setToolTipText(String) */ public void setToolTipText(String text) { painter.setToolTipText(text); } /** Return the currently set default tooltip text. * @see JComponent#setToolTipText */ public String getToolTipText() { return painter.getToolTipText(); } /** Provide for different tool tips depending on the actual location * over the decoration. Note that if you <em>only</em> override this * method, you must also invoke {@link #setToolTipText(String)} with * a non-<span class="javakeyword">null</span> argument. * @see JComponent#getToolTipText(MouseEvent) */ public String getToolTipText(MouseEvent e) { return getToolTipText(); } /** Indicate whether the decoration is showing. Its painter must be * visible and showing (showing depends on window ancestor). */ public boolean isShowing() { return painter.isShowing(); } /** Indicate whether any of the decoration is visible. The decoration * may be clipped by ancestor scroll panes or by being moved outside * if the visible region of its parent window. */ public boolean isVisible() { // The isVisible method appears to have altered it functoinality, so instead we // are going to perform an intersection of the bounds and painter bounds to find out // if the component is visibile or not. Rectangle componentBounds = component.getBounds(); Rectangle painterBounds = painter.getBounds(); Rectangle result = new Rectangle(); Rectangle.intersect(componentBounds, painterBounds, result); return !result.isEmpty() && painter.isVisible(); // Won't be visible if painter disabled } /** Use this to change the visibility of the decoration. */ public void setVisible(boolean visible) { painter.setVisible(visible); } protected void attach() { if (layerRoot != null) { layerRoot.removePropertyChangeListener(listener); layerRoot = null; } RootPaneContainer rpc = (RootPaneContainer) SwingUtilities.getAncestorOfClass(RootPaneContainer.class, component); if (rpc != null && SwingUtilities.isDescendingFrom(component, rpc.getLayeredPane())) { JLayeredPane lp = rpc.getLayeredPane(); Component layeredChild = component; int layer = JLayeredPane.DRAG_LAYER.intValue(); if (this instanceof BackgroundPainter) { layer = ((BackgroundPainter)this).layer; painter.setDecoratedLayer(layer); } else if (layeredChild == lp) { // Is the drag layer the best layer to use when decorating // the layered pane? painter.setDecoratedLayer(layer); } else { while (layeredChild.getParent() != lp) { layeredChild = layeredChild.getParent(); } int base = lp.getLayer(layeredChild); // NOTE: JLayeredPane doesn't properly repaint an overlapping // child when an obscured child calls repaint() if the two // are in the same layer, so we use the next-higher layer // instead of simply using a different position within the // layer. layer = base + layerOffset; if (layerOffset < 0) { BackgroundPainter bp = (BackgroundPainter) lp.getClientProperty(BackgroundPainter.key(base)); if (bp == null) { bp = new BackgroundPainter(lp, base); } } painter.setDecoratedLayer(base); layerRoot = layeredChild; layerRoot.addPropertyChangeListener(listener); } lp.add(painter, new Integer(layer), position); } else { // Always detach when the target component's window is null // or is not a suitable container, // otherwise we might prevent GC of the component Container parent = painter.getParent(); if (parent != null) { parent.remove(painter); } } // Track size changes in the decorated component's parent if (parent != null) { parent.removeComponentListener(listener); } parent = component.getParent(); if (parent != null) { parent.addComponentListener(listener); } synch(); } /** Ensure the size of the decorator matches the current * decoration bounds with appropriate clipping to viewports. */ protected void synch() { Container painterParent = painter.getParent(); if (painterParent != null) { Rectangle decorated = getDecorationBounds(); Rectangle clipRect = clipDecorationBounds(decorated); Point pt = SwingUtilities.convertPoint(component, clipRect.x, clipRect.y, painterParent); if (clipRect.width <= 0 || clipRect.height <= 0) { setPainterBounds(-1, -1, 0, 0); setVisible(false); } else { setPainterBounds(pt.x, pt.y, clipRect.width, clipRect.height); setVisible(true); } painterParent.repaint(); } } /** Adjust the painting offsets and size of the decoration to * account for ancestor clipping. This might be due to scroll panes * or having the decoration lie outside the parent layered pane. */ protected Rectangle clipDecorationBounds(Rectangle decorated) { // Amount we have to translate the Graphics context originOffset.x = decorated.x; originOffset.y = decorated.y; // If the the component is obscured (by a viewport or some // other means), use the painter bounds to clip to the visible // bounds. Doing may change the actual origin, so adjust our // origin offset accordingly Rectangle visible = getClippingRect(component, decorated); Rectangle clipRect = decorated.intersection(visible); if (decorated.x < visible.x) originOffset.x += visible.x - decorated.x; if (decorated.y < visible.y) originOffset.y += visible.y - decorated.y; return clipRect; } /** Return any clipping rectangle detected above the given component, * in the coordinate space of the given component. The given rectangle * is desired to be visible. */ private Rectangle getClippingRect(Container component, Rectangle desired) { Rectangle visible = component instanceof JComponent ? ((JComponent)component).getVisibleRect() : new Rectangle(0, 0, component.getWidth(), component.getHeight()); Rectangle clip = new Rectangle(desired); if (desired.x >= visible.x && desired.y >= visible.y && desired.x + desired.width <= visible.x + visible.width && desired.y + desired.height <= visible.y + visible.height) { // desired rect is within the current clip rect } else if (component.getParent() != null) { // Only apply the clip if it is actually smaller than the // component's visible area if (component != painter.getParent() && (visible.x > 0 || visible.y > 0 || visible.width < component.getWidth() || visible.height < component.getHeight())) { // Don't alter the original rectangle desired = new Rectangle(desired); desired.x = Math.max(desired.x, visible.x); desired.y = Math.max(desired.y, visible.y); desired.width = Math.min(desired.width, visible.x + visible.width - desired.x); desired.height = Math.min(desired.height, visible.y + visible.height - desired.y); // Check for clipping further up the hierarchy desired.x += component.getX(); desired.y += component.getY(); clip = getClippingRect(component.getParent(), desired); clip.x -= component.getX(); clip.y -= component.getY(); } } return clip; } /** Return the bounds, relative to the decorated component, of the * decoration. The default covers the entire component. Note that * this method will be called from the constructor, so be careful * when overriding and referencing derived class state. */ protected Rectangle getDecorationBounds() { return bounds != DEFAULT_BOUNDS ? bounds : new Rectangle(0, 0, component.getWidth(), component.getHeight()); } /** Change the bounds of the decoration, relative to the decorated * component. The special value {@link #DEFAULT_BOUNDS} means the bounds * will track the component bounds. */ public void setDecorationBounds(Rectangle bounds) { if (bounds == DEFAULT_BOUNDS) { this.bounds = bounds; } else { this.bounds = new Rectangle(bounds); } synch(); } /** Change the bounds of the decoration, relative to the decorated * component. */ public void setDecorationBounds(int x, int y, int w, int h) { setDecorationBounds(new Rectangle(x, y, w, h)); } protected void setPainterBounds(int x, int y, int w, int h) { painter.setLocation(x, y); painter.setSize(w, h); repaint(); } /** Returns the decorated component. */ protected JComponent getComponent() { return component; } /** Returns the component used to paint the decoration and optionally * track events. */ protected JComponent getPainter() { return painter; } /** Set the cursor to appear anywhere over the decoration bounds. * If null, the cursor of the decorated component will be used. */ public void setCursor(Cursor cursor) { painter.setCursor(cursor); } /** Force a refresh of the underlying component and its decoration. */ public void repaint() { JLayeredPane p = (JLayeredPane)painter.getParent(); if (p != null) { p.repaint(painter.getBounds()); } } /** Stop decorating. */ public void dispose() { if (component == null) return; // Disposal must occur on the EDT if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { dispose(); }}); return; } component.removeHierarchyListener(listener); component.removeComponentListener(listener); if (parent != null) { parent.removeComponentListener(listener); parent = null; } if (layerRoot != null) { layerRoot.removePropertyChangeListener(listener); layerRoot = null; } Container painterParent = painter.getParent(); if (painterParent != null) { Rectangle bounds = painter.getBounds(); painterParent.remove(painter); painterParent.repaint(bounds.x, bounds.y, bounds.width, bounds.height); } component.repaint(); component = null; } /** Define the decoration's appearance. The point (0,0) represents * the upper left corner of the decorated component. * The default clip mask will be the extents of the decoration bounds, as * indicated by {@link #getDecorationBounds()}, which defaults to the * decorated component bounds. */ public abstract void paint(Graphics g); public String toString() { return super.toString() + " on " + getComponent(); } private static Field nComponents; static { try { nComponents = Container.class.getDeclaredField("ncomponents"); nComponents.setAccessible(true); } catch(Exception e) { nComponents = null; } } private static boolean useSimpleBackground() { return nComponents == null; } /** Used to hook into the Swing painting and event architecture. */ protected class Painter extends JComponent { private int base; private Cursor cursor; { setFocusable(false); } public JComponent getComponent() { return AbstractComponentDecorator.this.getComponent(); } public void setDecoratedLayer(int base) { this.base = base; } public int getDecoratedLayer() { return base; } public boolean isBackgroundDecoration() { return layerOffset < 0; } /** Set the cursor to something else. If null, the cursor of * the decorated component will be used. */ public void setCursor(Cursor cursor) { Cursor oldCursor = getCursor(); // Make sure the cursor actually changed, otherwise // we get cursor flicker (notably on w32 title bars) if (oldCursor == null && cursor != null || oldCursor != null && !oldCursor.equals(cursor)) { this.cursor = cursor; super.setCursor(cursor); } } /** Returns the cursor of the decorated component, or the last * cursor set by {@link #setCursor}. */ public Cursor getCursor() { return cursor != null ? cursor : component.getCursor(); } /** Delegate to the containing decorator to perform the paint. */ public void paintComponent(Graphics g) { if (!component.isShowing()) return; Graphics g2 = g.create(); g2.translate(-originOffset.x, -originOffset.y); AbstractComponentDecorator.this.paint(g2); g2.dispose(); } /** Provide a decorator-specific tooltip, shown when within the * decorator's bounds. */ public String getToolTipText(MouseEvent e) { return AbstractComponentDecorator.this.getToolTipText(e); } public String toString() { return "Painter for " + AbstractComponentDecorator.this; } } /** Provides a shared background painting mechanism for multiple * decorations. This ensures that the background is only painted once * if more than one background decorator is applied. */ private static class BackgroundPainter extends AbstractComponentDecorator { private static String key(int layer) { return "backgroundPainter for layer " + layer; } private String key; private int layer; public BackgroundPainter(JLayeredPane p, int layer) { super(p, 0, TOP); this.layer = layer; key = key(layer); p.putClientProperty(key, this); } private int hideChildren(Container c) { if (c == null) return 0; int value = c.getComponentCount(); try { nComponents.set(c, new Integer(0)); } catch(Exception e) { return c.getComponentCount(); } return value; } private void restoreChildren(Container c, int count) { if (c != null) { try { nComponents.set(c, new Integer(count)); } catch(Exception e) { } } } private void paintBackground(Graphics g, Component parent, JComponent jc) { int x = jc.getX(); int y = jc.getY(); int w = jc.getWidth(); int h = jc.getHeight(); paintBackground(g.create(x, y, w, h), jc); } private void paintBackground(Graphics g, JComponent jc) { if (jc.isOpaque()) { if (useSimpleBackground()) { g.setColor(jc.getBackground()); g.fillRect(0, 0, jc.getWidth(), jc.getHeight()); } else { int count = hideChildren(jc); boolean db = jc.isDoubleBuffered(); if (db) jc.setDoubleBuffered(false); jc.paint(g); if (db) jc.setDoubleBuffered(true); restoreChildren(jc, count); } } Component[] kids = jc.getComponents(); for (int i=0;i < kids.length;i++) { if (kids[i] instanceof JComponent) { paintBackground(g, jc, (JComponent)kids[i]); } } } private List findOpaque(Component root) { List list = new ArrayList(); if (root.isOpaque() && root instanceof JComponent) { list.add(root); ((JComponent)root).setOpaque(false); } if (root instanceof Container) { Component[] kids = ((Container)root).getComponents(); for (int i=0;i < kids.length;i++) { list.addAll(findOpaque(kids[i])); } } return list; } private List findDoubleBuffered(Component root) { List list = new ArrayList(); if (root.isDoubleBuffered() && root instanceof JComponent) { list.add(root); ((JComponent)root).setDoubleBuffered(false); } if (root instanceof Container) { Component[] kids = ((Container)root).getComponents(); for (int i=0;i < kids.length;i++) { list.addAll(findDoubleBuffered(kids[i])); } } return list; } private void paintForeground(Graphics g, JComponent jc) { List opaque = findOpaque(jc); List db = findDoubleBuffered(jc); jc.paint(g); for (Iterator i=opaque.iterator();i.hasNext();) { ((JComponent)i.next()).setOpaque(true); } for (Iterator i=db.iterator();i.hasNext();) { ((JComponent)i.next()).setDoubleBuffered(true); } } /** Walk the list of "background" decorators and paint them. */ public void paint(Graphics g) { JLayeredPane lp = (JLayeredPane)getComponent(); Component[] kids = lp.getComponents(); // Construct an area of the intersection of all decorators Area area = new Area(); List painters = new ArrayList(); List components = new ArrayList(); for (int i=kids.length-1;i >=0; i--) { if (kids[i] instanceof Painter) { Painter p = (Painter)kids[i]; if (p.isBackgroundDecoration() && p.getDecoratedLayer() == layer && p.isShowing()) { painters.add(p); area.add(new Area(p.getBounds())); } } else if (lp.getLayer(kids[i]) == layer && kids[i] instanceof JComponent) { components.add(kids[i]); } } if (painters.size() == 0) { dispose(); return; } g.setClip(area); // Paint background for that area for (Iterator i=components.iterator();i.hasNext();) { JComponent c = (JComponent)i.next(); paintBackground(g, lp, c); } // Paint the bg decorators for (Iterator i=painters.iterator();i.hasNext();) { Painter p = (Painter)i.next(); p.paint(g.create(p.getX(), p.getY(), p.getWidth(), p.getHeight())); } // Paint foreground for the area for (Iterator i=components.iterator();i.hasNext();) { JComponent c = (JComponent)i.next(); paintForeground(g.create(c.getX(), c.getY(), c.getWidth(), c.getHeight()), c); } } public void dispose() { getComponent().putClientProperty(key, null); super.dispose(); } public String toString() { return key + " on " + getComponent(); } } /** Tracks changes to component configuration. */ private final class Listener extends ComponentAdapter implements HierarchyListener, PropertyChangeListener { // NOTE: OSX (1.6) doesn't generate these the same as w32 public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { attach(); } } public void propertyChange(PropertyChangeEvent e) { if (JLayeredPane.LAYER_PROPERTY.equals(e.getPropertyName())) { attach(); } } public void componentMoved(ComponentEvent e) { // FIXME figure out why attach works and synch doesn't // when painting a selection marquee over a decorated background attach(); } public void componentResized(ComponentEvent e) { // FIXME figure out why attach works and synch doesn't // when painting a selection marquee over a decorated background attach(); } public void componentHidden(ComponentEvent e) { setVisible(false); } public void componentShown(ComponentEvent e) { setVisible(true); } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/AnimatedIcon.java
package abbot.editor.widgets; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.geom.AffineTransform; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javax.swing.CellRendererPane; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import sun.awt.image.GifImageDecoder; import sun.awt.image.ImageDecoder; import sun.awt.image.InputStreamImageSource; import abbot.Log; /** Ensures animated icons are properly handled within objects that use * renderers within a {@link CellRendererPane} to render the icon. Keeps * a list of repaint rectangles to be used to queue repaint requests when * the animated icon indicates an update. The set of repaint rectangles * is cleared after the repaint requests are queued. * @author twall */ public class AnimatedIcon implements Icon { /** Cache results to reduce decoding overhead. */ private static Map decoded = new WeakHashMap(); /** Returns whether the given icon is an animated GIF. */ public static boolean isAnimated(Icon icon) { if (icon instanceof ImageIcon) { Image image = ((ImageIcon)icon).getImage(); if (image != null) { // Quick check for commonly-occurring animated GIF comment Object comment = image.getProperty("comment", null); if (String.valueOf(comment).startsWith("GifBuilder")) return true; // Check cache of already-decoded images if (decoded.containsKey(image)) { return Boolean.TRUE.equals(decoded.get(image)); } InputStream is = null; try { URL url = new URL(icon.toString()); is = url.openConnection().getInputStream(); } catch(MalformedURLException e) { // Not from a URL, ignore it } catch(IOException e) { Log.warn("Failed to load from " + icon, e); } if (is == null) { ImageProducer p = image.getSource(); try { // Beware: lots of hackery to obtain the image input stream // Be sure to catch security exceptions if (p instanceof InputStreamImageSource) { Method m = InputStreamImageSource.class.getDeclaredMethod("getDecoder", null); m.setAccessible(true); ImageDecoder d = (ImageDecoder)m.invoke(p, null); if (d instanceof GifImageDecoder) { GifImageDecoder gd = (GifImageDecoder)d; Field input = ImageDecoder.class.getDeclaredField("input"); input.setAccessible(true); is = (InputStream)input.get(gd); } } } catch(Exception e) { Log.warn("Can't decode from image producer: " + p, e); } } if (is != null) { GifDecoder decoder = new GifDecoder(); decoder.read(is); boolean animated = decoder.getFrameCount() > 1; decoded.put(image, Boolean.valueOf(animated)); return animated; } } return false; } return icon instanceof AnimatedIcon; } private ImageIcon original; private Set repaints = new HashSet(); /** For use by derived classes that don't have an original. */ protected AnimatedIcon() { } /** Create an icon that takes care of animating itself on components * which use a CellRendererPane. */ public AnimatedIcon(ImageIcon original) { this.original = original; new AnimationObserver(this, original); } /** Trigger a repaint on all components on which we've previously been * painted. */ protected synchronized void repaint() { for (Iterator i=repaints.iterator();i.hasNext();) { ((RepaintArea)i.next()).repaint(); } repaints.clear(); } public int getIconHeight() { return original.getIconHeight(); } public int getIconWidth() { return original.getIconWidth(); } public synchronized void paintIcon(Component c, Graphics g, int x, int y) { paintFrame(c, g, x, y); if (c != null) { int w = getIconWidth(); int h = getIconHeight(); AffineTransform tx = ((Graphics2D)g).getTransform(); w = (int)(w * tx.getScaleX()); h = (int)(h * tx.getScaleY()); registerRepaintArea(c, x, y, w, h); } } protected void paintFrame(Component c, Graphics g, int x, int y) { original.paintIcon(c, g, x, y); } /** Register repaint areas, which get get cleared once the repaint request * has been queued. */ protected void registerRepaintArea(Component c, int x, int y, int w, int h) { repaints.add(new RepaintArea(c, x, y, w, h)); } /** Object to encapsulate an area on a component to be repainted. */ private class RepaintArea { public int x, y, w, h; public Component component; private int hashCode; public RepaintArea(Component c, int x, int y, int w, int h) { Component ancestor = findNonRendererAncestor(c); if (ancestor != c) { Point pt = SwingUtilities.convertPoint(c, x, y, ancestor); c = ancestor; x = pt.x; y = pt.y; } this.component = c; this.x = x; this.y = y; this.w = w; this.h = h; String hash = String.valueOf(x) + "," + y + ":" + c.hashCode(); this.hashCode = hash.hashCode(); } /** Find the first ancestor <em>not</em> descending from a * {@link CellRendererPane}. */ private Component findNonRendererAncestor(Component c) { Component ancestor = SwingUtilities.getAncestorOfClass(CellRendererPane.class, c); if (ancestor != null && ancestor != c && ancestor.getParent() != null) { c = findNonRendererAncestor(ancestor.getParent()); } return c; } /** Queue a repaint request for this area. */ public void repaint() { component.repaint(x, y, w, h); } public boolean equals(Object o) { if (o instanceof RepaintArea) { RepaintArea area = (RepaintArea)o; return area.component == component && area.x == x && area.y == y && area.w == w && area.h == h; } return false; } /** Since we're using a HashSet. */ public int hashCode() { return hashCode; } public String toString() { return "Repaint(" + component.getClass().getName() + "@" + x + "," + y + " " + w + "x" + h + ")"; } } /** Detect changes in the original animated image, and remove self * if the target icon is GC'd. * @author twall */ private static class AnimationObserver implements ImageObserver { private WeakReference ref; private ImageIcon original; public AnimationObserver(AnimatedIcon animIcon, ImageIcon original) { this.original = original; this.original.setImageObserver(this); ref = new WeakReference(animIcon); } /** Queue repaint requests for all known painted areas. */ public boolean imageUpdate(Image img, int flags, int x, int y, int width, int height) { if ((flags & (FRAMEBITS|ALLBITS)) != 0) { AnimatedIcon animIcon = (AnimatedIcon)ref.get(); if (animIcon != null) { animIcon.repaint(); } else original.setImageObserver(null); } // Return true if we want to keep painting return (flags & (ALLBITS|ABORT)) == 0; } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/ArrayEditor.java
package abbot.editor.widgets; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import abbot.i18n.Strings; import abbot.editor.widgets.TextField; /** Provides editing of a variable-length array of strings. Actions fired will have the index of the changed item in the ID (or -1 if the list added or removed an element), and the action command be one of ACTION_LIST_CHANGED, ACTION_ITEM_CHANGED, ACTION_ROW_INSERTED or ACTION_ROW_REMOVED. Allows for a single type of editor, as provided by the createEditor method. */ // TODO: use a model (cf TableModel) public class ArrayEditor extends Box { public static final String ACTION_LIST_CHANGED = "list.changed"; public static final String ACTION_ITEM_CHANGED = "item.changed"; public static final String ACTION_ITEM_INSERTED = "item.inserted"; public static final String ACTION_ITEM_DELETED = "item.deleted"; private static final int DEFAULT_COLUMNS = 10; private ArrayList listeners = new ArrayList(); private ArrayList data; private boolean adjusting = false; private ArrayList rows = new ArrayList(); protected interface ElementEditor { void setValue(Object value); Object getValue(); Component getEditorComponent(); void addActionListener(ActionListener listener); void removeActionListener(ActionListener listener); void setEnabled(boolean enabled); } /** The default editor for array elements. */ protected class TextEditor extends TextField implements ElementEditor { public TextEditor(Object value) { super(value.toString(), DEFAULT_COLUMNS); } public Object getValue() { return getText(); } public void setValue(Object o) { setText(o == null ? "" : o.toString()); } public Component getEditorComponent() { return this; } } /** Encapsulates one row of the entire array, an editor with add/remove buttons. */ protected class Row extends JPanel { public ElementEditor elementEditor; public Component editor; public JButton addButton; public JButton removeButton; private class SizedButton extends JButton { public SizedButton(String label) { super(label); } /** Ensure all insets are equal. */ public Insets getInsets() { Insets insets = super.getInsets(); int min = Math.min(insets.top, Math.min(insets.bottom, Math.min(insets.right, insets.left))); insets.right = insets.left = insets.top = insets.bottom = min; return insets; } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { Dimension size = editor.getPreferredSize(); size.width = size.height; return size; } } public Row(Object value) { BorderLayout layout = new BorderLayout(); layout.setVgap(0); setLayout(layout); elementEditor = createEditor(value); add(editor = elementEditor.getEditorComponent()); editor.setName("editor"); Box buttons = new Box(BoxLayout.X_AXIS); add(buttons, BorderLayout.EAST); buttons.add(removeButton = new SizedButton("-")); removeButton.setName("remove"); removeButton.setToolTipText(Strings.get("editor.array.remove")); buttons.add(addButton = new SizedButton("+")); addButton.setName("add"); addButton.setToolTipText(Strings.get("editor.array.insert")); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { insertRow(getRowCount() == 0 ? 0 : getRowIndex() + 1); } }); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { removeRow(getRowIndex()); } }); elementEditor.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int index = getRowIndex(); if (!adjusting && index != -1) { adjusting = true; setValueAt(index, elementEditor.getValue(), true); adjusting = false; } } }); } public Dimension getMaximumSize() { Dimension size = super.getMaximumSize(); size.height = super.getPreferredSize().height; return size; } protected int getRowIndex() { Container parent = getParent(); if (parent != null) { Component kids[] = parent.getComponents(); for (int i=0;i < kids.length;i++) { if (kids[i] == this) { return i; } } } return -1; } public String toString() { return super.toString() + "[" + getRowIndex() + ": " + elementEditor.getValue() + "]"; } } /** Creates a default, empty editor. */ public ArrayEditor() { this(new String[0]); } /** Creates an editor with the given contents. */ public ArrayEditor(Object[] contents) { super(BoxLayout.Y_AXIS); setValues(contents, false); } protected ElementEditor createEditor(Object initialValue) { return new TextEditor(initialValue); } private Row getRow(int row) { return (Row)rows.get(row); } private Row addRow(int index, Object value) { Row row = new Row(value); rows.add(index, row); add(row, index); return row; } private void init() { removeAll(); rows.clear(); for (int i=0;i < data.size();i++) { addRow(i, data.get(i)); } // Always keep one editing component visible if (data.size() == 0) { Row row = addRow(0, ""); row.removeButton.setEnabled(false); row.elementEditor.setEnabled(false); } validate(); repaint(); } private void setValues(Object[] contents, boolean fire) { if (contents == null) { if (data != null) { data = null; init(); if (fire) fireActionPerformed(ACTION_LIST_CHANGED, -1); } } else if (data == null || contents.length != data.size()) { data = new ArrayList(Arrays.asList(contents)); init(); if (fire) fireActionPerformed(ACTION_LIST_CHANGED, -1); } else { for (int i=0;i < contents.length;i++) { setValueAt(i, contents[i], fire); } } } public int getRowCount() { return data.size(); } public void insertRow(int row) { insertRow(row, ""); } public void insertRow(int row, Object value) { if (row < 0 || row > data.size()) row = data.size(); data.add(row, value); if (data.size() == 1) { row = 0; Row r = getRow(row); r.elementEditor.setEnabled(true); r.removeButton.setEnabled(true); r.elementEditor.setValue(value); } else { addRow(row, value); } validate(); repaint(); fireActionPerformed(ACTION_ITEM_INSERTED, row); } public void removeRow(int index) { if (index < 0 || index >= getRowCount()) throw new IllegalArgumentException("Row " + index + " out of bounds (" + getRowCount() + ")"); Row r = getRow(index); data.remove(index); // Always keep one editing component visible if (data.size() == 0) { // ignore messaging adjusting = true; r.elementEditor.setValue(null); adjusting = false; r.elementEditor.setEnabled(false); r.removeButton.setEnabled(false); } else { rows.remove(r); remove(r); } validate(); repaint(); fireActionPerformed(ACTION_ITEM_DELETED, index); } public Object[] getValues() { return data.toArray(new Object[data.size()]); } public void setValues(Object[] contents) { setValues(contents, true); } public void setValueAt(int index, Object value) { setValueAt(index, value, true); } private void setValueAt(int index, Object value, boolean fire) { if (index < 0 || index >= data.size()) throw new IndexOutOfBoundsException("Index " + index + " out of range (" + data.size() + ")"); if (value == data.get(index) || (value != null && value.equals(data.get(index)))) return; data.set(index, value); if (!adjusting) getRow(index).elementEditor.setValue(value); if (fire) fireActionPerformed(ACTION_ITEM_CHANGED, index); } public String getValueAt(int index) { return (String)data.get(index); } protected void fireActionPerformed(String action, int index) { Iterator iter = listeners.iterator(); ActionEvent e = new ActionEvent(this, index, action); while (iter.hasNext()) { ((ActionListener)iter.next()).actionPerformed(e); } } public void addActionListener(ActionListener l) { listeners.add(l); } public void removeActionListener(ActionListener l) { listeners.remove(l); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/GifDecoder.java
package abbot.editor.widgets; import java.net.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.image.*; /** * Class GifDecoder - Decodes a GIF file into one or more frames. <br> * * <pre> * Example: * GifDecoder d = new GifDecoder(); * d.read(&quot;sample.gif&quot;); * int n = d.getFrameCount(); * for (int i = 0; i &lt; n; i++) { * BufferedImage frame = d.getFrame(i); // frame i * int t = d.getDelay(i); // display duration of frame in milliseconds * // do something with frame * } * </pre> * * No copyright asserted on the source code of this class. May be used * for any purpose, however, refer to the Unisys LZW patent for any * additional restrictions. Please forward any corrections to * [email protected]. * * @author Kevin Weiner, FM Software; LZW decoder adapted from John * Cristy's ImageMagick. * @version 1.03 November 2003 */ public class GifDecoder { /** * File read status: No errors. */ public static final int STATUS_OK = 0; /** * File read status: Error decoding file (may be partially decoded) */ public static final int STATUS_FORMAT_ERROR = 1; /** * File read status: Unable to open source. */ public static final int STATUS_OPEN_ERROR = 2; protected BufferedInputStream in; protected int status; protected int width; // full image width protected int height; // full image height protected boolean gctFlag; // global color table used protected int gctSize; // size of global color table protected int loopCount = 1; // iterations; 0 = repeat forever protected int[] gct; // global color table protected int[] lct; // local color table protected int[] act; // active color table protected int bgIndex; // background color index protected int bgColor; // background color protected int lastBgColor; // previous bg color protected int pixelAspect; // pixel aspect ratio protected boolean lctFlag; // local color table flag protected boolean interlace; // interlace flag protected int lctSize; // local color table size protected int ix, iy, iw, ih; // current image rectangle protected Rectangle lastRect; // last image rect protected BufferedImage image; // current frame protected BufferedImage lastImage; // previous frame protected byte[] block = new byte[256]; // current data block protected int blockSize = 0; // block size // last graphic control extension info protected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev protected int lastDispose = 0; protected boolean transparency = false; // use transparent color protected int delay = 0; // delay in milliseconds protected int transIndex; // transparent color index protected static final int MaxStackSize = 4096; // max decoder pixel stack size // LZW decoder working arrays protected short[] prefix; protected byte[] suffix; protected byte[] pixelStack; protected byte[] pixels; protected ArrayList frames; // frames read from current file protected int frameCount; static class GifFrame { public GifFrame(BufferedImage im, int del) { image = im; delay = del; } public BufferedImage image; public int delay; } /** * Gets display duration for specified frame. * * @param n * int index of frame * @return delay in milliseconds */ public int getDelay(int n) { // delay = -1; if ((n >= 0) && (n < frameCount)) { delay = ((GifFrame)frames.get(n)).delay; } return delay; } /** * Gets the number of frames read from file. * * @return frame count */ public int getFrameCount() { return frameCount; } /** * Gets the first (or only) image read. * * @return BufferedImage containing first frame, or null if none. */ public BufferedImage getImage() { return getFrame(0); } /** * Gets the "Netscape" iteration count, if any. A count of 0 means * repeat indefinitiely. * * @return iteration count if one was specified, else 1. */ public int getLoopCount() { return loopCount; } /** * Creates new frame image from current data (and previous frames as * specified by their disposition codes). */ protected void setPixels() { // expose destination image's pixels as int array int[] dest = ((DataBufferInt)image.getRaster().getDataBuffer()) .getData(); // fill in starting image contents based on last image's dispose // code if (lastDispose > 0) { if (lastDispose == 3) { // use image before last int n = frameCount - 2; if (n > 0) { lastImage = getFrame(n - 1); } else { lastImage = null; } } if (lastImage != null) { int[] prev = ((DataBufferInt)lastImage.getRaster() .getDataBuffer()) .getData(); System.arraycopy(prev, 0, dest, 0, width * height); // copy pixels if (lastDispose == 2) { // fill last image rect area with background color Graphics2D g = image.createGraphics(); Color c = null; if (transparency) { c = new Color(0, 0, 0, 0); // assume background // is transparent } else { c = new Color(lastBgColor); // use given // background color } g.setColor(c); g.setComposite(AlphaComposite.Src); // replace area g.fill(lastRect); g.dispose(); } } } // copy each source line to the appropriate place in the // destination int pass = 1; int inc = 8; int iline = 0; for (int i = 0; i < ih; i++) { int line = i; if (interlace) { if (iline >= ih) { pass++; switch (pass) { case 2: iline = 4; break; case 3: iline = 2; inc = 4; break; case 4: iline = 1; inc = 2; } } line = iline; iline += inc; } line += iy; if (line < height) { int k = line * width; int dx = k + ix; // start of line in dest int dlim = dx + iw; // end of dest line if ((k + width) < dlim) { dlim = k + width; // past dest edge } int sx = i * iw; // start of line in source while (dx < dlim) { // map color and insert in destination int index = pixels[sx++] & 0xff; int c = act[index]; if (c != 0) { dest[dx] = c; } dx++; } } } } /** * Gets the image contents of frame n. * * @return BufferedImage representation of frame, or null if n is * invalid. */ public BufferedImage getFrame(int n) { BufferedImage im = null; if ((n >= 0) && (n < frameCount)) { im = ((GifFrame)frames.get(n)).image; } return im; } /** * Gets image size. * * @return GIF image dimensions */ public Dimension getFrameSize() { return new Dimension(width, height); } /** * Reads GIF image from stream * * @param is BufferedInputStream * containing GIF file. * @return read status code (0 = no errors) */ public int read(BufferedInputStream is) { init(); if (is != null) { in = is; readHeader(); if (!err()) { readContents(); if (frameCount < 0) { status = STATUS_FORMAT_ERROR; } } } else { status = STATUS_OPEN_ERROR; } try { is.close(); } catch (IOException e) { } return status; } /** * Reads GIF image from stream * * @param is InputStream * containing GIF file. * @return read status code (0 = no errors) */ public int read(InputStream is) { init(); if (is != null) { if (!(is instanceof BufferedInputStream)) is = new BufferedInputStream(is); in = (BufferedInputStream)is; readHeader(); if (!err()) { readContents(); if (frameCount < 0) { status = STATUS_FORMAT_ERROR; } } } else { status = STATUS_OPEN_ERROR; } try { is.close(); } catch (IOException e) { } return status; } /** * Reads GIF file from specified file/URL source (URL assumed if * name contains ":/" or "file:") * * @param name * String containing source * @return read status code (0 = no errors) */ public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } /** * Decodes LZW image data into pixel array. Adapted from John * Cristy's ImageMagick. */ protected void decodeImageData() { int NullCode = -1; int npix = iw * ih; int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi; if ((pixels == null) || (pixels.length < npix)) { pixels = new byte[npix]; // allocate new pixel array } if (prefix == null) prefix = new short[MaxStackSize]; if (suffix == null) suffix = new byte[MaxStackSize]; if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1]; // Initialize GIF data stream decoder. data_size = read(); clear = 1 << data_size; end_of_information = clear + 1; available = clear + 2; old_code = NullCode; code_size = data_size + 1; code_mask = (1 << code_size) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = (byte)code; } // Decode GIF pixel stream. datum = bits = count = first = top = pi = bi = 0; for (i = 0; i < npix;) { if (top == 0) { if (bits < code_size) { // Load bytes until there are enough bits for a // code. if (count == 0) { // Read a new data block. count = readBlock(); if (count <= 0) break; bi = 0; } datum += (block[bi] & 0xff) << bits; bits += 8; bi++; count--; continue; } // Get the next code. code = datum & code_mask; datum >>= code_size; bits -= code_size; // Interpret the code if ((code > available) || (code == end_of_information)) break; if (code == clear) { // Reset decoder. code_size = data_size + 1; code_mask = (1 << code_size) - 1; available = clear + 2; old_code = NullCode; continue; } if (old_code == NullCode) { pixelStack[top++] = suffix[code]; old_code = code; first = code; continue; } in_code = code; if (code == available) { pixelStack[top++] = (byte)first; code = old_code; } while (code > clear) { pixelStack[top++] = suffix[code]; code = prefix[code]; } first = suffix[code] & 0xff; // Add a new string to the string table, if (available >= MaxStackSize) break; pixelStack[top++] = (byte)first; prefix[available] = (short)old_code; suffix[available] = (byte)first; available++; if (((available & code_mask) == 0) && (available < MaxStackSize)) { code_size++; code_mask += available; } old_code = in_code; } // Pop a pixel off the pixel stack. top--; pixels[pi++] = pixelStack[top]; i++; } for (i = pi; i < npix; i++) { pixels[i] = 0; // clear missing pixels } } /** * Returns true if an error was encountered during reading/decoding */ protected boolean err() { return status != STATUS_OK; } /** * Initializes or re-initializes reader */ protected void init() { status = STATUS_OK; frameCount = 0; frames = new ArrayList(); gct = null; lct = null; } /** * Reads a single byte from the input stream. */ protected int read() { int curByte = 0; try { curByte = in.read(); } catch (IOException e) { status = STATUS_FORMAT_ERROR; } return curByte; } /** * Reads next variable length block from input. * * @return number of bytes stored in "buffer" */ protected int readBlock() { blockSize = read(); int n = 0; if (blockSize > 0) { try { int count = 0; while (n < blockSize) { count = in.read(block, n, blockSize - n); if (count == -1) break; n += count; } } catch (IOException e) { } if (n < blockSize) { status = STATUS_FORMAT_ERROR; } } return n; } /** * Reads color table as 256 RGB integer values * * @param ncolors * int number of colors to read * @return int array containing 256 colors (packed ARGB with full * alpha) */ protected int[] readColorTable(int ncolors) { int nbytes = 3 * ncolors; int[] tab = null; byte[] c = new byte[nbytes]; int n = 0; try { n = in.read(c); } catch (IOException e) { } if (n < nbytes) { status = STATUS_FORMAT_ERROR; } else { tab = new int[256]; // max size to avoid bounds checks int i = 0; int j = 0; while (i < ncolors) { int r = c[j++] & 0xff; int g = c[j++] & 0xff; int b = c[j++] & 0xff; tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; } } return tab; } /** * Main file parser. Reads GIF content blocks. */ protected void readContents() { // read GIF file content blocks boolean done = false; while (!(done || err())) { int code = read(); switch (code) { case 0x2C: // image separator readImage(); break; case 0x21: // extension code = read(); switch (code) { case 0xf9: // graphics control extension readGraphicControlExt(); break; case 0xff: // application extension readBlock(); String app = ""; for (int i = 0; i < 11; i++) { app += (char)block[i]; } if (app.equals("NETSCAPE2.0")) { readNetscapeExt(); } else skip(); // don't care break; default: // uninteresting extension skip(); } break; case 0x3b: // terminator done = true; break; case 0x00: // bad byte, but keep going and see what happens break; default: status = STATUS_FORMAT_ERROR; } } } /** * Reads Graphics Control Extension values */ protected void readGraphicControlExt() { read(); // block size int packed = read(); // packed fields dispose = (packed & 0x1c) >> 2; // disposal method if (dispose == 0) { dispose = 1; // elect to keep old image if discretionary } transparency = (packed & 1) != 0; delay = readShort() * 10; // delay in milliseconds transIndex = read(); // transparent color index read(); // block terminator } /** * Reads GIF file header information. */ protected void readHeader() { String id = ""; for (int i = 0; i < 6; i++) { id += (char)read(); } if (!id.startsWith("GIF")) { status = STATUS_FORMAT_ERROR; return; } readLSD(); if (gctFlag && !err()) { gct = readColorTable(gctSize); bgColor = gct[bgIndex]; } } /** * Reads next frame image */ protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if // specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame // list if (transparency) { act[transIndex] = save; } resetFrame(); } /** * Reads Logical Screen Descriptor */ protected void readLSD() { // logical screen size width = readShort(); height = readShort(); // packed fields int packed = read(); gctFlag = (packed & 0x80) != 0; // 1 : global color table flag // 2-4 : color resolution // 5 : gct sort flag gctSize = 2 << (packed & 7); // 6-8 : gct size bgIndex = read(); // background color index pixelAspect = read(); // pixel aspect ratio } /** * Reads Netscape extenstion to obtain iteration count */ protected void readNetscapeExt() { do { readBlock(); if (block[0] == 1) { // loop count sub-block int b1 = block[1] & 0xff; int b2 = block[2] & 0xff; loopCount = (b2 << 8) | b1; } } while ((blockSize > 0) && !err()); } /** * Reads next 16-bit value, LSB first */ protected int readShort() { // read 16-bit value, LSB first return read() | (read() << 8); } /** * Resets frame state for reading next image. */ protected void resetFrame() { lastDispose = dispose; lastRect = new Rectangle(ix, iy, iw, ih); lastImage = image; lastBgColor = bgColor; dispose = 0;//was local transparency = false;//was local delay = 0;//was local lct = null; } /** * Skips variable length blocks up to and including next zero length * block. */ protected void skip() { do { readBlock(); } while ((blockSize > 0) && !err()); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/Highlighter.java
package abbot.editor.widgets; import java.awt.*; import javax.swing.JComponent; /** Provides a persistent border around a component, drawn <i>after</i> the component itself is drawn. */ public class Highlighter extends AbstractComponentDecorator { private static final float WIDTH = 2; private static final Color BASE = Color.red; private static final Color COLOR = new Color(BASE.getRed(), BASE.getGreen(), BASE.getBlue(), 64); public Highlighter(JComponent c) { super(c); } public void paint(Graphics graphics) { Component c = getComponent(); Graphics2D g = (Graphics2D)graphics; g.setColor(COLOR); g.setStroke(new BasicStroke(WIDTH)); g.drawRect(Math.round(0 + WIDTH/2), Math.round(0 + WIDTH/2), Math.round(c.getWidth()-WIDTH), Math.round(c.getHeight()-WIDTH)); g.fillRect(Math.round(0 + WIDTH/2), Math.round(0 + WIDTH/2), Math.round(c.getWidth()-WIDTH), Math.round(c.getHeight()-WIDTH)); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/Mnemonic.java
package abbot.editor.widgets; import java.awt.*; import java.awt.event.KeyEvent; import java.lang.reflect.Method; import javax.swing.*; import abbot.Log; import abbot.Platform; import abbot.tester.KeyStrokeMap; import abbot.util.AWT; import abbot.i18n.Strings; /** Provide access to mnemonics appropriate for the current platform and * locale. Encapsulates displayed text, a KeyEvent.VK_ constant, and a * displayed mnemonic index. All instances are obtained through the factory * method, {@link #getMnemonic(String)}. * @see java.awt.event.KeyEvent * @see javax.swing.AbstractButton#setMnemonic(int) * @see javax.swing.AbstractButton#setDisplayedMnemonicIndex(int) * @see javax.swing.JLabel#setDisplayedMnemonic(int) * @see javax.swing.JLabel#setDisplayedMnemonicIndex(int) * @see javax.swing.Action#MNEMONIC_KEY */ public class Mnemonic { /** The unencoded text. For example "&amp;File" results in "File". */ public String text; /** The keycode to use as an argument to {@link AbstractButton#setMnemonic(int)}. Returns KeyEvent.VK_UNDEFINED if no mnemonic was found. */ public int keycode; /** The index to use as an argument to {@link AbstractButton#setDisplayedMnemonicIndex(int)}. Returns -1 if the default value should be used. */ public int index; private Mnemonic(String text, int keycode, int index) { this.text = text; this.keycode = keycode; this.index = index; } /** Set the displayed mnemonic index, if doing so is supported. */ public static void setDisplayedMnemonicIndex(Component c, int index) { if (index == -1) return; try { Method m = c.getClass().getMethod("setDisplayedMnemonicIndex", new Class[] { int.class }); m.invoke(c, new Object[] { new Integer(index) }); } catch(Exception e) { // ignore errors } } public String toString() { return "Mnemonic text=" + text + ", keycode=" + AWT.getKeyCode(keycode) + (index != -1 ? ("displayed index=" + index) : ""); } /** Apply this mnemonic to the given AbstractButton. */ public void setMnemonic(AbstractButton button) { button.setText(text); button.setMnemonic(keycode); setDisplayedMnemonicIndex(button, index); } /** Apply this mnemonic to the given JLabel. */ public void setMnemonic(JLabel label) { label.setText(text); label.setDisplayedMnemonic(keycode); setDisplayedMnemonicIndex(label, index); } /** Apply this mnemonic to the given JLabel. */ public void setMnemonic(JTabbedPane tabbedPane, int tabIndex) { tabbedPane.setTitleAt(tabIndex, text); // NOTE: 1.4-only try { Method m = JTabbedPane.class.getMethod("setMnemonicAt", new Class[] { int.class, int.class, }); m.invoke(tabbedPane, new Object[] { new Integer(tabIndex), new Integer(keycode)}); m = JTabbedPane.class.getMethod("setDisplayedMnemonicIndexAt", new Class[] { int.class, int.class, }); if (index != -1) m.invoke(tabbedPane, new Object[] { new Integer(tabIndex), new Integer(index) }); } catch(Exception e) { // ignore errors } } /** Apply this mnemonic to the given Action. */ public void setMnemonic(Action action) { action.putValue(Action.NAME, text); if (keycode != KeyEvent.VK_UNDEFINED) action.putValue(Action.MNEMONIC_KEY, new Integer(keycode)); // Don't think buttons listen for mnemonic index changes anyway... //if (index != -1) //action.putValue(Action.MNEMONIC_INDEX, new Integer(index)); } /** Return whether the character is disallowed as a mnemonic. */ private static boolean isDisallowed(char ch) { return Character.isWhitespace(ch) || ch == '\'' || ch == '"'; } /** Return the appropriate mnemonic for the given character. */ private static int getMnemonicMapping(char ch) { if (isDisallowed(ch)) return KeyEvent.VK_UNDEFINED; if (ch >= 'A' && ch <= 'Z') return KeyEvent.VK_A + ch - 'A'; if (ch >= 'a' && ch <= 'z') return KeyEvent.VK_A + ch - 'a'; if (ch >= '0' && ch <= '9') return KeyEvent.VK_0 + ch - '0'; // See if there's been a mapping defined; usage is similar to NetBeans // handling, except that raw integers are not allowed (use the VK_ // constant name instead). String str = Strings.get("MNEMONIC_" + ch, true); if (str != null) { try { return AWT.getKeyCode("VK_" + str.toUpperCase()); } catch(IllegalArgumentException e) { Log.warn("'" + str + "' is not a valid mnemonic " + "(use a VK_ constant from KeyEvent)"); } } // Make a guess based on keymaps KeyStroke keystroke = KeyStrokeMap.getKeyStroke(ch); if (keystroke != null) { return keystroke.getKeyCode(); } return KeyEvent.VK_UNDEFINED; } /** Create a Mnemonic instance with the mnemonic information from the given encoded String. Unencoded text, the mnemonic keycode, and the display index are encapsulated in the returned Mnemonic object. Encoding consists of placing an ampersand (&) prior to the character designated as the mnemonic. <p> Mnemonics may be encoded as follows: <table border=1> <tr><td><i>Original Text</i></td><td><i>Visible Text</i></td><td><i>Mnemonic</i></td></tr> <tr><td>&File</td><td><u>F</u>ile</td><td><b>VK_F</b></td></tr> <tr><td>Save &As...</td><td>Save <u>A</u>s...</td><td><b>VK_A</b> second instance</td></tr> <tr><td>Me&&&You</td><td>Me&<u>Y</u>ou</td><td><b>VK_Y</b> ambiguous ampersands must be escaped</td></tr> <tr><td>Sugar & Spice</td><td>Sugar & Spice</td><td><b>None</b> ampersand is unambiguous, whitespace is not allowed as a mnemonic</td></tr> </table> <p> Swing restricts mnemonics to available KeyEvent VK_ constants, so there must exist a mapping between text characters and said constants. If the obvious mappings (A-Z, a-z, 0-9) don't hold, lookup falls back to other methods. Whitespace, quotes, and ampersand are disallowed as mnemonics. <p> Mappings from arbitrary characters to mnemonic keys may be defined by providing a property MNEMONIC_{unicode char}={KeyEvent.VK_ constant name} within a bundle accessible by <code>abbot.i18n.Strings</code>. If no such mapping is defined, a VK_ code is guessed by checking if there can be found a keystroke mapping for the original character. <p> @see abbot.tester.KeyStrokeMap @see abbot.i18n.Strings */ public static Mnemonic getMnemonic(String input) { String text = input; int mnemonicIndex = -1; int keycode = KeyEvent.VK_UNDEFINED; int amp = text.indexOf("&"); int displayIndex = -1; while (amp != -1 && amp < text.length()-1) { char ch = text.charAt(amp + 1); if (ch == '&') { text = text.substring(0, amp) + text.substring(amp + 1); amp = text.indexOf("&", amp + 1); } else { int code = getMnemonicMapping(ch); if (code == KeyEvent.VK_UNDEFINED) { amp = text.indexOf("&", amp + 2); } else { // Only use the first mapping if (mnemonicIndex == -1) { text = text.substring(0, amp) + text.substring(amp + 1); displayIndex = mnemonicIndex = amp; keycode = code; } amp = text.indexOf("&", amp + 1); } } } // Mnemonics are not used on OSX if (!useMnemonics()) { keycode = KeyEvent.VK_UNDEFINED; displayIndex = -1; } Mnemonic m = new Mnemonic(text, keycode, displayIndex); Log.debug(input + "->" + m); return m; } public static boolean useMnemonics() { return !Platform.isOSX(); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/SpinningDial.java
package abbot.editor.widgets; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.image.BufferedImage; import javax.swing.Icon; import javax.swing.ImageIcon; /** Provides a spinning disk of hash marks. */ public class SpinningDial extends AbstractAnimatedIcon { private static final int MIN_ALPHA = 32; private static final int DEFAULT_SIZE = 32; private static final int SPOKES = 16; /** This is a good delay between increasing the phase. */ public static final int SPIN_INTERVAL = 1000/SPOKES; private int w; private int h; private Image[] frames; public SpinningDial() { this(DEFAULT_SIZE, DEFAULT_SIZE); } /** Not recommended to go below 16 pixels. */ public SpinningDial(int diameter) { this(diameter, diameter); } /** Not recommended to go below 16x16. */ public SpinningDial(int w, int h) { this(w, h, SPOKES); } public SpinningDial(int w, int h, int spokes) { super(spokes, SPIN_INTERVAL); this.w = w; this.h = h; frames = new Image[getFrameCount()]; } public int getIconHeight() { return h; } public int getIconWidth() { return w; } /** Set the stroke width according to the size. */ protected float getStrokeWidth(int size) { return size/16f; } // TODO: move image snapshot up to abstract class protected void paintFrame(Component c, Graphics graphics, int x, int y) { int idx = getFrame(); if (frames[idx] == null) { int w = getIconWidth(); int h = getIconHeight(); int size = Math.min(w, h); Image image = c != null ? c.getGraphicsConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT) : new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D)image.getGraphics(); g.setComposite(AlphaComposite.Clear); g.fillRect(0, 0, w, h); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int FULL_SIZE = 256; float strokeWidth = getStrokeWidth(FULL_SIZE); float fraction = .6f; g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.translate((float)w/2, (float)h/2); float scale = (float)size/FULL_SIZE; g.scale(scale, scale); int alpha = 255; int x1, y1, x2, y2; int radius = FULL_SIZE/2-1-(int)(strokeWidth/2); int frameCount = getFrameCount(); for (int i=0;i < frameCount;i++) { double cos = Math.cos(Math.PI*2-Math.PI*2*(i-idx)/frameCount); double sin = Math.sin(Math.PI*2-Math.PI*2*(i-idx)/frameCount); x1 = (int)(radius*fraction * cos); x2 = (int)(radius* cos); y1 = (int)(radius*fraction * sin); y2 = (int)(radius* sin); g.setColor(new Color(0,0,0,Math.min(255, alpha))); g.drawLine(x1, y1, x2, y2); alpha = Math.max(MIN_ALPHA, alpha*3/4); } g.dispose(); frames[idx] = image; } graphics.drawImage(frames[idx], x, y, null); } public String toString() { return "SpinningDial(" + getIconWidth() + "x" + getIconHeight() + ")"; } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/SpinningDialWaitIndicator.java
package abbot.editor.widgets; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.Timer; import abbot.util.AWT; /* Gradually fade the display, then show a spinning dial indicator. */ // TODO: provide text next to spinner (i.e. paint JLabel instead of icon) public class SpinningDialWaitIndicator extends WaitIndicator implements ActionListener { private static final int MAX_SIZE = 64; private static final int FADE_INTERVAL = 1000/24; private static final int FADE_THRESHOLD = 192; // size of margins when space is sufficiently large private static final int MARGIN = 8; // margins take up 1/MARGIN_FRACTION when space is limited private static final int MARGIN_FRACTION = 8; private Timer timer; private int fade; private int verticalOffset; private SpinningDial dial; private String text; public SpinningDialWaitIndicator(JFrame frame) { this(frame.getLayeredPane()); JMenuBar mb = frame.getJMenuBar(); if (mb != null) { // Exclude the menu bar from centering/sizing verticalOffset = mb.getHeight(); } } public SpinningDialWaitIndicator(JComponent target) { this(target, null); } public SpinningDialWaitIndicator(final JComponent target, String text) { super(target); this.text = text; // Draw the dial centered and scaled to fit, up to a maximum size dial = new SpinningDial() { public int getIconWidth() { Rectangle r = getComponent().getVisibleRect(); int margin = Math.min(MARGIN, r.width/MARGIN_FRACTION); return Math.min(MAX_SIZE, r.width-margin*2); } public int getIconHeight() { Rectangle r = getComponent().getVisibleRect(); int margin = Math.min(MARGIN, r.height/MARGIN_FRACTION); return Math.min(MAX_SIZE, r.height-verticalOffset-margin*2); } }; // Disable automatic animation dial.setFrameInterval(0); } public void setText(String text) { this.text = text; repaint(); } /** Fade the affected component to background, then apply a spinning * wait indicator. */ public void paint(Graphics graphics) { if (timer == null) { timer = new Timer(FADE_INTERVAL, this); timer.start(); } Graphics2D g = (Graphics2D)graphics.create(); Rectangle r = getComponent().getVisibleRect(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setColor(AWT.alpha(getComponent().getBackground(), fade)); g.fillRect(r.x, r.y, r.width, r.height); if (fade < FADE_THRESHOLD) return; int x = r.x; if (text == null) x += (r.width - dial.getIconWidth())/2; else x += dial.getIconWidth()/4; int y = r.y + verticalOffset + (r.height - verticalOffset - dial.getIconHeight())/2; dial.paintIcon(getPainter(), g, x, y); if (text != null) { Font font = g.getFont(); g.setFont(font.deriveFont(Font.BOLD, dial.getIconHeight()/2)); FontMetrics m = g.getFontMetrics(); x += dial.getIconWidth() * 5/4; // FIXME vertical offset is not quite right y += dial.getIconHeight() - (dial.getIconHeight() - m.getAscent())/2; g.setColor(getComponent().getForeground()); g.drawString(text, x, y); } g.dispose(); } /** Remove the wait decoration. */ public void dispose() { if (timer != null) { timer.stop(); timer = null; } super.dispose(); } /** First fade the background, then spin the dial. */ public void actionPerformed(ActionEvent e) { if (fade < FADE_THRESHOLD) { fade += 32; if (fade >= FADE_THRESHOLD) timer.setDelay(SpinningDial.SPIN_INTERVAL); } else { dial.nextFrame(); } getPainter().repaint(); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/TextArea.java
package abbot.editor.widgets; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import abbot.Log; /** A better text area that fires when focus leaves the component, and also selects all the contents when the action is fired to indicate the contents were accepted. */ // FIXME extend to have a "commit" on enter or focus change, where ESC will // revert public class TextArea extends JTextArea { public static final String ACTION_FOCUS_LOST = "focus-lost"; public static final String ACTION_TEXT_CHANGED = "text-changed"; public static final String ACTION_TEXT_INSERTED = "text-changed"; public static final String ACTION_TEXT_REMOVED = "text-changed"; private boolean continuousFire = true; private boolean fieldChanging = false; private ArrayList listeners = new ArrayList(); public TextArea(String value) { super(value); addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent ev) { if (!ev.isTemporary() && !isLocalMenuActive()) { Log.debug("Firing on focus loss"); fireActionPerformed(ACTION_FOCUS_LOST); } } }); getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent ev) { if (!fieldChanging && continuousFire) fireActionPerformed(ACTION_TEXT_CHANGED); } public void insertUpdate(DocumentEvent ev) { if (!fieldChanging && continuousFire) fireActionPerformed(ACTION_TEXT_INSERTED); } public void removeUpdate(DocumentEvent ev) { if (!fieldChanging && continuousFire) fireActionPerformed(ACTION_TEXT_REMOVED); } }); } /** Don't fire events when text is set directly (to conform to regular JTextArea behavior). */ public void setText(String text) { fieldChanging = true; super.setText(text); fieldChanging = false; } /** Detect temporary focus loss due to menu activation. */ private boolean isLocalMenuActive() { boolean active = false; Window window = SwingUtilities.getWindowAncestor(TextArea.this); while (window != null && !active) { window = SwingUtilities.getWindowAncestor(window); if (window instanceof JFrame) { Component comp = window.getFocusOwner(); Log.debug("Focus is in " + abbot.tester.Robot.toString(comp)); active = comp != null && (comp instanceof JMenuItem); } } return active; } protected void fireActionPerformed(String actionCommand) { fireActionPerformed(actionCommand, false); } protected void fireActionPerformed() { fireActionPerformed(getText(), true); } /** On normal fire (enter) select all text. */ protected void fireActionPerformed(String cmd, boolean select) { if (select) selectAll(); ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, cmd); Iterator iter = listeners.iterator(); while (iter.hasNext()) { ((ActionListener)iter.next()).actionPerformed(e); } } public void addActionListener(ActionListener l) { listeners.add(l); } public void removeActionListener(ActionListener l) { listeners.remove(l); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/TextField.java
package abbot.editor.widgets; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import abbot.Log; /** A better text field with some useful features. <ul> <li>Fires when focus leaves the component. <li>Selects all the contents when the action is fired to indicate the contents were accepted. <li>Until the user causes a notify-field-accept (usually with the Enter key), the contents may be reverted to the original value by invoking the field-revert action (bound to ESC by default). <li>Actions are fired on all edits. <li>The field has a fixed height. <li>Pressing Enter when the field is blank will insert a default value, if one has been provided. </ul> <p> This functionality may be applied to any JTextField with the {@link #decorate(JTextField)} method. */ public class TextField extends JTextField { /** * The delay to update the text field listener after a user action, this is to prevent * a message storm when processing UI updates such as updating the class and methods. */ public static final int TEXT_FIELD_UPDATE_DELAY = 300; /** * A client property that controls the lazy updating of this text field */ /*package*/ static final String DELAYED_EVENTS_CLIENT_PROPERTY = "DELAYED_UPDATE_EVENTS"; /** Action command when the field loses focus. */ public static final String ACTION_FOCUS_LOST = "focus-lost"; /** Action command when the text changes. */ public static final String ACTION_TEXT_CHANGED = "text-changed"; /** Action command when text is inserted. */ public static final String ACTION_TEXT_INSERTED = "text-inserted"; /** Action command when text is removed. */ public static final String ACTION_TEXT_REMOVED = "text-removed"; /** Action command when the field reverts to its original value. The * action is equivalent to typing the original text and hitting "enter". */ public static final String ACTION_TEXT_REVERTED = "text-reverted"; private static final String REVERT_ACTION_NAME = "field-revert"; public static boolean isDocumentAction(String action) { return action == ACTION_TEXT_CHANGED || action == ACTION_TEXT_INSERTED || action == ACTION_TEXT_REMOVED; } public static void decorate(JTextField tf) { new Decorator(tf); } public static void decorate(JTextField tf, String defaultValue) { new Decorator(tf, defaultValue); } /** Avoid recursive changes to the field's text. */ private boolean notifying; private Decorator decorator; public TextField(String value, int columns) { super(value, columns); decorator = new Decorator(this); } public TextField(String value, String defaultValue, int columns) { super(value, columns); decorator = new Decorator(this, defaultValue); } public TextField(String value) { super(value); decorator = new Decorator(this); } public TextField(String value, String defaultValue, boolean delayedUpdate) { super(value); decorator = new Decorator(this, defaultValue); putClientProperty(DELAYED_EVENTS_CLIENT_PROPERTY, delayedUpdate); } /** Don't allow text field to resize height. */ public Dimension getMaximumSize() { Dimension size = super.getMaximumSize(); size.height = super.getPreferredSize().height; return size; } /** Don't allow text field to resize height. */ public Dimension getMinimumSize() { Dimension size = super.getMinimumSize(); size.height = super.getPreferredSize().height; return size; } /** The default value will be inserted when the field is blank and ENTER is pressed. This behavior is disabled if the value is null. */ public void setDefaultValue(String value) { decorator.setDefaultValue(value); } public void setText(String text) { if (!getText().equals(text) && !notifying) super.setText(text != null ? text : ""); } protected void fireActionPerformed() { notifying = true; try { super.fireActionPerformed(); } finally { notifying = false; } } public static class Decorator { private JTextField textField; /** Text used when field is reverted. Updated on any notify-field-accept action or when setText() is invoked directly. */ private String revertText; // whether to notify action listeners on every text change private boolean continuousFire = true; // Value to place in field when it is empty and Enter is hit private String defaultValue; // Used to make sure we don't kill the event queue for every key event private TextFieldUpdateTimer updateTimer = new TextFieldUpdateTimer(); public Decorator(JTextField textField) { this(textField, null); } public Decorator(final JTextField textField, String defValue) { this.textField = textField; this.defaultValue = defValue; textField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent ev) { if (!ev.isTemporary() && !isLocalMenuActive(textField)) { fireActionPerformed(ACTION_FOCUS_LOST); } } }); DocumentListener listener = new DocumentListener() { public void changedUpdate(DocumentEvent ev) { if (continuousFire) { fireActionPerformed(ACTION_TEXT_CHANGED); } } public void insertUpdate(DocumentEvent ev) { // If setText is called, update the revert text String stack = Log.getStack(Log.FULL_STACK); if (stack.indexOf("JTextComponent.setText") != -1) { revertText = textField.getText(); } if (continuousFire) { fireActionPerformed(ACTION_TEXT_INSERTED); } } public void removeUpdate(DocumentEvent ev) { if (continuousFire) { fireActionPerformed(ACTION_TEXT_REMOVED); } } }; textField.getDocument().addDocumentListener(listener); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Select all text when there is an effective commit, // and make note of the new committed text. // If the field is blank, set the default value if there // is one. String text = textField.getText(); if (!isDocumentAction(e.getActionCommand())) { if (defaultValue != null && "".equals(text)) { text = defaultValue; SwingUtilities.invokeLater(new Runnable() { public void run() { textField.setText(defaultValue); textField.selectAll(); } }); } revertText = text; textField.selectAll(); } } }); // Changing the input map doesn't work on the JComboBox editor, // so use a key listener instead. textField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { revertText(); } } }); /* // This would appear to be a better method for handling revert, // but the following code doesn't work, and I can't figure out why ActionMap am = textField.getActionMap(); am.put(REVERT_ACTION_NAME, new RevertFieldAction()); InputMap im = textField.getInputMap(); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), REVERT_ACTION_NAME); */ // Initialize revertText = textField.getText(); } private void setDefaultValue(String value) { this.defaultValue = value; } private void revertText() { if (!textField.getText().equals(revertText)) { textField.setText(revertText); fireActionPerformed(ACTION_TEXT_REVERTED); } } private void fireActionPerformed(String command) { if (Boolean.TRUE.equals(textField.getClientProperty(DELAYED_EVENTS_CLIENT_PROPERTY))) { // This will queue the event for a little bit so that we don't end up // storing the class loader, if the events are the same then we coalese the // events, otherwise we post the previous event right away then queue // the new one updateTimer.pushIfDifferent(command); } else { fireActionPerformedImpl(command); } } private void fireActionPerformedImpl(String command) { textField.setActionCommand(command); textField.postActionEvent(); textField.setActionCommand(null); } /** Detect temporary focus loss due to menu activation (pre-1.4). */ private boolean isLocalMenuActive(JTextField field) { Window window = SwingUtilities.getWindowAncestor(field); if (window != null) { Component comp = window.getFocusOwner(); return comp != null && (comp instanceof JMenuItem); } return false; } protected class TextFieldUpdateTimer extends Timer { public TextFieldUpdateTimer() { super(TEXT_FIELD_UPDATE_DELAY, null); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fireActionPerformedImpl(e.getActionCommand()); // Clear action command TextFieldUpdateTimer.this.setActionCommand(null); } }); setRepeats(false); } /** * Assuming this all happens on the event queue * @param command */ public void pushIfDifferent(String newCommand) { if (newCommand.equals(getActionCommand())) { restart(); } else { stop(); // Force this message to first if (getActionCommand()!=null) { fireActionPerformed(new ActionEvent(TextFieldUpdateTimer.this, 0, getActionCommand(), System.currentTimeMillis(), 0)); } // Start the timer with the new command setActionCommand(newCommand); restart(); } } } protected class RevertFieldAction extends AbstractAction { public RevertFieldAction() { super(REVERT_ACTION_NAME); } public void actionPerformed(ActionEvent e) { revertText(); } } } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/TextFormat.java
package abbot.editor.widgets; import abbot.i18n.Strings; /** Provides text formatting utilities. */ public class TextFormat { public static final int TOOLTIP_WRAP = 50; public static final int DIALOG_WRAP = 60; /** Turns "SomeRunTogetherWords" into "Some Run Together Words". */ public static String wordBreak(String phrase) { StringBuffer words = new StringBuffer(phrase); for (int i=0;i < words.length()-1;i++) { char up = words.charAt(i+1); if (Character.isUpperCase(up) && (i == words.length()-2 || Character.isLowerCase(words.charAt(i+2)))) { words.insert(++i, ' '); } } return words.toString(); } /** Wrap the given text at the given number of characters per line. Whitespace may be compressed. */ public static String wordWrap(String msg, int wrapAt, String lineSep) { if (msg == null) return null; int len = msg.length(); StringBuffer sb = new StringBuffer(len * 3 / 2); int pos = 0; while (pos < len) { // Trim leading whitespace char ch; while (pos < len && Character.isWhitespace(ch = msg.charAt(pos))) { if (ch == '\n') { sb.append(lineSep); } ++pos; } // Find the last whitespace prior to the wrap column int lastWhite = -1; boolean nonwhite = false; int col = 0; while (pos + col < len && col <= wrapAt) { if (Character.isWhitespace(ch = msg.charAt(pos + col))) { if (lastWhite == -1 || nonwhite) { lastWhite = pos + col; } if (ch == '\n') { break; } } else { nonwhite = true; } ++col; } if (pos + col == len) { // end of input while (pos < len) { sb.append(msg.charAt(pos)); ++pos; } break; } else if (lastWhite != -1) { // found whitespace, wrap there while (pos < lastWhite) { sb.append(msg.charAt(pos)); ++pos; } } else { // no whitespace on the line; wrap at next whitespace // or end of input while (pos < len) { ch = msg.charAt(pos); if (Character.isWhitespace(ch)) break; sb.append(ch); ++pos; } if (pos == len) break; } sb.append(lineSep); ++pos; } return sb.toString(); } /** Emit html, suitably line-wrapped and formatted for a tool tip. */ public static String tooltip(String tip) { if (tip.startsWith("<html>")) { tip = tip.substring(6, tip.length() - 7); } else { tip = wordWrap(tip, TOOLTIP_WRAP, "<br>"); } return Strings.get("TooltipFormat", new Object[] { tip }); } /** Emit html, suitably line-wrapped and formatted for a dialog. */ public static String dialog(String msg) { if (msg.startsWith("<html>")) { msg = msg.substring(6, msg.length() - 7); } else { msg = wordWrap(msg, DIALOG_WRAP, "<br>"); } return Strings.get("DialogFormat", new Object[] { msg }); } }
0
java-sources/abbot/costello/1.4.0/abbot/editor
java-sources/abbot/costello/1.4.0/abbot/editor/widgets/WaitIndicator.java
package abbot.editor.widgets; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseMotionAdapter; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import abbot.util.AWT; /** Prevents mouse and key input to a {@link JComponent} or {@link JFrame}, * while dimming the component and displaying a wait cursor. */ public class WaitIndicator extends AbstractComponentDecorator implements KeyEventDispatcher { /** Place the wait indicator over the entire frame. */ public WaitIndicator(JFrame frame) { this(frame.getLayeredPane()); } /** Place the wait indicator over the given component. */ public WaitIndicator(JComponent target) { super(target); KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this); getPainter().addMouseListener(new MouseAdapter() { }); getPainter().addMouseMotionListener(new MouseMotionAdapter() { }); getPainter().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } /** Remove the wait indicator. */ public void dispose() { super.dispose(); KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(this); } /** Consume events targeted at our target component. Return true to * consume the event. */ public boolean dispatchKeyEvent(KeyEvent e) { return SwingUtilities.isDescendingFrom(e.getComponent(), getComponent()); } /** The default dims the blocked component. */ public void paint(Graphics g) { Color c = AWT.alpha(getComponent().getBackground(), 128); Rectangle r = getDecorationBounds(); g = g.create(); g.setColor(c); g.fillRect(r.x, r.y, r.width, r.height); g.dispose(); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Action.java
package abbot.script; import java.lang.reflect.Method; import java.util.*; import abbot.tester.*; import abbot.util.AWT; /** Encapsulate an action. Usage:<br> * <blockquote><code> * &lt;action method="..." args="..."&gt;<br> * &lt;action method="..." args="component_id[,...]" class="..."&gt;<br> * </code></blockquote> * An Action reproduces a user semantic action (such as a mouse click, menu * selection, or drag/drop action) on a particular component. The id of the * component being operated on must be the first argument, and the class of * that component must be identified by the class tag if the action is not * provided by the base {@link abbot.tester.ComponentTester} class<p> * Note that the method name is the name of the actionXXX method, * e.g. to click a button (actionClick on * AbstractButtonTester), the XML would appear thus:<p> * <blockquote><code> * &lt;action method="actionClick" args="My Button" class=javax.swing.AbstractButton&gt;<br> * </code></blockquote> * Note that if the first argument is a Component, the class tag is required. * Note also that the specified class is the <i>tested</i> class, not the * target class for the method invocation. * <p> * The target class for the method invocation is always a * ComponentTester-derived class. */ // Any reason for the tested class to be saved and not the target class? the // tester class gets looked up dynamically, but is there any reason that would // be required? // The component reference class should be used; that way the component can // change class w/o affecting the action; also the action class should *not* // be saved, and the component tester looked up dynamically. public class Action extends Call { private static final String USAGE = "<action method=\"...\" args=\"...\" [class=\"...\"]/>"; // Account for deprecated methods which use String representations of // modifier masks. private static Set stringModifierMethods = new HashSet(Arrays.asList(new String[] { "actionKeyStroke", "actionKeyPress", "actionKeyRelease" })); private static Set optionalFocusMethods = new HashSet(Arrays.asList(new String[] { "actionKeyStroke", "actionKeyPress", "actionKeyRelease", "actionKeyString", })); private static final String DEFAULT_CLASS_NAME = "java.awt.Component"; /** Provide a default value for the target class name, so that the Call * parent class won't choke. */ private static Map patchAttributes(Map map) { if (map.get(TAG_CLASS) == null) { map.put(TAG_CLASS, DEFAULT_CLASS_NAME); } return map; } public Action(Resolver resolver, Map attributes) { super(resolver, patchAttributes(attributes)); patchMethodName(); } /** Action for a method in the ComponentTester base class. */ public Action(Resolver resolver, String description, String methodName, String[] args) { super(resolver, description, DEFAULT_CLASS_NAME, methodName, args); patchMethodName(); } public Action(Resolver resolver, String description, String methodName, String[] args, Class targetClass) { super(resolver, description, targetClass.getName(), methodName, args); patchMethodName(); } private void patchMethodName() { // account for deprecated usage String mn = getMethodName(); if (!mn.startsWith("action")) setMethodName("action" + mn); } /** Ensure the default class name is DEFAULT_CLASS_NAME * The target class <i>must</i> be a subclass of java.awt.Component. */ public void setTargetClassName(String cn) { if (cn == null || "".equals(cn)) cn = DEFAULT_CLASS_NAME; super.setTargetClassName(cn); } /** Return the XML tag for this step. */ public String getXMLTag() { return TAG_ACTION; } /** Return custom attributes for an Action. */ public Map getAttributes() { Map map = super.getAttributes(); // Only save the class attribute if it's not the default map.remove(TAG_CLASS); if (!DEFAULT_CLASS_NAME.equals(getTargetClassName())) { map.put(TAG_CLASS, getTargetClassName()); } return map; } /** Return the proper XML usage for this step. */ public String getUsage() { return USAGE; } /** Return a default description for this action. */ public String getDefaultDescription() { // strip off "action", if it's there String name = getMethodName(); if (name.startsWith("action")) name = name.substring(6); return name + getArgumentsDescription(); } public Class getTargetClass() throws ClassNotFoundException { return resolveTester(getTargetClassName()).getClass(); } /** Convert the String representation of the arguments into actual * arguments. */ protected Object evaluateParameter(Method m, String param, Class type) throws Exception { // Convert ComponentLocation arguments if (ComponentLocation.class.isAssignableFrom(type)) { ComponentTester tester = (ComponentTester)getTarget(m); String arg = ArgumentParser.substitute(getResolver(), param); return tester.parseLocation(arg); } // Convert virtual key codes and modifier masks into integers else if ((type == int.class || type == Integer.class) && (param.startsWith("VK_") || param.indexOf("_MASK") != -1)) { if (param.startsWith("VK_")) return new Integer(AWT.getKeyCode(param)); return new Integer(AWT.getModifiers(param)); } else { return super.evaluateParameter(m, param, type); } } /** Return the target of the invocation. */ protected Object getTarget(Method m) throws ClassNotFoundException { return resolveTester(getTargetClassName()); } /** Remove deprecated methods from those looked up. */ protected Method[] resolveMethods(String name, Class cls, Class returnType) throws NoSuchMethodException { Method[] methods = super.resolveMethods(name, cls, returnType); if (stringModifierMethods.contains(name)) { // still have some key methods hanging around which expect a // string representation of the VK_ code and/or modifiers. // ignore them here. ArrayList list = new ArrayList(Arrays.asList(methods)); for (int i=0;i < methods.length;i++) { Class[] ptypes = methods[i].getParameterTypes(); for (int j=0;j < ptypes.length;j++) { if (ptypes[j] == String.class) { list.remove(methods[i]); break; } } } methods = (Method[])list.toArray(new Method[list.size()]); } return methods; } /** Resolve the method name into its final form. */ public Method getMethod() throws ClassNotFoundException, NoSuchMethodException { return resolveMethod(getMethodName(), getTargetClass(), void.class); } protected Method disambiguateMethod(Method[] methods) { // Try to find the right one by examining some of the parameters // Nothing fancy, just explicitly picks between the variants. if (methods.length == 2) { // pick between key action variants if (optionalFocusMethods.contains(methods[0].getName())) { Class[] params = methods[0].getParameterTypes(); Method kcMethod, crefMethod; if (params[0] == int.class) { kcMethod = methods[0]; crefMethod = methods[1]; } else { kcMethod = methods[1]; crefMethod = methods[0]; } String[] args = getArguments(); if (args.length > 0 && args[0].startsWith("VK_")) { return kcMethod; } return crefMethod; } } return super.disambiguateMethod(methods); } }