source: trunk/autoquest-jfcmonitor/src/main/java/de/ugoe/cs/autoquest/jfcmonitor/JFCComponent.java @ 927

Last change on this file since 927 was 927, checked in by sherbold, 12 years ago
  • added copyright under the Apache License, Version 2.0
  • Property svn:mime-type set to text/plain
File size: 13.8 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.jfcmonitor;
16
17import java.awt.Component;
18import java.awt.Container;
19import java.awt.event.ContainerListener;
20import java.beans.PropertyChangeListener;
21import java.io.File;
22import java.lang.reflect.InvocationTargetException;
23import java.lang.reflect.Method;
24import java.security.InvalidParameterException;
25import java.util.ArrayList;
26import java.util.HashMap;
27import java.util.LinkedList;
28import java.util.List;
29import java.util.Map;
30
31import javax.accessibility.AccessibleContext;
32
33import de.ugoe.cs.util.StringTools;
34
35/**
36 * <p>
37 * This class manages information about the current GUI. It always contains the current GUI
38 * hierarchy.
39 * </p>
40 *
41 * @author Steffen Herbold
42 * @author Fabian Glaser
43 * @version 1.0
44 */
45public class JFCComponent {
46
47    /**
48     * <p>
49     * Map of all known GUI components.
50     * </p>
51     */
52    private static Map<Component, JFCComponent> knownComponents =
53        new HashMap<Component, JFCComponent>();
54   
55    /**
56     * <p>
57     * List of PropertyChangeListeners that are registered on the components.
58     * </p>
59     */
60    private static List<PropertyChangeListener> propertyChangeListeners =
61        new ArrayList<PropertyChangeListener>();
62   
63    /**
64     * <p>
65     * List of ContainerListeners that are registered on the components.
66     * </p>
67     */
68    private static List<ContainerListener> containerListeners =
69                new ArrayList<ContainerListener>();
70
71    /**
72     * <p>
73     * Adds a AWT component to the GUI hierarchy. If the component already exists in the hierarchy,
74     * it is not added a second time.
75     * </p>
76     *
77     * @param component
78     *            component that is added
79     */
80    public static void add(Component component) {
81        add(component, find(component.getParent()));
82    }
83   
84    /**
85     * <p>
86     * Adds a new PropertyChangeListener to the components.
87     * </p>
88     * @param list
89     *                  the PropertyChangeListener
90     */
91    public static void addPropertyChangeListener(PropertyChangeListener list){
92        propertyChangeListeners.add(list);
93    }
94   
95    /**
96     * <p>
97     * Adds a new ContainerListener to the components.
98     * </p>
99     * @param list
100     *                  the ContainerListener
101     */
102    public static void addContainerListener(ContainerListener list){
103        containerListeners.add(list);
104    }
105   
106    /**
107     * <p>
108     * Tests if a component is already known.
109     * </p>
110     * @param component to be tested
111     * @return true, if component is already known, false otherwise.
112     */
113    public static boolean isKnown(Component component){
114        if (knownComponents.containsKey(component))
115                return true;
116        return false;
117    }
118
119    /**
120     * <p>
121     * Adds a AWT component to the GUI hierarchy. If the component already exists in the hierarchy,
122     * it is not added a second time.
123     * </p>
124     *
125     * @param component
126     *            component that is added
127     * @param parent
128     *            parent of the component
129     */
130    public static void add(Component component, JFCComponent parent) {
131        if (!knownComponents.containsKey(component)) {
132            knownComponents.put(component, new JFCComponent(component, parent));
133        }
134    }
135
136    /**
137     * <p>
138     * Finds a component in the GUI hierarchy and returns the corresponding JFComponent instance.
139     * Returns null if the component is not found.
140     * </p>
141     *
142     * @param component
143     *            component that is searched for
144     * @return corresponding JFComponent instance; null if the compenent is not found
145     */
146    public static JFCComponent find(Component component) {
147        return knownComponents.get(component);
148    }
149
150    /**
151     * <p>
152     * Removes a component from the GUI hierarchy. In case the component is not part of the known
153     * hierachy, nothing happens.
154     * </p>
155     *
156     * @param component
157     *            component to be removed
158     */
159    public static void remove(Component component) {
160        JFCComponent jfcComponent = knownComponents.remove(component);
161        if (jfcComponent != null) {
162            jfcComponent.removeFromParent();
163            jfcComponent.removeChildren();
164        }
165    }
166
167    /**
168     * <p>
169     * Parent of the GUI component. null means, that the component has no parent.
170     * </p>
171     */
172    private JFCComponent parent = null;
173
174    /**
175     * <p>
176     * Child components of the component.
177     * </p>
178     */
179    private List<JFCComponent> children = new LinkedList<JFCComponent>();
180
181    /**
182     * <p>
183     * Reference to the actual GUI component.
184     * </p>
185     */
186    private Component component;
187
188    /**
189     * <p>
190     * Helper attribute that contains the title of the component. Set by {@link #setTitle()}.
191     * </p>
192     */
193    private String title = null;
194
195    /**
196     * <p>
197     * Helper attribute that contains the class of the component. Set by {@link #setClass()}.
198     * </p>
199     */
200    private String componentClass = null;
201
202    /**
203     * <p>
204     * Helper attribute that contains the icon of the component. Set by {@link #setIcon()}.
205     * </p>
206     */
207    private String icon = null;
208
209    /**
210     * <p>
211     * Helper attribute that contains the icon of the component. Set by {@link #setIndex()}.
212     * </p>
213     */
214    private int index = -1;
215
216    /**
217     * <p>
218     * Constructor. Creates a new JFCComponent. Only used internally by
219     * {@link #add(Component, JFCComponent)}.
220     * </p>
221     *
222     * @param component
223     *            component associated with the JFCComponent
224     * @param parent
225     *            parent of the component; null if there is no parent
226     */
227    private JFCComponent(Component component, JFCComponent parent) {
228        if (component == null) {
229            throw new InvalidParameterException("parameter component must not be null");
230        }
231        this.component = component;
232       
233        // add PropertyChangeListeners to AccessibleContext
234        AccessibleContext context = component.getAccessibleContext();
235        if (context != null){
236                for (PropertyChangeListener listener: propertyChangeListeners)
237                        context.addPropertyChangeListener(listener);
238        }
239       
240        // add PropertyChangeListeners to component itself
241        for (PropertyChangeListener listener: propertyChangeListeners)
242                this.component.addPropertyChangeListener(listener);
243       
244        this.parent = parent;
245        if (parent != null) {
246            parent.addChild(this);
247        }
248
249        if (component instanceof Container) {
250                for (ContainerListener listener: containerListeners)
251                        ((Container) component).addContainerListener(listener);
252               
253            for (Component childComponent : ((Container) component).getComponents()) {
254                add(childComponent, this);
255            }
256        }
257    }
258
259    /**
260     * <p>
261     * Adds a child component to the current component.
262     * </p>
263     *
264     * @param child
265     *            child component to be added
266     */
267    private void addChild(JFCComponent child) {
268        children.add(child);
269    }
270
271    /**
272     * <p>
273     * Returns an XML representation of the component.
274     * </p>
275     *
276     * @return XLM snippet
277     */
278    public String getXML() {
279        setClass();
280        setIcon();
281        setIndex();
282        setTitle();
283        StringBuilder builder = new StringBuilder();
284        builder.append("<component");
285        if (parent != null){
286                if (!JFCComponent.isKnown(parent.component))
287                        throw new AssertionError("Referenced parent is not known.");
288                builder.append(" parent=\"" + Integer.toHexString(parent.component.hashCode()) + "\"");
289        }
290        builder.append(">"+ StringTools.ENDLINE);
291        builder.append(" <param name=\"title\" value=\"" + title + "\" />" + StringTools.ENDLINE);
292        builder.append(" <param name=\"class\" value=\"" + componentClass + "\" />" +
293            StringTools.ENDLINE);
294        builder.append(" <param name=\"icon\" value=\"" + icon + "\" />" + StringTools.ENDLINE);
295        builder.append(" <param name=\"index\" value=\"" + index + "\" />" + StringTools.ENDLINE);
296        builder.append(" <param name=\"hash\" value=\"" +
297            Integer.toHexString(component.hashCode()) + "\" />" + StringTools.ENDLINE);
298        builder.append(getInheritanceTree());
299        builder.append("</component>" + StringTools.ENDLINE);
300        return builder.toString();
301    }
302   
303    /**
304     * <p>
305     * Returns an XML representation of the components children.
306     * </p>
307     * @return XML representation of children
308     */
309    public String printChildren(){
310        StringBuilder builder = new StringBuilder();
311        for (JFCComponent child: children){
312                builder.append(child.getXML());
313                builder.append(child.printChildren());
314        }
315        return builder.toString();
316    }
317
318    /**
319     * <p>
320     * Removes a child component from the current component.
321     * </p>
322     *
323     * @param child
324     *            child component to be removed
325     */
326    private void removeChild(JFCComponent child) {
327        children.remove(child);
328    }
329
330    /**
331     * <p>
332     * Removes the component from the list of children of its parent.
333     * </p>
334     */
335    private void removeFromParent() {
336        if (parent != null) {
337            parent.removeChild(this);
338        }
339    }
340
341    /**
342     * <p>
343     * Triggers the removals of all child components from the GUI hierarchy, i.e., calls
344     * {@link #remove(Component)} for all child components.
345     * </p>
346     */
347    private void removeChildren() {
348        for (JFCComponent child : children) {
349            remove(child.component);
350        }
351    }
352
353    /**
354     * <p>
355     * Sets the {@link #title} of the component. The title is defined as follows (first in the list,
356     * that is not null):
357     * <ul>
358     * <li>accessible name of the component if available</li>
359     * <li>{@link #icon} of the component</li>
360     * <li>name of the component</li>
361     * <li>coordinates of the component</li>
362     * </ul>
363     * </p>
364     */
365    private void setTitle() {
366        title = null; // reset title
367
368        AccessibleContext accessibleContext = component.getAccessibleContext();
369        if (accessibleContext != null) {
370            title = accessibleContext.getAccessibleName();
371        }
372        if (title == null) {
373            title = icon;
374        }
375        if (title == null) {
376            title = component.getName();
377        }
378        if (title == null) {
379            // use coordinates as last resort
380            title = "Pos(" + component.getX() + "," + component.getY() + ")";
381        }
382    }
383
384    /**
385     * <p>
386     * Sets the {@link #componentClass} of the component.
387     * </p>
388     */
389    private void setClass() {
390        componentClass = component.getClass().getName();
391    }
392
393    /**
394     * <p>
395     * Sets the {@link #icon} of the component.
396     * </p>
397     */
398    private void setIcon() {
399        icon = null; // reset icon
400
401        Method getIconMethod;
402        try {
403            getIconMethod = component.getClass().getMethod("getIcon", new Class[0]);
404            if (getIconMethod != null) {
405                Object iconObject = getIconMethod.invoke(component, new Object[] { });
406                if (iconObject != null) {
407                    String iconPath = iconObject.toString();
408                    if (!iconPath.contains("@")) {
409                        System.out.println("iconPath");
410                        String[] splitResult =
411                            iconPath.split(File.separatorChar == '\\' ? "\\\\" : File.separator);
412                        icon = splitResult[splitResult.length - 1];
413                    }
414                }
415            }
416        }
417        catch (SecurityException e) {}
418        catch (NoSuchMethodException e) {}
419        catch (IllegalArgumentException e) {}
420        catch (IllegalAccessException e) {}
421        catch (InvocationTargetException e) {
422            System.err.println("Found method with name " + "getIcon" + " but could not access it.");
423        }
424    }
425
426    /**
427     * <p>
428     * Sets the {@link #index} of the component as the index in the parent, if it is accessible.
429     * </p>
430     */
431    private void setIndex() {
432        index = -1; // reset index
433
434        AccessibleContext accessibleContext = component.getAccessibleContext();
435        if (accessibleContext != null) {
436            index = accessibleContext.getAccessibleIndexInParent();
437        }
438    }
439   
440    /**
441     * <p>
442     * Constructs a string that represents inheritance of component.
443     * </p>
444     * @return
445     */
446    private String getInheritanceTree(){
447        StringBuilder builder = new StringBuilder();
448        Class<? extends Object> classobject = component.getClass();
449        while(classobject.getSuperclass() != null){
450                classobject = classobject.getSuperclass();
451                builder.append(" <ancestor name=\"");
452                builder.append(classobject.getName());
453                builder.append("\" />" + StringTools.ENDLINE);
454        }
455        return builder.toString();
456    }
457}
Note: See TracBrowser for help on using the repository browser.