org.melanee.graphdsl.service.GraphicalrepresentationToFigureTransformator.java Source code

Java tutorial

Introduction

Here is the source code for org.melanee.graphdsl.service.GraphicalrepresentationToFigureTransformator.java

Source

/*******************************************************************************
 * Copyright (c) 2013, 2014 University of Mannheim: Chair for Software Engineering
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Ralph Gerbig - initial API and implementation and initial documentation
 *******************************************************************************/
package org.melanee.graphdsl.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.draw2d.AbstractLayout;
import org.eclipse.draw2d.ConnectionLocator;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.GridData;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ImageFigure;
import org.eclipse.draw2d.ImageUtilities;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineDecoration;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.RotatableDecoration;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.ScalablePolygonShape;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.diagram.ui.figures.BorderedNodeFigure;
import org.eclipse.gmf.runtime.diagram.ui.figures.LabelLocator;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.ocl.ParserException;
import org.eclipse.ocl.ecore.Constraint;
import org.eclipse.ocl.expressions.OCLExpression;
import org.eclipse.ocl.helper.OCLHelper;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.melanee.core.modeleditor.edit.parts.ParticipationEditPart.ConnectionParticipationFigure;
import org.melanee.core.models.plm.PLM.AbstractDSLVisualizer;
import org.melanee.core.models.plm.PLM.Attribute;
import org.melanee.core.models.plm.PLM.Clabject;
import org.melanee.core.models.plm.PLM.Participation;
import org.melanee.core.workbench.ExtensionPointService;
import org.melanee.core.workbench.interfaces.IConstraintLanguageService;
import org.melanee.graphdsl.models.definition.graphdef.Alignment;
import org.melanee.graphdsl.models.definition.graphdef.BorderLayoutInformationDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.Circle;
import org.melanee.graphdsl.models.definition.graphdef.ColorConstant;
import org.melanee.graphdsl.models.definition.graphdef.Compartment;
import org.melanee.graphdsl.models.definition.graphdef.ConditionalLayoutContent;
import org.melanee.graphdsl.models.definition.graphdef.ConditionalValue;
import org.melanee.graphdsl.models.definition.graphdef.DefaultLinkDecoration;
import org.melanee.graphdsl.models.definition.graphdef.DefaultLinkDecorationTypes;
import org.melanee.graphdsl.models.definition.graphdef.ExpressionLabel;
import org.melanee.graphdsl.models.definition.graphdef.FlowLayout;
import org.melanee.graphdsl.models.definition.graphdef.FontDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.FontStyle;
import org.melanee.graphdsl.models.definition.graphdef.FreehandShape;
import org.melanee.graphdsl.models.definition.graphdef.GraphicalDSLVisualizer;
import org.melanee.graphdsl.models.definition.graphdef.InformationDisplayDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.LabelDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.LabelOrientation;
import org.melanee.graphdsl.models.definition.graphdef.LayoutContentDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.LayoutDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.LayoutInformationDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.LineStyle;
import org.melanee.graphdsl.models.definition.graphdef.Link;
import org.melanee.graphdsl.models.definition.graphdef.LinkDecoration;
import org.melanee.graphdsl.models.definition.graphdef.MappingLabel;
import org.melanee.graphdsl.models.definition.graphdef.Pin;
import org.melanee.graphdsl.models.definition.graphdef.Point;
import org.melanee.graphdsl.models.definition.graphdef.Rectangle;
import org.melanee.graphdsl.models.definition.graphdef.RenderedLayoutContentDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.SVGFigure;
import org.melanee.graphdsl.models.definition.graphdef.ShapeDescriptor;
import org.melanee.graphdsl.models.definition.graphdef.StaticLabel;
import org.melanee.graphdsl.models.definition.graphdef.TableLayout;
import org.melanee.graphdsl.models.definition.graphdef.TableLayoutInformation;
import org.melanee.graphdsl.models.definition.graphdef.VisualizationDescriptor;

/**
 * <p>Translates a visualizer model excerpt into a figure that
 * can be used with gef and gmf.</p> 
 * 
 * 
 * <p>Figures containing a border Item need to be completely copied as they contain
 * a DefaultNode Figure. The locator needs to be created newly, because this locator
 * has the wrong figure as main figure.</p>
 *
 */
public class GraphicalrepresentationToFigureTransformator {

    private Map<VisualizationDescriptor, IFigure> descriptor2figure = new HashMap<VisualizationDescriptor, IFigure>();
    GraphicalDSLVisualizer visualizer = null;
    private Clabject clabject = null;
    private IFigure compartmentFigure = null;
    private IConstraintLanguageService constraintLanguageService = null;

    private IConstraintLanguageService getConstraintLanguageService() {
        IConstraintLanguageService result = null;

        try {
            result = ExtensionPointService.Instance().getActiveConstraintLanguageService();
        } catch (CoreException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * This is for participations
     * 
     * @param v visualizer to create figure from
     * @param p the participation to visualize
     * @param figure the figure of the participation to visualize (this figure is actually modified only)
     * @return the modified figure of the participation
     */
    public Object run(AbstractDSLVisualizer v, Participation p, IFigure figure) {
        visualizer = (GraphicalDSLVisualizer) v;
        constraintLanguageService = getConstraintLanguageService();

        ConnectionParticipationFigure connectionFigure = (ConnectionParticipationFigure) figure;

        //Do the DSL rendering -> Set decoration independent of isNavigable
        //Set labels independent of DSL rendering
        connectionFigure.getFigureConnectionParticipationNameFigure().setText("");
        connectionFigure.getFigureConnectionParticipationMultiplicityFigure().setText("");

        //We did not find any LMLVisualizer or the LMLVisualizer is not
        //containing link rendering information thus exit
        if (visualizer == null || !(visualizer.getContent().get(0) instanceof Link))
            return null;

        Link l = (Link) visualizer.getContent().get(0);

        connectionFigure.setForegroundColor(colorConstant2Color(l.getForegroundColor()));
        connectionFigure.setBackgroundColor(colorConstant2Color(l.getBackgroundColor()));

        // **********************************************
        // Set line style
        // **********************************************
        if (l.getLineStyle() == LineStyle.DASHED)
            connectionFigure.setLineStyle(SWT.LINE_DASH);
        else if (l.getLineStyle() == LineStyle.DOTTED)
            connectionFigure.setLineStyle(SWT.LINE_DOT);
        else if (l.getLineStyle() == LineStyle.SOLID)
            connectionFigure.setLineStyle(SWT.LINE_SOLID);

        // **********************************************
        // Add DSL Link decoration
        // **********************************************
        LinkDecoration decoDesc = l.getLinkDecorationForParticipation(p);

        // Neither decoration for participation name found nor for the index
        if (decoDesc == null)
            connectionFigure.setTargetDecoration(null);
        else {
            // We have a special decoration
            if (((DefaultLinkDecoration) decoDesc)
                    .getDecorationType() != DefaultLinkDecorationTypes.NO_LINE_DECORATION) {
                RotatableDecoration decoration = ((DefaultLinkDecoration) decoDesc)
                        .getDecorationType() == DefaultLinkDecorationTypes.POLY_LINE_DECORATION
                                ? new PolylineDecoration()
                                : new PolygonDecoration();
                decoration.setBackgroundColor(colorConstant2Color(decoDesc.getBackgroundColor()));
                decoration.setForegroundColor(colorConstant2Color(decoDesc.getForegroundColor()));
                // set the decoration
                connectionFigure.setTargetDecoration(decoration);
            }
            // We have no special decoration
            else
                connectionFigure.setTargetDecoration(null);
        }

        // *********************************************
        // Add DSl label
        // *********************************************
        LabelDescriptor labelDesc = l.getLabelDescriptorForParticipation(p);
        if (!(labelDesc == null)) {

            if (labelDesc instanceof ExpressionLabel || labelDesc instanceof MappingLabel) {
                // Execute the OCL expression to get the value
                Set feature = null;

                org.eclipse.ocl.ecore.OCL ocl = org.eclipse.ocl.ecore.OCL.newInstance();
                OCLHelper<EClassifier, ?, ?, Constraint> helper = ocl.createOCLHelper();
                helper.setContext(org.melanee.core.models.plm.PLM.PLMPackage.Literals.CONNECTION);

                try {

                    String attributeName = "";
                    if (labelDesc instanceof ExpressionLabel)
                        attributeName = ((ExpressionLabel) labelDesc).getExpression();
                    else if (labelDesc instanceof MappingLabel)
                        attributeName = ((MappingLabel) labelDesc).getAttribute().getName();

                    OCLExpression<EClassifier> q = helper
                            .createQuery("self.feature->select(f | f.oclIsKindOf(Attribute) and f.name = '"
                                    + attributeName + "')");
                    feature = (Set) ocl.evaluate(p.getConnection(), q);
                } catch (ParserException e) {
                    e.printStackTrace();
                }

                if (!feature.isEmpty()) {
                    WrappingLabel label = new WrappingLabel(
                            ((org.melanee.core.models.plm.PLM.Attribute) feature.iterator().next()).getValue());
                    label.setParent(connectionFigure);
                    connectionFigure.add(label, new LabelLocator(connectionFigure,
                            new org.eclipse.draw2d.geometry.Point(-10, -10), ConnectionLocator.SOURCE));
                }
            } else if (labelDesc instanceof StaticLabel) {
                WrappingLabel label = new WrappingLabel(((StaticLabel) labelDesc).getText());
                label.setParent(connectionFigure);
                connectionFigure.add(label, new LabelLocator(connectionFigure,
                        new org.eclipse.draw2d.geometry.Point(-10, -10), ConnectionLocator.SOURCE));
            }

        }

        return figure;
    }

    /**
     * This is for clabjects (i.e. Connection, Entity)
     * 
     * @param v visualizer to create figure from
     * @param c clabject to visualize (this is used to retrieve values of labels etc.)
     * @param compartmentFigure
     * @return returns an IFigure wich is an interpretation of the visualizer
     */
    public Object run(AbstractDSLVisualizer v, Clabject c, IFigure compartmentFigure) {

        visualizer = (GraphicalDSLVisualizer) v;
        clabject = c;
        this.compartmentFigure = compartmentFigure;
        constraintLanguageService = getConstraintLanguageService();

        //The conditional values are evaluated before building the
        //figure.
        evaluateConditionalValues();

        DefaultSizeNodeFigure defaultSizeNodeFigure = new DefaultSizeNodeFigure(40, 40);
        //If we have border items we need a BorderNodeFigure as outermost container
        BorderedNodeFigure borderNode = null;

        //A BorderedNodeFigure is created in cases where text is displayed
        //around a shape. Thus a visualizer contains at least two descriptors,
        //the shape and the border labels
        if (visualizer.getContent().size() > 1) {

            //We need to check if one built labels around the
            //shape or did a mistake (-> no BorderedNodeFigure)
            //such a "mistake" can happen with visualizers
            //providing multiple apsects
            boolean containsBorderLabels = false;

            for (EObject eObj : visualizer.getContent())
                if (eObj instanceof InformationDisplayDescriptor
                //&& !((InformationDisplayDescriptor)eObj).isAspect()
                )
                    containsBorderLabels = true;

            if (containsBorderLabels)
                borderNode = new BorderedNodeFigure(defaultSizeNodeFigure);
        }
        TreeIterator<EObject> iterator = v.eAllContents();

        while (iterator.hasNext()) {
            EObject eObj = iterator.next();

            if (!(eObj instanceof LayoutContentDescriptor))
                continue;

            IFigure newFigure = createFigure((LayoutContentDescriptor) eObj);

            //This can happen after calling for compartment
            //with an empty content compartment. In this case
            //null is returned as empty compartments are not shown
            if (newFigure == null)
                continue;

            //If a conditioncl LayoutContent is not executed (condition = false) null is returned
            //and the tree is not followed any further
            if (newFigure == null && eObj instanceof ConditionalLayoutContent) {
                iterator.prune();
                continue;
            }

            descriptor2figure.put((VisualizationDescriptor) eObj, newFigure);

            IFigure parentFigure;
            if ((parentFigure = descriptor2figure
                    .get(getParentVisualizationDescriptor((LayoutContentDescriptor) eObj))) != null) {
                if (((RenderedLayoutContentDescriptor) eObj).getLayoutInformation() != null) {
                    parentFigure.add(newFigure, createLayoutInformation(
                            ((RenderedLayoutContentDescriptor) eObj).getLayoutInformation()));
                    newFigure.setParent(parentFigure);
                } else {
                    parentFigure.add(newFigure);
                    newFigure.setParent(parentFigure);
                }
            } else if (visualizer.getContent().indexOf(eObj) == 0)
                defaultSizeNodeFigure.add(newFigure);
            else if (visualizer.getContent().indexOf(eObj) > 0
                    //This can happen through visualizer which have
                    //lables that are aspects
                    && borderNode != null
                    //The check is needed because with aspects it is allowed to place
                    //multiple non labels at the root of a visualizer
                    && eObj instanceof InformationDisplayDescriptor)
                if (((RenderedLayoutContentDescriptor) eObj).getLayoutInformation() != null)
                    borderNode.getBorderItemContainer().add(newFigure, createLayoutInformation(
                            ((RenderedLayoutContentDescriptor) eObj).getLayoutInformation()));
                else
                    borderNode.getBorderItemContainer().add(newFigure);
        }

        return borderNode != null ? borderNode : defaultSizeNodeFigure;
    }

    private void evaluateConditionalValues() {

        if (constraintLanguageService == null)
            return;

        TreeIterator<EObject> iterator = visualizer.eAllContents();

        Clabject definitionContext = null;

        //This can happen for visualizers which have been merged with provided
        //aspects as these do not have a parent as they are a copy only.
        if (visualizer.eContainer() == null)
            definitionContext = GraphicalVisualizationService.findOwnerOfVisualizer(visualizer);
        else
            definitionContext = (Clabject) visualizer.eContainer().eContainer();

        //If no definition context was found something is going seriously wrong
        if (definitionContext == null)
            throw new RuntimeException("No definition contex found!");

        Clabject context = clabject;

        while (iterator.hasNext()) {
            EObject current = iterator.next();

            if (current instanceof ConditionalValue) {
                try {
                    ConditionalValue conditionalValue = (ConditionalValue) current;
                    Object objectResult = constraintLanguageService.evaluate(definitionContext, context,
                            conditionalValue.getCondition());

                    if (conditionalValue.getAttribute().getEType() instanceof EEnum
                            && objectResult instanceof String) {
                        EEnum type = (EEnum) conditionalValue.getAttribute().getEType();

                        for (EEnumLiteral literal : type.getELiterals())
                            if (literal.getLiteral().equalsIgnoreCase((String) objectResult)) {
                                objectResult = literal.getInstance();
                                break;
                            }
                    }
                    if (conditionalValue.eContainer().eGet(conditionalValue.getAttribute()) != objectResult)
                        conditionalValue.eContainer().eSet(conditionalValue.getAttribute(), objectResult);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private ShapeDescriptor getParentVisualizationDescriptor(LayoutContentDescriptor desc) {

        if (desc.eContainer() instanceof GraphicalDSLVisualizer)
            return null;
        else if (desc.eContainer() instanceof ShapeDescriptor)
            return (ShapeDescriptor) desc.eContainer();
        else if (desc.eContainer() instanceof ConditionalLayoutContent)
            return (ShapeDescriptor) desc.eContainer().eContainer().eContainer();
        else
            return (ShapeDescriptor) desc.eContainer().eContainer();

        //Old statement before condition
        //return desc.eContainer() instanceof GraphicalDSLVisualizer ? null : desc.eContainer() instanceof ShapeDescriptor ? (ShapeDescriptor)desc.eContainer() : (ShapeDescriptor)desc.eContainer().eContainer();
    }

    /**
     * Creates figures and labels
     * 
     * @param desc
     * @return
     */
    private IFigure createFigure(LayoutContentDescriptor desc) {

        //Containment Representing Figure
        //The compartment figures need to be before rectangle as they inherit from it
        if (desc instanceof org.melanee.graphdsl.models.definition.graphdef.Compartment)
            return createCompartment((org.melanee.graphdsl.models.definition.graphdef.Compartment) desc);
        if (desc instanceof Pin)
            return createCompartment((org.melanee.graphdsl.models.definition.graphdef.Compartment) desc);
        //Figures
        else if (desc instanceof org.melanee.graphdsl.models.definition.graphdef.RoundedRectangle)
            return createRoundedRectangle((org.melanee.graphdsl.models.definition.graphdef.RoundedRectangle) desc);
        else if (desc instanceof Rectangle)
            return createRectangle((Rectangle) desc);
        else if (desc instanceof Circle)
            return createCircle((Circle) desc);
        else if (desc instanceof FreehandShape)
            return createFreehandShape((FreehandShape) desc);
        else if (desc instanceof SVGFigure)
            return createSVGFigure((SVGFigure) desc);

        //Conditions
        else if (desc instanceof ConditionalLayoutContent)
            return createConditionalLayoutContent((ConditionalLayoutContent) desc);

        //Labels
        else if (desc instanceof ExpressionLabel)
            return createExpressionLabel((ExpressionLabel) desc);
        else if (desc instanceof MappingLabel)
            return createMappingLabel((MappingLabel) desc);
        else if (desc instanceof StaticLabel)
            return createStaticLabel((StaticLabel) desc);

        return null;
    }

    private IFigure createConditionalLayoutContent(ConditionalLayoutContent desc) {

        Clabject definitionContext = (Clabject) visualizer.eContainer().eContainer();
        Clabject context = clabject;
        boolean execute = false;
        Object resultObject = null;

        //In case of no active constraint language servuce, the
        //Conditional content is not rendered
        if (constraintLanguageService == null)
            return null;

        try {
            if (desc.getCondition() != null && desc.getCondition().length() > 0) {
                resultObject = constraintLanguageService.evaluate(definitionContext, context, desc.getCondition());
                if (resultObject instanceof Boolean)
                    execute = ((Boolean) resultObject).booleanValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (execute && desc.getContent() != null)
            return createFigure(desc.getContent());
        else
            return null;
    }

    private IFigure createCompartment(Compartment desc) {
        return compartmentFigure;
    }

    private IFigure createPin(Pin desc) {
        throw new RuntimeException("Not implemented");
    }

    private IFigure createSVGFigure(SVGFigure desc) {
        org.eclipse.gmf.runtime.lite.svg.SVGFigure figure = new org.eclipse.gmf.runtime.lite.svg.SVGFigure();

        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(desc.getDocumentURI()));

        if (file != null && file.getLocation() != null) {
            figure.setURI("file:///" + file.getLocation().toOSString());

            //If preferred size is not set the shape is resizing to its
            //parent size
            if (desc.getHeight() != 0 && desc.getWidth() != 0)
                figure.setPreferredSize(desc.getWidth(), desc.getHeight());

            if (desc.getLayout() != null)
                figure.setLayoutManager(createLayout(desc.getLayout()));
        } else {
            System.err.println("SVG file not found.");
        }

        return figure;
    }

    private IFigure createFreehandShape(FreehandShape desc) {
        ScalablePolygonShape fig = new ScalablePolygonShape();

        for (Point p : desc.getPoints())
            fig.addPoint(new org.eclipse.draw2d.geometry.Point(p.getX(), p.getY()));

        fig.setOutline(desc.isOutline());
        fig.setFill(desc.isFill());
        fig.setBackgroundColor(colorConstant2Color(desc.getBackgroundColor()));
        fig.setForegroundColor(colorConstant2Color(desc.getForegroundColor()));
        fig.setLineWidth(desc.getOutlineWidth());
        //If preferred size is not set the shape is resizing to its
        //parent size
        if (desc.getHeight() != 0 && desc.getWidth() != 0)
            fig.setPreferredSize(desc.getWidth(), desc.getHeight());

        if (desc.getLayout() != null)
            fig.setLayoutManager(createLayout(desc.getLayout()));

        return fig;
    }

    private IFigure createRectangle(Rectangle rect) {
        RectangleFigure fig = new RectangleFigure();

        //If preferred size is not set the shape is resizing to its
        //parent size
        if (rect.getHeight() != 0 && rect.getWidth() != 0)
            fig.setPreferredSize(rect.getWidth(), rect.getHeight());
        fig.setOutline(rect.isOutline());
        fig.setFill(rect.isFill());
        fig.setBackgroundColor(colorConstant2Color(rect.getBackgroundColor()));
        fig.setForegroundColor(colorConstant2Color(rect.getForegroundColor()));
        fig.setLineWidth(rect.getOutlineWidth());

        if (rect.getLayout() != null)
            fig.setLayoutManager(createLayout(rect.getLayout()));

        return fig;
    }

    private IFigure createRoundedRectangle(org.melanee.graphdsl.models.definition.graphdef.RoundedRectangle rect) {
        RoundedRectangle fig = new RoundedRectangle();
        //If preferred size is not set the shape is resizing to its
        //parent size
        if (rect.getHeight() != 0 && rect.getWidth() != 0)
            fig.setPreferredSize(rect.getWidth(), rect.getHeight());
        fig.setOutline(rect.isOutline());
        fig.setFill(rect.isFill());
        fig.setBackgroundColor(colorConstant2Color(rect.getBackgroundColor()));
        fig.setForegroundColor(colorConstant2Color(rect.getForegroundColor()));
        fig.setCornerDimensions(new Dimension(rect.getRadius(), rect.getRadius()));
        fig.setLineWidth(rect.getOutlineWidth());

        if (rect.getLayout() != null)
            fig.setLayoutManager(createLayout(rect.getLayout()));

        return fig;
    }

    private IFigure createCircle(Circle circle) {
        Ellipse fig = new Ellipse();

        //If preferred size is not set the shape is resizing to its
        //parent size
        if (circle.getRadius() != 0)
            fig.setPreferredSize(circle.getRadius(), circle.getRadius());
        fig.setOutline(circle.isOutline());
        fig.setFill(circle.isFill());
        fig.setBackgroundColor(colorConstant2Color(circle.getBackgroundColor()));
        fig.setForegroundColor(colorConstant2Color(circle.getForegroundColor()));
        fig.setLineWidth(circle.getOutlineWidth());

        if (circle.getLayout() != null)
            fig.setLayoutManager(createLayout(circle.getLayout()));

        return fig;
    }

    private IFigure createStaticLabel(StaticLabel desc) {
        return createLabelWithText(desc, desc.getText());
    }

    /**
     * To get this working we need an OCL Factory that supports the OCA
     * @param desc
     * @return
     */
    private IFigure createExpressionLabel(ExpressionLabel desc) {
        Clabject definitionContext = (Clabject) visualizer.eContainer().eContainer();
        Clabject context = clabject;
        String labelText = null;
        Object resultObject = null;

        //In case of no active constraint language servuce, the
        //Conditional content is not rendered
        if (constraintLanguageService == null && desc.getExpression().length() > 0)
            return createLabelForAttributeName(desc.getExpression(), desc);
        else if (constraintLanguageService == null)
            return createLabelWithText(desc, "");

        try {
            if (desc.getExpression() != null && desc.getExpression().length() > 0) {
                resultObject = constraintLanguageService.evaluate(definitionContext, context, desc.getExpression());
                if (resultObject != null)
                    labelText = String.valueOf(resultObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (labelText != null)
            return createLabelWithText(desc, labelText);
        else
            return createLabelWithText(desc, "");
    }

    /**
     * Creates a mapping label
     * 
     * @param desc
     * @return
     */
    private IFigure createMappingLabel(MappingLabel desc) {
        //If attribute is null create a "" label. Can happen in live DSL modeling
        return createLabelForAttributeName(desc.getAttribute() == null ? "" : desc.getAttribute().getName(), desc);
    }

    /**
     * This method is responsible for creating the graphical label
     * 
     * @param desc
     * @return
     */
    private IFigure createLabelForAttributeName(String attributeName, LabelDescriptor desc) {
        //***********************
        // Set the text
        //***********************
        //Execute the OCL expression to get the value
        org.melanee.core.models.plm.PLM.Feature[] feature = new org.melanee.core.models.plm.PLM.Feature[] {};

        org.eclipse.ocl.ecore.OCL ocl = org.eclipse.ocl.ecore.OCL.newInstance();
        OCLHelper<EClassifier, ?, ?, Constraint> helper = ocl.createOCLHelper();
        helper.setContext(org.melanee.core.models.plm.PLM.PLMPackage.Literals.ENTITY);

        try {
            OCLExpression<EClassifier> q = helper
                    .createQuery("self.feature->select(f | f.oclIsKindOf(Attribute))->select(f | f.name = '"
                            + attributeName + "')");
            feature = ((HashSet<org.melanee.core.models.plm.PLM.Feature>) ocl.evaluate(clabject, q))
                    .toArray(new org.melanee.core.models.plm.PLM.Feature[] {});
        } catch (ParserException e) {
            e.printStackTrace();
        }

        if (feature.length == 0)
            return createLabelWithText(desc, "");
        else
            return createLabelWithText(desc, ((Attribute) feature[0]).getValue());
    }

    private IFigure createLabelWithText(LabelDescriptor desc, String text) {

        //**************************
        // Configure parameters
        //*************************
        Color foregroundColor = colorConstant2Color(desc.getForegroundColor());
        Color backgroundColor = colorConstant2Color(desc.getBackgroundColor());

        org.eclipse.jface.resource.FontDescriptor fd = null;

        if (desc.getFont() != null) {
            FontDescriptor fontDesc = desc.getFont();
            if (fontDesc.getFontName() != null && fontDesc.getFontStyle() != null)
                fd = org.eclipse.jface.resource.FontDescriptor.createFrom(fontDesc.getFontName(),
                        fontDesc.getSize(), fontDesc.getFontStyle() == FontStyle.NORMAL ? SWT.NORMAL
                                : fontDesc.getFontStyle() == FontStyle.ITALICS ? SWT.ITALIC : SWT.BOLD);
        }

        //**************************
        // Create vertical label
        //*************************
        if (desc.getOrientation() == LabelOrientation.VERTICAL) {
            //TODO: Implement code for disposing image
            Display d = PlatformUI.getWorkbench().getDisplay();
            if (text == null || text.length() == 0)
                text = " ";
            return new ImageFigure(ImageUtilities.createRotatedImageOfString(text,
                    (fd != null ? JFaceResources.getResources(PlatformUI.getWorkbench().getDisplay()).createFont(fd)
                            : d.getSystemFont()),
                    foregroundColor, backgroundColor));
        }

        //**************************
        // Create horizontal label
        //*************************
        WrappingLabel label = new WrappingLabel();

        label.setBackgroundColor(backgroundColor);
        label.setForegroundColor(foregroundColor);

        if (fd != null)
            label.setFont(JFaceResources.getResources(PlatformUI.getWorkbench().getDisplay()).createFont(fd));

        label.setText(text);

        return label;
    }

    private AbstractLayout createLayout(LayoutDescriptor desc) {
        if (desc instanceof FlowLayout)
            return createFlowLayout((FlowLayout) desc);
        else if (desc instanceof TableLayout)
            return createTableLayout((TableLayout) desc);

        return null;
    }

    private GridLayout createTableLayout(TableLayout desc) {
        GridLayout layout = new GridLayout(desc.getColumns(), desc.isEqualWitdth());

        if (desc.getMargin() != null) {
            layout.marginHeight = desc.getMargin().getY();
            layout.marginWidth = desc.getMargin().getX();
        }

        if (desc.getPadding() != null) {
            layout.verticalSpacing = desc.getPadding().getY();
            layout.horizontalSpacing = desc.getPadding().getX();
        }

        return layout;
    }

    private org.eclipse.draw2d.FlowLayout createFlowLayout(FlowLayout desc) {
        org.eclipse.draw2d.FlowLayout layout = new org.eclipse.draw2d.FlowLayout();

        return layout;
    }

    private Object createLayoutInformation(LayoutInformationDescriptor layoutInformation) {

        if (layoutInformation instanceof TableLayoutInformation)
            return createTableLayoutInformation((TableLayoutInformation) layoutInformation);
        if (layoutInformation instanceof BorderLayoutInformationDescriptor)
            return createBorderLayoutInformation((BorderLayoutInformationDescriptor) layoutInformation);

        return null;
    }

    private Object createBorderLayoutInformation(BorderLayoutInformationDescriptor layoutInformation) {

        org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator locator = null;

        //We need to find out at which side the item shall be place
        if (layoutInformation.getVerticalAlignment() == Alignment.BEGIN
                && layoutInformation.getHorizontalAlignment() == Alignment.BEGIN)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.NORTH_WEST);
        else if (layoutInformation.getVerticalAlignment() == Alignment.BEGIN
                && layoutInformation.getHorizontalAlignment() == Alignment.CENTER)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.NORTH);
        else if (layoutInformation.getVerticalAlignment() == Alignment.BEGIN
                && layoutInformation.getHorizontalAlignment() == Alignment.END)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.NORTH_EAST);
        else if (layoutInformation.getVerticalAlignment() == Alignment.CENTER
                && layoutInformation.getHorizontalAlignment() == Alignment.BEGIN)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.WEST);
        else if (layoutInformation.getVerticalAlignment() == Alignment.CENTER
                && layoutInformation.getHorizontalAlignment() == Alignment.END)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.EAST);
        else if (layoutInformation.getVerticalAlignment() == Alignment.END
                && layoutInformation.getHorizontalAlignment() == Alignment.BEGIN)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.SOUTH_WEST);
        else if (layoutInformation.getVerticalAlignment() == Alignment.END
                && layoutInformation.getHorizontalAlignment() == Alignment.CENTER)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.SOUTH);
        else if (layoutInformation.getVerticalAlignment() == Alignment.END
                && layoutInformation.getHorizontalAlignment() == Alignment.END)
            locator = new org.melanee.core.modeleditor.custom.borders.CenteredBorderItemLocator(
                    descriptor2figure.get(layoutInformation.eContainer()), PositionConstants.SOUTH_EAST);

        if (locator != null)
            locator.setInitialOffset(layoutInformation.getHorizontalOffset(),
                    layoutInformation.getVerticalOffset());

        return locator;
    }

    private Object createTableLayoutInformation(TableLayoutInformation layoutInformation) {

        GridData data = new GridData();

        data.horizontalSpan = layoutInformation.getColumnSpan();
        data.verticalSpan = layoutInformation.getRowSpan();

        data.grabExcessHorizontalSpace = layoutInformation.isGrabHorizontalExcess();
        data.grabExcessVerticalSpace = layoutInformation.isGrabVerticalExcess();

        if (layoutInformation.getVerticalAlignment() == Alignment.BEGIN)
            data.verticalAlignment = SWT.TOP;
        else if (layoutInformation.getVerticalAlignment() == Alignment.CENTER)
            data.verticalAlignment = SWT.CENTER;
        else if (layoutInformation.getVerticalAlignment() == Alignment.END)
            data.verticalAlignment = SWT.BOTTOM;
        else if (layoutInformation.getVerticalAlignment() == Alignment.FILL)
            data.verticalAlignment = SWT.FILL;

        if (layoutInformation.getHorizontalAlignment() == Alignment.BEGIN)
            data.horizontalAlignment = SWT.LEFT;
        else if (layoutInformation.getHorizontalAlignment() == Alignment.CENTER)
            data.horizontalAlignment = SWT.CENTER;
        else if (layoutInformation.getHorizontalAlignment() == Alignment.END)
            data.horizontalAlignment = SWT.RIGHT;
        else if (layoutInformation.getHorizontalAlignment() == Alignment.FILL)
            data.horizontalAlignment = SWT.FILL;

        return data;
    }

    private Color colorConstant2Color(ColorConstant constant) {
        switch (constant.getValue()) {
        case ColorConstant.BLACK_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_BLACK);
        case ColorConstant.WHITE_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_WHITE);
        case ColorConstant.BLUE_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_BLUE);
        case ColorConstant.RED_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_RED);
        case ColorConstant.GREEN_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_GREEN);
        case ColorConstant.YELLOW_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_YELLOW);
        case ColorConstant.ORANGE_VALUE:
            return PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_MAGENTA);
        default:
            return null;
        }
    }
}