Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Modeling » Papyrus » How to visualize elements programatically
How to visualize elements programatically [message #703969] Thu, 28 July 2011 06:03 Go to next message
Timothy Marc is currently offline Timothy MarcFriend
Messages: 547
Registered: July 2009
Senior Member
Hi all,

this is slighty relate to the post from Neslepeaks "How to create a diagram
element programmatically", but in fact completely different. I'm seeking for
the easiest and most convenient way to visualize already existing elements
in a UML model on a diagram programatically - in a way as if someone would
have dragged the element from the model explorer and dropped it onto the
canvas.

I guess it is somehow related with changing the notation file, but actually,
I'm not sure and I have not found any information on this neither in the
Papyrus SVN nor in the web. Could someone give a hint where to search or how
to achieve this, please?

Timothy
Re: How to visualize elements programatically [message #713468 is a reply to message #703969] Mon, 08 August 2011 14:01 Go to previous messageGo to next message
Vincent   is currently offline Vincent Friend
Messages: 35
Registered: December 2009
Member
Here is a part of a class which should help you.
You may perform some refactoring, but all you need should be there.
Take care to respect the copyright.

/*****************************************************************************
 * Copyright (c) 2010 Atos Origin.
 *
 *    
 * 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:
 *  Vincent Hemery (Atos Origin}) {vincent.hemery@atosorigin.com} - Initial API and implementation
 *
 *****************************************************************************/
package org.topcased.requirement.bundle.papyrus.services;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.transaction.RollbackException;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.osgi.util.NLS;
import org.eclipse.papyrus.core.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.core.modelsetquery.ModelSetQuery;
import org.eclipse.papyrus.core.utils.EditorUtils;
import org.eclipse.papyrus.diagram.common.util.DiagramEditPartsUtil;
import org.eclipse.papyrus.resource.IModel;
import org.eclipse.papyrus.resource.ModelSet;
import org.eclipse.papyrus.resource.uml.UmlModel;
import org.eclipse.papyrus.sasheditor.contentprovider.IPageMngr;
import org.eclipse.papyrus.sasheditor.editor.AbstractMultiPageSashEditor;
import org.eclipse.papyrus.sasheditor.editor.ISashWindowsContainer;
import org.eclipse.ui.IEditorPart;
import org.topcased.requirement.bundle.papyrus.Activator;
import org.topcased.requirement.bundle.papyrus.internal.Messages;
import org.topcased.requirement.bundle.papyrus.resource.RequirementModel;
import org.topcased.requirement.core.extensions.IEditorServices;
import org.topcased.requirement.core.views.AbstractRequirementPage;

/**
 * This class provides services for using requirements with the papyrus core editor. It is intended to be used only by
 * extension point org.topcased.requirement.core.supportingEditors.
 * 
 * @author vhemery
 */
public class PapyrusEditorServices implements IEditorServices
{
[...]


    /**
     * Get the currently active Papyrus diagram editor.
     * 
     * @return the editor part or null.
     */
    public IEditorPart getActiveEditor()
    {
        return EditorUtils.getMultiDiagramEditor();
    }
[...]

    /**
     * Sets the selection state for the editor to reveal the position of the given EObject.<br>
     * It searches in the different diagrams the occurrences of the EObject and ask the user to select the destination
     * if the given EObject has several graphical representation.
     * 
     * @param editor the editor or null for currently active one
     * @param listOfEObjects list of eobjects to select
     * @param openDiagramIfNeeded if true, when the object is not in current active diagram, a representing diagram will
     *        open
     */
    public void gotoEObjects(IEditorPart editor, List<EObject> listOfEObjects, boolean openDiagramIfNeeded)
    {
        if (editor == null)
        {
            editor = getActiveEditor();
        }
        if (editor instanceof IMultiDiagramEditor)
        {
            List<EditPart> editPartsToSelect = new ArrayList<EditPart>(listOfEObjects.size());
            // find appropriate viewer and edit parts to select
            EditPartViewer currentViewer = getGraphicalViewer(editor);
            Map< ? , ? > currentRegistry = currentViewer.getEditPartRegistry();
            if (openDiagramIfNeeded)
            {
                /*
                 * Reference diagrams which represent these elements to know the best one (with most represented
                 * elements)
                 */
                Map<Diagram, Integer> numberOfRepresentedElementsByDiagram = new HashMap<Diagram, Integer>();
                for (EObject toSelect : listOfEObjects)
                {
                    Set<Diagram> diagramsRepresentingThisObject = new HashSet<Diagram>();
                    List< ? > views = DiagramEditPartsUtil.getEObjectViews(toSelect);
                    for (Object view : views)
                    {
                        if (view instanceof View && !(view instanceof Diagram))
                        {
                            Diagram diagram = ((View) view).getDiagram();
                            // test if a representation has already been counted for this diagram
                            if (!diagramsRepresentingThisObject.contains(diagram))
                            {
                                // the element is represented in this diagram
                                diagramsRepresentingThisObject.add(diagram);
                                if (!numberOfRepresentedElementsByDiagram.containsKey(diagram))
                                {
                                    numberOfRepresentedElementsByDiagram.put(diagram, 0);
                                }
                                Integer num = numberOfRepresentedElementsByDiagram.get(diagram);
                                numberOfRepresentedElementsByDiagram.put(diagram, num + 1);
                            }
                        }
                    }
                }
                // find diagram where the largest number of elements are available
                Diagram bestDiagram = null;
                int numberOfRepresented = 0;
                for (Entry<Diagram, Integer> entry : numberOfRepresentedElementsByDiagram.entrySet())
                {
                    if (entry.getValue() > numberOfRepresented)
                    {
                        // take better diagram
                        bestDiagram = entry.getKey();
                        numberOfRepresented = entry.getValue();
                    }
                    else if (entry.getValue() == numberOfRepresented)
                    {
                        // take the currently opened diagram if it is as good
                        if (currentRegistry.get(entry.getKey()) != null)
                        {
                            bestDiagram = entry.getKey();
                        }
                    }
                }
                // change active diagram if necessary
                if (bestDiagram != null && currentRegistry.get(bestDiagram) == null)
                {
                    Object pageMngr = editor.getAdapter(IPageMngr.class);
                    if (pageMngr instanceof IPageMngr)
                    {
                        IPageMngr pageManager = (IPageMngr) pageMngr;
                        if (pageManager.isOpen(bestDiagram))
                        {
                            // bring to top
                            pageManager.closePage(bestDiagram);
                            pageManager.openPage(bestDiagram);
                        }
                        else
                        {
                            // open
                            pageManager.openPage(bestDiagram);
                        }
                    }
                    currentViewer = getGraphicalViewer(editor);
                    currentRegistry = currentViewer.getEditPartRegistry();
                }
            }
            // select edit parts in the current viewer
            for (EObject toSelect : listOfEObjects)
            {
                List< ? > views = DiagramEditPartsUtil.getEObjectViews(toSelect);
                for (Object view : views)
                {
                    if (currentRegistry.containsKey(view))
                    {
                        Object part = currentRegistry.get(view);
                        if (part instanceof EditPart)
                        {
                            editPartsToSelect.add((EditPart) part);
                        }
                    }
                }
            }
            // select edit parts if selection has to change
            if (!(editPartsToSelect.containsAll(currentViewer.getSelectedEditParts()) && currentViewer.getSelectedEditParts().contains(editPartsToSelect)))
            {
                boolean firstSelectedPartInViewer = true;
                for (EditPart editPart : editPartsToSelect)
                {
                    if (firstSelectedPartInViewer)
                    {
                        currentViewer.select(editPart);
                        firstSelectedPartInViewer = false;
                    }
                    else
                    {
                        currentViewer.appendSelection(editPart);
                    }
                }
            }
        }
    }
[...]

    /**
     * Get the graphical viewer of the editor.
     * 
     * @param editor the editor or null for currently active one
     * @return the graphical viewer.
     */
    public EditPartViewer getGraphicalViewer(IEditorPart editor)
    {
        if (editor == null)
        {
            editor = getActiveEditor();
        }
        if (editor instanceof IMultiDiagramEditor)
        {
            Object viewer = editor.getAdapter(IDiagramGraphicalViewer.class);
            if (viewer instanceof EditPartViewer)
            {
                return (EditPartViewer) viewer;
            }
        }
        return null;
    }
[...]
}
Re: How to visualize elements programatically [message #713544 is a reply to message #713468] Mon, 08 August 2011 15:27 Go to previous messageGo to next message
Timothy Marc is currently offline Timothy MarcFriend
Messages: 547
Registered: July 2009
Senior Member
Hi Vincent,

thanks for your answer. Will be quite hard to obtain a result by just having
this fragment. Please, may I ask you another question on this.

I suppose the method gotoEObject is the core concept for the solution of my
problem, however, it seems to me as if the method goToEObjects would open
the editor where a selected EObject is already present. Is this true? I
glanced over the code and I did not found anything that looked like adding
an EObject to the canvas. Maybe, if your time permits it, you could give me
some more details on how to customize this thing. It would be highly
appreciated, indeed.

Thanks in advance and have your day.

Thanks, Timothy

"Vincent" schrieb im Newsbeitrag news:j1opka$n9u$1@news.eclipse.org...

Here is a part of a class which should help you.
You may perform some refactoring, but all you need should be there.
Take care to respect the copyright.

/*****************************************************************************
* Copyright (c) 2010 Atos Origin.
*
*
* 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:
* Vincent Hemery (Atos Origin}) {vincent.hemery@atosorigin.com} - Initial
API and implementation
*
*****************************************************************************/
package org.topcased.requirement.bundle.papyrus.services;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.transaction.RollbackException;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.osgi.util.NLS;
import org.eclipse.papyrus.core.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.core.modelsetquery.ModelSetQuery;
import org.eclipse.papyrus.core.utils.EditorUtils;
import org.eclipse.papyrus.diagram.common.util.DiagramEditPartsUtil;
import org.eclipse.papyrus.resource.IModel;
import org.eclipse.papyrus.resource.ModelSet;
import org.eclipse.papyrus.resource.uml.UmlModel;
import org.eclipse.papyrus.sasheditor.contentprovider.IPageMngr;
import org.eclipse.papyrus.sasheditor.editor.AbstractMultiPageSashEditor;
import org.eclipse.papyrus.sasheditor.editor.ISashWindowsContainer;
import org.eclipse.ui.IEditorPart;
import org.topcased.requirement.bundle.papyrus.Activator;
import org.topcased.requirement.bundle.papyrus.internal.Messages;
import org.topcased.requirement.bundle.papyrus.resource.RequirementModel;
import org.topcased.requirement.core.extensions.IEditorServices;
import org.topcased.requirement.core.views.AbstractRequirementPage;

/**
* This class provides services for using requirements with the papyrus core
editor. It is intended to be used only by
* extension point org.topcased.requirement.core.supportingEditors.
*
* @author vhemery
*/
public class PapyrusEditorServices implements IEditorServices
{
[...]


/**
* Get the currently active Papyrus diagram editor.
*
* @return the editor part or null.
*/
public IEditorPart getActiveEditor()
{
return EditorUtils.getMultiDiagramEditor();
}
[...]

/**
* Sets the selection state for the editor to reveal the position of the
given EObject.<br>
* It searches in the different diagrams the occurrences of the EObject
and ask the user to select the destination
* if the given EObject has several graphical representation.
*
* @param editor the editor or null for currently active one
* @param listOfEObjects list of eobjects to select
* @param openDiagramIfNeeded if true, when the object is not in current
active diagram, a representing diagram will
* open
*/
public void gotoEObjects(IEditorPart editor, List<EObject>
listOfEObjects, boolean openDiagramIfNeeded)
{
if (editor == null)
{
editor = getActiveEditor();
}
if (editor instanceof IMultiDiagramEditor)
{
List<EditPart> editPartsToSelect = new
ArrayList<EditPart>(listOfEObjects.size());
// find appropriate viewer and edit parts to select
EditPartViewer currentViewer = getGraphicalViewer(editor);
Map< ? , ? > currentRegistry =
currentViewer.getEditPartRegistry();
if (openDiagramIfNeeded)
{
/*
* Reference diagrams which represent these elements to know
the best one (with most represented
* elements)
*/
Map<Diagram, Integer> numberOfRepresentedElementsByDiagram =
new HashMap<Diagram, Integer>();
for (EObject toSelect : listOfEObjects)
{
Set<Diagram> diagramsRepresentingThisObject = new
HashSet<Diagram>();
List< ? > views =
DiagramEditPartsUtil.getEObjectViews(toSelect);
for (Object view : views)
{
if (view instanceof View && !(view instanceof
Diagram))
{
Diagram diagram = ((View) view).getDiagram();
// test if a representation has already been
counted for this diagram
if
(!diagramsRepresentingThisObject.contains(diagram))
{
// the element is represented in this
diagram
diagramsRepresentingThisObject.add(diagram);
if
(!numberOfRepresentedElementsByDiagram.containsKey(diagram))
{
numberOfRepresentedElementsByDiagram.put(diagram,
0);
}
Integer num =
numberOfRepresentedElementsByDiagram.get(diagram);
numberOfRepresentedElementsByDiagram.put(diagram,
num + 1);
}
}
}
}
// find diagram where the largest number of elements are
available
Diagram bestDiagram = null;
int numberOfRepresented = 0;
for (Entry<Diagram, Integer> entry :
numberOfRepresentedElementsByDiagram.entrySet())
{
if (entry.getValue() > numberOfRepresented)
{
// take better diagram
bestDiagram = entry.getKey();
numberOfRepresented = entry.getValue();
}
else if (entry.getValue() == numberOfRepresented)
{
// take the currently opened diagram if it is as
good
if (currentRegistry.get(entry.getKey()) != null)
{
bestDiagram = entry.getKey();
}
}
}
// change active diagram if necessary
if (bestDiagram != null && currentRegistry.get(bestDiagram)
== null)
{
Object pageMngr = editor.getAdapter(IPageMngr.class);
if (pageMngr instanceof IPageMngr)
{
IPageMngr pageManager = (IPageMngr) pageMngr;
if (pageManager.isOpen(bestDiagram))
{
// bring to top
pageManager.closePage(bestDiagram);
pageManager.openPage(bestDiagram);
}
else
{
// open
pageManager.openPage(bestDiagram);
}
}
currentViewer = getGraphicalViewer(editor);
currentRegistry = currentViewer.getEditPartRegistry();
}
}
// select edit parts in the current viewer
for (EObject toSelect : listOfEObjects)
{
List< ? > views =
DiagramEditPartsUtil.getEObjectViews(toSelect);
for (Object view : views)
{
if (currentRegistry.containsKey(view))
{
Object part = currentRegistry.get(view);
if (part instanceof EditPart)
{
editPartsToSelect.add((EditPart) part);
}
}
}
}
// select edit parts if selection has to change
if
(!(editPartsToSelect.containsAll(currentViewer.getSelectedEditParts()) &&
currentViewer.getSelectedEditParts().contains(editPartsToSelect)))
{
boolean firstSelectedPartInViewer = true;
for (EditPart editPart : editPartsToSelect)
{
if (firstSelectedPartInViewer)
{
currentViewer.select(editPart);
firstSelectedPartInViewer = false;
}
else
{
currentViewer.appendSelection(editPart);
}
}
}
}
}
[...]

/**
* Get the graphical viewer of the editor.
*
* @param editor the editor or null for currently active one
* @return the graphical viewer.
*/
public EditPartViewer getGraphicalViewer(IEditorPart editor)
{
if (editor == null)
{
editor = getActiveEditor();
}
if (editor instanceof IMultiDiagramEditor)
{
Object viewer =
editor.getAdapter(IDiagramGraphicalViewer.class);
if (viewer instanceof EditPartViewer)
{
return (EditPartViewer) viewer;
}
}
return null;
}
[...]
}
Re: How to visualize elements programatically [message #714364 is a reply to message #703969] Wed, 10 August 2011 12:27 Go to previous messageGo to next message
Vincent   is currently offline Vincent Friend
Messages: 35
Registered: December 2009
Member
Timothy Marc wrote on Thu, 28 July 2011 02:03
I'm seeking for
the easiest and most convenient way to visualize already existing elements
in a UML model on a diagram programatically - in a way as if someone would
have dragged the element from the model explorer and dropped it onto the
canvas.

Sorry, I though you meant an already drawn element (represented in diagram).

Hence, I suppose you already know the diagram in which you want to represent it (that was the hardest part of my code : finding the diagram in which it is already represented).


You should have a look at org.eclipse.papyrus.diagram.common.editpolicies.CommonDiagramDragDropEditPolicy.getDropObjectsCommand(DropObjectsRequest)
too see how to call such a command creation.

Try putting a breakpoint in it and inspect it in debug to know how the request has been contructed and called.
Re: How to visualize elements programatically [message #837103 is a reply to message #714364] Thu, 05 April 2012 09:21 Go to previous messageGo to next message
Alexandra Bardiau is currently offline Alexandra BardiauFriend
Messages: 21
Registered: March 2012
Junior Member
Hi,

I know this a bit late to ask the question, but Timothy Marc did you solve your problem? Could you post some of your code over here? I'm currently working on something very similar to what you've described, but since it's not the main focus of my project, it would be great if I could solve it as fast as possible.

Thanks a lot, and to Vincent for the code snippets, they were helpful indeed.

Cheers!
Re: How to visualize elements programatically [message #837189 is a reply to message #837103] Thu, 05 April 2012 11:30 Go to previous messageGo to next message
Alexandra Bardiau is currently offline Alexandra BardiauFriend
Messages: 21
Registered: March 2012
Junior Member
Hi,

If anyone else wonders about how to do this, here's the code (working):

                EObject model = null;
	
		try {
					
			// Get root element
			model = UmlUtils.getUmlModel().lookupRoot();
			} catch (org.eclipse.papyrus.resource.NotFoundException e) {
			e.printStackTrace();
		}
		
		// Get the model package
		final org.eclipse.uml2.uml.Package modelpackage = (org.eclipse.uml2.uml.Package) model;

		// Add new elements to the model
		TransactionalEditingDomain ted = TransactionUtil.getEditingDomain(model);
		ted.getCommandStack().execute(new RecordingCommand(ted) {
			
			EList<Element> elementsInModel;
			EList<Element> elementsInComponent;
			Component c;
			Port p;
			Interface newItf;
			Stereotype s;
			
			protected void doExecute() {
				
				String text = "";
					
				elementsInModel = modelpackage.allOwnedElements();
				
				/*
				 * Get all the components in the model.
				 */
				
				for (int i=0; i<elementsInModel.size(); i++) {
					if (elementsInModel.get(i).eClass().getName().compareTo("Component") == 0) {
						c = (Component) elementsInModel.get(i);
						text = text + "Component: " + c.getName() + System.getProperty("line.separator");
						/*
						 * For each component, get all the ports (stereotyped).
						 */
						elementsInComponent = c.getOwnedElements();
						for (int j=0; j<elementsInComponent.size(); j++) {
							if (elementsInComponent.get(j).eClass().getName().compareTo("Port") == 0) {
								p = (Port) elementsInComponent.get(j);
								text = text + "      Port: " + p.getName() + System.getProperty("line.separator");
								/*
								 * For each port, generate a new Interface, stereotyped with the same
								 * stereotype as the port.
								 * Rename the port from [name] to [_name].
								 * Associate the new interface to its corresponding port
								 * by typing the port with the new interface
								 * (port.setType(newInterface)).
								 */
								newItf = c.createOwnedInterface(p.getName());
								p.setName("_" + p.getName());
								s = p.getAppliedStereotypes().get(0);
								newItf.applyStereotype(s);
								p.setType(newItf);
								
								text = text + "      New inteface: " + newItf.getName() + System.getProperty("line.separator");
							}
						}
					}
				}
				JOptionPane.showMessageDialog(null, text);				
			}
		});
		
		/*
		 * Generate the Class diagram containing all the newly created
		 * interfaces.
		 */
		
		DropObjectsRequest dropObjectsRequest = new DropObjectsRequest();
		ArrayList list = new ArrayList();
		EList<Element> elementsInModel = modelpackage.allOwnedElements();
		for (int i=0; i<elementsInModel.size(); i++) {
			if (elementsInModel.get(i).eClass().getName().compareTo("Interface") == 0)
				list.add((org.eclipse.uml2.uml.Element)elementsInModel.get(i));
		}
		dropObjectsRequest.setObjects(list);
		dropObjectsRequest.setLocation(new Point(20,100));
		Command commandDrop = getDiagramEditPart().getCommand(dropObjectsRequest);
		
		((UmlClassDiagramForMultiEditor) EditorUtils.getMultiDiagramEditor().getActiveEditor()).getDiagram();
		
		getDiagramEditPart().getDiagramEditDomain().getDiagramCommandStack().execute(commandDrop);
Re: How to visualize elements programatically [message #870190 is a reply to message #837189] Mon, 07 May 2012 08:21 Go to previous messageGo to next message
Johannes Bürdek is currently offline Johannes BürdekFriend
Messages: 2
Registered: May 2012
Junior Member
Hi,

I have a very similar problem. I try to add and visualize an initial node in the currently opened activity diagram. The add part is working. The initial node is shown in the model explorer. I tried to use the code of Alexandra Bardiau to visualize the added initial node, but I couldn't adapt the code for solving my problem. It would be great, if someone could help me to fix it. Thanks!

                /*
		 *  Add a new initial node to the model
		 */
		// get transactional editing domain
		TransactionalEditingDomain transactionalEditingDomain = null;
		try {
			ServicesRegistry serviceRegistry = ServiceUtilsForActionHandlers
					.getInstance().getServiceRegistry();
			transactionalEditingDomain = ServiceUtils.getInstance()
					.getTransactionalEditingDomain(serviceRegistry);
		} catch (ServiceException e) {
			e.printStackTrace();
		}

		// get activity
		TreeIterator<Notifier> allContents = transactionalEditingDomain
				.getResourceSet().getAllContents();
		Activity activity = null;
		while (allContents.hasNext()) {
			Notifier not = allContents.next();

			if (not instanceof Activity) {
				activity = (Activity) not;
			}
		}

		// create new initial node
		InitialNode element = UMLFactory.eINSTANCE.createInitialNode();
		element.setName("InitialNode123");

		// add initial node to activity
		transactionalEditingDomain.getCommandStack().execute(
				SetCommand.create(transactionalEditingDomain, element,
						UMLPackage.eINSTANCE.getActivityNode_Activity(),
						activity));
		

		/*
		 * Visualize initial node
		 */
		DropObjectsRequest dropObjectsRequest = new DropObjectsRequest();
		ArrayList<Element> list = new ArrayList<Element>();
		EObject model = null;

		try {
			// Get root element
			model = UmlUtils.getUmlModel().lookupRoot();
		} catch (org.eclipse.papyrus.resource.NotFoundException e) {
			e.printStackTrace();
		}
		// Get the model package
		final org.eclipse.uml2.uml.Package modelpackage = (org.eclipse.uml2.uml.Package) model;

		// find all initial nodes and add them to the list
		EList<Element> elementsInModel = modelpackage.allOwnedElements();
		for (int i = 0; i < elementsInModel.size(); i++) {
			if (elementsInModel.get(i).eClass().getName()
					.compareTo("InitialNode") == 0) {
				list.add((org.eclipse.uml2.uml.Element) elementsInModel.get(i));
			}
		}
		dropObjectsRequest.setObjects(list);
		dropObjectsRequest.setLocation(new Point(20, 100));

		// get the currently opened editor
		IEditorPart editorPart = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		ServicesRegistry serviceRegistry = (ServicesRegistry) editorPart
				.getAdapter(ServicesRegistry.class);
		DiagramEditor diagramEditor = null;
		try {
			diagramEditor = (DiagramEditor) ServiceUtils.getInstance()
					.getNestedActiveIEditorPart(serviceRegistry);
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (ClassCastException e) {
			e.printStackTrace();
		}
		DiagramEditPart diagramEditPart = diagramEditor.getDiagramEditPart();
		
		// create and execute command to drop the initial nodes
		Command commandDrop = diagramEditPart.getCommand(dropObjectsRequest);
		diagramEditPart.getDiagramEditDomain().getDiagramCommandStack()
				.execute(commandDrop);
Re: How to visualize elements programatically [message #870930 is a reply to message #870190] Thu, 10 May 2012 09:38 Go to previous messageGo to next message
Raimar Bühmann is currently offline Raimar BühmannFriend
Messages: 2
Registered: May 2012
Junior Member
These examples doesn't work for me.

Has anyone further hints or examples for adding nodes programatically to an active papyrus diagram editor?
Re: How to visualize elements programatically [message #883267 is a reply to message #870190] Fri, 08 June 2012 07:15 Go to previous message
Johannes Bürdek is currently offline Johannes BürdekFriend
Messages: 2
Registered: May 2012
Junior Member
I have got a good tip to visualize elements programatically. If someone else wants to do this you can have a look at dev.eclipse.org/svnroot/modeling/org.eclipse.mdt.papyrus/branches/0.8.X/extraplugins/diagramtemplate . Here you can find the method showElementIn() in the oep.diagramtemplate.launcher.DiagramTemplateLauncher class. It is a part of org.eclipse.papyrus.diagramtemplate.editor. In this method you find all hints you'll need.
Previous Topic:Papyrus 0.8.2-SR2-RC4 MANIFEST.MF file error
Next Topic:Can not assign stereotype with Papyrus
Goto Forum:
  


Current Time: Thu Mar 28 23:31:23 GMT 2024

Powered by FUDForum. Page generated in 0.02779 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top