Just An Application

November 5, 2009

An Extended NewAnnotation Wizard For Eclipse: Defining The NewWizard Extension

To make Eclipse aware that the fragment contains a wizard we have to define an extension corresponding to the Eclipse defined extension point

    org.eclipse.ui.newWizards

As it says in the documentation for this extension point, which can be found here Platform Plug-in Developer Guide:Reference:Extension Points Reference:org.eclipse.ui.newWizards

This extension point is used to register resource creation wizard extensions. Creation wizards appear as choices within the “New Dialog”, and are typically used to create folders and files.

In the “New Dialog”, wizards are organized into categories which usually reflect a particular problem domain. For instance, a Java oriented plugin may define a category called “Java” which is appropriate for “Class” or “Package” creation wizards. The categories defined by one plug-in can be referenced by other plug-ins using the category attribute. Uncategorized wizards, as well as wizards with invalid category paths, will end up in an “Other” category.

An extension can be defined by simply adding a piece of XML conforming to the schema for the corresponding extension point to the fragment.xml file.

There are two ways to do this. The first is to use the ‘Extensions’ tab of the ‘Fragment’ view which you can bring-ip by double-clicking the MANIFEST.MF file in the ‘Package Explorer’ view.

Extensions

Click Add to bring up the ‘New Extension’ dialog

ExtensionPointSelection

Enter org.eclipse.ui.newWizards in the ‘Extension Pointer filter’ text field. It will appear as the sole element in the list below it. Select it and hit ‘Finish’.

Extensions2

Control-click or right-click the org.eclipse.ui.newWizards element then select New > wizard from the pop-menu.

Extensions3

Then fill in the fields of the resulting editor.

Extensions4

Alternatively you can create a file called fragment.xml in the root directory of the project and put something like this in it.


    <?xml version="1.0" encoding="UTF-8"?>
    <?eclipse version="3.4"?>
    <fragment>
        <extension
            point = "org.eclipse.ui.newWizards">
            <wizard
                name     = "%NewAnnotationType.label"
                icon     = "$nl$/icons/full/etool16/newannotation_wiz.gif"
                category = "org.eclipse.jdt.ui.java"
                id       = "xper.eclipse.plugin.jdt.ui.wizards.NewAnnotationCreationWizard">
                <class 
                    class = "xper.eclipse.plugin.jdt.ui.annotation.NewAnnotationWizard">
                    <parameter 
                        name  = "javatype" 
                        value = "true"/>
                </class>
            </wizard>
        </extension>
    </fragment>

In this case, the name is the same as that of the Eclipse supplied wizard and is in fact a property. The existing value is accessible because the fragment is hosted by the bundle defining. Using the same value however results in two wizards with the same name appearing in menus, etc., which is a bit confusing so I defined a new value in the fragment.properties file.

The fragment.properties file should be in the root directory of the project. In this case it simply contains a single entry.

    NewAnnotationType.label = Annotation [extended]

The icon is that of the Eclipse suppiied wizard and is accessible for the same reason as the name.

The category is the same as that for the Eclipse supplied Java type creation wizards which ensures that the new wizard appears in all the same places that they do.

Note that If you do create the fragment.xml file by hand, and/or a fragment.properties file you will need to add them to the list of files to be included in the binary build, which is configurable from the ‘Build ‘ tab of the ‘Fragment’ view.

Running the fragment using the Eclipse Application configuration results in the new wizard being available. For example, from the drop-down menu of the Java creation button

DropDown


Copyright (c) 2009 By Simon Lewis. All Rights Reserved

November 2, 2009

An Extended NewAnnotation Wizard For Eclipse: Creating The Annotation

By default, for a class inheriting from NewTypeWizardPage, the creation of the Java type is performed by the inherited method

    public void createType(IProgressMonitor monitor)

This method in turn calls

    protected void createTypeMembers(
                       IType            newType,
                       ImportsManager   imports,
                       IProgressMonitor monitor)
                   throws 
                       CoreException

which is documented as a hook method, and it is this method which the example in the documentation overrides.

To create the annotated definition we need to add the referenced Annotation types and Enums to the list of imports and annotate the created Annotation. Both the created type, in this case the Annotation, and the ImportsManager are being passed to the hook method, so it looks as though it should be possible to do what is necessary by overriding this method.

Adding the imports to the ImportsManager is easily done.


        ...

        if (documented)
        {
            imports.addImport(DOCUMENTED_ANNOTATION_TYPE);
        }
        if (inherited)
        {
            imports.addImport(INHERITED_ANNOTATION_TYPE);
        }
        switch (retention)
        {
            case CLASS:
				
                break;
				
                default:
				
                    imports.addImport(RETENTION_ANNOTATION_TYPE);
                    imports.addImport(RETENTION_POLICY_ENUM_TYPE);
        }
        if (targets.size() != 0)
        {
            imports.addImport(TARGET_ANNOTATION_TYPE);
            imports.addImport(ELEMENT_TYPE_ENUM_TYPE);
        }

        ...

with the constants being defined as follows


        private static final String DOCUMENTED_ANNOTATION_TYPE	= "java.lang.annotation.Documented";
	
        private static final String INHERITED_ANNOTATION_TYPE	= "java.lang.annotation.Inherited";
	
        private static final String RETENTION_ANNOTATION_TYPE	= "java.lang.annotation.Retention";
	
        private static final String TARGET_ANNOTATION_TYPE      = "java.lang.annotation.Target";
	
        private static final String ELEMENT_TYPE_ENUM_TYPE      = "java.lang.annotation.ElementType";
	
        private static final String RETENTION_POLICY_ENUM_TYPE	= "java.lang.annotation.RetentionPolicy";

For the Documented and Inherited meta-annotations only the Annotation types themselves need to be imported. In the Retention and Target cases the Enum value types are also imported.

Adding the Annotations themselves to the newly created type turns out to be more difficult. The IType interface extends the IAnnotable amongst others, but none of the methods on IAnnotable or any of the super-interfaces, or on IType itself apparently enable the addition of Annotations.

It is entirely possible that somewhere in the maze of twisty little interfaces there is a way to do so, but I have yet to stumble upon it.

In the end, following a good deal of random experimentation I discovered the


    protected String constructCUContent(
                         ICompilationUnit cu,
                         String           typeContent,
                         String           lineDelimiter)
                     throws 
                         CoreException
 

method on NewTypeWizardPage.

The typeContent argument contains the source of the annotation as created.

Overriding this method modifying the typeContent argument and then invoking the overridden method turns out to have the required effect.


        @Override
        protected String constructCUContent(
                             ICompilationUnit 	theCompilationUnit,
                             String             theTypeContent, 
                             String             theLineDelimiter) 
                         throws 
                             CoreException 
        {	
            StringBuilder builder = new StringBuilder();
		
            if (documented)
            {
                builder.append("@Documented ");
            }
            if (inherited)
            {
                builder.append("@Inherited ");
            }
            switch (retention)
            {
                case CLASS:
			
                    break;
				
                default:
				
                    builder.append("@Retention(RetentionPolicy.");
                    builder.append(retention);
                    builder.append(") ");
            }
		
            int nTargets = targets.size();
		
            if (nTargets != 0)
            {
                builder.append("@Target(");
			
                if (nTargets != 1)
                {
                    boolean first = true;
				
                    builder.append("{");
                    for (ElementType type : targets)
                    {
                        if (!first)
                        {
                            builder.append(", ");
                        }
                        else
                        {
                            first = false;
                        }
                        builder.append("ElementType.");
                        builder.append(type);
                    }
                    builder.append("}");
                }
                else
                {
                    for (ElementType type : targets)
                    {
                        builder.append("ElementType.");
                        builder.append(type);
                    }
                }
                builder.append(") ");
            }
            builder.append(theTypeContent);
            return super.constructCUContent(theCompilationUnit,  builder.toString(), theLineDelimiter);
        }

In CLOS this would have been an :around method. Sigh …


Copyright (c) 2009 By Simon Lewis. All Rights Reserved

November 1, 2009

An Extended NewAnnotation Wizard For Eclipse: Implementing The Wizard Page UI

The UI for a wizard page is created by its implementation of the

    public void createControl(Composite parent);

method defined in the

    org.eclipse.jface.dialogs.IWizardPage

interface.

The NewAnnotationWizardPage implementation of it is as follows


        @Override
        public void createControl(Composite theParent) 
        {
            initializeDialogUnits(theParent);
		
            Composite composite= new Composite(theParent, SWT.NONE);

            composite.setFont(theParent.getFont());
		
            int nColumns = 4;

            GridLayout layout= new GridLayout();
			
            layout.numColumns= nColumns;
            composite.setLayout(layout);

            createContainerControls(composite, nColumns);
            createPackageControls(composite, nColumns);
            createEnclosingTypeControls(composite, nColumns);

            createSeparator(composite, nColumns);

            createTypeNameControls(composite, nColumns);
            createModifierControls(composite, nColumns);
		
            createSeparator(composite, nColumns);
		
            createAnnotationsControls(composite);
		
            createSeparator(composite, nColumns);

            createCommentControls(composite, nColumns);
            enableCommentControl(true);

            setControl(composite);

            Dialog.applyDialogFont(composite);
        }

This is essentially a clone of the same method from the existing Eclipse supplied class with the addition of these three lines.


        ...

        createSeparator(composite, nColumns);
		
        createAnnotationsControls(composite);
		
        createSeparator(composite, nColumns);
		
        ...

The createAnnotationsControls(Composite) method is responsible for the creation of the new UI elements within the page. These are shown below.

NewControls

The text at the top is a Label and is added directly to the parent composite passed in to the call to createControl(Composite), with a horizontal span set to ensure that it is in a row on its own.


        Label label = new Label(theParent, SWT.NONE);
		
        label.setText(Text.WHICH_ANNOTATIONS_TEXT);
		
        GridData labelData = new GridData();
		
        labelData.horizontalSpan = nColumns;
		
        label.setLayoutData(labelData);

There are controls to specify the addition of the four basic meta-annotations

  • Documented
  • Inherited
  • Retention
  • Target

These controls are grouped together into a Composite which is laid out in two columns using a GridLayout


        Composite  group  = new Composite(theParent, SWT.NONE);
        GridLayout layout = new GridLayout();
		
        layout.numColumns = 2;
        group.setLayout(layout);
		
        GridData groupData = new GridData(GridData.FILL_HORIZONTAL);
		
        groupData.horizontalAlignment = SWT.CENTER;
        groupData.horizontalSpan = nColumns - 1;
        group.setLayoutData(groupData);

Both Documented and Inherited are marker annotations: they are either present or not. In each case a checkbox is used to indicate whether they should be present or not.


        Button button = null;
		
        // Documented
	
        label = new Label(group, SWT.NONE);
        label.setText(Text.DOCUMENTED_LABEL);
		
        button = new Button(group, SWT.CHECK);
        button.addSelectionListener(
                   new SelectionAdapter()
                   {
                       public void widgetSelected(SelectionEvent theEvent)
                       {
                           documented = ((Button)(theEvent.widget)).getSelection();
                       }
                   });
		
        // Inherited
		
        label = new Label(group, SWT.NONE);
        label.setText(Text.INHERITED_LABEL);
		
        button = new Button(group, SWT.CHECK);
        button.addSelectionListener(
                   new SelectionAdapter()
                   {
                       public void widgetSelected(SelectionEvent theEvent)
                       {
                           inherited = ((Button)(theEvent.widget)).getSelection();
                       }
                   });

The Retention annotation has value of type RetentionPolicy which is an Enum with a choice of three values. These are represented by a group of radio buttons. The currently selected value is represented by the corresponding value of RetentionPolicy which is stored in the retention instance variable.


        // Retention
		
        label = new Label(group, SWT.NONE);
        label.setText(Text.RETENTION_LABEL);
		
        Composite  retentionGroup        = new Composite(group, SWT.NONE);
        GridLayout retentionGroupLayout  = new GridLayout();
		
        retentionGroupLayout.numColumns   = N_RETENTION_GROUP_COLUMNS;
        retentionGroup.setLayout(retentionGroupLayout);
		
        Listener listener = new Listener()
                            {
                                @Override
                                public void handleEvent(Event theEvent) 
                                {
                                    Button button = (Button)(theEvent.widget);
									
                                    if (button.getSelection())
                                    {
                                        retention = (RetentionPolicy)button.getData();
                                    }
                                }
                            };
		
        for (String name : sortedNames(RetentionPolicy.class))
        {
            label = new Label(retentionGroup, SWT.NONE);
            label.setText(name);
		
            button = new Button(retentionGroup, SWT.RADIO);
            button.addListener(SWT.Selection, listener);
            button.setData(Enum.valueOf(RetentionPolicy.class, name));
            if (RetentionPolicy.CLASS.name().equals(name))
            {
                button.setSelection(true);
            }
        }

The sortedNames method is a utility method which returns the names of an Enum’s values in alphabetical order. It is possible to obtain a set containing all the values of a given Enum but these are in the order they appear in the Enum definition, which is not necessarily alphabetical.


        private <E extends Enum<E>> Iterable<String> sortedNames(Class<E> theEnumClass)
        {
            List<String> names = new ArrayList<String>();
		
            for (Enum<E> e : EnumSet.allOf(theEnumClass))
            {
                names.add(e.name());
            }
            Collections.sort(names);
            return names;
        }

The Target annotation can have multiple values of the Enum type ElementType. These are represented by a group of checkboxes. The currently selected values are held in the instance variable targets which is of type EnumSet<ElementType>.


        // Targets
		
        label = new Label(group, SWT.NONE);
        label.setText(Text.TARGETS_LABEL);
		
        GridData targetsData = new GridData();
		
        targetsData.verticalAlignment = SWT.TOP;
        label.setLayoutData(targetsData);
		
        Composite targetsGroup       = new Composite(group, SWT.NONE);
        RowLayout targetsGroupLayout = new RowLayout(SWT.VERTICAL);
		
        targetsGroupLayout.marginLeft = 0;
        targetsGroupLayout.marginTop  = 0;
        targetsGroup.setLayout(targetsGroupLayout);
		
        listener = new Listener()
        {
            @Override
            public void handleEvent(Event theEvent) 
            {
                Button      button = (Button)(theEvent.widget);
                ElementType type   = (ElementType)button.getData();
				
                if (button.getSelection())
                {
                    targets.add(type);
                }
                else
                {
                    targets.remove(type);
                }
            }
        };
		
        for (String name : sortedNames(ElementType.class))
        {
            button = new Button(targetsGroup, SWT.CHECK);
            button.addListener(SWT.Selection, listener);
            button.setData(Enum.valueOf(ElementType.class, name));
            button.setText(name);
        }



Copyright (c) 2009 By Simon Lewis. All Rights Reserved

Blog at WordPress.com.

%d bloggers like this: