diff --git a/P/Sd1/Array/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml b/P/Sd1/Array/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml deleted file mode 100644 index 8b89c977b1ee3e2eef78b7510558066a2834b957..0000000000000000000000000000000000000000 --- a/P/Sd1/Array/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<javadocOptions> - <docletArtifacts> - <docletArtifact /> - </docletArtifacts> - <tagletArtifacts> - <tagletArtifact /> - </tagletArtifacts> - <javadocResourcesDirectory>src/main/javadoc</javadocResourcesDirectory> -</javadocOptions> diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ClassTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ClassTarget.java deleted file mode 100644 index 29fe304b600129858b61b84e204d5274560c2f22..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ClassTarget.java +++ /dev/null @@ -1,2024 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2010,2011,2012,2013 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.Color; -import java.awt.EventQueue; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.swing.AbstractAction; -import javax.swing.JPopupMenu; - -import bluej.Config; -import bluej.debugger.DebuggerClass; -import bluej.debugger.gentype.Reflective; -import bluej.debugmgr.objectbench.InvokeListener; -import bluej.editor.Editor; -import bluej.editor.EditorManager; -import bluej.extensions.BClass; -import bluej.extensions.BClassTarget; -import bluej.extensions.BDependency; -import bluej.extensions.ExtensionBridge; -import bluej.extensions.event.ClassEvent; -import bluej.extensions.event.ClassTargetEvent; -import bluej.extmgr.ClassMenuObject; -import bluej.extmgr.ExtensionsManager; -import bluej.extmgr.MenuManager; -import bluej.graph.GraphEditor; -import bluej.graph.Moveable; -import bluej.graph.Vertex; -import bluej.parser.entity.EntityResolver; -import bluej.parser.entity.PackageResolver; -import bluej.parser.entity.ParsedReflective; -import bluej.parser.nodes.ParsedCUNode; -import bluej.parser.nodes.ParsedTypeNode; -import bluej.parser.symtab.ClassInfo; -import bluej.parser.symtab.Selection; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.PkgMgrFrame; -import bluej.pkgmgr.Project; -import bluej.pkgmgr.SourceInfo; -import bluej.pkgmgr.dependency.Dependency; -import bluej.pkgmgr.dependency.ExtendsDependency; -import bluej.pkgmgr.dependency.ImplementsDependency; -import bluej.pkgmgr.dependency.UsesDependency; -import bluej.pkgmgr.target.role.AbstractClassRole; -import bluej.pkgmgr.target.role.AppletClassRole; -import bluej.pkgmgr.target.role.ClassRole; -import bluej.pkgmgr.target.role.EnumClassRole; -import bluej.pkgmgr.target.role.InterfaceClassRole; -import bluej.pkgmgr.target.role.MIDletClassRole; -import bluej.pkgmgr.target.role.StdClassRole; -import bluej.pkgmgr.target.role.UnitTestClassRole; -import bluej.utility.Debug; -import bluej.utility.DialogManager; -import bluej.utility.FileEditor; -import bluej.utility.FileUtility; -import bluej.utility.JavaNames; -import bluej.utility.JavaReflective; -import bluej.utility.JavaUtils; -import bluej.views.ConstructorView; -import bluej.views.MethodView; - -/** - * A class target in a package, i.e. a target that is a class file built from - * Java source code - * - * @author Michael Cahill - * @author Michael Kolling - * @author Bruce Quig - */ -public class ClassTarget extends DependentTarget - implements Moveable, InvokeListener -{ - final static int MIN_WIDTH = 60; - final static int MIN_HEIGHT = 30; - private final static String editStr = Config.getString("pkgmgr.classmenu.edit"); - private final static String compileStr = Config.getString("pkgmgr.classmenu.compile"); - private final static String inspectStr = Config.getString("pkgmgr.classmenu.inspect"); - private final static String removeStr = Config.getString("pkgmgr.classmenu.remove"); - private final static String createTestStr = Config.getString("pkgmgr.classmenu.createTest"); - - // Define Background Colours - private final static Color compbg = new Color(200,150,100); - - private static String usesArrowMsg = Config.getString("pkgmgr.usesArrowMsg"); - - // temporary file name extension to trick windows if changing case only in - // class name - private static String TEMP_FILE_EXTENSION = "-temp"; - - // the role object represents the changing roles that are class - // target can have ie changing from applet to an interface etc - // 'role' should never be null - // role should be accessed using getRole() and set using - // setRole(). A role should not contain important state information - // because role objects are thrown away at a whim. - private ClassRole role = new StdClassRole(); - - // a flag indicating whether an editor, when opened for the first - // time, should display the interface of this class - private boolean openWithInterface = false; - - // cached information obtained by parsing the source code - // automatically becomes invalidated when the source code is - // edited - private SourceInfo sourceInfo = new SourceInfo(); - - // caches whether the class is abstract. Only accurate when the - // classtarget state is normal (ie. the class is compiled). - private boolean isAbstract; - - // a flag indicating whether an editor should have the naviview expanded/collapsed - private Boolean isNaviviewExpanded=null; - - // flag to prevent recursive calls to analyseDependancies() - private boolean analysing = false; - - private int ghostX; - private int ghostY; - private int ghostWidth; - private int ghostHeight; - private boolean isDragging = false; - private boolean isMoveable = true; - private boolean hasSource; - - // Whether the source has been modified since it was last compiled. This - // starts off as "true", which is a lie, but it prevents setting breakpoints - // in an initially uncompiled class. - private boolean modifiedSinceCompile = true; - - private String typeParameters = ""; - - //properties map to store values used in the editor from the props (if necessary) - private Map<String,String> properties = new HashMap<String,String>(); - - /** - * Create a new class target in package 'pkg'. - * - * @param pkg Description of the Parameter - * @param baseName Description of the Parameter - */ - public ClassTarget(Package pkg, String baseName) - { - this(pkg, baseName, null); - } - - /** - * Create a new class target in package 'pkg'. - * - * @param pkg Description of the Parameter - * @param baseName Description of the Parameter - * @param template Description of the Parameter - */ - public ClassTarget(Package pkg, String baseName, String template) - { - super(pkg, baseName); - hasSource = getSourceFile().canRead(); - - // we can take a guess at what the role is going to be for the - // object based on the start of the template name. If we get this - // wrong, its no great shame as it'll be fixed the first time they - // successfully analyse/compile the source. - if (template != null) { - if (template.startsWith("applet")) { - role = new AppletClassRole(); - } - else if (template.startsWith("unittest")) { - role = new UnitTestClassRole(true); - } - else if (template.startsWith("abstract")) { - role = new AbstractClassRole(); - } - else if (template.startsWith("interface")) { - role = new InterfaceClassRole(); - } - else if (template.startsWith("enum")) { - role = new EnumClassRole(); - } - else if (template.startsWith("midlet")) { - role = new MIDletClassRole(); - } - } - setGhostPosition(0, 0); - setGhostSize(0, 0); - } - - private BClass singleBClass; // Every Target has none or one BClass - private BClassTarget singleBClassTarget; // Every Target has none or one BClassTarget - - /** - * Return the extensions BProject associated with this Project. - * There should be only one BProject object associated with each Project. - * @return the BProject associated with this Project. - */ - public synchronized final BClass getBClass () - { - if ( singleBClass == null ) { - singleBClass = ExtensionBridge.newBClass(this); - } - - return singleBClass; - } - - /** - * Returns the {@link BClassTarget} associated with this {@link ClassTarget} - * . There should be only one {@link BClassTarget} object associated with - * each {@link ClassTarget}. - * - * @return The {@link BClassTarget} associated with this {@link ClassTarget}. - */ - public synchronized final BClassTarget getBClassTarget() - { - if (singleBClassTarget == null) { - singleBClassTarget = ExtensionBridge.newBClassTarget(this); - } - - return singleBClassTarget; - } - - - /** - * Return the target's name, including the package name. eg. - * bluej.pkgmgr.Target - * - * @return The qualifiedName value - */ - public String getQualifiedName() - { - return getPackage().getQualifiedName(getBaseName()); - } - - /** - * Return the target's base name (ie the name without the package name). eg. - * Target - * - * @return The baseName value - */ - public String getBaseName() - { - return getIdentifierName(); - } - - /** - * Return information about the source of this class. - * - * @return The source info object. - */ - public SourceInfo getSourceInfo() - { - return sourceInfo; - } - - /** - * Get a reflective for the type represented by this target. - * - * @return A suitable reflective, or null. - */ - public Reflective getTypeRefelective() - { - // If compiled, return a reflective based on actual reflection - if (isCompiled()) { - Class<?> cl = getPackage().loadClass(getQualifiedName()); - if (cl != null) { - return new JavaReflective(cl); - } - else { - return null; - } - } - - // Not compiled; try to get a reflective from the parser - ParsedCUNode node = null; - getEditor(); - if (editor != null) { - node = editor.getParsedNode(); - } - - if (node != null) { - ParsedTypeNode ptn = (ParsedTypeNode) node.getTypeNode(getBaseName()); - if (ptn != null) { - return new ParsedReflective(ptn); - } - } - - return null; - } - - /** - * Returns the text which the target is displaying as its label. For normal - * classes this is just the identifier name. For generic classes the generic - * parameters are shown as well - * - * @return The displayName value - */ - @Override - public String getDisplayName() - { - return super.getDisplayName() + getTypeParameters(); - } - - /** - * Returns the type parameters for a generic class as declared in the source - * file. - * - * @return The typeParameters value - */ - private String getTypeParameters() - { - return typeParameters; - } - - /** - * Change the state of this target. The target will be repainted to show the - * new state. - * - * @param newState The new state value - */ - @Override - public void setState(int newState) - { - if (state != newState) { - getPackage().getProject().removeInspectorInstance(getQualifiedName()); - - // Notify extensions if necessary. Note we don't distinguish - // S_COMPILING and S_INVALID. - if (newState == S_NORMAL) { - modifiedSinceCompile = false; - if (editor != null) { - editor.reInitBreakpoints(); - } - ClassEvent event = new ClassEvent(ClassEvent.STATE_CHANGED, getPackage(), getBClass(), true); - ExtensionsManager.getInstance().delegateEvent(event); - } - else if (state == S_NORMAL) { - ClassEvent event = new ClassEvent(ClassEvent.STATE_CHANGED, getPackage(), getBClass(), false); - ExtensionsManager.getInstance().delegateEvent(event); - } - - state = newState; - repaint(); - } - } - - /** - * Return the role object for this class target. - * - * @return The role value - */ - public ClassRole getRole() - { - return role; - } - - /** - * Set the role for this class target. - * - * <p>Avoids changing over the role object if the new one is of the same type. - * - * @param newRole The new role value - */ - protected void setRole(ClassRole newRole) - { - if (role.getRoleName() != newRole.getRoleName()) { - role = newRole; - } - } - - /** - * Test if a given class is a Junit 4 test class. - * - * <p>In Junit4, test classes can be of any type. - * The only way to test is to check if it has one of the following annotations: - * @Before, @Test or @After - * - * @param cl class to test - */ - @SuppressWarnings("unchecked") - public static boolean isJunit4TestClass(Class<?> cl) - { - ClassLoader clLoader = cl.getClassLoader(); - try { - Class<? extends Annotation> beforeClass = - (Class<? extends Annotation>) Class.forName("org.junit.Before", false, clLoader); - Class<? extends Annotation> afterClass = - (Class<? extends Annotation>) Class.forName("org.junit.After", false, clLoader); - Class<? extends Annotation> testClass = - (Class<? extends Annotation>) Class.forName("org.junit.Test", false, clLoader); - - Method[] methods = cl.getDeclaredMethods(); - for (int i=0; i<methods.length; i++) { - if (methods[i].getAnnotation(beforeClass) != null) { - return true; - } - if (methods[i].getAnnotation(afterClass) != null) { - return true; - } - if (methods[i].getAnnotation(testClass) != null) { - return true; - } - } - - } - catch (ClassNotFoundException cnfe) {} - catch (LinkageError le) {} - - // No suitable annotations found, so not a test class - return false; - } - - /** - * Use a variety of tests to determine what our role is. - * - * <p>All tests must be very quick and should not rely on any significant - * computation (ie. reparsing). If computation is required, the existing - * role will do for the time being. - * - * @param cl Description of the Parameter - */ - public void determineRole(Class<?> cl) - { - isAbstract = false; - - if (cl != null) { - isAbstract = Modifier.isAbstract(cl.getModifiers()); - - ClassLoader clLoader = cl.getClassLoader(); - Class<?> junitClass = null; - Class<?> appletClass = null; - Class<?> midletClass = null; - - // It shouldn't ever be the case that the class is on the bootstrap - // class path (and was loaded by the bootstrap class loader), unless - // someone has done something rather strange - but it has happened; - // see bug # 1017. - - if (clLoader != null) { - try { - junitClass = clLoader.loadClass("junit.framework.TestCase"); - } - catch (ClassNotFoundException cnfe) {} - catch (LinkageError le) {} - - try { - appletClass = clLoader.loadClass("java.applet.Applet"); - } - catch (ClassNotFoundException cnfe) {} - catch (LinkageError le) {} - - try { - midletClass = clLoader.loadClass("javax.microedition.midlet.MIDlet"); - } - catch (ClassNotFoundException cnfe) {} - catch (LinkageError le) {} - } - - if (junitClass == null) { - junitClass = junit.framework.TestCase.class; - } - - if (appletClass == null) { - appletClass = java.applet.Applet.class; - } - - // As cl is non-null, it is the definitive information - // source ie. if it thinks its an applet who are we to argue - // with it. - if (appletClass.isAssignableFrom(cl)) { - setRole(new AppletClassRole()); - } - else if (junitClass.isAssignableFrom(cl)) { - setRole(new UnitTestClassRole(false)); - } - else if (Modifier.isInterface(cl.getModifiers())) { - setRole(new InterfaceClassRole()); - } - else if (JavaUtils.getJavaUtils().isEnum(cl)) { - setRole(new EnumClassRole()); - } - else if (isAbstract) { - setRole(new AbstractClassRole()); - } - else if ( ( midletClass != null ) && ( midletClass.isAssignableFrom(cl) ) ) { - setRole(new MIDletClassRole()); - } - else if (isJunit4TestClass(cl)) { - setRole(new UnitTestClassRole(true)); - } - else { - setRole(new StdClassRole()); - } - } - else { - // try the parsed source code - ClassInfo classInfo = sourceInfo.getInfoIfAvailable(); - - if (classInfo != null) { - if (classInfo.isApplet()) { - setRole(new AppletClassRole()); - } - else if (classInfo.isMIDlet()) { - setRole(new MIDletClassRole()); - } - else if (classInfo.isUnitTest()) { - setRole(new UnitTestClassRole(false)); - } - else if (classInfo.isInterface()) { - setRole(new InterfaceClassRole()); - } - else if (classInfo.isEnum()) { - setRole(new EnumClassRole()); - } - else if (classInfo.isAbstract()) { - setRole(new AbstractClassRole()); - } - else { - // We shouldn't override applet/unit test class roles based only - // on source analysis: if they inherit only indirectly from Applet - // or UnitTest, source analysis won't give the correct role - if (! (role instanceof AppletClassRole) && - ! (role instanceof UnitTestClassRole)) - { - setRole(new StdClassRole()); - } - } - } - // If no information gained from parsing the file (classInfo = null), - // then we don't really know the role: let's leave it as it was - } - } - - /** - * Load existing information about this class target - * - * @param props the properties object to read - * @param prefix an internal name used for this target to identify its - * properties in a properties file used by multiple targets. - * @exception NumberFormatException Description of the Exception - */ - @Override - public void load(Properties props, String prefix) - throws NumberFormatException - { - super.load(props, prefix); - - // try to determine if any role was set when we saved - // the class target. Be careful here as if you add role types - // you need to add them here as well. - String type = props.getProperty(prefix + ".type"); - - String intf = props.getProperty(prefix + ".showInterface"); - openWithInterface = Boolean.valueOf(intf).booleanValue(); - - if (AppletClassRole.APPLET_ROLE_NAME.equals(type)) { - setRole(new AppletClassRole()); - } - else if (MIDletClassRole.MIDLET_ROLE_NAME.equals(type)) { - setRole(new MIDletClassRole()); - } - else if (UnitTestClassRole.UNITTEST_ROLE_NAME.equals(type)) { - setRole(new UnitTestClassRole(false)); - } - else if (UnitTestClassRole.UNITTEST_ROLE_NAME_JUNIT4.equals(type)) { - setRole(new UnitTestClassRole(true)); - } - else if (AbstractClassRole.ABSTRACT_ROLE_NAME.equals(type)) { - setRole(new AbstractClassRole()); - } - else if (InterfaceClassRole.INTERFACE_ROLE_NAME.equals(type)) { - setRole(new InterfaceClassRole()); - } - else if (EnumClassRole.ENUM_ROLE_NAME.equals(type)) { - setRole(new EnumClassRole()); - } - - getRole().load(props, prefix); - String value=props.getProperty(prefix + ".naviview.expanded"); - if (value!=null){ - setNaviviewExpanded(Boolean.parseBoolean(value)); - setProperty(NAVIVIEW_EXPANDED_PROPERTY, String.valueOf(value)); - } - } - - /** - * Save information about this class target - * - * - * @param props the properties object to save to - * @param prefix an internal name used for this target to identify its - * properties in a properties file used by multiple targets. - */ - @Override - public void save(Properties props, String prefix) - { - super.save(props, prefix); - - if (getRole().getRoleName() != null) { - props.put(prefix + ".type", getRole().getRoleName()); - } - - if (editorOpen()) { - openWithInterface = getEditor().isShowingInterface(); - } - //saving the state of the naviview (open/close) to the props - //setting the value of the expanded according to the value from the editor (if there is) - //else if there was a previous setting use that - if (editorOpen() && getProperty(NAVIVIEW_EXPANDED_PROPERTY)!=null){ - props.put(prefix + ".naviview.expanded", String.valueOf(getProperty(NAVIVIEW_EXPANDED_PROPERTY))); - } else if (isNaviviewExpanded!=null) - props.put(prefix + ".naviview.expanded", String.valueOf(isNaviviewExpanded())); - - props.put(prefix + ".showInterface", new Boolean(openWithInterface).toString()); - - getRole().save(props, 0, prefix); - - - } - - /** - * Notification that the source file may have been updated, and so we should - * reload. - */ - public void reload() - { - hasSource = getSourceFile().canRead(); - if (hasSource) { - if (editor != null) { - editor.reloadFile(); - } - else { - analyseSource(); - } - } - } - - /** - * Check if the compiled class and the source are up to date. - * (Specifically, check if recompilation is not needed. This will - * always be considered true if the target has no source). - * - * @return true if they are in sync (or there is no source); otherwise false. - */ - public boolean upToDate() - { - // check if the class file is up to date - File src = getSourceFile(); - File clss = getClassFile(); - - // if just a .class file with no src, it better be up to date - if (!hasSourceCode()) { - return true; - } - - if (!clss.exists() || (src.exists() && (src.lastModified() > clss.lastModified()))) { - return false; - } - - return true; - } - - /** - * Mark this class as modified, and mark all dependent classes too - */ - public void invalidate() - { - setState(S_INVALID); - for (Iterator<? extends Dependency> it = dependents(); it.hasNext();) { - Dependency d = it.next(); - ClassTarget dependent = (ClassTarget) d.getFrom(); - - if (! dependent.isInvalidState()) { - // Invalidate the dependent only if it is not already invalidated. - // Will avoid going into an infinite circular loop. - dependent.invalidate(); - } - } - } - - /** - * Verify whether this class target is an interface class - * - * @return true if class target is an interface class, else returns false - */ - public boolean isInterface() - { - return (getRole() instanceof InterfaceClassRole); - } - - /** - * Verify whether this class target is an unit test class - * - * @return true if class target is a unit test class, else returns false - */ - public boolean isUnitTest() - { - return (getRole() instanceof UnitTestClassRole); - } - - /** - * Verify whether this class target represents an Enum - * - * @return true if class target represents an Enum, else false - */ - public boolean isEnum() - { - return (getRole() instanceof EnumClassRole); - } - - /** - * Check whether this class target represents an abstract class. This - * can be true regardless of the role (unit test, applet, standard class). - * - * The return is only valid if isCompiled() is true. - */ - public boolean isAbstract() - { - return isAbstract; - } - - // --- Target interface --- - - /** - * Gets the backgroundColour attribute of the ClassTarget object - * - * @return The backgroundColour value - */ - public Paint getBackgroundPaint(int width, int height) - { - if (state == S_COMPILING) { - return compbg; - } - else { - return getRole().getBackgroundPaint(width, height); - } - } - - - // --- EditableTarget interface --- - - /** - * Tell whether we have access to the source for this class. - * - * @return Description of the Return Value - */ - public boolean hasSourceCode() - { - return hasSource; - } - - /** - * @return the name of the (text) file this target corresponds to. - */ - public File getSourceFile() - { - return new File(getPackage().getPath(), getBaseName() + ".java"); - } - - /** - * @return the name of the context(.ctxt) file this target corresponds to. - */ - public File getContextFile() - { - return new File(getPackage().getPath(), getBaseName() + ".ctxt"); - } - - /** - * @return the name of the class (.class) file this target corresponds to. - */ - public File getClassFile() - { - return new File(getPackage().getPath(), getBaseName() + ".class"); - } - - /** - * Get the name of the documentation (.html) file corresponding to this target. - */ - public File getDocumentationFile() - { - String filename = getSourceFile().getPath(); - String docFilename = getPackage().getProject().getDocumentationFile(filename); - return new File(docFilename); - } - - /** - * Get a list of .class files for inner classes. - */ - public File [] getInnerClassFiles() - { - File[] files = getPackage().getPath().listFiles(new InnerClassFileFilter()); - return files; - } - - /** - * Description of the Class - */ - class InnerClassFileFilter - implements FileFilter - { - /** - * Description of the Method - * - * @param pathname Description of the Parameter - * @return Description of the Return Value - */ - public boolean accept(File pathname) - { - return pathname.getName().startsWith(getBaseName() + "$"); - } - } - - /** - * Get the editor associated with this class. - * @return the editor object associated with this target. May be null if - * there was a problem opening this editor. - */ - public Editor getEditor() - { - return getEditor(openWithInterface); - } - - /** - * Get an editor for this class, either in source view or interface view. - * - * @param showInterface Determine whether to show interface view or - * source view in the editor. - * @return the editor object associated with this target. May be null if - * there was a problem opening this editor. - */ - private Editor getEditor(boolean showInterface) - { - // ClassTarget must have source code if it is to provide an editor - if (editor == null) { - String filename = getSourceFile().getPath(); - String docFilename = getPackage().getProject().getDocumentationFile(filename); - if (! hasSourceCode()) { - filename = null; // no source - show docs only - showInterface = true; - if (! new File(docFilename).exists()) { - return null; - } - } - - Project project = getPackage().getProject(); - EntityResolver resolver = new PackageResolver(project.getEntityResolver(), - getPackage().getQualifiedName()); - - if (editorBounds == null) { - PkgMgrFrame frame = PkgMgrFrame.findFrame(getPackage()); - if (frame != null) { - editorBounds = new Rectangle(); - editorBounds.x = frame.getX() + 40; - editorBounds.y = frame.getY() + 20; - } - } - - editor = EditorManager.getEditorManager().openClass(filename, docFilename, - project.getProjectCharset(), - getBaseName(), this, isCompiled(), editorBounds, resolver, - project.getJavadocResolver()); - - // editor may be null if source has been deleted - // for example. - if (editor != null) { - editor.showInterface(showInterface); - } - } - return editor; - } - - /** - * Ensure that the source file of this class is up-to-date (i.e. - * that any possible unsaved changes in an open editor window are - * saved). - * - * <p>This can cause saveEvent() to be generated, which might move - * the class to a new package (if the package line has been changed). - */ - @Override - public void ensureSaved() throws IOException - { - if(editor != null) { - editor.save(); - } - } - - // --- end of EditableTarget interface --- - - // --- user interface function implementation --- - - /** - */ - private void inspect() - { - new Thread() { - - int state = 0; - DebuggerClass clss; - - @Override - public void run() { - switch (state) { - // This is the intial state. Try and load the class. - case 0: - try { - clss = getPackage().getDebugger().getClass(getQualifiedName(), true); - state = 1; - EventQueue.invokeLater(this); - } - catch (ClassNotFoundException cnfe) {} - break; - - // Once this state is reached, we're running on the Swing event queue. - case 1: - getPackage().getProject().getClassInspectorInstance(clss, getPackage(), PkgMgrFrame.findFrame(getPackage())); - } - } - }.start(); - } - - // --- EditorWatcher interface --- - - @Override - public void modificationEvent(Editor editor) - { - invalidate(); - if (! modifiedSinceCompile) { - removeBreakpoints(); - getPackage().getProject().getDebugger().removeBreakpointsForClass(getQualifiedName()); - modifiedSinceCompile = true; - } - sourceInfo.setSourceModified(); - } - - @Override - public void saveEvent(Editor editor) - { - ClassInfo info = analyseSource(); - if (info != null) { - updateTargetFile(info); - } - determineRole(null); - } - - @Override - public String breakpointToggleEvent(Editor editor, int lineNo, boolean set) - { - if (isCompiled() || ! modifiedSinceCompile) { - String possibleError = getPackage().getDebugger().toggleBreakpoint(getQualifiedName(), lineNo, set, null); - return possibleError; - } - else { - return Config.getString("pkgmgr.breakpointMsg"); - } - } - - // --- end of EditorWatcher interface --- - - /** - * Remove all breakpoints in this class. - */ - public void removeBreakpoints() - { - if (editor != null) { - editor.removeBreakpoints(); - } - } - - /** - * Re-initialize the breakpoints which have been set in this - * class. - */ - public void reInitBreakpoints() - { - if (editor != null && isCompiled()) { - editor.reInitBreakpoints(); - } - } - - /** - * Remove the step mark in this case - * (the mark in the editor that shows where execution is) - */ - public void removeStepMark() - { - if (editor != null) { - editor.removeStepMark(); - } - } - - /** - * Gets the compiled attribute of the ClassTarget object - * - * @return The compiled value - */ - public boolean isCompiled() - { - return (state == S_NORMAL); - } - - /** - * Description of the Method - * - * @param editor Description of the Parameter - */ - @Override - public void compile(Editor editor) - { - getPackage().compile(this); - } - - /** - * Called when this class target has just been successfully compiled. - * - * We load the compiled class if possible and check it the compilation has - * resulted in it taking a different role (ie abstract to applet) - */ - public void endCompile() - { - Class<?> cl = getPackage().loadClass(getQualifiedName()); - - determineRole(cl); - analyseDependencies(cl); - } - - /** - * generates a source code skeleton for this class - */ - public boolean generateSkeleton(String template) - { - // delegate to role object - if (template == null) { - Debug.reportError("generate class skeleton error"); - return false; - } - else { - boolean success = role.generateSkeleton(template, getPackage(), getBaseName(), getSourceFile().getPath()); - if (success) { - // skeleton successfully generated - setState(S_INVALID); - hasSource = true; - return true; - } - return false; - } - } - - /** - * Description of the Method - * - * @param packageName Description of the Parameter - * @exception IOException Description of the Exception - */ - public void enforcePackage(String packageName) - throws IOException - { - if (!JavaNames.isQualifiedIdentifier(packageName)) { - throw new IllegalArgumentException(); - } - - ClassInfo info = sourceInfo.getInfo(getSourceFile(), getPackage()); - if (info == null) { - return; - } - - // We may or may not need to change each of the semi colon selection text, - // package name selection text, and package statement selection text. - String semiReplacement = null; - String nameReplacement = null; - String pkgStatementReplacement = null; - - // Figure out if we need to change anything, and if so, what: - if (packageName.length() == 0) { - if (info.hasPackageStatement()) { - // we must delete all parts of the "package" statement - semiReplacement = ""; - nameReplacement = ""; - pkgStatementReplacement = ""; - } - else { - // if we have no package statement we do not need - // to do anything to turn it into an anonymous package - return; - } - } - else { - if (info.hasPackageStatement()) { - // it is trivial to make the package name the same - if (info.getPackage().equals(packageName)) { - return; - } - // we must change just the package name - nameReplacement = packageName; - } - else { - // we must insert all the "package" statement - semiReplacement = ";\n\n"; - nameReplacement = packageName; - pkgStatementReplacement = "package "; - } - } - - // Change the relevant parts of the file - FileEditor fed = new FileEditor(getSourceFile()); - - if (semiReplacement != null) { - Selection selSemi = info.getPackageSemiSelection(); - fed.replaceSelection(selSemi, semiReplacement); - } - - if (nameReplacement != null) { - Selection selName = info.getPackageNameSelection(); - fed.replaceSelection(selName, nameReplacement); - } - - if (pkgStatementReplacement != null) { - Selection selStatement = info.getPackageStatementSelection(); - fed.replaceSelection(selStatement, pkgStatementReplacement); - } - - // save changes back to disk - fed.save(); - } - - /** - * Analyse the source code, and save retrieved information. - * This includes comments and parameter names for methods/constructors, - * class name, type parameters, etc. - * <p> - * Also causes the class role (normal class, unit test, etc) to be - * guessed based on the source. - */ - public ClassInfo analyseSource() - { - if (analysing) { - return null; - } - - analysing = true; - - ClassInfo info = sourceInfo.getInfo(getSourceFile(), getPackage()); - - // info will be null if the source was unparseable - if (info != null) { - // the following may update the package display but it - // will not modify the classes source code - determineRole(null); - setTypeParameters(info); - analyseDependencies(info); - } - - // getPackage().repaint(); - - analysing = false; - return info; - } - - /** - * Change file name and package to match that found in the source file. - * @param info The information from source analysis - */ - private void updateTargetFile(ClassInfo info) - { - if (analyseClassName(info)) { - if (nameEqualsIgnoreCase(info.getName())) { - // this means file has same name but different case - // to trick Windows OS to do a name change we need to - // rename to temp name and then rename to desired name - doClassNameChange(info.getName() + TEMP_FILE_EXTENSION); - } - doClassNameChange(info.getName()); - } - if (analysePackageName(info)) { - doPackageNameChange(info.getPackage()); - } - } - - /** - * Sets the typeParameters attribute of the ClassTarget object - * - * @param info The new typeParameters value - */ - public void setTypeParameters(ClassInfo info) - { - String newTypeParameters = ""; - if (info.hasTypeParameter()) { - Iterator<String> i = info.getTypeParameterTexts().iterator(); - newTypeParameters = "<" + i.next(); - - while (i.hasNext()) { - newTypeParameters += "," + i.next(); - } - newTypeParameters += ">"; - } - if (!newTypeParameters.equals(typeParameters)) { - typeParameters = newTypeParameters; - updateSize(); - } - } - - /** - * Analyses class name of Classtarget with that of parsed src file. Aim is - * to detect any textual changes of class name and modify resources to suit - * - * - * @param info contains parsed class information - * @return true if class name is different - */ - public boolean analyseClassName(ClassInfo info) - { - String newName = info.getName(); - - if ((newName == null) || (newName.length() == 0)) { - return false; - } - - return (!getBaseName().equals(newName)); - } - - /** - * Check whether the package name has been changed by comparing the package - * name in the information from the parser with the current package name - */ - public boolean analysePackageName(ClassInfo info) - { - String newName = info.getPackage(); - - return (!getPackage().getQualifiedName().equals(newName)); - } - - /** - * Analyse the current dependencies in the source code and update the - * dependencies in the graphical display accordingly. - */ - public void analyseDependencies(ClassInfo info) - { - // currently we don't remove uses dependencies, but just warn - - //removeAllOutDependencies(); - removeInheritDependencies(); - unflagAllOutDependencies(); - - String pkgPrefix = getPackage().getQualifiedName(); - pkgPrefix = (pkgPrefix.length() == 0) ? pkgPrefix : pkgPrefix + "."; - - // handle superclass dependency - if (info.getSuperclass() != null) { - setSuperClass(info.getSuperclass()); - } - - // handle implemented interfaces - List<String> vect = info.getImplements(); - for (Iterator<String> it = vect.iterator(); it.hasNext();) { - String name = it.next(); - addInterface(name); - } - - // handle used classes - vect = info.getUsed(); - for (Iterator<String> it = vect.iterator(); it.hasNext();) { - String name = it.next(); - DependentTarget used = getPackage().getDependentTarget(name); - if (used != null) { - if (used.getAssociation() == this || this.getAssociation() == used) { - continue; - } - - getPackage().addDependency(new UsesDependency(getPackage(), this, used), true); - } - } - - // check for inconsistent use dependencies - for (Iterator<UsesDependency> it = usesDependencies(); it.hasNext();) { - UsesDependency usesDep = ((UsesDependency) it.next()); - if (!usesDep.isFlagged()) { - getPackage().setStatus(usesArrowMsg + usesDep); - } - } - } - - /** - * Analyse the current dependencies in the compiled class and update the - * dependencies in the graphical display accordingly. - */ - public void analyseDependencies(Class<?> cl) - { - if (cl != null) { - removeInheritDependencies(); - - Class<?> superClass = cl.getSuperclass(); - if (superClass != null) { - setSuperClass(superClass.getName()); - } - - Class<?> [] interfaces = cl.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - addInterface(interfaces[i].getName()); - } - } - } - - - /** - * Set the superclass. This adds an extends dependency to the appropriate class. - * The old extends dependency (if any) must be removed separately. - * - * @param superName the fully-qualified name of the superclass - */ - private void setSuperClass(String superName) - { - String pkgPrefix = getPackage().getQualifiedName(); - if (superName.startsWith(pkgPrefix)) { - // Must account for the final "." in the fully qualified name, if the package is - // not the default package: - int prefixLen = pkgPrefix.length(); - prefixLen = prefixLen == 0 ? 0 : prefixLen + 1; - - superName = superName.substring(prefixLen); - DependentTarget superclass = getPackage().getDependentTarget(superName); - if (superclass != null) { - getPackage().addDependency(new ExtendsDependency(getPackage(), this, superclass), false); - if (superclass.getState() != S_NORMAL) { - setState(S_INVALID); - } - } - } - } - - /** - * Add an interface. This adds an implements dependency to the appropriate interface. - */ - private void addInterface(String interfaceName) - { - String pkgPrefix = getPackage().getQualifiedName(); - if (interfaceName.startsWith(pkgPrefix)) { - int dotlen = pkgPrefix.length(); - // If not the default package, we must account for the extra '.' - dotlen = (dotlen == 0) ? 0 : (dotlen + 1); - interfaceName = interfaceName.substring(dotlen); - DependentTarget interfce = getPackage().getDependentTarget(interfaceName); - - if (interfce != null) { - getPackage().addDependency(new ImplementsDependency(getPackage(), this, interfce), false); - if (interfce.getState() != S_NORMAL) { - setState(S_INVALID); - } - } - } - } - - /** - * Notification that the class represented by this class target has changed name. - */ - private boolean doClassNameChange(String newName) - { - //need to check that class does not already exist - if (getPackage().getTarget(newName) != null) { - getPackage().showError("duplicate-name"); - return false; - } - - File newSourceFile = new File(getPackage().getPath(), newName + ".java"); - File oldSourceFile = getSourceFile(); - - try { - FileUtility.copyFile(oldSourceFile, newSourceFile); - - getPackage().updateTargetIdentifier(this, getIdentifierName(), newName); - - String filename = newSourceFile.getAbsolutePath(); - String docFilename = getPackage().getProject().getDocumentationFile(filename); - getEditor().changeName(newName, filename, docFilename); - - oldSourceFile.delete(); - getClassFile().delete(); - getContextFile().delete(); - getDocumentationFile().delete(); - - // this is extremely dangerous code here.. must track all - // variables which are set when ClassTarget is first - // constructed and fix them up for new class name - String oldName = getIdentifierName(); - setIdentifierName(newName); - setDisplayName(newName); - updateSize(); - - // Update the BClass object - BClass bClass = getBClass(); - ExtensionBridge.ChangeBClassName(bClass, getQualifiedName()); - - // Update the BClassTarget object - BClassTarget bClassTarget = getBClassTarget(); - ExtensionBridge.changeBClassTargetName(bClassTarget, getQualifiedName()); - - // Update all BDependency objects related to this target - for (Iterator<? extends Dependency> iterator = dependencies(); iterator.hasNext();) { - Dependency outgoingDependency = iterator.next(); - BDependency bDependency = outgoingDependency.getBDependency(); - ExtensionBridge.changeBDependencyOriginName(bDependency, getQualifiedName()); - } - - for (Iterator<? extends Dependency> iterator = dependents(); iterator.hasNext();) { - Dependency incomingDependency = iterator.next(); - BDependency bDependency = incomingDependency.getBDependency(); - ExtensionBridge.changeBDependencyTargetName(bDependency, getQualifiedName()); - } - - // Inform all listeners about the name change - ClassEvent event = new ClassEvent(ClassEvent.CHANGED_NAME, getPackage(), getBClass(), oldName); - ExtensionsManager.getInstance().delegateEvent(event); - - return true; - } - catch (IOException ioe) { - return false; - } - } - - /** - * Checks for ClassTarget name equality if case is ignored. - * - * - * @param newName - * @return true if name is equal ignoring case. - */ - private boolean nameEqualsIgnoreCase(String newName) - { - return (getBaseName().equalsIgnoreCase(newName)); - } - - /** - * Change the package of a class target to something else. - * - * - * @param newName the new fully qualified package name - */ - private void doPackageNameChange(String newName) - { - Project proj = getPackage().getProject(); - - Package dstPkg = proj.getPackage(newName); - - if (dstPkg == null) { - DialogManager.showError(null, "package-name-invalid"); - } - else { - // fix for bug #382. Potentially could clash with a package - // in the destination package with the same name - if (dstPkg.getTarget(getBaseName()) != null) { - DialogManager.showError(null, "package-name-clash"); - // fall through to enforcePackage, below. - } - else if (DialogManager.askQuestion(null, "package-name-changed") == 0) { - dstPkg.importFile(getSourceFile()); - prepareForRemoval(); - getPackage().removeTarget(this); - close(); - return; - } - } - - // all non working paths lead here.. lets fix the package line - // up so it is back to what we expect - try { - enforcePackage(getPackage().getQualifiedName()); - getEditor().reloadFile(); - } - catch (IOException ioe) {} - } - - /** - * Resizes the class so the entire classname + type parameter are visible - * - */ - private void updateSize() - { - int width = calculateWidth(getDisplayName()); - setSize(width, getHeight()); - repaint(); - } - - /** - * Construct a popup menu for the class target, including caching of - * results. - */ - protected JPopupMenu menu = null; - boolean compiledMenu = false; - - /** - * Post the context menu for this target. - * - * @param x the x coordinate for the menu, relative to graph editor - * @param y the y coordinate for the menu, relative to graph editor - */ - @Override - public void popupMenu(int x, int y, GraphEditor graphEditor) - { - Class<?> cl = null; - - if (state == S_NORMAL) { - // handle error causes when loading classes which are compiled - // but not loadable in the current VM. (Eg if they were compiled - // for a later VM). - // we detect the error, remove the class file, and invalidate - // to allow them to be recompiled - cl = getPackage().loadClass(getQualifiedName()); - if (cl == null) { - // trouble loading the class - // remove the class file and invalidate the target - if (hasSourceCode()) { - getClassFile().delete(); - invalidate(); - } - } - } - - // check that the class loading hasn't changed out state - if (state == S_NORMAL) { - menu = createMenu(cl); - // editor.add(menu); - } - else { - menu = createMenu(null); - // editor.add(menu); - } - - if (menu != null) { - menu.show(graphEditor, x, y); - } - } - - /** - * Creates a popup menu for this class target. - * - * @param cl class object associated with this class target - * @return the created popup menu object - */ - protected JPopupMenu createMenu(Class<?> cl) - { - JPopupMenu menu = new JPopupMenu(getBaseName() + " operations"); - - // call on role object to add any options needed at top - role.createRoleMenu(menu, this, cl, state); - - if (cl != null) { - if (role.createClassConstructorMenu(menu, this, cl)) { - menu.addSeparator(); - } - } - - if (cl != null) { - if (role.createClassStaticMenu(menu, this, cl)) { - menu.addSeparator(); - } - } - boolean sourceOrDocExists = hasSourceCode() || getDocumentationFile().exists(); - role.addMenuItem(menu, new EditAction(), sourceOrDocExists); - role.addMenuItem(menu, new CompileAction(), hasSourceCode()); - role.addMenuItem(menu, new InspectAction(), cl != null); - role.addMenuItem(menu, new RemoveAction(), true); - - // call on role object to add any options needed at bottom - role.createRoleMenuEnd(menu, this, state); - - MenuManager menuManager = new MenuManager(menu); - menuManager.setAttachedObject(new ClassMenuObject(this)); - menuManager.addExtensionMenu(getPackage().getProject()); - - return menu; - } - - /** - * Action which creates a test - */ - public class CreateTestAction extends AbstractAction - { - /** - * Constructor for the CreateTestAction object - */ - public CreateTestAction() - { - putValue(NAME, createTestStr); - } - - @Override - public void actionPerformed(ActionEvent e) - { - PkgMgrFrame pmf = PkgMgrFrame.findFrame(getPackage()); - - if (pmf != null) { - String testClassName = getIdentifierName() + "Test"; - pmf.createNewClass(testClassName, "unittest", true); - // we want to check that the previous called actually - // created a unit test class as a name clash with an existing - // class would not. This prevents a non unit test becoming - // associated with a class unintentionally - Target target = getPackage().getTarget(testClassName); - ClassTarget ct = null; - if (target instanceof ClassTarget) { - ct = (ClassTarget) target; - if (ct != null && ct.isUnitTest()) { - setAssociation((DependentTarget) getPackage().getTarget(getIdentifierName() + "Test")); - } - } - updateAssociatePosition(); - getPackage().getEditor().revalidate(); - getPackage().getEditor().repaint(); - - } - } - } - - /** - * Action to open the editor for a classtarget - */ - private class EditAction extends AbstractAction - { - public EditAction() - { - putValue(NAME, editStr); - } - - @Override - public void actionPerformed(ActionEvent e) - { - open(); - } - } - - /** - * Action to compile a classtarget - */ - private class CompileAction extends AbstractAction - { - public CompileAction() - { - putValue(NAME, compileStr); - } - - @Override - public void actionPerformed(ActionEvent e) - { - getPackage().compile(ClassTarget.this); - } - } - - /** - * Action to remove a classtarget from its package - */ - private class RemoveAction extends AbstractAction - { - public RemoveAction() - { - putValue(NAME, removeStr); - } - - @Override - public void actionPerformed(ActionEvent e) - { - PkgMgrFrame pmf = PkgMgrFrame.findFrame(getPackage()); - if (pmf.askRemoveClass()) { - getPackage().getEditor().raiseRemoveTargetEvent(ClassTarget.this); - } - } - } - - /** - * Action to inspect the static members of a class - */ - private class InspectAction extends AbstractAction - { - public InspectAction() - { - putValue(NAME, inspectStr); - } - - @Override - public void actionPerformed(ActionEvent e) - { - if (checkDebuggerState()) { - inspect(); - } - } - } - - /** - * Process a double click on this target. That is: open its editor. - * - * @param evt Description of the Parameter - */ - @Override - public void doubleClick(MouseEvent evt) - { - open(); - } - - /** - * @return Returns the ghostX. - */ - @Override - public int getGhostX() - { - return ghostX; - } - - /** - * @return Returns the ghostX. - */ - @Override - public int getGhostY() - { - return ghostY; - } - - /** - * @return Returns the ghostX. - */ - public int getGhostWidth() - { - return ghostWidth; - } - - /** - * @return Returns the ghostX. - */ - public int getGhostHeight() - { - return ghostHeight; - } - - /** - * Set the position of the ghost image given a delta to the real size. - * - * @param deltaX The new ghostPosition value - * @param deltaY The new ghostPosition value - */ - @Override - public void setGhostPosition(int deltaX, int deltaY) - { - this.ghostX = getX() + deltaX; - this.ghostY = getY() + deltaY; - } - - /** - * Set the size of the ghost image given a delta to the real size. - * - * @param deltaX The new ghostSize value - * @param deltaY The new ghostSize value - */ - @Override - public void setGhostSize(int deltaX, int deltaY) - { - ghostWidth = Math.max(getWidth() + deltaX, MIN_WIDTH); - ghostHeight = Math.max(getHeight() + deltaY, MIN_HEIGHT); - } - - /** - * Set the target's position to its ghost position. - */ - @Override - public void setPositionToGhost() - { - super.setPos(ghostX, ghostY); - setSize(ghostWidth, ghostHeight); - isDragging = false; - } - - /** - * Ask whether we are currently dragging. - * - * @return The dragging value - */ - @Override - public boolean isDragging() - { - return isDragging; - } - - /** - * Set whether or not we are currently dragging this class (either moving or - * resizing). - * - * @param isDragging The new dragging value - */ - @Override - public void setDragging(boolean isDragging) - { - this.isDragging = isDragging; - } - - /** - * Set the position of this target. - * - * @param x The new pos value - * @param y The new pos value - */ - @Override - public void setPos(int x, int y) - { - super.setPos(x, y); - setGhostPosition(0, 0); - } - - /** - * Set the size of this target. - * - * @param width The new size value - * @param height The new size value - */ - @Override - public void setSize(int width, int height) - { - super.setSize(Math.max(width, MIN_WIDTH), Math.max(height, MIN_HEIGHT)); - setGhostSize(0, 0); - } - - @Override - public void setVisible(boolean visible) - { - if (visible != isVisible()) { - super.setVisible(visible); - - // Inform all listeners about the visibility change - ClassTargetEvent event = new ClassTargetEvent(this, getPackage(), visible); - ExtensionsManager.getInstance().delegateEvent(event); - } - } - - /** - * Prepares this ClassTarget for removal from a Package. It removes - * dependency arrows and calls prepareFilesForRemoval() to remove applicable - * files. - */ - private void prepareForRemoval() - { - if (editor != null) { - editor.close(); - } - - // if this target is the assocation for another Target, remove - // the association - Iterator<? extends Vertex> it = getPackage().getVertices(); - while (it.hasNext()) { - Object o = it.next(); - if (o instanceof DependentTarget) { - DependentTarget d = (DependentTarget) o; - if (this.equals(d.getAssociation())) { - d.setAssociation(null); - } - } - } - - // flag dependent Targets as invalid - invalidate(); - - removeAllInDependencies(); - removeAllOutDependencies(); - - // remove associated files (.class, .java and .ctxt) - prepareFilesForRemoval(); - } - - /** - * Removes applicable files (.class, .java and .ctxt) prior to this - * ClassTarget being removed from a Package. - */ - public void prepareFilesForRemoval() - { - if (getSourceFile().exists()) { - // remove all inner class files starting with the same name as - // sourceFile$ - File[] files = getPackage().getPath().listFiles(new InnerClassFileFilter()); - - if (files != null) { - for (int i = 0; i < files.length; i++) { - files[i].delete(); - } - } - } - - List<File> allFiles = getRole().getAllFiles(this); - for(Iterator<File> i = allFiles.iterator(); i.hasNext(); ) { - i.next().delete(); - } - } - - @Override - public void generateDoc() - { - getPackage().generateDocumentation(this); - } - - @Override - public void remove() - { - prepareForRemoval(); - getPackage().removeTarget(this); - } - - @Override - public boolean isMoveable() - { - return isMoveable; - } - - /** - * Set whether this ClassTarget can be moved by the user (dragged around). - * This is set false for unit tests which are associated with another class. - * - * @see bluej.graph.Moveable#setIsMoveable(boolean) - */ - @Override - public void setIsMoveable(boolean isMoveable) - { - this.isMoveable = isMoveable; - } - - /** - * perform interactive method call - */ - @Override - public void executeMethod(MethodView mv) - { - getPackage().getEditor().raiseMethodCallEvent(this, mv); - } - - /** - * interactive constructor call - */ - @Override - public void callConstructor(ConstructorView cv) - { - getPackage().getEditor().raiseMethodCallEvent(this, cv); - } - - /** - * Method to check state of debug VM (currently running may cause problems) - * and then give options accordingly. - * Returns a value from user about how to continue i.e should the original requested be executed. - * - * @return Whether the original request should be executed (dependent on how the user wants to proceed) - */ - private boolean checkDebuggerState() - { - return PkgMgrFrame.createFrame(getPackage()).checkDebuggerState(); - } - - /** - * Returns the naviview expanded value from the properties file - * @return - */ - public boolean isNaviviewExpanded() - { - return isNaviviewExpanded; - } - - /** - * Sets the naviview expanded value from the properties file to this local variable - * @param isNaviviewExpanded - */ - public void setNaviviewExpanded(boolean isNaviviewExpanded) - { - this.isNaviviewExpanded=isNaviviewExpanded; - } - - /** - * Retrieves a property from the editor - */ - @Override - public String getProperty(String key) - { - return (String)properties.get(key); - } - - /** - * Sets a property for the editor - */ - @Override - public void setProperty(String key, String value) - { - properties.put(key, value); - } - - @Override - public String getTooltipText() - { - if (!getSourceInfo().isValid()) { - return Config.getString("graph.tooltip.classBroken"); - } else { - return null; - } - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/DependentTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/DependentTarget.java deleted file mode 100644 index aa71be32a56ed24247c8793d7af3e6eea7e29caf..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/DependentTarget.java +++ /dev/null @@ -1,501 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2012 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.*; -import java.util.*; -import java.util.List; - -import bluej.graph.Moveable; -import bluej.pkgmgr.*; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.dependency.*; -import bluej.utility.MultiIterator; - -/** - * A target that has relationships to other targets - * - * @author Michael Cahill - * @author Michael Kolling - */ -public abstract class DependentTarget extends EditableTarget -{ - /** States * */ - public static final int S_NORMAL = 0; - public static final int S_INVALID = 1; - public static final int S_COMPILING = 2; - - protected int state = S_INVALID; - - private List<UsesDependency> inUses; - private List<UsesDependency> outUses; - private List<Dependency> parents; - private List<Dependency> children; - - protected DependentTarget assoc; - - /** - * Create a new target belonging to the specified package. - */ - public DependentTarget(Package pkg, String identifierName) - { - super(pkg, identifierName); - - inUses = new ArrayList<UsesDependency>(); - outUses = new ArrayList<UsesDependency>(); - parents = new ArrayList<Dependency>(); - children = new ArrayList<Dependency>(); - - assoc = null; - } - - @Override - public void setPos(int x, int y) - { - super.setPos(x,y); - recalcDependentPositions(); - } - - @Override - public void setSize(int width, int height) - { - super.setSize(width, height); - recalcDependentPositions(); - } - - /** - * Save association information about this class target - * @param props the properties object to save to - * @param prefix an internal name used for this target to identify - */ - @Override - public void save(Properties props, String prefix) - { - super.save(props, prefix); - - if (getAssociation() != null) { - String assocName = getAssociation().getIdentifierName(); - props.put(prefix + ".association", assocName); - } - } - - public void setAssociation(DependentTarget t) - { - assoc = t; - //assoiated classes are not allowed to move on their own - if (assoc instanceof Moveable){ - ((Moveable)assoc).setIsMoveable(false); - } - } - - public DependentTarget getAssociation() - { - return assoc; - } - - public void addDependencyOut(Dependency d, boolean recalc) - { - if(d instanceof UsesDependency) { - outUses.add((UsesDependency) d); - if(recalc) - recalcOutUses(); - } - else if((d instanceof ExtendsDependency) - || (d instanceof ImplementsDependency)) { - parents.add(d); - } - - if(recalc) { - setState(S_INVALID); - } - } - - public void addDependencyIn(Dependency d, boolean recalc) - { - if(d instanceof UsesDependency) { - inUses.add((UsesDependency) d); - if(recalc) - recalcInUses(); - } - else if((d instanceof ExtendsDependency) - || (d instanceof ImplementsDependency)) { - children.add(d); - } - } - - public void removeDependencyOut(Dependency d, boolean recalc) - { - if(d instanceof UsesDependency) { - outUses.remove(d); - if(recalc) - recalcOutUses(); - } - else if((d instanceof ExtendsDependency) - || (d instanceof ImplementsDependency)) { - parents.remove(d); - } - - if(recalc) - setState(S_INVALID); - } - - public void removeDependencyIn(Dependency d, boolean recalc) - { - if(d instanceof UsesDependency) { - inUses.remove(d); - if(recalc) { - recalcInUses(); - } - } - else if((d instanceof ExtendsDependency) - || (d instanceof ImplementsDependency)) { - children.remove(d); - } - } - - public Iterator<? extends Dependency> dependencies() - { - List<Iterator<? extends Dependency>> v = new ArrayList<Iterator<? extends Dependency>>(2); - v.add(parents.iterator()); - v.add(outUses.iterator()); - return new MultiIterator<Dependency>(v); - } - - public Iterator<? extends Dependency> dependents() - { - List<Iterator<? extends Dependency>> v = new ArrayList<Iterator<? extends Dependency>>(2); - v.add(children.iterator()); - v.add(inUses.iterator()); - return new MultiIterator<Dependency>(v); - } - - /** - * Get the dependencies between this target and its parent(s). - * The returned list should not be modified and may be a view or a copy. - */ - public List<Dependency> getParents() - { - return Collections.unmodifiableList(parents); - } - - /** - * Get the dependencies between this target and its children. - * - * @return - */ - public List<Dependency> getChildren() - { - return Collections.unmodifiableList(children); - } - - public List<Dependency> dependentsAsList() - { - List<Dependency> list = new LinkedList<Dependency>(); - list.addAll(inUses); - list.addAll(outUses); - list.addAll(children); - list.addAll(parents); - return list; - } - - public Iterator<UsesDependency> usesDependencies() - { - return Collections.unmodifiableList(outUses).iterator(); - } - - /** - * Remove all outgoing dependencies. Also updates the package. (Don't - * call from package remove method - this will cause infinite recursion.) - */ - protected void removeAllOutDependencies() - { - // While removing the dependencies the dependency list must be - // copied since the original is modified during this operation. - // Enumerations over the original would go wrong. - - // delete outgoing uses dependencies - if(!outUses.isEmpty()) { - Dependency[] outUsesArray = new Dependency[outUses.size()]; - outUses.toArray(outUsesArray); - for(int i = 0; i < outUsesArray.length ; i++) { - getPackage().removeDependency(outUsesArray[i], false); - } - } - - removeInheritDependencies(); - } - - /** - * Remove inheritance dependencies. - */ - protected void removeInheritDependencies() - { - // While removing the dependencies the dependency list must be - // copied since the original is modified during this operation. - // Enumerations over the original would go wrong. - - if(!parents.isEmpty()) { - Dependency[] parentsArray = new Dependency[ parents.size() ]; - parents.toArray(parentsArray); - for(int i = 0; i < parentsArray.length ; i++) - getPackage().removeDependency(parentsArray[i], false); - } - } - - /** - * Remove all incoming dependencies. Also updates the package. (Don't - * call from package remove method - this will cause infinite recursion.) - */ - protected void removeAllInDependencies() - { - // While removing the dependencies the dependency list must be - // copied since the original is modified during this operation. - // Enumerations over the original would go wrong. - - // delete incoming uses dependencies - if(!inUses.isEmpty()) { - Dependency[] inUsesArray = new Dependency[ inUses.size() ]; - inUses.toArray(inUsesArray); - for(int i = 0; i < inUsesArray.length ; i++) - getPackage().removeDependency(inUsesArray[i], false); - } - - // delete dependencies to child classes - if(!children.isEmpty()) { - Dependency[] childrenArray = new Dependency[ children.size() ]; - children.toArray(childrenArray); - for(int i = 0; i < childrenArray.length ; i++) - getPackage().removeDependency(childrenArray[i], false); - } - } - - public void recalcOutUses() - { - // Determine the visible outgoing uses dependencies - List<UsesDependency> visibleOutUses = getVisibleUsesDependencies(outUses); - - // Order the arrows by quadrant and then appropriate coordinate - Collections.sort(visibleOutUses, new LayoutComparer(this, false)); - - // Count the number of arrows into each quadrant - int cy = getY() + getHeight() / 2; - int n_top = 0, n_bottom = 0; - for(int i = visibleOutUses.size() - 1; i >= 0; i--) { - Target to = ((Dependency) visibleOutUses.get(i)).getTo(); - int to_cy = to.getY() + to.getHeight() / 2; - if(to_cy < cy) - ++n_top; - else - ++n_bottom; - } - - // Assign source coordinates to each arrow - int top_left = getX() + (getWidth() - (n_top - 1) * ARR_HORIZ_DIST) / 2; - int bottom_left = getX() + (getWidth() - (n_bottom - 1) * ARR_HORIZ_DIST) / 2; - for(int i = 0; i < n_top + n_bottom; i++) { - UsesDependency d = (UsesDependency) visibleOutUses.get(i); - int to_cy = d.getTo().getY() + d.getTo().getHeight() / 2; - if(to_cy < cy) { - d.setSourceCoords(top_left, getY() - 4, true); - top_left += ARR_HORIZ_DIST; - } - else { - d.setSourceCoords(bottom_left, getY() + getHeight() + 4, false); - bottom_left += ARR_HORIZ_DIST; - } - } - } - - /** - * Re-layout arrows into this target - */ - public void recalcInUses() - { - // Determine the visible incoming uses dependencies - List<UsesDependency> visibleInUses = getVisibleUsesDependencies(inUses); - - // Order the arrows by quadrant and then appropriate coordinate - Collections.sort(visibleInUses, new LayoutComparer(this, true)); - - // Count the number of arrows into each quadrant - int cx = getX() + getWidth() / 2; - int n_left = 0, n_right = 0; - for(int i = visibleInUses.size() - 1; i >= 0; i--) - { - Target from = ((Dependency) visibleInUses.get(i)).getFrom(); - int from_cx = from.getX() + from.getWidth() / 2; - if(from_cx < cx) - ++n_left; - else - ++n_right; - } - - // Assign source coordinates to each arrow - int left_top = getY() + (getHeight() - (n_left - 1) * ARR_VERT_DIST) / 2; - int right_top = getY() + (getHeight() - (n_right - 1) * ARR_VERT_DIST) / 2; - for(int i = 0; i < n_left + n_right; i++) - { - UsesDependency d = (UsesDependency) visibleInUses.get(i); - int from_cx = d.getFrom().getX() + d.getFrom().getWidth() / 2; - if(from_cx < cx) - { - d.setDestCoords(getX() - 4, left_top, true); - left_top += ARR_VERT_DIST; - } - else - { - d.setDestCoords(getX() + getWidth() + 4, right_top, false); - right_top += ARR_VERT_DIST; - } - } - } - - /** - * Returns from the specified {@link List} all uses dependencies which are - * currently visible. - * - * @param usesDependencies - * A {@link List} of uses dependencies. - * @return A {@link List} containing all visible uses dependencies from the - * input list. - */ - private List<UsesDependency> getVisibleUsesDependencies(List<UsesDependency> usesDependencies) - { - List<UsesDependency> result = new ArrayList<UsesDependency>(); - - for (UsesDependency incomingUsesDependency : usesDependencies) { - if (incomingUsesDependency.isVisible()) { - result.add(incomingUsesDependency); - } - } - - return result; - } - - /** - * Clear the flag in a outgoing uses dependencies - */ - protected void unflagAllOutDependencies() - { - for(int i = 0; i < outUses.size(); i++) - ((UsesDependency)outUses.get(i)).setFlag(false); - } - - public Point getAttachment(double angle) - { - double radius; - double sin = Math.sin(angle); - double cos = Math.cos(angle); - double tan = sin / cos; - double m = (double) getHeight() / getWidth(); - - if(Math.abs(tan) < m) // side - radius = 0.5 * getWidth() / Math.abs(cos); - else // top - radius = 0.5 * getHeight() / Math.abs(sin); - - Point p = new Point(getX() + getWidth() / 2 + (int)(radius * cos), - getY() + getHeight() / 2 - (int)(radius * sin)); - - // Correct for shadow - if((-m < tan) && (tan < m) && (cos > 0)) // right side - p.x += SHAD_SIZE; - if((Math.abs(tan) > m) && (sin < 0) && (p.x > getX() + SHAD_SIZE)) // bottom - p.y += SHAD_SIZE; - - return p; - } - - - /** - * The user may have moved or resized the target. If so, recalculate the - * dependency arrows associated with this target. - * @param editor - */ - public void recalcDependentPositions() - { - // Recalculate arrows - recalcInUses(); - recalcOutUses(); - - // Recalculate neighbours' arrows - for(Iterator<UsesDependency> it = inUses.iterator(); it.hasNext(); ) { - Dependency d = it.next(); - d.getFrom().recalcOutUses(); - } - for(Iterator<UsesDependency> it = outUses.iterator(); it.hasNext(); ) { - Dependency d = it.next(); - d.getTo().recalcInUses(); - } - - updateAssociatePosition(); - } - - protected void updateAssociatePosition() - { - DependentTarget t = getAssociation(); - - if (t != null) { - //TODO magic numbers. Should also take grid size in to account. - t.setPos(getX() + 30, getY() - 30); - t. recalcDependentPositions(); - } - } - - @Override - public String toString() - { - return getDisplayName(); - } - - /** - * Return the current state of the target (one of S_NORMAL, S_INVALID, - * S_COMPILING) - */ - public int getState() - { - return state; - } - - public boolean isInvalidState() - { - return getState() == S_INVALID; - } - - public void setInvalidState() - { - setState(S_INVALID); - } - - /** - * Change the state of this target. The target will be repainted to show the - * new state. - * - * @param newState The new state value - */ - public void setState(int newState) - { - state = newState; - repaint(); - } - -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/EditableTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/EditableTarget.java deleted file mode 100644 index 78cc758eac9343df7126ee41db769cd6dab2ba61..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/EditableTarget.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2011 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.Rectangle; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import bluej.editor.*; -import bluej.pkgmgr.Package; - -/** - * A target in a package that can be edited as text - * - * @author Michael Cahill - */ -public abstract class EditableTarget extends Target - implements EditorWatcher -{ - protected Editor editor; - protected Rectangle editorBounds; - - protected EditableTarget(Package pkg, String name) - { - super(pkg, name); - } - - /** - * @return the name of the (text) file this target corresponds to. - */ - protected abstract File getSourceFile(); - - /** - * @return the editor object associated with this target - */ - public abstract Editor getEditor(); - - /** - * Ensure that the source file of this target is up-to-date (i.e. - * that any possible unsaved changes in an open editor window are - * saved). - */ - public void ensureSaved() throws IOException - { - if(editor != null) { - editor.save(); - } - } - - /** - * Called to open the editor for this target - */ - public void open() - { - Editor editor = getEditor(); - - if(editor == null) - getPackage().showError("error-open-source"); - else - editor.setVisible(true); - } - - /** - * Close the editor for this target. - */ - protected void close() - { - getEditor().close(); - } - - /** - * Return true if this editor has been opened at some point since this project was opened. - */ - public boolean editorOpen() - { - return (editor!=null); - } - - public void load(Properties props, String prefix) throws NumberFormatException - { - super.load(props, prefix); - if(props.getProperty(prefix + ".editor.x") != null) { - editorBounds = new Rectangle(Integer.parseInt(props.getProperty(prefix + ".editor.x")), - Integer.parseInt(props.getProperty(prefix + ".editor.y")), - Integer.parseInt(props.getProperty(prefix + ".editor.width")), - Integer.parseInt(props.getProperty(prefix + ".editor.height"))); - } - } - - public void save(Properties props, String prefix) - { - super.save(props, prefix); - if (editor != null) { - editorBounds = editor.getBounds(); - } - if(editorBounds!=null) { - props.put(prefix + ".editor.x", String.valueOf((int) editorBounds.getX())); - props.put(prefix + ".editor.y", String.valueOf((int) editorBounds.getY())); - props.put(prefix + ".editor.width", String.valueOf((int) editorBounds.getWidth())); - props.put(prefix + ".editor.height", String.valueOf((int) editorBounds.getHeight())); - } - } - - // --- EditorWatcher interface --- - // (The EditorWatcher methods are typically redefined in subclasses) - - /* - * Called by Editor when a file is changed - */ - public void modificationEvent(Editor editor) {} - - /* - * Called by Editor when a file is saved - */ - public void saveEvent(Editor editor) {} - - /* - * Called by Editor when a file is closed - */ - public void closeEvent(Editor editor) {} - - /* - * Called by Editor when a breakpoint is been set/cleared - */ - public String breakpointToggleEvent(Editor editor, int lineNo, boolean set) - { return null; } - - /* - * The "compile" function was invoked in the editor - */ - public void compile(Editor editor) {} - - // --- end of EditorWatcher interface --- -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/PackageTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/PackageTarget.java deleted file mode 100644 index a55b1b7a6d8ea70b25f652405264d372dd62eaa5..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/PackageTarget.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010,2011 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.io.File; -import java.lang.reflect.Array; -import java.util.Properties; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -import bluej.Config; -import bluej.graph.GraphEditor; -import bluej.graph.Moveable; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.PkgMgrFrame; -import bluej.prefmgr.PrefMgr; -import bluej.utility.Debug; - -/** - * A sub package (or parent package) - * - * @author Michael Cahill - */ -public class PackageTarget extends Target - implements Moveable -{ - static final int MIN_WIDTH = 60; - static final int MIN_HEIGHT = 40; - - private static final int TAB_HEIGHT = 12; - - static String openStr = Config.getString("pkgmgr.packagemenu.open"); - static String removeStr = Config.getString("pkgmgr.packagemenu.remove"); - - static final Color envOpColour = Config.ENV_COLOUR; - - static final BasicStroke normalStroke = new BasicStroke(1); - static final BasicStroke selectedStroke = new BasicStroke(3); - - private int ghostX; - private int ghostY; - private int ghostWidth; - private int ghostHeight; - private boolean isDragging; - private boolean isMoveable = true; - - public PackageTarget(Package pkg, String baseName) - { - super(pkg, baseName); - - setSize(calculateWidth(baseName), DEF_HEIGHT + TAB_HEIGHT); - } - - /** - * Return the target's base name (ie the name without the package name). eg. - * Target - */ - public String getBaseName() - { - return getIdentifierName(); - } - - /** - * Return the target's name, including the package name. eg. bluej.pkgmgr - */ - public String getQualifiedName() - { - return getPackage().getQualifiedName(getBaseName()); - } - - @Override - public void load(Properties props, String prefix) - throws NumberFormatException - { - super.load(props, prefix); - } - - @Override - public void save(Properties props, String prefix) - { - super.save(props, prefix); - - props.put(prefix + ".type", "PackageTarget"); - } - - /** - * Deletes applicable files (directory and ALL contentes) prior to this - * PackageTarget being removed from a Package. - */ - public void deleteFiles() - { - deleteDir(new File(getPackage().getPath(), getBaseName())); - } - - /** - * Delete a directory recursively. - * This method will delete all files and subdirectories in any - * directory without asking questions. Use with care. - * - * @param directory The directory that will be deleted. - */ - private void deleteDir(File directory) - { - File[] fileList = directory.listFiles(); - - // If it is a file or an empty directory, delete - if (fileList == null) { - try{ - directory.delete(); - } catch (SecurityException se){ - Debug.message("Trouble deleting: "+directory+se); - } - } - else { - if (getPackage().getProject().prepareDeleteDir(directory)) { - // delete all subdirectories - for(int i=0;i<Array.getLength(fileList);i++) { - deleteDir(fileList[i]); - } - - // then delete the directory (when it is empty) - directory.delete(); - } - } - } - - /** - * Called when a package icon in a GraphEditor is double clicked. Creates a - * new PkgFrame when a package is drilled down on. - */ - @Override - public void doubleClick(MouseEvent evt) - { - getPackage().getEditor().raiseOpenPackageEvent(this, getPackage().getQualifiedName(getBaseName())); - } - - /** - * Disply the context menu. - */ - @Override - public void popupMenu(int x, int y, GraphEditor graphEditor) - { - JPopupMenu menu = createMenu(); - if (menu != null) { - menu.show(graphEditor, x, y); - } - } - - /** - * Construct a popup menu which displays all our parent packages. - */ - private JPopupMenu createMenu() - { - JPopupMenu menu = new JPopupMenu(getBaseName()); - - Action openAction = new OpenAction(openStr, this, getPackage().getQualifiedName(getBaseName())); - addMenuItem(menu, openAction); - - Action removeAction = new RemoveAction(removeStr, this); - addMenuItem(menu, removeAction); - - return menu; - } - - private void addMenuItem(JPopupMenu menu, Action action) - { - JMenuItem item = menu.add(action); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setForeground(envOpColour); - } - - private class OpenAction extends AbstractAction - { - private Target t; - private String pkgName; - - public OpenAction(String menu, Target t, String pkgName) - { - super(menu); - this.t = t; - this.pkgName = pkgName; - } - - @Override - public void actionPerformed(ActionEvent e) - { - getPackage().getEditor().raiseOpenPackageEvent(t, pkgName); - } - } - - private class RemoveAction extends AbstractAction - { - private Target t; - - public RemoveAction(String menu, Target t) - { - super(menu); - this.t = t; - } - - @Override - public void actionPerformed(ActionEvent e) - { - getPackage().getEditor().raiseRemoveTargetEvent(t); - } - } - - @Override - public void remove() - { - PkgMgrFrame pmf = PkgMgrFrame.findFrame(getPackage()); - if (pmf.askRemovePackage(this)) { - deleteFiles(); - getPackage().getProject().removePackage(getQualifiedName()); - getPackage().removeTarget(this); - } - } - - /** - * Removes the package associated with this target unconditionally. - */ - public void removeImmediate() - { - deleteFiles(); - getPackage().removeTarget(this); - getPackage().getProject().removePackage(getQualifiedName()); - } - - @Override - public void setSize(int width, int height) - { - super.setSize(Math.max(width, MIN_WIDTH), Math.max(height, MIN_HEIGHT)); - setGhostSize(0, 0); - } - - @Override - public void setPos(int x, int y) - { - super.setPos(x, y); - setGhostPosition(0, 0); - } - - /** - * @return Returns the ghostX. - */ - public int getGhostX() - { - return ghostX; - } - - /** - * @return Returns the ghostX. - */ - public int getGhostY() - { - return ghostY; - } - - /** - * @return Returns the ghostX. - */ - public int getGhostWidth() - { - return ghostWidth; - } - - /** - * @return Returns the ghostX. - */ - public int getGhostHeight() - { - return ghostHeight; - } - - /** - * Set the position of the ghost image given a delta to the real size. - */ - public void setGhostPosition(int deltaX, int deltaY) - { - this.ghostX = getX() + deltaX; - this.ghostY = getY() + deltaY; - } - - /** - * Set the size of the ghost image given a delta to the real size. - */ - public void setGhostSize(int deltaX, int deltaY) - { - ghostWidth = Math.max(getWidth() + deltaX, MIN_WIDTH); - ghostHeight = Math.max(getHeight() + deltaY, MIN_HEIGHT); - } - - /** - * Set the target's position to its ghost position. - */ - public void setPositionToGhost() - { - super.setPos(ghostX, ghostY); - setSize(ghostWidth, ghostHeight); - isDragging = false; - } - - /** - * Ask whether we are currently dragging. - */ - public boolean isDragging() - { - return isDragging; - } - - /** - * Set whether or not we are currently dragging this class - * (either moving or resizing). - */ - public void setDragging(boolean isDragging) - { - this.isDragging = isDragging; - } - - @Override - public boolean isMoveable() - { - return isMoveable; - } - - @Override - public void setIsMoveable(boolean isMoveable) - { - this.isMoveable = isMoveable; - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ParentPackageTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ParentPackageTarget.java deleted file mode 100644 index b0a42ae81918e87ea2d1798f40f6daca9dc9ed8f..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ParentPackageTarget.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.event.*; -import java.util.Properties; - -import javax.swing.*; - -import bluej.Config; -import bluej.graph.GraphEditor; -import bluej.pkgmgr.Package; -import bluej.prefmgr.PrefMgr; -import bluej.utility.JavaNames; - -/** - * A parent package - * - * @author Andrew Patterson - */ -public class ParentPackageTarget extends PackageTarget -{ - final static String openStr = Config.getString("pkgmgr.parentpackagetarget.open"); - final static String openUnamedStr = Config.getString("pkgmgr.parentpackagetarget.openunamed"); - - public ParentPackageTarget(Package pkg) - { - super(pkg, "<go up>"); - } - - public void load(Properties props, String prefix) - { - } - - public void save(Properties props, String prefix) - { - } - - /** - * Deletes applicable files (directory and ALL contentes) prior to - * this PackageTarget being removed from a Package. For safety (it - * should never be called on this target) we override this to do - * nothing - */ - public void deleteFiles() - { - } - - /** - * Copy all the files belonging to this target to a new location. - * For package targets, this has not yet been implemented. - * - * @arg directory The directory to copy into (ending with "/") - */ - public boolean copyFiles(String directory) - { - return true; - } - - public boolean isResizable() - { - return false; - } - - public boolean isMoveable() - { - return false; - } - - public boolean isSaveable() - { - return false; - } - - /** - * Called when a package icon in a GraphEditor is double clicked. - * Creates a new PkgFrame when a package is drilled down on. - */ - public void doubleClick(MouseEvent evt) - { - getPackage().getEditor().raiseOpenPackageEvent(this, - JavaNames.getPrefix(getPackage().getQualifiedName())); - } - - /** - * Disply the context menu. - */ - public void popupMenu(int x, int y, GraphEditor graphEditor) - { - JPopupMenu menu = createMenu(null); - if (menu != null) { - menu.show(graphEditor, x, y); - } - } - - /** - * Construct a popup menu which displays all our parent packages. - */ - private JPopupMenu createMenu(Class<?> cl) - { - JPopupMenu menu = new JPopupMenu(getBaseName()); - - String item = JavaNames.getPrefix(getPackage().getQualifiedName()); - - while(!item.equals("")) { - addMenuItem(menu, openStr + " " + item, item); - item = JavaNames.getPrefix(item); - } - - addMenuItem(menu, openUnamedStr, ""); - - return menu; - } - - private void addMenuItem(JPopupMenu menu, String itemString, String pkgName) - { - JMenuItem item; - - Action openAction = new OpenAction(itemString, this, pkgName); - - item = menu.add(openAction); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setForeground(envOpColour); - } - - private class OpenAction extends AbstractAction - { - private Target t; - private String pkgName; - - public OpenAction(String menu, Target t, String pkgName) - { - super(menu); - this.t = t; - this.pkgName = pkgName; - } - - public void actionPerformed(ActionEvent e) - { - getPackage().getEditor().raiseOpenPackageEvent(t, pkgName); - } - } - public void remove(){ - // The user is not permitted to remove a paretnPackage - } - - -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ReadmeTarget.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ReadmeTarget.java deleted file mode 100644 index 22874d4e5146009e897e9e36e9911f266ec7c177..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/ReadmeTarget.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010,2011,2012,2013 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.awt.Color; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -import bluej.Config; -import bluej.editor.Editor; -import bluej.editor.EditorManager; -import bluej.graph.GraphEditor; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.graphPainter.ReadmeTargetPainter; -import bluej.prefmgr.PrefMgr; -import bluej.utility.Debug; - -/** - * A parent package - * - * @author Andrew Patterson - */ -public class ReadmeTarget extends EditableTarget -{ - private static final int WIDTH = ReadmeTargetPainter.getMaxImageWidth(); - private static final int HEIGHT = ReadmeTargetPainter.getMaxImageHeight(); - private static String openStr = Config.getString("pkgmgr.packagemenu.open"); - private static final Color envOpColour = Config.ENV_COLOUR; - - public static final String README_ID = "@README"; - - public ReadmeTarget(Package pkg) - { - // create the target with an identifier name that cannot be - // a valid java name - super(pkg, README_ID); - - setPos(10, 10); - setSize(WIDTH, HEIGHT); - } - - @Override - public void load(Properties props, String prefix) throws NumberFormatException - { - if(props.getProperty(prefix + ".editor.x") != null) { - editorBounds = new Rectangle(Integer.parseInt(props.getProperty(prefix + ".editor.x")), - Integer.parseInt(props.getProperty(prefix + ".editor.y")), - Integer.parseInt(props.getProperty(prefix + ".editor.width")), - Integer.parseInt(props.getProperty(prefix + ".editor.height"))); - } - } - - @Override - public void save(Properties props, String prefix) - { - if (editor != null) { - editorBounds = editor.getBounds(); - } - if(editorBounds!=null) { - props.put(prefix + ".editor.x", String.valueOf((int) editorBounds.getX())); - props.put(prefix + ".editor.y", String.valueOf((int) editorBounds.getY())); - props.put(prefix + ".editor.width", String.valueOf((int) editorBounds.getWidth())); - props.put(prefix + ".editor.height", String.valueOf((int) editorBounds.getHeight())); - } - } - - /* - * @return the name of the (text) file this target corresponds to. - */ - @Override - public File getSourceFile() - { - return new File(getPackage().getPath(), Package.readmeName); - } - - @Override - public boolean isResizable() - { - return false; - } - - /* - * Although we do save some information (the editor position) about a Readme - * this is not done via the usual target save mechanism. If the normal save - * mechanism was used, the readme target would appear as a normal target. - * This would result in not being able to open a project saved in a newer - * BlueJ version with an older BlueJ version. - */ - @Override - public boolean isSaveable() - { - return false; - } - - @Override - public Editor getEditor() - { - if(editor == null) { - editor = EditorManager.getEditorManager().openText( - getSourceFile().getPath(), - getPackage().getProject().getProjectCharset(), - Package.readmeName, editorBounds); - } - return editor; - } - - - private void openEditor() - { - if (editor == null) { - if (! getSourceFile().exists()) { - try { - getSourceFile().createNewFile(); - } - catch (IOException ioe) { - Debug.reportError("Couldn't open README", ioe); - } - } - } - - // now try again to open it - if(getEditor() != null) { - editor.setVisible(true); - } - } - - /* - * Called when a package icon in a GraphEditor is double clicked. - * Creates a new PkgFrame when a package is drilled down on. - */ - @Override - public void doubleClick(MouseEvent evt) - { - openEditor(); - } - - /* - * Post the context menu for this target. - */ - @Override - public void popupMenu(int x, int y, GraphEditor editor) - { - JPopupMenu menu = createMenu(null); - if (menu != null) { - // editor.add(menu); - menu.show(editor, x, y); - } - } - - /** - * Construct a popup menu which displays all our parent packages. - */ - private JPopupMenu createMenu(Class<?> cl) - { - JPopupMenu menu = new JPopupMenu(); - JMenuItem item; - - Action openAction = new OpenAction(openStr); - - item = menu.add(openAction); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setForeground(envOpColour); - return menu; - } - - private class OpenAction extends AbstractAction - { - public OpenAction(String menu) - { - super(menu); - } - - public void actionPerformed(ActionEvent e) - { - openEditor(); - } - } - - @Override - public void remove() - { - // The user is not permitted to remove the readmefile - } - - @Override - public void generateDoc() - { - // meaningless - } - - @Override - public String getProperty(String key) - { - return null; - } - - @Override - public void setProperty(String key, String value) - { - - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/Target.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/Target.java deleted file mode 100644 index 56ce4652681859e73965112027292313e659cb77..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/Target.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import bluej.pkgmgr.Package; -import bluej.prefmgr.PrefMgr; -import bluej.graph.Vertex; -import bluej.graph.GraphEditor; - -import java.util.Properties; -import java.awt.*; -import java.awt.font.*; -import java.awt.geom.*; - -/** - * A general target in a package - * - * @author Michael Cahill - * @version $Id: Target.java 6963 2010-01-05 05:41:50Z davmac $ - */ -public abstract class Target extends Vertex - implements Comparable<Target> -{ - static final int DEF_WIDTH = 80; - static final int DEF_HEIGHT = 50; - static final int ARR_HORIZ_DIST = 5; - static final int ARR_VERT_DIST = 10; - static final int HANDLE_SIZE = 20; - static final int TEXT_HEIGHT = 16; - static final int TEXT_BORDER = 4; - static final int SHAD_SIZE = 4; - - private String identifierName; // the name handle for this target within - // this package (must be unique within this - // package) - private String displayName; // displayed name of the target - private Package pkg; // the package this target belongs to - - protected boolean disabled; - - protected boolean selected; - protected boolean queued; - - // the following fields are needed to correctly calculate the width of - // a target in dependence of its name and the font used to display it - static FontRenderContext FRC = new FontRenderContext(new AffineTransform(), false, false); - - /** - * Create a new target with default size. - */ - public Target(Package pkg, String identifierName) - { - super(0, 0, calculateWidth(identifierName), DEF_HEIGHT); - - if (pkg == null) - throw new NullPointerException(); - - this.pkg = pkg; - this.identifierName = identifierName; - this.displayName = identifierName; - } - - /** - * Calculate the width of a target depending on the length of its name and - * the font used for displaying the name. The size returned is a multiple of - * 10 (to fit the interactive resizing behaviour). - * - * @param name - * the name of the target (may be null). - * @return the width the target should have to fully display its name. - */ - protected static int calculateWidth(String name) - { - int width = 0; - if (name != null) - width = (int) PrefMgr.getTargetFont().getStringBounds(name, FRC).getWidth(); - if ((width + 20) <= DEF_WIDTH) - return DEF_WIDTH; - else - return (width + 29) / GraphEditor.GRID_SIZE * GraphEditor.GRID_SIZE; - } - - /** - * This target has been removed from its package. - */ - public void setRemoved() - { - // This can be used to detect that a class target has been removed. - pkg = null; - } - - /** - * Load this target's properties from a properties file. The prefix is an - * internal name used for this target to identify its properties in a - * properties file used by multiple targets. - */ - public void load(Properties props, String prefix) - throws NumberFormatException - { - // No super.load, but need to get Vertex properties: - int xpos = 0; - int ypos = 0; - int width = 20; // arbitrary fallback values - int height = 10; - - // Try to get the positional properties in a robust manner. - try { - xpos = Math.max(Integer.parseInt(props.getProperty(prefix + ".x")), 0); - ypos = Math.max(Integer.parseInt(props.getProperty(prefix + ".y")), 0); - width = Math.max(Integer.parseInt(props.getProperty(prefix + ".width")), 1); - height = Math.max(Integer.parseInt(props.getProperty(prefix + ".height")), 1); - } - catch (NumberFormatException nfe) {} - - setPos(xpos, ypos); - setSize(width, height); - } - - /** - * Save the target's properties to 'props'. - */ - public void save(Properties props, String prefix) - { - props.put(prefix + ".x", String.valueOf(getX())); - props.put(prefix + ".y", String.valueOf(getY())); - props.put(prefix + ".width", String.valueOf(getWidth())); - props.put(prefix + ".height", String.valueOf(getHeight())); - - props.put(prefix + ".name", getIdentifierName()); - } - - /** - * Return this target's package (ie the package that this target is - * currently shown in) - */ - public Package getPackage() - { - return pkg; - } - - /** - * Change the text which the target displays for its label - */ - public void setDisplayName(String name) - { - displayName = name; - } - - /** - * Returns the text which the target is displaying as its label - */ - public String getDisplayName() - { - return displayName; - } - - public String getIdentifierName() - { - return identifierName; - } - - public void setIdentifierName(String newName) - { - identifierName = newName; - } - - /* - * (non-Javadoc) - * - * @see bluej.graph.Selectable#setSelected(boolean) - */ - public void setSelected(boolean selected) - { - this.selected = selected; - repaint(); - } - - /* - * (non-Javadoc) - * - * @see bluej.graph.Selectable#isSelected() - */ - public boolean isSelected() - { - return selected; - } - - /** - * Return a bounding box for this target. - */ - public Rectangle getBoundingBox() - { - return getRectangle(); - } - - public void toggleSelected() - { - selected = !selected; - repaint(); - } - - /* - * (non-Javadoc) - * - * @see bluej.graph.Selectable#isHandle(int, int) - */ - public boolean isHandle(int x, int y) - { - return (x - this.getX() + y - this.getY() >= getWidth() + getHeight() - HANDLE_SIZE); - } - - public boolean isQueued() - { - return queued; - } - - public void setQueued(boolean queued) - { - this.queued = queued; - } - - public boolean isResizable() - { - return true; - } - - public boolean isSaveable() - { - return true; - } - - public boolean isSelectable() - { - return true; - } - - public void repaint() - { - if (pkg != null && pkg.getEditor() != null) { - pkg.getEditor().repaint(getX(), getY(), getWidth(), getHeight()); - } - } - - /** - * We have a notion of equality that relates solely to the identifierName. - * If the identifierNames's are equal then the Target's are equal. - */ - public boolean equals(Object o) - { - if (o instanceof Target) { - Target t = (Target) o; - return this.identifierName.equals(t.identifierName); - } - return false; - } - - public int hashCode() - { - return identifierName.hashCode(); - } - - public int compareTo(Target t) - { - if (equals(t)) - return 0; - - if (this.getY() < t.getY()) - return -1; - else if (this.getY() > t.getY()) - return 1; - - if (this.getX() < t.getX()) - return -1; - else if (this.getX() > t.getX()) - return 1; - - return this.identifierName.compareTo(t.getIdentifierName()); - } - - public String toString() - { - return getDisplayName(); - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/TargetCollection.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/TargetCollection.java deleted file mode 100644 index 4eaa42786f7c7d0d109e15d21ffa7d43289474d4..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/TargetCollection.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target; - -import java.util.*; - -/** - * A collection of targets. - * - * @author Andrew Patterson - */ -public class TargetCollection -{ - /** all the targets in a package */ - protected HashMap<String,Target> targets = new HashMap<String,Target>(); - - public Iterator<Target> iterator() - { - return targets.values().iterator(); - } - - public Iterator<Target> sortediterator() - { - return new TreeSet<Target>(targets.values()).iterator(); - } - - public Target get(String identifierName) - { - return (Target) targets.get(identifierName); - } - - public Target remove(String identifierName) - { - return (Target) targets.remove(identifierName); - } - - public void add(String identifierName, Target target) - { - targets.put(identifierName, target); - } - - public String toString() - { - return targets.toString(); - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AbstractClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AbstractClassRole.java deleted file mode 100644 index 51452aed54632b87f96beee0205c6447d1cad493..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AbstractClassRole.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import javax.swing.*; -import java.awt.*; - -import bluej.Config; -import bluej.pkgmgr.target.*; - -/** - * A role object to represent the behaviour of abstract classes. - * - * @author Andrew Patterson - * @version $Id: AbstractClassRole.java 8123 2010-08-20 04:29:01Z davmac $ - */ -public class AbstractClassRole extends ClassRole -{ - public final static String ABSTRACT_ROLE_NAME = "AbstractTarget"; - private static final Color abstractbg = Config.getOptionalItemColour("colour.class.bg.abstract"); - - /** - * Create the abstract class role. - */ - public AbstractClassRole() - { - } - - public String getRoleName() - { - return ABSTRACT_ROLE_NAME; - } - - public String getStereotypeLabel() - { - return "abstract"; - } - - /** - * Return the intended background colour for this type of target. - */ - public Paint getBackgroundPaint(int width, int height) - { - if (abstractbg != null) { - return abstractbg; - } else { - return super.getBackgroundPaint(width, height); - } - } - - /** - * Creates a class menu containing any constructors. - * - * <p>Because we are an abstract class we cannot have any constructors - * so we override this method to do nothing. - * - * @param menu the popup menu to add the class menu items to - * @param cl Class object associated with this class target - */ - public boolean createClassConstructorMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - return false; - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AppletClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AppletClassRole.java deleted file mode 100644 index a73e9ac0a854bb21fabfde65cf65b6ae66d07f29..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/AppletClassRole.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2010 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.nio.charset.Charset; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import javax.swing.AbstractAction; -import javax.swing.JFrame; -import javax.swing.JPopupMenu; - -import bluej.Config; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.PackageEditor; -import bluej.pkgmgr.PkgMgrFrame; -import bluej.pkgmgr.RunAppletDialog; -import bluej.pkgmgr.target.ClassTarget; -import bluej.pkgmgr.target.Target; -import bluej.utility.BlueJFileReader; -import bluej.utility.Debug; -import bluej.utility.FileUtility; -import bluej.utility.Utility; - -/** - * An Applet class role in a package, i.e. a target that is a Applet class file - * built from Java source code. - * - * @author Bruce Quig - */ -public class AppletClassRole extends StdClassRole -{ - public static final String APPLET_ROLE_NAME = "AppletTarget"; - - private RunAppletDialog dialog; - - private static final Color appletbg = Config.getOptionalItemColour("colour.class.bg.applet"); - static final String runAppletStr = Config.getString("pkgmgr.classmenu.runApplet"); - static final String htmlComment = Config.getString("pkgmgr.runApplet.htmlComment"); - - static final String APPLETVIEWER_COMMAND = - Config.getJDKExecutablePath("appletViewer.command", "appletviewer"); - - public static final String HTML_EXTENSION = ".html"; - private static final int DEFAULT_APPLET_WIDTH = 500; - private static final int DEFAULT_APPLET_HEIGHT = 500; - - private String[] appletParams; - private int appletHeight; - private int appletWidth; - - /** - * Create the class role. - */ - public AppletClassRole() - { - appletHeight = DEFAULT_APPLET_HEIGHT; - appletWidth = DEFAULT_APPLET_WIDTH; - } - - public String getRoleName() - { - return APPLET_ROLE_NAME; - } - - public String getStereotypeLabel() - { - return "applet"; - } - - /** - * Return the intended background colour for this type of target. - */ - public Paint getBackgroundPaint(int width, int height) - { - if (appletbg != null) { - return appletbg; - } else { - return super.getBackgroundPaint(width, height); - } - } - - /** - * Save this AppletClassRole details to file - * @param props the properties object that stores target information - * @param prefix prefix for this target for identification - */ - public void save(Properties props, int modifiers, String prefix) - { - super.save(props, modifiers, prefix); - if(dialog != null) { - appletParams = dialog.getAppletParameters(); - props.put(prefix + ".numberAppletParameters", String.valueOf(appletParams.length)); - for(int i = 0; i < appletParams.length; i++) { - props.put(prefix + ".appletParameter" + (i + 1), appletParams[i]); - } - - } - else - props.put(prefix + ".numberAppletParameters", String.valueOf(0)); - - props.put(prefix + ".appletHeight", String.valueOf(appletHeight)); - props.put(prefix + ".appletWidth", String.valueOf(appletWidth)); - } - - - /** - * load existing information about this applet class role - * @param props the properties object to read - * @param prefix an internal name used for this target to identify - * its properties in a properties file used by multiple targets. - */ - public void load(Properties props, String prefix) throws NumberFormatException - { - String value = props.getProperty(prefix + ".numberAppletParameters"); - - int numberParameters = 0; - if(value != null) - numberParameters = Integer.parseInt(value); - if(numberParameters > 0) { - appletParams = new String[numberParameters]; - for(int i = 0; i < numberParameters; i++) - appletParams[i] = props.getProperty(prefix + ".appletParameter" + (i + 1)); - } - - value = props.getProperty(prefix + ".appletHeight"); - if(value != null) - appletHeight = Integer.parseInt(value); - - value = props.getProperty(prefix + ".appletWidth"); - if(value != null) - appletWidth = Integer.parseInt(value); - } - - /** - * Generate a popup menu for this class role. - * - * @param menu the menu to add items to - * @param ct the ClassTarget we are constructing the role for - * @param state whether the target is COMPILED etc. - * @return true if we added any menu tiems, false otherwise - */ - public boolean createRoleMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl, int state) - { - // add run applet option - addMenuItem(menu, new AppletAction(ct.getPackage().getEditor(),ct), - (state == ClassTarget.S_NORMAL)); - menu.addSeparator(); - - return true; - } - - private class AppletAction extends AbstractAction - { - private Target t; - private PackageEditor ped; - - public AppletAction(PackageEditor ped, Target t) - { - super(runAppletStr); - this.ped = ped; - this.t = t; - } - - public void actionPerformed(ActionEvent e) - { - ped.raiseRunTargetEvent(t, null); - } - } - - /** - * Runs the applet using options provided by user RunAppletDialog dialog - * choices. Options are: - * - generate a package independent HTML page only - * - run applet in JDK appletviewer - * _ run in web browser - * - * @param ct the class target that is represented by this applet class - * - */ - public void run(PkgMgrFrame parent, ClassTarget ct, String param) - { - String name = ct.getQualifiedName(); - Package pkg = ct.getPackage(); - - if(dialog == null) { - dialog = new RunAppletDialog(parent, name); - // add params that originated from pkg properties - if(appletParams != null) - dialog.setAppletParameters(appletParams); - dialog.setAppletHeight(appletHeight); - dialog.setAppletWidth(appletWidth); - } - - if(dialog.display()) { // if OK was clicked - // TODO: check is the class path handling can be simplified. - File[] libs = parent.getProject().getClassLoader().getClassPathAsFiles(); - - int execOption = dialog.getAppletExecutionOption(); - if(execOption == RunAppletDialog.GENERATE_PAGE_ONLY) { - // generate HTML page for Applet using selected path and file name - File generatedFile = chooseWebPage(parent); - if(generatedFile != null) { - createWebPage(generatedFile, name, pkg.getPath().getPath(), libs); - } - } - else { - String fname = name + HTML_EXTENSION; - File destFile = new File(pkg.getProject().getProjectDir(), name + HTML_EXTENSION); - - createWebPage(destFile, name, ".", libs); - - // Run applet as an external process - if(execOption == RunAppletDialog.EXEC_APPLETVIEWER) { - try { - String[] execCommand = {APPLETVIEWER_COMMAND, fname}; - PkgMgrFrame.displayMessage(Config.getString("pkgmgr.appletInViewer")); - - Process applet = Runtime.getRuntime().exec(execCommand, null, - pkg.getProject().getProjectDir()); - - new StreamReader(applet.getErrorStream()).start(); - new StreamReader(applet.getInputStream()).start(); - } catch (Exception e) { - pkg.showError("appletviewer-error"); - Debug.reportError("Exception thrown in execution of appletviewer"); - e.printStackTrace(); - } - } - else { - // start in Browser - PkgMgrFrame.displayMessage(Config.getString("pkgmgr.appletInBrowser")); - Utility.openWebBrowser(destFile); - } - } - } - } - - /** - * A utility class to mop up all the output that an applet might vomit. - */ - private class StreamReader extends Thread - { - private InputStream stream; - - public StreamReader(InputStream stream) - { - this.stream = stream; - } - - @Override - public void run() - { - byte [] buf = new byte[1024]; - try { - int len; - do { - len = stream.read(buf); - } - while (len != -1); - } - catch (IOException ioe) {} - } - } - - /** - * Use a file chooser to select a web page name and location. - * - * @param frame the parent frame for the file chooser - * @return the full file name for the web page or null - * if cancel selected in file chooser - */ - private File chooseWebPage(JFrame frame) - { - String fullFileName = FileUtility.getFileName(frame, - Config.getString("pkgmgr.chooseWebPage.title"), - Config.getString("pkgmgr.chooseWebPage.buttonLabel"), - null, false); - - if (fullFileName == null) { - return null; - } - - if(! fullFileName.endsWith(HTML_EXTENSION)) { - fullFileName += HTML_EXTENSION; - } - - return new File(fullFileName); - } - - /** - * Read the applet parameters (width, height, params) from the - * dialog and store them. - */ - private void updateAppletProperties() - { - try{ - appletHeight = Integer.parseInt(dialog.getAppletHeight()); - appletWidth = Integer.parseInt(dialog.getAppletWidth()); - } catch (NumberFormatException nfe) { - // add exception handling - } - appletParams = dialog.getAppletParameters(); - } - - /** - * Create a HTML page that contains this JApplet using - * parameters input by user in RunAppletDialog class. - * - * @param fileName fileName for HTML file to house Applet - */ - private void createWebPage(File outputFile, String appletName, String appletCodeBase, File[] libs) - { - updateAppletProperties(); - generateHTMLSkeleton(outputFile, appletName, appletCodeBase, libs, - dialog.getAppletWidth(), dialog.getAppletHeight(), appletParams); - } - - /** - * Creates a HTML Skeleton that contains this JApplet using - * parameters input by user in RunAppletDialog class. - * - * @param name the fully qualified name of the applet class - * @param outputFileName the name of the generated HTML file - * @param appletCodeBase code base to be included in applet tag (canot be null) - * @param width specified width of applet - * @param height specified height of applet - * @param parameters optional applet parameters - */ - private void generateHTMLSkeleton(File outputFile, String appletName, String appletCodeBase, File[] libs, - String width, String height, String[] parameters) - { - Hashtable<String,String> translations = new Hashtable<String,String>(); - - translations.put("TITLE", appletName); - translations.put("COMMENT", htmlComment); - translations.put("CLASSFILE", appletName + ".class"); - // whilst it would be nice to be able to have no codebase, it is in the - // HTML template file and hence even if we define no CODEBASE here, it - // will appear in the resulting HTML anyway (as CODEBASE=$CODEBASE) - translations.put("CODEBASE", appletCodeBase); - translations.put("APPLETWIDTH", width); - translations.put("APPLETHEIGHT", height); - - // add libraries from <project>/+libs/ to archives - String archives = ""; - try{ - for(int i=0; i < libs.length; i++) { - if(archives.length() == 0) { - archives = libs[i].toURI().toURL().toString(); - } - else { - archives += "," + libs[i].toURI().toURL(); - } - } - } - catch(MalformedURLException e) {} - - translations.put("ARCHIVE", archives); - - StringBuffer allParameters = new StringBuffer(); - for(int index = 0; index < parameters.length; index++) - allParameters.append("\t" + parameters[index] + "\n"); - - translations.put("PARAMETERS", allParameters.toString()); - - File tmplFile = Config.getTemplateFile("html"); - - try { - Charset utf8 = Charset.forName("UTF-8"); - BlueJFileReader.translateFile(tmplFile, outputFile, translations, utf8, utf8); - } catch(IOException e) { - Debug.reportError("Exception during file translation from " + - tmplFile + " to " + outputFile); - e.printStackTrace(); - } - } - - /* (non-Javadoc) - * @see bluej.pkgmgr.target.role.ClassRole#getAllFiles(bluej.pkgmgr.target.ClassTarget) - */ - public List<File> getAllFiles(ClassTarget ct) - { - List<File> rlist = super.getAllFiles(ct); - - File htmlFile = new File(ct.getPackage().getProject().getProjectDir(), - ct.getQualifiedName() + HTML_EXTENSION); - rlist.add(htmlFile); - - return rlist; - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/ClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/ClassRole.java deleted file mode 100644 index 325b238b093e208c28e3bf3d4875f60a185b24f8..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/ClassRole.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2011 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Paint; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import javax.swing.Action; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -import bluej.Config; -import bluej.debugmgr.ConstructAction; -import bluej.debugmgr.objectbench.InvokeAction; -import bluej.debugmgr.objectbench.InvokeListener; -import bluej.pkgmgr.Package; -import bluej.pkgmgr.PkgMgrFrame; -import bluej.pkgmgr.target.ClassTarget; -import bluej.prefmgr.PrefMgr; -import bluej.utility.BlueJFileReader; -import bluej.utility.Debug; -import bluej.views.CallableView; -import bluej.views.ConstructorView; -import bluej.views.MethodView; -import bluej.views.View; -import bluej.views.ViewFilter; - -/** - * A class role in a class target, providing behaviour specific to particular - * class types - * - * @author Bruce Quig - */ -public abstract class ClassRole -{ - public final static String CLASS_ROLE_NAME = null; - - private final Color defaultbg = Config.getOptionalItemColour("colour.class.bg.default"); - protected final Color envOpColour = Config.ENV_COLOUR; - - public String getRoleName() - { - return CLASS_ROLE_NAME; - } - - /** - * save details about the class target variant this role represents. - * - * @param props - * the properties object associated with this target and role - * @param modifiers - * modifiers for - * @param prefix - * prefix to identifiy this role's target - */ - public void save(Properties props, int modifiers, String prefix) - { - } - - /** - * load existing information about this class role - * - * @param props - * the properties object to read - * @param prefix - * an internal name used for this target to identify its - * properties in a properties file used by multiple targets. - */ - public void load(Properties props, String prefix) - throws NumberFormatException - { - - } - - /** - * Return the default background colour for targets that don't want to - * define their own colour. - * @param width Width of total area to paint - * @param height Height of total area to paint - */ - public Paint getBackgroundPaint(int width, int height) - { - if (defaultbg != null) { - return defaultbg; - } else { - return new GradientPaint( - 0, 0, new Color(246,221,192), - 0, height, new Color(245,204,155)); - } - } - - /** - * Get the "stereotype label" for this class role. This will be displayed - * on classes in the UML diagram along with the class name. It may return - * null if there is no stereotype label. - */ - public String getStereotypeLabel() - { - return null; - } - - /** - * Generates a source code skeleton for this class. - * - * @param template - * the name of the particular class template (just the base name - * without path and suffix) - * @param pkg - * the package that the class target resides in - * @param name - * the name of the class - * @param sourceFile - * the name of the source file to be generated - */ - public boolean generateSkeleton(String template, Package pkg, String name, String sourceFile) - { - Hashtable<String,String> translations = new Hashtable<String,String>(); - translations.put("CLASSNAME", name); - - if (pkg.isUnnamedPackage()) { - translations.put("PKGLINE", ""); - } - else { - translations.put("PKGLINE", "package " + pkg.getQualifiedName() + ";" + Config.nl + Config.nl); - } - - try { - // Check for existing file. Normally this won't happen (the check for duplicate - // target occurs prior to this) but on Windows filenames are case insensitive. - File dest = new File(sourceFile); - if (dest.exists()) { - pkg.showError("duplicate-name"); - return false; - } - BlueJFileReader.translateFile(Config.getClassTemplateFile(template), - new File(sourceFile), translations, - Charset.forName("UTF-8"), pkg.getProject().getProjectCharset()); - return true; - } - catch (IOException e) { - pkg.showError("skeleton-error"); - Debug.reportError("The default skeleton for the class could not be generated"); - Debug.reportError("Exception: " + e); - return false; - } - } - - /** - * Adds a single item to this roles popup menu. - * - * This method is used by ClassTarget to add some standard menus as well as - * by the roles to add menus. It should be overridden with caution. - * - * @param menu - * the popup menu the item is to be added to - * @param action - * the action to be registered with this menu item - * @param itemString - * the String to be displayed on menu item - * @param enabled - * boolean value representing whether item should be enabled - * - */ - public void addMenuItem(JPopupMenu menu, Action action, boolean enabled) - { - JMenuItem item; - - item = new JMenuItem(); - item.setAction(action); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setForeground(envOpColour); - item.setEnabled(enabled); - - menu.add(item); - } - - /** - * Adds role specific items at the top of the popup menu for this class - * target. - * - * @param menu - * the menu object to add to - * @param ct - * ClassTarget object associated with this class role - * @param state - * the state of the ClassTarget - * - * @return true if any menu items have been added - */ - public boolean createRoleMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl, int state) - { - return false; - } - - /** - * Adds role specific items at the bottom of the popup menu for this class - * target. - * - * @param menu - * the menu object to add to - * @param ct - * ClassTarget object associated with this class role - * @param state - * the state of the ClassTarget - * - * @return true if any menu items have been added - */ - public boolean createRoleMenuEnd(JPopupMenu menu, ClassTarget ct, int state) - { - return false; - } - - /** - * Creates a class menu containing the constructors. - * - * @param menu - * the popup menu to add the class menu items to - * @param cl - * Class object associated with this class target - */ - public boolean createClassConstructorMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - ViewFilter filter; - View view = View.getView(cl); - - if (!java.lang.reflect.Modifier.isAbstract(cl.getModifiers())) { - filter = new ViewFilter(ViewFilter.INSTANCE | ViewFilter.PACKAGE); - ConstructorView[] constructors = view.getConstructors(); - - if (createMenuItems(menu, constructors, filter, 0, constructors.length, "new ", ct)) - return true; - } - - return false; - } - - public boolean createClassStaticMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - ViewFilter filter; - View view = View.getView(cl); - - filter = new ViewFilter(ViewFilter.STATIC | ViewFilter.PACKAGE); - MethodView[] allMethods = view.getAllMethods(); - if (createMenuItems(menu, allMethods, filter, 0, allMethods.length, "", ct)) - return true; - - return false; - } - - /** - * Create the menu items for the given members (constructors or methods). - * @return true if any items were created - */ - public static boolean createMenuItems(JPopupMenu menu, CallableView[] members, ViewFilter filter, int first, int last, - String prefix, InvokeListener il) - { - // Debug.message("Inside ClassTarget.createMenuItems\n first = " + first - // + " last = " + last); - boolean hasEntries = false; - JMenuItem item; - - for (int i = first; i < last; i++) { - try { - CallableView m = members[last - i - 1]; - if (!filter.accept(m)) - continue; - // Debug.message("createSubMenu - creating MenuItem"); - - Action callAction = null; - if (m instanceof MethodView) - callAction = new InvokeAction((MethodView) m, il, prefix + m.getLongDesc()); - else if (m instanceof ConstructorView) - callAction = new ConstructAction((ConstructorView) m, il, prefix + m.getLongDesc()); - - if (callAction != null) { - item = menu.add(callAction); - item.setFont(PrefMgr.getPopupMenuFont()); - hasEntries = true; - } - } - catch (Exception e) { - Debug.reportError("Exception accessing methods: " + e); - e.printStackTrace(); - } - } - return hasEntries; - } - - public void run(PkgMgrFrame pmf, ClassTarget ct, String param) - {} - - /** - * Get all the files belonging to a class target - source, class, ctxt, docs - * @param ct The class target - * @return A list of File objects - */ - public List<File> getAllFiles(ClassTarget ct) - { - // Source, .class, .ctxt, and doc (.html) - List<File> rlist = new ArrayList<File>(); - - rlist.add(ct.getClassFile()); - rlist.add(ct.getSourceFile()); - rlist.add(ct.getContextFile()); - rlist.add(ct.getDocumentationFile()); - - File [] innerClasses = ct.getInnerClassFiles(); - for (int i = 0; i < innerClasses.length; i++) { - rlist.add(innerClasses[i]); - } - - return rlist; - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/EnumClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/EnumClassRole.java deleted file mode 100644 index b66a278efdc02dcfa7c7838140a2b4c3280395f4..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/EnumClassRole.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.Color; -import java.awt.Paint; - -import javax.swing.JPopupMenu; -import bluej.Config; -import bluej.pkgmgr.target.ClassTarget; -import bluej.prefmgr.PrefMgr; - -/** - * A role object to represent the behaviour of enums. - * - * @author Poul Henriksen <polle@mip.sdu.dk> - */ -public class EnumClassRole extends ClassRole -{ - public final static String ENUM_ROLE_NAME = "EnumTarget"; - private static final Color enumbg = Config.getOptionalItemColour("colour.class.bg.enum"); - - /** - * Create the enum class role. - */ - public EnumClassRole() - { - } - - public String getRoleName() - { - return ENUM_ROLE_NAME; - } - - public String getStereotypeLabel() - { - return "enum"; - } - - /** - * Return the intended background colour for this type of target. - */ - public Paint getBackgroundPaint(int width, int height) - { - if (enumbg != null) { - return enumbg; - } else { - return super.getBackgroundPaint(width, height); - } - } - - /** - * Creates a class menu containing any constructors. - * - * Because we are an enum class we cannot have any constructors - * so we override this method to do nothing. - * - * @param menu the popup menu to add the class menu items to - * @param cl Class object associated with this class target - */ - public boolean createClassConstructorMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - return false; - } - - /** - * Adds role specific items at the bottom of the popup menu for this class target. - * - * @param menu the menu object to add to - * @param ct ClassTarget object associated with this class role - * @param state the state of the ClassTarget - * - * @return true if any menu items have been added - */ - public boolean createRoleMenuEnd(JPopupMenu menu, ClassTarget ct, int state) - { - if(PrefMgr.getFlag(PrefMgr.SHOW_TEST_TOOLS)) { - if (ct.getAssociation() == null) { - menu.addSeparator(); - addMenuItem(menu, ct.new CreateTestAction(), true); - } - } - return true; - } - - -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/InterfaceClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/InterfaceClassRole.java deleted file mode 100644 index 4653e68eb4c62d9fef4de45c72599aea585ff22d..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/InterfaceClassRole.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.*; - -import bluej.Config; - -/** - * A role object to represent the behaviour of interfaces. - * - * @author Andrew Patterson - * @version $Id: InterfaceClassRole.java 7594 2010-05-18 14:39:08Z nccb $ - */ -public class InterfaceClassRole extends ClassRole -{ - public final static String INTERFACE_ROLE_NAME = "InterfaceTarget"; - private static final Color interfacebg = Config.getOptionalItemColour("colour.class.bg.interface"); - - /** - * Create the interface class role. - */ - public InterfaceClassRole() - { - } - - public String getRoleName() - { - return INTERFACE_ROLE_NAME; - } - - public String getStereotypeLabel() - { - return "interface"; - } - - /** - * Return the intended background colour for this type of target. - */ - public Paint getBackgroundPaint(int width, int height) - { - if (interfacebg != null) { - return interfacebg; - } else { - return super.getBackgroundPaint(width, height); - } - } - -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/MIDletClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/MIDletClassRole.java deleted file mode 100644 index 1d75fcb99549beb2501e28ed3f2bb4a2da7421c6..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/MIDletClassRole.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.Color; -import java.awt.Paint; -import bluej.Config; - -/** - * A MIDlet class role in a package, i.e. a target that is a MIDlet class file - * built from Java source code. - * - * @author Cecilia Vargas - */ -public class MIDletClassRole extends ClassRole -{ - public static final String MIDLET_ROLE_NAME = "MIDletTarget"; - - private static final Color bckgrndColor = Config.getOptionalItemColour("colour.class.bg.midlet"); - - - public MIDletClassRole() { } - - public String getRoleName() - { - return MIDLET_ROLE_NAME; - } - - public String getStereotypeLabel() - { - return "MIDlet"; - } - - public Paint getBackgroundPaint(int width, int height) - { - if (bckgrndColor != null) { - return bckgrndColor; - } else { - return super.getBackgroundPaint(width, height); - } - } - } diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/StdClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/StdClassRole.java deleted file mode 100644 index 1ff1eba1b716cd4c897f8f719616bc0e2f30d9fa..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/StdClassRole.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2010 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import javax.swing.JPopupMenu; - -import bluej.pkgmgr.target.ClassTarget; -import bluej.prefmgr.PrefMgr; - -/** - * A role object which a class target uses to delegate behaviour to. - * StdClassRole is used to represent standard Java classes. - * - * @author Bruce Quig - */ -public class StdClassRole extends ClassRole -{ - /** - * Create the class role. - */ - public StdClassRole() - { - } - - public String getRoleName() - { - return "ClassTarget"; - } - - /** - * Generate a popup menu for this class role. - * - * @param menu the menu to add items to - * @param ct the ClassTarget we are constructing the role for - * @param state whether the target is COMPILED etc. - * @return true if we added any menu tiems, false otherwise - */ - public boolean createRoleMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl, int state) - { - return false; - } - - /** - * Adds role specific items at the bottom of the popup menu for this class target. - * - * @param menu the menu object to add to - * @param ct ClassTarget object associated with this class role - * @param state the state of the ClassTarget - * - * @return true if any menu items have been added - */ - public boolean createRoleMenuEnd(JPopupMenu menu, ClassTarget ct, int state) - { - if(PrefMgr.getFlag(PrefMgr.SHOW_TEST_TOOLS)) { - if (ct.getAssociation() == null) { - menu.addSeparator(); - addMenuItem(menu, ct.new CreateTestAction(), true); - } - } - return true; - } -} diff --git a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/UnitTestClassRole.java b/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/UnitTestClassRole.java deleted file mode 100644 index 4887996359a1d19e7c572613f1d7a5b90727ce1c..0000000000000000000000000000000000000000 --- a/ws/eclipse/bluej/src/main/java/bluej/pkgmgr/target/role/UnitTestClassRole.java +++ /dev/null @@ -1,771 +0,0 @@ -/* - This file is part of the BlueJ program. - Copyright (C) 1999-2009,2010,2011,2012,2013 Michael Kolling and John Rosenberg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - This file is subject to the Classpath exception as provided in the - LICENSE.txt file that accompanied this code. - */ -package bluej.pkgmgr.target.role; - -import java.awt.Color; -import java.awt.EventQueue; -import java.awt.GradientPaint; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -import org.junit.Test; - -import bluej.Config; -import bluej.debugger.DebuggerObject; -import bluej.debugmgr.objectbench.ObjectWrapper; -import bluej.editor.Editor; -import bluej.parser.SourceLocation; -import bluej.parser.SourceSpan; -import bluej.parser.UnitTestAnalyzer; -import bluej.pkgmgr.PackageEditor; -import bluej.pkgmgr.PkgMgrFrame; -import bluej.pkgmgr.TestRunnerThread; -import bluej.pkgmgr.target.ClassTarget; -import bluej.pkgmgr.target.Target; -import bluej.prefmgr.PrefMgr; -import bluej.testmgr.TestDisplayFrame; -import bluej.testmgr.record.ExistingFixtureInvokerRecord; -import bluej.utility.Debug; -import bluej.utility.DialogManager; -import bluej.utility.JavaNames; -import bluej.utility.JavaUtils; - -/** - * A role object for Junit unit tests. - * - * @author Andrew Patterson - */ -public class UnitTestClassRole extends ClassRole -{ - public static final String UNITTEST_ROLE_NAME = "UnitTestTarget"; - public static final String UNITTEST_ROLE_NAME_JUNIT4 = "UnitTestTargetJunit4"; - - private final Color unittestbg = Config.getOptionalItemColour("colour.class.bg.unittest"); - - private static final String testAll = Config.getString("pkgmgr.test.popup.testAll"); - private static final String createTest = Config.getString("pkgmgr.test.popup.createTest"); - private static final String benchToFixture = Config.getString("pkgmgr.test.popup.benchToFixture"); - private static final String fixtureToBench = Config.getString("pkgmgr.test.popup.fixtureToBench"); - - /** Whether this is a Junit 4 test class. If false, it's a Junit 3 test class. */ - private boolean isJunit4; - - /** - * Create the unit test class role. - */ - public UnitTestClassRole(boolean isJunit4) - { - this.isJunit4 = isJunit4; - } - - @Override - public String getRoleName() - { - if (isJunit4) { - return UNITTEST_ROLE_NAME_JUNIT4; - } - else { - return UNITTEST_ROLE_NAME; - } - } - - @Override - public String getStereotypeLabel() - { - return "unit test"; - } - - /** - * Return the intended background colour for this type of target. - */ - @Override - public Paint getBackgroundPaint(int width, int height) - { - if (unittestbg != null) { - return unittestbg; - } else { - return new GradientPaint( - 0, 0, new Color(197,211,165), - 0, height, new Color(170,190,140)); - } - } - - @SuppressWarnings("unchecked") - private boolean isJUnitTestMethod(Method m) - { - if (isJunit4) { - Class<?> cl = m.getDeclaringClass(); - ClassLoader classLoader = cl.getClassLoader(); - try { - Class<Test> testClass; - if (classLoader == null) { - testClass = org.junit.Test.class; - } - else { - testClass = (Class<Test>) classLoader.loadClass("org.junit.Test"); - } - - if (m.getAnnotation(testClass) != null) { - if (!Modifier.isPublic(m.getModifiers())) return false; - if (m.getParameterTypes().length != 0) return false; - return true; - } - } - catch (ClassNotFoundException cnfe) {} - catch (LinkageError le) {} - - // No suitable annotations found, so not a test class - return false; - } - else { - // look for reasons to not include this method as a test case - if (!m.getName().startsWith("test")) return false; - if (!Modifier.isPublic(m.getModifiers())) return false; - if (m.getParameterTypes().length != 0) return false; - if (!m.getReturnType().equals(Void.TYPE)) return false; - return true; - } - } - - /** - * Generate a popup menu for this TestClassRole. - * @param cl the class object that is represented by this target - * @param editorFrame the frame in which this targets package is displayed - * @return the generated JPopupMenu - */ - @Override - public boolean createRoleMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl, int state) - { - boolean enableTestAll = false; - - if (state == ClassTarget.S_NORMAL && cl != null && ! ct.isAbstract()) { - Method[] allMethods = cl.getMethods(); - - for (int i=0; i < allMethods.length; i++) { - Method m = allMethods[i]; - - if (isJUnitTestMethod(m)) { - enableTestAll = true; - break; - } - } - } - - // add run all tests option - addMenuItem(menu, new TestAction(testAll, ct.getPackage().getEditor(),ct), enableTestAll); - menu.addSeparator(); - - return false; - } - - /** - * creates a class menu containing any constructors and static methods etc. - * - * @param menu the popup menu to add the class menu items to - * @param cl Class object associated with this class target - */ - @Override - public boolean createClassConstructorMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - boolean hasEntries = false; - - Method[] allMethods = cl.getMethods(); - - if (! ct.isAbstract()) { - for (int i=0; i < allMethods.length; i++) { - Method m = allMethods[i]; - - if (!isJUnitTestMethod(m)) { - continue; - } - - String rtype; - try { - rtype = JavaUtils.getJavaUtils().getReturnType(m).toString(true); - } - catch (ClassNotFoundException cnfe) { - rtype = m.getReturnType().getName(); - } - Action testAction = new TestAction(rtype + " " + m.getName() + "()", - ct.getPackage().getEditor(), ct, m.getName()); - - JMenuItem item = new JMenuItem(); - item.setAction(testAction); - item.setFont(PrefMgr.getPopupMenuFont()); - menu.add(item); - hasEntries = true; - } - if (!hasEntries) { - JMenuItem item = new JMenuItem(Config.getString("pkgmgr.test.popup.noTests")); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setEnabled(false); - menu.add(item); - } - } - else { - JMenuItem item = new JMenuItem(Config.getString("pkgmgr.test.popup.abstract")); - item.setFont(PrefMgr.getPopupMenuFont()); - item.setEnabled(false); - menu.add(item); - } - return true; - } - - @Override - public boolean createClassStaticMenu(JPopupMenu menu, ClassTarget ct, Class<?> cl) - { - boolean enable = !ct.getPackage().getProject().inTestMode() && ct.hasSourceCode() && ! ct.isAbstract(); - - addMenuItem(menu, new MakeTestCaseAction(createTest, - ct.getPackage().getEditor(), ct), enable); - addMenuItem(menu, new BenchToFixtureAction(benchToFixture, - ct.getPackage().getEditor(), ct), enable); - addMenuItem(menu, new FixtureToBenchAction(fixtureToBench, - ct.getPackage().getEditor(), ct), enable); - - return true; - } - - @Override - public void run(final PkgMgrFrame pmf, final ClassTarget ct, final String param) - { - if (param != null) { - // Only running a single test - TestDisplayFrame.getTestDisplay().startTest(pmf.getProject(), 1); - } - - new TestRunnerThread(pmf, ct, param).start(); - } - - /** - * Set up a test run. This just involves going through the methods in the class - * and creating a list of those which are test methods. - * - * @param pmf The package manager frame - * @param ct The class target - * @param trt The test runner thread - */ - public void doRunTest(PkgMgrFrame pmf, ClassTarget ct, TestRunnerThread trt) - { - Class<?> cl = pmf.getPackage().loadClass(ct.getQualifiedName()); - - if (cl == null) - return; - - // Test the whole class - Method[] allMethods = cl.getMethods(); - - ArrayList<String> testMethods = new ArrayList<String>(); - - int testCount = 0; - - for (int i=0; i < allMethods.length; i++) { - if (isJUnitTestMethod(allMethods[i])) { - testCount++; - testMethods.add(allMethods[i].getName()); - } - } - - String [] testMethodsArr = (String []) testMethods.toArray(new String[testCount]); - trt.setMethods(testMethodsArr); - TestDisplayFrame.getTestDisplay().startTest(pmf.getProject(), testCount); - } - - /** - * Get the count of tests in the test class. - * @param ct The ClassTarget of the unit test class - * @return the number of tests in the unit test class - */ - public int getTestCount(ClassTarget ct) - { - if (! ct.isCompiled()) { - return 0; - } - - Class<?> cl = ct.getPackage().loadClass(ct.getQualifiedName()); - if (cl == null) { - return 0; - } - - Method[] allMethods = cl.getMethods(); - - int testCount = 0; - - for (int i=0; i < allMethods.length; i++) { - if (isJUnitTestMethod(allMethods[i])) { - testCount++; - } - } - - return testCount; - } - - /** - * Start the construction of a test method. - * - * This method prompts the user for a test method name and then sets up - * all the variables for constructing a new test method. - * - * @param pmf the PkgMgrFrame this is all occurring in - * @param ct the ClassTarget of the unit test class - */ - public void doMakeTestCase(final PkgMgrFrame pmf, final ClassTarget ct) - { - // prompt for a new test name - String newTestName = DialogManager.askString(pmf, "unittest-new-test-method"); - - if (newTestName == null) { - return; - } - - if (newTestName.length() == 0) { - pmf.setStatus(Config.getString("pkgmgr.test.noTestName")); - return; - } - - // Junit 3 test methods must start with the word "test" - if(!isJunit4 && !newTestName.startsWith("test")) { - newTestName = "test" + Character.toTitleCase(newTestName.charAt(0)) + newTestName.substring(1); - } - - // and they must be a valid Java identifier - if (!JavaNames.isIdentifier(newTestName)) { - pmf.setStatus(Config.getString("pkgmgr.test.invalidTestName")); - return; - } - - // find out if the method already exists in the unit test src - try { - Charset charset = pmf.getProject().getProjectCharset(); - UnitTestAnalyzer uta = analyzeUnitTest(ct, charset); - - SourceSpan existingSpan = uta.getMethodBlockSpan(newTestName); - - if (existingSpan != null) { - if (DialogManager.askQuestion(null, "unittest-method-present") == 1) { - return; - } - } - } - catch (IOException ioe) { - DialogManager.showErrorWithText(null, "unittest-io-error", ioe.getLocalizedMessage()); - Debug.reportError("Error reading unit test source", ioe); - } - - pmf.testRecordingStarted(Config.getString("pkgmgr.test.recording") + " " - + ct.getBaseName() + "." + newTestName + "()"); - - pmf.getProject().removeClassLoader(); - - runTestSetup(pmf, ct, false); - - pmf.getObjectBench().resetRecordingInteractions(); - pmf.setTestInfo(newTestName, ct); - } - - /** - * Analyze a unit test file. - * @param ct The classtarget representing the unit test class to analyze - * @return A UnitTestAnalyzer object with information about the unit test class - * @throws IOException if the source file can't be saved or read - */ - private UnitTestAnalyzer analyzeUnitTest(ClassTarget ct, Charset fileEncoding) throws IOException - { - ct.ensureSaved(); - - UnitTestAnalyzer uta = null; - FileInputStream fis = null; - try { - fis = new FileInputStream(ct.getSourceFile()); - Reader reader = new InputStreamReader(fis, fileEncoding); - uta = new UnitTestAnalyzer(reader); - } - catch (FileNotFoundException fnfe) { - throw fnfe; - } - finally { - if (fis != null) { - try { - fis.close(); - } - catch (IOException ioe) { - // shouldn't happen - Debug.reportError(ioe); - } - } - } - - return uta; - } - - /** - * Run the test setup. - * @param pmf The package manager frame to run the setup in - * @param ct The classtarget for the test class - */ - private void runTestSetup(final PkgMgrFrame pmf, final ClassTarget ct, final boolean recordAsFixtureToBench) - { - // Avoid running test setup (which is user code) on the event thread. - // Run it on a new thread instead. - new Thread() { - public void run() { - - final Map<String,DebuggerObject> dobs = pmf.getProject().getDebugger().runTestSetUp(ct.getQualifiedName()); - - EventQueue.invokeLater(new Runnable() { - public void run() { - Iterator<Map.Entry<String,DebuggerObject>> it = dobs.entrySet().iterator(); - - while(it.hasNext()) { - Map.Entry<String,DebuggerObject> mapent = it.next(); - DebuggerObject objVal = mapent.getValue(); - - if (! objVal.isNullObject()) { - pmf.putObjectOnBench(mapent.getKey(), objVal, objVal.getGenType(), null); - } - } - } - }); - } - }.start(); - } - - private static final String spaces = " "; - - /** - * Get a string of whitespace corresponding to an indentation. - */ - private String getIndentString() - { - int ts = Math.min(Config.getPropInteger("bluej.editor.tabsize", 4), spaces.length()); - return spaces.substring(0, ts); - } - - /** - * End the construction of a test method. - * <p> - * This method is responsible for actually created the source code for a - * just-recorded test method. - * - * @param pmf the PkgMgrFrame this is all occurring in - * @param ct the ClassTarget of the unit test class - * @param name the name of the test method we are writing out - */ - public void doEndMakeTestCase(PkgMgrFrame pmf, ClassTarget ct, String name) - { - Editor ed = ct.getEditor(); - String ts = getIndentString(); - try { - Charset charset = pmf.getProject().getProjectCharset(); - UnitTestAnalyzer uta = analyzeUnitTest(ct, charset); - - SourceSpan existingSpan = uta.getMethodBlockSpan(name); - - if (existingSpan != null) { - // replace this method (don't replace the method header!) - ed.setSelection(existingSpan.getStartLine(), existingSpan.getStartColumn(), - existingSpan.getEndLine(), existingSpan.getEndColumn()); - ed.insertText("{\n" + pmf.getObjectBench().getTestMethod(ts + ts) + ts + "}", false); - } - else { - // insert a complete method - SourceLocation methodInsert = uta.getNewMethodInsertLocation(); - - if (methodInsert != null) { - ed.setSelection(methodInsert.getLine(), methodInsert.getColumn(), 1); - if (isJunit4) { - ed.insertText("\n" + ts + "@Test\n" + ts + "public void " + name + "()\n" + ts + "{\n" - + pmf.getObjectBench().getTestMethod(ts + ts) + ts + "}\n}\n", false); - } - else { - ed.insertText("\n" + ts + "public void " + name + "()\n" + ts + "{\n" - + pmf.getObjectBench().getTestMethod(ts + ts) + ts + "}\n}\n", false); - } - } - } - - ed.save(); - } - catch (IOException ioe) { - PkgMgrFrame.showMessageWithText(pmf.getPackage(), "generic-file-save-error", ioe.getLocalizedMessage()); - } - } - - /** - * Turn the fixture declared in a unit test class into a set of - * objects on the object bench. - * - * @param pmf the PkgMgrFrame that will hold the object bench - * @param ct the ClassTarget of the unit test class - */ - public void doFixtureToBench(PkgMgrFrame pmf, ClassTarget ct) - { - Editor ed = ct.getEditor(); - - // our first step is to save all the existing code that creates the - // fixture into a special invoker record - // this can then be used to recreate this fixture from the object - // bench if needed - ExistingFixtureInvokerRecord existing = new ExistingFixtureInvokerRecord(); - - try { - Charset charset = pmf.getProject().getProjectCharset(); - UnitTestAnalyzer uta = analyzeUnitTest(ct, charset); - - // iterate through all the declarations of fields (fixture items) in the class - List<SourceSpan> fixtureSpans = uta.getFieldSpans(); - ListIterator<SourceSpan> it = fixtureSpans.listIterator(); - - while(it.hasNext()) { - SourceSpan variableSpan = it.next(); - String fieldDecl = ed.getText(variableSpan.getStartLocation(), variableSpan.getEndLocation()); - existing.addFieldDeclaration(fieldDecl); - } - - // find the source code of the "setUp" method - SourceSpan setUpSpan = uta.getMethodBlockSpan("setUp"); - - if (setUpSpan != null) { - String setUpWithBrackets = ed.getText(setUpSpan.getStartLocation(), setUpSpan.getEndLocation()); - // copy everything between the opening { and the final } - String setUpWithoutBrackets = - setUpWithBrackets.substring(setUpWithBrackets.indexOf('{') + 1, - setUpWithBrackets.lastIndexOf('}')).trim(); - existing.setSetupMethod(setUpWithoutBrackets); - } - - } - catch (IOException ioe) { - PkgMgrFrame.showMessageWithText(pmf.getPackage(), "generic-file-save-error", ioe.getLocalizedMessage()); - } - - runTestSetup(pmf, ct, true); - - pmf.getObjectBench().addInteraction(existing); - } - - /** - * Convert the objects on the object bench into a test fixture. - */ - public void doBenchToFixture(PkgMgrFrame pmf, ClassTarget ct) - { - if(pmf.getObjectBench().getObjectCount() == 0) { - return; - } - - Editor ed = ct.getEditor(); - try { - Charset charset = pmf.getProject().getProjectCharset(); - UnitTestAnalyzer uta = analyzeUnitTest(ct, charset); - - // find all the fields declared in this unit test class - List<SourceSpan> variables = uta.getFieldSpans(); - - // if we already have fields, ask if we are sure we want to get rid of them - if (variables != null && variables.size() > 0) { - if (DialogManager.askQuestion(null, "unittest-fixture-present") == 1) { - return; - } - } - - // if we have fields, we need to nuke them - // we need to make sure we delete these in reverse order (from the last - // field to the first) or else when we delete them, we change the line - // numbers for the following ones - if (variables != null) { - // start iterating from the last element - ListIterator<SourceSpan> it = variables.listIterator(variables.size()); - - while(it.hasPrevious()) { - SourceSpan variableSpan = (SourceSpan) it.previous(); - - ed.setSelection(variableSpan.getStartLine(), variableSpan.getStartColumn(), - variableSpan.getEndLine(), variableSpan.getEndColumn()); - ed.insertText("", false); - } - - // to get correct locations for rewriting setUp(), we need to reparse - uta = analyzeUnitTest(ct, charset); - } - - // find a location to insert new methods - SourceLocation fixtureInsertLocation = uta.getFixtureInsertLocation(); - - // sanity check.. this shouldn't ever be null but if it is, lets not - // make it worse by trying to edit the source - if (fixtureInsertLocation == null) { - return; - } - - { - List<String> names = new ArrayList<String>(); - for (ObjectWrapper obj : pmf.getObjectBench().getObjects()) - { - names.add(obj.getName()); - } - } - - // find the curly brackets for the setUp() method - SourceSpan setupSpan = uta.getMethodBlockSpan("setUp"); - - String ts = getIndentString(); - - // rewrite the setUp() method of the unit test (if it exists) - if (setupSpan != null) { - ed.setSelection(setupSpan.getStartLine(), setupSpan.getStartColumn(), - setupSpan.getEndLine(), setupSpan.getEndColumn()); - } else { - // otherwise, we will be inserting a brand new setUp() method - ed.setSelection(fixtureInsertLocation.getLine(), - fixtureInsertLocation.getColumn(), 1); - if (isJunit4) { - ed.insertText("{\n" + ts + "@Before\n" + ts + "public void setUp()\n" + ts, false); - } - else { - ed.insertText("{\n" + ts + "public void setUp()\n" + ts, false); - } - } - - // insert the code for our setUp() method - ed.insertText("{\n" + pmf.getObjectBench().getFixtureSetup(ts + ts) - + ts + "}", false); - - // insert our new fixture declarations - ed.setSelection(fixtureInsertLocation.getLine(), - fixtureInsertLocation.getColumn(), 1); - - ed.insertText("{\n" + pmf.getObjectBench().getFixtureDeclaration(ts), false); - ed.save(); - } - catch (IOException ioe) { - PkgMgrFrame.showMessageWithText(pmf.getPackage(), - "generic-file-save-error", ioe.getLocalizedMessage()); - } - - pmf.getPackage().compileQuiet(ct); - - pmf.getProject().removeClassLoader(); - pmf.getProject().newRemoteClassLoaderLeavingBreakpoints(); - } - - /** - * A base class for all our actions that run on targets. - */ - private abstract class TargetAbstractAction extends AbstractAction - { - protected Target t; - protected PackageEditor ped; - - public TargetAbstractAction(String name, PackageEditor ped, Target t) - { - super(name); - this.ped = ped; - this.t = t; - } - } - - /** - * A TestAction is an action that causes a JUnit test to be run on a class. - * If testName is not provided, it is set to null which means that the whole - * test class is run; otherwise it refers to a test method that should be run - * individually. - */ - private class TestAction extends TargetAbstractAction - { - private String testName; - - public TestAction(String actionName, PackageEditor ped, Target t) - { - super(actionName, ped, t); - this.testName = null; - } - - public TestAction(String actionName, PackageEditor ped, Target t, String testName) - { - super(actionName, ped, t); - this.testName = testName; - } - - public void actionPerformed(ActionEvent e) - { - ped.raiseRunTargetEvent(t, testName); - } - } - - private class MakeTestCaseAction extends TargetAbstractAction - { - public MakeTestCaseAction(String name, PackageEditor ped, Target t) - { - super(name, ped, t); - } - - public void actionPerformed(ActionEvent e) - { - ped.raiseMakeTestCaseEvent(t); - } - } - - private class BenchToFixtureAction extends TargetAbstractAction - { - public BenchToFixtureAction(String name, PackageEditor ped, Target t) - { - super(name, ped, t); - } - - public void actionPerformed(ActionEvent e) - { - ped.raiseBenchToFixtureEvent(t); - } - } - - private class FixtureToBenchAction extends TargetAbstractAction - { - public FixtureToBenchAction(String name, PackageEditor ped, Target t) - { - super(name, ped, t); - } - - public void actionPerformed(ActionEvent e) - { - ped.raiseFixtureToBenchEvent(t); - } - } - -}